locale.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. import * as React from 'react';
  2. import * as Sentry from '@sentry/react';
  3. import Jed from 'jed';
  4. import isArray from 'lodash/isArray';
  5. import isObject from 'lodash/isObject';
  6. import isString from 'lodash/isString';
  7. import {sprintf} from 'sprintf-js';
  8. import localStorage from 'sentry/utils/localStorage';
  9. const markerStyles = {
  10. background: '#ff801790',
  11. outline: '2px solid #ff801790',
  12. };
  13. const LOCALE_DEBUG = localStorage.getItem('localeDebug') === '1';
  14. export const DEFAULT_LOCALE_DATA = {
  15. '': {
  16. domain: 'sentry',
  17. lang: 'en',
  18. plural_forms: 'nplurals=2; plural=(n != 1);',
  19. },
  20. };
  21. export function setLocaleDebug(value: boolean) {
  22. localStorage.setItem('localeDebug', value ? '1' : '0');
  23. // eslint-disable-next-line no-console
  24. console.log(`Locale debug is: ${value ? 'on' : 'off'}. Reload page to apply changes!`);
  25. }
  26. /**
  27. * Toggles the locale debug flag in local storage, but does _not_ reload the
  28. * page. The caller should do this.
  29. */
  30. export function toggleLocaleDebug() {
  31. const currentValue = localStorage.getItem('localeDebug');
  32. setLocaleDebug(currentValue !== '1');
  33. }
  34. /**
  35. * Global Jed locale object loaded with translations via setLocale
  36. */
  37. let i18n: any = null;
  38. /**
  39. * Set the current application locale.
  40. *
  41. * NOTE: This MUST be called early in the application before calls to any
  42. * translation functions, as this mutates a singleton translation object used
  43. * to lookup translations at runtime.
  44. */
  45. export function setLocale(translations: any) {
  46. i18n = new Jed({
  47. domain: 'sentry',
  48. missing_key_callback: () => {},
  49. locale_data: {
  50. sentry: translations,
  51. },
  52. });
  53. return i18n;
  54. }
  55. type FormatArg = ComponentMap | React.ReactNode;
  56. /**
  57. * Helper to return the i18n client, and initialize for the default locale (English)
  58. * if it has otherwise not been initialized.
  59. */
  60. function getClient() {
  61. if (!i18n) {
  62. // If this happens, it could mean that an import was added/changed where
  63. // locale initialization does not happen soon enough.
  64. const warning = new Error('Locale not set, defaulting to English');
  65. console.error(warning); // eslint-disable-line no-console
  66. Sentry.captureException(warning);
  67. return setLocale(DEFAULT_LOCALE_DATA);
  68. }
  69. return i18n;
  70. }
  71. /**
  72. * printf style string formatting which render as react nodes.
  73. */
  74. function formatForReact(formatString: string, args: FormatArg[]) {
  75. const nodes: React.ReactNodeArray = [];
  76. let cursor = 0;
  77. // always re-parse, do not cache, because we change the match
  78. sprintf.parse(formatString).forEach((match: any, idx: number) => {
  79. if (isString(match)) {
  80. nodes.push(match);
  81. return;
  82. }
  83. let arg: FormatArg = null;
  84. if (match[2]) {
  85. arg = (args[0] as ComponentMap)[match[2][0]];
  86. } else if (match[1]) {
  87. arg = args[parseInt(match[1], 10) - 1];
  88. } else {
  89. arg = args[cursor++];
  90. }
  91. // this points to a react element!
  92. if (React.isValidElement(arg)) {
  93. nodes.push(React.cloneElement(arg, {key: idx}));
  94. } else {
  95. // not a react element, fuck around with it so that sprintf.format
  96. // can format it for us. We make sure match[2] is null so that we
  97. // do not go down the object path, and we set match[1] to the first
  98. // index and then pass an array with two items in.
  99. match[2] = null;
  100. match[1] = 1;
  101. nodes.push(<span key={idx++}>{sprintf.format([match], [null, arg])}</span>);
  102. }
  103. });
  104. return nodes;
  105. }
  106. /**
  107. * Determine if any arguments include React elements.
  108. */
  109. function argsInvolveReact(args: FormatArg[]) {
  110. if (args.some(React.isValidElement)) {
  111. return true;
  112. }
  113. if (args.length !== 1 || !isObject(args[0])) {
  114. return false;
  115. }
  116. const componentMap = args[0] as ComponentMap;
  117. return Object.keys(componentMap).some(key => React.isValidElement(componentMap[key]));
  118. }
  119. /**
  120. * Parse template strings will be parsed into an array of TemplateSubvalue's,
  121. * this represents either a portion of the string, or a object with the group
  122. * key indicating the group to lookup the group value in.
  123. */
  124. type TemplateSubvalue = string | {group: string};
  125. /**
  126. * ParsedTemplate is a mapping of group names to Template Subvalue arrays.
  127. */
  128. type ParsedTemplate = {[group: string]: TemplateSubvalue[]};
  129. /**
  130. * ComponentMap maps template group keys to react node instances.
  131. *
  132. * NOTE: template group keys that include additional sub values (e.g.
  133. * [groupName:this string is the sub value]) will override the mapped react
  134. * nodes children prop.
  135. *
  136. * In the above example the component map of {groupName: <strong>text</strong>}
  137. * will be translated to `<strong>this string is the sub value</strong>`.
  138. */
  139. type ComponentMap = {[group: string]: React.ReactNode};
  140. /**
  141. * Parses a template string into groups.
  142. *
  143. * The top level group will be keyed as `root`. All other group names will have
  144. * been extracted from the template string.
  145. */
  146. export function parseComponentTemplate(template: string) {
  147. const parsed: ParsedTemplate = {};
  148. function process(startPos: number, group: string, inGroup: boolean) {
  149. const regex = /\[(.*?)(:|\])|\]/g;
  150. const buf: TemplateSubvalue[] = [];
  151. let satisfied = false;
  152. let match: ReturnType<typeof regex.exec>;
  153. let pos = (regex.lastIndex = startPos);
  154. // eslint-disable-next-line no-cond-assign
  155. while ((match = regex.exec(template)) !== null) {
  156. const substr = template.substr(pos, match.index - pos);
  157. if (substr !== '') {
  158. buf.push(substr);
  159. }
  160. const [fullMatch, groupName, closeBraceOrValueSeparator] = match;
  161. if (fullMatch === ']') {
  162. if (inGroup) {
  163. satisfied = true;
  164. break;
  165. } else {
  166. pos = regex.lastIndex;
  167. continue;
  168. }
  169. }
  170. if (closeBraceOrValueSeparator === ']') {
  171. pos = regex.lastIndex;
  172. } else {
  173. pos = regex.lastIndex = process(regex.lastIndex, groupName, true);
  174. }
  175. buf.push({group: groupName});
  176. }
  177. let endPos = regex.lastIndex;
  178. if (!satisfied) {
  179. const rest = template.substr(pos);
  180. if (rest) {
  181. buf.push(rest);
  182. }
  183. endPos = template.length;
  184. }
  185. parsed[group] = buf;
  186. return endPos;
  187. }
  188. process(0, 'root', false);
  189. return parsed;
  190. }
  191. /**
  192. * Renders a parsed template into a React tree given a ComponentMap to use for
  193. * the parsed groups.
  194. */
  195. export function renderTemplate(template: ParsedTemplate, components: ComponentMap) {
  196. let idx = 0;
  197. function renderGroup(groupKey: string) {
  198. const children: React.ReactNode[] = [];
  199. const group = template[groupKey] || [];
  200. for (const item of group) {
  201. if (isString(item)) {
  202. children.push(<span key={idx++}>{item}</span>);
  203. } else {
  204. children.push(renderGroup(item.group));
  205. }
  206. }
  207. // In case we cannot find our component, we call back to an empty
  208. // span so that stuff shows up at least.
  209. let reference = components[groupKey] ?? <span key={idx++} />;
  210. if (!React.isValidElement(reference)) {
  211. reference = <span key={idx++}>{reference}</span>;
  212. }
  213. const element = reference as React.ReactElement;
  214. return children.length === 0
  215. ? React.cloneElement(element, {key: idx++})
  216. : React.cloneElement(element, {key: idx++}, children);
  217. }
  218. return <React.Fragment>{renderGroup('root')}</React.Fragment>;
  219. }
  220. /**
  221. * mark is used to debug translations by visually marking translated strings.
  222. *
  223. * NOTE: This is a no-op and will return the node if LOCALE_DEBUG is not
  224. * currently enabled. See setLocaleDebug and toggleLocaleDebug.
  225. */
  226. function mark<T>(node: T): T {
  227. if (!LOCALE_DEBUG) {
  228. return node;
  229. }
  230. // TODO(epurkhiser): Explain why we manually create a react node and assign
  231. // the toString function. This could likely also use better typing, but will
  232. // require some understanding of reacts internal types.
  233. const proxy: any = {
  234. $$typeof: Symbol.for('react.element'),
  235. type: 'span',
  236. key: null,
  237. ref: null,
  238. props: {
  239. style: markerStyles,
  240. children: isArray(node) ? node : [node],
  241. },
  242. _owner: null,
  243. _store: {},
  244. };
  245. proxy.toString = () => '✅' + node + '✅';
  246. return proxy;
  247. }
  248. /**
  249. * sprintf style string formatting. Does not handle translations.
  250. *
  251. * See the sprintf-js library [0] for specifics on the argument
  252. * parameterization format.
  253. *
  254. * [0]: https://github.com/alexei/sprintf.js
  255. */
  256. export function format(formatString: string, args: FormatArg[]) {
  257. if (argsInvolveReact(args)) {
  258. return formatForReact(formatString, args);
  259. }
  260. return sprintf(formatString, ...args) as string;
  261. }
  262. /**
  263. * Translates a string to the current locale.
  264. *
  265. * See the sprintf-js library [0] for specifics on the argument
  266. * parameterization format.
  267. *
  268. * [0]: https://github.com/alexei/sprintf.js
  269. */
  270. export function gettext(string: string, ...args: FormatArg[]) {
  271. const val: string = getClient().gettext(string);
  272. if (args.length === 0) {
  273. return mark(val);
  274. }
  275. // XXX(ts): It IS possible to use gettext in such a way that it will return a
  276. // React.ReactNodeArray, however we currently rarely (if at all) use it in
  277. // this way, and usually just expect strings back.
  278. return mark(format(val, args) as string);
  279. }
  280. /**
  281. * Translates a singular and plural string to the current locale. Supports
  282. * argument parameterization, and will use the first argument as the counter to
  283. * determine which message to use.
  284. *
  285. * See the sprintf-js library [0] for specifics on the argument
  286. * parameterization format.
  287. *
  288. * [0]: https://github.com/alexei/sprintf.js
  289. */
  290. export function ngettext(singular: string, plural: string, ...args: FormatArg[]) {
  291. let countArg = 0;
  292. if (args.length > 0) {
  293. countArg = Math.abs(args[0] as number) || 0;
  294. // `toLocaleString` will render `999` as `"999"` but `9999` as `"9,999"`. This means that any call with `tn` or `ngettext` cannot use `%d` in the codebase but has to use `%s`.
  295. // This means a string is always being passed in as an argument, but `sprintf-js` implicitly coerces strings that can be parsed as integers into an integer.
  296. // This would break under any locale that used different formatting and other undesirable behaviors.
  297. if ((singular + plural).includes('%d')) {
  298. // eslint-disable-next-line no-console
  299. console.error(new Error('You should not use %d within tn(), use %s instead'));
  300. } else {
  301. args = [countArg.toLocaleString(), ...args.slice(1)];
  302. }
  303. }
  304. // XXX(ts): See XXX in gettext.
  305. return mark(format(getClient().ngettext(singular, plural, countArg), args) as string);
  306. }
  307. /**
  308. * special form of gettext where you can render nested react components in
  309. * template strings.
  310. *
  311. * ```jsx
  312. * gettextComponentTemplate('Welcome. Click [link:here]', {
  313. * root: <p/>,
  314. * link: <a href="#" />,
  315. * });
  316. * ```
  317. *
  318. * The root string is always called "root", the rest is prefixed with the name
  319. * in the brackets
  320. *
  321. * You may recursively nest additional groups within the grouped string values.
  322. */
  323. export function gettextComponentTemplate(template: string, components: ComponentMap) {
  324. const tmpl = parseComponentTemplate(getClient().gettext(template));
  325. return mark(renderTemplate(tmpl, components));
  326. }
  327. /**
  328. * Shorthand versions should primarily be used.
  329. */
  330. export {gettext as t, gettextComponentTemplate as tct, ngettext as tn};