@translata/react
Version:
React integration for translata: The Composable Translation Utility
76 lines (75 loc) • 2.51 kB
JavaScript
;
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
exports.__esModule = true;
var react_1 = __importStar(require("react"));
/**
* Create a translator provider, including hooks to consume the translation context.
*
* @param defaultLocale Default locale.
* @param factory Translator factory.
*/
function createTranslatorProvider(defaultLocale, factory) {
var Context = react_1.createContext({
translator: null,
locale: null,
setLocale: null
});
/**
* The Translator Provider.
*
* @param props
*/
function Provider(props) {
var _a = __read(react_1.useState(defaultLocale), 2), locale = _a[0], setLocale = _a[1];
var translator = react_1.useMemo(function () { return factory(locale); }, [locale]);
var state = react_1.useMemo(function () { return ({
translator: translator,
locale: locale,
setLocale: setLocale
}); }, [translator, locale]);
return react_1["default"].createElement(Context.Provider, { value: state }, props.children);
}
/**
* Use the current translator from context.
*/
function useTranslator() {
return react_1.useContext(Context).translator;
}
/**
* Use the current locale from context.
*/
function useLocale() {
return react_1.useContext(Context).locale;
}
/**
* Use the locale setter from context, this allows you to change
* the default locale on context level.
*/
function useSetLocale() {
return react_1.useContext(Context).setLocale;
}
return Object.assign(Provider, { useLocale: useLocale, useSetLocale: useSetLocale, useTranslator: useTranslator });
}
exports.createTranslatorProvider = createTranslatorProvider;