Utilisateur:Fabimaru/inserttemplate.js

De Wikivoyage

Note : après avoir publié vos modifications, il se peut que vous deviez forcer le rechargement complet du cache de votre navigateur pour voir les changements.

  • Firefox / Safari : maintenez la touche Maj (Shift) en cliquant sur le bouton Actualiser ou appuyez sur Ctrl + F5 ou Ctrl + R (⌘ + R sur un Mac).
  • Google Chrome : appuyez sur Ctrl + Maj + R (⌘ + Shift + R sur un Mac).
  • Internet Explorer / Edge : maintenez la touche Ctrl en cliquant sur le bouton Actualiser ou pressez Ctrl + F5.
  • Opera : appuyez sur Ctrl + F5.
function liste_region_en_fr() {
  var textbox = $('#wpTextbox1');
  var alltext = textbox.val();
  var selstart = textbox[0].selectionStart;
  var selend = textbox[0].selectionEnd;
  var before = alltext.substr(0, selstart);
  var selected = alltext.substr(selstart, selend - selstart);
  var after = alltext.substr(selend);
  var text = selected;
  var expr = /region([0-9]+)([^=]+)/m;
  var newtext = '';
  for (; ; ) {
    var res = expr.exec(text);
    if (res === null) {
      newtext += text;
      break;
    }
    var repl = res[2];
    if (repl == 'name') {
      repl = 'nom';
    } else if (repl == 'color') {
      repl = 'couleur';
    } else if (repl == 'items') {
      repl = 'elements';
    }
    newtext = newtext + text.substr(0, res.index) + repl + 'region' + res[1];
    text = text.substr(res.index + res[0].length);
  }
  textbox.val(before+newtext+after);
}

function addToolbar() {
	var myhtml = "<div style='overflow: hidden; clear: both;float: left;width: 100%' id='my-tbl-links'>";
	myhtml += '<style>#my-tbl-links a{margin-left: 1em;margin-rigth: 1em}</style>';
	myhtml += '<a href="#">Heure</a><a href="#">Minutes</a><a href="#">Horaire</a><a href="#">Mois</a>';
	myhtml += '<a href="#">¥</a><a href="#">€</a><a href="#">Nombre</a><a href="#">Guillemets</a><a href="#">Guillemets-ital.</a>';
	myhtml += '<a href="#">Lang=ja</a><a href="#">Regionlist_enfr</a><a href="#">Unité</a>';
	myhtml += '<a href="#">Marqueur</a>';
	myhtml += '<a href="#">Traduit de</a>';
	myhtml += '<a href="#">CoordPrecision</a>';
	myhtml += '<a href="#">Listing</a>';
	myhtml += '<a href="#">Climat</a>';
	myhtml += '<a href="#">Route</a>';
	myhtml += "</div>";
	
	$(myhtml).insertAfter($(".wikiEditor-ui-toolbar .sections"));
	$("#my-tbl-links a").click(function(event){
	  event.preventDefault();
	  var sel = $(this).text();
	  var text = null;
	  // test type of action
	  if (sel=="Regionlist_enfr") {
	  	liste_region_en_fr();
	  	return;
	  }  else if (sel=="CoordPrecision") {
	  	coordPrecision();
	  } else if (sel=="Heure") {
	    text = ["{{Heure|", "}}"];
	  } else if (sel=="Minutes") {
	    text = ["{{Heure||", "}}"];
	  } else if (sel=="Mois") {
	    text = ["{{Mois|", "}}"];
	  } else if (sel=="Horaire") {
	    text = ["{{Horaire|||h1||h2|", "}}"];
	  } else if (sel=="Nombre") {
	    text = ["{{formatnum:", "}}"];
	  } else if (sel=="Guillemets") {
	    text = ["« ", " »"];
	  } else if (sel=="Guillemets-ital.") {
	    text = ["« ''", "'' »"];
	  } else if (sel=="¥") {
	    text = ["{{Prix|", "|¥}}"];
	  } else if (sel=="€") {
	    text = ["{{Prix|", "|€}}"];
	  } else if (sel=="Lang=ja") {
	    text = ["{{Lang|ja|", "}}"];
	  } else if (sel=="Unité") {
	    text = ["{{Unité|", "}}"];
	  } else if (sel=="Traduit de") {
	    text = ["{{Traduit de|en|NOMANGLAIS|JOUR/MOIS/2017|NUMEROVERSION}}", ""];
	  } else if (sel=="Marqueur") {
	    text = ["{{Marqueur|nom=", "|type=|latitude=|longitude=|url=|wikipédia=}}"];
	  } else if (sel=="Listing") {
	  	text = [];
	  } else if (sel=="Climat") {
	  	text = [];
	  } else if (sel=="Route") {
	  	text = [];
	  }
	  if (text===null) {
	    return;
	  }
	  var textbox = $("#wpTextbox1");
	  var alltext = textbox.val();
	  var selstart = textbox[0].selectionStart;
	  var selend = textbox[0].selectionEnd;
	  var before = alltext.substr(0, selstart);
	  var selected = alltext.substr(selstart, selend-selstart);
	  var after = alltext.substr(selend);
	  if (sel=="Unité") {
	    var parsed = selected.match(/([0-9-.]+)(.*)/);
	    if (parsed===null) {
	    	selected = selected + "|";
	    } else {
	    	var unit = parsed[2];
	    	if (unit=="km") {
	    		unit = "km|abr=kilomètre";
	    	} else if (unit=="km²") {
	    		unit = "km²|abr=kilomètre carré";
	    	} else if (unit=="m") {
	    		unit = "m|abr=mètre";
	    	} else if (unit=="m²") {
	    		unit = "m²|abr=mètre carré";
	    	} else if (unit=="kg") {
	    		unit = "kg|abr=kilogramme";
	    	} else if (unit=="g") {
	    		unit = "g|abr=gramme";
	    	}
	    	selected = parsed[1] + "|" + unit;
	    }
	  }
	  if (sel=="Listing") {
	  	textbox.val(before+translateListing(selected)+after);
	  } else if (sel=="Climat") {
	  	textbox.val(before+translateClimat(selected)+after);
	  } else if (sel=="Route") {
	  	textbox.val(before+translateRoute(selected)+after);
	  } else {
	  	textbox.val(before+text[0]+selected+text[1]+after);
	  }
	});
}

