import React from 'react';
const SEP = '$.$';
/**
* 格式化
* @param {string} template string format
* @param {...any} res input params
*/
const format = (template, _params) => {
const args = _params;
let idx = 0;
let state = 'UNDEFINED';
let cache = [];
const s = template.replace(/([{}])\1|[{](.*?)[}]/g, (match, literal, _key) => {
if (literal != null) {
return literal;
}
const base = `{${_key}}`;
let key = _key;
if (key.length > 0) {
if (state === 'IMPLICIT') {
console.warn('cannot switch from implicit to explicit numbering');
return base;
}
state = 'EXPLICIT';
} else {
if (state === 'EXPLICIT') {
console.warn('cannot switch from explicit to implicit numbering');
return base;
}
state = 'IMPLICIT';
key = String(idx);
idx += 1;
}
const path = key.split('.');
// const value = (/^\d+$/.test(path[0]) ? path : ['0'].concat(path))
// .reduce((maybe, k) => maybe.reduce((_, x) => (x != null && k in Object(x) ? [typeof x[k] === 'function' ? x[k]() : x[k]] : []), []), [args])
// .reduce((_, x) => x, base);
const value = path
.reduce((maybe, k) => maybe.reduce((_, x) => (x != null && k in Object(x) ? [x[k]] : []), []), [args])
.reduce((_, x) => x, base);
cache.push(value);
return SEP;
});
const hasElement = cache.some(n => React.isValidElement(n));
if (hasElement) {
const I18NComponent = function() {
return (
<>
{s.split(SEP).map((x, i) => {
return (
{x}
{cache[i] && React.isValidElement(cache[i]) ? React.cloneElement(cache[i]) : cache[i]}
);
})}
>
);
};
return ;
}
return s
.split(SEP)
.map((x, i) => `${x}${cache[i] || ''}`)
.join('');
};
export { format };