Utilisateur:Ssimono/common.js

Note : après avoir enregistré la page, vous devrez forcer le rechargement complet du cache de votre navigateur pour voir les changements.

Mozilla / Firefox / Konqueror / Safari : maintenez la touche Majuscule (Shift) en cliquant sur le bouton Actualiser (Reload) ou pressez Maj-Ctrl-R (Cmd-R sur Apple Mac) ;

Firefox (sur GNU/Linux) / Chrome / Internet Explorer / Opera : maintenez la touche Ctrl en cliquant sur le bouton Actualiser ou pressez Ctrl-F5.
// Generated by CoffeeScript 1.7.1

/*
  SUBJECT AGE FROM YEAR
  Description: In an article about a person or a company, when the mouse hovers
  over a year in the article, the age of the article's subject by that year
  appears in a tooltip.

  TODO: Show age of item for establishments on death year.
  TODO: For biographies with no birth year but with a death year
  ([[Cyrus the Great]], [[Leonidas I]]), make dates relative to death year
  instead so that they stil work.
  TODO: For articles with more than one category beginning with a number,
  like [[Babe Ruth]], use the year closest to the present year.
  TODO: When someone is born in 10 BC and dies in 10 AD, they are not 20 years
  old, but 19, because 0 is not a year. Find people born before 1 BC
  through categories.
  TODO: Indicate the establishment and disestablishment dates in the first
  ABBR, if it isn't listed. Such as for buildings.
 */
var SubjectAgeFromYear, SubjectYear, Util;

Util = (function() {
  function Util() {}

  Util.pluralize = function(string, count, plural) {
    if (plural == null) {
      plural = string + 's';
    }
    if (count === 1) {
      return string;
    } else {
      return plural;
    }
  };

  return Util;

})();

