UNPKG

@gifyourgame/stream-chat-react

Version:

React components to create chat conversations or livestream style chat

1,239 lines (1,155 loc) 535 kB
import _defineProperty from '@babel/runtime/helpers/defineProperty'; import React, { useRef, useState, useCallback, useEffect, useContext, useMemo, useReducer, useImperativeHandle, Component, Fragment, PureComponent } from 'react'; import { StreamChat, Channel as Channel$2, logChatPromiseExecution } from 'stream-chat'; import _extends from '@babel/runtime/helpers/extends'; import Dayjs from 'dayjs'; import LocalizedFormat from 'dayjs/plugin/localizedFormat'; import emojiRegex from 'emoji-regex'; import ReactMarkdown from 'react-markdown/with-html'; import truncate from 'lodash/truncate'; import data from 'emoji-mart/data/all.json'; import { find } from 'linkifyjs/lib/linkify'; import _regeneratorRuntime from '@babel/runtime/regenerator'; import _asyncToGenerator from '@babel/runtime/helpers/asyncToGenerator'; import _classCallCheck from '@babel/runtime/helpers/classCallCheck'; import _createClass from '@babel/runtime/helpers/createClass'; import i18n from 'i18next'; import calendar from 'dayjs/plugin/calendar'; import updateLocale from 'dayjs/plugin/updateLocale'; import localeData from 'dayjs/plugin/localeData'; import relativeTime from 'dayjs/plugin/relativeTime'; import 'dayjs/locale/nl'; import 'dayjs/locale/ru'; import 'dayjs/locale/tr'; import 'dayjs/locale/fr'; import 'dayjs/locale/hi'; import 'dayjs/locale/it'; import 'dayjs/locale/en'; import Media from 'react-player'; import PropTypes from 'prop-types'; import { v4 } from 'uuid'; import _slicedToArray from '@babel/runtime/helpers/slicedToArray'; import { sanitizeUrl } from '@braintree/sanitize-url'; import { FileIcon, dataTransferItemsToFiles, dataTransferItemsHaveFiles, ImagePreviewer, FilePreviewer, ImageDropzone, FileUploadButton, LoadingIndicator as LoadingIndicator$1 } from 'react-file-utils'; import prettybytes from 'pretty-bytes'; import Carousel, { ModalGateway, Modal as Modal$1 } from 'react-images'; import _assertThisInitialized from '@babel/runtime/helpers/assertThisInitialized'; import _inherits from '@babel/runtime/helpers/inherits'; import _possibleConstructorReturn from '@babel/runtime/helpers/possibleConstructorReturn'; import _getPrototypeOf from '@babel/runtime/helpers/getPrototypeOf'; import getCaretCoordinates from 'textarea-caret'; import CustomEvent from 'custom-event'; import { isValidElementType } from 'react-is'; import Textarea from 'react-textarea-autosize'; import truncate$1 from 'lodash.truncate'; import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray'; import Immutable from 'seamless-immutable'; import Visibility from 'visibilityjs'; import debounce from 'lodash/debounce'; import throttle from 'lodash/throttle'; import { emojiIndex, Picker, NimbleEmoji } from 'emoji-mart'; import debounce$1 from 'lodash.debounce'; import _objectWithoutProperties from '@babel/runtime/helpers/objectWithoutProperties'; import deepequal from 'react-fast-compare'; import uniqBy from 'lodash.uniqby'; function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } /** * @typedef {import('types').ChatContextValue} ChatContext */ var ChatContext = React.createContext( /** @type {ChatContext} */ { client: new StreamChat('') }); /** @param { React.ComponentClass | React.FC } OriginalComponent */ function withChatContext(OriginalComponent) { /** @param {any} props */ var ContextAwareComponent = function ContextComponent(props) { return /*#__PURE__*/React.createElement(ChatContext.Consumer, null, function (context) { var mergedProps = _objectSpread(_objectSpread({}, context), props); return /*#__PURE__*/React.createElement(OriginalComponent, mergedProps); }); }; /** @type {string} */ ContextAwareComponent.displayName = OriginalComponent.displayName || OriginalComponent.name || 'Component'; ContextAwareComponent.displayName = ContextAwareComponent.displayName.replace('Base', ''); return ContextAwareComponent; } /** * @typedef {import('types').ChannelContextValue} ChannelContext */ var ChannelContext = React.createContext( /** @type {ChannelContext} */ {}); /** @param { React.ComponentClass | React.FC } OriginalComponent */ function withChannelContext(OriginalComponent) { /** @param {any} props */ var ContextAwareComponent = function ContextComponent(props) { return /*#__PURE__*/React.createElement(ChannelContext.Consumer, null, function (channelContext) { return /*#__PURE__*/React.createElement(OriginalComponent, _extends({}, channelContext, props)); }); }; /** @type {string} */ ContextAwareComponent.displayName = OriginalComponent.displayName || OriginalComponent.name || 'Component'; ContextAwareComponent.displayName = ContextAwareComponent.displayName.replace('Base', ''); return ContextAwareComponent; } var extendedDayjs = Dayjs.extend(LocalizedFormat); /** @type {React.Context<{ t: import("i18next").TFunction, tDateTimeParser: (msg: string) => Dayjs.Dayjs }>} */ var TranslationContext = React.createContext({ t: /** @param {string} key */ function t(key) { return key; }, tDateTimeParser: function tDateTimeParser(input) { return extendedDayjs(input); } }); function withTranslationContext(OriginalComponent) { var ContextAwareComponent = function ContextComponent(props) { return /*#__PURE__*/React.createElement(TranslationContext.Consumer, null, function (translationContext) { return /*#__PURE__*/React.createElement(OriginalComponent, _extends({}, translationContext, props)); }); }; ContextAwareComponent.displayName = OriginalComponent.displayName || OriginalComponent.name || 'Component'; ContextAwareComponent.displayName = ContextAwareComponent.displayName.replace('Base', ''); return ContextAwareComponent; } function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$1(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } var emojiSetDef = { spriteUrl: 'https://getstream.imgix.net/images/emoji-sprite.png', size: 20, sheetColumns: 2, sheetRows: 3, sheetSize: 64 }; var commonEmoji = { emoticons: [], short_names: [], custom: true }; /** @type {import("types").MinimalEmojiInterface[]} */ var defaultMinimalEmojis = [_objectSpread$1(_objectSpread$1({ id: 'like', name: 'like', colons: ':+1:', sheet_x: 0, sheet_y: 0 }, commonEmoji), emojiSetDef), _objectSpread$1(_objectSpread$1({ id: 'love', name: 'love', colons: ':heart:', sheet_x: 1, sheet_y: 2 }, commonEmoji), emojiSetDef), _objectSpread$1(_objectSpread$1({ id: 'haha', name: 'haha', colons: ':joy:', sheet_x: 1, sheet_y: 0 }, commonEmoji), emojiSetDef), _objectSpread$1(_objectSpread$1({ id: 'wow', name: 'wow', colons: ':astonished:', sheet_x: 0, sheet_y: 2 }, commonEmoji), emojiSetDef), _objectSpread$1(_objectSpread$1({ id: 'sad', name: 'sad', colons: ':pensive:', sheet_x: 0, sheet_y: 1 }, commonEmoji), emojiSetDef), _objectSpread$1(_objectSpread$1({ id: 'angry', name: 'angry', colons: ':angry:', sheet_x: 1, sheet_y: 1 }, commonEmoji), emojiSetDef)]; var d = Object.assign({}, data); d.emojis = {}; // use this only for small lists like in ReactionSelector var emojiData = d; var isOnlyEmojis = function isOnlyEmojis(text) { if (!text) return false; var noEmojis = text.replace(emojiRegex(), ''); var noSpace = noEmojis.replace(/[\s\n]/gm, ''); return !noSpace; }; var isPromise = function isPromise(thing) { return thing && typeof thing.then === 'function'; }; var byDate = function byDate(a, b) { return a.created_at - b.created_at; }; // https://stackoverflow.com/a/29234240/7625485 /** * @deprecated This function is deprecated and will be removed in future major release. * @param {*} dict * @param {*} currentUserId */ var formatArray = function formatArray(dict, currentUserId) { var arr2 = Object.keys(dict); var arr3 = []; arr2.forEach(function (item, i) { if (currentUserId === dict[arr2[i]].user.id) { return; } arr3.push(dict[arr2[i]].user.name || dict[arr2[i]].user.id); }); var outStr = ''; if (arr3.length === 1) { outStr = arr3[0] + ' is typing...'; } else if (arr3.length === 2) { //joins all with "and" but =no commas //example: "bob and sam" outStr = arr3.join(' and ') + ' are typing...'; } else if (arr3.length > 2) { //joins all with commas, but last one gets ", and" (oxford comma!) //example: "bob, joe, and sam" outStr = arr3.slice(0, -1).join(', ') + ', and ' + arr3.slice(-1) + ' are typing...'; } return outStr; }; var allowedMarkups = ['html', 'root', 'text', 'break', 'paragraph', 'emphasis', 'strong', 'link', 'list', 'listItem', 'code', 'inlineCode', 'blockquote', 'delete']; var matchMarkdownLinks = function matchMarkdownLinks(message) { var regexMdLinks = /\[([^\[]+)\](\(.*\))/gm; var matches = message.match(regexMdLinks); var singleMatch = /\[([^\[]+)\]\((.*)\)/; var links = matches ? matches.map(function (match) { return singleMatch.exec(match)[2]; }) : []; return links; }; var renderText = function renderText(message) { // take the @ mentions and turn them into markdown? // translate links var text = message.text, mentioned_users = message.mentioned_users; if (!text) return null; var newText = message.text; var markdownLinks = matchMarkdownLinks(newText); // extract all valid links/emails within text and replace it with proper markup find(newText).forEach(function (_ref) { var type = _ref.type, href = _ref.href, value = _ref.value; // check if message is already markdown var noParsingNeeded = markdownLinks && markdownLinks.filter(function (text) { return text.indexOf(href) !== -1; }); if (noParsingNeeded.length > 0) return; var displayLink = type === 'email' ? value : truncate(value.replace(/(http(s?):\/\/)?(www\.)?/, ''), { length: 20 }); newText = newText.replace(value, "[".concat(displayLink, "](").concat(encodeURI(href), ")")); }); if (mentioned_users && mentioned_users.length) { for (var i = 0; i < mentioned_users.length; i++) { var username = mentioned_users[i].name || mentioned_users[i].id; var mkdown = "**@".concat(username, "**"); var re = new RegExp("@".concat(username), 'g'); newText = newText.replace(re, mkdown); } } return /*#__PURE__*/React.createElement(ReactMarkdown, { allowedTypes: allowedMarkups, source: newText, linkTarget: "_blank", plugins: [], escapeHtml: true, skipHtml: false, unwrapDisallowed: true, transformLinkUri: function transformLinkUri(uri) { if (uri.startsWith('app://')) { return uri; } else { return require('react-markdown').uriTransformer(uri); } } }); }; // https://stackoverflow.com/a/6860916/2570866 function generateRandomId() { // prettier-ignore return S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4(); } function S4() { return ((1 + Math.random()) * 0x10000 | 0).toString(16).substring(1); } var smartRender = function smartRender(ElementOrComponentOrLiteral, props, fallback) { if (ElementOrComponentOrLiteral === undefined) { ElementOrComponentOrLiteral = fallback; } if ( /*#__PURE__*/React.isValidElement(ElementOrComponentOrLiteral)) { // Flow cast through any, to make flow believe it's a React.Element var element = ElementOrComponentOrLiteral; // eslint-disable-line return element; } // Flow cast through any to remove React.Element after previous check var ComponentOrLiteral = ElementOrComponentOrLiteral; if (typeof ComponentOrLiteral === 'string' || typeof ComponentOrLiteral === 'number' || typeof ComponentOrLiteral === 'boolean' || ComponentOrLiteral == null) { return ComponentOrLiteral; } return /*#__PURE__*/React.createElement(ComponentOrLiteral, props); }; var filterEmoji = function filterEmoji(emoji) { if (emoji.name === 'White Smiling Face' || emoji.name === 'White Frowning Face') { return false; } return true; }; var getReadByTooltipText = function getReadByTooltipText(users, t, client) { var outStr = ''; // first filter out client user, so restLength won't count it var otherUsers = users.filter(function (item) { return item && item.id !== client.user.id; }).map(function (item) { return item.name || item.id; }); var slicedArr = otherUsers.slice(0, 5); var restLength = otherUsers.length - slicedArr.length; if (slicedArr.length === 1) { outStr = slicedArr[0] + ' '; } else if (slicedArr.length === 2) { //joins all with "and" but =no commas //example: "bob and sam" outStr = t('{{ firstUser }} and {{ secondUser }}', { firstUser: slicedArr[0], secondUser: slicedArr[1] }); } else if (slicedArr.length > 2) { //joins all with commas, but last one gets ", and" (oxford comma!) //example: "bob, joe, sam and 4 more" if (restLength === 0) { // mutate slicedArr to remove last user to display it separately var lastUser = slicedArr.splice(slicedArr.length - 2, 1); outStr = t('{{ commaSeparatedUsers }}, and {{ lastUser }}', { commaSeparatedUsers: slicedArr.join(', '), lastUser }); } else { outStr = t('{{ commaSeparatedUsers }} and {{ moreCount }} more', { commaSeparatedUsers: slicedArr.join(', '), moreCount: restLength }); } } return outStr; }; var Cancel = "Cancel"; var Close = "Close"; var Delete = "Delete"; var Delivered = "Delivered"; var Flag = "Flag"; var Mute = "Mute"; var Send = "Send"; var Thread = "Thread"; var Unmute = "Unmute"; var live = "live"; var enTranslations = { "1 reply": "1 reply", "Attach files": "Attach files", Cancel: Cancel, "Channel Missing": "Channel Missing", Close: Close, "Connection failure, reconnecting now...": "Connection failure, reconnecting now...", Delete: Delete, Delivered: Delivered, "Edit Message": "Edit Message", "Empty message...": "Empty message...", "Error adding flag: Either the flag already exist or there is issue with network connection ...": "Error adding flag: Either the flag already exist or there is issue with network connection ...", "Error banning user...": "Error banning user...", "Error connecting to chat, refresh the page to try again.": "Error connecting to chat, refresh the page to try again.", "Error muting a user ...": "Error muting a user ...", "Error unmuting a user ...": "Error unmuting a user ...", "Error · Unsent": "Error · Unsent", "Error: {{ errorMessage }}": "Error: {{ errorMessage }}", Flag: Flag, "Message Failed · Click to try again": "Message Failed · Click to try again", "Message deleted": "Message deleted", "Message failed. Click to try again.": "Message failed. Click to try again.", "Message has been successfully flagged": "Message has been successfully flagged", Mute: Mute, "New Messages!": "New Messages!", "Nothing yet...": "Nothing yet...", "Only visible to you": "Only visible to you", "Open emoji picker": "Open emoji picker", "Pick your emoji": "Pick your emoji", Send: Send, "Sending...": "Sending...", "Start of a new thread": "Start of a new thread", "This message was deleted...": "This message was deleted...", Thread: Thread, "Type your message": "Type your message", Unmute: Unmute, "You have no channels currently": "You have no channels currently", live: live, "this content could not be displayed": "this content could not be displayed", "{{ commaSeparatedUsers }} and {{ lastUser }} are typing...": "{{ commaSeparatedUsers }} and {{ lastUser }} are typing...", "{{ commaSeparatedUsers }} and {{ moreCount }} more": "{{ commaSeparatedUsers }} and {{ moreCount }} more", "{{ commaSeparatedUsers }}, and {{ lastUser }}": "{{ commaSeparatedUsers }}, and {{ lastUser }}", "{{ firstUser }} and {{ secondUser }}": "{{ firstUser }} and {{ secondUser }}", "{{ firstUser }} and {{ secondUser }} are typing...": "{{ firstUser }} and {{ secondUser }} are typing...", "{{ imageCount }} more": "{{ imageCount }} more", "{{ memberCount }} members": "{{ memberCount }} members", "{{ replyCount }} replies": "{{ replyCount }} replies", "{{ user }} has been banned": "{{ user }} has been banned", "{{ user }} has been muted": "{{ user }} has been muted", "{{ user }} has been unmuted": "{{ user }} has been unmuted", "{{ user }} is typing...": "{{ user }} is typing...", "{{ watcherCount }} online": "{{ watcherCount }} online", "🏙 Attachment...": "🏙 Attachment..." }; var Cancel$1 = "Annuleer"; var Close$1 = "Sluit"; var Delete$1 = "Verwijder"; var Delivered$1 = "Afgeleverd"; var Flag$1 = "Markeer"; var Mute$1 = "Mute"; var Send$1 = "Verstuur"; var Thread$1 = "Draadje"; var Unmute$1 = "Unmute"; var live$1 = "live"; var nlTranslations = { "1 reply": "1 antwoord", "Attach files": "Bijlage toevoegen", Cancel: Cancel$1, "Channel Missing": "Kanaal niet gevonden", Close: Close$1, "Connection failure, reconnecting now...": "Probleem met de verbinding, opnieuw verbinding maken...", Delete: Delete$1, Delivered: Delivered$1, "Edit Message": "Pas bericht aan", "Empty message...": "Leeg bericht...", "Error adding flag: Either the flag already exist or there is issue with network connection ...": "Fout bij het markeren: of het bericht is al gemarkeerd of er is een probleem met de netwerk verbinding", "Error banning user...": "", "Error connecting to chat, refresh the page to try again.": "Fout bij het verbinden, ververs de pagina om nogmaals te proberen", "Error muting a user ...": "Fout bij het muten van de gebruiker", "Error unmuting a user ...": "Fout bij het unmuten van de gebruiker", "Error · Unsent": "Error: · niet verzonden", "Error: {{ errorMessage }}": "Error: {{ errorMessage }}", Flag: Flag$1, "Message Failed · Click to try again": "Bericht mislukt, klik om het nogmaals te proberen", "Message deleted": "Bericht verwijderd", "Message failed. Click to try again.": "Bericht mislukt, klik om het nogmaals te proberen", "Message has been successfully flagged": "Bericht is succesvol gemarkeerd", Mute: Mute$1, "New Messages!": "Nieuwe Berichten!", "Nothing yet...": "Nog niets ...", "Only visible to you": "Alleen zichtbaar voor jou", "Open emoji picker": "Open emojipicker", "Pick your emoji": "Kies je emoji", Send: Send$1, "Sending...": "Aan het verzenden...", "Start of a new thread": "Begin van een nieuwe draadje", "This message was deleted...": "Dit bericht was verwijderd", Thread: Thread$1, "Type your message": "Type je bericht", Unmute: Unmute$1, "You have no channels currently": "Er zijn geen chats beschikbaar", live: live$1, "this content could not be displayed": "Deze inhoud kan niet weergegeven worden", "{{ commaSeparatedUsers }} and {{ lastUser }} are typing...": "{{ commaSeparatedUsers }} en {{ lastUser }} zijn aan het typen ...", "{{ commaSeparatedUsers }} and {{ moreCount }} more": "{{ commaSeparatedUsers }} en {{ moreCount }} meer", "{{ commaSeparatedUsers }}, and {{ lastUser }}": "{{ commaSeparatedUsers }} en {{ lastUser }}", "{{ firstUser }} and {{ secondUser }}": "{{ firstUser }} en {{ secondUser }}", "{{ firstUser }} and {{ secondUser }} are typing...": "{{ firstUser }} en {{ secondUser }} zijn aan het typen ...", "{{ imageCount }} more": "+{{ imageCount }}", "{{ memberCount }} members": "{{ memberCount }} deelnemers", "{{ replyCount }} replies": "{{ replyCount }} antwoorden", "{{ user }} has been banned": "", "{{ user }} has been muted": "{{ user }} is muted", "{{ user }} has been unmuted": "{{ user }} is unmuted", "{{ user }} is typing...": "{{ user }} is aan het typen...", "{{ watcherCount }} online": "{{ watcherCount }} online", "🏙 Attachment...": "🏙 Bijlage..." }; var Cancel$2 = "Отмена"; var Close$2 = "Закрыть"; var Delete$2 = "Удалить"; var Delivered$2 = "Отправлено"; var Flag$2 = "Пожаловаться"; var Mute$2 = "Отключить уведомления"; var Send$2 = "Отправить"; var Thread$2 = "Ветка"; var Unmute$2 = "Включить уведомления"; var live$2 = "В прямом эфире"; var ruTranslations = { "1 reply": "1 ответ", "Attach files": "Прикрепить файлы", Cancel: Cancel$2, "Channel Missing": "Канал не найден", Close: Close$2, "Connection failure, reconnecting now...": "Ошибка соединения, переподключение...", Delete: Delete$2, Delivered: Delivered$2, "Edit Message": "Редактировать сообщение", "Empty message...": "Пустое сообщение...", "Error adding flag: Either the flag already exist or there is issue with network connection ...": "Ошибка добавления флага: флаг уже существует или ошибка подключения к сети...", "Error banning user...": "", "Error connecting to chat, refresh the page to try again.": "Ошибка подключения к чату, обновите страницу чтобы попробовать снова.", "Error muting a user ...": "Ошибка отключения уведомлений от пользователя...", "Error unmuting a user ...": "Ошибка включения уведомлений...", "Error · Unsent": "Ошибка · Не отправлено", "Error: {{ errorMessage }}": "Ошибка: {{ errorMessage }}", Flag: Flag$2, "Message Failed · Click to try again": "Ошибка отправки сообщения · Нажмите чтобы повторить", "Message deleted": "Сообщение удалено", "Message failed. Click to try again.": "Ошибка отправки сообщения · Нажмите чтобы повторить", "Message has been successfully flagged": "Жалоба на сообщение была принята", Mute: Mute$2, "New Messages!": "Новые сообщения!", "Nothing yet...": "Пока ничего нет...", "Only visible to you": "Только видно для вас", "Open emoji picker": "Выбрать emoji", "Pick your emoji": "Выберите свой emoji", Send: Send$2, "Sending...": "Отправка...", "Start of a new thread": "Начало новой ветки", "This message was deleted...": "Сообщение было удалено...", Thread: Thread$2, "Type your message": "Ваше сообщение", Unmute: Unmute$2, "You have no channels currently": "У вас нет каналов в данный момент", live: live$2, "this content could not be displayed": "Этот контент не может быть отображен в данный момент", "{{ commaSeparatedUsers }} and {{ lastUser }} are typing...": "{{ commaSeparatedUsers }} и {{ lastUser }} пишут...", "{{ commaSeparatedUsers }} and {{ moreCount }} more": "{{ commaSeparatedUsers }} и {{ moreCount }} еще", "{{ commaSeparatedUsers }}, and {{ lastUser }}": "{{ commaSeparatedUsers }} и {{ lastUser }}", "{{ firstUser }} and {{ secondUser }}": "{{ firstUser }} и {{ secondUser }}", "{{ firstUser }} and {{ secondUser }} are typing...": "{{ firstUser }} и {{ secondUser }} пишут...", "{{ imageCount }} more": "Ещё {{ imageCount }}", "{{ memberCount }} members": "{{ memberCount }} члены", "{{ replyCount }} replies": "{{ replyCount }} ответов", "{{ user }} has been banned": "", "{{ user }} has been muted": "Вы отписались от уведомлений от {{ user }}", "{{ user }} has been unmuted": "Уведомления от {{ user }} были включены", "{{ user }} is typing...": "{{ user }} пишет...", "{{ watcherCount }} online": "{{ watcherCount }} в сети", "🏙 Attachment...": "🏙 Вложение..." }; var Cancel$3 = "İptal"; var Close$3 = "Kapat"; var Delete$3 = "Sil"; var Delivered$3 = "İletildi"; var Flag$3 = "Bayrak"; var Mute$3 = "Sessiz"; var Send$3 = "Gönder"; var Thread$3 = "Konu"; var Unmute$3 = "Sesini aç"; var live$3 = "canlı"; var trTranslations = { "1 reply": "1 cevap", "Attach files": "Dosya ekle", Cancel: Cancel$3, "Channel Missing": "Kanal bulunamıyor", Close: Close$3, "Connection failure, reconnecting now...": "Bağlantı hatası, tekrar bağlanılıyor...", Delete: Delete$3, Delivered: Delivered$3, "Edit Message": "Mesajı Düzenle", "Empty message...": "Boş mesaj...", "Error adding flag: Either the flag already exist or there is issue with network connection ...": "Bayraklama hatası: Bayrak zaten var veya bağlantı sorunlu", "Error banning user...": "", "Error connecting to chat, refresh the page to try again.": "Bağlantı hatası, sayfayı yenileyip tekrar deneyin.", "Error muting a user ...": "Kullanıcıyı sessize alırken hata oluştu ...", "Error unmuting a user ...": "Kullanıcının sesini açarken hata oluştu ...", "Error · Unsent": "Hata · Gönderilemedi", "Error: {{ errorMessage }}": "Hata: {{ errorMessage }}", Flag: Flag$3, "Message Failed · Click to try again": "Mesaj Başarısız · Tekrar denemek için tıklayın", "Message deleted": "Mesaj silindi", "Message failed. Click to try again.": "Mesaj başarısız oldu. Tekrar denemek için tıklayın", "Message has been successfully flagged": "Mesaj başarıyla bayraklandı", Mute: Mute$3, "New Messages!": "Yeni Mesajlar!", "Nothing yet...": "Şimdilik hiçbir şey...", "Only visible to you": "Sadece size görünür", "Open emoji picker": "Emoji klavyesini aç", "Pick your emoji": "Emoji seçin", Send: Send$3, "Sending...": "Gönderiliyor...", "Start of a new thread": "Yeni konunun başı", "This message was deleted...": "Bu mesaj silindi", Thread: Thread$3, "Type your message": "Mesajınızı yazın", Unmute: Unmute$3, "You have no channels currently": "Henüz kanalınız yok", live: live$3, "this content could not be displayed": "bu içerik gösterilemiyor", "{{ commaSeparatedUsers }} and {{ lastUser }} are typing...": "{{ commaSeparatedUsers }} ve {{ lastUser }} yazıyor...", "{{ commaSeparatedUsers }} and {{ moreCount }} more": "{{ commaSeparatedUsers }} ve {{ moreCount }} daha", "{{ commaSeparatedUsers }}, and {{ lastUser }}": "{{ commaSeparatedUsers }}, ve {{ lastUser }}", "{{ firstUser }} and {{ secondUser }}": "{{ firstUser }} ve {{ secondUser }}", "{{ firstUser }} and {{ secondUser }} are typing...": "{{ firstUser }} ve {{ secondUser }} yazıyor...", "{{ imageCount }} more": "{{ imageCount }} adet daha", "{{ memberCount }} members": "{{ memberCount }} üyeler", "{{ replyCount }} replies": "{{ replyCount }} cevaplar", "{{ user }} has been banned": "", "{{ user }} has been muted": "{{ user }} sessize alındı", "{{ user }} has been unmuted": "{{ user }} sesi açıldı", "{{ user }} is typing...": "{{ user }} yazıyor...", "{{ watcherCount }} online": "{{ watcherCount }} çevrimiçi", "🏙 Attachment...": "🏙 Ek..." }; var Cancel$4 = "Annuler"; var Close$4 = "Fermer"; var Delete$4 = "Supprimer"; var Delivered$4 = "Publié"; var Flag$4 = "Signaler"; var Mute$4 = "Muet"; var Send$4 = "Envoyer"; var Thread$4 = "Fil de discussion"; var Unmute$4 = "Désactiver muet"; var live$4 = "en direct"; var frTranslations = { "1 reply": "1 réponse", "Attach files": "Pièces jointes", Cancel: Cancel$4, "Channel Missing": "Canal Manquant", Close: Close$4, "Connection failure, reconnecting now...": "Échec de la connexion, reconnexion en cours...", Delete: Delete$4, Delivered: Delivered$4, "Edit Message": "Éditer un message", "Empty message...": "Message vide...", "Error adding flag: Either the flag already exist or there is issue with network connection ...": "Erreur d'ajout du flag : le flag existe déjà ou vous rencontrez un problème de connexion au réseau ...", "Error banning user...": "", "Error connecting to chat, refresh the page to try again.": "Erreur de connexion au chat, rafraîchissez la page pour réessayer.", "Error muting a user ...": "Erreur de mise en sourdine d'un utilisateur ...", "Error unmuting a user ...": "Erreur de désactivation de la fonction sourdine pour un utilisateur ...", "Error · Unsent": "Erreur - Non envoyé", "Error: {{ errorMessage }}": "Erreur : {{ errorMessage }}", Flag: Flag$4, "Message Failed · Click to try again": "Échec de l'envoi du message - Cliquez pour réessayer", "Message deleted": "Message supprimé", "Message failed. Click to try again.": "Échec de l'envoi du message - Cliquez pour réessayer", "Message has been successfully flagged": "Le message a été signalé avec succès", Mute: Mute$4, "New Messages!": "Nouveaux Messages!", "Nothing yet...": "Aucun message...", "Only visible to you": "Visible uniquement pour vous", "Open emoji picker": "Ouvrez le sélecteur d'emoji", "Pick your emoji": "Choisissez votre emoji", Send: Send$4, "Sending...": "Envoi en cours...", "Start of a new thread": "Début d'un nouveau fil de discussion", "This message was deleted...": "Ce message a été supprimé...", Thread: Thread$4, "Type your message": "Saisissez votre message", Unmute: Unmute$4, "You have no channels currently": "Vous n'avez actuellement aucun canal", live: live$4, "this content could not be displayed": "ce contenu n'a pu être affiché", "{{ commaSeparatedUsers }} and {{ lastUser }} are typing...": "{{ commaSeparatedUsers }} et {{ lastUser }} sont en train d'écrire...", "{{ commaSeparatedUsers }} and {{ moreCount }} more": "{{ commaSeparatedUsers }} et {{ moreCount }} autres", "{{ commaSeparatedUsers }}, and {{ lastUser }}": "{{ commaSeparatedUsers }} et {{ lastUser }}", "{{ firstUser }} and {{ secondUser }}": "{{ firstUser }} et {{ secondUser }}", "{{ firstUser }} and {{ secondUser }} are typing...": "{{ firstUser }} et {{ secondUser }} sont en train d'écrire...", "{{ imageCount }} more": "{{ imageCount }} supplémentaires", "{{ memberCount }} members": "{{ memberCount }} membres", "{{ replyCount }} replies": "{{ replyCount }} réponses", "{{ user }} has been banned": "", "{{ user }} has been muted": "{{ user }} a été mis en sourdine", "{{ user }} has been unmuted": "{{ user }} n'est plus en sourdine", "{{ user }} is typing...": "{{ user }} est en train d'écrire...", "{{ watcherCount }} online": "{{ watcherCount }} en ligne", "🏙 Attachment...": "🏙 Pièce jointe..." }; var Cancel$5 = "रद्द करें"; var Close$5 = "बंद करे"; var Delete$5 = "डिलीट"; var Delivered$5 = "पहुंच गया"; var Flag$5 = "फ्लैग करे"; var Mute$5 = "म्यूट करे"; var Send$5 = "भेजे"; var Thread$5 = "रिप्लाई थ्रेड"; var Unmute$5 = "अनम्यूट"; var live$5 = "लाइव"; var hiTranslations = { "1 reply": "1 रिप्लाई", "Attach files": "फाइल्स अटैच करे", Cancel: Cancel$5, "Channel Missing": "चैनल उपलब्ध नहीं है", Close: Close$5, "Connection failure, reconnecting now...": "कनेक्शन विफल रहा, अब पुनः कनेक्ट हो रहा है ...", Delete: Delete$5, Delivered: Delivered$5, "Edit Message": "मैसेज में बदलाव करे", "Empty message...": "खाली संदेश ...", "Error adding flag: Either the flag already exist or there is issue with network connection ...": "फ़ैल: या तो यह मैसेज के ऊपर पहले से फ्लैग है या तो आपके इंटरनेट कनेक्शन में कुछ परेशानी है", "Error banning user...": "", "Error connecting to chat, refresh the page to try again.": "चैट से कनेक्ट करने में त्रुटि, पेज को रिफ्रेश करें", "Error muting a user ...": "यूजर को म्यूट करने का प्रयास फेल हुआ", "Error unmuting a user ...": "यूजर को अनम्यूट करने का प्रयास फेल हुआ", "Error · Unsent": "फेल", "Error: {{ errorMessage }}": "फेल: {{ errorMessage }}", Flag: Flag$5, "Message Failed · Click to try again": "मैसेज फ़ैल - पुनः कोशिश करें", "Message deleted": "मैसेज हटा दिया गया", "Message failed. Click to try again.": "मैसेज फ़ैल - पुनः कोशिश करें", "Message has been successfully flagged": "मैसेज को फ्लैग कर दिया गया है", Mute: Mute$5, "New Messages!": "नए मैसेज!", "Nothing yet...": "कोई मैसेज नहीं है", "Only visible to you": "सिर्फ आपको दिखाई दे रहा है", "Open emoji picker": "इमोजी पिकर खोलिये", "Pick your emoji": "इमोजी चूस करे", Send: Send$5, "Sending...": "भेजा जा रहा है", "Start of a new thread": "एक नए थ्रेड की शुरुआत", "This message was deleted...": "मैसेज हटा दिया गया", Thread: Thread$5, "Type your message": "अपना मैसेज लिखे", Unmute: Unmute$5, "You have no channels currently": "आपके पास कोई चैनल नहीं है", live: live$5, "this content could not be displayed": "यह कॉन्टेंट लोड नहीं हो पाया", "{{ commaSeparatedUsers }} and {{ lastUser }} are typing...": "{{ commaSeparatedUsers }} और {{ lastUser }} टाइप कर रहे हैं...", "{{ commaSeparatedUsers }} and {{ moreCount }} more": "{{ commaSeparatedUsers }} और {{ moreCount }} और", "{{ commaSeparatedUsers }}, and {{ lastUser }}": "{{ commaSeparatedUsers }} और {{ lastUser }}", "{{ firstUser }} and {{ secondUser }}": "{{ firstUser }} और {{ secondUser }}", "{{ firstUser }} and {{ secondUser }} are typing...": "{{ firstUser }} और {{ secondUser }} टाइप कर रहे हैं...", "{{ imageCount }} more": "{{ imageCount }} और", "{{ memberCount }} members": "{{ memberCount }} मेंबर्स", "{{ replyCount }} replies": "{{ replyCount }} रिप्लाई", "{{ user }} has been banned": "", "{{ user }} has been muted": "{{ user }} को म्यूट कर दिया गया है", "{{ user }} has been unmuted": "{{ user }} को अनम्यूट कर दिया गया है", "{{ user }} is typing...": "{{ user }} टाइप कर रहा है...", "{{ watcherCount }} online": "{{ watcherCount }} online", "🏙 Attachment...": "🏙 अटैचमेंट" }; var Cancel$6 = "Annulla"; var Close$6 = "Chiudi"; var Delete$6 = "Cancella"; var Delivered$6 = "Consegnato"; var Flag$6 = "Segnala"; var Mute$6 = "Silenzia"; var Send$6 = "Invia"; var Thread$6 = "Thread"; var Unmute$6 = "Riattiva le notifiche"; var live$6 = "live"; var itTranslations = { "1 reply": "Una risposta", "Attach files": "Allega file", Cancel: Cancel$6, "Channel Missing": "Il canale non esiste", Close: Close$6, "Connection failure, reconnecting now...": "Connessione fallitta, riconnessione in corso...", Delete: Delete$6, Delivered: Delivered$6, "Edit Message": "Modifica messaggio", "Empty message...": "Message vuoto...", "Error adding flag: Either the flag already exist or there is issue with network connection ...": "Errore durante la segnalazione: la segnalazione esiste giá o c'é un problema di connessione ...", "Error banning user...": "", "Error connecting to chat, refresh the page to try again.": "Errore di connessione alla chat, aggiorna la pagina per riprovare", "Error muting a user ...": "Errore silenziando un utente ...", "Error unmuting a user ...": "Errore riattivando le notifiche per l'utente ...", "Error · Unsent": "Errore · Non inviato", "Error: {{ errorMessage }}": "Errore: {{ errorMessage }}", Flag: Flag$6, "Message Failed · Click to try again": "Invio messaggio fallito · Clicca per riprovare", "Message deleted": "Messaggio cancellato", "Message failed. Click to try again.": "Invio messaggio fallito. Clicca per riprovare.", "Message has been successfully flagged": "Il messaggio é stato segnalato con successo", Mute: Mute$6, "New Messages!": "Nuovo messaggio!", "Nothing yet...": "Ancora niente...", "Only visible to you": "Visibile soltanto da te", "Open emoji picker": "Apri il selettore dellle emoji", "Pick your emoji": "Scegli la tua emoji", Send: Send$6, "Sending...": "Invio in corso...", "Start of a new thread": "Inizia un nuovo thread", "This message was deleted...": "Questo messaggio é stato cancellato", Thread: Thread$6, "Type your message": "Scrivi il tuo messaggio", Unmute: Unmute$6, "You have no channels currently": "Al momento non sono presenti canali", live: live$6, "this content could not be displayed": "questo contenuto non puó essere mostrato", "{{ commaSeparatedUsers }} and {{ lastUser }} are typing...": "{{ commaSeparatedUsers }} e {{ lastUser }} stanno scrivendo...", "{{ commaSeparatedUsers }} and {{ moreCount }} more": "{{ commaSeparatedUsers }} e altri {{ moreCount }}", "{{ commaSeparatedUsers }}, and {{ lastUser }}": "{{ commaSeparatedUsers }} e {{ lastUser }}", "{{ firstUser }} and {{ secondUser }}": "{{ firstUser }} e {{ secondUser }}", "{{ firstUser }} and {{ secondUser }} are typing...": "{{ firstUser }} e {{ secondUser }} stanno scrivendo...", "{{ imageCount }} more": "+ {{ imageCount }}", "{{ memberCount }} members": "{{ memberCount }} membri", "{{ replyCount }} replies": "{{ replyCount }} risposte", "{{ user }} has been banned": "", "{{ user }} has been muted": "{{ user }} é stato silenziato", "{{ user }} has been unmuted": "Notifiche riattivate per {{ user }}", "{{ user }} is typing...": "{{ user }} sta scrivendo...", "{{ watcherCount }} online": "{{ watcherCount }} online", "🏙 Attachment...": "🏙 Allegato..." }; function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread$2(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys$2(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } var defaultNS = 'translation'; var defaultLng = 'en'; Dayjs.extend(updateLocale); Dayjs.updateLocale('nl', { calendar: { sameDay: '[vandaag om] LT', nextDay: '[morgen om] LT', nextWeek: 'dddd [om] LT', lastDay: '[gisteren om] LT', lastWeek: '[afgelopen] dddd [om] LT', sameElse: 'L' } }); Dayjs.updateLocale('it', { calendar: { sameDay: '[Oggi alle] LT', nextDay: '[Domani alle] LT', nextWeek: 'dddd [alle] LT', lastDay: '[Ieri alle] LT', lastWeek: '[lo scorso] dddd [alle] LT', sameElse: 'L' } }); Dayjs.updateLocale('hi', { calendar: { sameDay: '[आज] LT', nextDay: '[कल] LT', nextWeek: 'dddd, LT', lastDay: '[कल] LT', lastWeek: '[पिछले] dddd, LT', sameElse: 'L' }, // Hindi notation for meridiems are quite fuzzy in practice. While there exists // a rigid notion of a 'Pahar' it is not used as rigidly in modern Hindi. meridiemParse: /रात|सुबह|दोपहर|शाम/, meridiemHour(hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'रात') { return hour < 4 ? hour : hour + 12; } else if (meridiem === 'सुबह') { return hour; } else if (meridiem === 'दोपहर') { return hour >= 10 ? hour : hour + 12; } else if (meridiem === 'शाम') { return hour + 12; } }, meridiem(hour) { if (hour < 4) { return 'रात'; } else if (hour < 10) { return 'सुबह'; } else if (hour < 17) { return 'दोपहर'; } else if (hour < 20) { return 'शाम'; } else { return 'रात'; } } }); Dayjs.updateLocale('fr', { calendar: { sameDay: '[Aujourd’hui à] LT', nextDay: '[Demain à] LT', nextWeek: 'dddd [à] LT', lastDay: '[Hier à] LT', lastWeek: 'dddd [dernier à] LT', sameElse: 'L' } }); Dayjs.updateLocale('tr', { calendar: { sameDay: '[bugün saat] LT', nextDay: '[yarın saat] LT', nextWeek: '[gelecek] dddd [saat] LT', lastDay: '[dün] LT', lastWeek: '[geçen] dddd [saat] LT', sameElse: 'L' } }); Dayjs.updateLocale('ru', { calendar: { sameDay: '[Сегодня, в] LT', nextDay: '[Завтра, в] LT', lastDay: '[Вчера, в] LT' } }); var en_locale = { weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_') }; /** * Wrapper around [i18next](https://www.i18next.com/) class for Stream related translations. * Instance of this class should be provided to Chat component to handle translations. * Stream provides following list of in-built translations: * 1. English (en) * 2. Dutch (nl) * 3. Russian (ru) * 4. Turkish (tr) * 5. French (fr) * 6. Italian (it) * 7. Hindi (hi) * * Simplest way to start using chat components in one of the in-built languages would be following: * * ``` * const i18n = new Streami18n({ language 'nl' }); * <Chat client={chatClient} i18nInstance={i18n}> * ... * </Chat> * ``` * * If you would like to override certain keys in in-built translation. * UI will be automatically updated in this case. * * ``` * const i18n = new Streami18n({ * language: 'nl', * translationsForLanguage: { * 'Nothing yet...': 'Nog Niet ...', * '{{ firstUser }} and {{ secondUser }} are typing...': '{{ firstUser }} en {{ secondUser }} zijn aan het typen...', * } * }); * * If you would like to register additional languages, use registerTranslation. You can add as many languages as you want: * * i18n.registerTranslation('zh', { * 'Nothing yet...': 'Nog Niet ...', * '{{ firstUser }} and {{ secondUser }} are typing...': '{{ firstUser }} en {{ secondUser }} zijn aan het typen...', * }); * * <Chat client={chatClient} i18nInstance={i18n}> * ... * </Chat> * ``` * * You can use the same function to add whole new language as well. * * ``` * const i18n = new Streami18n(); * * i18n.registerTranslation('mr', { * 'Nothing yet...': 'काहीही नाही ...', * '{{ firstUser }} and {{ secondUser }} are typing...': '{{ firstUser }} आणि {{ secondUser }} टीपी करत आहेत ', * }); * * // Make sure to call setLanguage to reflect new language in UI. * i18n.setLanguage('it'); * <Chat client={chatClient} i18nInstance={i18n}> * ... * </Chat> * ``` * * ## Datetime translations * * Stream react chat components uses [dayjs](https://day.js.org/en/) internally by default to format datetime stamp. * e.g., in ChannelPreview, MessageContent components. * Dayjs has locale support as well - https://day.js.org/docs/en/i18n/i18n * Dayjs is a lightweight alternative to Momentjs with the same modern API. * * Dayjs provides locale config for plenty of languages, you can check the whole list of locale configs at following url * https://github.com/iamkun/dayjs/tree/dev/src/locale * * You can either provide the dayjs locale config while registering * language with Streami18n (either via constructor or registerTranslation()) or you can provide your own Dayjs or Moment instance * to Streami18n constructor, which will be then used internally (using the language locale) in components. * * 1. Via language registration * * e.g., * ``` * const i18n = new Streami18n({ * language: 'nl', * dayjsLocaleConfigForLanguage: { * months: [...], * monthsShort: [...], * calendar: { * sameDay: ...' * } * } * }); * ``` * * Similarly, you can add locale config for moment while registering translation via `registerTranslation` function. * * e.g., * ``` * const i18n = new Streami18n(); * * i18n.registerTranslation( * 'mr', * { * 'Nothing yet...': 'काहीही नाही ...', * '{{ firstUser }} and {{ secondUser }} are typing...': '{{ firstUser }} आणि {{ secondUser }} टीपी करत आहेत ', * }, * { * months: [...], * monthsShort: [...], * calendar: { * sameDay: ...' * } * } * ); *``` * 2. Provide your own Moment object * * ```js * import 'moment/locale/nl'; * import 'moment/locale/it'; * // or if you want to include all locales * import 'moment/min/locales'; * * import Moment from moment * * const i18n = new Streami18n({ * language: 'nl', * DateTimeParser: Moment * }) * ``` * * 3. Provide your own Dayjs object * * ```js * import Dayjs from 'dayjs' * * import 'dayjs/locale/nl'; * import 'dayjs/locale/it'; * // or if you want to include all locales * import 'dayjs/min/locales'; * * const i18n = new Streami18n({ * language: 'nl', * DateTimeParser: Dayjs * }) * ``` * If you would like to stick with english language for datetimes in Stream compoments, you can set `disableDateTimeTranslations` to true. * */ var defaultStreami18nOptions = { language: 'en', disableDateTimeTranslations: false, debug: false, logger: function logger(msg) { return console.warn(msg); }, dayjsLocaleConfigForLanguage: null, DateTimeParser: Dayjs }; var Streami18n = /*#__PURE__*/function () { /** * dayjs.defineLanguage('nl') also changes the global locale. We don't want to do that * when user calls registerTranslation() function. So intead we will store the locale configs * given to registerTranslation() function in `dayjsLocales` object, and register the required locale * with moment, when setLanguage is called. * */ /** * Contructor accepts following options: * - language (String) default: 'en' * Language code e.g., en, tr * * - translationsForLanguage (object) * Translations object. Please check src/i18n/en.json for example. * * - disableDateTimeTranslations (boolean) default: false * Disable translations for datetimes * * - debug (boolean) default: false * Enable debug mode in internal i18n class * * - logger (function) default: () => {} * Logger function to log warnings/errors from this class * * - dayjsLocaleConfigForLanguage (object) default: 'enConfig' * [Config object](https://momentjs.com/docs/#/i18n/changing-locale/) for internal moment object, * corresponding to language (param) * * - DateTimeParser (function) Moment or Dayjs instance/function. * Make sure to load all the required locales in this Moment or Dayjs instance that you will be provide to Streami18n * * @param {*} options */ function Streami18n() { var _this = this; var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, Streami18n); _defineProperty(this, "i18nInstance", i18n.createInstance()); _defineProperty(this, "Dayjs", null); _defineProperty(this, "setLanguageCallback", function () { return null; }); _defineProperty(this, "initialized", false); _defineProperty(this, "t", null); _defineProperty(this, "tDateTimeParser", null); _defineProperty(this, "translations", { en: { [defaultNS]: enTranslations }, nl: { [defaultNS]: nlTranslations }, ru: { [defaultNS]: ruTranslations }, tr: { [defaultNS]: trTranslations }, fr: { [defaultNS]: frTranslations }, hi: { [defaultNS]: hiTranslations }, it: { [defaultNS]: itTranslations } }); _defineProperty(this, "dayjsLocales", {}); _defineProperty(this, "localeExists", function (language) { if (_this.isCustomDateTimeParser) return true; return Object.keys(Dayjs.Ls).indexOf(language) > -1; }); _defineProperty(this, "validateCurrentLanguage", function () { var availableLanguages = Object.keys(_this.translations); if (availableLanguages.indexOf(_this.currentLanguage) === -1) { _this.logger("Streami18n: '".concat(_this.currentLanguage, "' language is not registered.") + " Please make sure to call streami18n.registerTranslation('".concat(_this.currentLanguage, "', {...}) or ") + "use one the built-in supported languages - ".concat(_this.getAvailableLanguages())); _this.currentLanguage = defaultLng; } }); _defineProperty(this, "geti18Instance", function () { return _this.i18nInstance; }); _defineProperty(this, "getAvailableLanguages", function () { return Object.keys(_this.translations); }); _defineProperty(this, "getTranslations", function () { return _this.translations; }); var finalOptions = _objectSpread$2(_objectSpread$2({}, defaultStreami18nOptions), options); // Prepare the i18next configuration. this.logger = finalOptions.logger; this.currentLanguage = finalOptions.language; this.DateTimeParser = finalOptions.DateTimeParser; try { // This is a shallow check to see if given parser is instance of Dayjs. // For some reason Dayjs.isDayjs(this.DateTimeParser()) doesn't work. if (this.DateTimeParser && this.DateTimeParser.extend) { this.DateTimeParser.extend(LocalizedFormat); this.DateTimeParser.extend(calendar); this.DateTimeParser.extend(localeData); this.DateTimeParser.extend(relativeTime); } } catch (error) { throw Error("Streami18n: Looks like you wanted to provide Dayjs instance, but something went wrong while adding plugins ".concat(error)); } this.isCustomDateTimeParser = !!options.DateTimeParser; var translationsForLanguage = finalOptions.translationsForLanguage; if (translationsForLanguage) { this.translations[this.currentLanguage] = { [defaultNS]: translationsForLanguage }; } // If translations don't exist for given language, then set it as empty object. if (!this.translations[this.currentLanguage]) { this.translations[this.currentLanguage] = { [defaultNS]: {} }; } this.i18nextConfig = {