<commit_before>sansAccents = function (s) {
  var r = s.toLowerCase();
  r = r.replace(/[àáâãäå]/g, "a");
  r = r.replace(/[èéêë]/g, "e");
  r = r.replace(/[ìíîï]/g, "i");
  r = r.replace(/[òóôõö]/g, "o");
  r = r.replace(/[ùúûü]/g, "u");
  r = r.replace(/[ýÿ]/g, "y");
  return r;
};

// Comptage et découpage d'un mot en syllabes avec les possibilités de diérèses gérées par la variable max
syllabify = function (s) {
  if (s.toLowerCase() == "pays") { // Exception pour ce mot ingérable autrement
    return ({syllabes: ["pa", "ys"], nb: 2, max: 2});
  }
  if (!s.trim().match(/[a-zA-Z]/g)) {
    return {syllabes: [], nb: 0, max: 0};
  }
  var consonnes = ['b', 'B', 'c', 'C', 'ç', 'Ç', 'd', 'D', 'f', 'F', 'g', 'G', 'h', 'H', 'j', 'J', 'k', 'K', 'l', 'L', 'm', 'M', 'n', 'N', 'ñ', 'Ñ', 'p', 'P', 'q', 'Q', 'r', 'R', 's', 'S', 't', 'T', 'v', 'V', 'w', 'W', 'x', 'X', 'y', 'Y', 'z', 'Z', '-'];
  var voyellesFortes = ['a', 'A', 'á', 'Á', 'à', 'À', 'â', 'Â', 'e', 'E', 'é', 'É', 'è', 'È', 'ê', 'Ê', 'í', 'Í', 'o', 'ó', 'O', 'Ó', 'ô', 'Ô', 'ú', 'Ú'];
  var voyellesFaibles = ['i', 'I', 'u', 'U', 'ü', 'Ü', 'ï', 'Ï', 'î', 'Î', 'û', 'Û'];
  var voyelles = voyellesFortes.concat(voyellesFaibles, ['y', 'Y']);
  var nb, coupure, voy;
  var j = 0, max = 0;
  var n = s.length - 1;
  var i = 0;
  var syllabes = [];
  while (i <= n) {
    coupure = 0; // Ne coupe pas
    if (consonnes.indexOf(s.charAt(i)) > -1) {
      if (voyelles.indexOf(s.charAt(i + 1)) > -1) {
        if (s.toLowerCase().charAt(i) == 'y') { // diérèse possible du y utilisé comme consonne
          max++;
        }
        if (voyelles.indexOf(s.charAt(i - 1)) > -1) {
          coupure = 1;
        }
      } else if ((['s', 'S'].indexOf(s.charAt(i)) > -1) && (['n', 'N'].indexOf(s.charAt(i - 1)) > -1) && (consonnes.indexOf(s.charAt(i + 1)) > -1)) {
        coupure = 2;
      } else if ((consonnes.indexOf(s.charAt(i + 1)) > -1) && (voyelles.indexOf(s.charAt(i - 1)) > -1)) {
        if (['r', 'R'].indexOf(s.charAt(i + 1)) > -1) {
          if (['b', 'B', 'c', 'C', 'd', 'D', 'f', 'F', 'g', 'G', 'k', 'K', 'p', 'P', 'r', 'R', 't', 'T', 'v', 'V'].indexOf(s.charAt(i)) > -1) {
            coupure = 1;
          } else {
            coupure = 2;
          }
        } else if (['l', 'L'].indexOf(s.charAt(i + 1)) > -1) {
          if (['b', 'B', 'c', 'C', 'd', 'D', 'f', 'F', 'g', 'G', 'k', 'K', 'l', 'L', 'p', 'P', 't', 'T', 'v', 'V'].indexOf(s.charAt(i)) > -1) {
            coupure = 1;
          } else {
            coupure = 2;
          }
        } else if (['h', 'H'].indexOf(s.charAt(i + 1)) > -1) {
          if (['c', 'C', 's', 'S', 'p', 'P'].indexOf(s.charAt(i)) > -1) {
            coupure = 1;
          } else {
            coupure = 2;
          }
        } else if ((['t', 'T', 'p', 'P'].indexOf(s.charAt(i + 1)) > -1) && (['s', 'S'].indexOf(s.charAt(i + 2)) > -1)) { // pour des mots comme "verts" ou "corps"
        coupure = 0;
      } else {
        coupure = 2;
      }
    }
  } else if (voyellesFortes.indexOf(s.charAt(i)) > -1) {
    if ((voyellesFortes.indexOf(s.charAt(i - 1)) > -1) &&
    (s.substring(i - 2, i).toLowerCase() != 'ge') &&
    (s.substring(i - 1, i + 2).toLowerCase() != 'eau') &&
    (s.substring(i - 1, i + 1).toLowerCase() != 'oe') &&
    ((s.substring(i - 1, i + 2).toLowerCase() != 'ée') && (s.substring(i + 1, i + 2).toLowerCase() != 'ées') && (s.substring(i + 1, i + 4).toLowerCase() != 'éent'))) {
      coupure = 1;
    }
  } else if (voyellesFaibles.indexOf(s.charAt(i)) > -1 && (s.substring(i - 1, i + 1).toLowerCase() != 'qu') && (s.substring(i - 1, i + 1).toLowerCase() != 'gu')) { // Gestion de la diérèse éventuelle, sauf pour les cas avec "qu" / "gu"
  if ((voyelles.indexOf(s.charAt(i + 1)) > -1) &&
  (consonnes.indexOf(s.charAt(i - 1)) > -1) &&
  (consonnes.indexOf(s.charAt(i - 2)) > -1) &&
  (s.substring(i, i + 2).toLowerCase() != 'ui')) { // diérèse obligatoire si deux consonnes avant
    if (s.toLowerCase().charAt(i + 1) == 'y') { // diérèse possible du y pour des mots comme "ennuyer" ou "essuyer"
    max++;
  }
  coupure = 2;
} else if ((voyelles.indexOf(s.charAt(i + 1)) > -1)) {
  if (((s.substring(i + 1, i + 4).toLowerCase() != 'ent') && (s.substring(i + 1, i + 4).toLowerCase() != 'es')) || // Si terminaisons en "-aient" et en "-aie(s)" : pas de diérèse possible
  (s.substring(i, i + 2).toLowerCase() != 'ui')) { // Si mot comme "fruit", "bruit", "impuissant", diérèse très rare mais tolérable
  max++;
}
}
}
if (coupure == 1) {  // Couper ici
  voy = s.substring(j, i);
  syllabes.push(voy);
  j = i;
} else if (coupure == 2) { // Couper au caractère suivant
  i++;
  voy = s.substring(j, i);
  syllabes.push(voy);
  j = i;
}
i++;
}
nb = syllabes.length;
if ((j == n) && (nb > 0) && (consonnes.indexOf(s.charAt(n)) > -1)) { //Dernière lettre
  syllabes[nb - 1] = syllabes[nb - 1] + s.charAt(n);
} else {
  voy = s.substring(j, n + 1);
  syllabes.push(voy); // Dernière syllabe
  nb++;
}
return {syllabes: syllabes, nb: nb, max: nb + max};
};

// Prend un tableau de mots en entrée. Pour chaque mot dans le tableau (vers), applique syllabify avec les règles d'élision du e
elisioner = function (mots) {
  var voyelles = ['a', 'A', 'á', 'Á', 'à', 'À', 'â', 'Â', 'e', 'E', 'é', 'É', 'è', 'È', 'ê', 'Ê', 'í', 'Í', 'o', 'ó', 'O', 'Ó', 'ô', 'Ô', 'ú', 'Ú', 'i', 'I', 'u', 'U', 'ü', 'Ü', 'û', 'Û', 'ï', 'Ï', 'î', 'Î'];
  var elision = voyelles.concat(['h', 'H']);
  var syllabes, nb = 0, max = 0;

  for (var i = 0; i < mots.length; i++) {
    syllabes = syllabify(mots[i]);
    nb += syllabes.nb;
    max += syllabes.max;
    if ((i > 0) &&
    (mots[i - 1].toLowerCase().slice(-1) == 'e') &&
    (elision.indexOf(mots[i].charAt(0)) > -1) &&
    (sansAccents(mots[i - 1].toLowerCase().slice(-2, -1)) != sansAccents(mots[i].charAt(0)))) { // élision du e de fin dans le mot précédent si liaison (MAIS élision interdite si même son, ex: "Thésée excusable")
    nb--;
    if (['h', 'H'].indexOf(mots[i].charAt(0)) < 0) {
      max--;
    }
  }
  if ((i == mots.length - 1) &&
  (mots[i].toLowerCase().slice(-1) == 'e' || mots[i].toLowerCase().slice(-2) == 'es' || mots[i].toLowerCase().slice(-3) == 'ent')) { // élision du e en fin de vers
    nb--;
    if (!((voyelles.indexOf(mots[i].toLowerCase().slice(-2, -1)) > -1) && (mots[i].toLowerCase().slice(-1) == 'e')) && // Si finit par une voyelle + "e" : l'élision peut-être évitée en appuyant le e (ex: "patrie")
    !((voyelles.indexOf(mots[i].toLowerCase().slice(-3, -2)) > -1) && (mots[i].toLowerCase().slice(-2) == 'es')) &&
    !((voyelles.indexOf(mots[i].toLowerCase().slice(-4, -3)) > -1) && (mots[i].toLowerCase().slice(-3) == 'ent')) &&
    (mots[i].toLowerCase().slice(-4) != 'ment')) { // Si c'est un adverbe, la syllabe finale est obligatoire donc on ne diminue pas max pour prévenir ces cas
    max--;
  }
}
}
return {nb: nb, max: max};
};

