Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Room roles visibility in members panel #34850

Draft
wants to merge 2 commits into
base: feat/add-endpoints-groups.membersOrderedByRole-channels.membersOrderedByRole
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions apps/meteor/client/views/hooks/useMembersList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,23 @@ type MembersListOptions = {

const endpointsByRoomType = {
d: '/v1/im.members',
p: '/v1/groups.members',
c: '/v1/channels.members',
p: '/v1/rooms.membersOrderedByRole',
c: '/v1/rooms.membersOrderedByRole',
} as const;

export const useMembersList = (options: MembersListOptions) => {
const getMembers = useEndpoint('GET', endpointsByRoomType[options.roomType]);

return useInfiniteQuery(
[options.roomType, 'members', options.rid, options.type, options.debouncedText],
['members', options.roomType, options.rid, options.type, options.debouncedText],
async ({ pageParam }) => {
const start = pageParam ?? 0;

return getMembers({
roomId: options.rid,
offset: start,
count: 20,
rolesOrder: ['owner', 'moderator'],
...(options.debouncedText && { filter: options.debouncedText }),
...(options.type !== 'all' && { status: [options.type] }),
});
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Box } from '@rocket.chat/fuselage';
import type { TranslationKey } from '@rocket.chat/ui-contexts';
import React from 'react';
import { useTranslation } from 'react-i18next';

type MembersListDividerProps = {
title: TranslationKey;
};

export const MembersListDivider = ({ title }: MembersListDividerProps) => {
const { t } = useTranslation();

return (
<Box key={title} backgroundColor='room' height={36} fontScale='p2m' color='defaut' paddingBlock={8} paddingInlineStart={12}>
<Box>{t(title)}</Box>
</Box>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ Default.args = {
username: 'rocket.cat',
status: UserStatus.ONLINE,
name: 'Rocket.Cat',
roles: ['owner'],
},
],
text: 'filter',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import type { IRoom, IUser } from '@rocket.chat/core-typings';
import type { IRoom, IUser, IRole } from '@rocket.chat/core-typings';
import type { SelectOption } from '@rocket.chat/fuselage';
import { Box, Icon, TextInput, Select, Throbber, ButtonGroup, Button, Callout } from '@rocket.chat/fuselage';
import { useAutoFocus, useDebouncedCallback } from '@rocket.chat/fuselage-hooks';
import { useTranslation, useSetting } from '@rocket.chat/ui-contexts';
import type { ReactElement, FormEventHandler, ComponentProps, MouseEvent } from 'react';
import React, { useMemo } from 'react';
import { Virtuoso } from 'react-virtuoso';
import { GroupedVirtuoso } from 'react-virtuoso';

import { MembersListDivider } from './MembersListDivider';
import RoomMembersRow from './RoomMembersRow';
import {
ContextualbarHeader,
Expand All @@ -21,7 +22,7 @@ import {
import { VirtuosoScrollbars } from '../../../../components/CustomScrollbars';
import InfiniteListAnchor from '../../../../components/InfiniteListAnchor';

type RoomMemberUser = Pick<IUser, 'username' | '_id' | 'name' | 'status' | 'freeSwitchExtension'>;
type RoomMemberUser = Pick<IUser, 'username' | '_id' | 'name' | 'status' | 'freeSwitchExtension'> & { roles?: IRole['_id'][] };

type RoomMembersProps = {
rid: IRoom['_id'];
Expand Down Expand Up @@ -86,6 +87,32 @@ const RoomMembers = ({

const useRealName = useSetting('UI_Use_Real_Name', false);

const { counts, titles } = useMemo(() => {
const owners = members.filter((member) => member.roles?.includes('owner'));
const moderators = members.filter((member) => !member.roles?.includes('owner') && member.roles?.includes('moderator'));
const normalMembers = members.filter((member) => !member.roles?.includes('owner') && !member.roles?.includes('moderator'));

const counts = [];
const titles = [];

if (owners.length > 0) {
counts.push(owners.length);
titles.push(<MembersListDivider title='Owners' />);
}

if (moderators.length > 0) {
counts.push(moderators.length);
titles.push(<MembersListDivider title='Moderators' />);
}

if (members.length > 0) {
counts.push(normalMembers.length);
titles.push(<MembersListDivider title='Members' />);
}

return { counts, titles };
}, [members]);

return (
<>
<ContextualbarHeader data-qa-id='RoomHeader-Members'>
Expand Down Expand Up @@ -129,18 +156,18 @@ const RoomMembers = ({
</Box>

<Box w='full' h='full' overflow='hidden' flexShrink={1}>
<Virtuoso
<GroupedVirtuoso
style={{
height: '100%',
width: '100%',
}}
totalCount={total}
overscan={50}
data={members}
groupCounts={counts}
groupContent={(index): ReactElement => titles[index]}
// eslint-disable-next-line react/no-multi-comp
components={{ Scroller: VirtuosoScrollbars, Footer: () => <InfiniteListAnchor loadMore={loadMoreMembers} /> }}
itemContent={(index, data): ReactElement => (
<RowComponent useRealName={useRealName} data={itemData} user={data} index={index} reload={reload} />
itemContent={(index): ReactElement => (
<RowComponent useRealName={useRealName} data={itemData} user={members[index]} index={index} reload={reload} />
)}
/>
</Box>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import React, { useCallback, useMemo } from 'react';

import GenericModal from '../../../../../components/GenericModal';
import { useEndpointAction } from '../../../../../hooks/useEndpointAction';
import { queryClient } from '../../../../../lib/queryClient';
import { roomCoordinator } from '../../../../../lib/rooms/roomCoordinator';
import { getRoomDirectives } from '../../../lib/getRoomDirectives';
import { useUserHasRoomRole } from '../../useUserHasRoomRole';
Expand Down Expand Up @@ -63,15 +64,18 @@ export const useChangeModeratorAction = (user: Pick<IUser, '_id' | 'username'>,
successMessage: t(changeModeratorMessage, { username: user.username, room_name: roomName }),
});

const handleConfirm = useCallback(() => {
changeModerator({ roomId: rid, userId: uid });
const handleConfirm = useCallback(async () => {
await changeModerator({ roomId: rid, userId: uid });
queryClient.invalidateQueries({ queryKey: ['members'] });
closeModal();
}, [changeModerator, rid, uid, closeModal]);

const handleChangeModerator = useCallback(
({ userId }) => {
async ({ userId }) => {
if (!isRoomFederated(room)) {
return changeModerator({ roomId: rid, userId: uid });
await changeModerator({ roomId: rid, userId: uid });
queryClient.invalidateQueries({ queryKey: ['members'] });
return;
}

const changingOwnRole = userId === loggedUserId;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { isRoomFederated } from '@rocket.chat/core-typings';
import { useMutableCallback } from '@rocket.chat/fuselage-hooks';
import { escapeHTML } from '@rocket.chat/string-helpers';
import { useTranslation, usePermission, useUserRoom, useUserSubscription, useSetModal, useUser } from '@rocket.chat/ui-contexts';
import { useQueryClient } from '@tanstack/react-query';
import type { ReactElement } from 'react';
import React, { useCallback, useMemo } from 'react';

Expand Down Expand Up @@ -43,6 +44,7 @@ export const useChangeOwnerAction = (user: Pick<IUser, '_id' | 'username'>, rid:
const { _id: loggedUserId = '' } = useUser() || {};
const loggedUserIsOwner = useUserHasRoomRole(loggedUserId, rid, 'owner');
const closeModal = useCallback(() => setModal(null), [setModal]);
const queryClient = useQueryClient();

if (!room) {
throw Error('Room not provided');
Expand All @@ -58,15 +60,18 @@ export const useChangeOwnerAction = (user: Pick<IUser, '_id' | 'username'>, rid:
successMessage: t(changeOwnerMessage, { username: user.username, room_name: roomName }),
});

const handleConfirm = useCallback(() => {
changeOwner({ roomId: rid, userId: uid });
const handleConfirm = useCallback(async () => {
await changeOwner({ roomId: rid, userId: uid });
queryClient.invalidateQueries({ queryKey: ['members'] });
closeModal();
}, [changeOwner, rid, uid, closeModal]);
}, [changeOwner, rid, uid, queryClient, closeModal]);

const handleChangeOwner = useCallback(
({ userId }) => {
async ({ userId }) => {
if (!isRoomFederated(room)) {
return changeOwner({ roomId: rid, userId: uid });
await changeOwner({ roomId: rid, userId: uid });
queryClient.invalidateQueries({ queryKey: ['members'] });
return;
}
const changingOwnRole = userId === loggedUserId;

Expand Down Expand Up @@ -96,7 +101,7 @@ export const useChangeOwnerAction = (user: Pick<IUser, '_id' | 'username'>, rid:

changeOwner({ roomId: rid, userId: uid });
},
[setModal, loggedUserId, loggedUserIsOwner, t, rid, uid, changeOwner, closeModal, handleConfirm, room],
[room, loggedUserId, loggedUserIsOwner, changeOwner, rid, uid, queryClient, setModal, closeModal, handleConfirm, t],
);

const changeOwnerAction = useMutableCallback(async () => handleChangeOwner({ roomId: rid, userId: uid }));
Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/server/lib/findUsersOfRoomOrderedByRole.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ export async function findUsersOfRoomOrderedByRole({

const totalResult = Subscriptions.col.aggregate([{ $match: { rid } }, ...filteredPipeline, { $count: 'total' }], { allowDiskUse: true });

const [members, [{ totalCount }]] = await Promise.all([membersResult.toArray(), totalResult.toArray()]);
const [members, [{ total: totalCount }]] = await Promise.all([membersResult.toArray(), totalResult.toArray()]);

return {
members: members.map((member: any) => {
Expand Down
2 changes: 2 additions & 0 deletions packages/i18n/src/locales/en.i18n.json
Original file line number Diff line number Diff line change
Expand Up @@ -3834,6 +3834,7 @@
"mobile-upload-file_description": "Permission to allow file upload on mobile devices",
"Mobile_Push_Notifications_Default_Alert": "Push Notifications Default Alert",
"Moderation": "Moderation",
"Moderators": "Moderators",
"Moderation_Show_reports": "Show reports",
"Moderation_See_reports": "See reports",
"Moderation_Go_to_message": "Go to message",
Expand Down Expand Up @@ -4269,6 +4270,7 @@
"Override_URL_to_which_files_are_uploaded_This_url_also_used_for_downloads_unless_a_CDN_is_given": "Override URL to which files are uploaded. This url also used for downloads unless a CDN is given",
"Override_Destination_Channel": "Allow to overwrite destination channel in the body parameters",
"Owner": "Owner",
"Owners": "Owners",
"Play": "Play",
"Page_not_exist_or_not_permission": "The page does not exist or you may not have access permission",
"Page_not_found": "Page not found",
Expand Down
2 changes: 1 addition & 1 deletion packages/rest-typings/src/v1/rooms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -843,7 +843,7 @@ export type RoomsEndpoints = {

'/v1/rooms.membersOrderedByRole': {
GET: (params: RoomsMembersOrderedByRoleProps) => PaginatedResult<{
members: IUser & { roles: IRole['_id'] }[];
members: IUser & { roles: IRole['_id'][] };
}>;
};
};
Loading