$(document).ready(function () {
	window.setTimeout(addToolbar, 1000);
	addSourceLink("Diff", "Diff", 1);
	addSourceLink("Permalink", "Permalink", 1);
	addSourceLink("Diff", "Diff2", 2);
});

function translateClimat(text) {
  let expr = /\|\s*(.*?)(high|low|precip)?\s*=(.*)/g;
  return text.replace(expr, function (all, param1, type, value) {
    value = value ? value.trim()  : '';
    if (param1 == 'description') {
      return '| lien source = ' + value;
    }
    if (!type) {
      return "| " + param1 + ' = ' + value;
    }
    let mappingType = {
      'low': 'tmin',
      'high': 'tmax',
      'precip': 'prec'
    };
    if (type in mappingType) {
      type = mappingType[type];
    }
    let mappingMonth = {
      'feb': 'fev',
      'apr': 'avr',
      'may': 'mai',
      'jun': 'jui',
      'aug': 'aou'
    };
    let month = (param1 in mappingMonth) ? mappingMonth[param1] : param1;
    return "| " + type + '-' + month + ' = ' + value;
  });
}

function translateRoute(text) {
	var repl = [
	  ["=W", "=O"],
	  ["=END", "=FIN"],
	  ["File:", "Fichier:"],
	  ["into ", "rejoint "],
	  ["Tokyo/", ""],
	  ["Chuo\\|", "Chūō (Tokyo)|"],
	  ["East\\|", "Est de Tokyo|"],
	  ["Tokyo Haneda Airport\\|", "Tokyo#Aéroport de Haneda", "i"],
	  ["Rtarrow", "flèche d", "i"],
	  ["lfarrow", "flèche g", "i"],
	];
	
	for(var cnt in repl) {
	  var tmp = repl[cnt];
	  var flags = "g";
	  if (tmp[2]) {
	    flags += tmp[2];
	  }
	  repl[cnt] = [new RegExp(tmp[0], flags), tmp[1]];
	}
	var new_text = text;
	for(var cnt in repl) {
	  new_text = new_text.replace(repl[cnt][0], repl[cnt][1]);
	}
	return new_text;
}

function addSourceLink(special, label, cnt) {
	var target = $("#ResumeDeluxe");
	target.append(" • ");
	var tmp = $("<a href='#'>"+label+" 'En'</a>").appendTo(target);
	
	tmp.click(function(event){
	  event.preventDefault();
	  var target = $("#wpSummary");
	  var text = target.val()+" depuis la version anglophone ";
	  if (cnt==1) {
	  	text += "([[:en:Special:"+special+"/VERSION|source]])";
	  } else if(cnt==2) {
	  	text += "(versions [[:en:Special:"+special+"/VERSION|source]] à [[:en:Special:"+special+"/VERSION|source]])";
	  }
	  target.val(text);
	});
}

