ardublockly_lang.js 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. /**
  2. * @license Licensed under the Apache License, Version 2.0 (the "License"):
  3. * http://www.apache.org/licenses/LICENSE-2.0
  4. *
  5. * @fileoverview Functions related to language and localisation.
  6. */
  7. 'use strict';
  8. /** Create a namespace for the application. */
  9. var Ardublockly = Ardublockly || {};
  10. /** Lookup for names of supported languages. Keys in ISO 639 format. */
  11. Ardublockly.LANGUAGE_NAME = {
  12. 'en': 'English',
  13. 'zh-hant': '繁体中文',
  14. 'zh-hans': '简体中文'
  15. };
  16. /**
  17. * Selected language, default English.
  18. * @type {string}
  19. */
  20. Ardublockly.LANG = 'en';
  21. /**
  22. * We keep a local copy of the default language in case translations cannot
  23. * be found in the injected language file.
  24. * @type {Object}
  25. */
  26. Ardublockly.DEFAULT_LANG_TEXT = {};
  27. /** Initialize the page language. */
  28. Ardublockly.initLanguage = function () {
  29. // Save the current default language ID to check if it has been changed
  30. var defaultLang = Ardublockly.LANG;
  31. // Check server settings and url language, url gets priority
  32. Ardublockly.LANG = Ardublockly.getUrlLanguage() ||
  33. Ardublockly.getLanguageSetting() || Ardublockly.LANG;
  34. //if (defaultLang !== Ardublockly.LANG) {
  35. Ardublockly.injectLanguageJsSources(Ardublockly.LANG);
  36. Ardublockly.duplicateDefaultLang();
  37. Ardublockly.updateLanguageText();
  38. //}
  39. };
  40. /**
  41. * Get the language previously set by the user from the server settings.
  42. * @return {string} Language saved in the server settings.
  43. */
  44. Ardublockly.getLanguageSetting = function () {
  45. //TODO: Server feature still to be implemented, for now return default
  46. return null;
  47. };
  48. /**
  49. * Get the language selected from the URL, format '?lang=en'.
  50. * @return {string} Selected language.
  51. */
  52. Ardublockly.getUrlLanguage = function () {
  53. var langKey = 'lang';
  54. var val = location.search.match(new RegExp('[?&]' + langKey + '=([^&]+)'));
  55. var language = val ? decodeURIComponent(val[1].replace(/\+/g, '%20')) : '';
  56. if (Ardublockly.LANGUAGE_NAME[language] == null) { language = 'en'; }
  57. return language;
  58. };
  59. /**
  60. * Because new languages are injected by overwriting Ardublockly.LOCALISED_TEXT
  61. * we keep a local copy of the default language (included in the html header) so
  62. * that we can still retrieve these strings if the translation cannot be found.
  63. */
  64. Ardublockly.duplicateDefaultLang = function () {
  65. for (var textId in Ardublockly.LOCALISED_TEXT) {
  66. Ardublockly.DEFAULT_LANG_TEXT[textId] = Ardublockly.LOCALISED_TEXT[textId];
  67. }
  68. };
  69. /** Updates the page text strings with the new language. */
  70. Ardublockly.updateLanguageText = function () {
  71. for (var textId in Ardublockly.LOCALISED_TEXT) {
  72. var textStrings = document.getElementsByClassName('translatable_' + textId);
  73. for (var i = 0; i < textStrings.length; i++) {
  74. textStrings[i].innerHTML = Ardublockly.getLocalStr(textId);
  75. }
  76. }
  77. };
  78. /**
  79. * Injects the language JavaScript files into the html head element.
  80. * @param {string} langKey Dictionary key for the language to inject, must also
  81. * be JS file name.
  82. */
  83. Ardublockly.injectLanguageJsSources = function (langKey) {
  84. var head = document.getElementsByTagName('head')[0];
  85. // Retrieve and inject Ardublockly translations synchronously
  86. var appLangJsLoad = document.createElement('script');
  87. var request = ArdublocklyServer.createAjaxRequest();
  88. var appLangJdPath = 'msg/' + langKey + '.js';
  89. try {
  90. request.open('GET', appLangJdPath, false);
  91. request.send('');
  92. appLangJsLoad.text = request.responseText;
  93. } catch (e) {
  94. // Display an alert to indicate we cannot load languages
  95. Ardublockly.alertMessage(
  96. Ardublockly.getLocalStr('noServerTitle'),
  97. Ardublockly.getLocalStr('noServerNoLangBody'),
  98. false);
  99. // But still asynchronous lazy load so at least some text gets translated
  100. appLangJsLoad.src = appLangJdPath;
  101. }
  102. head.appendChild(appLangJsLoad);
  103. // Retrieve and inject Blockly translations asynchronously
  104. var blocklyLangJsLoad = document.createElement('script');
  105. blocklyLangJsLoad.src = 'blockly/msg/js/' + langKey + '.js';
  106. head.appendChild(blocklyLangJsLoad);
  107. };
  108. /** Saves the blocks and reloads with a different language. */
  109. Ardublockly.changeLanguage = function () {
  110. // Store the blocks for the duration of the reload only
  111. // Ardublockly.saveSessionStorageBlocks();
  112. var languageMenu = document.getElementById('language');
  113. var newLang = encodeURIComponent(
  114. languageMenu.options[languageMenu.selectedIndex].value);
  115. var search = window.location.search;
  116. if (search.length <= 1) {
  117. search = '?lang=' + newLang;
  118. } else if (search.match(/[?&]lang=[^&]*/)) {
  119. search = search.replace(/([?&]lang=)[^&]*/, '$1' + newLang);
  120. } else {
  121. search = search.replace(/\?/, '?lang=' + newLang + '&');
  122. }
  123. window.location = window.location.protocol + '//' +
  124. window.location.host + window.location.pathname + search;
  125. };
  126. /**
  127. * Finds and returns the requests string in the localised language.
  128. * If the translation is not returned, it fetches the original language string.
  129. * @param {string} stringId
  130. * @return {!string} The localised, original, or an empty string.
  131. */
  132. Ardublockly.getLocalStr = function (stringId) {
  133. var text = Ardublockly.LOCALISED_TEXT[stringId];
  134. if (!text) {
  135. console.log('Localised text string ID "' + stringId + '" does not exists!');
  136. }
  137. return text || Ardublockly.DEFAULT_LANG_TEXT[stringId] || '';
  138. };