From 458ee3cce4f6ba6b2e1ca278a6ac9f4e7d197ef9 Mon Sep 17 00:00:00 2001 From: Ryan Miller Date: Wed, 27 Mar 2024 17:36:07 +1100 Subject: [PATCH] feat: add i18n component for rendering html from a localized string --- ts/components/basic/I18n.tsx | 47 ++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 ts/components/basic/I18n.tsx diff --git a/ts/components/basic/I18n.tsx b/ts/components/basic/I18n.tsx new file mode 100644 index 000000000..1b82ca51b --- /dev/null +++ b/ts/components/basic/I18n.tsx @@ -0,0 +1,47 @@ +import React from 'react'; +import type { + GetMessageArgs, + I18nProps, + LocalizerDictionary, + LocalizerToken, +} from '../../types/Localizer'; + +import { SessionHtmlRenderer } from './SessionHTMLRenderer'; + +/** An array of supported html tags to render if found in a string */ +const supportedFormattingTags = ['b', 'i', 'u', 's']; + +/** A regex to match supported formatting tags */ +const formattingTagRegex = new RegExp( + `<(?:${supportedFormattingTags.join('|')})>.*?`, + 'g' +); + +/** + * Retrieve a localized message string, substituting dynamic parts where necessary and formatting it as HTML if necessary. + * + * @param token - The token identifying the message to retrieve and an optional record of substitution variables and their replacement values. + * @param args - An optional record of substitution variables and their replacement values. This is required if the string has dynamic parts. + * + * @returns The localized message string with substitutions and formatting applied. + * + * @example + * ```tsx + * + * + * ``` + */ +export const I18n = (props: I18nProps) => { + const i18nArgs = 'args' in props ? props.args : undefined; + + const i18nString = window.i18n( + ...([props.token, i18nArgs] as GetMessageArgs) + ); + + /** If the string contains a relevant formatting tag, render it as HTML */ + if (i18nString.match(formattingTagRegex)) { + return ; + } + + return <>{i18nString}; +};