locale.tsx 11 KB

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