locale.tsx 12 KB

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