verdnatura-chat/app/views/LanguageView/index.tsx

172 lines
4.6 KiB
TypeScript
Raw Permalink Normal View History

import React from 'react';
import { FlatList } from 'react-native';
import { connect } from 'react-redux';
import RNRestart from 'react-native-restart';
import { Dispatch } from 'redux';
import RocketChat from '../../lib/rocketchat';
import I18n, { LANGUAGES, isRTL } from '../../i18n';
import { showErrorAlert } from '../../utils/info';
import log, { events, logEvent } from '../../utils/log';
import { setUser as setUserAction } from '../../actions/login';
import StatusBar from '../../containers/StatusBar';
import * as List from '../../containers/List';
2019-12-04 16:39:53 +00:00
import { themes } from '../../constants/colors';
import { withTheme } from '../../theme';
2022-01-07 20:40:48 +00:00
import { appStart as appStartAction } from '../../actions/app';
2020-02-11 14:09:14 +00:00
import { getUserSelector } from '../../selectors/login';
import database from '../../lib/database';
[CHORE] Update react-navigation to v5 (#2154) * react-navigation v5 installed * compiling * Outside working * InsideStack compiling * Switch stack * Starting room * RoomView header * SafeAreaView * Slide from right stack animation * stash * Fix params * Create channel * inapp notification * Custom status * Add server working * Refactor appStart * Attachment * in-app notification * AuthLoadingView * Remove compat * Navigation * Outside animations * Fix new server icon * block modal * AttachmentView header * Remove unnecessary code * SelectedUsersView header * StatusView * CreateDiscussionView * RoomInfoView * RoomInfoEditView style * RoomMembersView * RoomsListView header * RoomView header * Share extension * getParam * Focus/blur * Trying to fix inapp * Lint * Simpler app container * Update libs * Revert "Simpler app container" This reverts commit 1e49d80bb49481c34f415831b9da5e9d53e66057. * Load messages faster * Fix safearea on ReactionsModal * Update safe area to v3 * lint * Fix transition * stash - drawer replace working * stash - modal nav * RoomActionsView as tablet modal * RoomStack * Stop showing RoomView header when there's no room * Custom Header and different navigation based on stack * Refactor setHeader * MasterDetailContext * RoomView header * Fix isMasterDetail rule * KeyCommands kind of working * Create channel on tablet * RoomView sCU * Remove withSplit * Settings opening as modal * Settings * StatusView headerLeft * Admin panel * TwoFactor style * DirectoryView * ServerDropdown and SortDropdown animations * ThreadMessagesView * Navigate to empty RoomView on server switch when in master detail * ProfileView header * Fix navigation issues * Nav to any room info on tablet * Room info * Refactoring * Fix rooms search * Roomslist commands * SearchMessagesView close modal * Key commands * Fix undefined subscription * Disallow navigate to focused room * isFocused state on RoomsListView * Blur text inputs when focus is lost * Replace animation * Default nav theme * Refactoring * Always open Attachment with close modal button * ModalContainer backdrop following themes * Screen tracking * Refactor get active route for in-app notification * Only mark room as focused when in master detail layout * Lint * Open modals as fade from bottom on Android * typo * Fixing tests * Fix in-app update * Fixing goRoom issues * Refactor stack names * Fix unreadsCount * Fix stack * Fix header animation * Refactor ShareNavigation * Refactor navigation theme * Make sure title is set * Fix create discussion navigation * Remove unused variable * Create discussions from actions fixed * Layout animation * Screen lock on share extension * Unnecessary change * Admin border * Set header after state callback * Fix key commands on outside stack * Fix back button pressed * Remove layout animations from Android * Tweak animations on Android * Disable swipe gesture to open drawer * Fix current item on RoomsListView * Fix add server * Fix drawer * Fix broadcast * LayoutAnimation instead of Transitions * Fix onboarding back press * Fix assorted tests * Create discussion fix * RoomInfoView header * Drawer active item
2020-06-15 14:00:46 +00:00
import SafeAreaView from '../../containers/SafeAreaView';
2022-01-07 20:40:48 +00:00
import { RootEnum } from '../../definitions';
interface ILanguageViewProps {
user: {
id: string;
language: string;
};
setUser(user: object): void;
appStart(params: any): void;
theme: string;
}
interface ILanguageViewState {
language: string;
}
class LanguageView extends React.Component<ILanguageViewProps, ILanguageViewState> {
static navigationOptions = () => ({
[CHORE] Update react-navigation to v5 (#2154) * react-navigation v5 installed * compiling * Outside working * InsideStack compiling * Switch stack * Starting room * RoomView header * SafeAreaView * Slide from right stack animation * stash * Fix params * Create channel * inapp notification * Custom status * Add server working * Refactor appStart * Attachment * in-app notification * AuthLoadingView * Remove compat * Navigation * Outside animations * Fix new server icon * block modal * AttachmentView header * Remove unnecessary code * SelectedUsersView header * StatusView * CreateDiscussionView * RoomInfoView * RoomInfoEditView style * RoomMembersView * RoomsListView header * RoomView header * Share extension * getParam * Focus/blur * Trying to fix inapp * Lint * Simpler app container * Update libs * Revert "Simpler app container" This reverts commit 1e49d80bb49481c34f415831b9da5e9d53e66057. * Load messages faster * Fix safearea on ReactionsModal * Update safe area to v3 * lint * Fix transition * stash - drawer replace working * stash - modal nav * RoomActionsView as tablet modal * RoomStack * Stop showing RoomView header when there's no room * Custom Header and different navigation based on stack * Refactor setHeader * MasterDetailContext * RoomView header * Fix isMasterDetail rule * KeyCommands kind of working * Create channel on tablet * RoomView sCU * Remove withSplit * Settings opening as modal * Settings * StatusView headerLeft * Admin panel * TwoFactor style * DirectoryView * ServerDropdown and SortDropdown animations * ThreadMessagesView * Navigate to empty RoomView on server switch when in master detail * ProfileView header * Fix navigation issues * Nav to any room info on tablet * Room info * Refactoring * Fix rooms search * Roomslist commands * SearchMessagesView close modal * Key commands * Fix undefined subscription * Disallow navigate to focused room * isFocused state on RoomsListView * Blur text inputs when focus is lost * Replace animation * Default nav theme * Refactoring * Always open Attachment with close modal button * ModalContainer backdrop following themes * Screen tracking * Refactor get active route for in-app notification * Only mark room as focused when in master detail layout * Lint * Open modals as fade from bottom on Android * typo * Fixing tests * Fix in-app update * Fixing goRoom issues * Refactor stack names * Fix unreadsCount * Fix stack * Fix header animation * Refactor ShareNavigation * Refactor navigation theme * Make sure title is set * Fix create discussion navigation * Remove unused variable * Create discussions from actions fixed * Layout animation * Screen lock on share extension * Unnecessary change * Admin border * Set header after state callback * Fix key commands on outside stack * Fix back button pressed * Remove layout animations from Android * Tweak animations on Android * Disable swipe gesture to open drawer * Fix current item on RoomsListView * Fix add server * Fix drawer * Fix broadcast * LayoutAnimation instead of Transitions * Fix onboarding back press * Fix assorted tests * Create discussion fix * RoomInfoView header * Drawer active item
2020-06-15 14:00:46 +00:00
title: I18n.t('Change_Language')
});
constructor(props: ILanguageViewProps) {
super(props);
this.state = {
language: props.user ? props.user.language : 'en'
};
}
shouldComponentUpdate(nextProps: ILanguageViewProps, nextState: ILanguageViewState) {
const { language } = this.state;
const { user, theme } = this.props;
2019-12-04 16:39:53 +00:00
if (nextProps.theme !== theme) {
return true;
}
if (nextState.language !== language) {
return true;
}
if (nextProps.user.language !== user.language) {
return true;
}
return false;
}
formIsChanged = (language: string) => {
const { user } = this.props;
return user.language !== language;
};
submit = async (language: string) => {
if (!this.formIsChanged(language)) {
return;
}
const { appStart, user } = this.props;
const shouldRestart = isRTL(language) || isRTL(user.language);
2022-01-07 20:40:48 +00:00
await appStart({ root: RootEnum.ROOT_LOADING, text: I18n.t('Change_language_loading') });
// shows loading for at least 300ms
await Promise.all([this.changeLanguage(language), new Promise(resolve => setTimeout(resolve, 300))]);
if (shouldRestart) {
await RNRestart.Restart();
} else {
2022-01-07 20:40:48 +00:00
await appStart({ root: RootEnum.ROOT_INSIDE });
}
};
changeLanguage = async (language: string) => {
[NEW] Log events from Room, Settings and Edit status (#2206) * Create method to track user event to isolate the logic to improve future refactoring * Track Onboarding view * Track NewServer view * Refactor track method due to firebase already send the current screen * Track default login and all the oAuth options * Track default sign up in RegisterView * Change trackUserEvent signature and update all the files * Track the remaining login services * track add server, change server and search * Track SidebarView and refactor to use react-navigation * Track profile events and handle exceptions * Track create channel flux * Track send message to user via NewMessageView * Track create direct message flux * Handle failure of create channel and group in the saga * Track create discussion flux * Track navigate to directory and its actions * Track read, favorite and hide a channel, handling its errors * Track all channels sorting and grouping * Resolve requests to improve the importing logs and events * Remove unused events file * Remove unused events file * log proposed Room events * Log proposed Message actions events * Log EditStatus proposed events * Log Settings proposed events * Leave a bugsnag breadcrumb when logging an event * Move all logEvent to the top of code block and log remaining fail events * Move all the non-logic-dependent logEvent to the top of code block * Move all non-logic and non-data dependent logEvent to the top of code block * Improve the logging of sidebar events * Improve events from onboarding and newserver * Improve events from login and register view, and log enter with apple * Improve NewMessageView events * Improve CreateChannel events * Improve CreateDiscussion and SelectedUsers create group events * Improve RoomsList events and log trivial events * Improve ProfileView events * Remove single line function body for the sidebarNavigate * Improve SettingsView events * Log more events from ScreenLockConfigView * Navigate to Status and AdminPanel View using the defined sidebarNavigate method * Improve StatusView events * Improve RoomView events Co-authored-by: Diego Mello <diegolmello@gmail.com>
2020-07-30 19:51:13 +00:00
logEvent(events.LANG_SET_LANGUAGE);
const { user, setUser } = this.props;
const params: { language?: string } = {};
// language
if (user.language !== language) {
params.language = language;
}
try {
await RocketChat.saveUserPreferences(params);
setUser({ language: params.language });
const serversDB = database.servers;
const usersCollection = serversDB.get('users');
await serversDB.write(async () => {
try {
const userRecord = await usersCollection.find(user.id);
await userRecord.update((record: any) => {
record.language = params.language;
});
} catch (e) {
[NEW] Log events from Room, Settings and Edit status (#2206) * Create method to track user event to isolate the logic to improve future refactoring * Track Onboarding view * Track NewServer view * Refactor track method due to firebase already send the current screen * Track default login and all the oAuth options * Track default sign up in RegisterView * Change trackUserEvent signature and update all the files * Track the remaining login services * track add server, change server and search * Track SidebarView and refactor to use react-navigation * Track profile events and handle exceptions * Track create channel flux * Track send message to user via NewMessageView * Track create direct message flux * Handle failure of create channel and group in the saga * Track create discussion flux * Track navigate to directory and its actions * Track read, favorite and hide a channel, handling its errors * Track all channels sorting and grouping * Resolve requests to improve the importing logs and events * Remove unused events file * Remove unused events file * log proposed Room events * Log proposed Message actions events * Log EditStatus proposed events * Log Settings proposed events * Leave a bugsnag breadcrumb when logging an event * Move all logEvent to the top of code block and log remaining fail events * Move all the non-logic-dependent logEvent to the top of code block * Move all non-logic and non-data dependent logEvent to the top of code block * Improve the logging of sidebar events * Improve events from onboarding and newserver * Improve events from login and register view, and log enter with apple * Improve NewMessageView events * Improve CreateChannel events * Improve CreateDiscussion and SelectedUsers create group events * Improve RoomsList events and log trivial events * Improve ProfileView events * Remove single line function body for the sidebarNavigate * Improve SettingsView events * Log more events from ScreenLockConfigView * Navigate to Status and AdminPanel View using the defined sidebarNavigate method * Improve StatusView events * Improve RoomView events Co-authored-by: Diego Mello <diegolmello@gmail.com>
2020-07-30 19:51:13 +00:00
logEvent(events.LANG_SET_LANGUAGE_F);
}
});
} catch (e) {
[NEW] Log events from Room, Settings and Edit status (#2206) * Create method to track user event to isolate the logic to improve future refactoring * Track Onboarding view * Track NewServer view * Refactor track method due to firebase already send the current screen * Track default login and all the oAuth options * Track default sign up in RegisterView * Change trackUserEvent signature and update all the files * Track the remaining login services * track add server, change server and search * Track SidebarView and refactor to use react-navigation * Track profile events and handle exceptions * Track create channel flux * Track send message to user via NewMessageView * Track create direct message flux * Handle failure of create channel and group in the saga * Track create discussion flux * Track navigate to directory and its actions * Track read, favorite and hide a channel, handling its errors * Track all channels sorting and grouping * Resolve requests to improve the importing logs and events * Remove unused events file * Remove unused events file * log proposed Room events * Log proposed Message actions events * Log EditStatus proposed events * Log Settings proposed events * Leave a bugsnag breadcrumb when logging an event * Move all logEvent to the top of code block and log remaining fail events * Move all the non-logic-dependent logEvent to the top of code block * Move all non-logic and non-data dependent logEvent to the top of code block * Improve the logging of sidebar events * Improve events from onboarding and newserver * Improve events from login and register view, and log enter with apple * Improve NewMessageView events * Improve CreateChannel events * Improve CreateDiscussion and SelectedUsers create group events * Improve RoomsList events and log trivial events * Improve ProfileView events * Remove single line function body for the sidebarNavigate * Improve SettingsView events * Log more events from ScreenLockConfigView * Navigate to Status and AdminPanel View using the defined sidebarNavigate method * Improve StatusView events * Improve RoomView events Co-authored-by: Diego Mello <diegolmello@gmail.com>
2020-07-30 19:51:13 +00:00
logEvent(events.LANG_SET_LANGUAGE_F);
showErrorAlert(I18n.t('There_was_an_error_while_action', { action: I18n.t('saving_preferences') }));
log(e);
}
};
2019-12-04 16:39:53 +00:00
renderIcon = () => {
const { theme } = this.props;
return <List.Icon name='check' color={themes[theme].tintColor} />;
};
renderItem = ({ item }: { item: { value: string; label: string } }) => {
const { value, label } = item;
const { language } = this.state;
const isSelected = language === value;
return (
<List.Item
title={label}
onPress={() => this.submit(value)}
testID={`language-view-${value}`}
right={isSelected ? this.renderIcon : null}
translateTitle={false}
/>
);
};
render() {
return (
<SafeAreaView testID='language-view'>
<StatusBar />
<FlatList
data={LANGUAGES}
keyExtractor={item => item.value}
ListHeaderComponent={List.Separator}
ListFooterComponent={List.Separator}
contentContainerStyle={List.styles.contentContainerStyleFlatList}
renderItem={this.renderItem}
ItemSeparatorComponent={List.Separator}
/>
</SafeAreaView>
);
}
}
const mapStateToProps = (state: any) => ({
user: getUserSelector(state)
});
const mapDispatchToProps = (dispatch: Dispatch) => ({
setUser: (params: any) => dispatch(setUserAction(params)),
appStart: (params: any) => dispatch(appStartAction(params))
});
2019-12-04 16:39:53 +00:00
export default connect(mapStateToProps, mapDispatchToProps)(withTheme(LanguageView));