A11yI18n.js 8.6 KB

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