UNPKG

andrei-bread-i18n

Version:

Small and type-safe package to create multi-language interfaces.

29 lines (28 loc) 1.05 kB
import { jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime"; import { Fragment } from "react"; import { I18NContext } from "./context"; export const I18NProvider = ({ i18n, children }) => { return _jsx(I18NContext.Provider, { value: i18n, children: children }); }; const tagsRegex = /(<\d+>[^<>]*<\/\d+>)/; const openCloseTagRegex = /<(\d+)>([^<>]*)<\/(\d+)>/; const interpolateTags = (text, params) => { if (!params) { return text; } const tokens = text.split(tagsRegex); return tokens.map((token) => { const matchResult = openCloseTagRegex.exec(token); if (!matchResult) { return token; } const [, openTag, content, closeTag] = matchResult; if (!openTag || !closeTag || openTag !== closeTag) { return token; } return (_jsx(Fragment, { children: params[openTag]?.(content ?? "") }, content)); }); }; export const TaggedText = ({ text, tags }) => { return _jsx(_Fragment, { children: interpolateTags(text, tags) }); };