SubjectAgeFromYear = (function() {
  function SubjectAgeFromYear() {}

  SubjectAgeFromYear.extractYearFromText = function(_arg) {
    var $abbr, $newNode, abbrText, birthYearIndex, condition, currentAge, currentYear, difference, firstPart, nodeText, patternIndex, secondPart, subjectYear, today, workThisYear, yearIndex, years, yearsLater;
    yearIndex = _arg.yearIndex, patternIndex = _arg.patternIndex, $newNode = _arg.$newNode, nodeText = _arg.nodeText, subjectYear = _arg.subjectYear, today = _arg.today, years = _arg.years;
    abbrText = years[yearIndex];
    currentYear = years[yearIndex];
    birthYearIndex = nodeText.indexOf(currentYear);
    workThisYear = true;
    if (patternIndex === 0 && (nodeText.substr(birthYearIndex + currentYear.length, 3).indexOf('BC') > -1 || nodeText.substr(birthYearIndex - 1, 1).indexOf(',') > -1 || (currentYear.length <= 2 && (this.nearAMonth(nodeText, birthYearIndex, -1, years, yearIndex) && currentYear.indexOf('AD') === -1) || this.nearAMonth(nodeText, birthYearIndex + currentYear.length, 1)) || nodeText.substr(birthYearIndex + currentYear.length, 5).indexOf('year') > -1)) {
      workThisYear = false;
    }
    currentYear = currentYear.indexOf('BC') > -1 || ((subjectYear.birthYear() < 0 || subjectYear.deathYear() < 0) && nodeText.substr(birthYearIndex + currentYear.length + ' BC'.length, 10).indexOf('BC') > -1) ? -1 * parseInt(currentYear) : currentYear.indexOf('AD') > -1 || currentYear.indexOf('CE') > -1 ? parseInt(currentYear.replace(/AD/, '').replace(/CE/, '')) : parseInt(currentYear);
    firstPart = nodeText.substring(0, birthYearIndex);
    difference = currentYear - subjectYear.birthYear();
    condition = workThisYear && (currentYear >= subjectYear.birthYear() || currentYear >= (subjectYear.birthYear() - subjectYear.birthYearBuffer())) && (currentYear <= subjectYear.deathYear() || currentYear <= (subjectYear.deathYear() + subjectYear.birthYearBuffer()));
    if (condition) {
      $abbr = $('<abbr class="subject-age-from-year"></abbr>');
      if (currentYear > subjectYear.deathYear() && currentYear <= (subjectYear.deathYear() + subjectYear.birthYearBuffer())) {
        yearsLater = currentYear - subjectYear.deathYear();
        $abbr.attr('title', yearsLater + ' ' + Util.pluralize('year', yearsLater) + ' after ' + subjectYear.phrase('death'));
      } else if (difference >= 0) {
        $abbr.attr('title', difference + ' ' + Util.pluralize('year', difference) + ' old');
        if (difference === 0) {
          currentAge = subjectYear.type() === 'biography' && subjectYear.isAlive() ? '; now ' + (today.getFullYear() - subjectYear.birthYear()) + ' years old' : '';
          $abbr.attr('title', $abbr.attr('title') + ' (' + subjectYear.phrase('birth') + currentAge + ')');
        } else if (currentYear === subjectYear.deathYear()) {
          $abbr.attr('title', $abbr.attr('title') + ' (' + subjectYear.phrase('death') + ')');
        }
      } else {
        $abbr.attr('title', Math.abs(difference) + ' ' + Util.pluralize('year', Math.abs(difference)) + ' before ' + subjectYear.phrase('birth'));
      }
      $abbr.append(abbrText);
    } else {
      $abbr = '';
    }
    $newNode.append(firstPart).append($abbr.length ? $abbr : abbrText);
    secondPart = (yearIndex + 1) === years.length ? nodeText.substring(birthYearIndex + abbrText.length) : void 0;
    if (secondPart != null) {
      $newNode.append(secondPart);
    }
    nodeText = nodeText.substring(birthYearIndex + abbrText.length);
    return {
      yearIndex: yearIndex,
      patternIndex: patternIndex,
      $newNode: $newNode,
      nodeText: nodeText,
      subjectYear: subjectYear,
      years: years
    };
  };

  SubjectAgeFromYear.findYearsInText = function(_arg) {
    var $newNode, $node, age, minBirthYearBuffer, nodeText, patternIndex, patterns, spansToRemove, subjectYear, today, yearIndex, years, _i, _ref, _ref1;
    patternIndex = _arg.patternIndex, $node = _arg.$node, patterns = _arg.patterns, spansToRemove = _arg.spansToRemove, subjectYear = _arg.subjectYear, today = _arg.today;
    if ($node[0].nodeType !== 3) {
      return true;
    }
    nodeText = $node[0].nodeValue;
    years = nodeText.match(patterns[patternIndex]);
    if (years == null) {
      return true;
    }
    minBirthYearBuffer = 100;
    age = subjectYear.deathYear() - subjectYear.birthYear();
    subjectYear.birthYearBuffer(age >= minBirthYearBuffer && subjectYear.type() === 'biography' ? age : minBirthYearBuffer);
    $newNode = $('<span></span>');
    for (yearIndex = _i = 0, _ref = years.length; 0 <= _ref ? _i < _ref : _i > _ref; yearIndex = 0 <= _ref ? ++_i : --_i) {
      _ref1 = this.extractYearFromText({
        yearIndex: yearIndex,
        patternIndex: patternIndex,
        $newNode: $newNode,
        nodeText: nodeText,
        subjectYear: subjectYear,
        today: today,
        years: years
      }), yearIndex = _ref1.yearIndex, patternIndex = _ref1.patternIndex, $newNode = _ref1.$newNode, nodeText = _ref1.nodeText, subjectYear = _ref1.subjectYear, years = _ref1.years;
    }
    if ($newNode.contents().length > 0) {
      $node.replaceWith($newNode);
      return spansToRemove.push($newNode);
    }
  };

  SubjectAgeFromYear.findMatchesinCategory = function(_arg) {
    var allBirthYears, allDeathYears, birthYear, deathYear, matches, type;
    allBirthYears = _arg.allBirthYears, allDeathYears = _arg.allDeathYears, birthYear = _arg.birthYear, deathYear = _arg.deathYear, matches = _arg.matches, type = _arg.type;
    if (!matches[2]) {
      matches[2] = '';
    }
    if (!matches[7]) {
      matches[7] = '';
    }
    if (!((matches[3] && (matches[3].indexOf('disestablishments') === 0 || matches[3].indexOf('deaths') === 0)) || (matches[4] && matches[4].indexOf('disestablished') === 0))) {
      birthYear = matches[3] ? matches[1] + matches[2] : matches[4] ? matches[6] + matches[7] : matches[11] ? matches[10] : matches[8] + matches[9];
      birthYear = birthYear.indexOf('BC') > -1 ? -1 * parseInt(birthYear) : parseInt(birthYear);
      allBirthYears.push(birthYear);
    } else {
      deathYear = matches[3] && (matches[3].indexOf('disestablishments') === 0 || matches[3].indexOf('deaths') === 0) ? matches[1] + matches[2] : matches[4] ? matches[6] + matches[7] : matches[8] + matches[9];
      deathYear = typeof deathYear === 'string' && deathYear.indexOf('BC') > -1 ? -1 * parseInt(deathYear) : parseInt(deathYear);
      allDeathYears.push(deathYear);
    }
    type = matches[3] && (matches[3].indexOf('births') === 0 || matches[3].indexOf('deaths') === 0) ? 'biography' : 'establishment';
    return {
      allBirthYears: allBirthYears,
      allDeathYears: allDeathYears,
      birthYear: birthYear,
      deathYear: deathYear,
      matches: matches,
      type: type
    };
  };

  SubjectAgeFromYear.findYearFromCategory = function(_arg) {
    var allBirthYears, allDeathYears, allMatches, birthYear, category, categoryMatchPattern, deathYear, matches, type, _ref;
    allBirthYears = _arg.allBirthYears, allDeathYears = _arg.allDeathYears, allMatches = _arg.allMatches, birthYear = _arg.birthYear, category = _arg.category, categoryMatchPattern = _arg.categoryMatchPattern, deathYear = _arg.deathYear, type = _arg.type;
    matches = category.match(categoryMatchPattern);
    if (matches) {
      allMatches.push(category);
      _ref = this.findMatchesinCategory({
        allBirthYears: allBirthYears,
        allDeathYears: allDeathYears,
        birthYear: birthYear,
        deathYear: deathYear,
        matches: matches,
        type: type
      }), allBirthYears = _ref.allBirthYears, allDeathYears = _ref.allDeathYears, birthYear = _ref.birthYear, deathYear = _ref.deathYear, matches = _ref.matches, type = _ref.type;
    }
    return {
      allBirthYears: allBirthYears,
      allDeathYears: allDeathYears,
      allMatches: allMatches,
      birthYear: birthYear,
      category: category,
      categoryMatchPattern: categoryMatchPattern,
      deathYear: deathYear,
      type: type
    };
  };

  SubjectAgeFromYear.findYearsFromCategories = function() {
    var allBirthYears, allDeathYears, allMatches, birthYear, categories, category, categoryMatchPattern, deathYear, type, _i, _len, _ref;
    allBirthYears = [];
    allDeathYears = [];
    allMatches = [];
    categories = (function() {
      var _i, _len, _ref, _results;
      _ref = mw.config.get('wgCategories');
      _results = [];
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        category = _ref[_i];
        _results.push(category.replace(/_/g, ' '));
      }
      return _results;
    })();
    categoryMatchPattern = /^([0-9]{1,4})( BC)? ([A-Za-z ]+)|(.*) (in|for) ([0-9]+)( BC)?$|^([0-9]{1,4})( BC)?$|^([0-9]{4,4}) ([A-Z][a-z]+)$/;
    for (_i = 0, _len = categories.length; _i < _len; _i++) {
      category = categories[_i];
      _ref = this.findYearFromCategory({
        allBirthYears: allBirthYears,
        allDeathYears: allDeathYears,
        allMatches: allMatches,
        birthYear: birthYear,
        category: category,
        categoryMatchPattern: categoryMatchPattern,
        deathYear: deathYear,
        type: type
      }), allBirthYears = _ref.allBirthYears, allDeathYears = _ref.allDeathYears, allMatches = _ref.allMatches, birthYear = _ref.birthYear, category = _ref.category, categoryMatchPattern = _ref.categoryMatchPattern, deathYear = _ref.deathYear, type = _ref.type;
      if ((birthYear != null) && (deathYear != null)) {
        break;
      }
    }
    $('#catlinks').attr('title', "Type: " + type + "\nBirth year: " + birthYear + "\nDeath year: " + deathYear + "\n\n Matched categories: " + (allMatches.join('; ')));
    return {
      allBirthYears: allBirthYears,
      allDeathYears: allDeathYears,
      birthYear: birthYear,
      deathYear: deathYear,
      type: type
    };
  };

  SubjectAgeFromYear.init = function() {
    var $allParagraphs, allBirthYears, allDeathYears, birthYear, birthYearLength, children, deathYear, deathYearLength, maxPossibleAge, parent, patternIndex, patterns, span, spansToRemove, subjectYear, today, todayLength, type, yearLength, _i, _ref, _ref1, _results;
    if ((mw.config.get('wgCanonicalNamespace') !== '' || mw.util.getParamValue('disable') === 'age' || mw.config.get('wgAction') !== 'view') && !(mw.config.get('wgPageName') === 'User:Gary_King/Sandbox' && (mw.config.get('wgAction') === 'view' || mw.config.get('wgAction') === 'submit'))) {
      return false;
    }
    _ref = this.findYearsFromCategories(), allBirthYears = _ref.allBirthYears, allDeathYears = _ref.allDeathYears, birthYear = _ref.birthYear, deathYear = _ref.deathYear, type = _ref.type;
    if (birthYear == null) {
      return false;
    }
    if (allBirthYears.length > 1) {
      allBirthYears.sort(function(a, b) {
        return a - b;
      });
      birthYear = allBirthYears[0];
    }
    if (allDeathYears.length > 1) {
      allDeathYears.sort(function(a, b) {
        return a - b;
      });
      deathYear = allDeathYears[0];
    }
    subjectYear = new SubjectYear;
    subjectYear.type(type);
    subjectYear.isAlive(false);
    today = new Date();
    maxPossibleAge = subjectYear.type() === 'biography' ? 125 : subjectYear.type() === 'establishment' ? 1000 : void 0;
    if (deathYear == null) {
      deathYear = birthYear + maxPossibleAge;
      if (deathYear >= today.getFullYear()) {
        subjectYear.isAlive(true);
      }
    }
    spansToRemove = [];
    patterns = [];
    birthYearLength = Math.abs(birthYear).toString().length;
    deathYearLength = Math.abs(deathYear).toString().length;
    todayLength = today.getFullYear().toString().length;
    yearLength = birthYear < 0 && deathYear > 0 ? 1 : birthYearLength < deathYearLength ? birthYearLength : deathYearLength;
    patterns.push(new RegExp('(AD |AD\u00A0)?\\b[0-9]{' + yearLength + ',' + todayLength + '}\\b( AD|\u00A0AD| CE|\u00A0CE)?', 'g'));
    if (birthYear < 0) {
      patterns.push(new RegExp('\\b[0-9]{' + yearLength + ',' + todayLength + '}( |\u00A0)?BC[E]?\\b', 'g'));
    }
    $allParagraphs = mw.config.get('wgAction') === 'submit' ? $('#wikiPreview > div > p') : $('#bodyContent > div > p');
    subjectYear.birthYear(birthYear);
    subjectYear.deathYear(deathYear);
    _results = [];
    for (patternIndex = _i = 0, _ref1 = patterns.length; 0 <= _ref1 ? _i < _ref1 : _i > _ref1; patternIndex = 0 <= _ref1 ? ++_i : --_i) {
      $allParagraphs.each((function(_this) {
        return function(index, element) {
          return $(element).contents().each(function(index, element) {
            return _this.findYearsInText({
              patternIndex: patternIndex,
              $node: $(element),
              patterns: patterns,
              spansToRemove: spansToRemove,
              subjectYear: subjectYear,
              today: today
            });
          });
        };
      })(this));
      _results.push((function() {
        var _j, _len, _results1;
        _results1 = [];
        for (_j = 0, _len = spansToRemove.length; _j < _len; _j++) {
          span = spansToRemove[_j];
          children = span.contents();
          parent = span.parent();
          if (!parent.length) {
            continue;
          }
          children.each(function() {
            return span.before($(this).clone());
          });
          span.remove();
          _results1.push(parent[0].normalize());
        }
        return _results1;
      })());
    }
    return _results;
  };

  SubjectAgeFromYear.nearAMonth = function(text, startIndex, beforeOrAfter, years, yearIndex) {
    var match, monthsArray, pattern;
    if (!beforeOrAfter) {
      beforeOrAfter = 1;
    }
    monthsArray = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
    pattern = new RegExp(monthsArray.join('|'));
    if (beforeOrAfter === 1) {
      text = text.substring(startIndex, text.length);
      match = text.match(pattern);
      if (match && text.indexOf(match[0]) === ' '.length) {
        return true;
      } else {
        return false;
      }
    } else if (beforeOrAfter === -1) {
      if (years[yearIndex + 1] && (startIndex + years[yearIndex].length + ', '.length) !== text.indexOf(years[yearIndex + 1])) {
        return false;
      }
      text = text.substring(0, startIndex);
      match = text.match(pattern);
      if (match && text.indexOf(match[0]) === (startIndex - ' '.length - match[0].length)) {
        return true;
      } else {
        return false;
      }
    }
  };

  return SubjectAgeFromYear;

})();

