Chore: Migrate ShareListView to Typescript (#3459)

Co-authored-by: Gerzon Z <gerzonc@icloud.com>
This commit is contained in:
Reinaldo Neto 2021-12-02 10:39:48 -03:00 committed by GitHub
parent 17c70e73d3
commit 65f5b03bdf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 120 additions and 84 deletions

View File

@ -1,5 +1,5 @@
import React from 'react'; import React from 'react';
import { Text, View } from 'react-native'; import { Text, View, ViewStyle } from 'react-native';
import Touch from '../../utils/touch'; import Touch from '../../utils/touch';
import Avatar from '../../containers/Avatar'; import Avatar from '../../containers/Avatar';
@ -10,7 +10,7 @@ import { themes } from '../../constants/colors';
export { ROW_HEIGHT }; export { ROW_HEIGHT };
interface IDirectoryItemLabel { interface IDirectoryItemLabel {
text: string; text?: string;
theme: string; theme: string;
} }
@ -21,9 +21,9 @@ interface IDirectoryItem {
type: string; type: string;
onPress(): void; onPress(): void;
testID: string; testID: string;
style: any; style?: ViewStyle;
rightLabel: string; rightLabel?: string;
rid: string; rid?: string;
theme: string; theme: string;
teamMain?: boolean; teamMain?: boolean;
} }
@ -32,7 +32,7 @@ const DirectoryItemLabel = React.memo(({ text, theme }: IDirectoryItemLabel) =>
if (!text) { if (!text) {
return null; return null;
} }
return <Text style={[styles.directoryItemLabel, { color: themes[theme!].auxiliaryText }]}>{text}</Text>; return <Text style={[styles.directoryItemLabel, { color: themes[theme].auxiliaryText }]}>{text}</Text>;
}); });
const DirectoryItem = ({ const DirectoryItem = ({

View File

@ -1,5 +1,4 @@
import React, { useState } from 'react'; import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { Keyboard, StyleSheet, View } from 'react-native'; import { Keyboard, StyleSheet, View } from 'react-native';
import ShareExtension from 'rn-extensions-share'; import ShareExtension from 'rn-extensions-share';
@ -8,6 +7,7 @@ import * as HeaderButton from '../../../containers/HeaderButton';
import { themes } from '../../../constants/colors'; import { themes } from '../../../constants/colors';
import sharedStyles from '../../Styles'; import sharedStyles from '../../Styles';
import { animateNextTransition } from '../../../utils/layoutAnimation'; import { animateNextTransition } from '../../../utils/layoutAnimation';
import { IShareListHeaderIos } from './interface';
const styles = StyleSheet.create({ const styles = StyleSheet.create({
container: { container: {
@ -16,10 +16,10 @@ const styles = StyleSheet.create({
} }
}); });
const Header = React.memo(({ searching, onChangeSearchText, initSearch, cancelSearch, theme }) => { const Header = React.memo(({ searching, onChangeSearchText, initSearch, cancelSearch, theme }: IShareListHeaderIos) => {
const [text, setText] = useState(''); const [text, setText] = useState('');
const onChangeText = searchText => { const onChangeText = (searchText: string) => {
onChangeSearchText(searchText); onChangeSearchText(searchText);
setText(searchText); setText(searchText);
}; };
@ -59,12 +59,4 @@ const Header = React.memo(({ searching, onChangeSearchText, initSearch, cancelSe
); );
}); });
Header.propTypes = {
searching: PropTypes.bool,
onChangeSearchText: PropTypes.func,
initSearch: PropTypes.func,
cancelSearch: PropTypes.func,
theme: PropTypes.string
};
export default Header; export default Header;

View File

@ -1,11 +1,11 @@
import React from 'react'; import React from 'react';
import { StyleSheet, Text, View } from 'react-native'; import { StyleSheet, Text, View } from 'react-native';
import PropTypes from 'prop-types';
import TextInput from '../../../presentation/TextInput'; import TextInput from '../../../presentation/TextInput';
import I18n from '../../../i18n'; import I18n from '../../../i18n';
import { themes } from '../../../constants/colors'; import { themes } from '../../../constants/colors';
import sharedStyles from '../../Styles'; import sharedStyles from '../../Styles';
import { IShareListHeader } from './interface';
const styles = StyleSheet.create({ const styles = StyleSheet.create({
container: { container: {
@ -24,7 +24,7 @@ const styles = StyleSheet.create({
} }
}); });
const Header = React.memo(({ searching, onChangeSearchText, theme }) => { const Header = React.memo(({ searching, onChangeSearchText, theme }: IShareListHeader) => {
const titleColorStyle = { color: themes[theme].headerTintColor }; const titleColorStyle = { color: themes[theme].headerTintColor };
const isLight = theme === 'light'; const isLight = theme === 'light';
if (searching) { if (searching) {
@ -43,10 +43,4 @@ const Header = React.memo(({ searching, onChangeSearchText, theme }) => {
return <Text style={[styles.title, titleColorStyle]}>{I18n.t('Send_to')}</Text>; return <Text style={[styles.title, titleColorStyle]}>{I18n.t('Send_to')}</Text>;
}); });
Header.propTypes = {
searching: PropTypes.bool,
onChangeSearchText: PropTypes.func,
theme: PropTypes.string
};
export default Header; export default Header;

View File

@ -1,11 +1,11 @@
import React from 'react'; import React from 'react';
import PropTypes from 'prop-types';
import Header from './Header'; import Header from './Header';
import { IShareListHeader } from './interface';
const ShareListHeader = React.memo(({ searching, initSearch, cancelSearch, search, theme }) => { const ShareListHeader = React.memo(({ searching, initSearch, cancelSearch, onChangeSearchText, theme }: IShareListHeader) => {
const onSearchChangeText = text => { const onSearchChangeText = (text: string) => {
search(text.trim()); onChangeSearchText(text.trim());
}; };
return ( return (
@ -19,12 +19,4 @@ const ShareListHeader = React.memo(({ searching, initSearch, cancelSearch, searc
); );
}); });
ShareListHeader.propTypes = {
searching: PropTypes.bool,
initSearch: PropTypes.func,
cancelSearch: PropTypes.func,
search: PropTypes.func,
theme: PropTypes.string
};
export default ShareListHeader; export default ShareListHeader;

View File

@ -0,0 +1,13 @@
import { TextInputProps } from 'react-native';
type RequiredOnChangeText = Required<Pick<TextInputProps, 'onChangeText'>>;
export interface IShareListHeader {
searching: boolean;
onChangeSearchText: RequiredOnChangeText['onChangeText'];
theme: string;
initSearch?: () => void;
cancelSearch?: () => void;
}
export type IShareListHeaderIos = Required<IShareListHeader>;

View File

@ -1,6 +1,6 @@
import React from 'react'; import React from 'react';
import PropTypes from 'prop-types'; import { StackNavigationProp } from '@react-navigation/stack';
import { BackHandler, FlatList, Keyboard, PermissionsAndroid, ScrollView, Text, View } from 'react-native'; import { BackHandler, FlatList, Keyboard, PermissionsAndroid, ScrollView, Text, View, Rationale } from 'react-native';
import ShareExtension from 'rn-extensions-share'; import ShareExtension from 'rn-extensions-share';
import * as FileSystem from 'expo-file-system'; import * as FileSystem from 'expo-file-system';
import { connect } from 'react-redux'; import { connect } from 'react-redux';
@ -25,24 +25,75 @@ import { sanitizeLikeString } from '../../lib/database/utils';
import styles from './styles'; import styles from './styles';
import ShareListHeader from './Header'; import ShareListHeader from './Header';
const permission = { interface IFile {
value: string;
type: string;
}
interface IAttachment {
filename: string;
description: string;
size: number;
mime: any;
path: string;
}
interface IChat {
rid: string;
t: string;
name: string;
fname: string;
blocked: boolean;
blocker: boolean;
prid: string;
uids: string[];
usernames: string[];
topic: string;
description: string;
}
interface IServerInfo {
useRealName: boolean;
}
interface IState {
searching: boolean;
searchText: string;
searchResults: IChat[];
chats: IChat[];
serversCount: number;
attachments: IAttachment[];
text: string;
loading: boolean;
serverInfo: IServerInfo;
needsPermission: boolean;
}
interface INavigationOption {
navigation: StackNavigationProp<any, 'ShareListView'>;
}
interface IShareListViewProps extends INavigationOption {
server: string;
token: string;
userId: string;
theme: string;
}
const permission: Rationale = {
title: I18n.t('Read_External_Permission'), title: I18n.t('Read_External_Permission'),
message: I18n.t('Read_External_Permission_Message') message: I18n.t('Read_External_Permission_Message'),
buttonPositive: 'Ok'
}; };
const getItemLayout = (data, index) => ({ length: data.length, offset: ROW_HEIGHT * index, index }); const getItemLayout = (data: any, index: number) => ({ length: data.length, offset: ROW_HEIGHT * index, index });
const keyExtractor = item => item.rid; const keyExtractor = (item: IChat) => item.rid;
class ShareListView extends React.Component { class ShareListView extends React.Component<IShareListViewProps, IState> {
static propTypes = { private unsubscribeFocus: (() => void) | undefined;
navigation: PropTypes.object,
server: PropTypes.string,
token: PropTypes.string,
userId: PropTypes.string,
theme: PropTypes.string
};
constructor(props) { private unsubscribeBlur: (() => void) | undefined;
constructor(props: IShareListViewProps) {
super(props); super(props);
this.state = { this.state = {
searching: false, searching: false,
@ -53,7 +104,7 @@ class ShareListView extends React.Component {
attachments: [], attachments: [],
text: '', text: '',
loading: true, loading: true,
serverInfo: null, serverInfo: {} as IServerInfo,
needsPermission: isAndroid || false needsPermission: isAndroid || false
}; };
this.setHeader(); this.setHeader();
@ -70,7 +121,7 @@ class ShareListView extends React.Component {
async componentDidMount() { async componentDidMount() {
const { server } = this.props; const { server } = this.props;
try { try {
const data = await ShareExtension.data(); const data = (await ShareExtension.data()) as IFile[];
if (isAndroid) { if (isAndroid) {
await this.askForPermission(data); await this.askForPermission(data);
} }
@ -85,7 +136,7 @@ class ShareListView extends React.Component {
size: file.size, size: file.size,
mime: mime.lookup(file.uri), mime: mime.lookup(file.uri),
path: file.uri path: file.uri
})); })) as IAttachment[];
const text = data.filter(item => item.type === 'text').reduce((acc, item) => `${item.value}\n${acc}`, ''); const text = data.filter(item => item.type === 'text').reduce((acc, item) => `${item.value}\n${acc}`, '');
this.setState({ this.setState({
text, text,
@ -98,14 +149,14 @@ class ShareListView extends React.Component {
this.getSubscriptions(server); this.getSubscriptions(server);
} }
UNSAFE_componentWillReceiveProps(nextProps) { UNSAFE_componentWillReceiveProps(nextProps: IShareListViewProps) {
const { server } = this.props; const { server } = this.props;
if (nextProps.server !== server) { if (nextProps.server !== server) {
this.getSubscriptions(nextProps.server); this.getSubscriptions(nextProps.server);
} }
} }
shouldComponentUpdate(nextProps, nextState) { shouldComponentUpdate(nextProps: IShareListViewProps, nextState: IState) {
const { searching, needsPermission } = this.state; const { searching, needsPermission } = this.state;
if (nextState.searching !== searching) { if (nextState.searching !== searching) {
return true; return true;
@ -151,7 +202,7 @@ class ShareListView extends React.Component {
searching={searching} searching={searching}
initSearch={this.initSearch} initSearch={this.initSearch}
cancelSearch={this.cancelSearch} cancelSearch={this.cancelSearch}
search={this.search} onChangeSearchText={this.search}
theme={theme} theme={theme}
/> />
) )
@ -168,7 +219,7 @@ class ShareListView extends React.Component {
) : ( ) : (
<HeaderButton.CancelModal onPress={ShareExtension.close} testID='share-extension-close' /> <HeaderButton.CancelModal onPress={ShareExtension.close} testID='share-extension-close' />
), ),
headerTitle: () => <ShareListHeader searching={searching} search={this.search} theme={theme} />, headerTitle: () => <ShareListHeader searching={searching} onChangeSearchText={this.search} theme={theme} />,
headerRight: () => headerRight: () =>
searching ? null : ( searching ? null : (
<HeaderButton.Container> <HeaderButton.Container>
@ -178,16 +229,16 @@ class ShareListView extends React.Component {
}); });
}; };
// eslint-disable-next-line react/sort-comp internalSetState = (...args: object[]) => {
internalSetState = (...args) => {
const { navigation } = this.props; const { navigation } = this.props;
if (navigation.isFocused()) { if (navigation.isFocused()) {
animateNextTransition(); animateNextTransition();
} }
// @ts-ignore
this.setState(...args); this.setState(...args);
}; };
query = async text => { query = async (text?: string) => {
const db = database.active; const db = database.active;
const defaultWhereClause = [ const defaultWhereClause = [
Q.where('archived', false), Q.where('archived', false),
@ -195,15 +246,16 @@ class ShareListView extends React.Component {
Q.experimentalSkip(0), Q.experimentalSkip(0),
Q.experimentalTake(20), Q.experimentalTake(20),
Q.experimentalSortBy('room_updated_at', Q.desc) Q.experimentalSortBy('room_updated_at', Q.desc)
]; ] as (Q.WhereDescription | Q.Skip | Q.Take | Q.SortBy | Q.Or)[];
if (text) { if (text) {
const likeString = sanitizeLikeString(text); const likeString = sanitizeLikeString(text);
defaultWhereClause.push(Q.or(Q.where('name', Q.like(`%${likeString}%`)), Q.where('fname', Q.like(`%${likeString}%`)))); defaultWhereClause.push(Q.or(Q.where('name', Q.like(`%${likeString}%`)), Q.where('fname', Q.like(`%${likeString}%`))));
} }
const data = await db const data = (await db
.get('subscriptions') .get('subscriptions')
.query(...defaultWhereClause) .query(...defaultWhereClause)
.fetch(); .fetch()) as IChat[];
return data.map(item => ({ return data.map(item => ({
rid: item.rid, rid: item.rid,
t: item.t, t: item.t,
@ -218,7 +270,7 @@ class ShareListView extends React.Component {
})); }));
}; };
getSubscriptions = async server => { getSubscriptions = async (server: string) => {
const serversDB = database.servers; const serversDB = database.servers;
if (server) { if (server) {
@ -242,7 +294,7 @@ class ShareListView extends React.Component {
} }
}; };
askForPermission = async data => { askForPermission = async (data: IFile[]) => {
const mediaIndex = data.findIndex(item => item.type === 'media'); const mediaIndex = data.findIndex(item => item.type === 'media');
if (mediaIndex !== -1) { if (mediaIndex !== -1) {
const result = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE, permission); const result = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE, permission);
@ -255,15 +307,14 @@ class ShareListView extends React.Component {
return Promise.resolve(); return Promise.resolve();
}; };
uriToPath = uri => decodeURIComponent(isIOS ? uri.replace(/^file:\/\//, '') : uri); uriToPath = (uri: string) => decodeURIComponent(isIOS ? uri.replace(/^file:\/\//, '') : uri);
getRoomTitle = item => { getRoomTitle = (item: IChat) => {
const { serverInfo } = this.state; const { serverInfo } = this.state;
const { useRealName } = serverInfo; return ((item.prid || serverInfo?.useRealName) && item.fname) || item.name;
return ((item.prid || useRealName) && item.fname) || item.name;
}; };
shareMessage = room => { shareMessage = (room: IChat) => {
const { attachments, text, serverInfo } = this.state; const { attachments, text, serverInfo } = this.state;
const { navigation } = this.props; const { navigation } = this.props;
@ -276,7 +327,7 @@ class ShareListView extends React.Component {
}); });
}; };
search = async text => { search = async (text: string) => {
const result = await this.query(text); const result = await this.query(text);
this.internalSetState({ this.internalSetState({
searchResults: result, searchResults: result,
@ -303,7 +354,7 @@ class ShareListView extends React.Component {
return false; return false;
}; };
renderSectionHeader = header => { renderSectionHeader = (header: string) => {
const { searching } = this.state; const { searching } = this.state;
const { theme } = this.props; const { theme } = this.props;
if (searching) { if (searching) {
@ -320,10 +371,9 @@ class ShareListView extends React.Component {
); );
}; };
renderItem = ({ item }) => { renderItem = ({ item }: { item: IChat }) => {
const { serverInfo } = this.state; const { serverInfo } = this.state;
const { useRealName } = serverInfo; const { theme } = this.props;
const { userId, token, server, theme } = this.props;
let description; let description;
switch (item.t) { switch (item.t) {
case 'c': case 'c':
@ -333,7 +383,7 @@ class ShareListView extends React.Component {
description = item.topic || item.description; description = item.topic || item.description;
break; break;
case 'd': case 'd':
description = useRealName ? item.name : item.fname; description = serverInfo?.useRealName ? item.name : item.fname;
break; break;
default: default:
description = item.fname; description = item.fname;
@ -341,12 +391,7 @@ class ShareListView extends React.Component {
} }
return ( return (
<DirectoryItem <DirectoryItem
user={{
id: userId,
token
}}
title={this.getRoomTitle(item)} title={this.getRoomTitle(item)}
baseUrl={server}
avatar={RocketChat.getRoomAvatar(item)} avatar={RocketChat.getRoomAvatar(item)}
description={description} description={description}
type={item.prid ? 'discussion' : item.t} type={item.prid ? 'discussion' : item.t}
@ -439,7 +484,7 @@ class ShareListView extends React.Component {
}; };
} }
const mapStateToProps = ({ share }) => ({ const mapStateToProps = ({ share }: any) => ({
userId: share.user && share.user.id, userId: share.user && share.user.id,
token: share.user && share.user.token, token: share.user && share.user.token,
server: share.server.server server: share.server.server