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

refactor: Improve sidebar search list hook #28328

Merged
merged 3 commits into from Mar 10, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 5 additions & 2 deletions apps/meteor/client/lib/utils/getConfig.ts
@@ -1,6 +1,9 @@
import { Meteor } from 'meteor/meteor';

export const getConfig = (key: string): string | null => {
export const getConfig = <T>(key: string, defaultValue?: T): string | null | T => {
const searchParams = new URLSearchParams(window.location.search);
return searchParams.get(key) || Meteor._localStorage.getItem(`rc-config-${key}`);

const storedItem = searchParams.get(key) || Meteor._localStorage.getItem(`rc-config-${key}`);

return storedItem ?? defaultValue ?? null;
};
34 changes: 15 additions & 19 deletions apps/meteor/client/sidebar/search/SearchList.tsx
@@ -1,14 +1,7 @@
import type { IRoom, ISubscription, RoomType } from '@rocket.chat/core-typings';
import { css } from '@rocket.chat/css-in-js';
import { Sidebar, TextInput, Box, Icon } from '@rocket.chat/fuselage';
import {
useMutableCallback,
useDebouncedValue,
useStableArray,
useAutoFocus,
useUniqueId,
useMergedRefs,
} from '@rocket.chat/fuselage-hooks';
import { useMutableCallback, useDebouncedValue, useAutoFocus, useUniqueId, useMergedRefs } from '@rocket.chat/fuselage-hooks';
import { escapeRegExp } from '@rocket.chat/string-helpers';
import { useUserPreference, useUserSubscriptions, useSetting, useTranslation, useMethod } from '@rocket.chat/ui-contexts';
import type { UseQueryResult } from '@tanstack/react-query';
Expand All @@ -20,6 +13,7 @@ import type { VirtuosoHandle } from 'react-virtuoso';
import { Virtuoso } from 'react-virtuoso';
import tinykeys from 'tinykeys';

import { getConfig } from '../../lib/utils/getConfig';
import { useAvatarTemplate } from '../hooks/useAvatarTemplate';
import { usePreventDefault } from '../hooks/usePreventDefault';
import { useTemplateByViewMode } from '../hooks/useTemplateByViewMode';
Expand All @@ -36,17 +30,18 @@ const shortcut = ((): string => {
return '(\u2303+K)';
})();

const LIMIT = parseInt(String(getConfig('Sidebar_Search_Spotlight_LIMIT', 20)));

const options = {
sort: {
lm: -1,
name: 1,
},
limit: LIMIT,
} as const;

const useSearchItems = (filterText: string): UseQueryResult<(ISubscription & IRoom)[] | undefined, Error> => {
const expression = /(@|#)?(.*)/i;
const [, mention, name] = filterText.match(expression) || [];

const [, mention, name] = useMemo(() => filterText.match(/(@|#)?(.*)/i) || [], [filterText]);
const query = useMemo(() => {
const filterRegex = new RegExp(escapeRegExp(name), 'i');

Expand All @@ -60,7 +55,7 @@ const useSearchItems = (filterText: string): UseQueryResult<(ISubscription & IRo

const localRooms: { rid: string; t: RoomType; _id: string; name: string; uids?: string }[] = useUserSubscriptions(query, options);

const usernamesFromClient = useStableArray([...localRooms?.map(({ t, name }) => (t === 'd' ? name : null))].filter(Boolean)) as string[];
const usernamesFromClient = [...localRooms?.map(({ t, name }) => (t === 'd' ? name : null))].filter(Boolean) as string[];

const searchForChannels = mention === '#';
const searchForDMs = mention === '@';
Expand All @@ -78,8 +73,12 @@ const useSearchItems = (filterText: string): UseQueryResult<(ISubscription & IRo
const getSpotlight = useMethod('spotlight');

return useQuery(
['sidebar/search/spotlight', name, usernamesFromClient, type, localRooms],
['sidebar/search/spotlight', name, usernamesFromClient, type],
async () => {
if (localRooms.length === LIMIT) {
return localRooms;
}

const spotlight = await getSpotlight(name, usernamesFromClient, type);

const filterUsersUnique = ({ _id }: { _id: string }, index: number, arr: { _id: string }[]): boolean =>
Expand All @@ -91,7 +90,7 @@ const useSearchItems = (filterText: string): UseQueryResult<(ISubscription & IRo
(room.t === 'd' && room.uids && room.uids.length > 1 && room.uids?.includes(item._id)) ||
[item.rid, item._id].includes(room._id),
);
const usersfilter = (user: { _id: string }): boolean =>
const usersFilter = (user: { _id: string }): boolean =>
!localRooms.find((room) => room.t === 'd' && room.uids && room.uids?.length === 2 && room.uids.includes(user._id));

const userMap = (user: {
Expand Down Expand Up @@ -123,7 +122,7 @@ const useSearchItems = (filterText: string): UseQueryResult<(ISubscription & IRo
}[];

const resultsFromServer: resultsFromServerType = [];
resultsFromServer.push(...spotlight.users.filter(filterUsersUnique).filter(usersfilter).map(userMap));
resultsFromServer.push(...spotlight.users.filter(filterUsersUnique).filter(usersFilter).map(userMap));
resultsFromServer.push(...spotlight.rooms.filter(roomFilter));

const exact = resultsFromServer?.filter((item) => [item.name, item.fname].includes(name));
Expand Down Expand Up @@ -245,7 +244,7 @@ const SearchList = forwardRef(function SearchList({ onClose }: SearchListProps,
if (!cursorRef?.current) {
return;
}
const unsubscribe = tinykeys(cursorRef?.current, {
return tinykeys(cursorRef?.current, {
Escape: (event) => {
event.preventDefault();
setFilterValue((value) => {
Expand Down Expand Up @@ -275,9 +274,6 @@ const SearchList = forwardRef(function SearchList({ onClose }: SearchListProps,
}
},
});
return (): void => {
unsubscribe();
};
}, [cursorRef, changeSelection, items.length, onClose, resetCursor, setFilterValue]);

const handleClick: MouseEventHandler<HTMLElement> = (e): void => {
Expand Down
5 changes: 1 addition & 4 deletions apps/meteor/client/views/hooks/useMembersList.ts
Expand Up @@ -61,10 +61,7 @@ export const useMembersList = (
const { loadMoreItems, initialItemCount } = useScrollableRecordList(
membersList,
fetchData,
useMemo(() => {
const filesListSize = getConfig('teamsChannelListSize');
return filesListSize ? parseInt(filesListSize, 10) : undefined;
}, []),
useMemo(() => parseInt(`${getConfig('teamsChannelListSize', 10)}`), []),
);

return {
Expand Down
Expand Up @@ -40,10 +40,7 @@ export const useDiscussionsList = (
const { loadMoreItems, initialItemCount } = useScrollableMessageList(
discussionsList,
fetchMessages,
useMemo(() => {
const discussionListSize = getConfig('discussionListSize');
return discussionListSize ? parseInt(discussionListSize, 10) : undefined;
}, []),
useMemo(() => parseInt(`${getConfig('discussionListSize', 10)}`), []),
);
useStreamUpdatesForMessageList(discussionsList, uid, options.rid);

Expand Down
Expand Up @@ -73,10 +73,7 @@ export const useFilesList = (
const { loadMoreItems, initialItemCount } = useScrollableRecordList(
filesList,
fetchMessages,
useMemo(() => {
const filesListSize = getConfig('discussionListSize');
return filesListSize ? parseInt(filesListSize, 10) : undefined;
}, []),
useMemo(() => parseInt(`${getConfig('discussionListSize', 10)}`), []),
);

// TODO: chapter day : frontend create useStreamUpdatesForUploadList
Expand Down
Expand Up @@ -41,10 +41,7 @@ export const useThreadsList = (
const { loadMoreItems, initialItemCount } = useScrollableMessageList(
threadsList,
fetchMessages,
useMemo(() => {
const threadsListSize = getConfig('threadsListSize');
return threadsListSize ? parseInt(threadsListSize, 10) : undefined;
}, []),
useMemo(() => parseInt(`${getConfig('threadsListSize', 10)}`), []),
);
useStreamUpdatesForMessageList(threadsList, uid, options.rid);

Expand Down
Expand Up @@ -58,10 +58,7 @@ export const useTeamsChannelList = (
const { loadMoreItems, initialItemCount } = useScrollableRecordList(
teamsChannelList,
fetchData,
useMemo(() => {
const filesListSize = getConfig('teamsChannelListSize');
return filesListSize ? parseInt(filesListSize, 10) : undefined;
}, []),
useMemo(() => parseInt(`${getConfig('teamsChannelListSize', 10)}`), []),
);

return {
Expand Down