chore: migrate RoomInfoView to hooks (#5074)

* create RoomInfoViewTitle

* create RoomInfoViewBody

* create RoomInfoViewAvatar

* remove some functions

* merge styles

* fix types

* remove UserInfoButton

* fix room

* fix type import

* working

* fix navigation type

* wip

* remove console

* types

* fix import

* fix types

* fix types

* wip

* add asPlain

* some tweaks

* wip

* some fixes

* wip

* fix block user

* finish migration

* some fixes

* fix rule

* add rid to avatar

* fix settings and room transition

* add disabled rule

* fix test ???
This commit is contained in:
Gleidson Daniel Silva 2023-09-26 11:33:53 -03:00 committed by GitHub
parent 2d323615f4
commit 7a7193d1ab
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
22 changed files with 574 additions and 570 deletions

View File

@ -15,8 +15,8 @@ const styles = StyleSheet.create({
}); });
interface IRoomTypeIcon { interface IRoomTypeIcon {
type?: string;
userId?: string | null; userId?: string | null;
type: string;
isGroupChat?: boolean; isGroupChat?: boolean;
teamMain?: boolean; teamMain?: boolean;
status?: TUserStatus; status?: TUserStatus;

View File

@ -36,6 +36,11 @@ export interface ILivechatVisitor extends IRocketChatRecord {
utc?: number; utc?: number;
} }
export interface ILivechatVisitorModified extends ILivechatVisitor {
os?: string;
browser?: string;
}
export interface ILivechatVisitorDTO { export interface ILivechatVisitorDTO {
id: string; id: string;
token: string; token: string;

View File

@ -111,7 +111,9 @@ export interface ISubscription {
uploads: RelationModified<TUploadModel>; uploads: RelationModified<TUploadModel>;
} }
export type TSubscriptionModel = ISubscription & Model; export type TSubscriptionModel = ISubscription & Model & {
asPlain: () => ISubscription;
};
export type TSubscription = TSubscriptionModel | ISubscription; export type TSubscription = TSubscriptionModel | ISubscription;
// https://github.com/RocketChat/Rocket.Chat/blob/a88a96fcadd925b678ff27ada37075e029f78b5e/definition/ISubscription.ts#L8 // https://github.com/RocketChat/Rocket.Chat/blob/a88a96fcadd925b678ff27ada37075e029f78b5e/definition/ISubscription.ts#L8

View File

@ -142,4 +142,70 @@ export default class Subscription extends Model {
@field('users_count') usersCount; @field('users_count') usersCount;
@json('source', sanitizer) source; @json('source', sanitizer) source;
asPlain() {
return {
_id: this._id,
f: this.f,
t: this.t,
ts: this.ts,
ls: this.ls,
name: this.name,
fname: this.fname,
sanitizedFname: this.sanitizedFname,
rid: this.rid,
open: this.open,
alert: this.alert,
roles: this.roles,
unread: this.unread,
userMentions: this.userMentions,
groupMentions: this.groupMentions,
tunread: this.tunread,
tunreadUser: this.tunreadUser,
tunreadGroup: this.tunreadGroup,
roomUpdatedAt: this.roomUpdatedAt,
ro: this.ro,
lastOpen: this.lastOpen,
description: this.description,
announcement: this.announcement,
bannerClosed: this.bannerClosed,
topic: this.topic,
blocked: this.blocked,
blocker: this.blocker,
reactWhenReadOnly: this.reactWhenReadOnly,
archived: this.archived,
joinCodeRequired: this.joinCodeRequired,
notifications: this.notifications,
muted: this.muted,
ignored: this.ignored,
broadcast: this.broadcast,
prid: this.prid,
draftMessage: this.draftMessage,
lastThreadSync: this.lastThreadSync,
jitsiTimeout: this.jitsiTimeout,
autoTranslate: this.autoTranslate,
autoTranslateLanguage: this.autoTranslateLanguage,
lastMessage: this.lastMessage,
hideUnreadStatus: this.hideUnreadStatus,
hideMentionStatus: this.hideMentionStatus,
sysMes: this.sysMes,
uids: this.uids,
usernames: this.usernames,
visitor: this.visitor,
departmentId: this.departmentId,
servedBy: this.servedBy,
livechatData: this.livechatData,
tags: this.tags,
E2EKey: this.E2EKey,
E2ESuggestedKey: this.E2ESuggestedKey,
encrypted: this.encrypted,
e2eKeyId: this.e2eKeyId,
avatarETag: this.avatarETag,
teamId: this.teamId,
teamMain: this.teamMain,
onHold: this.onHold,
usersCount: this.usersCount,
source: this.source
};
}
} }

View File

@ -4,7 +4,7 @@ import { store as reduxStore } from '../../store/auxStore';
import database from '../../database'; import database from '../../database';
export function isGroupChat(room): boolean { export function isGroupChat(room): boolean {
return ((room.uids && room.uids.length > 2) || (room.usernames && room.usernames.length > 2)) ?? false; return ((room?.uids && room.uids.length > 2) || (room?.usernames && room.usernames.length > 2)) ?? false;
} }
export function getRoomAvatar(room) { export function getRoomAvatar(room) {
@ -49,7 +49,7 @@ export function getRoomTitle(room) {
if (allowSpecialChars && room.t !== 'd') { if (allowSpecialChars && room.t !== 'd') {
return room.fname || room.name; return room.fname || room.name;
} }
return ((room.prid || useRealName) && room.fname) || room.name; return ((room?.prid || useRealName) && room?.fname) || room?.name;
} }
export function getSenderName(sender) { export function getSenderName(sender) {

View File

@ -98,7 +98,8 @@ const ChatsStackNavigator = () => {
<ChatsStack.Screen name='RoomView' component={RoomView} /> <ChatsStack.Screen name='RoomView' component={RoomView} />
<ChatsStack.Screen name='RoomActionsView' component={RoomActionsView} options={RoomActionsView.navigationOptions} /> <ChatsStack.Screen name='RoomActionsView' component={RoomActionsView} options={RoomActionsView.navigationOptions} />
<ChatsStack.Screen name='SelectListView' component={SelectListView} options={SelectListView.navigationOptions} /> <ChatsStack.Screen name='SelectListView' component={SelectListView} options={SelectListView.navigationOptions} />
<ChatsStack.Screen name='RoomInfoView' component={RoomInfoView} options={RoomInfoView.navigationOptions} /> <ChatsStack.Screen name='RoomInfoView' component={RoomInfoView} />
{/* @ts-ignore */}
<ChatsStack.Screen name='RoomInfoEditView' component={RoomInfoEditView} options={RoomInfoEditView.navigationOptions} /> <ChatsStack.Screen name='RoomInfoEditView' component={RoomInfoEditView} options={RoomInfoEditView.navigationOptions} />
<ChatsStack.Screen name='ChangeAvatarView' component={ChangeAvatarView} /> <ChatsStack.Screen name='ChangeAvatarView' component={ChangeAvatarView} />
<ChatsStack.Screen name='RoomMembersView' component={RoomMembersView} /> <ChatsStack.Screen name='RoomMembersView' component={RoomMembersView} />

View File

@ -115,7 +115,9 @@ const ModalStackNavigator = React.memo(({ navigation }: INavigation) => {
screenOptions={{ ...defaultHeader, ...themedHeader(theme), ...StackAnimation } as StackNavigationOptions} screenOptions={{ ...defaultHeader, ...themedHeader(theme), ...StackAnimation } as StackNavigationOptions}
> >
<ModalStack.Screen name='RoomActionsView' component={RoomActionsView} /> <ModalStack.Screen name='RoomActionsView' component={RoomActionsView} />
<ModalStack.Screen name='RoomInfoView' component={RoomInfoView} options={RoomInfoView.navigationOptions} /> {/* @ts-ignore */}
<ModalStack.Screen name='RoomInfoView' component={RoomInfoView} />
{/* @ts-ignore */}
<ModalStack.Screen name='SelectListView' component={SelectListView} /> <ModalStack.Screen name='SelectListView' component={SelectListView} />
<ModalStack.Screen name='RoomInfoEditView' component={RoomInfoEditView} options={RoomInfoEditView.navigationOptions} /> <ModalStack.Screen name='RoomInfoEditView' component={RoomInfoEditView} options={RoomInfoEditView.navigationOptions} />
<ModalStack.Screen name='ChangeAvatarView' component={ChangeAvatarView} /> <ModalStack.Screen name='ChangeAvatarView' component={ChangeAvatarView} />

View File

@ -773,9 +773,9 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
params: { params: {
rid, rid,
t, t,
room, room: room.asPlain ? room.asPlain() : room,
member, member,
fromRid: room.rid fromRid: room?.rid
} }
}) })
} }

View File

@ -4,30 +4,17 @@ import I18n from '../../i18n';
import { ISubscription } from '../../definitions'; import { ISubscription } from '../../definitions';
import Item from './Item'; import Item from './Item';
const Channel = ({ room }: { room: ISubscription }) => { const Channel = ({ room }: { room?: ISubscription }): React.ReactElement => {
const { description, topic, announcement } = room; const description = room?.description || `__${I18n.t('No_label_provided', { label: 'description' })}__`;
const topic = room?.topic || `__${I18n.t('No_label_provided', { label: 'topic' })}__`;
const announcement = room?.announcement || `__${I18n.t('No_label_provided', { label: 'announcement' })}__`;
const broadcast = room?.broadcast ? I18n.t('Broadcast_hint') : '';
return ( return (
<> <>
<Item <Item label={I18n.t('Description')} content={description} testID='room-info-view-description' />
label={I18n.t('Description')} <Item label={I18n.t('Topic')} content={topic} testID='room-info-view-topic' />
content={description || `__${I18n.t('No_label_provided', { label: 'description' })}__`} <Item label={I18n.t('Announcement')} content={announcement} testID='room-info-view-announcement' />
testID='room-info-view-description' <Item label={I18n.t('Broadcast')} content={broadcast} testID='room-info-view-broadcast' />
/>
<Item
label={I18n.t('Topic')}
content={topic || `__${I18n.t('No_label_provided', { label: 'topic' })}__`}
testID='room-info-view-topic'
/>
<Item
label={I18n.t('Announcement')}
content={announcement || `__${I18n.t('No_label_provided', { label: 'announcement' })}__`}
testID='room-info-view-announcement'
/>
<Item
label={I18n.t('Broadcast')}
content={room.broadcast ? I18n.t('Broadcast_hint') : ''}
testID='room-info-view-broadcast'
/>
</> </>
); );
}; };

View File

@ -2,14 +2,12 @@ import React from 'react';
import Item from './Item'; import Item from './Item';
const CustomFields = ({ customFields }: { customFields?: { [key: string]: string } }) => { const CustomFields = ({ customFields }: { customFields?: { [key: string]: string } }): React.ReactElement | null => {
if (customFields) { if (customFields) {
return ( return (
<> <>
{Object.keys(customFields).map((title: string) => { {Object.keys(customFields).map((title: string) => {
if (!customFields[title]) { if (!customFields[title]) return null;
return null;
}
return <Item label={title} content={customFields[title]} />; return <Item label={title} content={customFields[title]} />;
})} })}
</> </>

View File

@ -1,29 +1,27 @@
import React from 'react'; import React from 'react';
import { Text, View } from 'react-native'; import { Text, View } from 'react-native';
import { IUserParsed } from '.';
import I18n from '../../i18n'; import I18n from '../../i18n';
import { useTheme } from '../../theme'; import { useTheme } from '../../theme';
import CustomFields from './CustomFields'; import CustomFields from './CustomFields';
import Timezone from './Timezone'; import Timezone from './Timezone';
import styles from './styles'; import styles from './styles';
import { IUser } from '../../definitions';
const Roles = ({ roles }: { roles?: string[] }) => { const Roles = ({ roles }: { roles?: string[] }) => {
const { colors } = useTheme(); const { colors } = useTheme();
if (roles?.length) { if (roles?.length) {
return ( return (
<View style={styles.item}> <View style={styles.item} testID='user-roles'>
<Text testID='user-roles' style={[styles.itemLabel, { color: colors.titleText }]}> <Text style={[styles.itemLabel, { color: colors.titleText }]}>{I18n.t('Roles')}</Text>
{I18n.t('Roles')}
</Text>
<View style={styles.rolesContainer}> <View style={styles.rolesContainer}>
{roles.map(role => {roles.map(role =>
role ? ( role ? (
<View <View
testID={`user-role-${role.replace(/ /g, '-')}`}
style={[styles.roleBadge, { backgroundColor: colors.chatComponentBackground }]} style={[styles.roleBadge, { backgroundColor: colors.chatComponentBackground }]}
key={role} key={role}
testID={`user-role-${role.replace(/ /g, '-')}`}
> >
<Text style={[styles.role, { color: colors.titleText }]}>{role}</Text> <Text style={[styles.role, { color: colors.titleText }]}>{role}</Text>
</View> </View>
@ -37,9 +35,9 @@ const Roles = ({ roles }: { roles?: string[] }) => {
return null; return null;
}; };
const Direct = ({ roomUser }: { roomUser: IUserParsed }): React.ReactElement => ( const Direct = ({ roomUser }: { roomUser: IUser }): React.ReactElement => (
<> <>
<Roles roles={roomUser.parsedRoles} /> <Roles roles={roomUser.roles} />
<Timezone utcOffset={roomUser.utcOffset} /> <Timezone utcOffset={roomUser.utcOffset} />
<CustomFields customFields={roomUser.customFields} /> <CustomFields customFields={roomUser.customFields} />
</> </>

View File

@ -2,7 +2,6 @@ import React from 'react';
import { Text, View } from 'react-native'; import { Text, View } from 'react-native';
import Markdown from '../../containers/markdown'; import Markdown from '../../containers/markdown';
import { themes } from '../../lib/constants';
import { useTheme } from '../../theme'; import { useTheme } from '../../theme';
import styles from './styles'; import styles from './styles';
@ -12,19 +11,17 @@ interface IItem {
testID?: string; testID?: string;
} }
const Item = ({ label, content, testID }: IItem) => { const Item = ({ label, content, testID }: IItem): React.ReactElement | null => {
const { theme } = useTheme(); const { colors } = useTheme();
if (!content) { if (!content) return null;
return null;
}
return ( return (
<View style={styles.item} testID={testID}> <View style={styles.item} testID={testID}>
<Text accessibilityLabel={label} style={[styles.itemLabel, { color: themes[theme].titleText }]}> <Text accessibilityLabel={label} style={[styles.itemLabel, { color: colors.titleText }]}>
{label} {label}
</Text> </Text>
<Markdown style={[styles.itemContent, { color: themes[theme].auxiliaryText }]} msg={content} theme={theme} /> <Markdown style={[styles.itemContent, { color: colors.auxiliaryText }]} msg={content} />
</View> </View>
); );
}; };

View File

@ -1,17 +1,16 @@
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { StyleSheet, Text } from 'react-native'; import { StyleSheet, Text } from 'react-native';
import { TSupportedThemes, useTheme } from '../../theme';
import sharedStyles from '../Styles';
import { themes } from '../../lib/constants';
import I18n from '../../i18n';
import { ISubscription } from '../../definitions'; import { ISubscription } from '../../definitions';
import { ILivechatVisitorModified } from './index'; import { ILivechatDepartment } from '../../definitions/ILivechatDepartment';
import { ILivechatVisitorModified } from '../../definitions/ILivechatVisitor';
import I18n from '../../i18n';
import { Services } from '../../lib/services';
import { useTheme } from '../../theme';
import sharedStyles from '../Styles';
import CustomFields from './CustomFields'; import CustomFields from './CustomFields';
import Item from './Item'; import Item from './Item';
import Timezone from './Timezone'; import Timezone from './Timezone';
import { ILivechatDepartment } from '../../definitions/ILivechatDepartment';
import { Services } from '../../lib/services';
const styles = StyleSheet.create({ const styles = StyleSheet.create({
title: { title: {
@ -21,13 +20,13 @@ const styles = StyleSheet.create({
} }
}); });
const Title = ({ title, theme }: { title: string; theme: TSupportedThemes }) => ( const Title = ({ title }: { title: string }) => {
<Text style={[styles.title, { color: themes[theme].titleText }]}>{title}</Text> const { colors } = useTheme();
); return <Text style={[styles.title, { color: colors.titleText }]}>{title}</Text>;
};
const Livechat = ({ room, roomUser }: { room: ISubscription; roomUser: ILivechatVisitorModified }) => { const Livechat = ({ room, roomUser }: { room: ISubscription; roomUser: ILivechatVisitorModified }): React.ReactElement => {
const [department, setDepartment] = useState<ILivechatDepartment>({} as ILivechatDepartment); const [department, setDepartment] = useState<ILivechatDepartment>({} as ILivechatDepartment);
const { theme } = useTheme();
const getDepartment = async (id: string) => { const getDepartment = async (id: string) => {
if (id) { if (id) {
@ -38,19 +37,16 @@ const Livechat = ({ room, roomUser }: { room: ISubscription; roomUser: ILivechat
} }
}; };
const getRoom = () => {
if (room.departmentId) {
getDepartment(room.departmentId);
}
};
useEffect(() => { useEffect(() => {
const getRoom = () => {
if (room.departmentId) getDepartment(room.departmentId);
};
getRoom(); getRoom();
}, [room]); }, [room.departmentId]);
return ( return (
<> <>
<Title title={I18n.t('User')} theme={theme} /> <Title title={I18n.t('User')} />
<Timezone utcOffset={roomUser.utc} /> <Timezone utcOffset={roomUser.utc} />
<Item label={I18n.t('Username')} content={roomUser.username} /> <Item label={I18n.t('Username')} content={roomUser.username} />
<Item <Item
@ -65,7 +61,7 @@ const Livechat = ({ room, roomUser }: { room: ISubscription; roomUser: ILivechat
<Item label={I18n.t('OS')} content={roomUser.os} /> <Item label={I18n.t('OS')} content={roomUser.os} />
<Item label={I18n.t('Browser')} content={roomUser.browser} /> <Item label={I18n.t('Browser')} content={roomUser.browser} />
<CustomFields customFields={roomUser.livechatData} /> <CustomFields customFields={roomUser.livechatData} />
<Title title={I18n.t('Conversation')} theme={theme} /> <Title title={I18n.t('Conversation')} />
<Item label={I18n.t('Agent')} content={room.servedBy?.username} /> <Item label={I18n.t('Agent')} content={room.servedBy?.username} />
{/* TODO: Will be deprecated */} {/* TODO: Will be deprecated */}
{/* @ts-ignore */} {/* @ts-ignore */}

View File

@ -1,34 +1,18 @@
import React from 'react';
import { connect } from 'react-redux';
import moment from 'moment'; import moment from 'moment';
import React from 'react';
import { IApplicationState } from '../../definitions';
import I18n from '../../i18n'; import I18n from '../../i18n';
import { useAppSelector } from '../../lib/hooks';
import Item from './Item'; import Item from './Item';
import { TSettingsValues } from '../../reducers/settings';
interface ITimezone { const Timezone = ({ utcOffset }: { utcOffset?: number }): React.ReactElement | null => {
utcOffset?: number; const Message_TimeFormat = useAppSelector(state => state.settings.Message_TimeFormat as string);
Message_TimeFormat?: TSettingsValues;
}
const Timezone = ({ utcOffset, Message_TimeFormat }: ITimezone) => { if (!utcOffset) return null;
if (!utcOffset) {
return null;
}
return ( return (
<Item <Item label={I18n.t('Timezone')} content={`${moment().utcOffset(utcOffset).format(Message_TimeFormat)} (UTC ${utcOffset})`} />
label={I18n.t('Timezone')}
content={`${moment()
.utcOffset(utcOffset)
.format(Message_TimeFormat as string)} (UTC ${utcOffset})`}
/>
); );
}; };
const mapStateToProps = (state: IApplicationState) => ({ export default Timezone;
Message_TimeFormat: state.settings.Message_TimeFormat
});
export default connect(mapStateToProps)(Timezone);

View File

@ -0,0 +1,110 @@
import React from 'react';
import { Text, View } from 'react-native';
import { BorderlessButton } from 'react-native-gesture-handler';
import { CustomIcon, TIconsName } from '../../../containers/CustomIcon';
import { ISubscription, SubscriptionType } from '../../../definitions';
import i18n from '../../../i18n';
import { useVideoConf } from '../../../lib/hooks/useVideoConf';
import { useTheme } from '../../../theme';
import styles from '../styles';
function BaseButton({
danger,
iconName,
onPress,
label,
showIcon = true,
enabled = true
}: {
danger?: boolean;
iconName: TIconsName;
onPress?: (prop: any) => void;
label: string;
showIcon?: boolean;
enabled?: boolean;
}): React.ReactElement | null {
const { colors } = useTheme();
const color = danger ? colors.dangerColor : colors.actionTintColor;
if (showIcon)
return (
<BorderlessButton enabled={enabled} testID={`room-info-view-${iconName}`} onPress={onPress} style={styles.roomButton}>
<CustomIcon name={iconName} size={30} color={color} />
<Text style={[styles.roomButtonText, { color }]}>{label}</Text>
</BorderlessButton>
);
return null;
}
function CallButton({ rid, roomFromRid }: { rid: string; isDirect: boolean; roomFromRid: boolean }): React.ReactElement | null {
const { callEnabled, disabledTooltip, showInitCallActionSheet } = useVideoConf(rid);
return (
<BaseButton
onPress={showInitCallActionSheet}
iconName='phone'
label={i18n.t('Call')}
enabled={!disabledTooltip}
showIcon={callEnabled && !roomFromRid}
/>
);
}
interface IRoomInfoButtons {
rid: string;
room: ISubscription | undefined;
roomUserId?: string;
isDirect: boolean;
fromRid?: string;
handleCreateDirectMessage: () => void;
handleIgnoreUser: () => void;
handleBlockUser: () => void;
roomFromRid: ISubscription | undefined;
}
export const RoomInfoButtons = ({
rid,
room: roomFromProps,
roomUserId,
isDirect,
fromRid,
handleCreateDirectMessage,
handleIgnoreUser,
handleBlockUser,
roomFromRid
}: IRoomInfoButtons): React.ReactElement => {
const room = roomFromRid || roomFromProps;
// Following the web behavior, when is a DM with myself, shouldn't appear block or ignore option
const isDmWithMyself = room?.uids && room.uids?.filter((uid: string) => uid !== roomUserId).length === 0;
const isFromDm = room?.t === SubscriptionType.DIRECT;
const isDirectFromSaved = isDirect && fromRid && room;
const isIgnored = room?.ignored?.includes?.(roomUserId || '');
const isBlocked = room?.blocker;
const renderIgnoreUser = isDirectFromSaved && !isFromDm && !isDmWithMyself;
const renderBlockUser = isDirectFromSaved && isFromDm;
return (
<View style={styles.roomButtonsContainer}>
<BaseButton onPress={handleCreateDirectMessage} label={i18n.t('Message')} iconName='message' />
<CallButton isDirect={isDirect} rid={rid} roomFromRid={!!roomFromRid} />
<BaseButton
onPress={handleIgnoreUser}
label={i18n.t(isIgnored ? 'Unignore' : 'Ignore')}
iconName='ignore'
showIcon={!!renderIgnoreUser}
danger
/>
<BaseButton
onPress={handleBlockUser}
label={i18n.t(`${isBlocked ? 'Unblock' : 'Block'}_user`)}
iconName='ignore'
showIcon={!!renderBlockUser}
danger
/>
</View>
);
};
export default RoomInfoButtons;

View File

@ -0,0 +1,47 @@
import React from 'react';
import { View } from 'react-native';
import { AvatarWithEdit } from '../../../containers/Avatar';
import Status from '../../../containers/Status';
import { SubscriptionType } from '../../../definitions';
import { useTheme } from '../../../theme';
import sharedStyles from '../../Styles';
import styles from '../styles';
const RoomInfoViewAvatar = ({
showEdit,
type,
username,
rid,
handleEditAvatar,
userId
}: {
showEdit: boolean;
type: SubscriptionType;
username: string;
rid?: string;
handleEditAvatar: () => void;
userId: string;
}): React.ReactElement => {
const { colors } = useTheme();
const showAvatarEdit = showEdit && type !== SubscriptionType.OMNICHANNEL;
return (
<AvatarWithEdit
text={username}
style={styles.avatar}
type={type}
rid={rid}
handleEdit={showAvatarEdit ? handleEditAvatar : undefined}
>
{type === SubscriptionType.DIRECT && userId ? (
<View style={[sharedStyles.status, { backgroundColor: colors.auxiliaryBackground }]}>
<Status size={20} id={userId} />
</View>
) : null}
</AvatarWithEdit>
);
};
export default RoomInfoViewAvatar;

View File

@ -0,0 +1,29 @@
import React from 'react';
import { ISubscription, SubscriptionType, IUser } from '../../../definitions';
import { ILivechatVisitorModified } from '../../../definitions/ILivechatVisitor';
import Channel from '../Channel';
import Direct from '../Direct';
import Livechat from '../Livechat';
const RoomInfoViewBody = ({
isDirect,
roomUser,
room
}: {
isDirect: boolean;
roomUser: IUser | ILivechatVisitorModified;
room?: ISubscription;
}): React.ReactElement => {
if (isDirect) {
return <Direct roomUser={roomUser as IUser} />;
}
if (room?.t === SubscriptionType.OMNICHANNEL && room) {
return <Livechat room={room} roomUser={roomUser as ILivechatVisitorModified} />;
}
return <Channel room={room} />;
};
export default RoomInfoViewBody;

View File

@ -0,0 +1,57 @@
import React from 'react';
import { Text, View } from 'react-native';
import { ISubscription, SubscriptionType } from '../../../definitions';
import styles from '../styles';
import { useTheme } from '../../../theme';
import { MarkdownPreview } from '../../../containers/markdown';
import RoomTypeIcon from '../../../containers/RoomTypeIcon';
import { getRoomTitle } from '../../../lib/methods/helpers';
interface IRoomInfoViewTitle {
room?: ISubscription;
name?: string;
username: string;
statusText?: string;
type: SubscriptionType;
}
const RoomInfoViewTitle = ({ room, name, username, statusText, type }: IRoomInfoViewTitle): React.ReactElement => {
const { colors } = useTheme();
if (type === SubscriptionType.DIRECT) {
return (
<>
<Text testID='room-info-view-name' style={[styles.roomTitle, { color: colors.titleText }]}>
{name}
</Text>
{username && (
<Text
testID='room-info-view-username'
style={[styles.roomUsername, { color: colors.auxiliaryText }]}
>{`@${username}`}</Text>
)}
{!!statusText && (
<View testID='room-info-view-custom-status'>
<MarkdownPreview msg={statusText} style={[styles.roomUsername, { color: colors.auxiliaryText }]} />
</View>
)}
</>
);
}
return (
<View style={styles.roomTitleContainer}>
<RoomTypeIcon
type={room?.prid ? 'discussion' : type}
teamMain={room?.teamMain}
key='room-info-type'
status={room?.visitor?.status}
sourceType={room?.source}
/>
<Text testID='room-info-view-name' style={[styles.roomTitle, { color: colors.titleText }]} key='room-info-name'>
{getRoomTitle(room)}
</Text>
</View>
);
};
export default RoomInfoViewTitle;

View File

@ -1,58 +0,0 @@
import React from 'react';
import { Text } from 'react-native';
import { BorderlessButton } from 'react-native-gesture-handler';
import { CustomIcon, TIconsName } from '../../../containers/CustomIcon';
import styles from '../styles';
import { useTheme } from '../../../theme';
import { useVideoConf } from '../../../lib/hooks/useVideoConf';
import i18n from '../../../i18n';
import { useAppSelector } from '../../../lib/hooks';
import { compareServerVersion } from '../../../lib/methods/helpers';
// TODO: change other icons on future
function UserInfoButton({
danger,
iconName,
onPress,
label,
showIcon,
enabled = true
}: {
danger?: boolean;
iconName: TIconsName;
onPress?: (prop: any) => void;
label: string;
showIcon?: boolean;
enabled?: boolean;
}): React.ReactElement | null {
const { colors } = useTheme();
let color = danger ? colors.dangerColor : colors.actionTintColor;
if (!enabled) color = colors.auxiliaryText;
if (showIcon)
return (
<BorderlessButton enabled={enabled} testID={`room-info-view-${iconName}`} onPress={onPress} style={styles.roomButton}>
<CustomIcon name={iconName} size={30} color={color} />
<Text style={[styles.roomButtonText, { color }]}>{label}</Text>
</BorderlessButton>
);
return null;
}
export function CallButton({ rid, isDirect }: { rid: string; isDirect: boolean }): React.ReactElement | null {
const { callEnabled, showInitCallActionSheet, disabledTooltip } = useVideoConf(rid);
const serverVersion = useAppSelector(state => state.server.version);
const greaterThanFive = compareServerVersion(serverVersion, 'greaterThanOrEqualTo', '5.0.0');
const showIcon = greaterThanFive ? callEnabled : callEnabled && isDirect;
return (
<UserInfoButton
enabled={!disabledTooltip}
onPress={showInitCallActionSheet}
iconName='phone'
label={i18n.t('Call')}
showIcon={showIcon}
/>
);
}

View File

@ -1,226 +1,124 @@
import { CompositeNavigationProp, RouteProp } from '@react-navigation/native'; import { CompositeNavigationProp, RouteProp, useNavigation, useRoute } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack'; import { StackNavigationProp } from '@react-navigation/stack';
import { uniq } from 'lodash'; import { uniq } from 'lodash';
import isEmpty from 'lodash/isEmpty'; import isEmpty from 'lodash/isEmpty';
import React from 'react'; import React, { useEffect, useRef, useState } from 'react';
import { ScrollView, Text, View } from 'react-native'; import { ScrollView, View } from 'react-native';
import { BorderlessButton } from 'react-native-gesture-handler'; import { Subscription } from 'rxjs';
import { connect } from 'react-redux';
import { Observable, Subscription } from 'rxjs';
import UAParser from 'ua-parser-js'; import UAParser from 'ua-parser-js';
import { AvatarWithEdit } from '../../containers/Avatar';
import { CustomIcon, TIconsName } from '../../containers/CustomIcon';
import * as HeaderButton from '../../containers/HeaderButton'; import * as HeaderButton from '../../containers/HeaderButton';
import RoomTypeIcon from '../../containers/RoomTypeIcon';
import SafeAreaView from '../../containers/SafeAreaView'; import SafeAreaView from '../../containers/SafeAreaView';
import Status from '../../containers/Status';
import StatusBar from '../../containers/StatusBar'; import StatusBar from '../../containers/StatusBar';
import { LISTENER } from '../../containers/Toast'; import { LISTENER } from '../../containers/Toast';
import { MarkdownPreview } from '../../containers/markdown'; import { ISubscription, IUser, SubscriptionType } from '../../definitions';
import { IApplicationState, ISubscription, IUser, SubscriptionType, TSubscriptionModel } from '../../definitions';
import { ILivechatVisitor } from '../../definitions/ILivechatVisitor';
import I18n from '../../i18n'; import I18n from '../../i18n';
import { themes } from '../../lib/constants';
import { getSubscriptionByRoomId } from '../../lib/database/services/Subscription'; import { getSubscriptionByRoomId } from '../../lib/database/services/Subscription';
import { useAppSelector } from '../../lib/hooks';
import { getRoomTitle, getUidDirectMessage, hasPermission } from '../../lib/methods/helpers'; import { getRoomTitle, getUidDirectMessage, hasPermission } from '../../lib/methods/helpers';
import EventEmitter from '../../lib/methods/helpers/events'; import EventEmitter from '../../lib/methods/helpers/events';
import { goRoom } from '../../lib/methods/helpers/goRoom'; import { goRoom } from '../../lib/methods/helpers/goRoom';
import { handleIgnore } from '../../lib/methods/helpers/handleIgnore'; import { handleIgnore } from '../../lib/methods/helpers/handleIgnore';
import log, { events, logEvent } from '../../lib/methods/helpers/log'; import log, { events, logEvent } from '../../lib/methods/helpers/log';
import Navigation from '../../lib/navigation/appNavigation';
import { Services } from '../../lib/services'; import { Services } from '../../lib/services';
import { TUsersRoles } from '../../reducers/usersRoles';
import { MasterDetailInsideStackParamList } from '../../stacks/MasterDetailStack/types'; import { MasterDetailInsideStackParamList } from '../../stacks/MasterDetailStack/types';
import { ChatsStackParamList } from '../../stacks/types'; import { ChatsStackParamList } from '../../stacks/types';
import { TSupportedThemes, withTheme } from '../../theme'; import { useTheme } from '../../theme';
import sharedStyles from '../Styles'; import RoomInfoButtons from './components/RoomInfoButtons';
import Channel from './Channel'; import RoomInfoViewAvatar from './components/RoomInfoViewAvatar';
import Direct from './Direct'; import RoomInfoViewBody from './components/RoomInfoViewBody';
import Livechat from './Livechat'; import RoomInfoViewTitle from './components/RoomInfoViewTitle';
import { CallButton } from './components/UserInfoButton';
import styles from './styles'; import styles from './styles';
interface IGetRoomTitle { type TRoomInfoViewNavigationProp = CompositeNavigationProp<
room: ISubscription; StackNavigationProp<ChatsStackParamList, 'RoomInfoView'>,
type: SubscriptionType; StackNavigationProp<MasterDetailInsideStackParamList>
name?: string; >;
username: string;
statusText?: string;
theme: TSupportedThemes;
}
const renderRoomTitle = ({ room, type, name, username, statusText, theme }: IGetRoomTitle) => type TRoomInfoViewRouteProp = RouteProp<ChatsStackParamList, 'RoomInfoView'>;
type === SubscriptionType.DIRECT ? (
<> const RoomInfoView = (): React.ReactElement => {
<Text testID='room-info-view-name' style={[styles.roomTitle, { color: themes[theme].titleText }]}> const {
{name} params: { rid, t, fromRid, member, room: roomParam, showCloseModal }
</Text> } = useRoute<TRoomInfoViewRouteProp>();
{username && ( const { addListener, setOptions, navigate, goBack } = useNavigation<TRoomInfoViewNavigationProp>();
<Text
testID='room-info-view-username' const [room, setRoom] = useState(roomParam);
style={[styles.roomUsername, { color: themes[theme].auxiliaryText }]} const [roomFromRid, setRoomFromRid] = useState<ISubscription | undefined>();
>{`@${username}`}</Text> const [roomUser, setRoomUser] = useState(member || {});
)} const [showEdit, setShowEdit] = useState(false);
{!!statusText && (
<View testID='room-info-view-custom-status'> const roomType = room?.t || t;
<MarkdownPreview msg={statusText} style={[styles.roomUsername, { color: themes[theme].auxiliaryText }]} /> const isDirect = roomType === SubscriptionType.DIRECT;
</View> const isLivechat = roomType === SubscriptionType.OMNICHANNEL;
)}
</> const subscription = useRef<Subscription | undefined>(undefined);
) : (
<View style={styles.roomTitleRow}> const {
<RoomTypeIcon isMasterDetail,
type={room.prid ? 'discussion' : room.t} subscribedRoom,
teamMain={room.teamMain} usersRoles,
key='room-info-type' roles,
status={room.visitor?.status} // permissions
sourceType={room.source} editRoomPermission,
/> editOmnichannelContact,
<Text testID='room-info-view-name' style={[styles.roomTitle, { color: themes[theme].titleText }]} key='room-info-name'> editLivechatRoomCustomfields
{getRoomTitle(room)} } = useAppSelector(state => ({
</Text> subscribedRoom: state.room.subscribedRoom,
</View> isMasterDetail: state.app.isMasterDetail,
roles: state.roles,
usersRoles: state.usersRoles,
// permissions
editRoomPermission: state.permissions['edit-room'],
editOmnichannelContact: state.permissions['edit-omnichannel-contact'],
editLivechatRoomCustomfields: state.permissions['edit-livechat-room-customfields']
}));
const { colors } = useTheme();
useEffect(() => {
const listener = addListener('focus', () => (isLivechat ? loadVisitor() : null));
return () => listener();
}, []);
useEffect(
() => () => {
subscription.current?.unsubscribe();
},
[]
); );
interface IRoomInfoViewProps { useEffect(() => {
navigation: CompositeNavigationProp< loadRoom();
StackNavigationProp<ChatsStackParamList, 'RoomInfoView'>, if (isDirect) loadUser();
StackNavigationProp<MasterDetailInsideStackParamList> }, []);
>;
route: RouteProp<ChatsStackParamList, 'RoomInfoView'>;
subscribedRoom: string;
theme: TSupportedThemes;
isMasterDetail: boolean;
jitsiEnabled: boolean;
editRoomPermission?: string[];
editOmnichannelContact?: string[];
editLivechatRoomCustomfields?: string[];
roles: { [key: string]: string };
usersRoles: TUsersRoles;
}
export interface IUserParsed extends IUser { const setHeader = (canEdit?: boolean) => {
parsedRoles?: string[]; const HeaderRight = () => (
} <HeaderButton.Container>
<HeaderButton.Item
export interface ILivechatVisitorModified extends ILivechatVisitor { iconName='edit'
os?: string; onPress={() => {
browser?: string; if (!room) return;
} logEvent(events[`RI_GO_${isLivechat ? 'LIVECHAT' : 'RI'}_EDIT`]);
const navigationProps = { room, roomUser };
interface IRoomInfoViewState { if (isLivechat) navigate('LivechatEditView', navigationProps);
room: ISubscription; else navigate('RoomInfoEditView', { rid, ...navigationProps });
roomUser: IUserParsed | ILivechatVisitorModified; }}
showEdit: boolean; testID='room-info-view-edit-button'
roomFromRid?: TSubscriptionModel; />
} </HeaderButton.Container>
);
class RoomInfoView extends React.Component<IRoomInfoViewProps, IRoomInfoViewState> { setOptions({
private rid: string; headerLeft: showCloseModal ? () => <HeaderButton.CloseModal /> : undefined,
title: isDirect ? I18n.t('User_Info') : I18n.t('Room_Info'),
private t: SubscriptionType; headerRight: canEdit ? () => <HeaderRight /> : undefined
private unsubscribeFocus?: () => void;
private subscription?: Subscription;
private roomObservable?: Observable<TSubscriptionModel>;
private fromRid?: string;
private subscriptionRoomFromRid?: Subscription;
constructor(props: IRoomInfoViewProps) {
super(props);
const room = props.route.params?.room;
const roomUser = props.route.params?.member;
this.rid = props.route.params?.rid;
this.t = props.route.params?.t;
this.fromRid = props.route.params?.fromRid;
this.state = {
room: (room || { rid: this.rid, t: this.t }) as any,
roomUser: roomUser || {},
showEdit: false,
roomFromRid: undefined
};
}
componentDidMount() {
if (this.isDirect) {
this.loadUser();
this.loadRoomFromRid();
} else {
this.loadRoom();
}
this.setHeader();
const { navigation } = this.props;
this.unsubscribeFocus = navigation.addListener('focus', () => {
if (this.isLivechat) {
this.loadVisitor();
}
});
}
componentWillUnmount() {
if (this.subscription && this.subscription.unsubscribe) {
this.subscription.unsubscribe();
}
if (this.subscriptionRoomFromRid && this.subscriptionRoomFromRid.unsubscribe) {
this.subscriptionRoomFromRid.unsubscribe();
}
if (this.unsubscribeFocus) {
this.unsubscribeFocus();
}
}
setHeader = () => {
const { roomUser, room, showEdit } = this.state;
const { navigation, route } = this.props;
const t = route.params?.t;
const rid = route.params?.rid;
const showCloseModal = route.params?.showCloseModal;
navigation.setOptions({
headerLeft: showCloseModal ? () => <HeaderButton.CloseModal navigation={navigation} /> : undefined,
title: t === SubscriptionType.DIRECT ? I18n.t('User_Info') : I18n.t('Room_Info'),
headerRight: showEdit
? () => (
<HeaderButton.Container>
<HeaderButton.Item
iconName='edit'
onPress={() => {
const isLivechat = t === SubscriptionType.OMNICHANNEL;
logEvent(events[`RI_GO_${isLivechat ? 'LIVECHAT' : 'RI'}_EDIT`]);
navigation.navigate(isLivechat ? 'LivechatEditView' : 'RoomInfoEditView', { rid, room, roomUser });
}}
testID='room-info-view-edit-button'
/>
</HeaderButton.Container>
)
: undefined
}); });
}; };
get isDirect() { const loadVisitor = async () => {
const { room } = this.state;
return room.t === SubscriptionType.DIRECT;
}
get isLivechat() {
const { room } = this.state;
return room.t === SubscriptionType.OMNICHANNEL;
}
getRoleDescription = (id: string) => {
const { roles } = this.props;
return roles[id];
};
loadVisitor = async () => {
const { room } = this.state;
try { try {
if (room.visitor?._id) { if (room?.visitor?._id) {
const result = await Services.getVisitorInfo(room.visitor._id); const result = await Services.getVisitorInfo(room.visitor._id);
if (result.success) { if (result.success) {
const { visitor } = result; const { visitor } = result;
@ -231,7 +129,8 @@ class RoomInfoView extends React.Component<IRoomInfoViewProps, IRoomInfoViewStat
params.os = `${ua.getOS().name} ${ua.getOS().version}`; params.os = `${ua.getOS().name} ${ua.getOS().version}`;
params.browser = `${ua.getBrowser().name} ${ua.getBrowser().version}`; params.browser = `${ua.getBrowser().name} ${ua.getBrowser().version}`;
} }
this.setState({ roomUser: { ...visitor, ...params } as ILivechatVisitorModified }, () => this.setHeader()); setRoomUser({ ...visitor, ...params });
setHeader();
} }
} }
} catch (error) { } catch (error) {
@ -239,150 +138,116 @@ class RoomInfoView extends React.Component<IRoomInfoViewProps, IRoomInfoViewStat
} }
}; };
parseRoles = (roleArray: string[]) => const parseRoles = (roleArray: string[]) => roleArray.map(role => roles[role]);
Promise.all(
roleArray.map(async role => {
const description = await this.getRoleDescription(role);
return description;
})
);
setUser = async (user: IUser) => { const handleRoles = (user: Pick<IUser, 'username' | 'roles'>) => {
const roles = (() => { const rrr = (() => {
const { usersRoles } = this.props;
const userRoles = usersRoles.find(u => u?.username === user.username); const userRoles = usersRoles.find(u => u?.username === user.username);
let r: string[] = []; let r: string[] = [];
if (userRoles?.roles?.length) r = userRoles.roles; if (userRoles?.roles?.length) r = userRoles.roles;
if (user.roles?.length) r = [...r, ...user.roles]; if (user.roles?.length) r = [...r, ...user.roles];
return uniq(r); return uniq(r);
})(); })();
if (roles.length) { if (rrr.length) {
const parsedRoles = await this.parseRoles(roles); const parsedRoles = parseRoles(rrr);
this.setState({ roomUser: { ...user, parsedRoles } }); return parsedRoles;
} else {
this.setState({ roomUser: user });
} }
}; };
loadUser = async () => { const loadUser = async () => {
const { room, roomUser } = this.state;
if (isEmpty(roomUser)) { if (isEmpty(roomUser)) {
try { try {
const roomUserId = getUidDirectMessage(room); const roomUserId = getUidDirectMessage(room || { rid, t });
const result = await Services.getUserInfo(roomUserId); const result = await Services.getUserInfo(roomUserId);
if (result.success) { if (result.success) {
const { user } = result; const { user } = result;
this.setUser(user as IUser); const r = handleRoles(user);
setRoomUser({ ...user, roles: r });
} }
} catch { } catch {
// do nothing // do nothing
} }
} else {
this.setUser(roomUser as IUser);
} }
const r = handleRoles(roomUser);
if (r) setRoomUser({ ...roomUser, roles: r });
}; };
loadRoomFromRid = async () => { const loadRoom = async () => {
if (this.fromRid) { const permissionToEdit = isLivechat ? [editOmnichannelContact, editLivechatRoomCustomfields] : [editRoomPermission];
try { const permissions = await hasPermission(permissionToEdit, rid);
const sub = await getSubscriptionByRoomId(this.fromRid); const canEdit = permissions.some(Boolean);
this.subscriptionRoomFromRid = sub?.observe().subscribe(roomFromRid => { const subRoom = await getSubscriptionByRoomId(rid);
this.setState({ roomFromRid }); if (!subRoom && isDirect && fromRid) {
const roomFromRid = await getSubscriptionByRoomId(fromRid);
if (roomFromRid?.observe) {
const sub = roomFromRid.observe();
subscription.current = sub.subscribe(changes => {
setRoomFromRid(changes.asPlain());
}); });
} catch (e) {
// do nothing
} }
} } else if (subRoom?.observe) {
}; const sub = subRoom.observe();
subscription.current = sub.subscribe(changes => {
loadRoom = async () => { setRoom(changes.asPlain());
const { room: roomState } = this.state; setHeader(canEdit);
const { route, editRoomPermission, editOmnichannelContact, editLivechatRoomCustomfields } = this.props;
let room = route.params?.room as any;
const roomModel = room as TSubscriptionModel;
if (roomModel && roomModel.observe) {
this.roomObservable = roomModel.observe();
this.subscription = this.roomObservable.subscribe(changes => {
this.setState({ room: changes }, () => this.setHeader());
}); });
} else { } else {
try { try {
const result = await Services.getRoomInfo(this.rid); if (!isDirect) {
if (result.success) { const result = await Services.getRoomInfo(rid);
({ room } = result); if (result.success) setRoom({ ...room, ...(result.room as unknown as ISubscription) });
this.setState({ room: { ...roomState, ...room } });
} }
} catch (e) { } catch (e) {
log(e); log(e);
} }
} }
setShowEdit(canEdit);
const permissionToEdit = this.isLivechat ? [editOmnichannelContact, editLivechatRoomCustomfields] : [editRoomPermission]; setHeader(canEdit);
const permissions = await hasPermission(permissionToEdit, room.rid);
if (permissions.some(Boolean)) {
this.setState({ showEdit: true }, () => this.setHeader());
}
}; };
createDirect = () => const createDirect = () =>
new Promise<void>(async (resolve, reject) => { new Promise<void | ISubscription>(async (resolve, reject) => {
const { route } = this.props;
// We don't need to create a direct // We don't need to create a direct
const member = route.params?.member; if (!isEmpty(member)) return resolve();
if (!isEmpty(member)) {
return resolve();
}
// TODO: Check if some direct with the user already exists on database
try { try {
const { const result = await Services.createDirectMessage(roomUser.username);
roomUser: { username } if (result.success) return resolve({ ...roomUser, rid: result.room.rid });
} = this.state;
const result = await Services.createDirectMessage(username);
if (result.success) {
const {
room: { rid }
} = result;
return this.setState(({ room }) => ({ room: { ...room, rid } }), resolve);
}
} catch { } catch {
// do nothing reject();
} }
reject();
}); });
goRoom = () => { const handleGoRoom = (r?: ISubscription) => {
logEvent(events.RI_GO_ROOM_USER); logEvent(events.RI_GO_ROOM_USER);
const { room } = this.state;
const { navigation, isMasterDetail, subscribedRoom } = this.props;
const params = { const params = {
rid: room.rid, rid: r?.rid,
name: getRoomTitle(room), name: getRoomTitle(r),
t: room.t, t: r?.t,
roomUserId: getUidDirectMessage(room) roomUserId: getUidDirectMessage(r)
}; };
if (room.rid) { if (r?.rid) {
if (room.rid === subscribedRoom) { if (r.rid === subscribedRoom) {
if (isMasterDetail) { if (isMasterDetail) {
return Navigation.navigate('DrawerNavigator'); return navigate('DrawerNavigator');
} }
return navigation.goBack(); goBack();
goBack();
return;
} }
// if it's on master detail layout, we close the modal and replace RoomView // if it's on master detail layout, we close the modal and replace RoomView
goRoom({ item: params, isMasterDetail, popToRoot: true }); goRoom({ item: params, isMasterDetail, popToRoot: true });
} }
}; };
handleCreateDirectMessage = async (onPress: () => void) => { const handleCreateDirectMessage = async () => {
try { try {
if (this.isDirect) { let r = room;
await this.createDirect(); if (isDirect) {
const direct = await createDirect();
if (direct) r = direct;
} }
onPress(); handleGoRoom(r);
} catch { } catch {
EventEmitter.emit(LISTENER, { EventEmitter.emit(LISTENER, {
message: I18n.t('error-action-not-allowed', { action: I18n.t('Create_Direct_Messages') }) message: I18n.t('error-action-not-allowed', { action: I18n.t('Create_Direct_Messages') })
@ -390,144 +255,61 @@ class RoomInfoView extends React.Component<IRoomInfoViewProps, IRoomInfoViewStat
} }
}; };
handleBlockUser = async (rid: string, blocked: string, block: boolean) => { const handleBlockUser = async () => {
const r = roomFromRid || room;
const userBlocked = roomUser._id;
const blocker = r?.blocker;
if (!r?.rid) return;
logEvent(events.RI_TOGGLE_BLOCK_USER); logEvent(events.RI_TOGGLE_BLOCK_USER);
try { try {
await Services.toggleBlockUser(rid, blocked, block); await Services.toggleBlockUser(r.rid, userBlocked, !blocker);
} catch (e) { } catch (e) {
log(e); log(e);
} }
}; };
handleEditAvatar = () => { const handleIgnoreUser = () => {
const { navigation } = this.props; const r = roomFromRid || room;
const { room } = this.state; const isIgnored = r?.ignored?.includes?.(roomUser._id);
navigation.navigate('ChangeAvatarView', { titleHeader: I18n.t('Room_Info'), room, t: this.t, context: 'room' }); if (r?.rid) handleIgnore(roomUser._id, !isIgnored, r?.rid);
}; };
renderAvatar = (room: ISubscription, roomUser: IUserParsed) => { return (
const { theme } = this.props; <ScrollView style={[styles.scroll, { backgroundColor: colors.backgroundColor }]}>
const { showEdit } = this.state; <StatusBar />
const showAvatarEdit = showEdit && this.t !== SubscriptionType.OMNICHANNEL; <SafeAreaView style={{ backgroundColor: colors.backgroundColor }} testID='room-info-view'>
<View style={[styles.avatarContainer, { backgroundColor: colors.auxiliaryBackground }]}>
<RoomInfoViewAvatar
username={room?.name || roomUser.username}
rid={room?.rid}
userId={roomUser?._id}
handleEditAvatar={() => navigate('ChangeAvatarView', { titleHeader: I18n.t('Room_Info'), room, t, context: 'room' })}
showEdit={showEdit}
type={t}
/>
<RoomInfoViewTitle
type={t}
room={room || roomUser}
name={roomUser?.name}
username={roomUser?.username}
statusText={roomUser?.statusText}
/>
<RoomInfoButtons
rid={room?.rid || rid}
fromRid={fromRid}
handleBlockUser={handleBlockUser}
handleCreateDirectMessage={handleCreateDirectMessage}
handleIgnoreUser={handleIgnoreUser}
isDirect={isDirect}
room={room || roomUser}
roomUserId={roomUser?._id}
roomFromRid={roomFromRid}
/>
</View>
<RoomInfoViewBody isDirect={isDirect} room={room} roomUser={roomUser} />
</SafeAreaView>
</ScrollView>
);
};
return ( export default RoomInfoView;
<AvatarWithEdit
text={room.name || roomUser.username}
style={styles.avatar}
type={this.t}
rid={room?.rid}
handleEdit={showAvatarEdit ? this.handleEditAvatar : undefined}
>
{this.t === SubscriptionType.DIRECT && roomUser._id ? (
<View style={[sharedStyles.status, { backgroundColor: themes[theme].auxiliaryBackground }]}>
<Status size={20} id={roomUser._id} />
</View>
) : null}
</AvatarWithEdit>
);
};
renderButton = (onPress: () => void, iconName: TIconsName, text: string, danger?: boolean) => {
const { theme } = this.props;
const color = danger ? themes[theme].dangerColor : themes[theme].actionTintColor;
return (
<BorderlessButton testID={`room-info-view-${iconName}`} onPress={onPress} style={styles.roomButton}>
<CustomIcon name={iconName} size={30} color={color} />
<Text style={[styles.roomButtonText, { color }]}>{text}</Text>
</BorderlessButton>
);
};
renderButtons = () => {
const { roomFromRid, roomUser, room } = this.state;
const isFromDm = roomFromRid?.rid ? new RegExp(roomUser._id).test(roomFromRid.rid) : false;
const isDirectFromSaved = this.isDirect && this.fromRid && roomFromRid;
// Following the web behavior, when is a DM with myself, shouldn't appear block or ignore option
const isDmWithMyself = roomFromRid?.uids && roomFromRid.uids?.filter(uid => uid !== roomUser._id).length === 0;
const ignored = roomFromRid?.ignored;
const isIgnored = ignored?.includes?.(roomUser._id);
const blocker = roomFromRid?.blocker;
return (
<View style={styles.roomButtonsContainer}>
{this.renderButton(() => this.handleCreateDirectMessage(this.goRoom), 'message', I18n.t('Message'))}
<CallButton isDirect={this.isDirect} rid={room.rid} />
{isDirectFromSaved && !isFromDm && !isDmWithMyself
? this.renderButton(
() => handleIgnore(roomUser._id, !isIgnored, roomFromRid.rid),
'ignore',
I18n.t(isIgnored ? 'Unignore' : 'Ignore'),
true
)
: null}
{isDirectFromSaved && isFromDm
? this.renderButton(
() => this.handleBlockUser(roomFromRid.rid, roomUser._id, !blocker),
'ignore',
I18n.t(`${blocker ? 'Unblock' : 'Block'}_user`),
true
)
: null}
</View>
);
};
renderContent = () => {
const { room, roomUser } = this.state;
if (this.isDirect) {
return <Direct roomUser={roomUser as IUserParsed} />;
}
if (this.t === SubscriptionType.OMNICHANNEL) {
return <Livechat room={room} roomUser={roomUser as ILivechatVisitorModified} />;
}
return <Channel room={room} />;
};
render() {
const { room, roomUser } = this.state;
const { theme } = this.props;
const roomUserParsed = roomUser as IUserParsed;
return (
<ScrollView style={[styles.scroll, { backgroundColor: themes[theme].backgroundColor }]}>
<StatusBar />
<SafeAreaView style={{ backgroundColor: themes[theme].backgroundColor }} testID='room-info-view'>
<View style={[styles.avatarContainer, { backgroundColor: themes[theme].auxiliaryBackground }]}>
{this.renderAvatar(room, roomUserParsed)}
<View style={styles.roomTitleContainer}>
{renderRoomTitle({
room,
type: this.t,
name: roomUserParsed?.name,
username: roomUserParsed?.username,
statusText: roomUserParsed?.statusText,
theme
})}
</View>
{this.renderButtons()}
</View>
{this.renderContent()}
</SafeAreaView>
</ScrollView>
);
}
}
const mapStateToProps = (state: IApplicationState) => ({
subscribedRoom: state.room.subscribedRoom,
isMasterDetail: state.app.isMasterDetail,
jitsiEnabled: (state.settings.Jitsi_Enabled as boolean) || false,
editRoomPermission: state.permissions['edit-room'],
editOmnichannelContact: state.permissions['edit-omnichannel-contact'],
editLivechatRoomCustomfields: state.permissions['edit-livechat-room-customfields'],
roles: state.roles,
usersRoles: state.usersRoles
});
export default connect(mapStateToProps)(withTheme(RoomInfoView));

View File

@ -30,7 +30,8 @@ export default StyleSheet.create({
roomTitleContainer: { roomTitleContainer: {
paddingTop: 32, paddingTop: 32,
marginHorizontal: 16, marginHorizontal: 16,
alignItems: 'center' alignItems: 'center',
flexDirection: 'row'
}, },
roomTitle: { roomTitle: {
fontSize: 20, fontSize: 20,

View File

@ -196,4 +196,4 @@ export const initApi = async (user: string, password: string): Promise<AxiosInst
api.defaults.headers.common['X-User-Id'] = userId; api.defaults.headers.common['X-User-Id'] = userId;
api.defaults.headers.common['X-Auth-Token'] = authToken; api.defaults.headers.common['X-Auth-Token'] = authToken;
return api; return api;
}; };