applocale.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. /*
  2. Application Locale Module
  3. author: tobychui
  4. This module translate the current web application page
  5. to the desired language specific by the browser.
  6. Example Usage:
  7. if (applocale){
  8. //Applocale found. Do localization
  9. applocale.init("../locale/file_explorer.json", function(){
  10. applocale.translate();
  11. //Do other init things on the page
  12. }, function(){
  13. //Optional: called instead when the locale file cannot be loaded
  14. });
  15. }
  16. */
  17. /*
  18. A page that styles its own fonts (e.g. System Settings) can set
  19. window.applocaleSkipFontFamily = true before loading its locale: the
  20. language's preferred font family is then not written inline onto every
  21. element, and the page applies it itself.
  22. */
  23. function applocaleInjectsFont(){
  24. return typeof window === "undefined" || window.applocaleSkipFontFamily !== true;
  25. }
  26. /*
  27. A page that hosts other pages' fragments (System Settings) sets
  28. window.applocaleKeepWindowTitle = true once its own title is in place, so
  29. a fragment's locale file does not rename the float window.
  30. */
  31. function applocaleSetsWindowTitle(){
  32. return typeof window === "undefined" || window.applocaleKeepWindowTitle !== true;
  33. }
  34. /*
  35. A language may use a font from the system font library (System Settings >
  36. System Fonts). The server then adds to its locale block fontCSS, the style
  37. sheet declaring that font, relative to the locale file. It is linked once
  38. per document; reload=true reloads it after the font choice changed.
  39. */
  40. function applocaleLinkFonts(localeFile, block, reload){
  41. if (typeof document === "undefined" || !block || !block.fontCSS){
  42. return;
  43. }
  44. var href;
  45. try {
  46. href = new URL(block.fontCSS, new URL(localeFile, document.baseURI)).href;
  47. } catch (e) {
  48. return;
  49. }
  50. var link = document.getElementById("applocale-fonts");
  51. if (!link){
  52. link = document.createElement("link");
  53. link.id = "applocale-fonts";
  54. link.rel = "stylesheet";
  55. document.head.appendChild(link);
  56. } else if (!reload){
  57. return;
  58. }
  59. link.href = reload ? href + (href.indexOf("?") >= 0 ? "&" : "?") + "v=" + Date.now() : href;
  60. }
  61. /*
  62. The system font (systemFont in the locale block, picked in System Fonts)
  63. applies to the whole page through CSS rather than inline styles, so text
  64. an app creates later gets it too:
  65. - every font-family rule of the page's style sheets that asks for a
  66. general UI font (below) gets the system font in front of its own list,
  67. with the same selector, so it wins by coming later;
  68. - the page root and form controls without a font of their own follow it.
  69. Rules naming any other font (monospace, icon fonts, an app's own web
  70. fonts or var()) are the app's choice and stay as they are. Style sheets
  71. added later are handled when they load.
  72. */
  73. var APPLOCALE_UI_FONTS = [
  74. "sans-serif", "system-ui", "-apple-system", "blinkmacsystemfont", "segoe ui", "helvetica neue",
  75. "helvetica", "arial", "lato", "roboto", "ubuntu", "cantarell", "tahoma", "verdana", "sf pro text",
  76. "noto sans", "open sans", "arial unicode ms", "microsoft jhenghei", "microsoft jhenghei ui",
  77. "microsoft yahei", "microsoft yahei ui", "simhei", "apple ligothic medium", "stheiti", "stxihei",
  78. "pingfang tc", "pingfang hk", "pingfang sc", "pingfangsc-medium", "hiragino sans",
  79. "hiragino kaku gothic pro", "meiryo", "meiryo ui", "yu gothic", "yu gothic ui",
  80. "malgun gothic", "apple sd gothic neo", "nanum gothic"
  81. ];
  82. var applocaleSystemFontState = null;
  83. function applocaleNamesUIFont(fontFamily){
  84. var first = String(fontFamily).split(",")[0].trim().replace(/^["']|["']$/g, "").toLowerCase();
  85. return APPLOCALE_UI_FONTS.indexOf(first) >= 0;
  86. }
  87. // applocaleFontOverrides returns the override rules for a list of CSS rules
  88. function applocaleFontOverrides(rules, family){
  89. var out = "";
  90. for (var i = 0; i < rules.length; i++){
  91. var rule = rules[i];
  92. if (typeof CSSStyleRule !== "undefined" && rule instanceof CSSStyleRule){
  93. var value = rule.style.getPropertyValue("font-family");
  94. if (value && applocaleNamesUIFont(value)){
  95. var important = rule.style.getPropertyPriority("font-family") ? " !important" : "";
  96. out += rule.selectorText + "{font-family:" + family + ", " + value + important + "}\n";
  97. }
  98. } else if (typeof CSSMediaRule !== "undefined" && rule instanceof CSSMediaRule){
  99. var media = applocaleFontOverrides(rule.cssRules, family);
  100. if (media) out += "@media " + rule.conditionText + "{\n" + media + "}\n";
  101. } else if (typeof CSSSupportsRule !== "undefined" && rule instanceof CSSSupportsRule){
  102. var supports = applocaleFontOverrides(rule.cssRules, family);
  103. if (supports) out += "@supports " + rule.conditionText + "{\n" + supports + "}\n";
  104. }
  105. }
  106. return out;
  107. }
  108. // applocaleRefreshSystemFont rebuilds the override style sheet, keeping it last
  109. function applocaleRefreshSystemFont(){
  110. var state = applocaleSystemFontState;
  111. if (!state){
  112. return;
  113. }
  114. var css = ":where(html){font-family:" + state.stack + "}\n" +
  115. ":where(button, input, select, textarea){font-family:inherit}\n";
  116. for (var i = 0; i < document.styleSheets.length; i++){
  117. var sheet = document.styleSheets[i];
  118. if (sheet.ownerNode === state.style){
  119. continue;
  120. }
  121. var cached = state.done.get(sheet);
  122. if (cached === undefined){
  123. try {
  124. cached = applocaleFontOverrides(sheet.cssRules, state.family);
  125. } catch (e) {
  126. cached = ""; //another origin, or not loaded yet (it is redone on load)
  127. }
  128. if (sheet.cssRules && sheet.cssRules.length > 0){
  129. state.done.set(sheet, cached);
  130. }
  131. }
  132. css += cached;
  133. }
  134. if (state.style.textContent !== css){
  135. state.style.textContent = css;
  136. }
  137. var parent = document.body || document.head;
  138. if (parent && parent.lastChild !== state.style){
  139. parent.appendChild(state.style);
  140. }
  141. }
  142. function applocaleUseSystemFont(block){
  143. if (typeof document === "undefined" || !block || !block.systemFont || !applocaleInjectsFont()){
  144. return false;
  145. }
  146. var family = '"' + String(block.systemFont).replace(/["\\]/g, "") + '"';
  147. var state = applocaleSystemFontState;
  148. if (state && state.family === family){
  149. return true;
  150. }
  151. if (!state){
  152. var style = document.createElement("style");
  153. style.id = "applocale-system-font";
  154. state = applocaleSystemFontState = { style: style, done: new WeakMap() };
  155. var timer = null;
  156. var schedule = function(){
  157. clearTimeout(timer);
  158. timer = setTimeout(applocaleRefreshSystemFont, 30);
  159. };
  160. //Style sheets added later: rescan once they are in (links: once loaded)
  161. new MutationObserver(function(records){
  162. records.forEach(function(r){
  163. r.addedNodes.forEach(function(node){
  164. if (node === style || node.nodeType !== 1){
  165. return;
  166. }
  167. var sheets = (node.matches && node.matches("style, link[rel~=stylesheet]")) ? [node] : (node.querySelectorAll ? node.querySelectorAll("style, link[rel~=stylesheet]") : []);
  168. Array.prototype.forEach.call(sheets, function(s){
  169. if (s.tagName === "LINK"){
  170. s.addEventListener("load", schedule);
  171. }
  172. schedule();
  173. });
  174. });
  175. });
  176. }).observe(document.documentElement, { childList: true, subtree: true });
  177. Array.prototype.forEach.call(document.querySelectorAll("link[rel~=stylesheet]"), function(link){
  178. link.addEventListener("load", schedule);
  179. });
  180. }
  181. state.family = family;
  182. state.stack = block.fontFamily || family;
  183. state.done = new WeakMap();
  184. applocaleRefreshSystemFont();
  185. return true;
  186. }
  187. function NewAppLocale(){
  188. return {
  189. lang: (localStorage.getItem('global_language') == null || localStorage.getItem('global_language') == "default" ? navigator.language : localStorage.getItem('global_language')).toLowerCase(),
  190. localeFile: "",
  191. localData: {},
  192. init: function(localeFile, callback = undefined, onError = undefined) {
  193. this.localeFile = localeFile;
  194. let targetApplocaleObject = this;
  195. $.ajax({
  196. dataType: "json",
  197. url: localeFile,
  198. error: function() {
  199. //Locale file missing or invalid. Let the page start with its built-in strings
  200. if (onError != undefined) {
  201. onError();
  202. }
  203. },
  204. success: function(data) {
  205. targetApplocaleObject.localData = data;
  206. if (data && data.keys) {
  207. applocaleLinkFonts(localeFile, data.keys[targetApplocaleObject.lang]);
  208. }
  209. if (callback != undefined) {
  210. callback(data);
  211. }
  212. if (applocaleSetsWindowTitle() && data.keys[targetApplocaleObject.lang] != undefined && data.keys[targetApplocaleObject.lang].fwtitle != undefined && data.keys[targetApplocaleObject.lang].fwtitle != "" && ao_module_virtualDesktop) {
  213. //Update the floatwindow title as well
  214. ao_module_setWindowTitle(data.keys[targetApplocaleObject.lang].fwtitle);
  215. }
  216. if (data.keys && applocaleUseSystemFont(data.keys[targetApplocaleObject.lang])) {
  217. //A system font: applied through CSS (applocaleUseSystemFont), not inline
  218. } else if (applocaleInjectsFont() && data.keys[targetApplocaleObject.lang] != undefined && data.keys[targetApplocaleObject.lang].fontFamily != undefined){
  219. //This language has a prefered font family. Inject it
  220. $("h1, h2, h3, p, span, div, a, button").css({
  221. "font-family":data.keys[targetApplocaleObject.lang].fontFamily
  222. });
  223. console.log("[Applocale] Updating font family to: ", data.keys[targetApplocaleObject.lang].fontFamily)
  224. }
  225. }
  226. });
  227. },
  228. translate: function(targetLang = "") {
  229. var targetLang = targetLang || this.lang;
  230. //Check if the given locale exists
  231. if (this.localData == undefined || this.localData.keys === undefined || this.localData.keys[targetLang] == undefined) {
  232. console.log("[Applocale] This language is not supported. Using default")
  233. return
  234. }
  235. //Update the page content to fit the localization
  236. let hasTitleLocale = (this.localData.keys[targetLang].titles !== undefined);
  237. let hasStringLocale = (this.localData.keys[targetLang].strings !== undefined);
  238. let hasPlaceHolderLocale = (this.localData.keys[targetLang].placeholder !== undefined);
  239. let localizedDataset = this.localData.keys[targetLang];
  240. $("*").each(function() {
  241. if ($(this).attr("title") != undefined && hasTitleLocale) {
  242. let targetString = localizedDataset.titles[$(this).attr("title")];
  243. if (targetString != undefined) {
  244. $(this).attr("title", targetString);
  245. }
  246. }
  247. if ($(this).attr("locale") != undefined && hasStringLocale) {
  248. let targetString = localizedDataset.strings[$(this).attr("locale")];
  249. if (targetString != undefined) {
  250. $(this).html(targetString);
  251. }
  252. }
  253. if ($(this).attr("placeholder") != undefined && hasPlaceHolderLocale) {
  254. let targetString = localizedDataset.placeholder[$(this).attr("placeholder")];
  255. if (targetString != undefined) {
  256. $(this).attr("placeholder", targetString);
  257. }
  258. }
  259. })
  260. if (applocaleInjectsFont() && this.localData.keys[this.lang] != undefined && this.localData.keys[this.lang].fontFamily != undefined && !this.localData.keys[this.lang].systemFont){
  261. //This language has a prefered font family. Inject it
  262. $("h1, h2, h3, h4, h5, p, span, div, a").css({
  263. "font-family":this.localData.keys[this.lang].fontFamily
  264. });
  265. }
  266. },
  267. getString: function(key, original, type = "strings") {
  268. var targetLang = this.lang;
  269. if (this.localData.keys === undefined || this.localData.keys[targetLang] == undefined) {
  270. return original;
  271. }
  272. let targetString = this.localData.keys[targetLang].strings[key];
  273. if (targetString != undefined) {
  274. return targetString
  275. } else {
  276. return original
  277. }
  278. },
  279. applyFontStyle: function(target){
  280. $(target).css({
  281. "font-family":applocale.localData.keys[applocale.lang].fontFamily
  282. })
  283. }
  284. }
  285. }
  286. if (applocale == undefined){
  287. //Only allow once instance of global applocale obj
  288. var applocale = NewAppLocale();
  289. }