stream-chat-react
Version:
React components to create chat conversations or livestream style chat
93 lines (92 loc) • 3.66 kB
JavaScript
export class TranslationTopic {
constructor(options) {
this.options = options;
this.translators = new Map();
this.setTranslator = (name, translator) => {
this.translators.set(name, translator);
};
this.removeTranslator = (name) => {
this.translators.delete(name);
};
this.i18next = options.i18next;
if (options.translators) {
Object.entries(options.translators).forEach(([name, translator]) => {
this.setTranslator(name, translator);
});
}
}
}
const forwardTranslation = ({ value }) => value;
export class TranslationBuilder {
constructor(i18next) {
this.i18next = i18next;
this.topics = new Map();
// need to keep a registration buffer so that translators can be registered once a topic is registered
// what does not happen when Streami18n is instantiated but rather once Streami18n.init() is invoked
this.translatorRegistrationsBuffer = {};
this.registerTopic = (name, Topic) => {
let topic = this.topics.get(name);
if (!topic) {
topic = new Topic({ i18next: this.i18next });
this.topics.set(name, topic);
this.i18next.use({
name,
process: (value, key, options) => {
const topic = this.topics.get(name);
if (!topic)
return value;
return topic.translate(value, key, options);
},
type: 'postProcessor',
});
}
const additionalTranslatorsToRegister = this.translatorRegistrationsBuffer[name];
if (additionalTranslatorsToRegister) {
Object.entries(additionalTranslatorsToRegister).forEach(([translatorName, translator]) => {
topic.setTranslator(translatorName, translator);
});
delete this.translatorRegistrationsBuffer[name];
}
return topic;
};
this.disableTopic = (topicName) => {
const topic = this.topics.get(topicName);
if (!topic)
return;
this.i18next.use({
name: topicName,
process: forwardTranslation,
type: 'postProcessor',
});
this.topics.delete(topicName);
};
this.getTopic = (topicName) => this.topics.get(topicName);
}
registerTranslators(topicName, translators) {
const topic = this.getTopic(topicName);
if (!topic) {
if (!this.translatorRegistrationsBuffer[topicName])
this.translatorRegistrationsBuffer[topicName] = {};
Object.entries(translators).forEach(([translatorName, translator]) => {
this.translatorRegistrationsBuffer[topicName][translatorName] = translator;
});
return;
}
Object.entries(translators).forEach(([name, translator]) => {
topic.setTranslator(name, translator);
});
}
removeTranslators(topicName, translators) {
const topic = this.getTopic(topicName);
if (this.translatorRegistrationsBuffer[topicName]) {
translators.forEach((translatorName) => {
delete this.translatorRegistrationsBuffer[topicName][translatorName];
});
}
if (!topic)
return;
translators.forEach((name) => {
topic.removeTranslator(name);
});
}
}