var coordPrecision = function () {
  function radians(deg) {
    return deg * Math.PI / 180;
  }
  function distance(lon1, lat1, lon2, lat2) {
    var radius = 6371; // km
    var dlat = radians(lat2 - lat1);
    var dlon = radians(lon2 - lon1);
    var a = Math.sin(dlat / 2) * Math.sin(dlat / 2) + Math.cos(radians(lat1)) * Math.cos(radians(lat2)) * Math.sin(dlon / 2) * Math.sin(dlon / 2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    var d = radius * c;
    return d;
  }
  function distance_text(lon1, lat1, lon2, lat2) {
    var d = distance(lon1, lat1, lon2, lat2);
    return (d > 1) ? (d + 'km')  : (d * 1000 + 'm');
  }
  function distance_l(lon, lat) {
    return distance(lon, lat, lon + 1, lat);
  }
  function distance_n(lon, lat, n) {
    var threshold = Math.pow(10, - n);
    return distance(lon, lat, lon + threshold, lat + threshold) * 1000;
  }
  function round1(num) {
    if (num - Math.floor(num) === 0) {
      return num;
    }
    var sign = Math.sign(num);
    var positive = num / sign;
    var nb_dec = ('' + num).split('.') [1].length;
    var mult = Math.pow(10, nb_dec - 1);
    return Math.round(num * mult) / mult;
  }
  function round1_(num) {
    if (num - Math.floor(num) === 0) {
      return num;
    }
    var nb_dec = ('' + num).split('.') [1].length;
    return parseFloat(num.toFixed(nb_dec - 1));
  }
  function precision(lorig_lon, orig_lat, lon, lat) {
    var lon1 = round1(lon);
    var lat1 = round1(lat);
    console.log("precision", lon, lon1, lat, lat1);
    var p_lon = lon==lon1 ? null : new Point(lon1, lat, distance(lorig_lon, orig_lat, lon1, lat));
    var p_lat = lat==lat1 ? null : new Point(lon, lat1, distance(lorig_lon, orig_lat, lon, lat1));
    return [p_lon, p_lat];
  }
  function Point(lon, lat, prec) {
    this.lon = lon;
    this.lat = lat;
    this.prec = prec;
    this.label = '';
  }
  Point.prototype.prec_text = function () {
    if (this.prec > 1) {
      return this.prec.toFixed(1) + 'km';
    } else if (this.prec > 0.001) {
      return (this.prec * 1000).toFixed(1) + 'm';
    } else {
      return (this.prec * 100000).toFixed(1) + 'cm';
    }
  };
  function process(orig_lon, orig_lat) {
    var lat = orig_lat;
    var lon = orig_lon;
    var all_choices = [];
    for (var cnt=0; cnt<30;++cnt) {
      var res = precision(orig_lon, orig_lat, lon, lat);
      var res1 = res[0];
      var res2 = res[1];
      var choice = null;
      //console.log(res1, res2);
      if (res1 === null) {
        if (res2 !== null) {
          choice = res2;
        }
      } else if (res2 === null) {
        choice = res1;
      } else {
        choice = res1.prec < res2.prec ? res1 : res2;
      }
      if (choice === null) {
        break;
      }
      all_choices.push(choice);
      console.log('longitude=' + choice.lon + ' | latitude=' + choice.lat + ' => ' + choice.prec_text());
      lon = choice.lon;
      lat = choice.lat;
    }
    // display

    var limits = [
      ['shop',
      0.001],
      [
        'city',
        0.25
      ],
      [
        'big city',
        3
      ]
    ];
    var prev = null;
    for (cnt in all_choices) {
      var choice2 = all_choices[cnt];
      console.log(limits);
      if (limits.length > 0 && choice2.prec > limits[0][1]) {
        if (prev === null) {
          choice2.label = limits[0][0];
        } else {
          prev.label = limits[0][0];
        }
        limits.shift();
      }
      prev = choice2;
    }
    // display result

    $('#coordPrecision').remove();
    $('.editOptions').before('<div id=\'coordPrecision\'><ul/></div>');
    var out = $('#coordPrecision ul');
    for (cnt in all_choices) {
      var choice3 = all_choices[cnt];
      var txt = 'latitude=' + choice3.lat + ' | longitude=' + choice3.lon + ' => ' + choice3.prec_text();
      if (choice3.label !== '') {
        txt += ' (' + choice3.label + ')';
      }
      out.append('<li>' + txt + '</li>');
    }
  }
  function processGUI() {
    var textbox = $('#wpTextbox1');
    var alltext = textbox.val();
    var selstart = textbox[0].selectionStart;
    var selend = textbox[0].selectionEnd;
    var selected = alltext.substr(selstart, selend - selstart);
    var res = /latitude *= *(-?[0-9.]+)/.exec(selected);
    if (res != null) {
      var lat = res[1];
      var res = /longitude *= *(-?[0-9.]+)/.exec(selected);
      if (res != null) {
        process(parseFloat(res[1]), parseFloat(lat));
      }
    }
  }
  return processGUI;
}();