SubjectYear = (function() {
  function SubjectYear() {}

  SubjectYear.prototype.birthYear = function(birthYearValue) {
    this.birthYearValue = birthYearValue != null ? birthYearValue : this.birthYearValue;
    return this.birthYearValue;
  };

  SubjectYear.prototype.birthYearBuffer = function(birthYearBufferValue) {
    this.birthYearBufferValue = birthYearBufferValue != null ? birthYearBufferValue : this.birthYearBufferValue;
    return this.birthYearBufferValue;
  };

  SubjectYear.prototype.deathYear = function(deathYearValue) {
    this.deathYearValue = deathYearValue != null ? deathYearValue : this.deathYearValue;
    return this.deathYearValue;
  };

  SubjectYear.prototype.isAlive = function(isAliveValue) {
    this.isAliveValue = isAliveValue != null ? isAliveValue : this.isAliveValue;
    return this.isAliveValue;
  };

  SubjectYear.prototype.phrase = function(phrase) {
    var phrases;
    phrase = phrase.toLowerCase();
    phrases = {
      biography: {
        birth: 'birth',
        death: 'death'
      },
      establishment: {
        birth: 'established',
        death: 'disestablished'
      }
    };
    if (!((this.typeValue != null) && (phrases[this.typeValue] != null) && (phrases[this.typeValue][phrase] != null))) {
      return false;
    }
    return phrases[this.typeValue][phrase];
  };

  SubjectYear.prototype.type = function(typeValue) {
    this.typeValue = typeValue != null ? typeValue : this.typeValue;
    return this.typeValue = this.typeValue.toLowerCase();
  };

  return SubjectYear;

})();

$(function() {
  return SubjectAgeFromYear.init();
});