@hhgtech/hhg-components
Version:
Hello Health Group common components
101 lines (97 loc) • 3.27 kB
JavaScript
import * as React from 'react';
import { useContext, useMemo } from 'react';
import { T as TranslationsContext } from './translationsContext-18f7b7e0.js';
// SRC: https://github.com/berezh/react-string-format
function format(text, params) {
let result = [text];
Object.keys(params).forEach((key) => {
result = parseAndReplace(result, params[key], key);
});
if (result.length === 0) {
return '';
}
else if (result.length === 1 && typeof result[0] === 'string') {
return result[0];
}
else if (result.every((x) => typeof x === 'string')) {
return result.join('');
}
else {
return (React.createElement(React.Fragment, null, result.map((x, i) => {
return React.createElement(React.Fragment, { key: i }, x);
})));
}
}
function replaceWhiteSpace(text) {
const result = [];
let start = false;
let end = false;
if (!!text.match(/^\s+/gi)) {
text = text.replace(/^\s+/gi, '');
start = true;
}
if (!!text.match(/\s+$/gi)) {
text = text.replace(/\s+$/gi, '');
end = true;
}
if (start) {
result.push(React.createElement(React.Fragment, null, "\u00A0"));
}
result.push(text);
if (end) {
result.push(React.createElement(React.Fragment, null, "\u00A0"));
}
return result;
}
function parseAndReplace(source, replaceWith, key) {
const result = [];
source.forEach((possibleText) => {
if (typeof possibleText === 'string') {
const pattern = new RegExp(`\\{${key}\\}`, 'gi');
if (typeof replaceWith === 'string' || typeof replaceWith === 'number') {
result.push(possibleText.replace(pattern, `${replaceWith}`));
}
else {
const splits = possibleText.split(pattern);
splits.forEach((splitText, i) => {
if (splitText) {
replaceWhiteSpace(splitText).forEach((text) => result.push(text));
}
// if NOT last
if (i + 1 < splits.length) {
result.push(replaceWith);
}
});
}
}
else {
result.push(possibleText);
}
});
return result;
}
function useTranslations() {
const { values, locale } = useContext(TranslationsContext) || {
locale: 'en-PH',
};
return useMemo(() => ({
t(k, option) {
if (!values) {
// console.error(
// '[useTranslations] t method called before translation values are loaded',
// )
return k;
}
if (values[k]) {
return option ? format(values[k] || k, option) : values[k] || k;
}
// console.warn(
// `[useTranslations] Missing translation for key ${k} and locale ${locale}`,
// )
return option ? format(k, option) : k;
},
// @ts-ignore
locale,
}), [values, locale]);
}
export { format as f, useTranslations as u };