locale.tsx 11 KB

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