2017-08-01 16:44:14 +00:00
|
|
|
// @flow
|
|
|
|
|
|
|
|
'use strict';
|
|
|
|
|
2018-09-06 13:58:44 +00:00
|
|
|
// $FlowFixMe
|
2017-08-01 16:44:14 +00:00
|
|
|
import { NativeModules, NativeEventEmitter, Platform } from 'react-native';
|
2018-04-21 16:38:11 +00:00
|
|
|
const { RNLanguages } = NativeModules;
|
2017-08-01 16:44:14 +00:00
|
|
|
|
|
|
|
type EventType = 'change';
|
|
|
|
|
|
|
|
type EventData = {
|
|
|
|
language: string,
|
|
|
|
languages: Array<string>
|
|
|
|
};
|
|
|
|
|
|
|
|
type EventHandler = (eventData: EventData) => any;
|
|
|
|
|
2018-04-21 16:38:11 +00:00
|
|
|
type RNLanguagesModule = {
|
2017-08-01 16:44:14 +00:00
|
|
|
_eventHandlers?: Set<EventHandler>,
|
|
|
|
_eventEmitter?: NativeEventEmitter,
|
|
|
|
language: string,
|
|
|
|
languages: Array<string>,
|
|
|
|
addEventListener: (type: EventType, handler: EventHandler) => void,
|
|
|
|
removeEventListener: (type: EventType, handler: EventHandler) => void
|
|
|
|
};
|
|
|
|
|
2018-04-21 16:38:11 +00:00
|
|
|
export const language: string = RNLanguages.language;
|
|
|
|
export const languages: string[] = RNLanguages.languages;
|
|
|
|
|
|
|
|
let Module: RNLanguagesModule = {
|
|
|
|
language: RNLanguages.language,
|
|
|
|
languages: RNLanguages.languages,
|
2017-08-01 16:44:14 +00:00
|
|
|
|
|
|
|
addEventListener(type, handler) {
|
|
|
|
if (type !== 'change') {
|
|
|
|
console.error(`Trying to subscribe to unknown event: "${type}"`);
|
|
|
|
} else if (this._eventHandlers && !this._eventHandlers.has(handler)) {
|
|
|
|
this._eventHandlers.add(handler);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
|
|
|
|
removeEventListener(type, handler) {
|
|
|
|
if (type !== 'change') {
|
|
|
|
console.error(`Trying to remove listener for unknown event: "${type}"`);
|
|
|
|
} else if (this._eventHandlers && this._eventHandlers.has(handler)) {
|
|
|
|
this._eventHandlers.delete(handler);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
if (Platform.OS === 'android') {
|
|
|
|
Module._eventHandlers = new Set();
|
2018-04-21 16:38:11 +00:00
|
|
|
Module._eventEmitter = new NativeEventEmitter(RNLanguages);
|
2017-08-01 16:44:14 +00:00
|
|
|
|
|
|
|
const onLanguagesChange = (eventData: EventData) => {
|
|
|
|
Module.language = eventData.language;
|
|
|
|
Module.languages = eventData.languages;
|
|
|
|
|
|
|
|
if (Module._eventHandlers) {
|
|
|
|
Module._eventHandlers.forEach(handler => handler(eventData));
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
Module._eventEmitter.addListener('languagesDidChange', onLanguagesChange);
|
|
|
|
}
|
|
|
|
|
|
|
|
export default Module;
|