language.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. function lang_init(obj,target){
  2. if (obj == null) {
  3. obj = $(document);
  4. } else {
  5. obj = $(obj);
  6. }
  7. $(target).empty();
  8. let langSelect = new Set();
  9. $("[lang]", obj).each(function(){
  10. if(langSelect.has($(this).attr("lang"))){ return true; }
  11. $(target).append("<span class=\"lang-select-item\" data-lang="+$(this).attr("lang")+">"+countryCodeToUTF8Flag($(this).attr("lang"))+"</span>");
  12. langSelect.add($(this).attr("lang"));
  13. });
  14. if(langSelect.size <= 1){
  15. $(target).hide();
  16. return;
  17. }
  18. $(target).show();
  19. displayLang($("html").attr("lang"), obj);
  20. $(".lang-select-item").click(function(){
  21. $("html").attr("lang", $(this).data("lang"));
  22. let lang = $("html").attr("lang");
  23. displayLang(lang);
  24. });
  25. }
  26. function displayLang(lang, obj){
  27. if(obj == null) obj = $(document);
  28. let elementsWithLangAttr = new Set();
  29. let elementIdsLangTrue = new Set();
  30. $("[lang]").each(function(){
  31. if($(this).is("html")){
  32. return true;
  33. }
  34. elementsWithLangAttr.add($(this).attr("id"));
  35. if($(this).attr("lang") != lang){
  36. $(this).hide();
  37. }else{
  38. $(this).show();
  39. elementIdsLangTrue.add($(this).attr("id"));
  40. }
  41. });
  42. let elemWithLangAttrArr = Array.from(elementsWithLangAttr);
  43. let elemIdsLangFalse = elemWithLangAttrArr.filter(x => !elementIdsLangTrue.has(x));
  44. elemIdsLangFalse.forEach(function(x){
  45. $("#"+x).first().show();
  46. });
  47. }
  48. function countryCodeToUTF8Flag(code){
  49. let charCodeA = "A".charCodeAt(0);
  50. let utf8CountryIndicatorA = 127462;
  51. let langCode = code;
  52. let langFlagMap = new Map([["en", "gb"]]);
  53. if(langFlagMap.has(code.toLowerCase())){
  54. langCode = langFlagMap.get(code);
  55. }
  56. const utf8CountryIndicator = function(letter) {return (letter.toUpperCase().charCodeAt(0) - charCodeA) + utf8CountryIndicatorA;}
  57. let firstIndicator = utf8CountryIndicator(langCode.charAt(0));
  58. let secondIndicator = utf8CountryIndicator(langCode.charAt(1));
  59. return "&#" + firstIndicator + ";&#" + secondIndicator + ";";
  60. }
  61. function fitTextToDiv(divTextElem, divFitToHeight, divFitToWidth){
  62. let measureDiv = $('<div/>').text(divTextElem.text()).css("font-size", divTextElem.css("font-size"));
  63. console.log($(this));
  64. divTextElem.css("font-size", parseInt(divTextElem.css("font-size"))*divFitToWidth/divTextElem.width());
  65. if(divTextElem.height() > divFitToHeight){
  66. divTextElem.css("font-size", parseInt(divTextElem.css("font-size"))*divFitToHeight/divTextElem.height());
  67. }
  68. }