snapshot of https://github.com/RocketChat/Rocket.Chat.git (develop, 2026-09-16; blobs > 131072B omitted)
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 1s
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 1s
This commit is contained in:
@@ -0,0 +1,12 @@
|
||||
import { buildRoomSearchQuery } from '@rocket.chat/ai-search';
|
||||
|
||||
export const emptySubscriptionQuery = { _id: '__ai_search_no_room_filter__' };
|
||||
|
||||
export const buildUsernameAutocompleteQuery = (
|
||||
term = '',
|
||||
): {
|
||||
selector: string;
|
||||
} => ({ selector: JSON.stringify({ term, conditions: {}, exceptions: [] }) });
|
||||
|
||||
export const getRoomLookupQuery = (roomLookupText: string): ReturnType<typeof buildRoomSearchQuery> | typeof emptySubscriptionQuery =>
|
||||
roomLookupText ? buildRoomSearchQuery(roomLookupText, '#') : emptySubscriptionQuery;
|
||||
@@ -0,0 +1,332 @@
|
||||
import { AI_SEARCH_FILTER_SUGGESTION_LIMIT, AI_SEARCH_PAGE_SIZE, emptySearchFilters } from '@rocket.chat/ai-search';
|
||||
import { UserStatus } from '@rocket.chat/core-typings';
|
||||
import { mockAppRoot } from '@rocket.chat/mock-providers';
|
||||
import type { AISearchResult } from '@rocket.chat/rest-typings';
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
|
||||
import { useAISearchItems } from './useAISearchItems';
|
||||
import { createFakeSubscription } from '../../../../tests/mocks/data';
|
||||
|
||||
let mockDebounce: (value: unknown) => unknown = (value) => value;
|
||||
|
||||
jest.mock('@rocket.chat/fuselage-hooks', () => ({
|
||||
...jest.requireActual('@rocket.chat/fuselage-hooks'),
|
||||
useDebouncedValue: (value: unknown) => mockDebounce(value),
|
||||
}));
|
||||
|
||||
type AutocompleteUser = {
|
||||
_id: string;
|
||||
name: string;
|
||||
username: string;
|
||||
nickname: string;
|
||||
status: UserStatus;
|
||||
avatarETag: string;
|
||||
};
|
||||
|
||||
const setup = ({
|
||||
subscriptions = [],
|
||||
intelligent = [],
|
||||
users = [],
|
||||
}: {
|
||||
subscriptions?: ReturnType<typeof createFakeSubscription>[];
|
||||
intelligent?: AISearchResult[];
|
||||
users?: AutocompleteUser[];
|
||||
} = {}) => {
|
||||
const aiSearchHandler = jest.fn(() => ({
|
||||
intelligent,
|
||||
meta: { intelligentSearchEnabled: true, intelligentSearchConfigured: true, answerGenerationConfigured: true },
|
||||
}));
|
||||
const usersAutocompleteHandler = jest.fn(() => ({ items: users }));
|
||||
|
||||
const wrapper = mockAppRoot()
|
||||
.withTranslations('en', 'core', {
|
||||
Search_in_this_room: 'Search in this room',
|
||||
Search_messages_from_this_username: 'Search messages from this username',
|
||||
Search_messages_from_this_user: 'Search messages from this user',
|
||||
Today: 'Today',
|
||||
Yesterday: 'Yesterday',
|
||||
Last_7_days: 'Last 7 days',
|
||||
})
|
||||
.withSubscriptions(subscriptions)
|
||||
.withEndpoint('GET', '/v1/ai.search', aiSearchHandler)
|
||||
.withEndpoint('GET', '/v1/users.autocomplete', usersAutocompleteHandler)
|
||||
.build();
|
||||
|
||||
return { wrapper, aiSearchHandler, usersAutocompleteHandler };
|
||||
};
|
||||
|
||||
const formatDate = (date: Date): string =>
|
||||
`${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
|
||||
|
||||
beforeEach(() => {
|
||||
mockDebounce = (value) => value;
|
||||
});
|
||||
|
||||
describe('useAISearchItems', () => {
|
||||
describe('when AI search is inactive', () => {
|
||||
it('passes the filter text through untouched and yields no items', async () => {
|
||||
const { wrapper, aiSearchHandler, usersAutocompleteHandler } = setup();
|
||||
const { result } = renderHook(
|
||||
() => useAISearchItems('in:general deploy', { ...emptySearchFilters(), roomNames: ['support'] }, false),
|
||||
{ wrapper },
|
||||
);
|
||||
|
||||
await act(async () => undefined);
|
||||
|
||||
expect(result.current.data.searchText).toBe('in:general deploy');
|
||||
expect(result.current.data.intelligent).toEqual([]);
|
||||
expect(result.current.data.filterSuggestions).toEqual([]);
|
||||
expect(result.current.isFetching).toBe(false);
|
||||
expect(aiSearchHandler).not.toHaveBeenCalled();
|
||||
expect(usersAutocompleteHandler).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('defaults to inactive when only the filter text is provided', async () => {
|
||||
const { wrapper, aiSearchHandler } = setup();
|
||||
const { result } = renderHook(() => useAISearchItems('deploy'), { wrapper });
|
||||
|
||||
await act(async () => undefined);
|
||||
|
||||
expect(result.current.data.searchText).toBe('deploy');
|
||||
expect(aiSearchHandler).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('intelligent search', () => {
|
||||
it('strips inline filter tokens and queries ai.search with the parsed filters', async () => {
|
||||
const intelligent = [{ _id: 'msg-1', msgId: 'msg-1', text: 'Deployment failed' }];
|
||||
const { wrapper, aiSearchHandler } = setup({ intelligent });
|
||||
const { result } = renderHook(
|
||||
() => useAISearchItems('in:general from:john after:2026-01-01 before:2026-02-01 deploy failed', emptySearchFilters(), true),
|
||||
{ wrapper },
|
||||
);
|
||||
|
||||
expect(result.current.data.searchText).toBe('deploy failed');
|
||||
expect(result.current.isFetching).toBe(true);
|
||||
|
||||
await waitFor(() => expect(result.current.data.intelligent).toEqual(intelligent));
|
||||
expect(result.current.isFetching).toBe(false);
|
||||
expect(aiSearchHandler).toHaveBeenCalledTimes(1);
|
||||
expect(aiSearchHandler).toHaveBeenCalledWith({
|
||||
query: 'deploy failed',
|
||||
intelligentCount: AI_SEARCH_PAGE_SIZE,
|
||||
roomNames: 'general',
|
||||
fromUsernames: 'john',
|
||||
startDate: '2026-01-01',
|
||||
endDate: '2026-02-01',
|
||||
});
|
||||
});
|
||||
|
||||
it('merges applied filters with inline filter tokens in the request', async () => {
|
||||
const { wrapper, aiSearchHandler } = setup();
|
||||
const { result } = renderHook(
|
||||
() =>
|
||||
useAISearchItems(
|
||||
'in:general hello',
|
||||
{ ...emptySearchFilters(), roomNames: ['support'], fromUsernames: ['jane'], startDate: '2026-05-01' },
|
||||
true,
|
||||
),
|
||||
{ wrapper },
|
||||
);
|
||||
|
||||
await waitFor(() => expect(aiSearchHandler).toHaveBeenCalled());
|
||||
expect(aiSearchHandler).toHaveBeenCalledWith({
|
||||
query: 'hello',
|
||||
intelligentCount: AI_SEARCH_PAGE_SIZE,
|
||||
roomNames: 'support,general',
|
||||
fromUsernames: 'jane',
|
||||
startDate: '2026-05-01',
|
||||
});
|
||||
await waitFor(() => expect(result.current.isFetching).toBe(false));
|
||||
});
|
||||
|
||||
it('does not hit ai.search when only filter tokens are present', async () => {
|
||||
const { wrapper, aiSearchHandler } = setup();
|
||||
const { result } = renderHook(() => useAISearchItems('in:general ', emptySearchFilters(), true), { wrapper });
|
||||
|
||||
await act(async () => undefined);
|
||||
|
||||
expect(result.current.data.searchText).toBe('');
|
||||
expect(result.current.data.intelligent).toEqual([]);
|
||||
expect(aiSearchHandler).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('withholds intelligent results while the debounced search text lags behind', async () => {
|
||||
mockDebounce = () => 'stale';
|
||||
const intelligent = [{ _id: 'msg-1', text: 'Old result' }];
|
||||
const { wrapper, aiSearchHandler } = setup({ intelligent });
|
||||
const { result } = renderHook(() => useAISearchItems('deploy', emptySearchFilters(), true), { wrapper });
|
||||
|
||||
await waitFor(() => expect(aiSearchHandler).toHaveBeenCalledWith(expect.objectContaining({ query: 'stale' })));
|
||||
await waitFor(() => expect(result.current.isFetching).toBe(false));
|
||||
|
||||
expect(result.current.data.intelligent).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('room filter suggestions', () => {
|
||||
it('suggests rooms while an in: token is being typed', async () => {
|
||||
const subscriptions = [createFakeSubscription({ rid: 'rid-general', name: 'general', fname: 'General', t: 'c' })];
|
||||
const { wrapper, aiSearchHandler } = setup({ subscriptions });
|
||||
const { result } = renderHook(() => useAISearchItems('in:gen', emptySearchFilters(), true), { wrapper });
|
||||
|
||||
await act(async () => undefined);
|
||||
|
||||
expect(result.current.data.searchText).toBe('');
|
||||
expect(aiSearchHandler).not.toHaveBeenCalled();
|
||||
expect(result.current.data.filterSuggestions).toEqual([
|
||||
{
|
||||
key: 'in-rid-general',
|
||||
group: 'rooms',
|
||||
title: '#General',
|
||||
description: 'Search in this room',
|
||||
value: 'in:general ',
|
||||
icon: 'hash',
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('caps room suggestions at the configured limit', async () => {
|
||||
const subscriptions = Array.from({ length: AI_SEARCH_FILTER_SUGGESTION_LIMIT + 2 }, (_, index) =>
|
||||
createFakeSubscription({ rid: `rid-${index}`, name: `general-${index}`, t: 'c' }),
|
||||
);
|
||||
const { wrapper } = setup({ subscriptions });
|
||||
const { result } = renderHook(() => useAISearchItems('in:gen', emptySearchFilters(), true), { wrapper });
|
||||
|
||||
await act(async () => undefined);
|
||||
|
||||
expect(result.current.data.filterSuggestions).toHaveLength(AI_SEARCH_FILTER_SUGGESTION_LIMIT);
|
||||
});
|
||||
|
||||
it('does not suggest rooms without an active in: token', async () => {
|
||||
const subscriptions = [createFakeSubscription({ rid: 'rid-general', name: 'general', t: 'c' })];
|
||||
const { wrapper } = setup({ subscriptions });
|
||||
const { result } = renderHook(() => useAISearchItems('general stuff', emptySearchFilters(), true), { wrapper });
|
||||
|
||||
await waitFor(() => expect(result.current.isFetching).toBe(false));
|
||||
|
||||
expect(result.current.data.filterSuggestions).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('user filter suggestions', () => {
|
||||
const john: AutocompleteUser = {
|
||||
_id: 'user-1',
|
||||
name: 'John Doe',
|
||||
username: 'john',
|
||||
nickname: '',
|
||||
status: UserStatus.ONLINE,
|
||||
avatarETag: '',
|
||||
};
|
||||
|
||||
it('suggests usernames from users.autocomplete while a from: token is active', async () => {
|
||||
const { wrapper, usersAutocompleteHandler } = setup({ users: [john] });
|
||||
const { result } = renderHook(() => useAISearchItems('from:jo', emptySearchFilters(), true), { wrapper });
|
||||
|
||||
await waitFor(() =>
|
||||
expect(result.current.data.filterSuggestions).toEqual([
|
||||
{
|
||||
key: 'from-user-1',
|
||||
group: 'users',
|
||||
title: '@john',
|
||||
description: 'John Doe',
|
||||
value: 'from:john ',
|
||||
icon: 'user',
|
||||
},
|
||||
{
|
||||
key: 'from-current',
|
||||
group: 'users',
|
||||
title: 'from:jo',
|
||||
description: 'Search messages from this username',
|
||||
value: 'from:jo ',
|
||||
icon: 'user',
|
||||
},
|
||||
]),
|
||||
);
|
||||
expect(usersAutocompleteHandler).toHaveBeenCalledWith({
|
||||
selector: JSON.stringify({ term: 'jo', conditions: {}, exceptions: [] }),
|
||||
});
|
||||
});
|
||||
|
||||
it('withholds username suggestions while the debounced from: value lags behind', async () => {
|
||||
mockDebounce = (value) => (value === 'jo' ? '' : value);
|
||||
const { wrapper, usersAutocompleteHandler } = setup({ users: [john] });
|
||||
const { result } = renderHook(() => useAISearchItems('from:jo', emptySearchFilters(), true), { wrapper });
|
||||
|
||||
await waitFor(() => expect(usersAutocompleteHandler).toHaveBeenCalled());
|
||||
await waitFor(() => expect(result.current.isFetching).toBe(false));
|
||||
|
||||
expect(result.current.data.filterSuggestions).toEqual([
|
||||
{
|
||||
key: 'from-current',
|
||||
group: 'users',
|
||||
title: 'from:jo',
|
||||
description: 'Search messages from this username',
|
||||
value: 'from:jo ',
|
||||
icon: 'user',
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('date filter suggestions', () => {
|
||||
// freeze the clock so the hook's `new Date()` and the expected values below agree even across midnight
|
||||
beforeEach(() => {
|
||||
jest.useFakeTimers({ now: new Date('2026-07-15T12:00:00Z'), advanceTimers: true });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
it('offers date suggestions for a trailing after: token', async () => {
|
||||
const { wrapper } = setup();
|
||||
const { result } = renderHook(() => useAISearchItems('after:', emptySearchFilters(), true), { wrapper });
|
||||
|
||||
await waitFor(() => expect(result.current.isFetching).toBe(false));
|
||||
|
||||
const today = new Date();
|
||||
const yesterday = new Date(today);
|
||||
yesterday.setDate(today.getDate() - 1);
|
||||
const lastWeek = new Date(today);
|
||||
lastWeek.setDate(today.getDate() - 7);
|
||||
|
||||
expect(result.current.data.filterSuggestions).toEqual([
|
||||
{
|
||||
key: `after-${formatDate(today)}`,
|
||||
group: 'dates',
|
||||
title: `after:${formatDate(today)}`,
|
||||
description: 'Today',
|
||||
value: `after:${formatDate(today)} `,
|
||||
icon: 'calendar',
|
||||
},
|
||||
{
|
||||
key: `after-${formatDate(yesterday)}`,
|
||||
group: 'dates',
|
||||
title: `after:${formatDate(yesterday)}`,
|
||||
description: 'Yesterday',
|
||||
value: `after:${formatDate(yesterday)} `,
|
||||
icon: 'calendar',
|
||||
},
|
||||
{
|
||||
key: `after-${formatDate(lastWeek)}`,
|
||||
group: 'dates',
|
||||
title: `after:${formatDate(lastWeek)}`,
|
||||
description: 'Last 7 days',
|
||||
value: `after:${formatDate(lastWeek)} `,
|
||||
icon: 'calendar',
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('offers date suggestions for a trailing before: token', async () => {
|
||||
const { wrapper } = setup();
|
||||
const { result } = renderHook(() => useAISearchItems('before:', emptySearchFilters(), true), { wrapper });
|
||||
|
||||
await waitFor(() => expect(result.current.isFetching).toBe(false));
|
||||
|
||||
expect(result.current.data.filterSuggestions).toHaveLength(3);
|
||||
expect(result.current.data.filterSuggestions.every(({ key, group }) => key.startsWith('before-') && group === 'dates')).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
101
apps/meteor/client/navbar/NavBarSearch/hooks/useAISearchItems.ts
Normal file
101
apps/meteor/client/navbar/NavBarSearch/hooks/useAISearchItems.ts
Normal file
@@ -0,0 +1,101 @@
|
||||
import {
|
||||
AI_SEARCH_PAGE_SIZE,
|
||||
AI_SEARCH_ROOM_LOOKUP_LIMIT,
|
||||
buildFilterSuggestions,
|
||||
buildUserFilterSuggestions,
|
||||
emptySearchFilters,
|
||||
getFilterSearchState,
|
||||
getRoomLookupText,
|
||||
mergeFilterSuggestions,
|
||||
type SearchFilters,
|
||||
type SearchFilterSuggestion,
|
||||
} from '@rocket.chat/ai-search';
|
||||
import { useDebouncedValue } from '@rocket.chat/fuselage-hooks';
|
||||
import type { AISearchResult } from '@rocket.chat/rest-typings';
|
||||
import { useEndpoint, useUserSubscriptions } from '@rocket.chat/ui-contexts';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useMemo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { buildUsernameAutocompleteQuery, emptySubscriptionQuery, getRoomLookupQuery } from './aiSearchAdapters';
|
||||
|
||||
const roomLookupOptions = {
|
||||
sort: { lm: -1, name: 1 },
|
||||
limit: AI_SEARCH_ROOM_LOOKUP_LIMIT,
|
||||
} as const;
|
||||
|
||||
export type AISearchItems = {
|
||||
intelligent: AISearchResult[];
|
||||
filterSuggestions: SearchFilterSuggestion[];
|
||||
searchText: string;
|
||||
};
|
||||
|
||||
export const useAISearchItems = (
|
||||
filterText: string,
|
||||
appliedSearchFilters: SearchFilters = emptySearchFilters(),
|
||||
aiSearchActive = false,
|
||||
): { data: AISearchItems; isFetching: boolean } => {
|
||||
const { t } = useTranslation();
|
||||
const enabled = aiSearchActive;
|
||||
const { searchText, filters, activeFilter } = useMemo(
|
||||
() => getFilterSearchState(filterText, appliedSearchFilters, enabled),
|
||||
[appliedSearchFilters, enabled, filterText],
|
||||
);
|
||||
const debouncedSearchText = useDebouncedValue(searchText, 500);
|
||||
const userFilter = activeFilter?.key === 'from' ? activeFilter.value.replace(/^@/, '') : '';
|
||||
const debouncedUserFilter = useDebouncedValue(userFilter, 500);
|
||||
const roomLookupText = useMemo(() => getRoomLookupText(activeFilter, enabled), [activeFilter, enabled]);
|
||||
const roomLookupQuery = useMemo(() => (roomLookupText ? getRoomLookupQuery(roomLookupText) : emptySubscriptionQuery), [roomLookupText]);
|
||||
const roomFilterRooms = useUserSubscriptions(roomLookupQuery, roomLookupOptions);
|
||||
|
||||
const aiSearch = useEndpoint('GET', '/v1/ai.search');
|
||||
const shouldSearch = Boolean(enabled && debouncedSearchText.trim());
|
||||
const { data: intelligent = [], isFetching: isIntelligentFetching } = useQuery({
|
||||
queryKey: ['sidebar/search/intelligent', debouncedSearchText, filters],
|
||||
enabled: shouldSearch,
|
||||
queryFn: async () => {
|
||||
const result = await aiSearch({
|
||||
query: debouncedSearchText,
|
||||
intelligentCount: AI_SEARCH_PAGE_SIZE,
|
||||
...(filters.roomNames.length && { roomNames: filters.roomNames.join(',') }),
|
||||
...(filters.fromUsernames.length && { fromUsernames: filters.fromUsernames.join(',') }),
|
||||
...(filters.startDate && { startDate: filters.startDate }),
|
||||
...(filters.endDate && { endDate: filters.endDate }),
|
||||
});
|
||||
|
||||
return result.intelligent;
|
||||
},
|
||||
staleTime: 60_000,
|
||||
});
|
||||
|
||||
const localSuggestions = useMemo(
|
||||
() => (enabled ? buildFilterSuggestions(filterText, activeFilter, roomFilterRooms, t) : []),
|
||||
[activeFilter, enabled, filterText, roomFilterRooms, t],
|
||||
);
|
||||
const usersAutocomplete = useEndpoint('GET', '/v1/users.autocomplete');
|
||||
const { data: users = [], isFetching: isUsersFetching } = useQuery({
|
||||
queryKey: ['sidebar/search/users-autocomplete', debouncedUserFilter],
|
||||
enabled: enabled && activeFilter?.key === 'from',
|
||||
queryFn: async () => (await usersAutocomplete(buildUsernameAutocompleteQuery(debouncedUserFilter))).items,
|
||||
staleTime: 60_000,
|
||||
});
|
||||
const filterSuggestions = useMemo(
|
||||
() =>
|
||||
activeFilter?.key === 'from'
|
||||
? mergeFilterSuggestions(
|
||||
buildUserFilterSuggestions(filterText, activeFilter, userFilter === debouncedUserFilter ? users : [], t),
|
||||
localSuggestions,
|
||||
)
|
||||
: localSuggestions,
|
||||
[activeFilter, debouncedUserFilter, filterText, localSuggestions, t, userFilter, users],
|
||||
);
|
||||
|
||||
return {
|
||||
data: {
|
||||
intelligent: shouldSearch && searchText === debouncedSearchText ? intelligent : [],
|
||||
filterSuggestions,
|
||||
searchText,
|
||||
},
|
||||
isFetching: isIntelligentFetching || isUsersFetching,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,92 @@
|
||||
import { mockAppRoot } from '@rocket.chat/mock-providers';
|
||||
import type { SubscriptionWithRoom } from '@rocket.chat/ui-contexts';
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
|
||||
import { useAISearchRooms } from './useAISearchRooms';
|
||||
|
||||
describe('useAISearchRooms', () => {
|
||||
it('should treat an unset filter as an empty search', () => {
|
||||
const wrapper = mockAppRoot()
|
||||
.withSubscriptions([])
|
||||
.withEndpoint('GET', '/v1/spotlight', () => ({ users: [], rooms: [] }))
|
||||
.build();
|
||||
|
||||
const { result } = renderHook(() => useAISearchRooms(undefined), { wrapper });
|
||||
|
||||
expect(result.current.items).toEqual([]);
|
||||
});
|
||||
|
||||
it('should deduplicate a user if they already exist in local subscriptions as a self-DM', async () => {
|
||||
const myUserName = 'rocketchat.internal.admin.test';
|
||||
const myUserId = 'user_id_456';
|
||||
|
||||
const wrapper = mockAppRoot()
|
||||
.withSubscriptions([
|
||||
{
|
||||
_id: 'local_room_123',
|
||||
t: 'd',
|
||||
name: myUserName,
|
||||
uids: [myUserId],
|
||||
} as unknown as SubscriptionWithRoom,
|
||||
])
|
||||
.withEndpoint('GET', '/v1/spotlight', () => ({
|
||||
users: [{ _id: myUserId, username: myUserName, name: 'Rocket Chat Test' }],
|
||||
rooms: [],
|
||||
}))
|
||||
.build();
|
||||
|
||||
const { result } = renderHook(() => useAISearchRooms(myUserName), { wrapper });
|
||||
|
||||
expect(result.current.items).toHaveLength(1);
|
||||
expect(result.current.items[0]._id).toBe('local_room_123');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
});
|
||||
|
||||
expect(result.current.items).toHaveLength(1);
|
||||
expect(result.current.items[0]._id).toBe('local_room_123');
|
||||
expect(result.current.items[0].name).toBe(myUserName);
|
||||
});
|
||||
|
||||
it('should append users from the server if they are NOT duplicates', async () => {
|
||||
const wrapper = mockAppRoot()
|
||||
.withSubscriptions([{ _id: 'local_room_123', t: 'd', name: 'general' } as unknown as SubscriptionWithRoom])
|
||||
.withEndpoint('GET', '/v1/spotlight', () => ({
|
||||
users: [{ _id: 'user_id_456', username: 'john.doe', name: 'John Doe' }],
|
||||
rooms: [],
|
||||
}))
|
||||
.build();
|
||||
|
||||
const { result } = renderHook(() => useAISearchRooms('jo'), { wrapper });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
expect(result.current.items).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
it('should not expose remote suggestions for a previous debounced value', async () => {
|
||||
const wrapper = mockAppRoot()
|
||||
.withSubscriptions([{ _id: 'local_room_123', t: 'c', name: 'general' } as unknown as SubscriptionWithRoom])
|
||||
.withEndpoint('GET', '/v1/spotlight', () => ({
|
||||
users: [{ _id: 'user_id_456', username: 'john.doe', name: 'John Doe' }],
|
||||
rooms: [],
|
||||
}))
|
||||
.build();
|
||||
|
||||
const { result, rerender } = renderHook(({ filterText }) => useAISearchRooms(filterText), {
|
||||
initialProps: { filterText: '@john' },
|
||||
wrapper,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.items).toHaveLength(2);
|
||||
});
|
||||
|
||||
rerender({ filterText: '@j' });
|
||||
|
||||
expect(result.current.items).toHaveLength(1);
|
||||
expect(result.current.items[0]._id).toBe('local_room_123');
|
||||
});
|
||||
});
|
||||
115
apps/meteor/client/navbar/NavBarSearch/hooks/useAISearchRooms.ts
Normal file
115
apps/meteor/client/navbar/NavBarSearch/hooks/useAISearchRooms.ts
Normal file
@@ -0,0 +1,115 @@
|
||||
import { useDebouncedValue } from '@rocket.chat/fuselage-hooks';
|
||||
import { escapeRegExp, isTruthy } from '@rocket.chat/tools';
|
||||
import type { SubscriptionWithRoom } from '@rocket.chat/ui-contexts';
|
||||
import { useEndpoint, useUserSubscriptions } from '@rocket.chat/ui-contexts';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useMemo } from 'react';
|
||||
|
||||
import { getConfig } from '../../../lib/utils/getConfig';
|
||||
|
||||
const LIMIT = parseInt(String(getConfig('Sidebar_Search_Spotlight_LIMIT', 20)));
|
||||
|
||||
const options = {
|
||||
sort: {
|
||||
lm: -1,
|
||||
name: 1,
|
||||
},
|
||||
limit: LIMIT,
|
||||
} as const;
|
||||
|
||||
type AISearchRoomResult = {
|
||||
_id: string;
|
||||
name: string;
|
||||
fname?: string;
|
||||
t: string;
|
||||
rid?: string;
|
||||
status?: string;
|
||||
avatarETag?: string;
|
||||
outside?: boolean;
|
||||
uids?: string[];
|
||||
};
|
||||
|
||||
export const useAISearchRooms = (filterText = ''): { items: SubscriptionWithRoom[]; isLoading: boolean } => {
|
||||
const [, mention, name] = useMemo(() => filterText.match(/(@|#)?(.*)/i) || [], [filterText]);
|
||||
|
||||
const query = useMemo(() => {
|
||||
const filterRegex = new RegExp(escapeRegExp(name), 'i');
|
||||
|
||||
return {
|
||||
...(mention && {
|
||||
t: mention === '@' ? 'd' : { $ne: 'd' },
|
||||
}),
|
||||
$or: [{ name: filterRegex }, { fname: filterRegex }],
|
||||
};
|
||||
}, [name, mention]);
|
||||
|
||||
const localRooms = useUserSubscriptions(query, options);
|
||||
const debouncedName = useDebouncedValue(name, 500);
|
||||
const usernamesFromClient = localRooms.map(({ t, name }) => (t === 'd' ? name : null)).filter(isTruthy);
|
||||
const searchForChannels = mention === '#';
|
||||
const searchForDMs = mention === '@';
|
||||
const type = useMemo(() => {
|
||||
if (searchForChannels) {
|
||||
return { users: false, rooms: true, includeFederatedRooms: true };
|
||||
}
|
||||
|
||||
if (searchForDMs) {
|
||||
return { users: true, rooms: false };
|
||||
}
|
||||
|
||||
return { users: true, rooms: true, includeFederatedRooms: true };
|
||||
}, [searchForChannels, searchForDMs]);
|
||||
|
||||
const getSpotlight = useEndpoint('GET', '/v1/spotlight');
|
||||
const { data: serverResults, isFetching } = useQuery({
|
||||
queryKey: ['sidebar/ai-search/spotlight', debouncedName, mention, type],
|
||||
enabled: localRooms.length < LIMIT,
|
||||
queryFn: async () => {
|
||||
const spotlight = await getSpotlight({
|
||||
query: debouncedName,
|
||||
usernames: usernamesFromClient.join(','),
|
||||
type: JSON.stringify(type),
|
||||
});
|
||||
|
||||
const filterUsersUnique = ({ _id }: { _id: string }, index: number, users: { _id: string }[]): boolean =>
|
||||
index === users.findIndex((user) => _id === user._id);
|
||||
const userMap = (user: { _id: string; name: string; username: string; status?: string }): AISearchRoomResult => ({
|
||||
_id: user._id,
|
||||
name: user.username,
|
||||
fname: user.name,
|
||||
t: 'd',
|
||||
rid: user._id,
|
||||
status: user.status,
|
||||
});
|
||||
const results: AISearchRoomResult[] = spotlight.users.filter(filterUsersUnique).map(userMap);
|
||||
results.push(...spotlight.rooms);
|
||||
|
||||
return results;
|
||||
},
|
||||
staleTime: 60_000,
|
||||
});
|
||||
|
||||
const items = useMemo(() => {
|
||||
const filterRegex = new RegExp(escapeRegExp(name), 'i');
|
||||
const matchesFilter = ({ name, fname }: { name?: string; fname?: string }) =>
|
||||
(name && filterRegex.test(name)) || (fname && filterRegex.test(fname));
|
||||
const isLocalDuplicate = (item: { _id: string; t?: string; uids?: string[]; name: string }): boolean =>
|
||||
localRooms.some((room) => {
|
||||
const sameRoom = [room.rid, room._id].includes(item._id);
|
||||
const sameGroupDM = item.t === 'd' && !!item.uids && item.uids.length > 1 && item.uids.includes(room._id);
|
||||
const sameDirectDM = item.t === 'd' && room.t === 'd' && !!room.uids && room.uids.length === 2 && room.uids.includes(item._id);
|
||||
const sameUserDM = item.t === 'd' && room.t === 'd' && item.name === room.name;
|
||||
return sameRoom || sameGroupDM || sameDirectDM || sameUserDM;
|
||||
});
|
||||
|
||||
const candidates = name === debouncedName && localRooms.length < LIMIT ? (serverResults ?? []) : [];
|
||||
const fromServer = candidates.filter((item) => matchesFilter(item) && !isLocalDuplicate(item));
|
||||
const exact = fromServer.filter((item) => [item.name, item.fname].includes(name));
|
||||
|
||||
return [...exact, ...localRooms, ...fromServer.filter((item) => !exact.includes(item))] as SubscriptionWithRoom[];
|
||||
}, [debouncedName, localRooms, name, serverResults]);
|
||||
|
||||
const isLoading = isFetching && serverResults === undefined;
|
||||
|
||||
return { items, isLoading };
|
||||
};
|
||||
@@ -0,0 +1,103 @@
|
||||
import type { OverlayTriggerState } from '@react-stately/overlays';
|
||||
import {
|
||||
AI_LICENSE_MODULE,
|
||||
buildAppliedFilterChips,
|
||||
extractCompletedSearchFilters,
|
||||
getAISearchButtonTooltip,
|
||||
mergeSearchFilters,
|
||||
type NavBarSearchFormValues,
|
||||
} from '@rocket.chat/ai-search';
|
||||
import { useSetting } from '@rocket.chat/ui-contexts';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import type { UseFormSetFocus, UseFormSetValue } from 'react-hook-form';
|
||||
import type { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useHasLicenseModule } from '../../../hooks/useHasLicenseModule';
|
||||
|
||||
type TranslationFn = ReturnType<typeof useTranslation>['t'];
|
||||
|
||||
export const useNavBarAISearch = ({
|
||||
filterText,
|
||||
appliedFilters,
|
||||
setFocus,
|
||||
setValue,
|
||||
state,
|
||||
t,
|
||||
}: {
|
||||
filterText: NavBarSearchFormValues['filterText'];
|
||||
appliedFilters: NavBarSearchFormValues['appliedFilters'];
|
||||
setFocus: UseFormSetFocus<NavBarSearchFormValues>;
|
||||
setValue: UseFormSetValue<NavBarSearchFormValues>;
|
||||
state: OverlayTriggerState;
|
||||
t: TranslationFn;
|
||||
}) => {
|
||||
const intelligentSearchEnabled = useSetting<boolean>('AI_Intelligent_Search_Enabled', false);
|
||||
const { data: hasIntelligentSearchLicense = false } = useHasLicenseModule(AI_LICENSE_MODULE);
|
||||
const canSearchWithAIFromTopBar = hasIntelligentSearchLicense && intelligentSearchEnabled;
|
||||
const [aiSearchRequested, setAISearchRequested] = useState(false);
|
||||
const aiSearchActive = Boolean(aiSearchRequested && canSearchWithAIFromTopBar);
|
||||
|
||||
const appliedFilterChips = useMemo(
|
||||
() => (aiSearchActive ? buildAppliedFilterChips(appliedFilters, t) : []),
|
||||
[aiSearchActive, appliedFilters, t],
|
||||
);
|
||||
|
||||
const handleRemoveFilter = useCallback(
|
||||
(filterKey: string) => {
|
||||
setValue(
|
||||
'appliedFilters',
|
||||
{
|
||||
...appliedFilters,
|
||||
...(filterKey === 'in' && { roomNames: [], rids: [], rid: undefined }),
|
||||
...(filterKey === 'from' && { fromUsernames: [], fromUsername: undefined }),
|
||||
...(filterKey === 'after' && { startDate: undefined }),
|
||||
...(filterKey === 'before' && { endDate: undefined }),
|
||||
},
|
||||
{ shouldDirty: true },
|
||||
);
|
||||
setFocus('filterText');
|
||||
},
|
||||
[appliedFilters, setFocus, setValue],
|
||||
);
|
||||
|
||||
const handleToggleAISearch = useCallback(() => {
|
||||
if (!canSearchWithAIFromTopBar) {
|
||||
return;
|
||||
}
|
||||
|
||||
setAISearchRequested((current) => !current);
|
||||
state.open();
|
||||
setFocus('filterText');
|
||||
}, [canSearchWithAIFromTopBar, setFocus, state]);
|
||||
|
||||
useEffect(() => {
|
||||
if (canSearchWithAIFromTopBar || !aiSearchRequested) {
|
||||
return;
|
||||
}
|
||||
|
||||
setAISearchRequested(false);
|
||||
}, [aiSearchRequested, canSearchWithAIFromTopBar]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!aiSearchActive || !filterText) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { searchText, filters, hasCompletedFilters } = extractCompletedSearchFilters(filterText);
|
||||
if (!hasCompletedFilters) {
|
||||
return;
|
||||
}
|
||||
|
||||
setValue('appliedFilters', mergeSearchFilters(appliedFilters, filters), { shouldDirty: true });
|
||||
setValue('filterText', searchText, { shouldDirty: true });
|
||||
}, [aiSearchActive, appliedFilters, filterText, setValue]);
|
||||
|
||||
return {
|
||||
aiSearchActive,
|
||||
canSearchWithAIFromTopBar,
|
||||
appliedFilterChips,
|
||||
aiSearchButtonTooltip: getAISearchButtonTooltip({ hasIntelligentSearchLicense, intelligentSearchEnabled, aiSearchActive, t }),
|
||||
handleRemoveFilter,
|
||||
handleToggleAISearch,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { OverlayTriggerState } from '@react-stately/overlays';
|
||||
import { useCallback } from 'react';
|
||||
|
||||
export const useSearchClick = (state: OverlayTriggerState) => {
|
||||
const handleClick = useCallback(() => {
|
||||
if (state.isOpen) {
|
||||
return;
|
||||
}
|
||||
|
||||
state.setOpen(true);
|
||||
}, [state]);
|
||||
|
||||
return handleClick;
|
||||
};
|
||||
@@ -0,0 +1,20 @@
|
||||
import type { OverlayTriggerState } from '@react-stately/overlays';
|
||||
import { useLayout } from '@rocket.chat/ui-contexts';
|
||||
import { useCallback, useEffect } from 'react';
|
||||
|
||||
export const useSearchFocus = (state: OverlayTriggerState) => {
|
||||
const { navbar } = useLayout();
|
||||
|
||||
useEffect(() => {
|
||||
if (!state.isOpen) {
|
||||
navbar.collapseSearch?.();
|
||||
}
|
||||
}, [navbar, state.isOpen]);
|
||||
|
||||
const handleFocus = useCallback(() => {
|
||||
navbar.expandSearch?.();
|
||||
state.setOpen(true);
|
||||
}, [navbar, state]);
|
||||
|
||||
return handleFocus;
|
||||
};
|
||||
@@ -0,0 +1,68 @@
|
||||
import { mockAppRoot } from '@rocket.chat/mock-providers';
|
||||
import type { SubscriptionWithRoom } from '@rocket.chat/ui-contexts';
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
|
||||
import { useSearchItems } from './useSearchItems';
|
||||
|
||||
describe('useSearchItems', () => {
|
||||
it('should treat an unset filter as an empty search', () => {
|
||||
const wrapper = mockAppRoot()
|
||||
.withSubscriptions([])
|
||||
.withEndpoint('GET', '/v1/spotlight', () => ({ users: [], rooms: [] }))
|
||||
.build();
|
||||
|
||||
const { result } = renderHook(() => useSearchItems(undefined), { wrapper });
|
||||
|
||||
expect(result.current.items).toEqual([]);
|
||||
});
|
||||
|
||||
it('should deduplicate a user if they already exist in local subscriptions as a self-DM', async () => {
|
||||
const myUserName = 'rocketchat.internal.admin.test';
|
||||
const myUserId = 'user_id_456';
|
||||
|
||||
const wrapper = mockAppRoot()
|
||||
.withSubscriptions([
|
||||
{
|
||||
_id: 'local_room_123',
|
||||
t: 'd',
|
||||
name: myUserName,
|
||||
uids: [myUserId],
|
||||
} as unknown as SubscriptionWithRoom,
|
||||
])
|
||||
.withEndpoint('GET', '/v1/spotlight', () => ({
|
||||
users: [{ _id: myUserId, username: myUserName, name: 'Rocket Chat Test' }],
|
||||
rooms: [],
|
||||
}))
|
||||
.build();
|
||||
|
||||
const { result } = renderHook(() => useSearchItems(myUserName), { wrapper });
|
||||
|
||||
expect(result.current.items).toHaveLength(1);
|
||||
expect(result.current.items[0]._id).toBe('local_room_123');
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
});
|
||||
|
||||
expect(result.current.items).toHaveLength(1);
|
||||
expect(result.current.items[0]._id).toBe('local_room_123');
|
||||
expect(result.current.items[0].name).toBe(myUserName);
|
||||
});
|
||||
|
||||
it('should append users from the server if they are NOT duplicates', async () => {
|
||||
const wrapper = mockAppRoot()
|
||||
.withSubscriptions([{ _id: 'local_room_123', t: 'd', name: 'general' } as unknown as SubscriptionWithRoom])
|
||||
.withEndpoint('GET', '/v1/spotlight', () => ({
|
||||
users: [{ _id: 'user_id_456', username: 'john.doe', name: 'John Doe' }],
|
||||
rooms: [],
|
||||
}))
|
||||
.build();
|
||||
|
||||
const { result } = renderHook(() => useSearchItems('jo'), { wrapper });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
expect(result.current.items).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
});
|
||||
159
apps/meteor/client/navbar/NavBarSearch/hooks/useSearchItems.ts
Normal file
159
apps/meteor/client/navbar/NavBarSearch/hooks/useSearchItems.ts
Normal file
@@ -0,0 +1,159 @@
|
||||
import { useDebouncedValue } from '@rocket.chat/fuselage-hooks';
|
||||
import { escapeRegExp } from '@rocket.chat/tools';
|
||||
import type { SubscriptionWithRoom } from '@rocket.chat/ui-contexts';
|
||||
import { useEndpoint, useUserSubscriptions } from '@rocket.chat/ui-contexts';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useMemo } from 'react';
|
||||
|
||||
import { getConfig } from '../../../lib/utils/getConfig';
|
||||
|
||||
const LIMIT = parseInt(String(getConfig('Sidebar_Search_Spotlight_LIMIT', 20)));
|
||||
|
||||
const options = {
|
||||
sort: {
|
||||
lm: -1,
|
||||
name: 1,
|
||||
},
|
||||
limit: LIMIT,
|
||||
} as const;
|
||||
|
||||
export const useSearchItems = (filterText = ''): { items: SubscriptionWithRoom[]; isLoading: boolean } => {
|
||||
const [, mention, name] = useMemo(() => filterText.match(/(@|#)?(.*)/i) || [], [filterText]);
|
||||
|
||||
const query = useMemo(() => {
|
||||
const filterRegex = new RegExp(escapeRegExp(name), 'i');
|
||||
|
||||
return {
|
||||
$or: [{ name: filterRegex }, { fname: filterRegex }],
|
||||
...(mention && {
|
||||
t: mention === '@' ? 'd' : { $ne: 'd' },
|
||||
}),
|
||||
};
|
||||
}, [name, mention]);
|
||||
|
||||
// Local cached subscriptions are matched against the *immediate* filter text so joined
|
||||
// rooms show up instantly, without waiting for the debounce or the server response.
|
||||
const localRooms = useUserSubscriptions(query, options);
|
||||
|
||||
// Only the server spotlight call is debounced — the local results above stay instant.
|
||||
const debouncedName = useDebouncedValue(name, 500);
|
||||
|
||||
const usernamesFromClient = [...localRooms?.map(({ t, name }) => (t === 'd' ? name : null))].filter(Boolean) as string[];
|
||||
|
||||
const searchForChannels = mention === '#';
|
||||
const searchForDMs = mention === '@';
|
||||
|
||||
const type = useMemo(() => {
|
||||
if (searchForChannels) {
|
||||
return { users: false, rooms: true, includeFederatedRooms: true };
|
||||
}
|
||||
if (searchForDMs) {
|
||||
return { users: true, rooms: false };
|
||||
}
|
||||
return { users: true, rooms: true, includeFederatedRooms: true };
|
||||
}, [searchForChannels, searchForDMs]);
|
||||
|
||||
const getSpotlight = useEndpoint('GET', '/v1/spotlight');
|
||||
|
||||
const {
|
||||
data: serverResults,
|
||||
isFetching,
|
||||
isPlaceholderData,
|
||||
} = useQuery({
|
||||
// Keyed on the debounced term only, so typing doesn't refetch on every keystroke.
|
||||
queryKey: ['sidebar/search/spotlight', debouncedName, mention, type],
|
||||
|
||||
// When local subscriptions already fill the limit there's nothing more to fetch.
|
||||
enabled: localRooms.length < LIMIT,
|
||||
|
||||
queryFn: async () => {
|
||||
const spotlight = await getSpotlight({
|
||||
query: debouncedName,
|
||||
usernames: usernamesFromClient.join(','),
|
||||
type: JSON.stringify(type),
|
||||
});
|
||||
|
||||
const filterUsersUnique = ({ _id }: { _id: string }, index: number, arr: { _id: string }[]): boolean =>
|
||||
index === arr.findIndex((user) => _id === user._id);
|
||||
|
||||
const userMap = (user: {
|
||||
_id: string;
|
||||
name: string;
|
||||
username: string;
|
||||
avatarETag?: string;
|
||||
}): {
|
||||
_id: string;
|
||||
t: string;
|
||||
name: string;
|
||||
fname: string;
|
||||
avatarETag?: string;
|
||||
} => ({
|
||||
_id: user._id,
|
||||
t: 'd',
|
||||
name: user.username,
|
||||
fname: user.name,
|
||||
avatarETag: user.avatarETag,
|
||||
});
|
||||
|
||||
type resultsFromServerType = {
|
||||
_id: string;
|
||||
t: string;
|
||||
name: string;
|
||||
teamMain?: boolean;
|
||||
fname?: string;
|
||||
avatarETag?: string | undefined;
|
||||
uids?: string[] | undefined;
|
||||
}[];
|
||||
|
||||
// Local subscriptions are deduped reactively in the merge below (against the *current*
|
||||
// localRooms), so server results aren't filtered against them here.
|
||||
const resultsFromServer: resultsFromServerType = [];
|
||||
resultsFromServer.push(...spotlight.users.filter(filterUsersUnique).map(userMap));
|
||||
resultsFromServer.push(...spotlight.rooms);
|
||||
|
||||
return resultsFromServer;
|
||||
},
|
||||
|
||||
staleTime: 60_000,
|
||||
// Keep the previous server results visible while a new search is in flight.
|
||||
placeholderData: (previousData) => previousData,
|
||||
});
|
||||
|
||||
// Merge reactively (outside the query) so local results render the instant the user types
|
||||
// and server results fold in — deduped — once they arrive.
|
||||
const items = useMemo(() => {
|
||||
// Server results are keyed on the *debounced* term, so while the user is still typing
|
||||
// (or via placeholderData) they may belong to a previous search. Drop the ones that no
|
||||
// longer match the current text so stale, non-matching results aren't rendered.
|
||||
const filterRegex = new RegExp(escapeRegExp(name), 'i');
|
||||
const matchesFilter = ({ name, fname }: { name?: string; fname?: string }) =>
|
||||
(name && filterRegex.test(name)) || (fname && filterRegex.test(fname));
|
||||
|
||||
// Single source of truth for local/server dedup: drop any server result already present as a
|
||||
// local subscription, checked against the *current* localRooms. The query isn't keyed on
|
||||
// localRooms (to avoid refetching on every subscription change), so subscriptions that load
|
||||
// in after the fetch would otherwise render twice — once from localRooms, once from server.
|
||||
const isLocalDuplicate = (item: { _id: string; t?: string; uids?: string[]; name: string }): boolean =>
|
||||
localRooms.some((room) => {
|
||||
const sameRoom = [room.rid, room._id].includes(item._id);
|
||||
const sameGroupDM = item.t === 'd' && !!item.uids && item.uids.length > 1 && item.uids.includes(room._id);
|
||||
const sameDirectDM = item.t === 'd' && room.t === 'd' && !!room.uids && room.uids.length === 2 && room.uids.includes(item._id);
|
||||
const sameUserDM = item.t === 'd' && room.t === 'd' && item.name === room.name;
|
||||
return sameRoom || sameGroupDM || sameDirectDM || sameUserDM;
|
||||
});
|
||||
|
||||
// When local subscriptions already fill the limit the server query is disabled, but React Query
|
||||
// keeps the last results around — ignore them so a full local list isn't padded with stale rows.
|
||||
const candidates = localRooms.length < LIMIT ? (serverResults ?? []) : [];
|
||||
const fromServer = candidates.filter((item) => matchesFilter(item) && !isLocalDuplicate(item));
|
||||
const exact = fromServer.filter((item) => [item.name, item.fname].includes(name));
|
||||
return Array.from(new Set([...exact, ...localRooms, ...fromServer])) as SubscriptionWithRoom[];
|
||||
}, [serverResults, localRooms, name]);
|
||||
|
||||
// `isFetching` is also true for silent background revalidations (after staleTime) of results we
|
||||
// already show — only surface loading while there's no usable data for the current term yet, i.e.
|
||||
// the very first fetch (serverResults undefined) or a new term still showing placeholder data.
|
||||
const isLoading = isFetching && (isPlaceholderData || serverResults === undefined);
|
||||
|
||||
return { items, isLoading };
|
||||
};
|
||||
@@ -0,0 +1,64 @@
|
||||
import { useFocusManager } from '@react-aria/focus';
|
||||
import type { OverlayTriggerState } from '@react-stately/overlays';
|
||||
import type { KeyboardEvent } from 'react';
|
||||
import { useCallback } from 'react';
|
||||
|
||||
export const isOption = (node: Element) => node.getAttribute('role') === 'option';
|
||||
|
||||
export const useListboxNavigation = (state: OverlayTriggerState) => {
|
||||
const focusManager = useFocusManager();
|
||||
|
||||
const handleKeyDown = useCallback(
|
||||
(e: KeyboardEvent) => {
|
||||
if (e.code === 'Tab') {
|
||||
state.close();
|
||||
}
|
||||
|
||||
if (e.code === 'ArrowUp' || e.code === 'ArrowDown') {
|
||||
e.preventDefault();
|
||||
|
||||
if (e.code === 'ArrowUp') {
|
||||
return focusManager?.focusPrevious({
|
||||
wrap: true,
|
||||
accept: (node) => isOption(node),
|
||||
});
|
||||
}
|
||||
|
||||
if (e.code === 'ArrowDown') {
|
||||
focusManager?.focusNext({
|
||||
wrap: true,
|
||||
accept: (node) => isOption(node),
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
[focusManager, state],
|
||||
);
|
||||
|
||||
return handleKeyDown;
|
||||
};
|
||||
|
||||
export const useSearchInputNavigation = (state: OverlayTriggerState) => {
|
||||
const focusManager = useFocusManager();
|
||||
|
||||
const handleKeyDown = useCallback(
|
||||
(e: KeyboardEvent) => {
|
||||
state.setOpen(true);
|
||||
|
||||
if ((e.code === 'Tab' && e.shiftKey) || e.key === 'Escape') {
|
||||
state.close();
|
||||
}
|
||||
|
||||
if (e.code === 'ArrowUp' || e.code === 'ArrowDown') {
|
||||
e.preventDefault();
|
||||
|
||||
focusManager?.focusNext({
|
||||
accept: (node) => isOption(node),
|
||||
});
|
||||
}
|
||||
},
|
||||
[focusManager, state],
|
||||
);
|
||||
|
||||
return handleKeyDown;
|
||||
};
|
||||
Reference in New Issue
Block a user