A11yI18n.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. /* *
  2. *
  3. * Accessibility module - internationalization support
  4. *
  5. * (c) 2010-2021 Highsoft AS
  6. * Author: Øystein Moseng
  7. *
  8. * License: www.highcharts.com/license
  9. *
  10. * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
  11. *
  12. * */
  13. 'use strict';
  14. import H from '../Core/Globals.js';
  15. import U from '../Core/Utilities.js';
  16. var format = U.format, pick = U.pick;
  17. /* eslint-disable valid-jsdoc */
  18. /**
  19. * String trim that works for IE6-8 as well.
  20. *
  21. * @private
  22. * @function stringTrim
  23. *
  24. * @param {string} str
  25. * The input string
  26. *
  27. * @return {string}
  28. * The trimmed string
  29. */
  30. function stringTrim(str) {
  31. return str.trim && str.trim() || str.replace(/^\s+|\s+$/g, '');
  32. }
  33. /**
  34. * i18n utility function. Format a single array or plural statement in a format
  35. * string. If the statement is not an array or plural statement, returns the
  36. * statement within brackets. Invalid array statements return an empty string.
  37. *
  38. * @private
  39. * @function formatExtendedStatement
  40. *
  41. * @param {string} statement
  42. *
  43. * @param {Highcharts.Dictionary<*>} ctx
  44. * Context to apply to the format string.
  45. *
  46. * @return {string}
  47. */
  48. function formatExtendedStatement(statement, ctx) {
  49. var eachStart = statement.indexOf('#each('), pluralStart = statement.indexOf('#plural('), indexStart = statement.indexOf('['), indexEnd = statement.indexOf(']'), arr, result;
  50. // Dealing with an each-function?
  51. if (eachStart > -1) {
  52. var eachEnd = statement.slice(eachStart).indexOf(')') + eachStart, preEach = statement.substring(0, eachStart), postEach = statement.substring(eachEnd + 1), eachStatement = statement.substring(eachStart + 6, eachEnd), eachArguments = eachStatement.split(','), lenArg = Number(eachArguments[1]), len;
  53. result = '';
  54. arr = ctx[eachArguments[0]];
  55. if (arr) {
  56. lenArg = isNaN(lenArg) ? arr.length : lenArg;
  57. len = lenArg < 0 ?
  58. arr.length + lenArg :
  59. Math.min(lenArg, arr.length); // Overshoot
  60. // Run through the array for the specified length
  61. for (var i = 0; i < len; ++i) {
  62. result += preEach + arr[i] + postEach;
  63. }
  64. }
  65. return result.length ? result : '';
  66. }
  67. // Dealing with a plural-function?
  68. if (pluralStart > -1) {
  69. var pluralEnd = statement.slice(pluralStart).indexOf(')') + pluralStart, pluralStatement = statement.substring(pluralStart + 8, pluralEnd), pluralArguments = pluralStatement.split(','), num = Number(ctx[pluralArguments[0]]);
  70. switch (num) {
  71. case 0:
  72. result = pick(pluralArguments[4], pluralArguments[1]);
  73. break;
  74. case 1:
  75. result = pick(pluralArguments[2], pluralArguments[1]);
  76. break;
  77. case 2:
  78. result = pick(pluralArguments[3], pluralArguments[1]);
  79. break;
  80. default:
  81. result = pluralArguments[1];
  82. }
  83. return result ? stringTrim(result) : '';
  84. }
  85. // Array index
  86. if (indexStart > -1) {
  87. var arrayName = statement.substring(0, indexStart), ix = Number(statement.substring(indexStart + 1, indexEnd)), val;
  88. arr = ctx[arrayName];
  89. if (!isNaN(ix) && arr) {
  90. if (ix < 0) {
  91. val = arr[arr.length + ix];
  92. // Handle negative overshoot
  93. if (typeof val === 'undefined') {
  94. val = arr[0];
  95. }
  96. }
  97. else {
  98. val = arr[ix];
  99. // Handle positive overshoot
  100. if (typeof val === 'undefined') {
  101. val = arr[arr.length - 1];
  102. }
  103. }
  104. }
  105. return typeof val !== 'undefined' ? val : '';
  106. }
  107. // Standard substitution, delegate to format or similar
  108. return '{' + statement + '}';
  109. }
  110. /**
  111. * i18n formatting function. Extends Highcharts.format() functionality by also
  112. * handling arrays and plural conditionals. Arrays can be indexed as follows:
  113. *
  114. * - Format: 'This is the first index: {myArray[0]}. The last: {myArray[-1]}.'
  115. *
  116. * - Context: { myArray: [0, 1, 2, 3, 4, 5] }
  117. *
  118. * - Result: 'This is the first index: 0. The last: 5.'
  119. *
  120. *
  121. * They can also be iterated using the #each() function. This will repeat the
  122. * contents of the bracket expression for each element. Example:
  123. *
  124. * - Format: 'List contains: {#each(myArray)cm }'
  125. *
  126. * - Context: { myArray: [0, 1, 2] }
  127. *
  128. * - Result: 'List contains: 0cm 1cm 2cm '
  129. *
  130. *
  131. * The #each() function optionally takes a length parameter. If positive, this
  132. * parameter specifies the max number of elements to iterate through. If
  133. * negative, the function will subtract the number from the length of the array.
  134. * Use this to stop iterating before the array ends. Example:
  135. *
  136. * - Format: 'List contains: {#each(myArray, -1) }and {myArray[-1]}.'
  137. *
  138. * - Context: { myArray: [0, 1, 2, 3] }
  139. *
  140. * - Result: 'List contains: 0, 1, 2, and 3.'
  141. *
  142. *
  143. * Use the #plural() function to pick a string depending on whether or not a
  144. * context object is 1. Arguments are #plural(obj, plural, singular). Example:
  145. *
  146. * - Format: 'Has {numPoints} {#plural(numPoints, points, point}.'
  147. *
  148. * - Context: { numPoints: 5 }
  149. *
  150. * - Result: 'Has 5 points.'
  151. *
  152. *
  153. * Optionally there are additional parameters for dual and none: #plural(obj,
  154. * plural, singular, dual, none). Example:
  155. *
  156. * - Format: 'Has {#plural(numPoints, many points, one point, two points,
  157. * none}.'
  158. *
  159. * - Context: { numPoints: 2 }
  160. *
  161. * - Result: 'Has two points.'
  162. *
  163. *
  164. * The dual or none parameters will take precedence if they are supplied.
  165. *
  166. * @requires modules/accessibility
  167. *
  168. * @function Highcharts.i18nFormat
  169. *
  170. * @param {string} formatString
  171. * The string to format.
  172. *
  173. * @param {Highcharts.Dictionary<*>} context
  174. * Context to apply to the format string.
  175. *
  176. * @param {Highcharts.Chart} chart
  177. * A `Chart` instance with a time object and numberFormatter, passed on
  178. * to format().
  179. *
  180. * @return {string}
  181. * The formatted string.
  182. */
  183. H.i18nFormat = function (formatString, context, chart) {
  184. var getFirstBracketStatement = function (sourceStr, offset) {
  185. var str = sourceStr.slice(offset || 0), startBracket = str.indexOf('{'), endBracket = str.indexOf('}');
  186. if (startBracket > -1 && endBracket > startBracket) {
  187. return {
  188. statement: str.substring(startBracket + 1, endBracket),
  189. begin: offset + startBracket + 1,
  190. end: offset + endBracket
  191. };
  192. }
  193. }, tokens = [], bracketRes, constRes, cursor = 0;
  194. // Tokenize format string into bracket statements and constants
  195. do {
  196. bracketRes = getFirstBracketStatement(formatString, cursor);
  197. constRes = formatString.substring(cursor, bracketRes && bracketRes.begin - 1);
  198. // If we have constant content before this bracket statement, add it
  199. if (constRes.length) {
  200. tokens.push({
  201. value: constRes,
  202. type: 'constant'
  203. });
  204. }
  205. // Add the bracket statement
  206. if (bracketRes) {
  207. tokens.push({
  208. value: bracketRes.statement,
  209. type: 'statement'
  210. });
  211. }
  212. cursor = bracketRes ? bracketRes.end + 1 : cursor + 1;
  213. } while (bracketRes);
  214. // Perform the formatting. The formatArrayStatement function returns the
  215. // statement in brackets if it is not an array statement, which means it
  216. // gets picked up by format below.
  217. tokens.forEach(function (token) {
  218. if (token.type === 'statement') {
  219. token.value = formatExtendedStatement(token.value, context);
  220. }
  221. });
  222. // Join string back together and pass to format to pick up non-array
  223. // statements.
  224. return format(tokens.reduce(function (acc, cur) {
  225. return acc + cur.value;
  226. }, ''), context, chart);
  227. };
  228. /**
  229. * Apply context to a format string from lang options of the chart.
  230. *
  231. * @requires modules/accessibility
  232. *
  233. * @function Highcharts.Chart#langFormat
  234. *
  235. * @param {string} langKey
  236. * Key (using dot notation) into lang option structure.
  237. *
  238. * @param {Highcharts.Dictionary<*>} context
  239. * Context to apply to the format string.
  240. *
  241. * @return {string}
  242. * The formatted string.
  243. */
  244. H.Chart.prototype.langFormat = function (langKey, context) {
  245. var keys = langKey.split('.'), formatString = this.options.lang, i = 0;
  246. for (; i < keys.length; ++i) {
  247. formatString = formatString && formatString[keys[i]];
  248. }
  249. return typeof formatString === 'string' ?
  250. H.i18nFormat(formatString, context, this) : '';
  251. };