GlobalizationProxy.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. /*
  2. *
  3. * Licensed to the Apache Software Foundation (ASF) under one
  4. * or more contributor license agreements. See the NOTICE file
  5. * distributed with this work for additional information
  6. * regarding copyright ownership. The ASF licenses this file
  7. * to you under the Apache License, Version 2.0 (the
  8. * "License"); you may not use this file except in compliance
  9. * with the License. You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing,
  14. * software distributed under the License is distributed on an
  15. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16. * KIND, either express or implied. See the License for the
  17. * specific language governing permissions and limitations
  18. * under the License.
  19. *
  20. */
  21. var GlobalizationError = require('./GlobalizationError');
  22. var l10n_loaded = new Event('l10n_loaded');
  23. var l10n_ready = new Event('l10n_ready');
  24. var is_l10n_ready = false;
  25. document.addEventListener('l10n_loaded', function() {
  26. console.log('DEBUG: L10n loaded');
  27. navigator.mozL10n.ready(function() {
  28. console.log('DEBUG: L10n ready');
  29. is_l10n_ready = true;
  30. document.dispatchEvent(l10n_ready);
  31. });
  32. });
  33. function callIfL10nReady(callback) {
  34. if (is_l10n_ready) {
  35. return callback();
  36. }
  37. document.addEventListener('l10n_ready', callback);
  38. }
  39. function loadFile(elementName, attributes, callback) {
  40. var e = document.createElement(elementName);
  41. for (var attrName in attributes) {
  42. if(attributes.hasOwnProperty(attrName)) {
  43. e.setAttribute(attrName, attributes[attrName]);
  44. }
  45. }
  46. e.onreadystatechange = e.onload = function() {
  47. var state = e.readyState;
  48. if (!callback.done && (!state || /loaded|complete/.test(state))) {
  49. callback.done = true;
  50. callback();
  51. }
  52. };
  53. document.head.appendChild(e);
  54. }
  55. function loadDependencies() {
  56. // Adding globalization file to the HEAD section
  57. // <link rel="resource" type="application/l10n" href="locales/date.ini" />
  58. loadFile('link', {
  59. 'rel': 'resource',
  60. 'type': 'application/l10n',
  61. 'href': 'locales/date.ini'}, function() {});
  62. loadFile('script', {
  63. 'type': 'text/javascript',
  64. 'src': 'js/l10n.js'},
  65. function() {
  66. loadFile('script', {
  67. 'type': 'text/javascript',
  68. 'src': 'js/l10n_date.js'},
  69. function() {
  70. document.dispatchEvent(l10n_loaded);
  71. });
  72. });
  73. }
  74. loadDependencies();
  75. function getPreferredLanguage(successCB, errorCB) {
  76. // WARNING: this isn't perfect - there is a difference between UI language
  77. // and preferred language, however it doesn't happen too often.
  78. callIfL10nReady(function() {
  79. successCB({value: navigator.mozL10n.language.code});
  80. });
  81. }
  82. function getLocaleName(successCB, errorCB) {
  83. callIfL10nReady(function() {
  84. successCB(navigator.mozL10n.language.code);
  85. });
  86. }
  87. function dateToString(successCB, errorCB, params) {
  88. var date = new Date(params[0].date);
  89. var options = params[0].options;
  90. callIfL10nReady(function() {
  91. var f = new navigator.mozL10n.DateTimeFormat();
  92. successCB({'value': _getStringFromDate(f, date, options)});
  93. });
  94. function _getStringFromDate(f, date, options) {
  95. var format = navigator.mozL10n.get('shortDateTimeFormat');
  96. if (options) {
  97. if (options.selector === 'date') {
  98. return f.localeDateString(date);
  99. }
  100. if (options.selector === 'time') {
  101. return f.localeTimeString(date);
  102. }
  103. if (options.formatLength !== 'short') {
  104. format = navigator.mozL10n.get('dateTimeFormat');
  105. return f.localeString(date, format);
  106. }
  107. if (options.selector === 'time') {
  108. return f.localeTimeString(date, format);
  109. }
  110. }
  111. var d = f.localeDateString(date);
  112. var t = f.localeTimeString(date);
  113. return d + ' ' + t;
  114. }
  115. }
  116. function stringToDate(successCB, errorCB, params) {
  117. var date;
  118. var dateString = params[0].dateString;
  119. var options = params[0].options;
  120. try {
  121. date = new Date(dateString);
  122. } catch(e) {
  123. console.log("Cordova, stringToDate, An error occurred " + e.message);
  124. return errorCB(new GlobalizationError(
  125. GlobalizationError.PARSING_ERROR, e.message));
  126. }
  127. if (!date || date === 'Invalid Date') {
  128. console.log("Cordova, stringToDate, Invalid Date: " + dateString);
  129. return errorCB(new GlobalizationError(
  130. GlobalizationError.PARSING_ERROR, 'Invalid Date (' + dateString + ')'));
  131. }
  132. var dateObj = {
  133. 'year': date.getFullYear(),
  134. 'month': date.getMonth(),
  135. 'day': date.getDay()
  136. };
  137. var timeObj = {
  138. 'hour': date.getHours(),
  139. 'minute': date.getMinutes(),
  140. 'second': date.getSeconds(),
  141. 'millisecond': date.getMilliseconds()
  142. };
  143. if (options) {
  144. if (options.selector === 'date') {
  145. return successCB(dateObj);
  146. }
  147. if (options.selector === 'time') {
  148. return successCB(timeObj);
  149. }
  150. }
  151. for (var i in timeObj) {
  152. if (timeObj.hasOwnProperty(i)) {
  153. dateObj[i] = timeObj[i];
  154. }
  155. }
  156. successCB(dateObj);
  157. }
  158. function getDatePattern(successCB, failureCB, options) {
  159. failureCB(GlobalizationError.UNKNOWN_ERROR, 'unsupported');
  160. }
  161. function getDateNames(successCB, failureCB, params) {
  162. callIfL10nReady(function() {
  163. var version = 'long';
  164. var item = 'month';
  165. var options = params[0].options;
  166. if (options) {
  167. if (options.type === 'narrow') {
  168. version = 'short';
  169. } else if (options.type === 'genitive' && options.item === 'months') {
  170. version = options.type;
  171. }
  172. if (options.item === 'days') {
  173. item = 'weekday';
  174. }
  175. }
  176. var limit = (item === 'month') ? 11 : 6;
  177. var arr = [];
  178. for (var i = 0; i <= limit; i++) {
  179. arr.push(navigator.mozL10n.get(item + '-' + i + '-' + version));
  180. }
  181. successCB({'value': arr});
  182. });
  183. }
  184. Date.prototype.stdTimezoneOffset = function() {
  185. // Return the standard timezone offset (usually 0 or -600)
  186. var jan = new Date(this.getFullYear(), 0, 1);
  187. var jul = new Date(this.getFullYear(), 6, 1);
  188. return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
  189. };
  190. Date.prototype.isDayLightSavingsTime = function() {
  191. return this.getTimezoneOffset() < this.stdTimezoneOffset();
  192. };
  193. function isDayLightSavingsTime(successCB, failureCB, params) {
  194. var date = new Date(params[0].date);
  195. successCB({'dst': date.isDayLightSavingsTime()});
  196. }
  197. function getFirstDayOfWeek(successCB, failureCB) {
  198. callIfL10nReady(function() {
  199. var firstDay = navigator.mozL10n.get('weekStartsOnMonday');
  200. // Sunday: 1
  201. // Monday: 2
  202. successCB({'value': 1 + parseInt(firstDay)});
  203. });
  204. }
  205. function numberToString(number, successCB, failureCB) {
  206. failureCB(GlobalizationError.UNKNOWN_ERROR, 'unsupported');
  207. }
  208. function stringToNumber(numberString, successCB, failureCB, options) {
  209. failureCB(GlobalizationError.UNKNOWN_ERROR, 'unsupported');
  210. }
  211. function getNumberPattern(successCB, failureCB, options) {
  212. failureCB(GlobalizationError.UNKNOWN_ERROR, 'unsupported');
  213. }
  214. function getCurrencyPattern(currencyCode, successCB, failureCB) {
  215. failureCB(GlobalizationError.UNKNOWN_ERROR, 'unsupported');
  216. }
  217. var Globalization = {
  218. getLocaleName: getLocaleName,
  219. getPreferredLanguage: getPreferredLanguage,
  220. dateToString: dateToString,
  221. stringToDate: stringToDate,
  222. getDatePattern: getDatePattern,
  223. getDateNames: getDateNames,
  224. isDayLightSavingsTime: isDayLightSavingsTime,
  225. getFirstDayOfWeek: getFirstDayOfWeek,
  226. numberToString: numberToString,
  227. stringToNumber: stringToNumber,
  228. getNumberPattern: getNumberPattern,
  229. getCurrencyPattern: getCurrencyPattern
  230. };
  231. require("cordova/exec/proxy").add("Globalization", Globalization);