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,44 @@
|
||||
import { mockAppRoot } from '@rocket.chat/mock-providers';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
|
||||
import NavBarAISearch from './NavBarAISearch';
|
||||
|
||||
import '@testing-library/jest-dom';
|
||||
|
||||
jest.mock('./NavBarAISearchListbox', () => () => null);
|
||||
jest.mock('./NavBarSearchListbox', () => () => null);
|
||||
jest.mock('tinykeys', () => ({ __esModule: true, default: () => jest.fn() }));
|
||||
jest.mock('./hooks/useNavBarAISearch', () => ({
|
||||
useNavBarAISearch: () => ({
|
||||
aiSearchActive: false,
|
||||
canSearchWithAIFromTopBar: true,
|
||||
appliedFilterChips: [],
|
||||
aiSearchButtonTooltip: 'Search with AI',
|
||||
handleRemoveFilter: jest.fn(),
|
||||
handleToggleAISearch: jest.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
describe('NavBarAISearch', () => {
|
||||
it('clears the search text', async () => {
|
||||
const user = userEvent.setup();
|
||||
const wrapper = mockAppRoot()
|
||||
.withTranslations('en', 'core', {
|
||||
Clear: 'Clear',
|
||||
Search_rooms: 'Search rooms',
|
||||
})
|
||||
.build();
|
||||
|
||||
render(<NavBarAISearch />, { wrapper });
|
||||
|
||||
const searchInput = screen.getByRole('combobox', { name: 'Search rooms' });
|
||||
await user.type(searchInput, 'deployment errors');
|
||||
expect(searchInput).toHaveValue('deployment errors');
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Clear' }));
|
||||
|
||||
expect(searchInput).toHaveValue('');
|
||||
expect(searchInput).toHaveFocus();
|
||||
});
|
||||
});
|
||||
122
apps/meteor/client/navbar/NavBarSearch/NavBarAISearch.tsx
Normal file
122
apps/meteor/client/navbar/NavBarSearch/NavBarAISearch.tsx
Normal file
@@ -0,0 +1,122 @@
|
||||
import { useFocusManager } from '@react-aria/focus';
|
||||
import { useOverlayTrigger } from '@react-aria/overlays';
|
||||
import { useOverlayTriggerState } from '@react-stately/overlays';
|
||||
import { emptySearchFilters, type NavBarSearchFormValues } from '@rocket.chat/ai-search';
|
||||
import { Box, TextInput } from '@rocket.chat/fuselage';
|
||||
import { useMergedRefs, useStableCallback } from '@rocket.chat/fuselage-hooks';
|
||||
import { useCallback, useEffect, useRef } from 'react';
|
||||
import { FormProvider, useForm } from 'react-hook-form';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import tinykeys from 'tinykeys';
|
||||
|
||||
import NavBarAISearchListBox from './NavBarAISearchListbox';
|
||||
import NavBarSearchInputAddon from './NavBarSearchInputAddon';
|
||||
import NavBarSearchListBox from './NavBarSearchListbox';
|
||||
import { getShortcutLabel } from './getShortcutLabel';
|
||||
import { useNavBarAISearch } from './hooks/useNavBarAISearch';
|
||||
import { useSearchClick } from './hooks/useSearchClick';
|
||||
import { useSearchFocus } from './hooks/useSearchFocus';
|
||||
import { useSearchInputNavigation } from './hooks/useSearchNavigation';
|
||||
|
||||
const NavBarAISearch = () => {
|
||||
const { t } = useTranslation();
|
||||
const focusManager = useFocusManager();
|
||||
const shortcut = getShortcutLabel();
|
||||
|
||||
const methods = useForm<NavBarSearchFormValues>({ defaultValues: { filterText: '', appliedFilters: emptySearchFilters() } });
|
||||
const { register, resetField, setFocus, setValue, watch } = methods;
|
||||
const { filterText = '', appliedFilters = emptySearchFilters() } = watch();
|
||||
|
||||
const { ref: filterRef, ...rest } = register('filterText');
|
||||
|
||||
const triggerRef = useRef(null);
|
||||
const mergedRefs = useMergedRefs(filterRef, triggerRef);
|
||||
|
||||
const state = useOverlayTriggerState({});
|
||||
const { triggerProps, overlayProps } = useOverlayTrigger({ type: 'listbox' }, state, triggerRef);
|
||||
delete triggerProps.onPress;
|
||||
|
||||
const handleKeyDown = useSearchInputNavigation(state);
|
||||
const handleFocus = useSearchFocus(state);
|
||||
const handleClick = useSearchClick(state);
|
||||
|
||||
const { aiSearchActive, canSearchWithAIFromTopBar, appliedFilterChips, aiSearchButtonTooltip, handleRemoveFilter, handleToggleAISearch } =
|
||||
useNavBarAISearch({ filterText, appliedFilters, setFocus, setValue, state, t });
|
||||
|
||||
const searchLabel = aiSearchActive ? t('Search_rooms_or_ask_AI') : t('Search_rooms');
|
||||
const placeholder = [searchLabel, shortcut].filter(Boolean).join(' ');
|
||||
|
||||
const handleEscSearch = useCallback(() => {
|
||||
resetField('filterText');
|
||||
setValue('appliedFilters', emptySearchFilters(), { shouldDirty: true });
|
||||
state.close();
|
||||
}, [resetField, setValue, state]);
|
||||
|
||||
const handleClearText = useStableCallback(() => {
|
||||
resetField('filterText');
|
||||
setFocus('filterText');
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const unsubscribe = tinykeys(window, {
|
||||
'$mod+K': (event) => {
|
||||
event.preventDefault();
|
||||
setFocus('filterText');
|
||||
},
|
||||
'$mod+P': (event) => {
|
||||
event.preventDefault();
|
||||
setFocus('filterText');
|
||||
},
|
||||
'Escape': (event) => {
|
||||
event.preventDefault();
|
||||
handleEscSearch();
|
||||
},
|
||||
});
|
||||
|
||||
return (): void => {
|
||||
unsubscribe();
|
||||
};
|
||||
}, [focusManager, handleEscSearch, setFocus]);
|
||||
|
||||
return (
|
||||
<FormProvider {...methods}>
|
||||
<Box width='100%' maxWidth='x622' role='search' aria-label={searchLabel} marginInline={8} position='relative'>
|
||||
<TextInput
|
||||
{...rest}
|
||||
{...triggerProps}
|
||||
onFocus={handleFocus}
|
||||
onKeyDown={handleKeyDown}
|
||||
onClick={handleClick}
|
||||
autoComplete='off'
|
||||
placeholder={placeholder}
|
||||
ref={mergedRefs}
|
||||
role='combobox'
|
||||
aria-label={searchLabel}
|
||||
aria-autocomplete='list'
|
||||
aria-keyshortcuts='Control+K Meta+K Control+P Meta+P'
|
||||
small
|
||||
endAddon={
|
||||
<NavBarSearchInputAddon
|
||||
appliedFilterChips={appliedFilterChips}
|
||||
aiSearchActive={aiSearchActive}
|
||||
aiSearchButtonTooltip={aiSearchButtonTooltip}
|
||||
hasSearchText={Boolean(filterText)}
|
||||
onClearText={handleClearText}
|
||||
onRemoveFilter={handleRemoveFilter}
|
||||
onToggleAISearch={handleToggleAISearch}
|
||||
t={t}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
{state.isOpen &&
|
||||
(aiSearchActive ? (
|
||||
<NavBarAISearchListBox state={state} overlayProps={overlayProps} aiSearchActive aiSearchAvailable={canSearchWithAIFromTopBar} />
|
||||
) : (
|
||||
<NavBarSearchListBox state={state} overlayProps={overlayProps} />
|
||||
))}
|
||||
</Box>
|
||||
</FormProvider>
|
||||
);
|
||||
};
|
||||
|
||||
export default NavBarAISearch;
|
||||
@@ -0,0 +1,82 @@
|
||||
import type { OverlayTriggerAria } from '@react-aria/overlays';
|
||||
import type { OverlayTriggerState } from '@react-stately/overlays';
|
||||
import { emptySearchFilters, type NavBarSearchFormValues } from '@rocket.chat/ai-search';
|
||||
import { Tile } from '@rocket.chat/fuselage';
|
||||
import { useOutsideClick, useStableCallback } from '@rocket.chat/fuselage-hooks';
|
||||
import { CustomScrollbars } from '@rocket.chat/ui-client';
|
||||
import { useRef } from 'react';
|
||||
import { useFormContext } from 'react-hook-form';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import NavBarSearchFilterSuggestions from './NavBarSearchFilterSuggestions';
|
||||
import NavBarSearchIntelligentSection from './NavBarSearchIntelligentSection';
|
||||
import NavBarSearchRoomSection from './NavBarSearchRoomSection';
|
||||
import { useAISearchItems } from './hooks/useAISearchItems';
|
||||
import { useAISearchRooms } from './hooks/useAISearchRooms';
|
||||
import { useListboxNavigation } from './hooks/useSearchNavigation';
|
||||
import ResultsLiveRegion from '../../components/ResultsLiveRegion';
|
||||
|
||||
export type NavBarAISearchListBoxProps = {
|
||||
state: OverlayTriggerState;
|
||||
overlayProps: OverlayTriggerAria['overlayProps'];
|
||||
aiSearchActive: boolean;
|
||||
aiSearchAvailable: boolean;
|
||||
};
|
||||
|
||||
const NavBarAISearchListBox = ({ state, overlayProps, aiSearchActive, aiSearchAvailable }: NavBarAISearchListBoxProps) => {
|
||||
const { t } = useTranslation();
|
||||
const containerRef = useRef<HTMLElement>(null);
|
||||
|
||||
const handleKeyDown = useListboxNavigation(state);
|
||||
useOutsideClick([containerRef], state.close);
|
||||
|
||||
const { resetField, setValue, watch } = useFormContext<NavBarSearchFormValues>();
|
||||
const { filterText = '', appliedFilters = emptySearchFilters() } = watch();
|
||||
|
||||
const handleSelect = useStableCallback(() => {
|
||||
state.close();
|
||||
resetField('filterText');
|
||||
setValue('appliedFilters', emptySearchFilters(), { shouldDirty: true });
|
||||
});
|
||||
|
||||
const { data: aiItems, isFetching } = useAISearchItems(filterText, appliedFilters, aiSearchActive);
|
||||
const { items: rooms, isLoading } = useAISearchRooms(aiSearchActive ? aiItems.searchText : filterText);
|
||||
const itemCount = rooms.length + aiItems.intelligent.length + aiItems.filterSuggestions.length;
|
||||
const isSearchLoading = isLoading || isFetching;
|
||||
const listboxLabel = aiSearchActive ? t('AI_Search_results') : t('Channels');
|
||||
|
||||
return (
|
||||
<Tile
|
||||
ref={containerRef}
|
||||
position='absolute'
|
||||
zIndex={99}
|
||||
padding={0}
|
||||
paddingBlock={16}
|
||||
marginBlockStart={4}
|
||||
minHeight='x52'
|
||||
maxHeight='50vh'
|
||||
display='flex'
|
||||
width='100%'
|
||||
flexDirection='column'
|
||||
>
|
||||
<ResultsLiveRegion shouldAnnounce={!isSearchLoading} itemCount={itemCount} isLoading={isSearchLoading} />
|
||||
<CustomScrollbars>
|
||||
<div {...overlayProps} role='listbox' aria-label={listboxLabel} aria-busy={isSearchLoading} tabIndex={-1} onKeyDown={handleKeyDown}>
|
||||
<NavBarSearchIntelligentSection items={aiItems.intelligent} onSelect={handleSelect} onClose={state.close} />
|
||||
<NavBarSearchFilterSuggestions suggestions={aiItems.filterSuggestions} />
|
||||
<NavBarSearchRoomSection
|
||||
filterText={filterText}
|
||||
itemCount={itemCount}
|
||||
isLoading={isLoading}
|
||||
isFetching={isFetching}
|
||||
rooms={rooms}
|
||||
suggestAISearch={aiSearchAvailable && !aiSearchActive}
|
||||
onSelect={handleSelect}
|
||||
/>
|
||||
</div>
|
||||
</CustomScrollbars>
|
||||
</Tile>
|
||||
);
|
||||
};
|
||||
|
||||
export default NavBarAISearchListBox;
|
||||
@@ -0,0 +1,19 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import GenericNoResults from '../../components/GenericNoResults';
|
||||
|
||||
export type NavBarAISearchNoResultsProps = {
|
||||
suggestAISearch: boolean;
|
||||
};
|
||||
|
||||
const NavBarAISearchNoResults = ({ suggestAISearch }: NavBarAISearchNoResultsProps) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<GenericNoResults
|
||||
description={t(suggestAISearch ? 'Try_entering_a_different_search_term_or_search_with_AI' : 'Try_entering_a_different_search_term')}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default NavBarAISearchNoResults;
|
||||
106
apps/meteor/client/navbar/NavBarSearch/NavBarSearch.tsx
Normal file
106
apps/meteor/client/navbar/NavBarSearch/NavBarSearch.tsx
Normal file
@@ -0,0 +1,106 @@
|
||||
import { useFocusManager } from '@react-aria/focus';
|
||||
import { useOverlayTrigger } from '@react-aria/overlays';
|
||||
import { useOverlayTriggerState } from '@react-stately/overlays';
|
||||
import { Box, Icon, IconButton, TextInput } from '@rocket.chat/fuselage';
|
||||
import { useStableCallback, useMergedRefs } from '@rocket.chat/fuselage-hooks';
|
||||
import { useCallback, useEffect, useRef } from 'react';
|
||||
import { FormProvider, useForm } from 'react-hook-form';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import tinykeys from 'tinykeys';
|
||||
|
||||
import NavBarSearchListBox from './NavBarSearchListbox';
|
||||
import { getShortcutLabel } from './getShortcutLabel';
|
||||
import { useSearchClick } from './hooks/useSearchClick';
|
||||
import { useSearchFocus } from './hooks/useSearchFocus';
|
||||
import { useSearchInputNavigation } from './hooks/useSearchNavigation';
|
||||
|
||||
const NavBarSearch = () => {
|
||||
const { t } = useTranslation();
|
||||
const focusManager = useFocusManager();
|
||||
const shortcut = getShortcutLabel();
|
||||
|
||||
const placeholder = [t('Search_rooms'), shortcut].filter(Boolean).join(' ');
|
||||
|
||||
const methods = useForm({ defaultValues: { filterText: '' } });
|
||||
const {
|
||||
formState: { isDirty },
|
||||
register,
|
||||
resetField,
|
||||
setFocus,
|
||||
} = methods;
|
||||
|
||||
const { ref: filterRef, ...rest } = register('filterText');
|
||||
|
||||
const triggerRef = useRef(null);
|
||||
const mergedRefs = useMergedRefs(filterRef, triggerRef);
|
||||
|
||||
const state = useOverlayTriggerState({});
|
||||
const { triggerProps, overlayProps } = useOverlayTrigger({ type: 'listbox' }, state, triggerRef);
|
||||
delete triggerProps.onPress;
|
||||
|
||||
const handleKeyDown = useSearchInputNavigation(state);
|
||||
const handleFocus = useSearchFocus(state);
|
||||
const handleClick = useSearchClick(state);
|
||||
|
||||
const handleEscSearch = useCallback(() => {
|
||||
resetField('filterText');
|
||||
state.close();
|
||||
}, [resetField, state]);
|
||||
|
||||
const handleClearText = useStableCallback(() => {
|
||||
resetField('filterText');
|
||||
setFocus('filterText');
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const unsubscribe = tinykeys(window, {
|
||||
'$mod+K': (event) => {
|
||||
event.preventDefault();
|
||||
setFocus('filterText');
|
||||
},
|
||||
'$mod+P': (event) => {
|
||||
event.preventDefault();
|
||||
setFocus('filterText');
|
||||
},
|
||||
'Escape': (event) => {
|
||||
event.preventDefault();
|
||||
handleEscSearch();
|
||||
},
|
||||
});
|
||||
|
||||
return (): void => {
|
||||
unsubscribe();
|
||||
};
|
||||
}, [focusManager, handleEscSearch, setFocus]);
|
||||
|
||||
return (
|
||||
<FormProvider {...methods}>
|
||||
<Box width='100%' maxWidth='x622' role='search' aria-label={t('Search_rooms')} marginInline={8} position='relative'>
|
||||
<TextInput
|
||||
{...rest}
|
||||
{...triggerProps}
|
||||
onFocus={handleFocus}
|
||||
onKeyDown={handleKeyDown}
|
||||
onClick={handleClick}
|
||||
autoComplete='off'
|
||||
placeholder={placeholder}
|
||||
ref={mergedRefs}
|
||||
role='combobox'
|
||||
aria-autocomplete='list'
|
||||
aria-keyshortcuts='Control+K Meta+K Control+P Meta+P'
|
||||
small
|
||||
endAddon={
|
||||
isDirty ? (
|
||||
<IconButton mini icon='cross' aria-label={t('Clear')} onClick={handleClearText} />
|
||||
) : (
|
||||
<Icon name='magnifier' size='x20' aria-label={t('Search')} />
|
||||
)
|
||||
}
|
||||
/>
|
||||
{state.isOpen && <NavBarSearchListBox state={state} overlayProps={overlayProps} />}
|
||||
</Box>
|
||||
</FormProvider>
|
||||
);
|
||||
};
|
||||
|
||||
export default NavBarSearch;
|
||||
@@ -0,0 +1,84 @@
|
||||
import {
|
||||
emptySearchFilters,
|
||||
mergeSearchFilters,
|
||||
parseSearchFilterText,
|
||||
type NavBarSearchFormValues,
|
||||
type SearchFilterSuggestion,
|
||||
} from '@rocket.chat/ai-search';
|
||||
import { Box, Icon, SidebarItem, SidebarItemIcon, SidebarItemTitle } from '@rocket.chat/fuselage';
|
||||
import type { MouseEvent, ReactElement } from 'react';
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import { useFormContext } from 'react-hook-form';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
const filterSuggestionGroupLabels = {
|
||||
rooms: 'Search_filter_rooms',
|
||||
users: 'Search_filter_users',
|
||||
dates: 'Search_filter_dates',
|
||||
} as const;
|
||||
|
||||
export type NavBarSearchFilterSuggestionsProps = {
|
||||
suggestions: SearchFilterSuggestion[];
|
||||
};
|
||||
|
||||
const groupFilterSuggestions = (suggestions: SearchFilterSuggestion[]): [SearchFilterSuggestion['group'], SearchFilterSuggestion[]][] => {
|
||||
const grouped: Record<SearchFilterSuggestion['group'], SearchFilterSuggestion[]> = { rooms: [], users: [], dates: [] };
|
||||
for (const suggestion of suggestions) {
|
||||
grouped[suggestion.group].push(suggestion);
|
||||
}
|
||||
|
||||
const groups: [SearchFilterSuggestion['group'], SearchFilterSuggestion[]][] = [];
|
||||
for (const group of ['rooms', 'users', 'dates'] as const) {
|
||||
if (grouped[group].length > 0) {
|
||||
groups.push([group, grouped[group]]);
|
||||
}
|
||||
}
|
||||
|
||||
return groups;
|
||||
};
|
||||
|
||||
const NavBarSearchFilterSuggestions = ({ suggestions }: NavBarSearchFilterSuggestionsProps): ReactElement | null => {
|
||||
const { t } = useTranslation();
|
||||
const { getValues, setFocus, setValue } = useFormContext<NavBarSearchFormValues>();
|
||||
const filterSuggestionGroups = useMemo(() => groupFilterSuggestions(suggestions), [suggestions]);
|
||||
|
||||
const handleFilterSuggestion = useCallback(
|
||||
(event: MouseEvent, value: string) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const { searchText, filters } = parseSearchFilterText(value);
|
||||
const appliedFilters = getValues('appliedFilters') ?? emptySearchFilters();
|
||||
setValue('appliedFilters', mergeSearchFilters(appliedFilters, filters), { shouldDirty: true });
|
||||
setValue('filterText', searchText, { shouldDirty: true });
|
||||
setFocus('filterText');
|
||||
},
|
||||
[getValues, setFocus, setValue],
|
||||
);
|
||||
|
||||
if (!filterSuggestionGroups.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{filterSuggestionGroups.map(([group, groupSuggestions]) => (
|
||||
<Box key={group} display='flex' flexDirection='column' paddingBlockStart={8}>
|
||||
<Box color='titles-labels' fontScale='c1' fontWeight='bold' paddingInline={12} marginBlockEnd={4} role='presentation' aria-hidden>
|
||||
{t(filterSuggestionGroupLabels[group])}
|
||||
</Box>
|
||||
{groupSuggestions.map((item) => (
|
||||
<SidebarItem key={item.key} role='option' onClick={(event) => handleFilterSuggestion(event, item.value)}>
|
||||
<SidebarItemIcon icon={<Icon name={item.icon} size='x16' />} />
|
||||
<SidebarItemTitle>{item.title}</SidebarItemTitle>
|
||||
<Box color='hint' fontScale='c1' flexShrink={0}>
|
||||
{item.description}
|
||||
</Box>
|
||||
</SidebarItem>
|
||||
))}
|
||||
</Box>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default NavBarSearchFilterSuggestions;
|
||||
@@ -0,0 +1,60 @@
|
||||
import type { SearchFilterChip } from '@rocket.chat/ai-search';
|
||||
import { Box, Chip, Icon, IconButton } from '@rocket.chat/fuselage';
|
||||
import type { TFunction } from 'i18next';
|
||||
import type { ReactElement } from 'react';
|
||||
|
||||
export type NavBarSearchInputAddonProps = {
|
||||
appliedFilterChips: SearchFilterChip[];
|
||||
aiSearchActive: boolean;
|
||||
aiSearchButtonTooltip: string;
|
||||
hasSearchText: boolean;
|
||||
onClearText: () => void;
|
||||
onRemoveFilter: (filterKey: string) => void;
|
||||
onToggleAISearch: () => void;
|
||||
t: TFunction;
|
||||
};
|
||||
|
||||
const NavBarSearchInputAddon = ({
|
||||
appliedFilterChips,
|
||||
aiSearchActive,
|
||||
aiSearchButtonTooltip,
|
||||
hasSearchText,
|
||||
onClearText,
|
||||
onRemoveFilter,
|
||||
onToggleAISearch,
|
||||
t,
|
||||
}: NavBarSearchInputAddonProps): ReactElement => (
|
||||
<Box display='flex' alignItems='center' gap={8}>
|
||||
{appliedFilterChips.length > 0 && (
|
||||
<Box display='flex' alignItems='center' gap={4} maxWidth='x320' overflow='auto'>
|
||||
{appliedFilterChips.map((filter) => (
|
||||
<Chip
|
||||
key={filter.key}
|
||||
height='x20'
|
||||
minHeight='x20'
|
||||
value={filter.label}
|
||||
onClick={() => onRemoveFilter(filter.key)}
|
||||
title={filter.title}
|
||||
aria-label={t('Remove_filter', { filter: filter.label })}
|
||||
renderDismissSymbol={() => <Icon name='cross' size='x12' />}
|
||||
>
|
||||
<Box is='span' maxWidth='x104' withTruncatedText>
|
||||
{filter.label}
|
||||
</Box>
|
||||
</Chip>
|
||||
))}
|
||||
</Box>
|
||||
)}
|
||||
{hasSearchText ? <IconButton mini icon='cross' aria-label={t('Clear')} onClick={onClearText} /> : <Icon name='magnifier' size='x20' />}
|
||||
<IconButton
|
||||
mini
|
||||
icon='stars'
|
||||
pressed={aiSearchActive}
|
||||
aria-label={aiSearchButtonTooltip}
|
||||
title={aiSearchButtonTooltip}
|
||||
onClick={onToggleAISearch}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
|
||||
export default NavBarSearchInputAddon;
|
||||
@@ -0,0 +1,85 @@
|
||||
import { emptySearchFilters, type NavBarSearchFormValues } from '@rocket.chat/ai-search';
|
||||
import { mockAppRoot } from '@rocket.chat/mock-providers';
|
||||
import type { RouterContextValue } from '@rocket.chat/ui-contexts';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import type { ReactNode } from 'react';
|
||||
import { FormProvider, useForm } from 'react-hook-form';
|
||||
|
||||
import NavBarSearchIntelligentSection from './NavBarSearchIntelligentSection';
|
||||
|
||||
import '@testing-library/jest-dom';
|
||||
|
||||
jest.mock('./NavBarSearchMessageRow', () => () => null);
|
||||
|
||||
const SearchFormProvider = ({ children }: { children: ReactNode }) => {
|
||||
const methods = useForm<NavBarSearchFormValues>({
|
||||
defaultValues: {
|
||||
filterText: 'deployment errors',
|
||||
appliedFilters: { ...emptySearchFilters(), roomNames: ['general'] },
|
||||
},
|
||||
});
|
||||
|
||||
return <FormProvider {...methods}>{children}</FormProvider>;
|
||||
};
|
||||
|
||||
const renderSection = (
|
||||
items: Parameters<typeof NavBarSearchIntelligentSection>[0]['items'],
|
||||
router: Partial<RouterContextValue> = {},
|
||||
onClose = jest.fn(),
|
||||
) => {
|
||||
const appWrapper = mockAppRoot()
|
||||
.withTranslations('en', 'core', {
|
||||
Intelligent_Search: 'AI Search',
|
||||
AI_Search_related_messages: '{{count}} related message',
|
||||
View_all_results: 'View all results',
|
||||
})
|
||||
.withRouter(router)
|
||||
.build();
|
||||
|
||||
render(
|
||||
<SearchFormProvider>
|
||||
<NavBarSearchIntelligentSection items={items} onSelect={jest.fn()} onClose={onClose} />
|
||||
</SearchFormProvider>,
|
||||
{ wrapper: appWrapper },
|
||||
);
|
||||
};
|
||||
|
||||
describe('NavBarSearchIntelligentSection', () => {
|
||||
it('does not render the AI Search action without related results', () => {
|
||||
const buildRoutePath = jest.fn(() => '/search' as const);
|
||||
renderSection([], { buildRoutePath });
|
||||
|
||||
expect(screen.queryByText('View all results')).not.toBeInTheDocument();
|
||||
expect(buildRoutePath).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('renders a native link to the AI Search page when related results are available', async () => {
|
||||
const user = userEvent.setup();
|
||||
const buildRoutePath = jest.fn(() => '/search?q=in%3Ageneral%20deployment%20errors' as const);
|
||||
const onClose = jest.fn();
|
||||
renderSection(
|
||||
[
|
||||
{
|
||||
_id: 'message-id',
|
||||
msgId: 'message-id',
|
||||
text: 'Deployment failed during startup',
|
||||
},
|
||||
],
|
||||
{ buildRoutePath },
|
||||
onClose,
|
||||
);
|
||||
|
||||
const action = screen.getByRole('option', { name: 'View all results' });
|
||||
expect(action.tagName).toBe('A');
|
||||
expect(action).toHaveAttribute('href', '/search?q=in%3Ageneral%20deployment%20errors');
|
||||
expect(buildRoutePath).toHaveBeenCalledWith({
|
||||
name: 'search',
|
||||
search: { q: 'in:general deployment errors' },
|
||||
});
|
||||
|
||||
action.addEventListener('click', (event) => event.preventDefault(), { once: true });
|
||||
await user.click(action);
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
import { emptySearchFilters, serializeSearchQuery, type NavBarSearchFormValues } from '@rocket.chat/ai-search';
|
||||
import { Box, Icon, SidebarItemIcon } from '@rocket.chat/fuselage';
|
||||
import type { AISearchResult } from '@rocket.chat/rest-typings';
|
||||
import { useRouter } from '@rocket.chat/ui-contexts';
|
||||
import type { ReactElement } from 'react';
|
||||
import { useFormContext } from 'react-hook-form';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import NavBarSearchItem from './NavBarSearchItem';
|
||||
import NavBarSearchMessageRow from './NavBarSearchMessageRow';
|
||||
|
||||
export type NavBarSearchIntelligentSectionProps = {
|
||||
items: AISearchResult[];
|
||||
onSelect: () => void;
|
||||
onClose: () => void;
|
||||
};
|
||||
|
||||
const NavBarSearchIntelligentSection = ({ items, onSelect, onClose }: NavBarSearchIntelligentSectionProps): ReactElement | null => {
|
||||
const { t } = useTranslation();
|
||||
const router = useRouter();
|
||||
const { watch } = useFormContext<NavBarSearchFormValues>();
|
||||
const { filterText = '', appliedFilters = emptySearchFilters() } = watch();
|
||||
|
||||
if (!items.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const query = serializeSearchQuery(filterText, appliedFilters);
|
||||
const searchHref = router.buildRoutePath({
|
||||
name: 'search',
|
||||
search: query ? { q: query } : {},
|
||||
});
|
||||
|
||||
return (
|
||||
<Box display='flex' flexDirection='column' paddingBlockStart={8} paddingBlockEnd={12}>
|
||||
<Box color='titles-labels' fontScale='c2' paddingInline={16} marginBlockEnd={4} role='presentation' aria-hidden>
|
||||
{t('Intelligent_Search')}
|
||||
</Box>
|
||||
<Box color='hint' fontScale='c1' paddingInline={12} marginBlockEnd={4}>
|
||||
{t('AI_Search_related_messages', { count: items.length })}
|
||||
</Box>
|
||||
{items.map((item) => (
|
||||
<NavBarSearchMessageRow key={`intelligent-${item._id}`} item={item} onClick={onSelect} />
|
||||
))}
|
||||
<NavBarSearchItem
|
||||
title={t('View_all_results')}
|
||||
avatar={null}
|
||||
icon={<SidebarItemIcon icon={<Icon name='arrow-forward' size='x16' />} />}
|
||||
href={searchHref}
|
||||
onClick={onClose}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export default NavBarSearchIntelligentSection;
|
||||
28
apps/meteor/client/navbar/NavBarSearch/NavBarSearchItem.tsx
Normal file
28
apps/meteor/client/navbar/NavBarSearch/NavBarSearchItem.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
import { SidebarItem, SidebarItemAvatarWrapper, SidebarItemTitle } from '@rocket.chat/fuselage';
|
||||
import type { HTMLAttributes, ReactNode } from 'react';
|
||||
|
||||
export type NavBarSearchItemProps = {
|
||||
title: string;
|
||||
avatar: ReactNode;
|
||||
icon: ReactNode;
|
||||
actions?: ReactNode;
|
||||
href?: string;
|
||||
unread?: boolean;
|
||||
selected?: boolean;
|
||||
badges?: ReactNode;
|
||||
clickable?: boolean;
|
||||
} & Omit<HTMLAttributes<HTMLAnchorElement>, 'is'>;
|
||||
|
||||
const NavBarSearchItem = ({ icon, title, avatar, actions, unread, badges, ...props }: NavBarSearchItemProps) => {
|
||||
return (
|
||||
<SidebarItem role='option' {...props}>
|
||||
{avatar && <SidebarItemAvatarWrapper>{avatar}</SidebarItemAvatarWrapper>}
|
||||
{icon && icon}
|
||||
<SidebarItemTitle unread={unread}>{title}</SidebarItemTitle>
|
||||
{badges && badges}
|
||||
{actions && actions}
|
||||
</SidebarItem>
|
||||
);
|
||||
};
|
||||
|
||||
export default NavBarSearchItem;
|
||||
@@ -0,0 +1,20 @@
|
||||
import { SidebarItem, SidebarItemAvatarWrapper, SidebarItemTitle, Skeleton } from '@rocket.chat/fuselage';
|
||||
|
||||
// Placeholder row shown while the server spotlight results are still loading.
|
||||
// Decorative only: it has no `role='option'` so keyboard navigation skips it
|
||||
// (see useSearchNavigation), and `tabIndex={-1}` + `pointerEvents='none'` keep
|
||||
// it out of reach of focus and mouse clicks. Loading is conveyed via aria-busy.
|
||||
const NavBarSearchItemSkeleton = () => {
|
||||
return (
|
||||
<SidebarItem aria-hidden tabIndex={-1} style={{ pointerEvents: 'none' }}>
|
||||
<SidebarItemAvatarWrapper>
|
||||
<Skeleton variant='rect' width={20} height={20} />
|
||||
</SidebarItemAvatarWrapper>
|
||||
<SidebarItemTitle>
|
||||
<Skeleton />
|
||||
</SidebarItemTitle>
|
||||
</SidebarItem>
|
||||
);
|
||||
};
|
||||
|
||||
export default NavBarSearchItemSkeleton;
|
||||
@@ -0,0 +1,42 @@
|
||||
import { SidebarItemIcon } from '@rocket.chat/fuselage';
|
||||
import type { SubscriptionWithRoom } from '@rocket.chat/ui-contexts';
|
||||
import type { ComponentProps, ReactNode } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import NavBarSearchItem from './NavBarSearchItem';
|
||||
import { RoomIcon } from '../../components/RoomIcon';
|
||||
import { roomCoordinator } from '../../lib/rooms/roomCoordinator';
|
||||
import SidebarItemBadges from '../../sidebar/badges/SidebarItemBadges';
|
||||
import { useUnreadDisplay } from '../../sidebar/hooks/useUnreadDisplay';
|
||||
|
||||
export type NavBarSearchItemWithDataProps = {
|
||||
room: SubscriptionWithRoom;
|
||||
id: string;
|
||||
AvatarTemplate: ReactNode;
|
||||
} & Partial<ComponentProps<typeof NavBarSearchItem>>;
|
||||
|
||||
const NavBarSearchItemWithData = ({ room, AvatarTemplate, ...props }: NavBarSearchItemWithDataProps) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const href = roomCoordinator.getRouteLink(room.t, room) || '';
|
||||
const title = roomCoordinator.getRoomName(room.t, room) || '';
|
||||
|
||||
const { unreadTitle, showUnread, highlightUnread: highlighted } = useUnreadDisplay(room);
|
||||
|
||||
const icon = <SidebarItemIcon highlighted={highlighted} icon={<RoomIcon room={room} placement='sidebar' size='x20' />} />;
|
||||
|
||||
return (
|
||||
<NavBarSearchItem
|
||||
{...props}
|
||||
unread={highlighted}
|
||||
href={href}
|
||||
aria-label={showUnread ? t('__unreadTitle__from__roomTitle__', { unreadTitle, roomTitle: title }) : title}
|
||||
title={title}
|
||||
icon={icon}
|
||||
badges={<SidebarItemBadges room={room} roomTitle={title} />}
|
||||
avatar={AvatarTemplate}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default NavBarSearchItemWithData;
|
||||
@@ -0,0 +1,80 @@
|
||||
import type { OverlayTriggerAria } from '@react-aria/overlays';
|
||||
import type { OverlayTriggerState } from '@react-stately/overlays';
|
||||
import { Box, Tile } from '@rocket.chat/fuselage';
|
||||
import { useStableCallback, useOutsideClick } from '@rocket.chat/fuselage-hooks';
|
||||
import { CustomScrollbars } from '@rocket.chat/ui-client';
|
||||
import { useRef } from 'react';
|
||||
import { useFormContext } from 'react-hook-form';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import NavBarSearchItemSkeleton from './NavBarSearchItemSkeleton';
|
||||
import NavBarSearchNoResults from './NavBarSearchNoResults';
|
||||
import NavBarSearchRow from './NavBarSearchRow';
|
||||
import { useSearchItems } from './hooks/useSearchItems';
|
||||
import { useListboxNavigation } from './hooks/useSearchNavigation';
|
||||
import ResultsLiveRegion from '../../components/ResultsLiveRegion';
|
||||
|
||||
export type NavBarSearchListBoxProps = {
|
||||
state: OverlayTriggerState;
|
||||
overlayProps: OverlayTriggerAria['overlayProps'];
|
||||
};
|
||||
|
||||
const NavBarSearchListBox = ({ state, overlayProps }: NavBarSearchListBoxProps) => {
|
||||
const { t } = useTranslation();
|
||||
const containerRef = useRef<HTMLElement>(null);
|
||||
|
||||
const handleKeyDown = useListboxNavigation(state);
|
||||
useOutsideClick([containerRef], state.close);
|
||||
|
||||
const { resetField, watch } = useFormContext();
|
||||
const { filterText } = watch();
|
||||
|
||||
const handleSelect = useStableCallback(() => {
|
||||
state.close();
|
||||
resetField('filterText');
|
||||
});
|
||||
|
||||
const { items, isLoading } = useSearchItems(filterText);
|
||||
|
||||
return (
|
||||
<Tile
|
||||
ref={containerRef}
|
||||
position='absolute'
|
||||
zIndex={99}
|
||||
padding={0}
|
||||
paddingBlock={16}
|
||||
marginBlockStart={4}
|
||||
minHeight='x52'
|
||||
maxHeight='50vh'
|
||||
display='flex'
|
||||
width='100%'
|
||||
flexDirection='column'
|
||||
>
|
||||
<ResultsLiveRegion shouldAnnounce={!isLoading} itemCount={items.length} isLoading={isLoading} />
|
||||
<CustomScrollbars>
|
||||
<div {...overlayProps} role='listbox' aria-label={t('Channels')} aria-busy={isLoading} tabIndex={-1} onKeyDown={handleKeyDown}>
|
||||
{items.length === 0 && !isLoading && <NavBarSearchNoResults />}
|
||||
{items.length > 0 && (
|
||||
<Box
|
||||
color='titles-labels'
|
||||
fontScale='c1'
|
||||
fontWeight='bold'
|
||||
paddingInline={12}
|
||||
marginBlockEnd={4}
|
||||
role='presentation'
|
||||
aria-hidden
|
||||
>
|
||||
{filterText ? t('Results') : t('Recent')}
|
||||
</Box>
|
||||
)}
|
||||
{items.map((item) => (
|
||||
<NavBarSearchRow key={item._id} room={item} onClick={handleSelect} />
|
||||
))}
|
||||
{isLoading && Array.from({ length: 4 }, (_, index) => <NavBarSearchItemSkeleton key={`skeleton-${index}`} />)}
|
||||
</div>
|
||||
</CustomScrollbars>
|
||||
</Tile>
|
||||
);
|
||||
};
|
||||
|
||||
export default NavBarSearchListBox;
|
||||
@@ -0,0 +1,58 @@
|
||||
import { Box, Icon, SidebarItemIcon } from '@rocket.chat/fuselage';
|
||||
import type { AISearchResult } from '@rocket.chat/rest-typings';
|
||||
import type { ReactElement } from 'react';
|
||||
import { memo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import NavBarSearchItem from './NavBarSearchItem';
|
||||
import { roomCoordinator } from '../../lib/rooms/roomCoordinator';
|
||||
|
||||
export type NavBarSearchMessageRowProps = {
|
||||
item: AISearchResult;
|
||||
onClick: () => void;
|
||||
};
|
||||
|
||||
const getHref = ({ room, rid, msgId }: AISearchResult): string | undefined => {
|
||||
if (!room) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const href = roomCoordinator.getRouteLink(room.t, {
|
||||
rid: room._id || rid,
|
||||
name: room.name,
|
||||
});
|
||||
|
||||
if (!href) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return msgId ? `${href}?msg=${encodeURIComponent(msgId)}` : href;
|
||||
};
|
||||
|
||||
const NavBarSearchMessageRow = ({ item, onClick }: NavBarSearchMessageRowProps): ReactElement => {
|
||||
const { t } = useTranslation();
|
||||
const { room } = item;
|
||||
const title = item.text.trim() || t('Intelligent_Search_Result');
|
||||
const roomLabel = room?.fname || room?.name;
|
||||
const href = getHref(item);
|
||||
|
||||
return (
|
||||
<NavBarSearchItem
|
||||
id={`search-intelligent-${item._id}`}
|
||||
href={href}
|
||||
onClick={onClick}
|
||||
title={title}
|
||||
avatar={null}
|
||||
icon={<SidebarItemIcon icon={<Icon name='stars' size='x16' />} />}
|
||||
actions={
|
||||
roomLabel ? (
|
||||
<Box color='hint' fontScale='c1' withTruncatedText flexShrink={0} maxWidth='x120'>
|
||||
{roomLabel}
|
||||
</Box>
|
||||
) : undefined
|
||||
}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default memo(NavBarSearchMessageRow);
|
||||
@@ -0,0 +1,10 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import GenericNoResults from '../../components/GenericNoResults';
|
||||
|
||||
const NavBarSearchNoResults = () => {
|
||||
const { t } = useTranslation();
|
||||
return <GenericNoResults description={t('Try_entering_a_different_search_term')} />;
|
||||
};
|
||||
|
||||
export default NavBarSearchNoResults;
|
||||
@@ -0,0 +1,48 @@
|
||||
import { Box } from '@rocket.chat/fuselage';
|
||||
import type { SubscriptionWithRoom } from '@rocket.chat/ui-contexts';
|
||||
import type { ReactElement } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import NavBarAISearchNoResults from './NavBarAISearchNoResults';
|
||||
import NavBarSearchItemSkeleton from './NavBarSearchItemSkeleton';
|
||||
import NavBarSearchRow from './NavBarSearchRow';
|
||||
|
||||
export type NavBarSearchRoomSectionProps = {
|
||||
filterText: string;
|
||||
itemCount: number;
|
||||
isLoading: boolean;
|
||||
isFetching: boolean;
|
||||
rooms: SubscriptionWithRoom[];
|
||||
suggestAISearch: boolean;
|
||||
onSelect: () => void;
|
||||
};
|
||||
|
||||
const NavBarSearchRoomSection = ({
|
||||
filterText,
|
||||
itemCount,
|
||||
isLoading,
|
||||
isFetching,
|
||||
rooms,
|
||||
suggestAISearch,
|
||||
onSelect,
|
||||
}: NavBarSearchRoomSectionProps): ReactElement => {
|
||||
const { t } = useTranslation();
|
||||
const showSkeleton = isLoading || (itemCount === 0 && isFetching);
|
||||
|
||||
return (
|
||||
<>
|
||||
{itemCount === 0 && !isLoading && !isFetching && <NavBarAISearchNoResults suggestAISearch={suggestAISearch} />}
|
||||
{rooms.length > 0 && (
|
||||
<Box color='titles-labels' fontScale='c1' fontWeight='bold' paddingInline={12} marginBlockEnd={4} role='presentation' aria-hidden>
|
||||
{filterText ? t('Results') : t('Recent')}
|
||||
</Box>
|
||||
)}
|
||||
{rooms.map((item) => (
|
||||
<NavBarSearchRow key={item._id} room={item} onClick={onSelect} />
|
||||
))}
|
||||
{showSkeleton && Array.from({ length: 4 }, (_, index) => <NavBarSearchItemSkeleton key={`skeleton-${index}`} />)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default NavBarSearchRoomSection;
|
||||
23
apps/meteor/client/navbar/NavBarSearch/NavBarSearchRow.tsx
Normal file
23
apps/meteor/client/navbar/NavBarSearch/NavBarSearchRow.tsx
Normal file
@@ -0,0 +1,23 @@
|
||||
import { RoomAvatar } from '@rocket.chat/ui-avatar';
|
||||
import type { SubscriptionWithRoom } from '@rocket.chat/ui-contexts';
|
||||
import { memo } from 'react';
|
||||
|
||||
import NavBarSearchItemWithData from './NavBarSearchItemWithData';
|
||||
import NavBarSearchUserRow from './NavBarSearchUserRow';
|
||||
|
||||
export type NavBarSearchRowProps = {
|
||||
room: SubscriptionWithRoom;
|
||||
onClick: () => void;
|
||||
};
|
||||
|
||||
const NavBarSearchRow = ({ room, onClick }: NavBarSearchRowProps) => {
|
||||
const Avatar = <RoomAvatar size='x20' room={{ ...room, _id: room.rid || room._id, type: room.t }} />;
|
||||
|
||||
if (room.t === 'd' && !room.u) {
|
||||
return <NavBarSearchUserRow id={`search-${room._id}`} room={room} AvatarTemplate={Avatar} onClick={onClick} />;
|
||||
}
|
||||
|
||||
return <NavBarSearchItemWithData id={`search-${room._id}`} room={room} AvatarTemplate={Avatar} onClick={onClick} />;
|
||||
};
|
||||
|
||||
export default memo(NavBarSearchRow);
|
||||
@@ -0,0 +1,26 @@
|
||||
import { SidebarItemIcon } from '@rocket.chat/fuselage';
|
||||
import type { SubscriptionWithRoom } from '@rocket.chat/ui-contexts';
|
||||
import { useSetting } from '@rocket.chat/ui-contexts';
|
||||
import type { ComponentProps, ReactNode } from 'react';
|
||||
import { memo } from 'react';
|
||||
|
||||
import NavBarSearchItem from './NavBarSearchItem';
|
||||
import { ReactiveUserStatus } from '../../components/UserStatus';
|
||||
import { roomCoordinator } from '../../lib/rooms/roomCoordinator';
|
||||
|
||||
export type NavBarSearchUserRowProps = {
|
||||
room: SubscriptionWithRoom;
|
||||
id: string;
|
||||
AvatarTemplate: ReactNode;
|
||||
} & Partial<ComponentProps<typeof NavBarSearchItem>>;
|
||||
|
||||
const NavBarSearchUserRow = ({ room, id, AvatarTemplate, ...props }: NavBarSearchUserRowProps) => {
|
||||
const useRealName = useSetting('UI_Use_Real_Name');
|
||||
const title = useRealName ? room.fname || room.name : room.name || room.fname || '';
|
||||
const icon = <SidebarItemIcon icon={<ReactiveUserStatus uid={room._id} />} />;
|
||||
const href = roomCoordinator.getRouteLink(room.t, { name: room.name }) || '';
|
||||
|
||||
return <NavBarSearchItem {...props} id={id} href={href} title={title} avatar={AvatarTemplate} icon={icon} />;
|
||||
};
|
||||
|
||||
export default memo(NavBarSearchUserRow);
|
||||
25
apps/meteor/client/navbar/NavBarSearch/getShortcutLabel.ts
Normal file
25
apps/meteor/client/navbar/NavBarSearch/getShortcutLabel.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
const mobileCheck = function () {
|
||||
let check = false;
|
||||
(function (a: string) {
|
||||
if (
|
||||
/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(
|
||||
a,
|
||||
) ||
|
||||
/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(
|
||||
a.substr(0, 4),
|
||||
)
|
||||
)
|
||||
check = true;
|
||||
})(navigator.userAgent || navigator.vendor || window.opera || '');
|
||||
return check;
|
||||
};
|
||||
|
||||
export const getShortcutLabel = (): string => {
|
||||
if (navigator.userAgentData?.mobile || mobileCheck()) {
|
||||
return '';
|
||||
}
|
||||
if (window.navigator.platform.toLowerCase().includes('mac')) {
|
||||
return '(\u2318+K)';
|
||||
}
|
||||
return '(Ctrl+K)';
|
||||
};
|
||||
@@ -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;
|
||||
};
|
||||
1
apps/meteor/client/navbar/NavBarSearch/index.ts
Normal file
1
apps/meteor/client/navbar/NavBarSearch/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { default } from './NavBarSearch';
|
||||
Reference in New Issue
Block a user