UNPKG

@enact/i18n

Version:

Internationalization support for Enact using iLib

300 lines (294 loc) 13.8 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = exports.TextDecorator = exports.Text = void 0; var _hoc = _interopRequireDefault(require("@enact/core/hoc")); var _ilib = _interopRequireDefault(require("ilib")); var _IString = _interopRequireDefault(require("ilib/lib/IString")); var _propTypes = _interopRequireDefault(require("prop-types")); var _react = require("react"); var _I18nDecorator = require("../I18nDecorator"); var _resBundle = require("../src/resBundle"); var _jsxRuntime = require("react/jsx-runtime"); function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } } function _arrayWithHoles(r) { if (Array.isArray(r)) return r; } function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); } function _possibleConstructorReturn(t, e) { if (e && ("object" == typeof e || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); } function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; } function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); } function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); } function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); } function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); } /** * An unstyled text translation component. * * @module i18n/Text * @exports Text * @exports TextDecorator */ function getTextMap(mapPropsToText, props) { var children = props.children, defaultText = props.defaultText; if (mapPropsToText) { var map = {}; Object.keys(mapPropsToText).forEach(function (prop) { var text = mapPropsToText[prop]; // if a prop is specified without a proper value (string or object), ignore it if (text) { if (typeof text === 'string') { // for string text values, pass them along as the untranslated text // without a default value map[prop] = { translated: false, text: text, defaultText: false }; } else if (typeof text.text === 'string') { // for object text values with a string text member, use it as the // untranslated text and optionally look for a string defaultText for a // default value map[prop] = { translated: false, text: text.text, defaultText: typeof text.defaultText === 'string' ? text.defaultText : false }; } } }); return map; } else if (typeof children === 'string') { return { children: { translated: false, text: children, defaultText: defaultText } }; } } var STRING_ONLY = function STRING_ONLY() {}; /** * Default config for {@link i18n/Text.TextDecorator}. * * @memberof i18n/Text.TextDecorator * @hocconfig */ var defaultConfig = { /** * Configures the translated text passed to the wrapped component. * * @type {Object<String, String|Object>} * @default null * @public * @memberof i18n/Text.TextDecorator.defaultConfig */ mapPropsToText: null }; /** * A higher-order component that is used to translate text and provide the translations via props. * * `TextDecorator` accepts an optional `mapPropsToText` config prop which defines the props it will * populate and the text to translate and provide in that prop. `defaultText` can also be provided * when appropriate. * * If translations are not available yet and all props do not include a default value, * `TextDecorator` will render nothing. Once translations are available, the component will update * with the translated strings. * * ``` * TextDecorator({ * mapPropsToText: { * // Always translate "Go" and pass it in the `children` prop * children: 'Go', * // Translate "Go to next page" but pass "" (value always untranslated) while * // waiting for the translated strings to be fetched. * 'aria-label': { * text: 'Go to next page', * defaultText: '' * } * } * }) * ``` * * @class TextDecorator * @memberof i18n/Text * @hoc * @public */ var TextDecorator = exports.TextDecorator = (0, _hoc["default"])(defaultConfig, function (config, Wrapped) { var _Class; var mapPropsToText = config.mapPropsToText; var Decorator = (_Class = /*#__PURE__*/function (_Component) { function Decorator(props) { var _this; _classCallCheck(this, Decorator); _this = _callSuper(this, Decorator, [props]); _this.state = { map: getTextMap(mapPropsToText, props) }; return _this; } _inherits(Decorator, _Component); return _createClass(Decorator, [{ key: "componentDidMount", value: function componentDidMount() { if (this.shouldTranslate()) { this.translate(this.props.locale); } } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { if (this.props.locale !== prevProps.locale) { this.translate(this.props.locale); } } }, { key: "shouldTranslate", value: function shouldTranslate() { return mapPropsToText || typeof this.props.children === 'string'; } }, { key: "translate", value: function translate() { var _this2 = this; var locale = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _ilib["default"].getLocale(); var map = this.state.map; var bundle = (0, _resBundle.getResBundle)(); if (!map) return; var props = Object.keys(map); Promise.all([new Promise(function (resolve) { if (bundle) { resolve(bundle); } (0, _resBundle.createResBundle)({ locale: locale, sync: false, onLoad: resolve }); }), // ResBundle.getString will try to synchronously fetch the plurals resource so need // to proactively fetch it to avoid the sync XHR new Promise(function (resolve) { return _IString["default"].loadPlurals(false, null, null, resolve); })]).then(function (_ref) { var _ref2 = _slicedToArray(_ref, 1), resBundle = _ref2[0]; if (!resBundle) return; var translated = props.reduce(function (obj, prop) { obj[prop].translated = String((0, _resBundle.getIStringFromBundle)(obj[prop].text, resBundle)); return obj; }, _objectSpread({}, map)); _this2.setState({ map: translated }); }); } }, { key: "canRender", value: function canRender() { var entries = Object.values(this.state.map); for (var _i = 0, _entries = entries; _i < _entries.length; _i++) { var entry = _entries[_i]; if (entry.translated === false && entry.defaultText === false) { return false; } } return true; } }, { key: "getTextForProp", value: function getTextForProp(prop) { var _this$state$map$prop = this.state.map[prop], _this$state$map$prop$ = _this$state$map$prop.defaultText, defaultText = _this$state$map$prop$ === void 0 ? '' : _this$state$map$prop$, translated = _this$state$map$prop.translated; return translated === false ? defaultText : translated; } }, { key: "render", value: function render() { var _this3 = this; if (!this.shouldTranslate()) { var passThrough = _objectSpread({}, this.props); delete passThrough.locale; return /*#__PURE__*/(0, _jsxRuntime.jsx)(Wrapped, _objectSpread({}, passThrough)); } if (!this.canRender()) { return null; } if (Wrapped === STRING_ONLY) { return this.getTextForProp('children'); } var props = _objectSpread({}, this.props); delete props.locale; Object.keys(this.state.map).forEach(function (prop) { props[prop] = _this3.getTextForProp(prop); }); return /*#__PURE__*/(0, _jsxRuntime.jsx)(Wrapped, _objectSpread({}, props)); } }]); }(_react.Component), _Class.displayName = 'TextDecorator', _Class.propTypes = /** @lends i18n/Text.TextDecorator.prototype */{ /** * Passed to the wrapped component. * * If `mapPropsToText` is `null` and `children` is a string, the string will be * translated before being passed to the wrapped component. * * @type {*} * @public */ children: _propTypes["default"].any, /** * The locale for translation. * * If not supplied, the current locale is used. * * @type {String} * @public */ locale: _propTypes["default"].string }, _Class); return (0, _I18nDecorator.I18nContextDecorator)({ localeProp: 'locale' }, Decorator); }); /** * Translates its child string value in the current locale. * * If translations are not available yet, `Text` will render nothing. Once translations are * available, the component will update with the translated string. * * ``` * <Text>Go</Text> * ``` * * @class Text * @memberof i18n/Text * @mixes i18n/Text.TextDecorator * @ui * @public */ var Text = exports.Text = TextDecorator(STRING_ONLY); /** * The string to be translated. * * @name children * @memberof i18n/Text.Text.prototype * @type {String} * @public */ var _default = exports["default"] = Text;