// Compte le nombre de syllabes des vers d'un poème en suivant les règles classiques d'élision
metrify = function (s) {
  s = s.replace(/[\.,…\/#!$%\^&\*;\?:{}=\_`~()]/g, "").replace(/[0-9]/g, '').replace(/\s{2,}/g, " ").replace(/œ/g, "oe").replace(/æ/g, "ae").replace(/\r\n|\r|\n/g, "
");
  var vers = s.split("
");
  vers = vers.filter(function(v) {
    return v !== '';
  });
  var mots = [];
  var nbsyllabes = [];

  for (var i = 0; i < vers.length; i++) {
    var lesmots = vers[i].split(" ");
    lesmots = lesmots.filter(function(v) {
      return v !== '';
    });
    mots[i] = lesmots; // range les mots dans un tableau différent pour chaque vers
  }

  // Appliquer elisioner au tableau de mots de chaque vers
  for (var k = 0; k < mots.length; k++) {
    nbsyllabes[k] = elisioner(mots[k]);
  }

  return {vers: vers, mots: mots, nbsyllabes: nbsyllabes};
};

module.exports = {
  metrique: metrify,
  elision: elisioner,
  syllabes: syllabify
};
<commit_msg>Minor refactoring<commit_after>sansAccents = function (s) {
    var r = s.toLowerCase();
    r = r.replace(/[àáâãäå]/g, "a");
    r = r.replace(/[èéêë]/g, "e");
    r = r.replace(/[ìíîï]/g, "i");
    r = r.replace(/[òóôõö]/g, "o");
    r = r.replace(/[ùúûü]/g, "u");
    r = r.replace(/[ýÿ]/g, "y");
    return r;
};

// Comptage et découpage d'un mot en syllabes avec les possibilités de diérèses gérées par la variable max
syllabify = function (s) {
    if (s.toLowerCase() == "pays") // Exception pour ce mot ingérable autrement
        return ({ syllabes: ["pa", "ys"], nb: 2, max: 2 });
    if (!s.trim().match(/[a-zA-Z]/g))
        return { syllabes: [], nb: 0, max: 0 };
    var consonnes = ['b', 'B', 'c', 'C', 'ç', 'Ç', 'd', 'D', 'f', 'F', 'g', 'G', 'h', 'H', 'j', 'J', 'k', 'K', 'l', 'L', 'm', 'M', 'n', 'N', 'ñ', 'Ñ', 'p', 'P', 'q', 'Q', 'r', 'R', 's', 'S', 't', 'T', 'v', 'V', 'w', 'W', 'x', 'X', 'y', 'Y', 'z', 'Z', '-'],
    voyellesFortes = ['a', 'A', 'á', 'Á', 'à', 'À', 'â', 'Â', 'e', 'E', 'é', 'É', 'è', 'È', 'ê', 'Ê', 'í', 'Í', 'o', 'ó', 'O', 'Ó', 'ô', 'Ô', 'ú', 'Ú'],
    voyellesFaibles = ['i', 'I', 'u', 'U', 'ü', 'Ü', 'ï', 'Ï', 'î', 'Î', 'û', 'Û'],
    voyelles = voyellesFortes.concat(voyellesFaibles, ['y', 'Y']),
    nb, coupure, voy, j = 0, max = 0, n = s.length - 1, i = 0, syllabes = [];
    while (i <= n) {
        coupure = 0; // Ne coupe pas
        if (consonnes.indexOf(s.charAt(i)) > -1) {
            if (voyelles.indexOf(s.charAt(i + 1)) > -1) {
                if (s.toLowerCase().charAt(i) == 'y') // diérèse possible du y utilisé comme consonne
                    max++;
                if (voyelles.indexOf(s.charAt(i - 1)) > -1)
                    coupure = 1;
            } else if ((['s', 'S'].indexOf(s.charAt(i)) > -1) && (['n', 'N'].indexOf(s.charAt(i - 1)) > -1) && (consonnes.indexOf(s.charAt(i + 1)) > -1)) {
                coupure = 2;
            } else if ((consonnes.indexOf(s.charAt(i + 1)) > -1) && (voyelles.indexOf(s.charAt(i - 1)) > -1)) {
                if (['r', 'R'].indexOf(s.charAt(i + 1)) > -1) {
                    coupure = ['b', 'B', 'c', 'C', 'd', 'D', 'f', 'F', 'g', 'G', 'k', 'K', 'p', 'P', 'r', 'R', 't', 'T', 'v', 'V'].indexOf(s.charAt(i)) > -1 ? 1 : 2;
                } else if (['l', 'L'].indexOf(s.charAt(i + 1)) > -1) {
                    coupure = ['b', 'B', 'c', 'C', 'd', 'D', 'f', 'F', 'g', 'G', 'k', 'K', 'l', 'L', 'p', 'P', 't', 'T', 'v', 'V'].indexOf(s.charAt(i)) > -1 ? 1 : 2;
                } else if (['h', 'H'].indexOf(s.charAt(i + 1)) > -1) {
                    coupure = ['c', 'C', 's', 'S', 'p', 'P'].indexOf(s.charAt(i)) > -1 ? 1 : 2;
                } else if ((['t', 'T', 'p', 'P'].indexOf(s.charAt(i + 1)) > -1) && (['s', 'S'].indexOf(s.charAt(i + 2)) > -1)) { // pour des mots comme "verts" ou "corps"
                    coupure = 0;
                } else {
                    coupure = 2;
                }
            }
        } else if (voyellesFortes.indexOf(s.charAt(i)) > -1) {
            if ((voyellesFortes.indexOf(s.charAt(i - 1)) > -1) &&
            (s.substring(i - 2, i).toLowerCase() != 'ge') &&
            (s.substring(i - 1, i + 2).toLowerCase() != 'eau') &&
            (s.substring(i - 1, i + 1).toLowerCase() != 'oe') &&
            ((s.substring(i - 1, i + 2).toLowerCase() != 'ée') && (s.substring(i + 1, i + 2).toLowerCase() != 'ées') && (s.substring(i + 1, i + 4).toLowerCase() != 'éent'))) {
                coupure = 1;
            }
        } else if (voyellesFaibles.indexOf(s.charAt(i)) > -1 && (s.substring(i - 1, i + 1).toLowerCase() != 'qu') && (s.substring(i - 1, i + 1).toLowerCase() != 'gu')) { // Gestion de la diérèse éventuelle, sauf pour les cas avec "qu" / "gu"
            if ((voyelles.indexOf(s.charAt(i + 1)) > -1) &&
            (consonnes.indexOf(s.charAt(i - 1)) > -1) &&
            (consonnes.indexOf(s.charAt(i - 2)) > -1) &&
            (s.substring(i, i + 2).toLowerCase() != 'ui')) { // diérèse obligatoire si deux consonnes avant
                if (s.toLowerCase().charAt(i + 1) == 'y') // diérèse possible du y pour des mots comme "ennuyer" ou "essuyer"
                    max++;
                coupure = 2;
            } else if ((voyelles.indexOf(s.charAt(i + 1)) > -1) &&
                (((s.substring(i + 1, i + 4).toLowerCase() != 'ent') && (s.substring(i + 1, i + 4).toLowerCase() != 'es')) || // Si terminaisons en "-aient" et en "-aie(s)" : pas de diérèse possible
                 (s.substring(i, i + 2).toLowerCase() != 'ui'))) { // Si mot comme "fruit", "bruit", "impuissant", diérèse très rare mais tolérable
                max++;
            }
        }
        if (coupure == 1) {  // Couper ici
            voy = s.substring(j, i);
            syllabes.push(voy);
            j = i;
        } else if (coupure == 2) { // Couper au caractère suivant
            i++;
            voy = s.substring(j, i);
            syllabes.push(voy);
            j = i;
        }
        i++;
    }
    nb = syllabes.length;
    if ((j == n) && (nb > 0) && (consonnes.indexOf(s.charAt(n)) > -1)) { //Dernière lettre
        syllabes[nb - 1] = syllabes[nb - 1] + s.charAt(n);
    } else {
        voy = s.substring(j, n + 1);
        syllabes.push(voy); // Dernière syllabe
        nb++;
    }
    return { syllabes: syllabes, nb: nb, max: nb + max };
};

// Prend un tableau de mots en entrée. Pour chaque mot dans le tableau (vers), applique syllabify avec les règles d'élision du e
elisioner = function (mots) {
    var voyelles = ['a', 'A', 'á', 'Á', 'à', 'À', 'â', 'Â', 'e', 'E', 'é', 'É', 'è', 'È', 'ê', 'Ê', 'í', 'Í', 'o', 'ó', 'O', 'Ó', 'ô', 'Ô', 'ú', 'Ú', 'i', 'I', 'u', 'U', 'ü', 'Ü', 'û', 'Û', 'ï', 'Ï', 'î', 'Î'],
    elision = voyelles.concat(['h', 'H']),
    syllabes, nb = 0, max = 0;
    for (var i = 0; i < mots.length; i++) {
        syllabes = syllabify(mots[i]);
        nb += syllabes.nb;
        max += syllabes.max;
        if ((i > 0) &&
        (mots[i - 1].toLowerCase().slice(-1) == 'e') &&
        (elision.indexOf(mots[i].charAt(0)) > -1) &&
        (sansAccents(mots[i - 1].toLowerCase().slice(-2, -1)) != sansAccents(mots[i].charAt(0)))) { // élision du e de fin dans le mot précédent si liaison (MAIS élision interdite si même son, ex: "Thésée excusable")
            nb--;
            if (['h', 'H'].indexOf(mots[i].charAt(0)) < 0)
                max--;
        }
        if ((i == mots.length - 1) &&
        (mots[i].toLowerCase().slice(-1) == 'e' || mots[i].toLowerCase().slice(-2) == 'es' || mots[i].toLowerCase().slice(-3) == 'ent')) { // élision du e en fin de vers
            nb--;
            if (!((voyelles.indexOf(mots[i].toLowerCase().slice(-2, -1)) > -1) && (mots[i].toLowerCase().slice(-1) == 'e')) && // Si finit par une voyelle + "e" : l'élision peut-être évitée en appuyant le e (ex: "patrie")
            !((voyelles.indexOf(mots[i].toLowerCase().slice(-3, -2)) > -1) && (mots[i].toLowerCase().slice(-2) == 'es')) &&
            !((voyelles.indexOf(mots[i].toLowerCase().slice(-4, -3)) > -1) && (mots[i].toLowerCase().slice(-3) == 'ent')) &&
            (mots[i].toLowerCase().slice(-4) != 'ment')) { // Si c'est un adverbe, la syllabe finale est obligatoire donc on ne diminue pas max pour prévenir ces cas
                max--;
            }
        }
    }
    return { nb: nb, max: max };
};

// Compte le nombre de syllabes des vers d'un poème en suivant les règles classiques d'élision
metrify = function (s) {
    s = s.replace(/[\.,…\/#!$%\^&\*;\?:{}=\_`~()]/g, "").replace(/[0-9]/g, '').replace(/\s{2,}/g, " ").replace(/œ/g, "oe").replace(/æ/g, "ae").replace(/\r\n|\r|\n/g, "
"),
    vers = s.split("
").filter(function (v) { return v !== ''; }),
    mots = [], nbsyllabes = [];
    for (var i = 0; i < vers.length; i++) {
        var lesmots = vers[i].split(" ");
        lesmots = lesmots.filter(function (v) { return v !== ''; });
        mots[i] = lesmots; // range les mots dans un tableau différent pour chaque vers
    }
    // Appliquer elisioner au tableau de mots de chaque vers
    for (var k = 0; k < mots.length; k++)
        nbsyllabes[k] = elisioner(mots[k]);
    return { vers: vers, mots: mots, nbsyllabes: nbsyllabes };
};

module.exports = {
    metrique: metrify,
    elision: elisioner,
    syllabes: syllabify
};
<|endoftext|>


<commit_before>/*global XMLHttpRequest */

/*
 * microAjax
 * Created 2015 Triangle717
 * <http://le717.github.io/>
 *
 * Licensed under The MIT License
 * <http://opensource.org/licenses/MIT/>
 */

/**
 * Perform a simple async AJAX request.
 * @param {Object} options.<[method=POST], url, data,
 *                                         [success=function], [warning=function], [error=function]>
 *                 method: GET or POST.
 *                 url: The URL to contact.
 *                 data: the content to send to the page.
 *                 success: Code to run on request success.
 *                 warning: Code to run on request warning.
 *                 error: Code to run on request error.
 */
function microAjax(options) {
  "use strict";

  // Default to POST
  if (options.method === undefined) {
    options.method = "POST";
  }

  // Define empty functions for the callbacks
  if (options.success === undefined) {
    options.success = function() {};
  }

  if (options.warning === undefined) {
    options.warning = function() {};
  }

  if (options.error === undefined) {
    options.error = function() {};
  }

  var request = new XMLHttpRequest();
  request.open(options.method, options.url, true);
  request.send(options.data);

  request.onload = function() {
    // Success!
    if (request.readyState === 4 && request.status === 200) {
      options.success(request.responseText);

      // We reached our target destination, but it returned an error
    } else {
      options.warning();
    }
  };

  // There was a connection error of some sort
  request.onerror = options.error();
}
<commit_msg>Update docstring<commit_after>/*global XMLHttpRequest */

/*
 * microAjax.js
 * Created 2015-2016 Triangle717
 * <http://le717.github.io/>
 *
 * Licensed under The MIT License
 * <http://opensource.org/licenses/MIT/>
 */

/**
 * Perform a simple async AJAX request.
 * @param {Object} options.<[method=POST], url, data,
 *                                         [success=function], [warning=function], [error=function]>
 *                 method: GET or POST.
 *                 url: The URL to contact.
 *                 data: the content to send to the page.
 *                 success: Code to run on request success.
 *                 warning: Code to run on request warning.
 *                 error: Code to run on request error.
 */
function microAjax(options) {
  "use strict";

  // Default to POST
  if (options.method === undefined) {
    options.method = "POST";
  }

  // Define empty functions for the callbacks
  if (options.success === undefined) {
    options.success = function() {};
  }

  if (options.warning === undefined) {
    options.warning = function() {};
  }

  if (options.error === undefined) {
    options.error = function() {};
  }

  var request = new XMLHttpRequest();
  request.open(options.method, options.url, true);
  request.send(options.data);

  request.onload = function() {
    // Success!
    if (request.readyState === 4 && request.status === 200) {
      options.success(request.responseText);

      // We reached our target destination, but it returned an error
    } else {
      options.warning();
    }
  };

  // There was a connection error of some sort
  request.onerror = options.error();
}
<|endoftext|>


<commit_before><commit_msg>s/this.studioApp/this.studioApp_<commit_after><|endoftext|>


<commit_before>import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

// 创建一个对象来保存应用启动时的初始状态
const state = {
  // TODO: 放置初始状态
}

// 创建一个对象
const mutations = {
  // TODO: 放置我们的状态变更函数
}

export default new Vuex.Store({
  state,
  mutations
})<commit_msg>create state & mutation<commit_after>import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

// 创建一个对象来保存应用启动时的初始状态
const state = {
  // TODO: 放置初始状态
  count: 0
}

// 创建一个对象
const mutations = {
  // TODO: 放置我们的状态变更函数
  // mutation 的第一个参数是当前的 state
  // 你可以在函数里修改 state
  INCREMENT (state, amount) {
  	state.count = state.count + amount
  }
}

export default new Vuex.Store({
  state,
  mutations
})<|endoftext|>


<commit_before>import { Vector3 } from "../../lib/three.es6.js";

import SpatialHash from "../geometry/spatial-hash.js";
import Colormaker from "./colormaker.js";
import { ColormakerRegistry } from "../globals.js";

const partialCharges = {
  "ARG": {
    "CD": 0.1,
    "CZ": 0.5,
    "NE": -0.1
  },
  "ASN": {
    "CG": 0.55,
    "OD1": -0.55
  },
  "ASP": {
    "CB": -0.16,
    "CG": 0.36,
    "OD1": -0.6,
    "OD2": -0.6
  },
  "CYS": {
    "CB": 0.19,
    "SG": -0.19
  },
  "GLN": {
    "CD": 0.55,
    "OE1": -0.55
  },
  "GLU": {
    "CD": 0.36,
    "CG": -0.16,
    "OE1": -0.6,
    "OE2": -0.6,
  },
  "HIS": {
    "CB": 0.1,
    "CD2": 0.2,
    "CE1": 0.45,
    "CG": 0.15,
    "ND1": 0.05,
    "NE2": 0.05
  },
  "LYS": {
    "CE": 0.25,
    "NZ": 0.75
  },
  "MET": {
    "CE": 0.06,
    "CG": 0.06,
    "SD": -0.12
  },
  "PTR": {
    "C": 0.55,
    "CA": 0.1,
    "CZ": 0.25,
    "N": -0.35,
    "O": -0.55,
    "O1P": -0.85,
    "O2P": -0.85,
    "O3P": -0.85,
    "OG1": -1.1,
    "P": 1.4
  },
  "SEP": {
    "C": 0.55,
    "CA": 0.1,
    "CB": 0.25,
    "N": -0.35,
    "O": -0.55,
    "O1P": -0.85,
    "O2P": -0.85,
    "O3P": -0.85,
    "OG1": -1.1,
    "P": 1.4
  },
  "SER": {
    "CB": 0.25,
    "OG": -0.25
  },
  "THR": {
    "CB": 0.25,
    "OG1": -0.25
  },
  "TPO": {
    "C": 0.55,
    "CA": 0.1,
    "CB": 0.25,
    "N": -0.35,
    "O": -0.55,
    "OG1": -1.1,
    "O1P": -0.85,
    "O2P": -0.85,
    "O3P": -0.85,
    "P": 1.4
  },
  "TRP": {
    "CD1": 0.06,
    "CD2": 0.1,
    "CE2": -0.04,
    "CE3": -0.03,
    "CG": -0.03,
    "NE1": -0.06
  },
  "TYR": {
    "CZ": 0.25,
    "OH": -0.25
  },
  "backbone": {
    "C": 0.55,
    "O": -0.55,
    "N": -0.1,
    "CA": 0.1
  }
};

// Constant for now (might want to make parameters?)
const maxRadius = 12.0;

class ElectrostaticColormaker extends Colormaker {
    constructor( params ) {
        super( params )

        if( !params.scale ){
            this.scale = "RdYlGn";
        }
        if( !params.domain ) {
            this.domain = [ -0.5, 0, 0.5 ];
        }

        const scale = this.getScale();

        // Create a spatial hash of coordinates for this structure
        function chargeForAtom( a ){
            if( !a.isProtein() ) { return 0.0; }
            return ( ( partialCharges[ a.resname ] &&
                    partialCharges[ a.resname ][ a.atomname ] ) ||
                    partialCharges[ "backbone" ][ a.atomname ] || 0.0 );
        }

        const structure = this.structure;
        const charges = new Float32Array( structure.atomCount );

        structure.eachAtom( ( ap ) => {
            charges[ ap.index ] = chargeForAtom( ap );
        } );

        const bbox = this.structure.getBoundingBox();
        const hash = new SpatialHash( this.structure.atomStore, bbox );

        const ap = this.atomProxy;
        const delta = new Vector3();
        const maxRadius2 = maxRadius * maxRadius;

        this.positionColor = function( v ){
            const neighbours = hash.within( v.x, v.y, v.z, maxRadius );
            let p = 0.0;
            for( let i = 0; i < neighbours.length; i++ ){
                const neighbour = neighbours[ i ],
                      charge = charges[ neighbour ];
                if( charge !== 0.0 ) {
                    ap.index = neighbour;
                    delta.x = v.x - ap.x;
                    delta.y = v.y - ap.y;
                    delta.z = v.z - ap.z;
                    const r2 = delta.lengthSq();
                    if( r2 < maxRadius2 ) {
                        p += charge / delta.lengthSq();
                    }
                }
            }
            return scale( p );
        }

    }
}

ColormakerRegistry.add( "electrostatic", ElectrostaticColormaker );

export default ElectrostaticColormaker;<commit_msg>esp-surface, wip: Place backbone N-H and add point charge for H<commit_after>import { Vector3 } from "../../lib/three.es6.js";

import Colormaker from "./colormaker.js";
import { ColormakerRegistry } from "../globals.js";
import SpatialHash from "../geometry/spatial-hash.js";

const partialCharges = {
    "ARG": {
        "CD": 0.1,
        "CZ": 0.5,
        "NE": -0.1
    },
    "ASN": {
        "CG": 0.55,
        "OD1": -0.55
    },
    "ASP": {
        "CB": -0.16,
        "CG": 0.36,
        "OD1": -0.6,
        "OD2": -0.6
    },
    "CYS": {
        "CB": 0.19,
        "SG": -0.19
    },
    "GLN": {
        "CD": 0.55,
        "OE1": -0.55
    },
    "GLU": {
        "CD": 0.36,
        "CG": -0.16,
        "OE1": -0.6,
        "OE2": -0.6,
    },
    "HIS": {
        "CB": 0.1,
        "CD2": 0.2,
        "CE1": 0.45,
        "CG": 0.15,
        "ND1": 0.05,
        "NE2": 0.05
    },
    "LYS": {
        "CE": 0.25,
        "NZ": 0.75
    },
    "MET": {
        "CE": 0.06,
        "CG": 0.06,
        "SD": -0.12
    },
    "PTR": {
        "C": 0.55,
        "CA": 0.1,
        "CZ": 0.25,
        "N": -0.35,
        "O": -0.55,
        "O1P": -0.85,
        "O2P": -0.85,
        "O3P": -0.85,
        "OG1": -1.1,
        "P": 1.4
    },
    "SEP": {
        "C": 0.55,
        "CA": 0.1,
        "CB": 0.25,
        "N": -0.35,
        "O": -0.55,
        "O1P": -0.85,
        "O2P": -0.85,
        "O3P": -0.85,
        "OG1": -1.1,
        "P": 1.4
    },
    "SER": {
        "CB": 0.25,
        "OG": -0.25
    },
    "THR": {
        "CB": 0.25,
        "OG1": -0.25
    },
    "TPO": {
        "C": 0.55,
        "CA": 0.1,
        "CB": 0.25,
        "N": -0.35,
        "O": -0.55,
        "OG1": -1.1,
        "O1P": -0.85,
        "O2P": -0.85,
        "O3P": -0.85,
        "P": 1.4
    },
    "TRP": {
        "CD1": 0.06,
        "CD2": 0.1,
        "CE2": -0.04,
        "CE3": -0.03,
        "CG": -0.03,
        "NE1": -0.06
    },
    "TYR": {
        "CZ": 0.25,
        "OH": -0.25
    },
    "backbone": {
        "C": 0.55,
        "O": -0.55,
        "N": -0.35,
        "CA": 0.1
    }
};

// Constant for now (might want to make parameters?)
const maxRadius = 12.0;

/*
 * Populates position vector with location of implicit or explicit H
 * Returns position or undefined if not able to locate H
 */
function backboneNHPosition( ap, position ){

    position = position || new Vector3();

    let h = false, ca = false, c = false;
    position.set( 2* ap.x, 2 * ap.y, 2 * ap.z );

    ap.eachBondedAtom( function( a2 ){
        // Any time we detect H, reset position and skip
        // future tests
        if( h ) return;
        if( a2.atomname === "H" ){
            position.set( a2 );
            h = true;
            return;
        }
        if( !ca && a2.atomname === "CA" ){
            position.sub( a2 );
            ca = true;
        }
        else if( !c && a2.atomname === "C" ){
            c = true;
            position.sub( a2 );
        }
    } );

    if( h ){ return position; }

    if( ca && c ){

        position.normalize();
        position.multiplyScalar( 1.04 ); // N-H dist
        position.add( ap );
        return position

    }
}

/* Takes the Vector3 positions and builds an object with
 * x,y,z and count attributes
 */
function buildStoreLike( positions ){
    const n = positions.length;
    const x = new Float32Array( n );
    const y = new Float32Array( n );
    const z = new Float32Array( n );

    for( let i = 0; i < positions.length; i++ ){
        const v = positions [ i ];
        x[ i ] = v.x;
        y[ i ] = v.y;
        z[ i ] = v.z;
    }

    return { x: x, y: y, z: z, count: n }
}

class ElectrostaticColormaker extends Colormaker {
    constructor( params ) {
        super( params )

        if( !params.scale ){
            this.scale = "RdYlGn";
        }
        if( !params.domain ) {
            this.domain = [ -0.5, 0, 0.5 ];
        }

        const scale = this.getScale();

        // Create a spatial hash of coordinates for this structure
        function chargeForAtom( a ){
            if( !a.isProtein() ) { return 0.0; }
            return ( ( partialCharges[ a.resname ] &&
                    partialCharges[ a.resname ][ a.atomname ] ) ||
                    partialCharges[ "backbone" ][ a.atomname ] || 0.0 );
        }

        const structure = this.structure;
        const charges = new Float32Array( structure.atomCount );

        const hPositions = []; // For now store as array of Vector3

        structure.eachAtom( ( ap ) => {
            charges[ ap.index ] = chargeForAtom( ap );
            if( ap.atomname === "N" ){
              const hPos = backboneNHPosition( ap );
              if( hPos !== undefined ){ hPositions.push( hPos ); }
            }
        } );

        const bbox = this.structure.getBoundingBox();
        bbox.expandByScalar( 1.04 ); // Worst case

        // SpatialHash requires x,y,z and count
        const hStore = buildStoreLike( hPositions );
        const hHash = new SpatialHash( hStore, bbox );
        const hash = new SpatialHash( this.structure.atomStore, bbox );

        const ap = this.atomProxy;
        const delta = new Vector3();
        const maxRadius2 = maxRadius * maxRadius;

        this.positionColor = function( v ){
            let p = 0.0;
            const neighbours = hash.within( v.x, v.y, v.z, maxRadius );

            for( let i = 0; i < neighbours.length; i++ ){
                const neighbour = neighbours[ i ],
                      charge = charges[ neighbour ];
                if( charge !== 0.0 ) {
                    ap.index = neighbour;
                    delta.x = v.x - ap.x;
                    delta.y = v.y - ap.y;
                    delta.z = v.z - ap.z;
                    const r2 = delta.lengthSq();
                    if( r2 < maxRadius2 ) {
                        p += charge / delta.lengthSq();
                    }
                }
            }

            const hNeighbours = hHash.within( v.x, v.y, v.z, maxRadius );
            for( let i = 0; i < hNeighbours.length; i++ ){
                const neighbour = hNeighbours[ i ];
                delta.x = v.x - hStore.x[ neighbour ];
                delta.y = v.y - hStore.y[ neighbour ];
                delta.z = v.z - hStore.z[ neighbour ];
                const r2 = delta.lengthSq();
                if( r2 < maxRadius2 ) {
                    p += 0.25 / delta.lengthSq();
                }

            }
            return scale( p );
        }

    }
}

ColormakerRegistry.add( "electrostatic", ElectrostaticColormaker );

export default ElectrostaticColormaker;
<|endoftext|>


<commit_before>// --
// Core.UI.Accessibility.UnitTest.js - UnitTests
// Copyright (C) 2001-2010 OTRS AG, http://otrs.org/\n";
// --
// $Id: Core.JSON.UnitTest.js,v 1.1 2010-07-13 09:46:45 mg Exp $
// --
// This software comes with ABSOLUTELY NO WARRANTY. For details, see
// the enclosed file COPYING for license information (AGPL). If you
// did not receive this file, see http://www.gnu.org/licenses/agpl.txt.
// --

"use strict";

var OTRS = OTRS || {};

Core.JSON = (function (Namespace) {
    Namespace.RunUnitTests = function(){
        module('Core.JSON');
        test('Core.JSON.Parse()', function(){

            expect(16);

            /*
             * Run the tests
             */
            var ValueTwo = "abcd";
            var StringOne = '{"ItemOne":1234,"ItemTwo":"' + ValueTwo + '","ItemThree":true,"ItemFour":false}';
            var ObjectOne = Core.JSON.Parse(StringOne);
            var ReturnOne = Core.JSON.Stringify(ObjectOne);

            equals(StringOne, ReturnOne, 'okay');
            equals(ObjectOne.ItemOne, '1234', 'okay');
            equals(ObjectOne.ItemTwo, ValueTwo, 'okay');

            /* Round 2*/
            var ObjectTwo =
            { "Consulting" : [
                                { "Address"     : "535 Joseph Roberts Av.",
                                  "Employees"   : 12,
                                  "LastUpdate"  : '06/12/2010' }
                              ],
              "Sales"       : [
                                { "Address"     : "789 Second St.",
                                  "Employees"   : 8,
                                  "LastUpdate"  : '06/12/2010' }
                              ]
            };
            var ReturnTwo   = Core.JSON.Stringify(ObjectTwo);
            var ObjectThree = Core.JSON.Parse(ReturnTwo);
            var ReturnThree = Core.JSON.Stringify(ObjectThree);

            equals(ObjectTwo.Consulting[0].Address, ObjectThree.Consulting[0].Address, 'okay');
            equals(ObjectTwo.Sales[0].LastUpdate, ObjectThree.Sales[0].LastUpdate, 'okay');
            equals(ReturnTwo, ReturnThree, 'okay');
            var ResultCompare1 = Core.Data.CompareObject(ObjectTwo, ObjectThree);
            equals(ResultCompare1, true, 'okay');

            // Delete a element and compare
            ObjectTwo.Sales[0].LastUpdate = '10/12/2010';
            var ResultCompare2 = Core.Data.CompareObject(ObjectTwo, ObjectThree);
            notEqual(ResultCompare2, true, 'okay');

            var ReturnDiferent = Core.JSON.Stringify(ObjectTwo);
            notEqual(ReturnTwo, ReturnDiferent, 'okay');

            /* Round 3*/
            var ObjectFour =
            {
                "CompanyOne" :
                    [{ "Areas" :
                        [{ "Marketing" :
                            [{ "Address"     : "23 Albert Einstein St.",
                               "Employees"   : 7,
                               "LastUpdate"  : '10/03/2008'
                            }],
                           "Sales" :
                            [{ "Address"     : "1555 London St.",
                               "Employees"   : 30,
                               "LastUpdate"  : '20/10/2009'
                            }]
                        }]
                    }]
             };

            var ObjectFive = {};
            var StringCompanyTwo =
                '{"Design":[{"Address":"777 Beach Av.","Employees":20,"LastUpdate":"25/02/2010"}],' +
                 '"Development":[{"Address":"1 Sunset St.","Employees":300,"LastUpdate":"24/06/2010"}]}';
            var ObjectSix = Core.JSON.Parse(StringCompanyTwo);
            ObjectFive.Areas = ObjectSix;

            ObjectFour.CompanyTwo = ObjectFive;
            ObjectFour.CompanyThree = {};
            ObjectFour.CompanyThree.Areas = ObjectTwo;

            var ReturnCompanyTwo   = Core.JSON.Stringify(ObjectFive.Areas);
            equals(StringCompanyTwo, ReturnCompanyTwo, 'okay');
            var ResultCompare3 = Core.Data.CompareObject(ObjectFour.CompanyTwo.Areas, ObjectSix);
            equals(ResultCompare3, true, 'okay');

            var ReturnCompanyTwoAreas   = Core.JSON.Stringify(ObjectFour.CompanyTwo.Areas);
            equals(ReturnCompanyTwoAreas, StringCompanyTwo, 'okay');

            var ResultCompare4 = Core.Data.CompareObject(ObjectFour.CompanyTwo, ObjectFour.CompanyThree);
            notEqual(ResultCompare4, true, 'okay');

            var ReturnFour      = Core.JSON.Stringify(ObjectFour);
            var ObjectFourParse = Core.JSON.Parse(ReturnFour);
            var ResultCompare5  = Core.Data.CompareObject(ObjectFourParse, ObjectFour);
            equals(ResultCompare5, true, 'okay');

            /* Round 4*/
            ObjectSeven          = {};
            ObjectSeven.one      = ObjectFour;
            ObjectSeven.two      = ObjectFourParse;
            ObjectSeven.three    = ObjectFive;
            ObjectSeven.four     = ObjectSix;
            var ReturnSeven      = Core.JSON.Stringify(ObjectSeven);
            var ObjectSevenParse = Core.JSON.Parse(ReturnSeven);
            var ResultCompare6   = Core.Data.CompareObject(ObjectSeven, ObjectSevenParse);
            equals(ResultCompare6, true, 'okay');

            ObjectSeven.five     = ObjectTwo;
            var ResultCompare7   = Core.Data.CompareObject(ObjectSevenParse, ObjectSeven);
            notEqual(ResultCompare7, true, 'okay');

        });
    };

    return Namespace;
}(Core.JSON || {}));<commit_msg>Fixed JSON unit test errors because of scrict mode.<commit_after>// --
// Core.UI.Accessibility.UnitTest.js - UnitTests
// Copyright (C) 2001-2011 OTRS AG, http://otrs.org/\n";
// --
// $Id: Core.JSON.UnitTest.js,v 1.2 2011-05-10 11:22:49 mg Exp $
// --
// This software comes with ABSOLUTELY NO WARRANTY. For details, see
// the enclosed file COPYING for license information (AGPL). If you
// did not receive this file, see http://www.gnu.org/licenses/agpl.txt.
// --

"use strict";

var OTRS = OTRS || {};

Core.JSON = (function (Namespace) {
    Namespace.RunUnitTests = function(){
        module('Core.JSON');
        test('Core.JSON.Parse()', function(){

            expect(16);

            /*
             * Run the tests
             */
            var ValueTwo = "abcd";
            var StringOne = '{"ItemOne":1234,"ItemTwo":"' + ValueTwo + '","ItemThree":true,"ItemFour":false}';
            var ObjectOne = Core.JSON.Parse(StringOne);
            var ReturnOne = Core.JSON.Stringify(ObjectOne);

            equals(StringOne, ReturnOne, 'okay');
            equals(ObjectOne.ItemOne, '1234', 'okay');
            equals(ObjectOne.ItemTwo, ValueTwo, 'okay');

            /* Round 2*/
            var ObjectTwo =
            { "Consulting" : [
                                { "Address"     : "535 Joseph Roberts Av.",
                                  "Employees"   : 12,
                                  "LastUpdate"  : '06/12/2010' }
                              ],
              "Sales"       : [
                                { "Address"     : "789 Second St.",
                                  "Employees"   : 8,
                                  "LastUpdate"  : '06/12/2010' }
                              ]
            };
            var ReturnTwo   = Core.JSON.Stringify(ObjectTwo);
            var ObjectThree = Core.JSON.Parse(ReturnTwo);
            var ReturnThree = Core.JSON.Stringify(ObjectThree);

            equals(ObjectTwo.Consulting[0].Address, ObjectThree.Consulting[0].Address, 'okay');
            equals(ObjectTwo.Sales[0].LastUpdate, ObjectThree.Sales[0].LastUpdate, 'okay');
            equals(ReturnTwo, ReturnThree, 'okay');
            var ResultCompare1 = Core.Data.CompareObject(ObjectTwo, ObjectThree);
            equals(ResultCompare1, true, 'okay');

            // Delete a element and compare
            ObjectTwo.Sales[0].LastUpdate = '10/12/2010';
            var ResultCompare2 = Core.Data.CompareObject(ObjectTwo, ObjectThree);
            notEqual(ResultCompare2, true, 'okay');

            var ReturnDiferent = Core.JSON.Stringify(ObjectTwo);
            notEqual(ReturnTwo, ReturnDiferent, 'okay');

            /* Round 3*/
            var ObjectFour =
            {
                "CompanyOne" :
                    [{ "Areas" :
                        [{ "Marketing" :
                            [{ "Address"     : "23 Albert Einstein St.",
                               "Employees"   : 7,
                               "LastUpdate"  : '10/03/2008'
                            }],
                           "Sales" :
                            [{ "Address"     : "1555 London St.",
                               "Employees"   : 30,
                               "LastUpdate"  : '20/10/2009'
                            }]
                        }]
                    }]
             };

            var ObjectFive = {};
            var StringCompanyTwo =
                '{"Design":[{"Address":"777 Beach Av.","Employees":20,"LastUpdate":"25/02/2010"}],' +
                 '"Development":[{"Address":"1 Sunset St.","Employees":300,"LastUpdate":"24/06/2010"}]}';
            var ObjectSix = Core.JSON.Parse(StringCompanyTwo);
            ObjectFive.Areas = ObjectSix;

            ObjectFour.CompanyTwo = ObjectFive;
            ObjectFour.CompanyThree = {};
            ObjectFour.CompanyThree.Areas = ObjectTwo;

            var ReturnCompanyTwo   = Core.JSON.Stringify(ObjectFive.Areas);
            equals(StringCompanyTwo, ReturnCompanyTwo, 'okay');
            var ResultCompare3 = Core.Data.CompareObject(ObjectFour.CompanyTwo.Areas, ObjectSix);
            equals(ResultCompare3, true, 'okay');

            var ReturnCompanyTwoAreas   = Core.JSON.Stringify(ObjectFour.CompanyTwo.Areas);
            equals(ReturnCompanyTwoAreas, StringCompanyTwo, 'okay');

            var ResultCompare4 = Core.Data.CompareObject(ObjectFour.CompanyTwo, ObjectFour.CompanyThree);
            notEqual(ResultCompare4, true, 'okay');

            var ReturnFour      = Core.JSON.Stringify(ObjectFour);
            var ObjectFourParse = Core.JSON.Parse(ReturnFour);
            var ResultCompare5  = Core.Data.CompareObject(ObjectFourParse, ObjectFour);
            equals(ResultCompare5, true, 'okay');

            /* Round 4*/
            var ObjectSeven          = {};
            ObjectSeven.one      = ObjectFour;
            ObjectSeven.two      = ObjectFourParse;
            ObjectSeven.three    = ObjectFive;
            ObjectSeven.four     = ObjectSix;
            var ReturnSeven      = Core.JSON.Stringify(ObjectSeven);
            var ObjectSevenParse = Core.JSON.Parse(ReturnSeven);
            var ResultCompare6   = Core.Data.CompareObject(ObjectSeven, ObjectSevenParse);
            equals(ResultCompare6, true, 'okay');

            ObjectSeven.five     = ObjectTwo;
            var ResultCompare7   = Core.Data.CompareObject(ObjectSevenParse, ObjectSeven);
            notEqual(ResultCompare7, true, 'okay');

        });
    };

    return Namespace;
}(Core.JSON || {}));<|endoftext|>


<commit_before>'use strict';

import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
import webpackConfig from './webpack.config.js';
import { assign } from 'lodash';
import gulp from 'gulp';
import gutil from 'gulp-util';
import manifest from 'gulp-manifest';
import shell from 'gulp-shell';
import minimist from 'minimist';
//import asar from  'asar';
import svgSprite from 'gulp-svg-sprite';
import image from 'gulp-image';
import gulpif from 'gulp-if';
import path from 'path';

const argv = minimist(process.argv.slice(2));
const isProduction = argv.release || false;

gulp.task('webpack:build', (callback) => {
  // modify some webpack config options
  var myConfig = Object.create(webpackConfig);
  myConfig.plugins = myConfig.plugins.concat(
    new webpack.DefinePlugin({
      'process.env': {
        // This has effect on the react lib size
        'NODE_ENV': JSON.stringify('production')
      }
    }),
    new webpack.optimize.UglifyJsPlugin()
  );

  // run webpack
  webpack(myConfig, (err, stats) => {
    if (err) {
      throw new gutil.PluginError('webpack:build', err);
    }
    gutil.log('[webpack:build]', stats.toString({
      colors: true
    }));
    callback();
  });
});

gulp.task('webpack-dev-server', () => {
  // modify some webpack config options
  assign(webpackConfig, {
    resolve: {
      modulesDirectories: ['node_modules'],
      root: [
        path.join(__dirname, 'src/app')
      ]
    },
    plugins: [
      new webpack.ResolverPlugin([
        new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin('package.json', ['main'])
      ]),
      new webpack.optimize.DedupePlugin(),
      new webpack.HotModuleReplacementPlugin(),
      new webpack.NoErrorsPlugin()
    ]
  });
  var myConfig = Object.create(webpackConfig);

  // Start a webpack-dev-server
  new WebpackDevServer(webpack(myConfig), {
    publicPath: '/assets/',
    contentBase: './dist',
    hot: true,
    historyApiFallback: true,
    stats: {
      colors: true
    }
  }).listen(3000, 'localhost', function(err) {
    if (err) {
      throw new gutil.PluginError('webpack-dev-server', err);
    }
    gutil.log('[webpack-dev-server]', 'http://localhost:3000');
  });
});

gulp.task('push', () => {
  gulp.src(['./push/*'])
    .pipe(gulp.dest('./dist/'));
});

gulp.task('assets', ['sounds', 'images', 'locale-data']);

gulp.task('sounds', () => {
  gulp.src(['src/assets/sound/**/*'])
    .pipe(gulp.dest('./dist/assets/sound'));
});

gulp.task('images', ['sprite', 'emoji'], () => {
  gulp.src(['src/assets/img/**/*', '!src/assets/img/svg/', '!src/assets/img/svg/**'])
    .pipe(gulpif(isProduction, image()))
    .pipe(gulp.dest('./dist/assets/img'));
});

gulp.task('sprite', () => {
  gulp.src('src/assets/img/svg/*.svg')
    .pipe(svgSprite({
      shape: {
        dimension: {
          maxWidth: 24,
          maxHeight: 24
        }
      },
      mode: {
        symbol: {
          dest: 'sprite',
          sprite: 'icons',
          scss: true
        }
      }
    }))
    .pipe(gulp.dest('./dist/assets/img'));
});

gulp.task('emoji', () => {
  gulp.src([
    './node_modules/emoji-data/sheet_apple_64.png',
    './node_modules/emoji-data/sheet_emojione_64.png',
    './node_modules/emoji-data/sheet_google_64.png',
    './node_modules/emoji-data/sheet_twitter_364.png'
  ], {base: './node_modules/emoji-data'})
    .pipe(gulpif(isProduction, image()))
    .pipe(gulp.dest('./dist/assets/img/emoji'));
});

gulp.task('html', () => {
  gulp.src(['src/index.html'])
    .pipe(gulp.dest('./dist/'));
});

gulp.task('locale-data', () => {
  gulp.src(['node_modules/intl/locale-data/json/**/*'])
    .pipe(gulp.dest('./dist/assets/locale-data'));
});

gulp.task('lib:build', shell.task(['cd ../.. && ./gradlew actor-sdk:sdk-core:core:core-js:buildPackage']));
gulp.task('lib:build:dev', shell.task(['cd ../.. && ./gradlew actor-sdk:sdk-core:core:core-js:buildPackageDev']));

gulp.task('lib', ['lib:build'], () => {
  gulp.src([
    '../../actor-sdk/sdk-core/core/core-js/build/library/actor/*',
    '../../actor-sdk/sdk-core/runtime/runtime-js/src/main/javascript/interval.js'
  ])
    .pipe(gulp.dest('./dist/actor/'));
});
gulp.task('lib:dev', ['lib:build:dev'], () => {
  gulp.src([
    '../../actor-sdk/sdk-core/core/core-js/build/library/actor/*',
    '../../actor-sdk/sdk-core/runtime/runtime-js/src/main/javascript/interval.js'
  ])
    .pipe(gulp.dest('./dist/actor/'));
});

gulp.task('manifest:prod', ['static', 'webpack:build'], () => {
  gulp.src(['./dist/**/*'])
    .pipe(manifest({
      hash: true,
      network: ['http://*', 'https://*', '*'],
      filename: 'app.appcache',
      exclude: ['assets/*.map']
    }))
    .pipe(gulp.dest('./dist/'));
});

gulp.task('electron:prepare', ['build'], () => {
  gulp.src(['dist/**/*'])
    .pipe(gulp.dest('./electron_dist/app'));
});

gulp.task('electron:app', () => {
  gulp.src(['electron/**/*'])
    .pipe(gulp.dest('./electron_dist/app'));
});

gulp.task('electron', ['electron:prepare', 'electron:app'], shell.task(['asar pack electron_dist/app electron_dist/app.asar']));

const staticTasksBase = ['html', 'assets', 'push'];
const staticTasks = staticTasksBase.concat(['lib']);
const staticTasksDev = staticTasksBase.concat(['lib:dev']);

gulp.task('static', staticTasks);
gulp.task('static:dev', staticTasksDev);

gulp.task('dev', ['static:dev', 'webpack-dev-server']);

gulp.task('build', ['static', 'webpack:build']);

gulp.task('build:gwt', ['static', 'webpack:build']);

gulp.task('dist', ['build', 'electron']);
<commit_msg>feat(web): Remove electron build<commit_after>'use strict';

import webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
import webpackConfig from './webpack.config.js';
import { assign } from 'lodash';
import gulp from 'gulp';
import gutil from 'gulp-util';
import manifest from 'gulp-manifest';
import shell from 'gulp-shell';
import minimist from 'minimist';
//import asar from  'asar';
import svgSprite from 'gulp-svg-sprite';
import image from 'gulp-image';
import gulpif from 'gulp-if';
import path from 'path';

const argv = minimist(process.argv.slice(2));
const isProduction = argv.release || false;

gulp.task('webpack:build', (callback) => {
  // modify some webpack config options
  var myConfig = Object.create(webpackConfig);
  myConfig.plugins = myConfig.plugins.concat(
    new webpack.DefinePlugin({
      'process.env': {
        // This has effect on the react lib size
        'NODE_ENV': JSON.stringify('production')
      }
    }),
    new webpack.optimize.UglifyJsPlugin()
  );

  // run webpack
  webpack(myConfig, (err, stats) => {
    if (err) {
      throw new gutil.PluginError('webpack:build', err);
    }
    gutil.log('[webpack:build]', stats.toString({
      colors: true
    }));
    callback();
  });
});

gulp.task('webpack-dev-server', () => {
  // modify some webpack config options
  assign(webpackConfig, {
    resolve: {
      modulesDirectories: ['node_modules'],
      root: [
        path.join(__dirname, 'src/app')
      ]
    },
    plugins: [
      new webpack.ResolverPlugin([
        new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin('package.json', ['main'])
      ]),
      new webpack.optimize.DedupePlugin(),
      new webpack.HotModuleReplacementPlugin(),
      new webpack.NoErrorsPlugin()
    ]
  });
  var myConfig = Object.create(webpackConfig);

  // Start a webpack-dev-server
  new WebpackDevServer(webpack(myConfig), {
    publicPath: '/assets/',
    contentBase: './dist',
    hot: true,
    historyApiFallback: true,
    stats: {
      colors: true
    }
  }).listen(3000, 'localhost', function(err) {
    if (err) {
      throw new gutil.PluginError('webpack-dev-server', err);
    }
    gutil.log('[webpack-dev-server]', 'http://localhost:3000');
  });
});

gulp.task('push', () => {
  gulp.src(['./push/*'])
    .pipe(gulp.dest('./dist/'));
});

gulp.task('assets', ['sounds', 'images', 'locale-data']);

gulp.task('sounds', () => {
  gulp.src(['src/assets/sound/**/*'])
    .pipe(gulp.dest('./dist/assets/sound'));
});

gulp.task('images', ['sprite', 'emoji'], () => {
  gulp.src(['src/assets/img/**/*', '!src/assets/img/svg/', '!src/assets/img/svg/**'])
    .pipe(gulpif(isProduction, image()))
    .pipe(gulp.dest('./dist/assets/img'));
});

gulp.task('sprite', () => {
  gulp.src('src/assets/img/svg/*.svg')
    .pipe(svgSprite({
      shape: {
        dimension: {
          maxWidth: 24,
          maxHeight: 24
        }
      },
      mode: {
        symbol: {
          dest: 'sprite',
          sprite: 'icons',
          scss: true
        }
      }
    }))
    .pipe(gulp.dest('./dist/assets/img'));
});

gulp.task('emoji', () => {
  gulp.src([
    './node_modules/emoji-data/sheet_apple_64.png',
    './node_modules/emoji-data/sheet_emojione_64.png',
    './node_modules/emoji-data/sheet_google_64.png',
    './node_modules/emoji-data/sheet_twitter_364.png'
  ], {base: './node_modules/emoji-data'})
    .pipe(gulpif(isProduction, image()))
    .pipe(gulp.dest('./dist/assets/img/emoji'));
});

gulp.task('html', () => {
  gulp.src(['src/index.html'])
    .pipe(gulp.dest('./dist/'));
});

gulp.task('locale-data', () => {
  gulp.src(['node_modules/intl/locale-data/json/**/*'])
    .pipe(gulp.dest('./dist/assets/locale-data'));
});

gulp.task('lib:build', shell.task(['cd ../.. && ./gradlew actor-sdk:sdk-core:core:core-js:buildPackage']));
gulp.task('lib:build:dev', shell.task(['cd ../.. && ./gradlew actor-sdk:sdk-core:core:core-js:buildPackageDev']));

gulp.task('lib', ['lib:build'], () => {
  gulp.src([
    '../../actor-sdk/sdk-core/core/core-js/build/library/actor/*',
    '../../actor-sdk/sdk-core/runtime/runtime-js/src/main/javascript/interval.js'
  ])
    .pipe(gulp.dest('./dist/actor/'));
});
gulp.task('lib:dev', ['lib:build:dev'], () => {
  gulp.src([
    '../../actor-sdk/sdk-core/core/core-js/build/library/actor/*',
    '../../actor-sdk/sdk-core/runtime/runtime-js/src/main/javascript/interval.js'
  ])
    .pipe(gulp.dest('./dist/actor/'));
});

gulp.task('manifest:prod', ['static', 'webpack:build'], () => {
  gulp.src(['./dist/**/*'])
    .pipe(manifest({
      hash: true,
      network: ['http://*', 'https://*', '*'],
      filename: 'app.appcache',
      exclude: ['assets/*.map']
    }))
    .pipe(gulp.dest('./dist/'));
});

const staticTasksBase = ['html', 'assets', 'push'];
const staticTasks = staticTasksBase.concat(['lib']);
const staticTasksDev = staticTasksBase.concat(['lib:dev']);

gulp.task('static', staticTasks);
gulp.task('static:dev', staticTasksDev);

gulp.task('dev', ['static:dev', 'webpack-dev-server']);

gulp.task('build', ['static', 'webpack:build']);

gulp.task('build:gwt', ['static', 'webpack:build']);

gulp.task('dist', ['build']);
<|endoftext|>


<commit_before>/*globals require: false, module: false */

'use strict';

var React = require('react');
var Col = require('react-bootstrap/lib/Col');
var Row = require('react-bootstrap/lib/Row');
var Button = require('react-bootstrap/lib/Button');
var ColumnEdit = require('./ColumnEdit');
var Sortable = require('./Sortable');
require('react-resizable/css/styles.css');
var _ = require('./underscore_ext');
var widgets = require('./columnWidgets');
var Tooltip = require('Tooltip');
var rxEventsMixin = require('./react-utils').rxEventsMixin;
var meta = require('./meta');
var VizSettings = require('./VizSettings');
require('./Columns.css'); // XXX switch to js styles
require('./YAxisLabel.css'); // XXX switch to js styles

var YAxisLabel = React.createClass({
	render: function () {
		// XXX would prefer to enforce that these keys are present & destructure
		var height = _.getIn(this.props, ['zoom', 'height']),
			index = _.getIn(this.props, ['zoom', 'index']) || 0,
			count = _.getIn(this.props, ['zoom', 'count']) || 0,
			length = _.getIn(this.props, ['samples', 'length']) || 0,
			fraction = count === length ? '' :
				// babel-eslint/issues/31
				`, showing ${ index } - ${ index + count - 1 }`, // eslint-disable-line comma-spacing
			 text = `Samples (N=${ length }) ${ fraction }`;

	return (

{text}

		);
	}
});

function zoomIn(pos, samples, zoom) {
	var {count, index} = zoom;
	var nCount = Math.max(1, Math.floor(count / 3)),
		maxIndex = samples - nCount,
		nIndex = Math.max(0, Math.min(Math.round(index + pos * count - nCount / 2), maxIndex));

	return _.merge(zoom, {count: nCount, index: nIndex});
}

function zoomOut(samples, zoom) {
	var {count, index} = zoom;
	var nCount = Math.min(samples, Math.round(count * 3)),
		maxIndex = samples - nCount,
		nIndex = Math.max(0, Math.min(Math.round(index + (count - nCount) / 2), maxIndex));

	return _.merge(zoom, {count: nCount, index: nIndex});
}

function targetPos(ev) {
	var bb = ev.target.getBoundingClientRect();
	return (ev.clientY - bb.top) / ev.target.clientHeight;
}

var Columns = React.createClass({
	// XXX pure render mixin? Check other widgets, too, esp. columns.
	mixins: [rxEventsMixin],
	componentWillMount: function () {
		this.events('tooltip', 'click', 'plotClick', 'plotDoubleClick');

		this.ev.plotClick.filter(ev => ev.shiftKey).subscribe(() => {
			let {callback, appState: {zoom, samples}} = this.props;
			callback(['zoom', zoomOut(samples.length, zoom)]);
		});

		this.ev.plotDoubleClick.subscribe(ev => {
			let {callback, appState: {samples, zoom}} = this.props;
			callback(['zoom', zoomIn(targetPos(ev), samples.length, zoom)]);
		});

		var toggle = this.ev.click.filter(ev => ev[meta.key])
			.map(() => 'toggle');

		this.tooltip = this.ev.tooltip.merge(toggle)
			// If open + user clicks, toggle freeze of display.
			.scan([null, false],
				([tt, frozen], ev) =>
					ev === 'toggle' ? [tt, tt.open && !frozen] : [ev, frozen])
			// Filter frozen events until frozen state changes.
			.distinctUntilChanged(([ev, frozen]) => frozen ? frozen : [ev, frozen])
			.map(([ev, frozen]) => _.assoc(ev, 'frozen', frozen))
			.subscribe(ev => this.setState({tooltip: ev}));
	},
	componentWillUnmount: function () { // XXX refactor into a takeUntil mixin?
		// XXX are there other streams we're leaking? What listens on this.ev.click, etc?
		this.tooltip.dispose();
	},
	getInitialState: function () {
		return {tooltip: {open: false}, openVizSettings: null};
	},
	setOrder: function (order) {
		this.props.callback(['order', order]);
	},
	onViz: function (id) {
		var dsID = _.getIn(this.props.appState, ['columns', id, 'dsID']);
		this.setState({openVizSettings: dsID});
	},
	render: function () {
		var {callback, appState} = this.props;
		// XXX maybe rename index -> indexes?
		var {data, index, zoom, columns, columnOrder, cohort, samples} = appState;
		var {openColumnEdit, openVizSettings} = this.state;
		var height = zoom.height;
		var editor = openColumnEdit ?
			<ColumnEdit
				{...this.props}
				onHide={() => this.setState({openColumnEdit: false})}
			/> : null;
		// XXX parameterize settings on column type
		var settings = openVizSettings ?
			<VizSettings
				dsID={openVizSettings}
				onRequestHide={() => this.setState({openVizSettings: null})}
				callback={callback}
				state={_.getIn(appState, ['vizSettings'])} /> : null;

		// XXX Should we use controllers/paths for accessing state data in
		// the view?
		var columnViews = _.map(columnOrder, id => widgets.column({
			ref: id,
			key: id,
			id: id,
			data: _.getIn(data, [id]),
			index: _.getIn(index, [id]),
			vizSettings: _.getIn(appState, ['vizSettings',
				_.getIn(columns, [id, 'dsID'])]),
			samples: samples,
			zoom: zoom,
			callback: callback,
			tooltip: this.ev.tooltip,
			onViz: this.onViz,
			onClick: this.ev.plotClick,
			onDoubleClick: this.ev.plotDoubleClick,
			column: _.getIn(columns, [id]),
			dataset: _.getIn(appState, ['datasets', 'datasets',
				_.getIn(columns, [id, 'dsID'])])
		}));

		return (

				<Sortable onClick={this.ev.click} setOrder={this.setOrder}>
					{columnViews}
				</Sortable>

					{cohort &&
						<Button
							onClick={() => this.setState({openColumnEdit: true})}
							className='Column-add-button'
							title='Add a column'>
							+
						</Button>}

				{editor}
				{settings}
				<Tooltip {...this.state.tooltip}/>

		);
	}
});

var Spreadsheet = React.createClass({
	render: function () {
		var {appState: {zoom, samples}} = this.props;
		return (
			<Row>
				<Col md={1}>
					<YAxisLabel
						samples={samples}
						zoom={zoom}
					/>
				</Col>
				<Col md={11}><Columns {...this.props}/></Col>
			</Row>
		);
	}
});

module.exports = Spreadsheet;
<commit_msg>Drop comment.<commit_after>/*globals require: false, module: false */

'use strict';

var React = require('react');
var Col = require('react-bootstrap/lib/Col');
var Row = require('react-bootstrap/lib/Row');
var Button = require('react-bootstrap/lib/Button');
var ColumnEdit = require('./ColumnEdit');
var Sortable = require('./Sortable');
require('react-resizable/css/styles.css');
var _ = require('./underscore_ext');
var widgets = require('./columnWidgets');
var Tooltip = require('Tooltip');
var rxEventsMixin = require('./react-utils').rxEventsMixin;
var meta = require('./meta');
var VizSettings = require('./VizSettings');
require('./Columns.css'); // XXX switch to js styles
require('./YAxisLabel.css'); // XXX switch to js styles

var YAxisLabel = React.createClass({
	render: function () {
		// XXX would prefer to enforce that these keys are present & destructure
		var height = _.getIn(this.props, ['zoom', 'height']),
			index = _.getIn(this.props, ['zoom', 'index']) || 0,
			count = _.getIn(this.props, ['zoom', 'count']) || 0,
			length = _.getIn(this.props, ['samples', 'length']) || 0,
			fraction = count === length ? '' :
				// babel-eslint/issues/31
				`, showing ${ index } - ${ index + count - 1 }`, // eslint-disable-line comma-spacing
			 text = `Samples (N=${ length }) ${ fraction }`;

	return (

{text}

		);
	}
});

function zoomIn(pos, samples, zoom) {
	var {count, index} = zoom;
	var nCount = Math.max(1, Math.floor(count / 3)),
		maxIndex = samples - nCount,
		nIndex = Math.max(0, Math.min(Math.round(index + pos * count - nCount / 2), maxIndex));

	return _.merge(zoom, {count: nCount, index: nIndex});
}

function zoomOut(samples, zoom) {
	var {count, index} = zoom;
	var nCount = Math.min(samples, Math.round(count * 3)),
		maxIndex = samples - nCount,
		nIndex = Math.max(0, Math.min(Math.round(index + (count - nCount) / 2), maxIndex));

	return _.merge(zoom, {count: nCount, index: nIndex});
}

function targetPos(ev) {
	var bb = ev.target.getBoundingClientRect();
	return (ev.clientY - bb.top) / ev.target.clientHeight;
}

var Columns = React.createClass({
	// XXX pure render mixin? Check other widgets, too, esp. columns.
	mixins: [rxEventsMixin],
	componentWillMount: function () {
		this.events('tooltip', 'click', 'plotClick', 'plotDoubleClick');

		this.ev.plotClick.filter(ev => ev.shiftKey).subscribe(() => {
			let {callback, appState: {zoom, samples}} = this.props;
			callback(['zoom', zoomOut(samples.length, zoom)]);
		});

		this.ev.plotDoubleClick.subscribe(ev => {
			let {callback, appState: {samples, zoom}} = this.props;
			callback(['zoom', zoomIn(targetPos(ev), samples.length, zoom)]);
		});

		var toggle = this.ev.click.filter(ev => ev[meta.key])
			.map(() => 'toggle');

		this.tooltip = this.ev.tooltip.merge(toggle)
			// If open + user clicks, toggle freeze of display.
			.scan([null, false],
				([tt, frozen], ev) =>
					ev === 'toggle' ? [tt, tt.open && !frozen] : [ev, frozen])
			// Filter frozen events until frozen state changes.
			.distinctUntilChanged(([ev, frozen]) => frozen ? frozen : [ev, frozen])
			.map(([ev, frozen]) => _.assoc(ev, 'frozen', frozen))
			.subscribe(ev => this.setState({tooltip: ev}));
	},
	componentWillUnmount: function () { // XXX refactor into a takeUntil mixin?
		// XXX are there other streams we're leaking? What listens on this.ev.click, etc?
		this.tooltip.dispose();
	},
	getInitialState: function () {
		return {tooltip: {open: false}, openVizSettings: null};
	},
	setOrder: function (order) {
		this.props.callback(['order', order]);
	},
	onViz: function (id) {
		var dsID = _.getIn(this.props.appState, ['columns', id, 'dsID']);
		this.setState({openVizSettings: dsID});
	},
	render: function () {
		var {callback, appState} = this.props;
		// XXX maybe rename index -> indexes?
		var {data, index, zoom, columns, columnOrder, cohort, samples} = appState;
		var {openColumnEdit, openVizSettings} = this.state;
		var height = zoom.height;
		var editor = openColumnEdit ?
			<ColumnEdit
				{...this.props}
				onHide={() => this.setState({openColumnEdit: false})}
			/> : null;
		// XXX parameterize settings on column type
		var settings = openVizSettings ?
			<VizSettings
				dsID={openVizSettings}
				onRequestHide={() => this.setState({openVizSettings: null})}
				callback={callback}
				state={_.getIn(appState, ['vizSettings'])} /> : null;

		var columnViews = _.map(columnOrder, id => widgets.column({
			ref: id,
			key: id,
			id: id,
			data: _.getIn(data, [id]),
			index: _.getIn(index, [id]),
			vizSettings: _.getIn(appState, ['vizSettings',
				_.getIn(columns, [id, 'dsID'])]),
			samples: samples,
			zoom: zoom,
			callback: callback,
			tooltip: this.ev.tooltip,
			onViz: this.onViz,
			onClick: this.ev.plotClick,
			onDoubleClick: this.ev.plotDoubleClick,
			column: _.getIn(columns, [id]),
			dataset: _.getIn(appState, ['datasets', 'datasets',
				_.getIn(columns, [id, 'dsID'])])
		}));

		return (

				<Sortable onClick={this.ev.click} setOrder={this.setOrder}>
					{columnViews}
				</Sortable>

					{cohort &&
						<Button
							onClick={() => this.setState({openColumnEdit: true})}
							className='Column-add-button'
							title='Add a column'>
							+
						</Button>}

				{editor}
				{settings}
				<Tooltip {...this.state.tooltip}/>

		);
	}
});

var Spreadsheet = React.createClass({
	render: function () {
		var {appState: {zoom, samples}} = this.props;
		return (
			<Row>
				<Col md={1}>
					<YAxisLabel
						samples={samples}
						zoom={zoom}
					/>
				</Col>
				<Col md={11}><Columns {...this.props}/></Col>
			</Row>
		);
	}
});

module.exports = Spreadsheet;
<|endoftext|>


<commit_before>/*
  This file is for contributors to OpenDota to add their DOTA friend codes (AKA SteamId3).

  Currently this will cause the /players/:id endpoint to return is_contributor = true for your profile
*/

module.exports = {
  88367253: {}, // howardchung
  102344608: {}, // albertcui
  9977887: {}, // gu3st
  115042342: {}, // builder-247
  197868209: {}, // TOG
  55268262: {}, // Proyoyo
  103637655: {}, // samantha
};
<commit_msg>Add c0rdawg to the contributors file (#1765)<commit_after>/*
  This file is for contributors to OpenDota to add their DOTA friend codes (AKA SteamId3).

  Currently this will cause the /players/:id endpoint to return is_contributor = true for your profile
*/

module.exports = {
  88367253: {}, // howardchung
  102344608: {}, // albertcui
  9977887: {}, // gu3st
  115042342: {}, // builder-247
  197868209: {}, // TOG
  55268262: {}, // Proyoyo
  1900588: {}, // c0rdawg
  103637655: {}, // samantha
};
<|endoftext|>


<commit_before>/*global angular*/
angular.module('hljs', [])

.provider('hljsService', function () {
  var _hljsOptions = {};

  return {
    setOptions: function (options) {
      angular.extend(_hljsOptions, options);
    },
    getOptions: function () {
      return angular.copy(_hljsOptions);
    },
    $get: ['$window', function ($window) {
      ($window.hljs.configure || angular.noop)(_hljsOptions);
      return $window.hljs;
    }]
  };
})

.factory('hljsCache', [
         '$cacheFactory',
function ($cacheFactory) {
  return $cacheFactory('hljsCache');
}])

.controller('HljsCtrl', [
                  'hljsCache', 'hljsService',
function HljsCtrl (hljsCache,   hljsService) {
  var ctrl = this;

  var _elm = null,
      _lang = null,
      _code = null,
      _hlCb = null;

  ctrl.init = function (codeElm) {
    _elm = codeElm;
  };

  ctrl.setLanguage = function (lang) {
    _lang = lang;

    if (_code) {
      ctrl.highlight(_code);
    }
  };

  ctrl.highlightCallback = function (cb) {
    _hlCb = cb;
  };

  ctrl.highlight = function (code) {
    if (!_elm) {
      return;
    }

    var res, cacheKey;

    _code = code;

    if (_lang) {
      // language specified
      cacheKey = ctrl._cacheKey(_lang, _code);
      res = hljsCache.get(cacheKey);

      if (!res) {
        res = hljsService.highlight(_lang, hljsService.fixMarkup(_code), true);
        hljsCache.put(cacheKey, res);
      }
    }
    else {
      // language auto-detect
      cacheKey = ctrl._cacheKey(_code);
      res = hljsCache.get(cacheKey);

      if (!res) {
        res = hljsService.highlightAuto(hljsService.fixMarkup(_code));
        hljsCache.put(cacheKey, res);
      }
    }

    _elm.html(res.value);
    // language as class on the  tag
    _elm.addClass(res.language);

    if (_hlCb !== null && angular.isFunction(_hlCb)) {
      _hlCb();
    }
  };

  ctrl.clear = function () {
    if (!_elm) {
      return;
    }
    _code = null;
    _elm.text('');
  };

  ctrl.release = function () {
    _elm = null;
  };

  ctrl._cacheKey = function () {
    var args = Array.prototype.slice.call(arguments),
        glue = "!angular-highlightjs!";
    return args.join(glue);
  };
}])

.directive('hljs', [function () {
  return {
    restrict: 'EA',
    controller: 'HljsCtrl',
    compile: function(tElm, tAttrs, transclude) {
      // get static code
      // strip the starting "new line" character
      var staticCode = tElm[0].textContent.replace(/^(\r\n|\r|\n)/m, '');

      // put template
      tElm.html('

');

      return function postLink(scope, iElm, iAttrs, ctrl) {
        ctrl.init(iElm.find('code'));

        if (iAttrs.onhighlight) {
          ctrl.highlightCallback(function () {
            scope.$eval(iAttrs.onhighlight);
          });
        }

        if (staticCode) {
          ctrl.highlight(staticCode);
        }

        scope.$on('$destroy', function () {
          ctrl.release();
        });
      };
    }
  };
}])

.directive('language', [function () {
  return {
    require: 'hljs',
    restrict: 'A',
    link: function (scope, iElm, iAttrs, ctrl) {
      iAttrs.$observe('language', function (lang) {
        if (angular.isDefined(lang)) {
          ctrl.setLanguage(lang);
        }
      });
    }
  };
}])

.directive('source', ['$compile', function ($compile) {
  return {
    require: 'hljs',
    restrict: 'A',
    link: function(scope, iElm, iAttrs, ctrl) {

      scope.$watch(iAttrs.source, function (newCode, oldCode) {
        if (newCode) {
          ctrl.highlight(newCode);
          // compile the new DOM and link it to the current scope.
          // NOTE: we only compile .childNodes so that
          // we don't get into infinite loop compiling ourselves
          $compile(iElm.find('code').contents())(scope);
        }
        else {
          ctrl.clear();
        }
      });
    }
  };
}])

.directive('include', [
         '$http', '$templateCache', '$q',
function ($http,   $templateCache,   $q) {
  return {
    require: 'hljs',
    restrict: 'A',
    compile: function(tElm, tAttrs, transclude) {
      var srcExpr = tAttrs.include;

      return function postLink(scope, iElm, iAttrs, ctrl) {
        var changeCounter = 0;

        scope.$watch(srcExpr, function (src) {
          var thisChangeId = ++changeCounter;

          if (src && angular.isString(src)) {
            var templateCachePromise, dfd;

            templateCachePromise = $templateCache.get(src);
            if (!templateCachePromise) {
              dfd = $q.defer();
              $http.get(src, {
                cache: $templateCache,
                transformResponse: function(data, headersGetter) {
                  // Return the raw string, so $http doesn't parse it
                  // if it's json.
                  return data;
                }
              }).success(function (code) {
                if (thisChangeId !== changeCounter) {
                  return;
                }
                dfd.resolve(code);
              }).error(function() {
                if (thisChangeId === changeCounter) {
                  ctrl.clear();
                }
                dfd.resolve();
              });
              templateCachePromise = dfd.promise;
            }

            $q.when(templateCachePromise)
            .then(function (code) {
              if (!code) {
                return;
              }

              // $templateCache from $http
              if (angular.isArray(code)) {
                // 1.1.5
                code = code[1];
              }
              else if (angular.isObject(code)) {
                // 1.0.7
                code = code.data;
              }

              code = code.replace(/^(\r\n|\r|\n)/m, '');
              ctrl.highlight(code);
            });
          }
          else {
            ctrl.clear();
          }
        });
      };
    }
  };
}]);
<commit_msg>Introduce `compile` support.<commit_after>/*global angular*/
angular.module('hljs', [])

.provider('hljsService', function () {
  var _hljsOptions = {};

  return {
    setOptions: function (options) {
      angular.extend(_hljsOptions, options);
    },
    getOptions: function () {
      return angular.copy(_hljsOptions);
    },
    $get: ['$window', function ($window) {
      ($window.hljs.configure || angular.noop)(_hljsOptions);
      return $window.hljs;
    }]
  };
})

.factory('hljsCache', [
         '$cacheFactory',
function ($cacheFactory) {
  return $cacheFactory('hljsCache');
}])

.controller('HljsCtrl', [
                  'hljsCache', 'hljsService',
function HljsCtrl (hljsCache,   hljsService) {
  var ctrl = this;

  var _elm = null,
      _lang = null,
      _code = null,
      _hlCb = null;

  ctrl.init = function (codeElm) {
    _elm = codeElm;
  };

  ctrl.setLanguage = function (lang) {
    _lang = lang;

    if (_code) {
      ctrl.highlight(_code);
    }
  };

  ctrl.highlightCallback = function (cb) {
    _hlCb = cb;
  };

  ctrl.highlight = function (code) {
    if (!_elm) {
      return;
    }

    var res, cacheKey;

    _code = code;

    if (_lang) {
      // language specified
      cacheKey = ctrl._cacheKey(_lang, _code);
      res = hljsCache.get(cacheKey);

      if (!res) {
        res = hljsService.highlight(_lang, hljsService.fixMarkup(_code), true);
        hljsCache.put(cacheKey, res);
      }
    }
    else {
      // language auto-detect
      cacheKey = ctrl._cacheKey(_code);
      res = hljsCache.get(cacheKey);

      if (!res) {
        res = hljsService.highlightAuto(hljsService.fixMarkup(_code));
        hljsCache.put(cacheKey, res);
      }
    }

    _elm.html(res.value);
    // language as class on the  tag
    _elm.addClass(res.language);

    if (_hlCb !== null && angular.isFunction(_hlCb)) {
      _hlCb();
    }
  };

  ctrl.clear = function () {
    if (!_elm) {
      return;
    }
    _code = null;
    _elm.text('');
  };

  ctrl.release = function () {
    _elm = null;
  };

  ctrl._cacheKey = function () {
    var args = Array.prototype.slice.call(arguments),
        glue = "!angular-highlightjs!";
    return args.join(glue);
  };
}])

.directive('hljs', ['$compile', '$parse', function ($compile, $parse) {
  return {
    restrict: 'EA',
    controller: 'HljsCtrl',
    compile: function(tElm, tAttrs, transclude) {
      // get static code
      // strip the starting "new line" character
      var staticCode = tElm[0].innerHTML.replace(/^(\r\n|\r|\n)/m, '');

      // put template
      tElm.html('

');

      return function postLink(scope, iElm, iAttrs, ctrl) {
        var compileCheck;

        if (angular.isDefined(iAttrs.compile)) {
          compileCheck = $parse(iAttrs.compile);
        }

        ctrl.init(iElm.find('code'));

        if (iAttrs.onhighlight) {
          ctrl.highlightCallback(function () {
            scope.$eval(iAttrs.onhighlight);
          });
        }

        if (staticCode) {
          ctrl.highlight(staticCode);

          // Check if the highlight result needs to be compiled
          if (compileCheck && compileCheck(scope)) {
            // compile the new DOM and link it to the current scope.
            // NOTE: we only compile .childNodes so that
            // we don't get into infinite loop compiling ourselves
            $compile(iElm.find('code').contents())(scope);
          }
        }

        scope.$on('$destroy', function () {
          ctrl.release();
        });
      };
    }
  };
}])

.directive('language', [function () {
  return {
    require: 'hljs',
    restrict: 'A',
    link: function (scope, iElm, iAttrs, ctrl) {
      iAttrs.$observe('language', function (lang) {
        if (angular.isDefined(lang)) {
          ctrl.setLanguage(lang);
        }
      });
    }
  };
}])

.directive('source', ['$compile', '$parse', function ($compile, $parse) {
  return {
    require: 'hljs',
    restrict: 'A',
    link: function(scope, iElm, iAttrs, ctrl) {
      var compileCheck;

      if (angular.isDefined(iAttrs.compile)) {
        compileCheck = $parse(iAttrs.compile);
      }

      scope.$watch(iAttrs.source, function (newCode, oldCode) {
        if (newCode) {
          ctrl.highlight(newCode);

          // Check if the highlight result needs to be compiled
          if (compileCheck && compileCheck(scope)) {
            // compile the new DOM and link it to the current scope.
            // NOTE: we only compile .childNodes so that
            // we don't get into infinite loop compiling ourselves
            $compile(iElm.find('code').contents())(scope);
          }
        }
        else {
          ctrl.clear();
        }
      });
    }
  };
}])

.directive('include', [
         '$http', '$templateCache', '$q', '$compile', '$parse',
function ($http,   $templateCache,   $q,   $compile,   $parse) {
  return {
    require: 'hljs',
    restrict: 'A',
    compile: function(tElm, tAttrs, transclude) {
      var srcExpr = tAttrs.include;

      return function postLink(scope, iElm, iAttrs, ctrl) {
        var changeCounter = 0, compileCheck;

        if (angular.isDefined(iAttrs.compile)) {
          compileCheck = $parse(iAttrs.compile);
        }

        scope.$watch(srcExpr, function (src) {
          var thisChangeId = ++changeCounter;

          if (src && angular.isString(src)) {
            var templateCachePromise, dfd;

            templateCachePromise = $templateCache.get(src);
            if (!templateCachePromise) {
              dfd = $q.defer();
              $http.get(src, {
                cache: $templateCache,
                transformResponse: function(data, headersGetter) {
                  // Return the raw string, so $http doesn't parse it
                  // if it's json.
                  return data;
                }
              }).success(function (code) {
                if (thisChangeId !== changeCounter) {
                  return;
                }
                dfd.resolve(code);
              }).error(function() {
                if (thisChangeId === changeCounter) {
                  ctrl.clear();
                }
                dfd.resolve();
              });
              templateCachePromise = dfd.promise;
            }

            $q.when(templateCachePromise)
            .then(function (code) {
              if (!code) {
                return;
              }

              // $templateCache from $http
              if (angular.isArray(code)) {
                // 1.1.5
                code = code[1];
              }
              else if (angular.isObject(code)) {
                // 1.0.7
                code = code.data;
              }

              code = code.replace(/^(\r\n|\r|\n)/m, '');
              ctrl.highlight(code);

              // Check if the highlight result needs to be compiled
              if (compileCheck && compileCheck(scope)) {
                // compile the new DOM and link it to the current scope.
                // NOTE: we only compile .childNodes so that
                // we don't get into infinite loop compiling ourselves
                $compile(iElm.find('code').contents())(scope);
              }
            });
          }
          else {
            ctrl.clear();
          }
        });
      };
    }
  };
}]);
<|endoftext|>


<commit_before>/**
 * Main Controller for processMaker v2.x
 * @date Jul 17, 2011
 * @author Erik Amaru Ortiz <erik@colosa.com>
 */

var Main = function() {
  return {
    /** properties */
    panels : new Array(),
    configuration: {},
    viewport : null,
    systemInfoWindow : null,

    /** init method */
    init : function() {

      Ext.QuickTips.init();
      Ext.form.Field.prototype.msgTarget = 'side';

      this.configureComponents();
      this.buildComponents();

      this.viewport = new Ext.Viewport({
        layout: 'border',
        items: [this.panels]
      });

      Ext.getCmp('eastPanel').hide();
      Ext.getCmp('westPanel').hide();
      Ext.getCmp('southPanel').hide();

      Ext.getCmp('northPanel').update(Ext.fly('header-content').dom.innerHTML);
      Ext.getCmp('centerPanel').ownerCt.doLayout();

      Ext.get('options-tool').on('click', function(eventObj, elRef) {
        var conn = new Ext.data.Connection();
        eventObj.stopEvent();
        if (!this.ctxMenu) {
          Main.buildUserMenu(this);
        }
        this.ctxMenu.show(elRef);
      });

      if (typeof flyNotify != 'undefined') {
        Ext.msgBoxSlider.msgTopCenter(flyNotify.type, flyNotify.title, flyNotify.text, flyNotify.time);
      }
    }
  }
}();

Main.configureComponents = function()
{
  this.configuration.eastPanel = {
    id:'eastPanel',
    region: 'east',
    width: 200,
    height: 500,
    minSize: 175,
    maxSize: 400,
    split: true,
    collapsible: true,
    items: []
  };

  this.configuration.centerPanel = {
    id:'centerPanel',
    region: 'center',
    layout: 'fit',
    width: 200,
    margins: '0 0 0 0' // top right botom left
  };

  this.configuration.centerPanel.items = new Array();
  this.configuration.centerPanel.items.push({
    xtype:"tabpanel",
    id: 'mainTabPanel',
    defaultType:"iframepanel",
    activeTab: activeTab != '' ? activeTab : 0
  });

  this.configuration.westPanel = {
    id:'westPanel',
    title: '',
    region: 'west',
    width: 200,
    split: true,
    collapsible: true,
    items: []
  };

  this.configuration.northPanel = {
    id:'northPanel',
    region: 'north',
    height: 50,
    //applyTo: 'panel-header',
    margins: '0 0 0 0', // top right botom left
    items: []
  };

  this.configuration.southPanel = {
    id:'southPanel',
    region: 'south',
    height: 68,
    margins: '0 0 0 0', // top right botom left
    items: []
  };

  this.configuration.userMenu = {}
  this.configuration.userMenu.items = new Array();

  if (switchInterface) {
    this.configuration.userMenu.items.push({
      text : _("ID_SWITCH_INTERFACE"),
      iconCls: 'ss_sprite ss_arrow_switch',
      handler: function() {
        var url = '../uxs/home';

        if (typeof parent != 'undefined') {
          parent.location.href = url;
        }
        else {
          location.href = url;
        }
      }
    });
  }

  this.configuration.userMenu.items.push({
    text : _("ID_VIEW_EDIT_PROFILE"),
    icon: '/images/profile-picture.png',
    handler: function() {
      Main._addTab('profile', 'Profile', 'users/usersInit');
    }
  });

  /*this.configuration.userMenu.items.push({
    id:'skinMenu',
    text : _("ID_SKINS"),
    icon: '/images/icon-pmskins.png'
  });*/

  if (showSystemInfo) {
    this.configuration.userMenu.items.push({
      text : _('ID_SYSTEM_INFO'),
      icon: '/images/sys-info-icon.png',
      handler: systemInfo
    });
  }

  this.configuration.userMenu.items.push({
    text : _('ID_LOGOUT'),
    icon: '/images/logout.gif',
    handler: function() {
      location.href = 'main/login';
    }
  });
};

Main.buildComponents = function()
{
  var centerTabPanelItems = new Array();
  for (var i=0; i<meta.menu.length; i++) {
    menuItem = meta.menu[i];
    target = menuItem.target;

    if (activeTab != '') {
      if (i == activeTab) {
        target = menuItem.target + '?' + urlAddGetParams;
      }
    }
    else {
      target = menuItem.target + '?' + urlAddGetParams;
    }

    centerTabPanelItems.push({
      id: 'pm-option-' + menuItem.idName.toLowerCase(),
      title: menuItem.label.toUpperCase(),
      iconCls: 'x-pm-tabmenu ' + menuItem.elementclass,
      defaultSrc: target,
      frameConfig:{
        name : 'pm-frame-' + menuItem.idName.toLowerCase(),
        id   : 'pm-frame-' + menuItem.idName.toLowerCase()
      },
      loadMask:{msg: _('ID_LOADING_GRID')}
    });
  }

  this.configuration.centerPanel.items[0].items = centerTabPanelItems;

  this.panels.push(new Ext.Panel(this.configuration.eastPanel));
  this.panels.push(new Ext.Panel(this.configuration.centerPanel));
  this.panels.push(new Ext.Panel(this.configuration.westPanel));
  this.panels.push(new Ext.Panel(this.configuration.southPanel));
  this.panels.push(new Ext.Panel(this.configuration.northPanel));
};

Main.buildUserMenu = function(obj)
{
  /*var skinMenu = new Ext.ux.menu.StoreMenu({
    url:'setup/skin_Ajax.php',
    baseParams: {
      action: 'skinList',
      type: 'menu'
    }
  });

  this.configuration.userMenu.items[1].menu = skinMenu;*/
  obj.ctxMenu = new Ext.menu.Menu(this.configuration.userMenu);
};

Main._addTab = function(id, title, src)
{
  var TabPanel = Ext.getCmp('mainTabPanel');
  tabId = 'pm-maintab-' + id;
  var tab = TabPanel.getItem(tabId);

  if (!tab) {
    TabPanel.add({
      id: tabId,
      title: title.toUpperCase(),
      iconCls: 'x-pm-tabmenu x-pm-' + id,
      defaultSrc: src,
      frameConfig:{
        name : 'pm-frame-' + tabId.toLowerCase(),
        id   : 'pm-frame-' + tabId.toLowerCase()
      },
      loadMask:{msg: _('ID_LOADING_GRID')},
      closable:true
    }).show();

    TabPanel.doLayout();
    tab = Ext.getCmp(tabId);
  }

  TabPanel.setActiveTab(tabId);
};

var systemInfo = function()
{
  if(Main.systemInfoWindow == null){
    var sysInfPanel = PMExt.createInfoPanel('main/getSystemInfo');

    Main.systemInfoWindow = new Ext.Window({
      layout:'fit',
      width:500,
      height:430,
      closeAction:'hide',
      items: [sysInfPanel]
    });
  }
  Main.systemInfoWindow.show(this);
}

function changeSkin(newSkin, currentSkin)
{
  currentLocation = top.location.href;
  newLocation = currentLocation.replace("/"+currentSkin+"/","/"+newSkin+"/");
  top.location.href = newLocation;
}

Ext.onReady(Main.init, Main, true);

<commit_msg>BUG 9636 Error en los tabs del skin UXModern SOLVED<commit_after>/**
 * Main Controller for processMaker v2.x
 * @date Jul 17, 2011
 * @author Erik Amaru Ortiz <erik@colosa.com>
 */

var Main = function() {
  return {
    /** properties */
    panels : new Array(),
    configuration: {},
    viewport : null,
    systemInfoWindow : null,

    /** init method */
    init : function() {

      Ext.QuickTips.init();
      Ext.form.Field.prototype.msgTarget = 'side';

      this.configureComponents();
      this.buildComponents();

      this.viewport = new Ext.Viewport({
        layout: 'border',
        items: [this.panels]
      });

      Ext.getCmp('eastPanel').hide();
      Ext.getCmp('westPanel').hide();
      Ext.getCmp('southPanel').hide();

      Ext.getCmp('northPanel').update(Ext.fly('header-content').dom.innerHTML);
      Ext.getCmp('centerPanel').ownerCt.doLayout();

      Ext.get('options-tool').on('click', function(eventObj, elRef) {
        var conn = new Ext.data.Connection();
        eventObj.stopEvent();
        if (!this.ctxMenu) {
          Main.buildUserMenu(this);
        }
        this.ctxMenu.show(elRef);
      });

      if (typeof flyNotify != 'undefined') {
        Ext.msgBoxSlider.msgTopCenter(flyNotify.type, flyNotify.title, flyNotify.text, flyNotify.time);
      }
    }
  }
}();

Main.configureComponents = function()
{
  this.configuration.eastPanel = {
    id:'eastPanel',
    region: 'east',
    width: 200,
    height: 500,
    minSize: 175,
    maxSize: 400,
    split: true,
    collapsible: true,
    items: []
  };

  this.configuration.centerPanel = {
    id:'centerPanel',
    region: 'center',
    layout: 'fit',
    width: 200,
    margins: '0 0 0 0' // top right botom left
  };

  this.configuration.centerPanel.items = new Array();
  this.configuration.centerPanel.items.push({
    xtype:"tabpanel",
    id: 'mainTabPanel',
    defaultType:"iframepanel",
    enableTabScroll: true,
    activeTab: activeTab != '' ? activeTab : 0
  });

  this.configuration.westPanel = {
    id:'westPanel',
    title: '',
    region: 'west',
    width: 200,
    split: true,
    collapsible: true,
    items: []
  };

  this.configuration.northPanel = {
    id:'northPanel',
    region: 'north',
    height: 50,
    //applyTo: 'panel-header',
    margins: '0 0 0 0', // top right botom left
    items: []
  };

  this.configuration.southPanel = {
    id:'southPanel',
    region: 'south',
    height: 68,
    margins: '0 0 0 0', // top right botom left
    items: []
  };

  this.configuration.userMenu = {}
  this.configuration.userMenu.items = new Array();

  if (switchInterface) {
    this.configuration.userMenu.items.push({
      text : _("ID_SWITCH_INTERFACE"),
      iconCls: 'ss_sprite ss_arrow_switch',
      handler: function() {
        var url = '../uxs/home';

        if (typeof parent != 'undefined') {
          parent.location.href = url;
        }
        else {
          location.href = url;
        }
      }
    });
  }

  this.configuration.userMenu.items.push({
    text : _("ID_VIEW_EDIT_PROFILE"),
    icon: '/images/profile-picture.png',
    handler: function() {
      Main._addTab('profile', 'Profile', 'users/usersInit');
    }
  });

  /*this.configuration.userMenu.items.push({
    id:'skinMenu',
    text : _("ID_SKINS"),
    icon: '/images/icon-pmskins.png'
  });*/

  if (showSystemInfo) {
    this.configuration.userMenu.items.push({
      text : _('ID_SYSTEM_INFO'),
      icon: '/images/sys-info-icon.png',
      handler: systemInfo
    });
  }

  this.configuration.userMenu.items.push({
    text : _('ID_LOGOUT'),
    icon: '/images/logout.gif',
    handler: function() {
      location.href = 'main/login';
    }
  });
};

Main.buildComponents = function()
{
  var centerTabPanelItems = new Array();
  for (var i=0; i<meta.menu.length; i++) {
    menuItem = meta.menu[i];
    target = menuItem.target;

    if (activeTab != '') {
      if (i == activeTab) {
        target = menuItem.target + '?' + urlAddGetParams;
      }
    }
    else {
      target = menuItem.target + '?' + urlAddGetParams;
    }

    centerTabPanelItems.push({
      id: 'pm-option-' + menuItem.idName.toLowerCase(),
      title: menuItem.label.toUpperCase(),
      iconCls: 'x-pm-tabmenu ' + menuItem.elementclass,
      defaultSrc: target,
      frameConfig:{
        name : 'pm-frame-' + menuItem.idName.toLowerCase(),
        id   : 'pm-frame-' + menuItem.idName.toLowerCase()
      },
      loadMask:{msg: _('ID_LOADING_GRID')}
    });
  }

  this.configuration.centerPanel.items[0].items = centerTabPanelItems;

  this.panels.push(new Ext.Panel(this.configuration.eastPanel));
  this.panels.push(new Ext.Panel(this.configuration.centerPanel));
  this.panels.push(new Ext.Panel(this.configuration.westPanel));
  this.panels.push(new Ext.Panel(this.configuration.southPanel));
  this.panels.push(new Ext.Panel(this.configuration.northPanel));
};

Main.buildUserMenu = function(obj)
{
  /*var skinMenu = new Ext.ux.menu.StoreMenu({
    url:'setup/skin_Ajax.php',
    baseParams: {
      action: 'skinList',
      type: 'menu'
    }
  });

  this.configuration.userMenu.items[1].menu = skinMenu;*/
  obj.ctxMenu = new Ext.menu.Menu(this.configuration.userMenu);
};

Main._addTab = function(id, title, src)
{
  var TabPanel = Ext.getCmp('mainTabPanel');
  tabId = 'pm-maintab-' + id;
  var tab = TabPanel.getItem(tabId);

  if (!tab) {
    TabPanel.add({
      id: tabId,
      title: title.toUpperCase(),
      iconCls: 'x-pm-tabmenu x-pm-' + id,
      defaultSrc: src,
      frameConfig:{
        name : 'pm-frame-' + tabId.toLowerCase(),
        id   : 'pm-frame-' + tabId.toLowerCase()
      },
      loadMask:{msg: _('ID_LOADING_GRID')},
      closable:true
    }).show();

    TabPanel.doLayout();
    tab = Ext.getCmp(tabId);
  }

  TabPanel.setActiveTab(tabId);
};

var systemInfo = function()
{
  if(Main.systemInfoWindow == null){
    var sysInfPanel = PMExt.createInfoPanel('main/getSystemInfo');

    Main.systemInfoWindow = new Ext.Window({
      layout:'fit',
      width:500,
      height:430,
      closeAction:'hide',
      items: [sysInfPanel]
    });
  }
  Main.systemInfoWindow.show(this);
}

function changeSkin(newSkin, currentSkin)
{
  currentLocation = top.location.href;
  newLocation = currentLocation.replace("/"+currentSkin+"/","/"+newSkin+"/");
  top.location.href = newLocation;
}

Ext.onReady(Main.init, Main, true);

<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import Box from '@material-ui/core/Box';
import Tab from '@material-ui/core/Tab';
import Tabs from '@material-ui/core/Tabs';
import { makeStyles } from '@material-ui/core/styles';
import TeamTasksProject from './TeamTasksProject';
import SettingsHeader from './SettingsHeader';
import CreateTeamTask from './CreateTeamTask';
import BlankState from '../layout/BlankState';
import { backgroundMain, ContentColumn } from '../../styles/js/shared';

const useStyles = makeStyles(theme => ({
  root: {
    flexGrow: 1,
    backgroundColor: `${backgroundMain}`,
    display: 'flex',
    minHeight: 224,
    marginBottom: 50,
  },
  tabs: {
    backgroundColor: `${backgroundMain}`,
    marginRight: theme.spacing(5),
    marginTop: theme.spacing(2),
  },
  tabContent: {
    width: '100%',
  },
}));

function TeamMetadataRender({ team, about }) {
  const [showTab, setShowTab] = React.useState('items');
  const classes = useStyles();
  const handleTabChange = (e, value) => {
    setShowTab(value);
  };
  const associatedType = showTab === 'items' ? 'ProjectMedia' : 'Source';
  const teamMetadata = team.team_tasks.edges.map(task => task.node)
    .filter(t => t.associated_type === associatedType);

  return (
    <Box display="flex" justifyContent="center" className="team-metadata">
      <Tabs
        indicatorColor="primary"
        scrollButtons="auto"
        textColor="primary"
        orientation="vertical"
        variant="scrollable"
        value={showTab}
        onChange={handleTabChange}
        className={classes.tabs}
      >
        <Tab
          fullWidth
          label="Items"
          value="items"
          className="metadata-tab__items"
        />
        <Tab
          label="Sources"
          value="sources"
          className="metadata-tab__source"
        />
      </Tabs>
      <ContentColumn large>
        <SettingsHeader
          title={
            associatedType === 'ProjectMedia' ?
              <FormattedMessage
                id="teamMetadataRender.itemTitle"
                defaultMessage="Item annotation form"
                description="Title for annotation settings screen. Refers to annotation applied to items generally, not any specific item or items."
              /> :
              <FormattedMessage
                id="teamMetadataRender.sourceTitle"
                defaultMessage="Source annotation form"
                description="Title for annotation settings screen. Refers to annotation applied to sources generally, not any specific source or sources."
              />
          }
          subtitle={
            associatedType === 'ProjectMedia' ?
              <FormattedMessage
                id="teamMetadataRender.metadataItemSubtitle"
                defaultMessage="Create dynamic forms to annotate items by adding fields."
                description="Subtitle for annotation settings screen applied to Items"
              /> :
              <FormattedMessage
                id="teamMetadataRender.metadataSourceSubtitle"
                defaultMessage="Create dynamic forms to annotate sources by adding fields."
                description="Subtitle for annotation settings screen applied to Sources"
              />
          }
          helpUrl="https://help.checkmedia.org/en/articles/4346772-metadata"
          actionButton={
            <CreateTeamTask fieldset="metadata" associatedType={associatedType} team={team} />
          }
        />

            { teamMetadata.length ?
              <TeamTasksProject
                fieldset="metadata"
                project={{ teamTasks: teamMetadata }}
                team={team}
                about={about}
              /> :
              <BlankState>
                <FormattedMessage
                  id="teamMetadataRender.blankMetadata"
                  defaultMessage="No metadata fields"
                  description="Text for empty metadata"
                />
              </BlankState>
            }

      </ContentColumn>
    </Box>
  );
}

TeamMetadataRender.propTypes = {
  team: PropTypes.object.isRequired, // GraphQL "Team" object
  about: PropTypes.object.isRequired,
};

export default TeamMetadataRender;
<commit_msg>Ticket CHECK-955: Adding KB link to source annotation form<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import Box from '@material-ui/core/Box';
import Tab from '@material-ui/core/Tab';
import Tabs from '@material-ui/core/Tabs';
import { makeStyles } from '@material-ui/core/styles';
import TeamTasksProject from './TeamTasksProject';
import SettingsHeader from './SettingsHeader';
import CreateTeamTask from './CreateTeamTask';
import BlankState from '../layout/BlankState';
import { backgroundMain, ContentColumn } from '../../styles/js/shared';

const useStyles = makeStyles(theme => ({
  root: {
    flexGrow: 1,
    backgroundColor: `${backgroundMain}`,
    display: 'flex',
    minHeight: 224,
    marginBottom: 50,
  },
  tabs: {
    backgroundColor: `${backgroundMain}`,
    marginRight: theme.spacing(5),
    marginTop: theme.spacing(2),
  },
  tabContent: {
    width: '100%',
  },
}));

function TeamMetadataRender({ team, about }) {
  const [showTab, setShowTab] = React.useState('items');
  const classes = useStyles();
  const handleTabChange = (e, value) => {
    setShowTab(value);
  };
  const associatedType = showTab === 'items' ? 'ProjectMedia' : 'Source';
  const teamMetadata = team.team_tasks.edges.map(task => task.node)
    .filter(t => t.associated_type === associatedType);

  return (
    <Box display="flex" justifyContent="center" className="team-metadata">
      <Tabs
        indicatorColor="primary"
        scrollButtons="auto"
        textColor="primary"
        orientation="vertical"
        variant="scrollable"
        value={showTab}
        onChange={handleTabChange}
        className={classes.tabs}
      >
        <Tab
          fullWidth
          label="Items"
          value="items"
          className="metadata-tab__items"
        />
        <Tab
          label="Sources"
          value="sources"
          className="metadata-tab__source"
        />
      </Tabs>
      <ContentColumn large>
        <SettingsHeader
          title={
            associatedType === 'ProjectMedia' ?
              <FormattedMessage
                id="teamMetadataRender.itemTitle"
                defaultMessage="Item annotation form"
                description="Title for annotation settings screen. Refers to annotation applied to items generally, not any specific item or items."
              /> :
              <FormattedMessage
                id="teamMetadataRender.sourceTitle"
                defaultMessage="Source annotation form"
                description="Title for annotation settings screen. Refers to annotation applied to sources generally, not any specific source or sources."
              />
          }
          subtitle={
            associatedType === 'ProjectMedia' ?
              <FormattedMessage
                id="teamMetadataRender.metadataItemSubtitle"
                defaultMessage="Create dynamic forms to annotate items by adding fields."
                description="Subtitle for annotation settings screen applied to Items"
              /> :
              <FormattedMessage
                id="teamMetadataRender.metadataSourceSubtitle"
                defaultMessage="Create dynamic forms to annotate sources by adding fields."
                description="Subtitle for annotation settings screen applied to Sources"
              />
          }
          helpUrl={
            associatedType === 'ProjectMedia' ?
              'https://help.checkmedia.org/en/articles/4346772-metadata' :
              'https://help.checkmedia.org/en/articles/4837896-sources#h_bb2bd143fd'
          }
          actionButton={
            <CreateTeamTask fieldset="metadata" associatedType={associatedType} team={team} />
          }
        />

            { teamMetadata.length ?
              <TeamTasksProject
                fieldset="metadata"
                project={{ teamTasks: teamMetadata }}
                team={team}
                about={about}
              /> :
              <BlankState>
                <FormattedMessage
                  id="teamMetadataRender.blankMetadata"
                  defaultMessage="No metadata fields"
                  description="Text for empty metadata"
                />
              </BlankState>
            }

      </ContentColumn>
    </Box>
  );
}

TeamMetadataRender.propTypes = {
  team: PropTypes.object.isRequired, // GraphQL "Team" object
  about: PropTypes.object.isRequired,
};

export default TeamMetadataRender;
<|endoftext|>