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:
20
apps/meteor/client/navbar/NavBar.tsx
Normal file
20
apps/meteor/client/navbar/NavBar.tsx
Normal file
@@ -0,0 +1,20 @@
|
||||
import { NavBar as NavBarComponent } from '@rocket.chat/fuselage';
|
||||
import { useLayout } from '@rocket.chat/ui-contexts';
|
||||
|
||||
import NavBarControlsSection from './NavBarControls/NavBarControlsSection';
|
||||
import NavBarNavigation from './NavBarNavigation';
|
||||
import NavBarPagesSection from './NavBarPagesSection';
|
||||
|
||||
const NavBar = () => {
|
||||
const { navbar } = useLayout();
|
||||
|
||||
return (
|
||||
<NavBarComponent aria-label='header'>
|
||||
{!navbar.searchExpanded && <NavBarPagesSection />}
|
||||
<NavBarNavigation />
|
||||
{!navbar.searchExpanded && <NavBarControlsSection />}
|
||||
</NavBarComponent>
|
||||
);
|
||||
};
|
||||
|
||||
export default NavBar;
|
||||
@@ -0,0 +1,48 @@
|
||||
import { NavBarItem } from '@rocket.chat/fuselage';
|
||||
import type { GenericMenuItemProps } from '@rocket.chat/ui-client';
|
||||
import { GenericMenu } from '@rocket.chat/ui-client';
|
||||
import type { HTMLAttributes } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useOmnichannelEnabled } from '../../views/omnichannel/hooks/useOmnichannelEnabled';
|
||||
|
||||
export type NavBarControlsMenuProps = Omit<HTMLAttributes<HTMLElement>, 'is'> & {
|
||||
omnichannelItems: GenericMenuItemProps[];
|
||||
isPressed: boolean;
|
||||
callItem?: GenericMenuItemProps;
|
||||
callHistoryItem?: GenericMenuItemProps;
|
||||
};
|
||||
|
||||
const NavBarControlsMenu = ({ omnichannelItems, isPressed, callItem, callHistoryItem, ...props }: NavBarControlsMenuProps) => {
|
||||
const { t } = useTranslation();
|
||||
const showOmnichannel = useOmnichannelEnabled();
|
||||
|
||||
const sections = [
|
||||
{
|
||||
title: t('Voice_Call'),
|
||||
items: callItem || callHistoryItem ? ([callItem, callHistoryItem].filter(Boolean) as GenericMenuItemProps[]) : [],
|
||||
},
|
||||
{
|
||||
title: t('Omnichannel'),
|
||||
items: showOmnichannel ? omnichannelItems : [],
|
||||
},
|
||||
].filter((section) => section.items.length > 0);
|
||||
|
||||
if (sections.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<GenericMenu
|
||||
sections={sections}
|
||||
title={t('Voice_and_omnichannel')}
|
||||
is={NavBarItem}
|
||||
placement='bottom-start'
|
||||
icon='kebab'
|
||||
pressed={isPressed}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default NavBarControlsMenu;
|
||||
@@ -0,0 +1,44 @@
|
||||
import { NavBarSection, NavBarGroup } from '@rocket.chat/fuselage';
|
||||
import { useUser, useLayout } from '@rocket.chat/ui-contexts';
|
||||
import { useMediaCallAction } from '@rocket.chat/ui-voip';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import NavBarControlsWithData from './NavBarControlsWithData';
|
||||
import { useOmnichannelEnabled } from '../../views/omnichannel/hooks/useOmnichannelEnabled';
|
||||
import NavBarOmnichannelGroup from '../NavBarOmnichannelGroup';
|
||||
import { NavBarItemLoginPage, NavBarItemAdministrationMenu, UserMenu } from '../NavBarSettingsToolbar';
|
||||
import NavBarVoipGroup from '../NavBarVoipGroup';
|
||||
|
||||
const NavBarControlsSection = () => {
|
||||
const { t } = useTranslation();
|
||||
const user = useUser();
|
||||
const { isMobile } = useLayout();
|
||||
|
||||
const showOmnichannel = useOmnichannelEnabled();
|
||||
const callAction = useMediaCallAction();
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<NavBarSection>
|
||||
{(showOmnichannel || callAction) && <NavBarControlsWithData />}
|
||||
<NavBarGroup aria-label={t('Workspace_and_user_preferences')}>
|
||||
<NavBarItemAdministrationMenu />
|
||||
{user ? <UserMenu user={user} /> : <NavBarItemLoginPage />}
|
||||
</NavBarGroup>
|
||||
</NavBarSection>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<NavBarSection>
|
||||
{callAction && <NavBarVoipGroup />}
|
||||
{showOmnichannel && <NavBarOmnichannelGroup />}
|
||||
<NavBarGroup aria-label={t('Workspace_and_user_preferences')}>
|
||||
<NavBarItemAdministrationMenu />
|
||||
{user ? <UserMenu user={user} /> : <NavBarItemLoginPage />}
|
||||
</NavBarGroup>
|
||||
</NavBarSection>
|
||||
);
|
||||
};
|
||||
|
||||
export default NavBarControlsSection;
|
||||
@@ -0,0 +1,96 @@
|
||||
import type { GenericMenuItemProps } from '@rocket.chat/ui-client';
|
||||
import { useRouter } from '@rocket.chat/ui-contexts';
|
||||
import { useMediaCallAction } from '@rocket.chat/ui-voip';
|
||||
import { useCallback, type HTMLAttributes } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import NavBarControlsMenu from './NavBarControlsMenu';
|
||||
import { useOmnichannelContactAction } from '../NavBarOmnichannelGroup/hooks/useOmnichannelContactAction';
|
||||
import { useOmnichannelLivechatToggle } from '../NavBarOmnichannelGroup/hooks/useOmnichannelLivechatToggle';
|
||||
import { useOmnichannelQueueAction } from '../NavBarOmnichannelGroup/hooks/useOmnichannelQueueAction';
|
||||
|
||||
type NavBarControlsMenuProps = Omit<HTMLAttributes<HTMLElement>, 'is'>;
|
||||
|
||||
const NavBarControlsWithData = (props: NavBarControlsMenuProps) => {
|
||||
const { t } = useTranslation();
|
||||
const callAction = useMediaCallAction();
|
||||
|
||||
const router = useRouter();
|
||||
const openCallHistory = useCallback(() => {
|
||||
router.navigate('/call-history');
|
||||
}, [router]);
|
||||
|
||||
const {
|
||||
isEnabled: queueEnabled,
|
||||
icon: queueIcon,
|
||||
title: queueTitle,
|
||||
handleGoToQueue,
|
||||
isPressed: isQueuePressed,
|
||||
} = useOmnichannelQueueAction();
|
||||
|
||||
const {
|
||||
title: contactCenterTitle,
|
||||
icon: contactCenterIcon,
|
||||
handleGoToContactCenter,
|
||||
isPressed: isContactPressed,
|
||||
} = useOmnichannelContactAction();
|
||||
|
||||
const {
|
||||
title: omnichannelLivechatTogglerTitle,
|
||||
icon: omnichannelLivechatTogglerIcon,
|
||||
handleAvailableStatusChange,
|
||||
} = useOmnichannelLivechatToggle();
|
||||
|
||||
const callItem = callAction
|
||||
? {
|
||||
id: 'rcx-media-call',
|
||||
icon: callAction.icon,
|
||||
content: callAction.title,
|
||||
onClick: () => callAction.action(),
|
||||
}
|
||||
: undefined;
|
||||
|
||||
const callHistoryItem = callAction
|
||||
? {
|
||||
id: 'rcx-media-call-history',
|
||||
icon: 'clock' as const,
|
||||
content: t('Call_history'),
|
||||
onClick: openCallHistory,
|
||||
}
|
||||
: undefined;
|
||||
|
||||
const omnichannelItems = [
|
||||
queueEnabled && {
|
||||
id: 'omnichannelQueue',
|
||||
icon: queueIcon,
|
||||
content: queueTitle,
|
||||
onClick: handleGoToQueue,
|
||||
},
|
||||
{
|
||||
id: 'omnichannelContact',
|
||||
icon: contactCenterIcon,
|
||||
content: contactCenterTitle,
|
||||
onClick: handleGoToContactCenter,
|
||||
},
|
||||
{
|
||||
id: 'omnichannelLivechatToggler',
|
||||
icon: omnichannelLivechatTogglerIcon,
|
||||
content: omnichannelLivechatTogglerTitle,
|
||||
onClick: handleAvailableStatusChange,
|
||||
},
|
||||
].filter(Boolean) as GenericMenuItemProps[];
|
||||
|
||||
const isPressed = isQueuePressed || isContactPressed;
|
||||
|
||||
return (
|
||||
<NavBarControlsMenu
|
||||
callHistoryItem={callHistoryItem}
|
||||
callItem={callItem}
|
||||
omnichannelItems={omnichannelItems}
|
||||
isPressed={isPressed}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default NavBarControlsWithData;
|
||||
39
apps/meteor/client/navbar/NavBarNavigation.tsx
Normal file
39
apps/meteor/client/navbar/NavBarNavigation.tsx
Normal file
@@ -0,0 +1,39 @@
|
||||
import { FocusScope } from '@react-aria/focus';
|
||||
import { NavBarGroup, NavBarItem, Box } from '@rocket.chat/fuselage';
|
||||
import { FeaturePreview, FeaturePreviewOff, FeaturePreviewOn } from '@rocket.chat/ui-client';
|
||||
import { useLayout, useRouter } from '@rocket.chat/ui-contexts';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import NavBarSearch from './NavBarSearch';
|
||||
import NavBarAISearch from './NavBarSearch/NavBarAISearch';
|
||||
|
||||
const NavbarNavigation = () => {
|
||||
const { t } = useTranslation();
|
||||
const { navigate } = useRouter();
|
||||
const { isMobile } = useLayout();
|
||||
|
||||
return (
|
||||
<Box display='flex' flexGrow={1} justifyContent='center'>
|
||||
<FocusScope>
|
||||
<FeaturePreview feature='aiSearch'>
|
||||
<FeaturePreviewOff>
|
||||
<NavBarSearch />
|
||||
</FeaturePreviewOff>
|
||||
<FeaturePreviewOn>
|
||||
<NavBarAISearch />
|
||||
</FeaturePreviewOn>
|
||||
</FeaturePreview>
|
||||
</FocusScope>
|
||||
{!isMobile && (
|
||||
<Box marginInlineEnd={8}>
|
||||
<NavBarGroup aria-label={t('History_navigation')}>
|
||||
<NavBarItem title={t('Back_in_history')} onClick={() => navigate(-1)} icon='chevron-right' small />
|
||||
<NavBarItem title={t('Forward_in_history')} onClick={() => navigate(1)} icon='chevron-left' small />
|
||||
</NavBarGroup>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export default NavbarNavigation;
|
||||
@@ -0,0 +1,23 @@
|
||||
import { NavBarItem } from '@rocket.chat/fuselage';
|
||||
import type { HTMLAttributes } from 'react';
|
||||
|
||||
import { useOmnichannelContactAction } from './hooks/useOmnichannelContactAction';
|
||||
|
||||
export type NavBarItemOmnichannelContactProps = Omit<HTMLAttributes<HTMLElement>, 'is'>;
|
||||
|
||||
const NavBarItemOmnichannelContact = (props: NavBarItemOmnichannelContactProps) => {
|
||||
const { icon, isPressed, title, handleGoToContactCenter } = useOmnichannelContactAction();
|
||||
|
||||
return (
|
||||
<NavBarItem
|
||||
{...props}
|
||||
icon={icon}
|
||||
title={title}
|
||||
onClick={handleGoToContactCenter}
|
||||
pressed={isPressed}
|
||||
aria-current={isPressed ? 'page' : undefined}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default NavBarItemOmnichannelContact;
|
||||
@@ -0,0 +1,23 @@
|
||||
import { NavBarItem } from '@rocket.chat/fuselage';
|
||||
import type { HTMLAttributes } from 'react';
|
||||
|
||||
import { useOmnichannelLivechatToggle } from './hooks/useOmnichannelLivechatToggle';
|
||||
|
||||
export type NavBarItemOmnichannelLivechatToggleProps = Omit<HTMLAttributes<HTMLElement>, 'is'>;
|
||||
|
||||
const NavBarItemOmnichannelLivechatToggle = (props: NavBarItemOmnichannelLivechatToggleProps) => {
|
||||
const { handleAvailableStatusChange, title, icon, isSuccess } = useOmnichannelLivechatToggle();
|
||||
|
||||
return (
|
||||
<NavBarItem
|
||||
{...props}
|
||||
id='omnichannel-status-toggle'
|
||||
title={title}
|
||||
success={isSuccess}
|
||||
icon={icon}
|
||||
onClick={handleAvailableStatusChange}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default NavBarItemOmnichannelLivechatToggle;
|
||||
@@ -0,0 +1,27 @@
|
||||
import { NavBarItem } from '@rocket.chat/fuselage';
|
||||
import type { HTMLAttributes } from 'react';
|
||||
|
||||
import { useOmnichannelQueueAction } from './hooks/useOmnichannelQueueAction';
|
||||
|
||||
export type NavBarItemOmnichannelQueueProps = Omit<HTMLAttributes<HTMLElement>, 'is'>;
|
||||
|
||||
const NavBarItemOmnichannelQueue = (props: NavBarItemOmnichannelQueueProps) => {
|
||||
const { isEnabled, title, icon, isPressed, handleGoToQueue } = useOmnichannelQueueAction();
|
||||
|
||||
if (!isEnabled) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<NavBarItem
|
||||
{...props}
|
||||
icon={icon}
|
||||
title={title}
|
||||
onClick={handleGoToQueue}
|
||||
pressed={isPressed}
|
||||
aria-current={isPressed ? 'page' : undefined}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default NavBarItemOmnichannelQueue;
|
||||
@@ -0,0 +1,20 @@
|
||||
import { NavBarGroup } from '@rocket.chat/fuselage';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import NavBarItemOmnichannelContact from './NavBarItemOmnichannelContact';
|
||||
import NavBarItemOmnichannelLivechatToggle from './NavBarItemOmnichannelLivechatToggle';
|
||||
import NavBarItemOmnichannelQueue from './NavBarItemOmnichannelQueue';
|
||||
|
||||
const NavBarOmnichannelGroup = () => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<NavBarGroup aria-label={t('Omnichannel')}>
|
||||
<NavBarItemOmnichannelQueue />
|
||||
<NavBarItemOmnichannelContact />
|
||||
<NavBarItemOmnichannelLivechatToggle />
|
||||
</NavBarGroup>
|
||||
);
|
||||
};
|
||||
|
||||
export default NavBarOmnichannelGroup;
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { Keys } from '@rocket.chat/icons';
|
||||
import { useCurrentRoutePath, useRouter } from '@rocket.chat/ui-contexts';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
export const useOmnichannelContactAction = () => {
|
||||
const { t } = useTranslation();
|
||||
const router = useRouter();
|
||||
const currentRoute = useCurrentRoutePath();
|
||||
|
||||
return {
|
||||
icon: 'address-book' as Keys,
|
||||
title: t('Contact_Center'),
|
||||
handleGoToContactCenter: () => router.navigate('/omnichannel-directory'),
|
||||
isPressed: currentRoute?.includes('/omnichannel-directory') || false,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,28 @@
|
||||
import { useStableCallback } from '@rocket.chat/fuselage-hooks';
|
||||
import type { Keys } from '@rocket.chat/icons';
|
||||
import { useEndpoint, useToastMessageDispatch } from '@rocket.chat/ui-contexts';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useOmnichannelAgentAvailable } from '../../../views/omnichannel/hooks/useOmnichannelAgentAvailable';
|
||||
|
||||
export const useOmnichannelLivechatToggle = () => {
|
||||
const { t } = useTranslation();
|
||||
const agentAvailable = useOmnichannelAgentAvailable();
|
||||
const changeAgentStatus = useEndpoint('POST', '/v1/livechat/agent.status');
|
||||
const dispatchToastMessage = useToastMessageDispatch();
|
||||
|
||||
const handleAvailableStatusChange = useStableCallback(async () => {
|
||||
try {
|
||||
await changeAgentStatus({});
|
||||
} catch (error: unknown) {
|
||||
dispatchToastMessage({ type: 'error', message: error });
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
title: agentAvailable ? t('Turn_off_answer_chats') : t('Turn_on_answer_chats'),
|
||||
isSuccess: agentAvailable,
|
||||
icon: (agentAvailable ? 'message' : 'message-disabled') as Keys,
|
||||
handleAvailableStatusChange,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { Keys } from '@rocket.chat/icons';
|
||||
import { useCurrentRoutePath, useRouter } from '@rocket.chat/ui-contexts';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useOmnichannelShowQueueLink } from '../../../views/omnichannel/hooks/useOmnichannelShowQueueLink';
|
||||
|
||||
export const useOmnichannelQueueAction = () => {
|
||||
const { t } = useTranslation();
|
||||
const showOmnichannelQueueLink = useOmnichannelShowQueueLink();
|
||||
|
||||
const router = useRouter();
|
||||
const currentRoute = useCurrentRoutePath();
|
||||
|
||||
return {
|
||||
isEnabled: showOmnichannelQueueLink,
|
||||
icon: 'queue' as Keys,
|
||||
title: t('Queue'),
|
||||
handleGoToQueue: () => router.navigate('/livechat-queue'),
|
||||
isPressed: currentRoute?.includes('/livechat-queue') || false,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1 @@
|
||||
export { default } from './NavBarOmnichannelGroup';
|
||||
@@ -0,0 +1,18 @@
|
||||
import { SidebarAction } from '@rocket.chat/fuselage';
|
||||
import { GenericMenu } from '@rocket.chat/ui-client';
|
||||
import type { HTMLAttributes } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useCreateNewMenu } from './hooks/useCreateNewMenu';
|
||||
|
||||
type CreateRoomProps = Omit<HTMLAttributes<HTMLElement>, 'is'>;
|
||||
|
||||
const NavBarItemCreateNew = (props: CreateRoomProps) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const sections = useCreateNewMenu();
|
||||
|
||||
return <GenericMenu icon='plus' sections={sections} title={t('Create_new')} is={SidebarAction} {...props} />;
|
||||
};
|
||||
|
||||
export default NavBarItemCreateNew;
|
||||
@@ -0,0 +1,28 @@
|
||||
import { NavBarItem } from '@rocket.chat/fuselage';
|
||||
import { useStableCallback } from '@rocket.chat/fuselage-hooks';
|
||||
import { useRouter, useCurrentRoutePath } from '@rocket.chat/ui-contexts';
|
||||
import type { HTMLAttributes } from 'react';
|
||||
|
||||
export type NavBarItemDirectoryPageProps = Omit<HTMLAttributes<HTMLElement>, 'is'>;
|
||||
|
||||
const NavBarItemDirectoryPage = (props: NavBarItemDirectoryPageProps) => {
|
||||
const router = useRouter();
|
||||
const handleDirectory = useStableCallback(() => {
|
||||
router.navigate('/directory');
|
||||
});
|
||||
const currentRoute = useCurrentRoutePath();
|
||||
|
||||
const directoryRoute = currentRoute?.includes('/directory');
|
||||
|
||||
return (
|
||||
<NavBarItem
|
||||
{...props}
|
||||
icon='notebook-hashtag'
|
||||
onClick={handleDirectory}
|
||||
aria-current={directoryRoute ? 'page' : undefined}
|
||||
pressed={directoryRoute}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default NavBarItemDirectoryPage;
|
||||
@@ -0,0 +1,25 @@
|
||||
import { NavBarItem } from '@rocket.chat/fuselage';
|
||||
import { useStableCallback } from '@rocket.chat/fuselage-hooks';
|
||||
import { useRouter, useLayout, useSetting, useCurrentRoutePath } from '@rocket.chat/ui-contexts';
|
||||
import type { HTMLAttributes } from 'react';
|
||||
|
||||
export type NavBarItemHomePageProps = Omit<HTMLAttributes<HTMLElement>, 'is'>;
|
||||
|
||||
const NavBarItemHomePage = (props: NavBarItemHomePageProps) => {
|
||||
const router = useRouter();
|
||||
const { sidebar } = useLayout();
|
||||
const showHome = useSetting('Layout_Show_Home_Button');
|
||||
const handleHome = useStableCallback(() => {
|
||||
sidebar.toggle();
|
||||
router.navigate('/home');
|
||||
});
|
||||
const currentRoute = useCurrentRoutePath();
|
||||
|
||||
const homeRoute = currentRoute?.includes('/home');
|
||||
|
||||
return showHome ? (
|
||||
<NavBarItem {...props} icon='home' onClick={handleHome} aria-current={homeRoute ? 'page' : undefined} pressed={homeRoute} />
|
||||
) : null;
|
||||
};
|
||||
|
||||
export default NavBarItemHomePage;
|
||||
@@ -0,0 +1,30 @@
|
||||
import { NavBarItem } from '@rocket.chat/fuselage';
|
||||
import { GenericMenu } from '@rocket.chat/ui-client';
|
||||
import { useCurrentRoutePath } from '@rocket.chat/ui-contexts';
|
||||
import type { HTMLAttributes } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useMarketPlaceMenu } from './hooks/useMarketPlaceMenu';
|
||||
|
||||
export type NavBarItemMarketPlaceMenuProps = Omit<HTMLAttributes<HTMLElement>, 'is'>;
|
||||
|
||||
const NavBarItemMarketPlaceMenu = (props: NavBarItemMarketPlaceMenuProps) => {
|
||||
const { t } = useTranslation();
|
||||
const sections = useMarketPlaceMenu();
|
||||
|
||||
const currentRoute = useCurrentRoutePath();
|
||||
|
||||
return (
|
||||
<GenericMenu
|
||||
sections={sections}
|
||||
title={t('Marketplace')}
|
||||
is={NavBarItem}
|
||||
placement='bottom-start'
|
||||
icon='store'
|
||||
pressed={currentRoute?.includes('/marketplace')}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default NavBarItemMarketPlaceMenu;
|
||||
@@ -0,0 +1,18 @@
|
||||
import { SidebarAction } from '@rocket.chat/fuselage';
|
||||
import { GenericMenu } from '@rocket.chat/ui-client';
|
||||
import type { HTMLAttributes } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useSortMenu } from './hooks/useSortMenu';
|
||||
|
||||
export type NavBarItemSortProps = Omit<HTMLAttributes<HTMLElement>, 'is'>;
|
||||
|
||||
const NavBarItemSort = (props: NavBarItemSortProps) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const sections = useSortMenu();
|
||||
|
||||
return <GenericMenu icon='sort' sections={sections} title={t('Display')} selectionMode='multiple' is={SidebarAction} {...props} />;
|
||||
};
|
||||
|
||||
export default NavBarItemSort;
|
||||
@@ -0,0 +1,36 @@
|
||||
import { NavBarGroup } from '@rocket.chat/fuselage';
|
||||
import { useLayout, usePermission } from '@rocket.chat/ui-contexts';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import NavBarItemCreateNew from './NavBarItemCreateNew';
|
||||
import NavBarItemDirectoryPage from './NavBarItemDirectoryPage';
|
||||
import NavBarItemHomePage from './NavBarItemHomePage';
|
||||
import NavBarItemMarketPlaceMenu from './NavBarItemMarketPlaceMenu';
|
||||
import NavBarItemSort from './NavBarItemSort';
|
||||
import NavBarPagesStackMenu from './NavBarPagesStackMenu';
|
||||
|
||||
const NavBarPagesGroup = () => {
|
||||
const { t } = useTranslation();
|
||||
const { isTablet, isMobile } = useLayout();
|
||||
|
||||
const hasManageAppsPermission = usePermission('manage-apps');
|
||||
const hasAccessMarketplacePermission = usePermission('access-marketplace');
|
||||
const showMarketplace = hasAccessMarketplacePermission || hasManageAppsPermission;
|
||||
|
||||
return (
|
||||
<NavBarGroup aria-label={t('Pages_and_actions')}>
|
||||
{isTablet && <NavBarPagesStackMenu />}
|
||||
{!isTablet && (
|
||||
<>
|
||||
<NavBarItemHomePage title={t('Home')} />
|
||||
<NavBarItemDirectoryPage title={t('Directory')} />
|
||||
</>
|
||||
)}
|
||||
{showMarketplace && !isMobile && <NavBarItemMarketPlaceMenu />}
|
||||
{!isMobile && <NavBarItemSort />}
|
||||
<NavBarItemCreateNew />
|
||||
</NavBarGroup>
|
||||
);
|
||||
};
|
||||
|
||||
export default NavBarPagesGroup;
|
||||
@@ -0,0 +1,46 @@
|
||||
import { NavBarItem } from '@rocket.chat/fuselage';
|
||||
import { useStableCallback } from '@rocket.chat/fuselage-hooks';
|
||||
import type { GenericMenuItemProps } from '@rocket.chat/ui-client';
|
||||
import { GenericMenu } from '@rocket.chat/ui-client';
|
||||
import { useCurrentRoutePath, useLayout, useRouter, useSetting } from '@rocket.chat/ui-contexts';
|
||||
import type { HTMLAttributes } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
export type NavBarPagesStackMenuProps = Omit<HTMLAttributes<HTMLElement>, 'is'>;
|
||||
|
||||
const NavBarPagesStackMenu = (props: NavBarPagesStackMenuProps) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const showHome = useSetting('Layout_Show_Home_Button');
|
||||
const { sidebar } = useLayout();
|
||||
const router = useRouter();
|
||||
|
||||
const handleGoToHome = useStableCallback(() => {
|
||||
sidebar.toggle();
|
||||
router.navigate('/home');
|
||||
});
|
||||
|
||||
const currentRoute = useCurrentRoutePath();
|
||||
const pressed = currentRoute?.includes('/directory') || currentRoute?.includes('/home');
|
||||
|
||||
const items = [
|
||||
showHome && {
|
||||
id: 'home',
|
||||
icon: 'home',
|
||||
content: t('Home'),
|
||||
onClick: handleGoToHome,
|
||||
},
|
||||
{
|
||||
id: 'directory',
|
||||
icon: 'notebook-hashtag',
|
||||
content: t('Directory'),
|
||||
onClick: () => router.navigate('/directory'),
|
||||
},
|
||||
].filter(Boolean) as GenericMenuItemProps[];
|
||||
|
||||
return (
|
||||
<GenericMenu items={items} title={t('Pages')} is={NavBarItem} placement='bottom-start' icon='stack' pressed={pressed} {...props} />
|
||||
);
|
||||
};
|
||||
|
||||
export default NavBarPagesStackMenu;
|
||||
@@ -0,0 +1,295 @@
|
||||
import { mockAppRoot } from '@rocket.chat/mock-providers';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
|
||||
import CreateChannelModal from './CreateChannelModal';
|
||||
import { createFakeLicenseInfo } from '../../../../tests/mocks/data';
|
||||
|
||||
jest.mock('../../../lib/rooms/roomCoordinator', () => ({}));
|
||||
|
||||
describe('CreateChannelModal', () => {
|
||||
describe('Encryption', () => {
|
||||
it('should render with encryption option disabled and set to off when E2E_Enable=false and E2E_Enabled_Default_PrivateRooms=false', async () => {
|
||||
render(<CreateChannelModal onClose={() => null} />, {
|
||||
wrapper: mockAppRoot().withSetting('E2E_Enable', false).withSetting('E2E_Enabled_Default_PrivateRooms', false).build(),
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByText('Advanced_settings'));
|
||||
|
||||
const encrypted = screen.getByLabelText('Encrypted') as HTMLInputElement;
|
||||
expect(encrypted).toBeInTheDocument();
|
||||
expect(encrypted).not.toBeChecked();
|
||||
expect(encrypted).toBeDisabled();
|
||||
});
|
||||
|
||||
it('should render with encryption option enabled and set to off when E2E_Enable=true and E2E_Enabled_Default_PrivateRooms=false', async () => {
|
||||
render(<CreateChannelModal onClose={() => null} />, {
|
||||
wrapper: mockAppRoot().withSetting('E2E_Enable', true).withSetting('E2E_Enabled_Default_PrivateRooms', false).build(),
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByText('Advanced_settings'));
|
||||
|
||||
const encrypted = screen.getByLabelText('Encrypted') as HTMLInputElement;
|
||||
expect(encrypted).toBeInTheDocument();
|
||||
expect(encrypted).not.toBeChecked();
|
||||
expect(encrypted).toBeEnabled();
|
||||
});
|
||||
|
||||
it('should render with encryption option disabled and set to off when E2E_Enable=false and E2E_Enabled_Default_PrivateRooms=true', async () => {
|
||||
render(<CreateChannelModal onClose={() => null} />, {
|
||||
wrapper: mockAppRoot().withSetting('E2E_Enable', false).withSetting('E2E_Enabled_Default_PrivateRooms', true).build(),
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByText('Advanced_settings'));
|
||||
|
||||
const encrypted = screen.getByLabelText('Encrypted') as HTMLInputElement;
|
||||
expect(encrypted).toBeInTheDocument();
|
||||
|
||||
expect(encrypted).not.toBeChecked();
|
||||
expect(encrypted).toBeDisabled();
|
||||
});
|
||||
|
||||
it('should render with encryption option enabled and set to on when E2E_Enable=true and E2E_Enabled_Default_PrivateRooms=True', async () => {
|
||||
render(<CreateChannelModal onClose={() => null} />, {
|
||||
wrapper: mockAppRoot().withSetting('E2E_Enable', true).withSetting('E2E_Enabled_Default_PrivateRooms', true).build(),
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByText('Advanced_settings'));
|
||||
|
||||
const encrypted = screen.getByLabelText('Encrypted') as HTMLInputElement;
|
||||
expect(encrypted).toBeChecked();
|
||||
expect(encrypted).toBeEnabled();
|
||||
});
|
||||
|
||||
it('when Private goes ON → OFF: forces Encrypted OFF and disables it (E2E_Enable=true, E2E_Enabled_Default_PrivateRooms=true)', async () => {
|
||||
render(<CreateChannelModal onClose={() => null} />, {
|
||||
wrapper: mockAppRoot().withSetting('E2E_Enable', true).withSetting('E2E_Enabled_Default_PrivateRooms', true).build(),
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByText('Advanced_settings'));
|
||||
|
||||
const encrypted = screen.getByLabelText('Encrypted') as HTMLInputElement;
|
||||
const priv = screen.getByLabelText('Private') as HTMLInputElement;
|
||||
|
||||
// initial: private=true, encrypted ON and enabled
|
||||
expect(priv).toBeChecked();
|
||||
expect(encrypted).toBeChecked();
|
||||
expect(encrypted).toBeEnabled();
|
||||
|
||||
// Private ON -> OFF: encrypted must become OFF and disabled
|
||||
await userEvent.click(priv);
|
||||
expect(priv).not.toBeChecked();
|
||||
expect(encrypted).not.toBeChecked();
|
||||
expect(encrypted).toBeDisabled();
|
||||
});
|
||||
|
||||
it('when Private goes OFF → ON: keeps Encrypted OFF but re-enables it (E2E_Enable=true, E2E_Enabled_Default_PrivateRooms=true)', async () => {
|
||||
render(<CreateChannelModal onClose={() => null} />, {
|
||||
wrapper: mockAppRoot().withSetting('E2E_Enable', true).withSetting('E2E_Enabled_Default_PrivateRooms', true).build(),
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByText('Advanced_settings'));
|
||||
|
||||
const encrypted = screen.getByLabelText('Encrypted') as HTMLInputElement;
|
||||
const priv = screen.getByLabelText('Private') as HTMLInputElement;
|
||||
|
||||
// turn private OFF to simulate user path from non-private
|
||||
await userEvent.click(priv);
|
||||
expect(priv).not.toBeChecked();
|
||||
expect(encrypted).not.toBeChecked();
|
||||
expect(encrypted).toBeDisabled();
|
||||
|
||||
// turn private back ON -> encrypted should remain OFF but become enabled
|
||||
await userEvent.click(priv);
|
||||
expect(priv).toBeChecked();
|
||||
expect(encrypted).not.toBeChecked();
|
||||
expect(encrypted).toBeEnabled();
|
||||
});
|
||||
|
||||
it('private room: toggling Broadcast on/off does not change or disable Encrypted', async () => {
|
||||
render(<CreateChannelModal onClose={() => null} />, {
|
||||
wrapper: mockAppRoot().withSetting('E2E_Enable', true).withSetting('E2E_Enabled_Default_PrivateRooms', true).build(),
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByText('Advanced_settings'));
|
||||
|
||||
const encrypted = screen.getByLabelText('Encrypted') as HTMLInputElement;
|
||||
const broadcast = screen.getByLabelText('Broadcast') as HTMLInputElement;
|
||||
const priv = screen.getByLabelText('Private') as HTMLInputElement;
|
||||
|
||||
expect(priv).toBeChecked();
|
||||
expect(encrypted).toBeChecked();
|
||||
expect(encrypted).toBeEnabled();
|
||||
expect(broadcast).not.toBeChecked();
|
||||
|
||||
// Broadcast: OFF -> ON (Encrypted unchanged + enabled)
|
||||
await userEvent.click(broadcast);
|
||||
expect(broadcast).toBeChecked();
|
||||
expect(encrypted).toBeChecked();
|
||||
expect(encrypted).toBeEnabled();
|
||||
|
||||
// Broadcast: ON -> OFF (Encrypted unchanged + enabled)
|
||||
await userEvent.click(broadcast);
|
||||
expect(broadcast).not.toBeChecked();
|
||||
expect(encrypted).toBeChecked();
|
||||
expect(encrypted).toBeEnabled();
|
||||
|
||||
// User can still toggle Encrypted freely while Broadcast is OFF
|
||||
await userEvent.click(encrypted);
|
||||
expect(encrypted).not.toBeChecked();
|
||||
|
||||
// User can still toggle Encrypted freely while Broadcast is ON
|
||||
await userEvent.click(broadcast);
|
||||
expect(broadcast).toBeChecked();
|
||||
expect(encrypted).not.toBeChecked();
|
||||
expect(encrypted).toBeEnabled();
|
||||
});
|
||||
|
||||
it('non-private room: Encrypted remains OFF and disabled regardless of Broadcast state', async () => {
|
||||
render(<CreateChannelModal onClose={() => null} />, {
|
||||
wrapper: mockAppRoot().withSetting('E2E_Enable', true).withSetting('E2E_Enabled_Default_PrivateRooms', true).build(),
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByText('Advanced_settings'));
|
||||
|
||||
const encrypted = screen.getByLabelText('Encrypted') as HTMLInputElement;
|
||||
const broadcast = screen.getByLabelText('Broadcast') as HTMLInputElement;
|
||||
const priv = screen.getByLabelText('Private') as HTMLInputElement;
|
||||
|
||||
// Switch to non-private
|
||||
await userEvent.click(priv);
|
||||
expect(priv).not.toBeChecked();
|
||||
|
||||
// Encrypted must be OFF + disabled (non-private cannot be encrypted)
|
||||
expect(encrypted).not.toBeChecked();
|
||||
expect(encrypted).toBeDisabled();
|
||||
|
||||
// Broadcast: OFF -> ON (Encrypted stays OFF + disabled)
|
||||
await userEvent.click(broadcast);
|
||||
expect(broadcast).toBeChecked();
|
||||
expect(encrypted).not.toBeChecked();
|
||||
expect(encrypted).toBeDisabled();
|
||||
|
||||
// Broadcast: ON -> OFF (Encrypted still OFF + disabled)
|
||||
await userEvent.click(broadcast);
|
||||
expect(broadcast).not.toBeChecked();
|
||||
expect(encrypted).not.toBeChecked();
|
||||
expect(encrypted).toBeDisabled();
|
||||
});
|
||||
|
||||
it('should render a private channel with encryption checked and disabled for changes when private room encryption is forced', async () => {
|
||||
render(<CreateChannelModal onClose={() => null} />, {
|
||||
wrapper: mockAppRoot().withSetting('E2E_Enable', true).withSetting('E2E_Force_Encryption_For_Private_Rooms', true).build(),
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByText('Advanced_settings'));
|
||||
|
||||
const encrypted = screen.getByLabelText('Encrypted') as HTMLInputElement;
|
||||
const priv = screen.getByLabelText('Private') as HTMLInputElement;
|
||||
|
||||
// private by default: encrypted is forced ON and cannot be changed
|
||||
expect(priv).toBeChecked();
|
||||
expect(encrypted).toBeChecked();
|
||||
expect(encrypted).toBeDisabled();
|
||||
|
||||
// Private ON -> OFF: encrypted turns OFF and stays disabled (public rooms cannot be encrypted)
|
||||
await userEvent.click(priv);
|
||||
expect(priv).not.toBeChecked();
|
||||
expect(encrypted).not.toBeChecked();
|
||||
expect(encrypted).toBeDisabled();
|
||||
|
||||
// Private OFF -> ON: encryption is forced back ON and remains disabled
|
||||
await userEvent.click(priv);
|
||||
expect(priv).toBeChecked();
|
||||
expect(encrypted).toBeChecked();
|
||||
expect(encrypted).toBeDisabled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Federation', () => {
|
||||
it('should render with federated option disabled when user lacks license module', async () => {
|
||||
render(<CreateChannelModal onClose={() => null} />, {
|
||||
wrapper: mockAppRoot().build(),
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByText('Advanced_settings'));
|
||||
const federated = screen.getByLabelText('Federation_Matrix_Federated');
|
||||
expect(federated).toHaveAccessibleDescription('error-this-is-a-premium-feature');
|
||||
expect(federated).toBeInTheDocument();
|
||||
expect(federated).not.toBeChecked();
|
||||
expect(federated).toBeDisabled();
|
||||
});
|
||||
|
||||
it('should render with federated option disabled if the feature is disabled for workspaces', async () => {
|
||||
render(<CreateChannelModal onClose={() => null} />, {
|
||||
wrapper: mockAppRoot()
|
||||
.withJohnDoe()
|
||||
.withSetting('Federation_Matrix_enabled', false)
|
||||
.withEndpoint(
|
||||
'GET',
|
||||
'/v1/licenses.info',
|
||||
jest.fn().mockImplementation(() => ({
|
||||
license: createFakeLicenseInfo({ activeModules: ['federation'] }),
|
||||
})),
|
||||
)
|
||||
.build(),
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByText('Advanced_settings'));
|
||||
const federated = screen.getByLabelText('Federation_Matrix_Federated');
|
||||
|
||||
expect(federated).toBeInTheDocument();
|
||||
expect(federated).not.toBeChecked();
|
||||
expect(federated).toBeDisabled();
|
||||
expect(federated).toHaveAccessibleDescription('Federation_Matrix_Federated_Description_disabled');
|
||||
});
|
||||
|
||||
it('should render with federated option disabled when user lacks permission', async () => {
|
||||
render(<CreateChannelModal onClose={() => null} />, {
|
||||
wrapper: mockAppRoot()
|
||||
.withJohnDoe()
|
||||
.withSetting('Federation_Matrix_enabled', true)
|
||||
.withEndpoint(
|
||||
'GET',
|
||||
'/v1/licenses.info',
|
||||
jest.fn().mockImplementation(() => ({
|
||||
license: createFakeLicenseInfo({ activeModules: ['federation'] }),
|
||||
})),
|
||||
)
|
||||
.build(),
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByText('Advanced_settings'));
|
||||
const federated = screen.getByLabelText('Federation_Matrix_Federated');
|
||||
|
||||
expect(federated).toBeInTheDocument();
|
||||
expect(federated).not.toBeChecked();
|
||||
expect(federated).toBeDisabled();
|
||||
expect(federated).toHaveAccessibleDescription('error-not-authorized-federation');
|
||||
});
|
||||
|
||||
it('should render with federated option enabled when user has license module, permission and feature enabled', async () => {
|
||||
render(<CreateChannelModal onClose={() => null} />, {
|
||||
wrapper: mockAppRoot()
|
||||
.withJohnDoe()
|
||||
.withSetting('Federation_Matrix_enabled', true)
|
||||
.withPermission('access-federation')
|
||||
.withEndpoint(
|
||||
'GET',
|
||||
'/v1/licenses.info',
|
||||
jest.fn().mockImplementation(() => ({
|
||||
license: createFakeLicenseInfo({ activeModules: ['federation'] }),
|
||||
})),
|
||||
)
|
||||
.build(),
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByText('Advanced_settings'));
|
||||
const federated = screen.getByLabelText('Federation_Matrix_Federated');
|
||||
expect(federated).toBeInTheDocument();
|
||||
expect(federated).not.toBeChecked();
|
||||
expect(federated).not.toBeDisabled();
|
||||
expect(federated).toHaveAccessibleDescription('Federation_Matrix_Federated_Description');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,351 @@
|
||||
import type { IRoom } from '@rocket.chat/core-typings';
|
||||
import {
|
||||
Box,
|
||||
Modal,
|
||||
Button,
|
||||
Icon,
|
||||
Accordion,
|
||||
AccordionItem,
|
||||
ModalHeader,
|
||||
ModalTitle,
|
||||
ModalClose,
|
||||
ModalContent,
|
||||
ModalFooter,
|
||||
ModalFooterControllers,
|
||||
} from '@rocket.chat/fuselage';
|
||||
import { TextInput, Field, ToggleSwitch, FieldGroup, FieldLabel, FieldRow, FieldError, FieldHint } from '@rocket.chat/fuselage-forms';
|
||||
import type { TranslationKey } from '@rocket.chat/ui-contexts';
|
||||
import {
|
||||
useSetting,
|
||||
useTranslation,
|
||||
useEndpoint,
|
||||
useToastMessageDispatch,
|
||||
usePermissionWithScopedRoles,
|
||||
usePermission,
|
||||
} from '@rocket.chat/ui-contexts';
|
||||
import type { ComponentProps } from 'react';
|
||||
import { useId, useEffect, useMemo } from 'react';
|
||||
import { useForm, Controller } from 'react-hook-form';
|
||||
|
||||
import { useEncryptedRoomDescription } from './useEncryptedRoomDescription';
|
||||
import UserAutoCompleteMultiple from '../../../components/UserAutoCompleteMultiple';
|
||||
import { useCreateChannelTypePermission } from '../../../hooks/useCreateChannelTypePermission';
|
||||
import { useHasLicenseModule } from '../../../hooks/useHasLicenseModule';
|
||||
import { useIsFederationEnabled } from '../../../hooks/useIsFederationEnabled';
|
||||
import { useGoToRoom } from '../../../views/room/hooks/useGoToRoom';
|
||||
|
||||
export type CreateChannelModalProps = {
|
||||
teamId?: string;
|
||||
mainRoom?: IRoom;
|
||||
onClose: () => void;
|
||||
reload?: () => void;
|
||||
onSuccess?: (rid: string) => void | Promise<void>;
|
||||
};
|
||||
|
||||
type CreateChannelModalPayload = {
|
||||
name: string;
|
||||
isPrivate: boolean;
|
||||
topic?: string;
|
||||
members: string[];
|
||||
readOnly: boolean;
|
||||
encrypted: boolean;
|
||||
broadcast: boolean;
|
||||
federated: boolean;
|
||||
};
|
||||
|
||||
const getFederationHintKey = (federationModule: boolean, featureToggle: boolean, federationAccessPermission: boolean): TranslationKey => {
|
||||
if (!federationModule) {
|
||||
return 'error-this-is-a-premium-feature';
|
||||
}
|
||||
|
||||
if (!featureToggle) {
|
||||
return 'Federation_Matrix_Federated_Description_disabled';
|
||||
}
|
||||
|
||||
if (!federationAccessPermission) {
|
||||
return 'error-not-authorized-federation';
|
||||
}
|
||||
|
||||
return 'Federation_Matrix_Federated_Description';
|
||||
};
|
||||
|
||||
const hasExternalMembers = (members: string[]): boolean => members.some((member) => member.startsWith('@'));
|
||||
|
||||
const CreateChannelModal = ({ teamId = '', mainRoom, onClose, reload, onSuccess }: CreateChannelModalProps) => {
|
||||
const t = useTranslation();
|
||||
const canSetReadOnly = usePermissionWithScopedRoles('set-readonly', ['owner']);
|
||||
const e2eEnabled = useSetting('E2E_Enable');
|
||||
const namesValidation = useSetting('UTF8_Channel_Names_Validation');
|
||||
const allowSpecialNames = useSetting('UI_Allow_room_names_with_special_chars');
|
||||
const e2eEnabledForPrivateByDefault = useSetting('E2E_Enabled_Default_PrivateRooms') && e2eEnabled;
|
||||
const e2eEnforcedForPrivate = Boolean(useSetting('E2E_Force_Encryption_For_Private_Rooms')) && Boolean(e2eEnabled);
|
||||
|
||||
const getEncryptedHint = useEncryptedRoomDescription('channel');
|
||||
|
||||
const channelNameRegex = useMemo(() => new RegExp(`^${namesValidation}$`), [namesValidation]);
|
||||
|
||||
const federationEnabled = useIsFederationEnabled();
|
||||
const { data: federationModule = false } = useHasLicenseModule('federation');
|
||||
const federationAccessPermission = usePermission('access-federation');
|
||||
const canUseFederation = federationModule && federationEnabled && federationAccessPermission;
|
||||
const federationFieldHint = getFederationHintKey(federationModule, federationEnabled, federationAccessPermission);
|
||||
|
||||
const channelNameExists = useEndpoint('GET', '/v1/rooms.nameExists');
|
||||
const createChannel = useEndpoint('POST', '/v1/channels.create');
|
||||
const createPrivateChannel = useEndpoint('POST', '/v1/groups.create');
|
||||
|
||||
const dispatchToastMessage = useToastMessageDispatch();
|
||||
|
||||
const canOnlyCreateOneType = useCreateChannelTypePermission(mainRoom?._id);
|
||||
|
||||
const {
|
||||
formState: { errors },
|
||||
handleSubmit,
|
||||
control,
|
||||
setValue,
|
||||
watch,
|
||||
} = useForm({
|
||||
defaultValues: {
|
||||
members: [],
|
||||
name: '',
|
||||
topic: '',
|
||||
isPrivate: canOnlyCreateOneType ? canOnlyCreateOneType === 'p' : true,
|
||||
readOnly: false,
|
||||
encrypted: Boolean(e2eEnforcedForPrivate || e2eEnabledForPrivateByDefault),
|
||||
broadcast: false,
|
||||
federated: false,
|
||||
},
|
||||
});
|
||||
|
||||
const { isPrivate, broadcast, readOnly, federated, encrypted } = watch();
|
||||
|
||||
useEffect(() => {
|
||||
if (federated) {
|
||||
// if room is federated, it cannot be encrypted or broadcast or readOnly
|
||||
setValue('encrypted', false);
|
||||
setValue('broadcast', false);
|
||||
setValue('readOnly', false);
|
||||
}
|
||||
}, [federated, setValue]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isPrivate) {
|
||||
setValue('encrypted', false);
|
||||
}
|
||||
}, [isPrivate, setValue]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isPrivate && e2eEnforcedForPrivate && !federated) {
|
||||
setValue('encrypted', true);
|
||||
}
|
||||
}, [isPrivate, e2eEnforcedForPrivate, federated, setValue]);
|
||||
|
||||
useEffect(() => {
|
||||
setValue('readOnly', broadcast);
|
||||
}, [broadcast, setValue]);
|
||||
|
||||
const validateChannelName = async (name: string): Promise<string | undefined> => {
|
||||
if (!name) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!allowSpecialNames && !channelNameRegex.test(name)) {
|
||||
return t('Name_cannot_have_special_characters');
|
||||
}
|
||||
|
||||
const { exists } = await channelNameExists({ roomName: name });
|
||||
if (exists) {
|
||||
return t('Channel_already_exist', { channelName: name });
|
||||
}
|
||||
};
|
||||
|
||||
const goToRoom = useGoToRoom();
|
||||
|
||||
const handleCreateChannel = async ({ name, members, readOnly, topic, broadcast, encrypted, federated }: CreateChannelModalPayload) => {
|
||||
let roomData;
|
||||
const params = {
|
||||
name,
|
||||
members,
|
||||
readOnly,
|
||||
extraData: {
|
||||
topic,
|
||||
broadcast,
|
||||
encrypted,
|
||||
...(federated && { federated }),
|
||||
...(teamId && { teamId }),
|
||||
},
|
||||
};
|
||||
|
||||
let rid: string;
|
||||
try {
|
||||
if (isPrivate) {
|
||||
roomData = await createPrivateChannel(params);
|
||||
rid = roomData.group._id;
|
||||
if (!teamId) goToRoom(roomData.group._id);
|
||||
} else {
|
||||
roomData = await createChannel(params);
|
||||
rid = roomData.channel._id;
|
||||
if (!teamId) goToRoom(roomData.channel._id);
|
||||
}
|
||||
|
||||
dispatchToastMessage({ type: 'success', message: t('Room_has_been_created') });
|
||||
void onSuccess?.(rid);
|
||||
reload?.();
|
||||
onClose();
|
||||
} catch (error) {
|
||||
dispatchToastMessage({ type: 'error', message: error });
|
||||
}
|
||||
};
|
||||
|
||||
const e2eDisabled = useMemo<boolean>(
|
||||
() => !isPrivate || Boolean(!e2eEnabled) || federated || (e2eEnforcedForPrivate && isPrivate),
|
||||
[e2eEnabled, federated, isPrivate, e2eEnforcedForPrivate],
|
||||
);
|
||||
|
||||
const createChannelFormId = useId();
|
||||
|
||||
return (
|
||||
<Modal
|
||||
aria-labelledby={`${createChannelFormId}-title`}
|
||||
wrapperFunction={(props: ComponentProps<typeof Box>) => (
|
||||
<Box is='form' id={createChannelFormId} onSubmit={handleSubmit(handleCreateChannel)} {...props} />
|
||||
)}
|
||||
>
|
||||
<ModalHeader>
|
||||
<ModalTitle id={`${createChannelFormId}-title`}>{t('Create_channel')}</ModalTitle>
|
||||
<ModalClose tabIndex={-1} title={t('Close')} onClick={onClose} />
|
||||
</ModalHeader>
|
||||
<ModalContent marginBlockEnd={2}>
|
||||
<FieldGroup marginBlockEnd={24}>
|
||||
<Field>
|
||||
<FieldLabel required>{t('Name')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
control={control}
|
||||
name='name'
|
||||
rules={{
|
||||
required: t('Required_field', { field: t('Name') }),
|
||||
validate: (value) => validateChannelName(value),
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<TextInput
|
||||
{...field}
|
||||
error={errors.name?.message}
|
||||
endAddon={<Icon name={isPrivate ? 'hashtag-lock' : 'hashtag'} size='x20' />}
|
||||
aria-required='true'
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
{errors.name && <FieldError>{errors.name.message}</FieldError>}
|
||||
{!allowSpecialNames && <FieldHint>{t('No_spaces_or_special_characters')}</FieldHint>}
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel>{t('Topic')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller control={control} name='topic' render={({ field }) => <TextInput {...field} />} />
|
||||
</FieldRow>
|
||||
<FieldHint>{t('Displayed_next_to_name')}</FieldHint>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel>{t('Members')}</FieldLabel>
|
||||
<Controller
|
||||
control={control}
|
||||
name='members'
|
||||
rules={{
|
||||
validate: (members) =>
|
||||
!federated && hasExternalMembers(members) ? t('You_cannot_add_external_users_to_non_federated_room') : true,
|
||||
}}
|
||||
render={({ field }) => <UserAutoCompleteMultiple {...field} federated={federated} placeholder={t('Add_people')} />}
|
||||
/>
|
||||
{errors.members && <FieldError>{errors.members.message}</FieldError>}
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldRow>
|
||||
<FieldLabel>{t('Private')}</FieldLabel>
|
||||
<Controller
|
||||
control={control}
|
||||
name='isPrivate'
|
||||
render={({ field: { value, ...field } }) => (
|
||||
<ToggleSwitch
|
||||
{...field}
|
||||
checked={canOnlyCreateOneType ? canOnlyCreateOneType === 'p' : value}
|
||||
disabled={!!canOnlyCreateOneType}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
<FieldHint>{isPrivate ? t('People_can_only_join_by_being_invited') : t('Anyone_can_access')}</FieldHint>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
<Accordion>
|
||||
<AccordionItem title={t('Advanced_settings')}>
|
||||
<FieldGroup>
|
||||
<Box is='h5' fontScale='h5' color='titles-labels'>
|
||||
{t('Security_and_permissions')}
|
||||
</Box>
|
||||
<Field>
|
||||
<FieldRow>
|
||||
<FieldLabel>{t('Federation_Matrix_Federated')}</FieldLabel>
|
||||
<Controller
|
||||
control={control}
|
||||
name='federated'
|
||||
render={({ field: { value, ...field } }) => <ToggleSwitch {...field} checked={value} disabled={!canUseFederation} />}
|
||||
/>
|
||||
</FieldRow>
|
||||
<FieldHint>{t(federationFieldHint)}</FieldHint>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldRow>
|
||||
<FieldLabel>{t('Encrypted')}</FieldLabel>
|
||||
<Controller
|
||||
control={control}
|
||||
name='encrypted'
|
||||
render={({ field: { value, ...field } }) => <ToggleSwitch {...field} checked={value} disabled={e2eDisabled} />}
|
||||
/>
|
||||
</FieldRow>
|
||||
<FieldHint>{getEncryptedHint({ isPrivate, encrypted })}</FieldHint>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldRow>
|
||||
<FieldLabel>{t('Read_only')}</FieldLabel>
|
||||
<Controller
|
||||
control={control}
|
||||
name='readOnly'
|
||||
render={({ field: { value, ...field } }) => (
|
||||
<ToggleSwitch {...field} checked={value} disabled={!canSetReadOnly || broadcast || federated} />
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
<FieldHint>
|
||||
{readOnly ? t('Read_only_field_hint_enabled', { roomType: 'channel' }) : t('Anyone_can_send_new_messages')}
|
||||
</FieldHint>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldRow>
|
||||
<FieldLabel>{t('Broadcast')}</FieldLabel>
|
||||
<Controller
|
||||
control={control}
|
||||
name='broadcast'
|
||||
render={({ field: { value, ...field } }) => <ToggleSwitch {...field} checked={value} disabled={!!federated} />}
|
||||
/>
|
||||
</FieldRow>
|
||||
{broadcast && <FieldHint>{t('Broadcast_hint_enabled', { roomType: 'channel' })}</FieldHint>}
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
</ModalContent>
|
||||
<ModalFooter>
|
||||
<ModalFooterControllers>
|
||||
<Button onClick={onClose}>{t('Cancel')}</Button>
|
||||
<Button type='submit' primary>
|
||||
{t('Create')}
|
||||
</Button>
|
||||
</ModalFooterControllers>
|
||||
</ModalFooter>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export default CreateChannelModal;
|
||||
@@ -0,0 +1,112 @@
|
||||
import type { IUser } from '@rocket.chat/core-typings';
|
||||
import {
|
||||
Box,
|
||||
Modal,
|
||||
Button,
|
||||
ModalHeader,
|
||||
ModalTitle,
|
||||
ModalClose,
|
||||
ModalContent,
|
||||
ModalFooter,
|
||||
ModalFooterControllers,
|
||||
} from '@rocket.chat/fuselage';
|
||||
import { FieldGroup, Field, FieldLabel, FieldRow, FieldError, FieldHint } from '@rocket.chat/fuselage-forms';
|
||||
import { useTranslation, useEndpoint, useToastMessageDispatch, useSetting } from '@rocket.chat/ui-contexts';
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
import { useId, memo } from 'react';
|
||||
import { useForm, Controller } from 'react-hook-form';
|
||||
|
||||
import UserAutoCompleteMultiple from '../../../components/UserAutoCompleteMultiple';
|
||||
import { useGoToRoom } from '../../../views/room/hooks/useGoToRoom';
|
||||
|
||||
export type CreateDirectMessageProps = { onClose: () => void; onSuccess?: (rid: string) => void | Promise<void> };
|
||||
|
||||
const CreateDirectMessage = ({ onClose, onSuccess }: CreateDirectMessageProps) => {
|
||||
const t = useTranslation();
|
||||
const directMaxUsers = useSetting('DirectMesssage_maxUsers', 1);
|
||||
const createDMFormId = useId();
|
||||
const dispatchToastMessage = useToastMessageDispatch();
|
||||
|
||||
const createDirectAction = useEndpoint('POST', '/v1/dm.create');
|
||||
|
||||
const {
|
||||
control,
|
||||
handleSubmit,
|
||||
formState: { isSubmitting, isValidating, errors },
|
||||
} = useForm({ defaultValues: { users: [] } });
|
||||
|
||||
const goToRoom = useGoToRoom();
|
||||
|
||||
const mutateDirectMessage = useMutation({
|
||||
mutationFn: createDirectAction,
|
||||
onSuccess: ({ room }) => {
|
||||
goToRoom(room.rid);
|
||||
void onSuccess?.(room.rid);
|
||||
},
|
||||
onError: (error) => {
|
||||
dispatchToastMessage({ type: 'error', message: error });
|
||||
},
|
||||
onSettled: () => {
|
||||
onClose();
|
||||
},
|
||||
});
|
||||
|
||||
const handleCreate = async ({ users }: { users: IUser['username'][] }) => {
|
||||
return mutateDirectMessage.mutateAsync({ usernames: users.join(',') });
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
aria-labelledby={`${createDMFormId}-title`}
|
||||
wrapperFunction={(props) => <Box is='form' onSubmit={handleSubmit(handleCreate)} {...props} />}
|
||||
>
|
||||
<ModalHeader>
|
||||
<ModalTitle id={`${createDMFormId}-title`}>{t('Create_direct_message')}</ModalTitle>
|
||||
<ModalClose tabIndex={-1} onClick={onClose} />
|
||||
</ModalHeader>
|
||||
<ModalContent marginBlockEnd={2}>
|
||||
<FieldGroup>
|
||||
<Field>
|
||||
<FieldLabel>{t('Direct_message_creation_description')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
name='users'
|
||||
rules={{
|
||||
required: t('Direct_message_creation_error'),
|
||||
validate: (users) =>
|
||||
users.length + 1 > directMaxUsers
|
||||
? t('error-direct-message-max-user-exceeded', { maxUsers: directMaxUsers })
|
||||
: undefined,
|
||||
}}
|
||||
control={control}
|
||||
render={({ field: { name, onChange, value, onBlur } }) => (
|
||||
<UserAutoCompleteMultiple
|
||||
name={name}
|
||||
onChange={onChange}
|
||||
value={value}
|
||||
onBlur={onBlur}
|
||||
federated
|
||||
aria-required='true'
|
||||
error={errors.users?.message}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
{errors.users && <FieldError>{errors.users.message}</FieldError>}
|
||||
<FieldHint>{t('Direct_message_creation_description_hint')}</FieldHint>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
</ModalContent>
|
||||
<ModalFooter>
|
||||
<ModalFooterControllers>
|
||||
<Button onClick={onClose}>{t('Cancel')}</Button>
|
||||
<Button loading={isSubmitting || isValidating} type='submit' primary>
|
||||
{t('Create')}
|
||||
</Button>
|
||||
</ModalFooterControllers>
|
||||
</ModalFooter>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export default memo(CreateDirectMessage);
|
||||
@@ -0,0 +1,273 @@
|
||||
import { mockAppRoot } from '@rocket.chat/mock-providers';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
|
||||
import CreateTeamModal from './CreateTeamModal';
|
||||
|
||||
jest.mock('../../../lib/rooms/roomCoordinator', () => ({}));
|
||||
|
||||
describe('CreateTeamModal', () => {
|
||||
it('should render with encryption option disabled and set to off when E2E_Enable=false and E2E_Enabled_Default_PrivateRooms=false', async () => {
|
||||
render(<CreateTeamModal onClose={() => null} />, {
|
||||
wrapper: mockAppRoot().withSetting('E2E_Enable', false).withSetting('E2E_Enabled_Default_PrivateRooms', false).build(),
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByText('Advanced_settings'));
|
||||
|
||||
const encrypted = screen.getByLabelText('Teams_New_Encrypted_Label') as HTMLInputElement;
|
||||
expect(encrypted).toBeInTheDocument();
|
||||
expect(encrypted).not.toBeChecked();
|
||||
expect(encrypted).toBeDisabled();
|
||||
});
|
||||
|
||||
it('should render with encryption option enabled and set to off when E2E_Enable=true and E2E_Enabled_Default_PrivateRooms=false', async () => {
|
||||
render(<CreateTeamModal onClose={() => null} />, {
|
||||
wrapper: mockAppRoot().withSetting('E2E_Enable', true).withSetting('E2E_Enabled_Default_PrivateRooms', false).build(),
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByText('Advanced_settings'));
|
||||
|
||||
const encrypted = screen.getByLabelText('Teams_New_Encrypted_Label') as HTMLInputElement;
|
||||
expect(encrypted).toBeInTheDocument();
|
||||
expect(encrypted).not.toBeChecked();
|
||||
expect(encrypted).toBeEnabled();
|
||||
});
|
||||
|
||||
it('should render with encryption option disabled and set to off when E2E_Enable=false and E2E_Enabled_Default_PrivateRooms=true', async () => {
|
||||
render(<CreateTeamModal onClose={() => null} />, {
|
||||
wrapper: mockAppRoot().withSetting('E2E_Enable', false).withSetting('E2E_Enabled_Default_PrivateRooms', true).build(),
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByText('Advanced_settings'));
|
||||
|
||||
const encrypted = screen.getByLabelText('Teams_New_Encrypted_Label') as HTMLInputElement;
|
||||
expect(encrypted).toBeInTheDocument();
|
||||
|
||||
expect(encrypted).not.toBeChecked();
|
||||
expect(encrypted).toBeDisabled();
|
||||
});
|
||||
|
||||
it('should render with encryption option enabled and set to on when E2E_Enable=true and E2E_Enabled_Default_PrivateRooms=True', async () => {
|
||||
render(<CreateTeamModal onClose={() => null} />, {
|
||||
wrapper: mockAppRoot().withSetting('E2E_Enable', true).withSetting('E2E_Enabled_Default_PrivateRooms', true).build(),
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByText('Advanced_settings'));
|
||||
|
||||
const encrypted = screen.getByLabelText('Teams_New_Encrypted_Label') as HTMLInputElement;
|
||||
expect(encrypted).toBeChecked();
|
||||
expect(encrypted).toBeEnabled();
|
||||
});
|
||||
|
||||
it('when Private goes ON → OFF: forces Encrypted OFF and disables it (E2E_Enable=true, E2E_Enabled_Default_PrivateRooms=true)', async () => {
|
||||
render(<CreateTeamModal onClose={() => null} />, {
|
||||
wrapper: mockAppRoot().withSetting('E2E_Enable', true).withSetting('E2E_Enabled_Default_PrivateRooms', true).build(),
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByText('Advanced_settings'));
|
||||
|
||||
const encrypted = screen.getByLabelText('Teams_New_Encrypted_Label') as HTMLInputElement;
|
||||
const priv = screen.getByLabelText('Teams_New_Private_Label') as HTMLInputElement;
|
||||
|
||||
// initial: private=true, encrypted ON and enabled
|
||||
expect(priv).toBeChecked();
|
||||
expect(encrypted).toBeChecked();
|
||||
expect(encrypted).toBeEnabled();
|
||||
|
||||
// Private ON -> OFF: encrypted must become OFF and disabled
|
||||
await userEvent.click(priv);
|
||||
expect(priv).not.toBeChecked();
|
||||
expect(encrypted).not.toBeChecked();
|
||||
expect(encrypted).toBeDisabled();
|
||||
});
|
||||
|
||||
it('when Private goes OFF → ON: keeps Encrypted OFF but re-enables it (E2E_Enable=true, E2E_Enabled_Default_PrivateRooms=true)', async () => {
|
||||
render(<CreateTeamModal onClose={() => null} />, {
|
||||
wrapper: mockAppRoot().withSetting('E2E_Enable', true).withSetting('E2E_Enabled_Default_PrivateRooms', true).build(),
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByText('Advanced_settings'));
|
||||
|
||||
const encrypted = screen.getByLabelText('Teams_New_Encrypted_Label') as HTMLInputElement;
|
||||
const priv = screen.getByLabelText('Teams_New_Private_Label') as HTMLInputElement;
|
||||
|
||||
// turn private OFF to simulate user path from non-private
|
||||
await userEvent.click(priv);
|
||||
expect(priv).not.toBeChecked();
|
||||
expect(encrypted).not.toBeChecked();
|
||||
expect(encrypted).toBeDisabled();
|
||||
|
||||
// turn private back ON -> encrypted should remain OFF but become enabled
|
||||
await userEvent.click(priv);
|
||||
expect(priv).toBeChecked();
|
||||
expect(encrypted).not.toBeChecked();
|
||||
expect(encrypted).toBeEnabled();
|
||||
});
|
||||
|
||||
it('private team: toggling Broadcast on/off does not change or disable Encrypted', async () => {
|
||||
render(<CreateTeamModal onClose={() => null} />, {
|
||||
wrapper: mockAppRoot().withSetting('E2E_Enable', true).withSetting('E2E_Enabled_Default_PrivateRooms', true).build(),
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByText('Advanced_settings'));
|
||||
|
||||
const encrypted = screen.getByLabelText('Teams_New_Encrypted_Label') as HTMLInputElement;
|
||||
const broadcast = screen.getByLabelText('Teams_New_Broadcast_Label') as HTMLInputElement;
|
||||
const priv = screen.getByLabelText('Teams_New_Private_Label') as HTMLInputElement;
|
||||
|
||||
expect(priv).toBeChecked();
|
||||
expect(encrypted).toBeChecked();
|
||||
expect(encrypted).toBeEnabled();
|
||||
expect(broadcast).not.toBeChecked();
|
||||
|
||||
// Broadcast: OFF -> ON (Encrypted unchanged + enabled)
|
||||
await userEvent.click(broadcast);
|
||||
expect(broadcast).toBeChecked();
|
||||
expect(encrypted).toBeChecked();
|
||||
expect(encrypted).toBeEnabled();
|
||||
|
||||
// Broadcast: ON -> OFF (Encrypted unchanged + enabled)
|
||||
await userEvent.click(broadcast);
|
||||
expect(broadcast).not.toBeChecked();
|
||||
expect(encrypted).toBeChecked();
|
||||
expect(encrypted).toBeEnabled();
|
||||
|
||||
// User can still toggle Encrypted freely while Broadcast is OFF
|
||||
await userEvent.click(encrypted);
|
||||
expect(encrypted).not.toBeChecked();
|
||||
|
||||
// User can still toggle Encrypted freely while Broadcast is ON
|
||||
await userEvent.click(broadcast);
|
||||
expect(broadcast).toBeChecked();
|
||||
expect(encrypted).not.toBeChecked();
|
||||
expect(encrypted).toBeEnabled();
|
||||
});
|
||||
|
||||
it('non-private team: Encrypted remains OFF and disabled regardless of Broadcast state', async () => {
|
||||
render(<CreateTeamModal onClose={() => null} />, {
|
||||
wrapper: mockAppRoot().withSetting('E2E_Enable', true).withSetting('E2E_Enabled_Default_PrivateRooms', true).build(),
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByText('Advanced_settings'));
|
||||
|
||||
const encrypted = screen.getByLabelText('Teams_New_Encrypted_Label') as HTMLInputElement;
|
||||
const broadcast = screen.getByLabelText('Teams_New_Broadcast_Label') as HTMLInputElement;
|
||||
const priv = screen.getByLabelText('Teams_New_Private_Label') as HTMLInputElement;
|
||||
|
||||
// Switch to non-private
|
||||
await userEvent.click(priv);
|
||||
expect(priv).not.toBeChecked();
|
||||
|
||||
// Encrypted must be OFF + disabled (non-private cannot be encrypted)
|
||||
expect(encrypted).not.toBeChecked();
|
||||
expect(encrypted).toBeDisabled();
|
||||
|
||||
// Broadcast: OFF -> ON (Encrypted stays OFF + disabled)
|
||||
await userEvent.click(broadcast);
|
||||
expect(broadcast).toBeChecked();
|
||||
expect(encrypted).not.toBeChecked();
|
||||
expect(encrypted).toBeDisabled();
|
||||
|
||||
// Broadcast: ON -> OFF (Encrypted still OFF + disabled)
|
||||
await userEvent.click(broadcast);
|
||||
expect(broadcast).not.toBeChecked();
|
||||
expect(encrypted).not.toBeChecked();
|
||||
expect(encrypted).toBeDisabled();
|
||||
});
|
||||
|
||||
it('should render a private team with encryption checked and disabled for changes when private room encryption is forced', async () => {
|
||||
render(<CreateTeamModal onClose={() => null} />, {
|
||||
wrapper: mockAppRoot().withSetting('E2E_Enable', true).withSetting('E2E_Force_Encryption_For_Private_Rooms', true).build(),
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByText('Advanced_settings'));
|
||||
|
||||
const encrypted = screen.getByLabelText('Teams_New_Encrypted_Label') as HTMLInputElement;
|
||||
const priv = screen.getByLabelText('Teams_New_Private_Label') as HTMLInputElement;
|
||||
|
||||
// private by default: encrypted is forced ON and cannot be changed
|
||||
expect(priv).toBeChecked();
|
||||
expect(encrypted).toBeChecked();
|
||||
expect(encrypted).toBeDisabled();
|
||||
|
||||
// Private ON -> OFF: encrypted turns OFF and stays disabled (public teams cannot be encrypted)
|
||||
await userEvent.click(priv);
|
||||
expect(priv).not.toBeChecked();
|
||||
expect(encrypted).not.toBeChecked();
|
||||
expect(encrypted).toBeDisabled();
|
||||
|
||||
// Private OFF -> ON: encryption is forced back ON and remains disabled
|
||||
await userEvent.click(priv);
|
||||
expect(priv).toBeChecked();
|
||||
expect(encrypted).toBeChecked();
|
||||
expect(encrypted).toBeDisabled();
|
||||
});
|
||||
|
||||
it('should disable and turn on ReadOnly toggle when Broadcast is ON and no set-readonly permission', async () => {
|
||||
render(<CreateTeamModal onClose={() => null} />, {
|
||||
wrapper: mockAppRoot().build(),
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByText('Advanced_settings'));
|
||||
|
||||
const broadcast = screen.getByLabelText('Teams_New_Broadcast_Label') as HTMLInputElement;
|
||||
const readOnly = screen.getByLabelText('Teams_New_Read_only_Label') as HTMLInputElement;
|
||||
|
||||
expect(readOnly).not.toBeChecked();
|
||||
|
||||
// Broadcast: OFF -> ON (ReadOnly stays ON + disabled)
|
||||
await userEvent.click(broadcast);
|
||||
expect(broadcast).toBeChecked();
|
||||
expect(readOnly).toBeChecked();
|
||||
expect(readOnly).toBeDisabled();
|
||||
});
|
||||
|
||||
it('should disable and turn on ReadOnly toggle when Broadcast is ON with set-readonly permission', async () => {
|
||||
render(<CreateTeamModal onClose={() => null} />, {
|
||||
wrapper: mockAppRoot().withPermission('set-readonly').build(),
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByText('Advanced_settings'));
|
||||
|
||||
const broadcast = screen.getByLabelText('Teams_New_Broadcast_Label') as HTMLInputElement;
|
||||
const readOnly = screen.getByLabelText('Teams_New_Read_only_Label') as HTMLInputElement;
|
||||
|
||||
expect(readOnly).not.toBeChecked();
|
||||
|
||||
// Broadcast: OFF -> ON (ReadOnly stays ON + disabled)
|
||||
await userEvent.click(broadcast);
|
||||
expect(broadcast).toBeChecked();
|
||||
expect(readOnly).toBeChecked();
|
||||
expect(readOnly).toBeDisabled();
|
||||
});
|
||||
|
||||
it('should disable and turn off ReadOnly toggle when Broadcast is OFF with no set-readonly permission', async () => {
|
||||
render(<CreateTeamModal onClose={() => null} />, {
|
||||
wrapper: mockAppRoot().build(),
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByText('Advanced_settings'));
|
||||
|
||||
const broadcast = screen.getByLabelText('Teams_New_Broadcast_Label') as HTMLInputElement;
|
||||
const readOnly = screen.getByLabelText('Teams_New_Read_only_Label') as HTMLInputElement;
|
||||
|
||||
expect(broadcast).not.toBeChecked();
|
||||
expect(readOnly).not.toBeChecked();
|
||||
expect(readOnly).toBeDisabled();
|
||||
});
|
||||
|
||||
it('should enable ReadOnly toggle when Broadcast is OFF with set-readonly permission', async () => {
|
||||
render(<CreateTeamModal onClose={() => null} />, {
|
||||
wrapper: mockAppRoot().withPermission('set-readonly').build(),
|
||||
});
|
||||
|
||||
await userEvent.click(screen.getByText('Advanced_settings'));
|
||||
|
||||
const broadcast = screen.getByLabelText('Teams_New_Broadcast_Label') as HTMLInputElement;
|
||||
const readOnly = screen.getByLabelText('Teams_New_Read_only_Label') as HTMLInputElement;
|
||||
|
||||
expect(broadcast).not.toBeChecked();
|
||||
expect(readOnly).not.toBeChecked();
|
||||
expect(readOnly).toBeEnabled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,295 @@
|
||||
import {
|
||||
Box,
|
||||
Button,
|
||||
Icon,
|
||||
Modal,
|
||||
Accordion,
|
||||
AccordionItem,
|
||||
ModalHeader,
|
||||
ModalTitle,
|
||||
ModalClose,
|
||||
ModalContent,
|
||||
ModalFooter,
|
||||
ModalFooterControllers,
|
||||
} from '@rocket.chat/fuselage';
|
||||
import { TextInput, ToggleSwitch, Field, FieldGroup, FieldLabel, FieldRow, FieldError, FieldHint } from '@rocket.chat/fuselage-forms';
|
||||
import {
|
||||
useEndpoint,
|
||||
usePermission,
|
||||
usePermissionWithScopedRoles,
|
||||
useSetting,
|
||||
useToastMessageDispatch,
|
||||
useTranslation,
|
||||
} from '@rocket.chat/ui-contexts';
|
||||
import type { ComponentProps } from 'react';
|
||||
import { useId, memo, useEffect, useMemo } from 'react';
|
||||
import { Controller, useForm } from 'react-hook-form';
|
||||
|
||||
import { useEncryptedRoomDescription } from './useEncryptedRoomDescription';
|
||||
import UserAutoCompleteMultiple from '../../../components/UserAutoCompleteMultiple';
|
||||
import { useCreateChannelTypePermission } from '../../../hooks/useCreateChannelTypePermission';
|
||||
import { useGoToRoom } from '../../../views/room/hooks/useGoToRoom';
|
||||
|
||||
type CreateTeamModalInputs = {
|
||||
name: string;
|
||||
topic: string;
|
||||
isPrivate: boolean;
|
||||
readOnly: boolean;
|
||||
encrypted: boolean;
|
||||
broadcast: boolean;
|
||||
members?: string[];
|
||||
};
|
||||
|
||||
export type CreateTeamModalProps = { onClose: () => void; onSuccess?: (rid: string) => void | Promise<void> };
|
||||
|
||||
const CreateTeamModal = ({ onClose, onSuccess }: CreateTeamModalProps) => {
|
||||
const t = useTranslation();
|
||||
const e2eEnabled = useSetting('E2E_Enable');
|
||||
const e2eEnabledForPrivateByDefault = useSetting('E2E_Enabled_Default_PrivateRooms') && e2eEnabled;
|
||||
const e2eEnforcedForPrivate = Boolean(useSetting('E2E_Force_Encryption_For_Private_Rooms')) && Boolean(e2eEnabled);
|
||||
const namesValidation = useSetting('UTF8_Channel_Names_Validation');
|
||||
const allowSpecialNames = useSetting('UI_Allow_room_names_with_special_chars');
|
||||
const canSetReadOnly = usePermissionWithScopedRoles('set-readonly', ['owner']);
|
||||
|
||||
const dispatchToastMessage = useToastMessageDispatch();
|
||||
const canCreateTeam = usePermission('create-team');
|
||||
|
||||
const checkTeamNameExists = useEndpoint('GET', '/v1/rooms.nameExists');
|
||||
const createTeamAction = useEndpoint('POST', '/v1/teams.create');
|
||||
|
||||
const teamNameRegex = useMemo(() => {
|
||||
if (allowSpecialNames) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new RegExp(`^${namesValidation}$`);
|
||||
}, [allowSpecialNames, namesValidation]);
|
||||
|
||||
const canOnlyCreateOneType = useCreateChannelTypePermission();
|
||||
|
||||
const validateTeamName = async (name: string): Promise<string | undefined> => {
|
||||
if (!name) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (teamNameRegex && !teamNameRegex?.test(name)) {
|
||||
return t('Name_cannot_have_special_characters');
|
||||
}
|
||||
|
||||
const { exists } = await checkTeamNameExists({ roomName: name });
|
||||
if (exists) {
|
||||
return t('Teams_Errors_Already_exists', { name });
|
||||
}
|
||||
};
|
||||
|
||||
const {
|
||||
control,
|
||||
handleSubmit,
|
||||
setValue,
|
||||
watch,
|
||||
formState: { errors, isSubmitting },
|
||||
} = useForm<CreateTeamModalInputs>({
|
||||
defaultValues: {
|
||||
name: '',
|
||||
topic: '',
|
||||
isPrivate: canOnlyCreateOneType ? canOnlyCreateOneType === 'p' : true,
|
||||
readOnly: false,
|
||||
encrypted: Boolean(e2eEnforcedForPrivate || e2eEnabledForPrivateByDefault),
|
||||
broadcast: false,
|
||||
members: [],
|
||||
},
|
||||
});
|
||||
|
||||
const { isPrivate, broadcast, readOnly, encrypted } = watch();
|
||||
|
||||
useEffect(() => {
|
||||
if (!isPrivate) {
|
||||
setValue('encrypted', false);
|
||||
} else if (e2eEnforcedForPrivate) {
|
||||
setValue('encrypted', true);
|
||||
}
|
||||
|
||||
setValue('readOnly', broadcast);
|
||||
}, [watch, setValue, broadcast, isPrivate, e2eEnforcedForPrivate]);
|
||||
|
||||
const readOnlyDisabled = broadcast || !canSetReadOnly;
|
||||
const canChangeEncrypted = isPrivate && e2eEnabled && !e2eEnforcedForPrivate;
|
||||
const getEncryptedHint = useEncryptedRoomDescription('team');
|
||||
|
||||
const goToRoom = useGoToRoom();
|
||||
|
||||
const handleCreateTeam = async ({
|
||||
name,
|
||||
members,
|
||||
isPrivate,
|
||||
readOnly,
|
||||
topic,
|
||||
broadcast,
|
||||
encrypted,
|
||||
}: CreateTeamModalInputs): Promise<void> => {
|
||||
const params = {
|
||||
name,
|
||||
members,
|
||||
type: isPrivate ? 1 : 0,
|
||||
room: {
|
||||
readOnly,
|
||||
extraData: {
|
||||
topic,
|
||||
broadcast,
|
||||
encrypted,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
try {
|
||||
const { team } = await createTeamAction(params);
|
||||
dispatchToastMessage({ type: 'success', message: t('Team_has_been_created') });
|
||||
goToRoom(team.roomId);
|
||||
void onSuccess?.(team.roomId);
|
||||
onClose();
|
||||
} catch (error) {
|
||||
dispatchToastMessage({ type: 'error', message: error });
|
||||
}
|
||||
};
|
||||
|
||||
const createTeamFormId = useId();
|
||||
|
||||
return (
|
||||
<Modal
|
||||
aria-labelledby={`${createTeamFormId}-title`}
|
||||
wrapperFunction={(props: ComponentProps<typeof Box>) => (
|
||||
<Box is='form' id={createTeamFormId} onSubmit={handleSubmit(handleCreateTeam)} {...props} />
|
||||
)}
|
||||
>
|
||||
<ModalHeader>
|
||||
<ModalTitle id={`${createTeamFormId}-title`}>{t('Teams_New_Title')}</ModalTitle>
|
||||
<ModalClose title={t('Close')} onClick={onClose} tabIndex={-1} />
|
||||
</ModalHeader>
|
||||
<ModalContent marginBlockEnd={2}>
|
||||
<Box fontScale='p2' marginBlockEnd={16}>
|
||||
{t('Teams_new_description')}
|
||||
</Box>
|
||||
<FieldGroup marginBlockEnd={24}>
|
||||
<Field>
|
||||
<FieldLabel required>{t('Teams_New_Name_Label')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
control={control}
|
||||
name='name'
|
||||
rules={{
|
||||
required: t('Required_field', { field: t('Name') }),
|
||||
validate: (value) => validateTeamName(value),
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<TextInput
|
||||
{...field}
|
||||
endAddon={<Icon size='x20' name={isPrivate ? 'team-lock' : 'team'} />}
|
||||
error={errors.name?.message}
|
||||
aria-required='true'
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
{errors?.name && <FieldError>{errors.name.message}</FieldError>}
|
||||
{!allowSpecialNames && <FieldHint>{t('No_spaces_or_special_characters')}</FieldHint>}
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel>{t('Topic')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller control={control} name='topic' render={({ field }) => <TextInput {...field} />} />
|
||||
</FieldRow>
|
||||
<FieldRow>
|
||||
<FieldHint>{t('Displayed_next_to_name')}</FieldHint>
|
||||
</FieldRow>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel>{t('Teams_New_Add_members_Label')}</FieldLabel>
|
||||
<Controller
|
||||
control={control}
|
||||
name='members'
|
||||
render={({ field: { onChange, value } }) => (
|
||||
<UserAutoCompleteMultiple value={value} onChange={onChange} placeholder={t('Add_people')} />
|
||||
)}
|
||||
/>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldRow>
|
||||
<FieldLabel>{t('Teams_New_Private_Label')}</FieldLabel>
|
||||
<Controller
|
||||
control={control}
|
||||
name='isPrivate'
|
||||
render={({ field: { onChange, value, ref } }) => (
|
||||
<ToggleSwitch
|
||||
onChange={onChange}
|
||||
checked={canOnlyCreateOneType ? canOnlyCreateOneType === 'p' : value}
|
||||
disabled={!!canOnlyCreateOneType}
|
||||
ref={ref}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
<FieldHint>{isPrivate ? t('People_can_only_join_by_being_invited') : t('Anyone_can_access')}</FieldHint>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
<Accordion>
|
||||
<AccordionItem title={t('Advanced_settings')}>
|
||||
<FieldGroup>
|
||||
<Box is='h5' fontScale='h5' color='titles-labels'>
|
||||
{t('Security_and_permissions')}
|
||||
</Box>
|
||||
<Field>
|
||||
<FieldRow>
|
||||
<FieldLabel>{t('Teams_New_Encrypted_Label')}</FieldLabel>
|
||||
<Controller
|
||||
control={control}
|
||||
name='encrypted'
|
||||
render={({ field: { onChange, value, ref } }) => (
|
||||
<ToggleSwitch disabled={!canChangeEncrypted} onChange={onChange} checked={value} ref={ref} />
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
<FieldHint>{getEncryptedHint({ isPrivate, encrypted })}</FieldHint>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldRow>
|
||||
<FieldLabel>{t('Teams_New_Read_only_Label')}</FieldLabel>
|
||||
<Controller
|
||||
control={control}
|
||||
name='readOnly'
|
||||
render={({ field: { onChange, value, ref } }) => (
|
||||
<ToggleSwitch disabled={readOnlyDisabled} onChange={onChange} checked={value} ref={ref} />
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
<FieldHint>
|
||||
{readOnly ? t('Read_only_field_hint_enabled', { roomType: 'team' }) : t('Anyone_can_send_new_messages')}
|
||||
</FieldHint>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldRow>
|
||||
<FieldLabel>{t('Teams_New_Broadcast_Label')}</FieldLabel>
|
||||
<Controller
|
||||
control={control}
|
||||
name='broadcast'
|
||||
render={({ field: { onChange, value, ref } }) => <ToggleSwitch onChange={onChange} checked={value} ref={ref} />}
|
||||
/>
|
||||
</FieldRow>
|
||||
{broadcast && <FieldHint>{t('Teams_New_Broadcast_Description')}</FieldHint>}
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
</ModalContent>
|
||||
<ModalFooter>
|
||||
<ModalFooterControllers>
|
||||
<Button onClick={onClose}>{t('Cancel')}</Button>
|
||||
<Button disabled={!canCreateTeam} loading={isSubmitting} type='submit' primary>
|
||||
{t('Create')}
|
||||
</Button>
|
||||
</ModalFooterControllers>
|
||||
</ModalFooter>
|
||||
</Modal>
|
||||
);
|
||||
};
|
||||
|
||||
export default memo(CreateTeamModal);
|
||||
@@ -0,0 +1,127 @@
|
||||
import { mockAppRoot } from '@rocket.chat/mock-providers';
|
||||
import { renderHook } from '@testing-library/react';
|
||||
|
||||
import { useEncryptedRoomDescription } from './useEncryptedRoomDescription';
|
||||
|
||||
const wrapper = mockAppRoot();
|
||||
|
||||
describe('useEncryptedRoomDescription', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
describe.each(['channel', 'team'] as const)('roomType=%s', (roomType) => {
|
||||
it('returns "Not_available_for_this_workspace" when E2E is disabled', () => {
|
||||
const { result } = renderHook(() => useEncryptedRoomDescription(roomType), {
|
||||
wrapper: wrapper.withSetting('E2E_Enable', false).build(),
|
||||
});
|
||||
const describe = result.current;
|
||||
|
||||
expect(describe({ isPrivate: true, encrypted: true })).toBe('Not_available_for_this_workspace');
|
||||
});
|
||||
|
||||
it('returns "Encrypted_not_available" when room is not private and E2E is enabled', () => {
|
||||
const { result } = renderHook(() => useEncryptedRoomDescription(roomType), {
|
||||
wrapper: wrapper.withSetting('E2E_Enable', true).build(),
|
||||
});
|
||||
const describe = result.current;
|
||||
|
||||
expect(describe({ isPrivate: false, encrypted: false })).toBe('Encrypted_not_available');
|
||||
});
|
||||
|
||||
it('returns "Encrypted_messages" when private and encrypted are true and E2E is enabled', () => {
|
||||
const { result } = renderHook(() => useEncryptedRoomDescription(roomType), {
|
||||
wrapper: wrapper.withSetting('E2E_Enable', true).build(),
|
||||
});
|
||||
const describe = result.current;
|
||||
|
||||
expect(describe({ isPrivate: true, encrypted: true })).toBe('Encrypted_messages');
|
||||
});
|
||||
|
||||
it('returns "Encrypted_messages_false" when private and encrypted are false and E2E is enabled', () => {
|
||||
const { result } = renderHook(() => useEncryptedRoomDescription(roomType), {
|
||||
wrapper: wrapper.withSetting('E2E_Enable', true).build(),
|
||||
});
|
||||
const describe = result.current;
|
||||
|
||||
expect(describe({ isPrivate: true, encrypted: false })).toBe('Encrypted_messages_false');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('useEncryptedRoomDescription, Portuguese (pt-BR)', () => {
|
||||
it('returns "Encrypted_not_available" when channel is not private and E2E is enabled,', () => {
|
||||
const { result } = renderHook(() => useEncryptedRoomDescription('channel'), {
|
||||
wrapper: mockAppRoot()
|
||||
.withSetting('E2E_Enable', true)
|
||||
.withDefaultLanguage('pt-BR')
|
||||
.withTranslations('pt-BR', 'core', {
|
||||
Encrypted_not_available: 'Indisponível para {{roomType}} público',
|
||||
channel: 'canal',
|
||||
team: 'equipe',
|
||||
})
|
||||
.build(),
|
||||
});
|
||||
const describe = result.current;
|
||||
|
||||
expect(describe({ isPrivate: false, encrypted: false })).toBe('Indisponível para canal público');
|
||||
});
|
||||
|
||||
it('returns "Encrypted_not_available" when team is not private and E2E is enabled,', () => {
|
||||
const { result } = renderHook(() => useEncryptedRoomDescription('team'), {
|
||||
wrapper: mockAppRoot()
|
||||
.withSetting('E2E_Enable', true)
|
||||
.withDefaultLanguage('pt-BR')
|
||||
.withTranslations('pt-BR', 'core', {
|
||||
Encrypted_not_available: 'Indisponível para {{roomType}} público',
|
||||
channel: 'canal',
|
||||
team: 'equipe',
|
||||
})
|
||||
.build(),
|
||||
});
|
||||
const describe = result.current;
|
||||
|
||||
expect(describe({ isPrivate: false, encrypted: false })).toBe('Indisponível para equipe público');
|
||||
});
|
||||
|
||||
it('returns "Encrypted_messages" when channel is private and encrypted are true and E2E is enabled', () => {
|
||||
const { result } = renderHook(() => useEncryptedRoomDescription('channel'), {
|
||||
wrapper: mockAppRoot()
|
||||
.withSetting('E2E_Enable', true)
|
||||
.withDefaultLanguage('pt-BR')
|
||||
.withTranslations('pt-BR', 'core', {
|
||||
// TODO: Improve the portuguese translation with a way to captalize the room type for it to be in the start of the sentence
|
||||
Encrypted_messages:
|
||||
'Criptografado de ponta a ponta {{roomType}}. A pesquisa não funcionará com {{roomType}} criptografado e as notificações podem não mostrar o conteúdo das mensagens.',
|
||||
team: 'equipe',
|
||||
channel: 'canal',
|
||||
})
|
||||
.build(),
|
||||
});
|
||||
const describe = result.current;
|
||||
|
||||
expect(describe({ isPrivate: true, encrypted: true })).toBe(
|
||||
'Criptografado de ponta a ponta canal. A pesquisa não funcionará com canal criptografado e as notificações podem não mostrar o conteúdo das mensagens.',
|
||||
);
|
||||
});
|
||||
|
||||
it('returns "Encrypted_messages" when team is private and encrypted are true and E2E is enabled', () => {
|
||||
const { result } = renderHook(() => useEncryptedRoomDescription('team'), {
|
||||
wrapper: mockAppRoot()
|
||||
.withSetting('E2E_Enable', true)
|
||||
.withTranslations('pt-BR', 'core', {
|
||||
Encrypted_messages:
|
||||
'Criptografado de ponta a ponta {{roomType}}. A pesquisa não funcionará com {{roomType}} criptografado e as notificações podem não mostrar o conteúdo das mensagens.',
|
||||
channel: 'canal',
|
||||
team: 'equipe',
|
||||
})
|
||||
.withDefaultLanguage('pt-BR')
|
||||
.build(),
|
||||
});
|
||||
const describe = result.current;
|
||||
|
||||
expect(describe({ isPrivate: true, encrypted: true })).toBe(
|
||||
'Criptografado de ponta a ponta equipe. A pesquisa não funcionará com equipe criptografado e as notificações podem não mostrar o conteúdo das mensagens.',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
import { useSetting } from '@rocket.chat/ui-contexts';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
export const useEncryptedRoomDescription = (roomType: 'channel' | 'team' | 'discussion') => {
|
||||
const { t } = useTranslation();
|
||||
const e2eEnabled = useSetting('E2E_Enable');
|
||||
const e2eEnforcedForPrivate = Boolean(useSetting('E2E_Force_Encryption_For_Private_Rooms')) && Boolean(e2eEnabled);
|
||||
|
||||
return ({ isPrivate, encrypted }: { isPrivate: boolean; encrypted: boolean }) => {
|
||||
if (!e2eEnabled) {
|
||||
return t('Not_available_for_this_workspace');
|
||||
}
|
||||
if (!isPrivate) {
|
||||
return t('Encrypted_not_available', { roomType: t(roomType) });
|
||||
}
|
||||
if (e2eEnforcedForPrivate && encrypted) {
|
||||
return t('Encrypted_enforced_by_workspace_policy');
|
||||
}
|
||||
if (encrypted) {
|
||||
return t('Encrypted_messages', { roomType: t(roomType) });
|
||||
}
|
||||
return t('Encrypted_messages_false');
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { GenericMenuItemProps } from '@rocket.chat/ui-client';
|
||||
import { useTranslation, useSetting, useAtLeastOnePermission } from '@rocket.chat/ui-contexts';
|
||||
|
||||
import { useCreateRoomModal } from './useCreateRoomModal';
|
||||
import CreateDiscussion from '../../../components/CreateDiscussion';
|
||||
import CreateChannelModal from '../actions/CreateChannelModal';
|
||||
import CreateDirectMessage from '../actions/CreateDirectMessage';
|
||||
import CreateTeamModal from '../actions/CreateTeamModal';
|
||||
|
||||
const CREATE_CHANNEL_PERMISSIONS = ['create-c', 'create-p'];
|
||||
const CREATE_TEAM_PERMISSIONS = ['create-team'];
|
||||
const CREATE_DIRECT_PERMISSIONS = ['create-d'];
|
||||
const CREATE_DISCUSSION_PERMISSIONS = ['start-discussion', 'start-discussion-other-user'];
|
||||
|
||||
export type UseCreateNewItemsParams = {
|
||||
onCreateSuccess?: (rid: string, name?: string) => void | Promise<void>;
|
||||
};
|
||||
|
||||
export const useCreateNewItems = ({ onCreateSuccess }: UseCreateNewItemsParams = {}): GenericMenuItemProps[] => {
|
||||
const t = useTranslation();
|
||||
const discussionEnabled = useSetting('Discussion_enabled');
|
||||
|
||||
const canCreateChannel = useAtLeastOnePermission(CREATE_CHANNEL_PERMISSIONS);
|
||||
const canCreateTeam = useAtLeastOnePermission(CREATE_TEAM_PERMISSIONS);
|
||||
const canCreateDirectMessages = useAtLeastOnePermission(CREATE_DIRECT_PERMISSIONS);
|
||||
const canCreateDiscussion = useAtLeastOnePermission(CREATE_DISCUSSION_PERMISSIONS);
|
||||
|
||||
const createChannel = useCreateRoomModal(CreateChannelModal, onCreateSuccess);
|
||||
const createTeam = useCreateRoomModal(CreateTeamModal, onCreateSuccess);
|
||||
const createDiscussion = useCreateRoomModal(CreateDiscussion, onCreateSuccess);
|
||||
const createDirectMessage = useCreateRoomModal(CreateDirectMessage, onCreateSuccess);
|
||||
|
||||
const createChannelItem: GenericMenuItemProps = {
|
||||
id: 'channel',
|
||||
content: t('Channel'),
|
||||
icon: 'hashtag',
|
||||
onClick: () => createChannel(),
|
||||
};
|
||||
const createTeamItem: GenericMenuItemProps = {
|
||||
id: 'team',
|
||||
content: t('Team'),
|
||||
icon: 'team',
|
||||
onClick: () => createTeam(),
|
||||
};
|
||||
const createDirectMessageItem: GenericMenuItemProps = {
|
||||
id: 'direct',
|
||||
content: t('Direct_message'),
|
||||
icon: 'balloon',
|
||||
onClick: () => createDirectMessage(),
|
||||
};
|
||||
const createDiscussionItem: GenericMenuItemProps = {
|
||||
id: 'discussion',
|
||||
content: t('Discussion'),
|
||||
icon: 'discussion',
|
||||
onClick: () => createDiscussion(),
|
||||
};
|
||||
|
||||
return [
|
||||
...(canCreateDirectMessages ? [createDirectMessageItem] : []),
|
||||
...(canCreateDiscussion && discussionEnabled ? [createDiscussionItem] : []),
|
||||
...(canCreateChannel ? [createChannelItem] : []),
|
||||
...(canCreateTeam && canCreateChannel ? [createTeamItem] : []),
|
||||
];
|
||||
};
|
||||
@@ -0,0 +1,41 @@
|
||||
import type { GenericMenuItemProps } from '@rocket.chat/ui-client';
|
||||
import { useAtLeastOnePermission } from '@rocket.chat/ui-contexts';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useCreateNewItems } from './useCreateNewItems';
|
||||
import { useCategoryModals } from '../../../sidebar/categories/hooks/useCategoryModals';
|
||||
import { useOutboundMessageAccess } from '../../../views/omnichannel/components/outboundMessage/hooks';
|
||||
import { useOutboundMessageModal } from '../../../views/omnichannel/components/outboundMessage/modals';
|
||||
|
||||
const CREATE_ROOM_PERMISSIONS = ['create-c', 'create-p', 'create-d', 'start-discussion', 'start-discussion-other-user'];
|
||||
|
||||
export const useCreateNewMenu = () => {
|
||||
const { t } = useTranslation();
|
||||
const showCreate = useAtLeastOnePermission(CREATE_ROOM_PERMISSIONS);
|
||||
const { openCreate } = useCategoryModals();
|
||||
|
||||
const canSendOutboundMessage = useOutboundMessageAccess();
|
||||
const outboundMessageModal = useOutboundMessageModal();
|
||||
|
||||
const createRoomItems = useCreateNewItems();
|
||||
const outboundMessageItem: GenericMenuItemProps = {
|
||||
id: 'outbound-message',
|
||||
content: t('Outbound_message'),
|
||||
icon: 'send',
|
||||
onClick: () => outboundMessageModal.open(),
|
||||
};
|
||||
|
||||
const sections = [
|
||||
{
|
||||
title: t('Create_new'),
|
||||
items: [...createRoomItems, ...(canSendOutboundMessage ? [outboundMessageItem] : [])],
|
||||
permission: showCreate || canSendOutboundMessage,
|
||||
},
|
||||
{
|
||||
items: [{ id: 'category', icon: 'folder', content: t('Category'), onClick: () => openCreate() }] as GenericMenuItemProps[],
|
||||
permission: true,
|
||||
},
|
||||
];
|
||||
|
||||
return sections.filter((section) => section.permission);
|
||||
};
|
||||
@@ -0,0 +1,18 @@
|
||||
import { useStableCallback } from '@rocket.chat/fuselage-hooks';
|
||||
import { useSetModal } from '@rocket.chat/ui-contexts';
|
||||
import type { ElementType } from 'react';
|
||||
|
||||
export const useCreateRoomModal = (
|
||||
Component: ElementType<{ onSuccess?: (rid: string, name?: string) => void | Promise<void>; onClose: () => void }>,
|
||||
onSuccess?: (rid: string, name?: string) => void | Promise<void>,
|
||||
): (() => void) => {
|
||||
const setModal = useSetModal();
|
||||
|
||||
return useStableCallback(() => {
|
||||
const handleClose = (): void => {
|
||||
setModal(null);
|
||||
};
|
||||
|
||||
setModal(<Component onSuccess={onSuccess} onClose={handleClose} />);
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,25 @@
|
||||
import { renderHook } from '@testing-library/react';
|
||||
|
||||
import { useGroupingListItems } from './useGroupingListItems';
|
||||
|
||||
it('should render groupingList items', async () => {
|
||||
const { result } = renderHook(() => useGroupingListItems());
|
||||
|
||||
expect(result.current[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
id: 'unread',
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.current[1]).toEqual(
|
||||
expect.objectContaining({
|
||||
id: 'favorites',
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.current[2]).toEqual(
|
||||
expect.objectContaining({
|
||||
id: 'types',
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
import { CheckBox } from '@rocket.chat/fuselage';
|
||||
import { useFeaturePreview, type GenericMenuItemProps } from '@rocket.chat/ui-client';
|
||||
import { useEndpoint, useUserPreference } from '@rocket.chat/ui-contexts';
|
||||
import { useCallback } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
export const useGroupingListItems = (): GenericMenuItemProps[] => {
|
||||
const { t } = useTranslation();
|
||||
const secondSidebarEnabled = useFeaturePreview('secondarySidebar');
|
||||
|
||||
const sidebarGroupByType = useUserPreference<boolean>('sidebarGroupByType');
|
||||
const sidebarShowFavorites = useUserPreference<boolean>('sidebarShowFavorites');
|
||||
const sidebarShowUnread = useUserPreference<boolean>('sidebarShowUnread');
|
||||
|
||||
const saveUserPreferences = useEndpoint('POST', '/v1/users.setPreferences');
|
||||
|
||||
const useHandleChange = (key: 'sidebarGroupByType' | 'sidebarShowFavorites' | 'sidebarShowUnread', value: boolean): (() => void) =>
|
||||
useCallback(() => saveUserPreferences({ data: { [key]: value } }), [key, value]);
|
||||
|
||||
const handleChangeGroupByType = useHandleChange('sidebarGroupByType', !sidebarGroupByType);
|
||||
const handleChangeShoFavorite = useHandleChange('sidebarShowFavorites', !sidebarShowFavorites);
|
||||
const handleChangeShowUnread = useHandleChange('sidebarShowUnread', !sidebarShowUnread);
|
||||
|
||||
return [
|
||||
{
|
||||
id: 'unread',
|
||||
content: t('Unread'),
|
||||
icon: 'flag',
|
||||
onClick: handleChangeShowUnread,
|
||||
addon: <CheckBox checked={sidebarShowUnread} onChange={() => undefined} />,
|
||||
},
|
||||
!secondSidebarEnabled && {
|
||||
id: 'favorites',
|
||||
content: t('Favorites'),
|
||||
icon: 'star',
|
||||
onClick: handleChangeShoFavorite,
|
||||
addon: <CheckBox checked={sidebarShowFavorites} onChange={() => undefined} />,
|
||||
},
|
||||
{
|
||||
id: 'types',
|
||||
content: t('Types'),
|
||||
icon: 'group-by-type',
|
||||
onClick: handleChangeGroupByType,
|
||||
addon: <CheckBox checked={sidebarGroupByType} onChange={() => undefined} />,
|
||||
},
|
||||
].filter(Boolean) as GenericMenuItemProps[];
|
||||
};
|
||||
@@ -0,0 +1,47 @@
|
||||
import { mockAppRoot } from '@rocket.chat/mock-providers';
|
||||
import { renderHook } from '@testing-library/react';
|
||||
|
||||
import { useGroupingListItems } from './useGroupingListItems';
|
||||
|
||||
it('should render all groupingList items', async () => {
|
||||
const { result } = renderHook(() => useGroupingListItems());
|
||||
|
||||
expect(result.current[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
id: 'unread',
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.current[1]).toEqual(
|
||||
expect.objectContaining({
|
||||
id: 'favorites',
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.current[2]).toEqual(
|
||||
expect.objectContaining({
|
||||
id: 'types',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should render only unread and types groupingList items if secondarySidebar is enabled', async () => {
|
||||
const { result } = renderHook(() => useGroupingListItems(), {
|
||||
wrapper: mockAppRoot()
|
||||
.withSetting('Accounts_AllowFeaturePreview', true)
|
||||
.withUserPreference('featuresPreview', [{ name: 'secondarySidebar', value: true }])
|
||||
.build(),
|
||||
});
|
||||
|
||||
expect(result.current[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
id: 'unread',
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.current[1]).toEqual(
|
||||
expect.objectContaining({
|
||||
id: 'types',
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import { mockAppRoot } from '@rocket.chat/mock-providers';
|
||||
import { renderHook } from '@testing-library/react';
|
||||
|
||||
import { useMarketPlaceMenu } from './useMarketPlaceMenu';
|
||||
|
||||
it('should return and empty array if the user does not have `manage-apps` and `access-marketplace` permission', () => {
|
||||
const { result } = renderHook(() => useMarketPlaceMenu(), {
|
||||
wrapper: mockAppRoot()
|
||||
.withEndpoint('GET', '/apps/actionButtons', () => [])
|
||||
.build(),
|
||||
});
|
||||
|
||||
expect(result.current[0].items).toEqual([]);
|
||||
});
|
||||
|
||||
it('should return `explore` and `installed` items if the user has `access-marketplace` permission', () => {
|
||||
const { result } = renderHook(() => useMarketPlaceMenu(), {
|
||||
wrapper: mockAppRoot()
|
||||
.withEndpoint('GET', '/apps/actionButtons', () => [])
|
||||
.withPermission('access-marketplace')
|
||||
.build(),
|
||||
});
|
||||
|
||||
expect(result.current[0].items[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
id: 'explore',
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.current[0].items[1]).toEqual(
|
||||
expect.objectContaining({
|
||||
id: 'installed',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should return `explore`, `installed` and `requested` items if the user has `manage-apps` permission', () => {
|
||||
const { result } = renderHook(() => useMarketPlaceMenu(), {
|
||||
wrapper: mockAppRoot()
|
||||
.withEndpoint('GET', '/apps/actionButtons', () => [])
|
||||
.withEndpoint('GET', '/apps/app-request/stats', () => ({
|
||||
data: {
|
||||
totalSeen: 0,
|
||||
totalUnseen: 1,
|
||||
},
|
||||
}))
|
||||
.withPermission('manage-apps')
|
||||
.build(),
|
||||
});
|
||||
|
||||
expect(result.current[0].items[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
id: 'explore',
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.current[0].items[1]).toEqual(
|
||||
expect.objectContaining({
|
||||
id: 'installed',
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.current[0].items[2]).toEqual(
|
||||
expect.objectContaining({
|
||||
id: 'requested-apps',
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import { Badge, Skeleton } from '@rocket.chat/fuselage';
|
||||
import type { GenericMenuItemProps } from '@rocket.chat/ui-client';
|
||||
import { useTranslation, usePermission, useRouter } from '@rocket.chat/ui-contexts';
|
||||
|
||||
import { useAppRequestStats } from '../../../views/marketplace/hooks/useAppRequestStats';
|
||||
|
||||
export const useMarketPlaceMenu = () => {
|
||||
const t = useTranslation();
|
||||
|
||||
const hasManageAppsPermission = usePermission('manage-apps');
|
||||
const hasAccessMarketplacePermission = usePermission('access-marketplace');
|
||||
|
||||
const showMarketplace = hasAccessMarketplacePermission || hasManageAppsPermission;
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
const appRequestStats = useAppRequestStats();
|
||||
|
||||
const marketPlaceItems: GenericMenuItemProps[] = [
|
||||
{
|
||||
id: 'explore',
|
||||
icon: 'compass',
|
||||
content: t('Explore'),
|
||||
onClick: () => router.navigate('/marketplace/explore/list'),
|
||||
},
|
||||
{
|
||||
id: 'installed',
|
||||
icon: 'circle-arrow-down',
|
||||
content: t('Installed'),
|
||||
onClick: () => router.navigate('/marketplace/installed/list'),
|
||||
},
|
||||
];
|
||||
|
||||
const appsManagementItem: GenericMenuItemProps = {
|
||||
id: 'requested-apps',
|
||||
icon: 'cube',
|
||||
content: t('Requested'),
|
||||
onClick: () => {
|
||||
router.navigate('/marketplace/requested/list');
|
||||
},
|
||||
addon: (
|
||||
<>
|
||||
{appRequestStats.isLoading && <Skeleton variant='circle' height={16} width={16} />}
|
||||
{appRequestStats.isSuccess && appRequestStats.data.totalUnseen > 0 && (
|
||||
<Badge variant='primary'>{appRequestStats.data.totalUnseen}</Badge>
|
||||
)}
|
||||
</>
|
||||
),
|
||||
};
|
||||
|
||||
return [
|
||||
{
|
||||
title: t('Marketplace'),
|
||||
items: [...(showMarketplace ? marketPlaceItems : []), ...(hasManageAppsPermission ? [appsManagementItem] : [])],
|
||||
},
|
||||
];
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { GenericMenuItemProps } from '@rocket.chat/ui-client';
|
||||
import { useFeaturePreview } from '@rocket.chat/ui-client';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useGroupingListItems } from './useGroupingListItems';
|
||||
import { useSortModeItems } from './useSortModeItems';
|
||||
import { useViewModeItems } from './useViewModeItems';
|
||||
|
||||
export const useSortMenu = () => {
|
||||
const { t } = useTranslation();
|
||||
const secondSidebarEnabled = useFeaturePreview('secondarySidebar');
|
||||
|
||||
const viewModeItems = useViewModeItems();
|
||||
const sortModeItems = useSortModeItems();
|
||||
const groupingListItems = useGroupingListItems();
|
||||
|
||||
return [
|
||||
!secondSidebarEnabled ? { title: t('Display'), items: viewModeItems } : undefined,
|
||||
{ title: t('Sort_By'), items: sortModeItems },
|
||||
{ title: t('Group_by'), items: groupingListItems },
|
||||
].filter(Boolean) as { title: string; items: GenericMenuItemProps[] }[];
|
||||
};
|
||||
@@ -0,0 +1,19 @@
|
||||
import { renderHook } from '@testing-library/react';
|
||||
|
||||
import { useSortModeItems } from './useSortModeItems';
|
||||
|
||||
it('should render sortMode items', async () => {
|
||||
const { result } = renderHook(() => useSortModeItems());
|
||||
|
||||
expect(result.current[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
id: 'activity',
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.current[1]).toEqual(
|
||||
expect.objectContaining({
|
||||
id: 'name',
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
import { RadioButton } from '@rocket.chat/fuselage';
|
||||
import type { GenericMenuItemProps } from '@rocket.chat/ui-client';
|
||||
import { useEndpoint, useUserPreference } from '@rocket.chat/ui-contexts';
|
||||
import { useCallback } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import {
|
||||
OmnichannelSortingDisclaimer,
|
||||
useOmnichannelSortingDisclaimer,
|
||||
} from '../../../views/omnichannel/components/OmnichannelSortingDisclaimer';
|
||||
|
||||
export const useSortModeItems = (): GenericMenuItemProps[] => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const saveUserPreferences = useEndpoint('POST', '/v1/users.setPreferences');
|
||||
const sidebarSortBy = useUserPreference<'activity' | 'alphabetical'>('sidebarSortby', 'activity');
|
||||
const isOmnichannelEnabled = useOmnichannelSortingDisclaimer();
|
||||
|
||||
const useHandleChange = (value: 'alphabetical' | 'activity'): (() => void) =>
|
||||
useCallback(() => saveUserPreferences({ data: { sidebarSortby: value } }), [value]);
|
||||
|
||||
const setToAlphabetical = useHandleChange('alphabetical');
|
||||
const setToActivity = useHandleChange('activity');
|
||||
|
||||
return [
|
||||
{
|
||||
id: 'activity',
|
||||
content: t('Activity'),
|
||||
icon: 'clock',
|
||||
onClick: setToActivity,
|
||||
addon: <RadioButton checked={sidebarSortBy === 'activity'} onChange={() => undefined} />,
|
||||
description: sidebarSortBy === 'activity' && isOmnichannelEnabled && <OmnichannelSortingDisclaimer />,
|
||||
},
|
||||
{
|
||||
id: 'name',
|
||||
content: t('Name'),
|
||||
icon: 'sort-az',
|
||||
onClick: setToAlphabetical,
|
||||
addon: <RadioButton checked={sidebarSortBy === 'alphabetical'} onChange={() => undefined} />,
|
||||
description: sidebarSortBy === 'alphabetical' && isOmnichannelEnabled && <OmnichannelSortingDisclaimer />,
|
||||
},
|
||||
];
|
||||
};
|
||||
@@ -0,0 +1,31 @@
|
||||
import { renderHook } from '@testing-library/react';
|
||||
|
||||
import { useViewModeItems } from './useViewModeItems';
|
||||
|
||||
it('should render viewMode items', async () => {
|
||||
const { result } = renderHook(() => useViewModeItems());
|
||||
|
||||
expect(result.current[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
id: 'extended',
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.current[1]).toEqual(
|
||||
expect.objectContaining({
|
||||
id: 'medium',
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.current[2]).toEqual(
|
||||
expect.objectContaining({
|
||||
id: 'condensed',
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.current[3]).toEqual(
|
||||
expect.objectContaining({
|
||||
id: 'avatars',
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import { RadioButton, ToggleSwitch } from '@rocket.chat/fuselage';
|
||||
import type { GenericMenuItemProps } from '@rocket.chat/ui-client';
|
||||
import { useEndpoint, useUserPreference } from '@rocket.chat/ui-contexts';
|
||||
import { useCallback } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
export const useViewModeItems = (): GenericMenuItemProps[] => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const saveUserPreferences = useEndpoint('POST', '/v1/users.setPreferences');
|
||||
|
||||
const useHandleChange = (value: 'medium' | 'extended' | 'condensed'): (() => void) =>
|
||||
useCallback(() => saveUserPreferences({ data: { sidebarViewMode: value } }), [value]);
|
||||
|
||||
const sidebarViewMode = useUserPreference<'medium' | 'extended' | 'condensed'>('sidebarViewMode', 'extended');
|
||||
const sidebarDisplayAvatar = useUserPreference('sidebarDisplayAvatar', false);
|
||||
|
||||
const setToExtended = useHandleChange('extended');
|
||||
const setToMedium = useHandleChange('medium');
|
||||
const setToCondensed = useHandleChange('condensed');
|
||||
|
||||
const handleChangeSidebarDisplayAvatar = useCallback(
|
||||
() => saveUserPreferences({ data: { sidebarDisplayAvatar: !sidebarDisplayAvatar } }),
|
||||
[saveUserPreferences, sidebarDisplayAvatar],
|
||||
);
|
||||
|
||||
return [
|
||||
{
|
||||
id: 'extended',
|
||||
content: t('Extended'),
|
||||
icon: 'extended-view',
|
||||
onClick: setToExtended,
|
||||
addon: <RadioButton checked={sidebarViewMode === 'extended'} onChange={() => undefined} />,
|
||||
},
|
||||
{
|
||||
id: 'medium',
|
||||
content: t('Medium'),
|
||||
icon: 'medium-view',
|
||||
onClick: setToMedium,
|
||||
addon: <RadioButton checked={sidebarViewMode === 'medium'} onChange={() => undefined} />,
|
||||
},
|
||||
{
|
||||
id: 'condensed',
|
||||
content: t('Condensed'),
|
||||
icon: 'condensed-view',
|
||||
onClick: setToCondensed,
|
||||
addon: <RadioButton checked={sidebarViewMode === 'condensed'} onChange={() => undefined} />,
|
||||
},
|
||||
{
|
||||
id: 'avatars',
|
||||
content: t('Avatars'),
|
||||
icon: 'user-rounded',
|
||||
onClick: handleChangeSidebarDisplayAvatar,
|
||||
addon: <ToggleSwitch checked={sidebarDisplayAvatar} onChange={() => undefined} />,
|
||||
},
|
||||
];
|
||||
};
|
||||
1
apps/meteor/client/navbar/NavBarPagesGroup/index.ts
Normal file
1
apps/meteor/client/navbar/NavBarPagesGroup/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { default } from './NavBarPagesGroup';
|
||||
24
apps/meteor/client/navbar/NavBarPagesSection.tsx
Normal file
24
apps/meteor/client/navbar/NavBarPagesSection.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
import { NavBarGroup, NavBarSection } from '@rocket.chat/fuselage';
|
||||
import { useLayout } from '@rocket.chat/ui-contexts';
|
||||
|
||||
import NavBarPagesGroup from './NavBarPagesGroup';
|
||||
import SidebarToggler from '../components/SidebarToggler';
|
||||
|
||||
const NavBarPagesSection = () => {
|
||||
const { sidebar } = useLayout();
|
||||
|
||||
return (
|
||||
<NavBarSection>
|
||||
{sidebar.shouldToggle && (
|
||||
<>
|
||||
<NavBarGroup>
|
||||
<SidebarToggler />
|
||||
</NavBarGroup>
|
||||
</>
|
||||
)}
|
||||
<NavBarPagesGroup />
|
||||
</NavBarSection>
|
||||
);
|
||||
};
|
||||
|
||||
export default NavBarPagesSection;
|
||||
@@ -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';
|
||||
@@ -0,0 +1,69 @@
|
||||
import { mockAppRoot } from '@rocket.chat/mock-providers';
|
||||
import { render, screen, waitFor } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
|
||||
import NavBarItemAdministrationMenu from './NavBarItemAdministrationMenu';
|
||||
|
||||
const handleMenuClick = async () => {
|
||||
const menuButton = await screen.findByRole('button', { name: 'Manage' });
|
||||
await userEvent.click(menuButton);
|
||||
};
|
||||
|
||||
it('should not display the menu if no permission is set', async () => {
|
||||
render(<NavBarItemAdministrationMenu />, { wrapper: mockAppRoot().build() });
|
||||
|
||||
expect(screen.queryByRole('button', { name: 'Manage' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should display the workspace menu item if at least one admin permission is set', async () => {
|
||||
render(<NavBarItemAdministrationMenu />, { wrapper: mockAppRoot().withPermission('access-permissions').build() });
|
||||
|
||||
await handleMenuClick();
|
||||
expect(await screen.findByRole('menuitem', { name: 'Workspace' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should display the omnichannel menu item if view-livechat-manager permission is set', async () => {
|
||||
render(<NavBarItemAdministrationMenu />, {
|
||||
wrapper: mockAppRoot().withPermission('view-livechat-manager').withPermission('access-permissions').build(),
|
||||
});
|
||||
|
||||
await handleMenuClick();
|
||||
expect(await screen.findByRole('menuitem', { name: 'Omnichannel' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should not display any audit items if has at least one admin permission, some audit permission and the auditing module is not enabled', async () => {
|
||||
render(<NavBarItemAdministrationMenu />, {
|
||||
wrapper: mockAppRoot().withPermission('access-permissions').withPermission('can-audit').build(),
|
||||
});
|
||||
|
||||
await handleMenuClick();
|
||||
expect(screen.queryByRole('menuitem', { name: 'Messages' })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('should display audit items if has at least one admin permission, both audit permission and the auditing module is enabled', async () => {
|
||||
render(<NavBarItemAdministrationMenu />, {
|
||||
wrapper: mockAppRoot()
|
||||
.withEndpoint('GET', '/v1/licenses.info', () => ({
|
||||
license: {
|
||||
license: {
|
||||
// @ts-expect-error: just for testing
|
||||
grantedModules: [{ module: 'auditing' }],
|
||||
},
|
||||
// @ts-expect-error: just for testing
|
||||
activeModules: ['auditing'],
|
||||
},
|
||||
}))
|
||||
.withJohnDoe()
|
||||
.withPermission('can-audit')
|
||||
.withPermission('can-audit-log')
|
||||
.build(),
|
||||
});
|
||||
|
||||
await handleMenuClick();
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Messages')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
expect(await screen.findByRole('menuitem', { name: 'Messages' })).toBeInTheDocument();
|
||||
expect(await screen.findByRole('menuitem', { name: 'Logs' })).toBeInTheDocument();
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import { NavBarItem } from '@rocket.chat/fuselage';
|
||||
import { GenericMenu } from '@rocket.chat/ui-client';
|
||||
import { useCurrentRoutePath } from '@rocket.chat/ui-contexts';
|
||||
import type { HTMLAttributes } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useAdministrationMenu } from './hooks/useAdministrationMenu';
|
||||
import { useAuditMenu } from './hooks/useAuditMenu';
|
||||
|
||||
export type NavBarItemAdministrationMenuProps = Omit<HTMLAttributes<HTMLElement>, 'is'>;
|
||||
|
||||
const NavBarItemAdministrationMenu = (props: NavBarItemAdministrationMenuProps) => {
|
||||
const { t } = useTranslation();
|
||||
const currentRoute = useCurrentRoutePath();
|
||||
|
||||
const adminSection = useAdministrationMenu();
|
||||
const auditSection = useAuditMenu();
|
||||
|
||||
const adminRoutesRegex = new RegExp(['/omnichannel/', '/admin', '/audit'].join('|'));
|
||||
const pressed = adminRoutesRegex.test(currentRoute || '');
|
||||
|
||||
const sections = [adminSection, auditSection].filter((section) => section.items.length > 0);
|
||||
|
||||
if (sections.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<GenericMenu sections={sections} title={t('Manage')} is={NavBarItem} icon='cog' pressed={pressed} placement='bottom-end' {...props} />
|
||||
);
|
||||
};
|
||||
|
||||
export default NavBarItemAdministrationMenu;
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Button } from '@rocket.chat/fuselage';
|
||||
import { useSessionDispatch } from '@rocket.chat/ui-contexts';
|
||||
import type { HTMLAttributes } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
export type NavBarItemLoginPageProps = Omit<HTMLAttributes<HTMLElement>, 'is'>;
|
||||
|
||||
const NavBarItemLoginPage = (props: NavBarItemLoginPageProps) => {
|
||||
const setForceLogin = useSessionDispatch('forceLogin');
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Button primary small icon='login' onClick={(): void => setForceLogin(true)} {...props}>
|
||||
{t('Login')}
|
||||
</Button>
|
||||
);
|
||||
};
|
||||
|
||||
export default NavBarItemLoginPage;
|
||||
@@ -0,0 +1,193 @@
|
||||
import { UserStatus as UserStatusType } from '@rocket.chat/core-typings';
|
||||
import type { SelectOption } from '@rocket.chat/fuselage';
|
||||
import { InputBox, Margins, Box } from '@rocket.chat/fuselage';
|
||||
import { Field, FieldGroup, FieldLabel, FieldRow, FieldError, FieldHint, TextInput, Select } from '@rocket.chat/fuselage-forms';
|
||||
import { useLocalStorage } from '@rocket.chat/fuselage-hooks';
|
||||
import { GenericModal } from '@rocket.chat/ui-client';
|
||||
import { useToastMessageDispatch, useSetting, useEndpoint, useUser, useTranslation } from '@rocket.chat/ui-contexts';
|
||||
import type { ChangeEvent, ComponentProps } from 'react';
|
||||
import { useEffect, useMemo } from 'react';
|
||||
import { Controller, useForm } from 'react-hook-form';
|
||||
|
||||
import UserStatusMenu from '../../../components/UserStatusMenu';
|
||||
import { USER_STATUS_TEXT_MAX_LENGTH } from '../../../lib/constants';
|
||||
import { getUserStatusInitialValues } from '../../../lib/getUserInitialStatus';
|
||||
import { STATUS_DURATION_OPTIONS, validateStatusExpiration } from '../../../lib/statusDurations';
|
||||
|
||||
export type EditStatusModalProps = {
|
||||
onClose: () => void;
|
||||
};
|
||||
|
||||
type StatusFormValues = {
|
||||
statusText: string;
|
||||
statusType: UserStatusType;
|
||||
statusDuration: string;
|
||||
statusCustomDate: string;
|
||||
statusCustomTime: string;
|
||||
};
|
||||
|
||||
const EditStatusModal = ({ onClose }: EditStatusModalProps) => {
|
||||
const t = useTranslation();
|
||||
const user = useUser();
|
||||
const allowUserStatusMessageChange = useSetting('Accounts_AllowUserStatusMessageChange');
|
||||
const dispatchToastMessage = useToastMessageDispatch();
|
||||
const [customStatus, setCustomStatus] = useLocalStorage<string>('Local_Custom_Status', '');
|
||||
|
||||
const {
|
||||
control,
|
||||
handleSubmit,
|
||||
setValue,
|
||||
watch,
|
||||
formState: { errors, isDirty },
|
||||
} = useForm<StatusFormValues>({
|
||||
defaultValues: getUserStatusInitialValues(user, customStatus),
|
||||
});
|
||||
|
||||
const { statusDuration, statusType, statusText } = watch();
|
||||
const isExpirationDisabled = statusType === UserStatusType.ONLINE && !statusText.trim();
|
||||
|
||||
useEffect(() => {
|
||||
if (isExpirationDisabled) {
|
||||
setValue('statusDuration', '', { shouldValidate: true });
|
||||
}
|
||||
}, [isExpirationDisabled, setValue]);
|
||||
|
||||
const isStatusFromCall = user?.statusSource === 'internal' || user?.statusSource === 'external';
|
||||
|
||||
const setUserStatus = useEndpoint('POST', '/v1/users.setStatus');
|
||||
|
||||
const durationOptions: SelectOption[] = useMemo(() => STATUS_DURATION_OPTIONS.map(({ value, labelKey }) => [value, t(labelKey)]), [t]);
|
||||
|
||||
const handleSaveStatus = async ({
|
||||
statusText,
|
||||
statusType,
|
||||
statusDuration,
|
||||
statusCustomDate,
|
||||
statusCustomTime,
|
||||
}: StatusFormValues): Promise<void> => {
|
||||
const expiresAt = STATUS_DURATION_OPTIONS.find((o) => o.value === statusDuration)?.getExpiresAt?.({
|
||||
now: new Date(),
|
||||
customDate: statusCustomDate,
|
||||
customTime: statusCustomTime,
|
||||
});
|
||||
try {
|
||||
await setUserStatus({
|
||||
message: statusText,
|
||||
status: statusType,
|
||||
...(expiresAt && { expiresAt: expiresAt.toISOString() }),
|
||||
});
|
||||
setCustomStatus(statusText);
|
||||
dispatchToastMessage({ type: 'success', message: t('StatusMessage_Changed_Successfully') });
|
||||
onClose();
|
||||
} catch (error) {
|
||||
dispatchToastMessage({ type: 'error', message: error });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<GenericModal
|
||||
icon={null}
|
||||
variant='warning'
|
||||
title={t('Status_set_your_status')}
|
||||
onCancel={onClose}
|
||||
confirmText={t('Save')}
|
||||
confirmDisabled={!isDirty}
|
||||
wrapperFunction={(props: ComponentProps<typeof Box>) => <Box is='form' onSubmit={handleSubmit(handleSaveStatus)} {...props} />}
|
||||
>
|
||||
<FieldGroup>
|
||||
<Field>
|
||||
<FieldLabel>{t('Status')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
control={control}
|
||||
name='statusText'
|
||||
rules={{
|
||||
maxLength: {
|
||||
value: USER_STATUS_TEXT_MAX_LENGTH,
|
||||
message: t('Max_length_is', { limit: USER_STATUS_TEXT_MAX_LENGTH }),
|
||||
},
|
||||
}}
|
||||
render={({ field }) => (
|
||||
<TextInput
|
||||
{...field}
|
||||
error={errors.statusText?.message}
|
||||
disabled={!allowUserStatusMessageChange}
|
||||
flexGrow={1}
|
||||
placeholder={t(statusType)}
|
||||
startAddon={
|
||||
<Controller
|
||||
control={control}
|
||||
name='statusType'
|
||||
render={({ field: { value, onChange } }) => <UserStatusMenu initialStatus={value} onChange={onChange} />}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
<FieldHint>{t(allowUserStatusMessageChange ? 'Status_you_can_use_emoji' : 'StatusMessage_Change_Disabled')}</FieldHint>
|
||||
{errors.statusText && <FieldError>{errors.statusText.message}</FieldError>}
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel>{t('Status_clear_after')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
control={control}
|
||||
name='statusDuration'
|
||||
rules={{
|
||||
deps: ['statusCustomDate', 'statusCustomTime'],
|
||||
validate: (value, { statusCustomDate, statusCustomTime }) =>
|
||||
validateStatusExpiration(value, { statusCustomDate, statusCustomTime }, t),
|
||||
}}
|
||||
render={({ field: { value, onChange } }) => (
|
||||
<Select
|
||||
value={value}
|
||||
options={durationOptions}
|
||||
onChange={(next) => onChange(String(next))}
|
||||
disabled={isExpirationDisabled}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
{statusDuration === 'custom' && (
|
||||
<Box display='flex' marginInline='neg-x4' marginBlockStart={8}>
|
||||
<Margins inline={4}>
|
||||
<Controller
|
||||
control={control}
|
||||
name='statusCustomDate'
|
||||
render={({ field: { value, onChange } }) => (
|
||||
<InputBox
|
||||
aria-label={t('Status_expiration_date')}
|
||||
type='date'
|
||||
flexGrow={1}
|
||||
value={value}
|
||||
onChange={(e: ChangeEvent<HTMLInputElement>) => onChange(e.currentTarget.value)}
|
||||
min={new Date().toLocaleDateString('en-CA')}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<Controller
|
||||
control={control}
|
||||
name='statusCustomTime'
|
||||
render={({ field: { value, onChange } }) => (
|
||||
<InputBox
|
||||
aria-label={t('Status_expiration_time')}
|
||||
type='time'
|
||||
flexGrow={1}
|
||||
value={value}
|
||||
onChange={(e: ChangeEvent<HTMLInputElement>) => onChange(e.currentTarget.value)}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</Margins>
|
||||
</Box>
|
||||
)}
|
||||
{errors.statusDuration && <FieldError>{errors.statusDuration.message}</FieldError>}
|
||||
<FieldHint>{t(isStatusFromCall ? 'Status_new_status_warning_after_call' : 'Status_new_status_warning')}</FieldHint>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
</GenericModal>
|
||||
);
|
||||
};
|
||||
|
||||
export default EditStatusModal;
|
||||
@@ -0,0 +1,79 @@
|
||||
import { Box } from '@rocket.chat/fuselage';
|
||||
import { Field, FieldGroup, FieldHint, FieldLabel, FieldRow } from '@rocket.chat/fuselage-forms';
|
||||
import { GenericModal } from '@rocket.chat/ui-client';
|
||||
import { useEndpoint, useToastMessageDispatch, useUser } from '@rocket.chat/ui-contexts';
|
||||
import type { ComponentProps } from 'react';
|
||||
import { Controller, useForm } from 'react-hook-form';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import UserAutoCompleteMultiple from '../../../components/UserAutoCompleteMultiple';
|
||||
|
||||
export type EditStatusVisibilityModalProps = {
|
||||
onClose: () => void;
|
||||
};
|
||||
|
||||
type StatusVisibilityFormValues = {
|
||||
statusVisibilityDenied: string[];
|
||||
};
|
||||
|
||||
export const EditStatusVisibilityModal = ({ onClose }: EditStatusVisibilityModalProps) => {
|
||||
const { t } = useTranslation();
|
||||
const user = useUser();
|
||||
const dispatchToastMessage = useToastMessageDispatch();
|
||||
const setPreferences = useEndpoint('POST', '/v1/users.setPreferences');
|
||||
|
||||
const {
|
||||
control,
|
||||
handleSubmit,
|
||||
formState: { isDirty, isSubmitting },
|
||||
} = useForm<StatusVisibilityFormValues>({
|
||||
defaultValues: {
|
||||
statusVisibilityDenied: user?.settings?.preferences?.statusVisibilityDenied ?? [],
|
||||
},
|
||||
});
|
||||
|
||||
const handleSave = async ({ statusVisibilityDenied }: StatusVisibilityFormValues) => {
|
||||
try {
|
||||
await setPreferences({ data: { statusVisibilityDenied } });
|
||||
dispatchToastMessage({ type: 'success', message: t('Accounts_StatusVisibility_Saved') });
|
||||
onClose();
|
||||
} catch (error) {
|
||||
dispatchToastMessage({ type: 'error', message: error });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<GenericModal
|
||||
icon={null}
|
||||
variant='warning'
|
||||
title={t('Accounts_StatusVisibility_HideStatus')}
|
||||
onCancel={onClose}
|
||||
confirmText={t('Save')}
|
||||
confirmDisabled={!isDirty || isSubmitting}
|
||||
wrapperFunction={(props: ComponentProps<typeof Box>) => <Box is='form' onSubmit={handleSubmit(handleSave)} {...props} />}
|
||||
>
|
||||
<FieldGroup>
|
||||
<Field>
|
||||
<FieldLabel>{t('Accounts_StatusVisibility_HideFromUsers')}</FieldLabel>
|
||||
<FieldRow>
|
||||
<Controller
|
||||
control={control}
|
||||
name='statusVisibilityDenied'
|
||||
render={({ field: { onChange, value } }) => (
|
||||
<UserAutoCompleteMultiple
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
exceptions={user?.username ? [user.username] : undefined}
|
||||
placeholder={t('Select_users')}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
</FieldRow>
|
||||
<FieldHint>{t('Accounts_StatusVisibility_HideFromUsers_Description')}</FieldHint>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
</GenericModal>
|
||||
);
|
||||
};
|
||||
|
||||
export default EditStatusVisibilityModal;
|
||||
@@ -0,0 +1,135 @@
|
||||
import { Box, Divider } from '@rocket.chat/fuselage';
|
||||
import { GenericModal } from '@rocket.chat/ui-client';
|
||||
import { Fragment, memo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
type KeyCombo = {
|
||||
mac: readonly string[];
|
||||
other: readonly string[];
|
||||
};
|
||||
|
||||
type ShortcutDefinition = {
|
||||
id: string;
|
||||
descriptionKey: string;
|
||||
combos: readonly KeyCombo[];
|
||||
};
|
||||
|
||||
const SHORTCUTS: readonly ShortcutDefinition[] = [
|
||||
{
|
||||
id: 'openKeyboardShortcuts',
|
||||
descriptionKey: 'Keyboard_Shortcuts_Show_Keyboard_Shortcuts',
|
||||
combos: [{ mac: ['Shift', '?'], other: ['Shift', '?'] }],
|
||||
},
|
||||
{
|
||||
id: 'openSearch',
|
||||
descriptionKey: 'Keyboard_Shortcuts_Open_Channel_Slash_User_Search',
|
||||
combos: [
|
||||
{ mac: ['Command', 'P'], other: ['Control', 'P'] },
|
||||
{ mac: ['Command', 'K'], other: ['Control', 'K'] },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: 'markAllAsRead',
|
||||
descriptionKey: 'Keyboard_Shortcuts_Mark_all_as_read',
|
||||
combos: [{ mac: ['Shift', 'Escape'], other: ['Control', 'Escape'] }],
|
||||
},
|
||||
{
|
||||
id: 'editPreviousMessage',
|
||||
descriptionKey: 'Keyboard_Shortcuts_Edit_Previous_Message',
|
||||
combos: [{ mac: ['ArrowUp'], other: ['ArrowUp'] }],
|
||||
},
|
||||
{
|
||||
id: 'moveToBeginningHorizontal',
|
||||
descriptionKey: 'Keyboard_Shortcuts_Move_To_Beginning_Of_Message',
|
||||
combos: [{ mac: ['Command', 'ArrowLeft'], other: ['Alt', 'ArrowLeft'] }],
|
||||
},
|
||||
{
|
||||
id: 'moveToBeginningVertical',
|
||||
descriptionKey: 'Keyboard_Shortcuts_Move_To_Beginning_Of_Message',
|
||||
combos: [{ mac: ['Command', 'ArrowUp'], other: ['Alt', 'ArrowUp'] }],
|
||||
},
|
||||
{
|
||||
id: 'moveToEndHorizontal',
|
||||
descriptionKey: 'Keyboard_Shortcuts_Move_To_End_Of_Message',
|
||||
combos: [{ mac: ['Command', 'ArrowRight'], other: ['Alt', 'ArrowRight'] }],
|
||||
},
|
||||
{
|
||||
id: 'moveToEndVertical',
|
||||
descriptionKey: 'Keyboard_Shortcuts_Move_To_End_Of_Message',
|
||||
combos: [{ mac: ['Command', 'ArrowDown'], other: ['Alt', 'ArrowDown'] }],
|
||||
},
|
||||
{
|
||||
id: 'newLine',
|
||||
descriptionKey: 'Keyboard_Shortcuts_New_Line_In_Message',
|
||||
combos: [{ mac: ['Shift', 'Enter'], other: ['Shift', 'Enter'] }],
|
||||
},
|
||||
];
|
||||
|
||||
const KEY_LABEL_TRANSLATIONS: Record<string, string> = {
|
||||
Command: 'Keyboard_Shortcut_Key_Command',
|
||||
Control: 'Keyboard_Shortcut_Key_Control',
|
||||
Option: 'Keyboard_Shortcut_Key_Option',
|
||||
Alt: 'Keyboard_Shortcut_Key_Alt',
|
||||
Shift: 'Keyboard_Shortcut_Key_Shift',
|
||||
Enter: 'Keyboard_Shortcut_Key_Enter',
|
||||
Escape: 'Keyboard_Shortcut_Key_Escape',
|
||||
ArrowUp: 'Keyboard_Shortcut_Key_ArrowUp',
|
||||
ArrowDown: 'Keyboard_Shortcut_Key_ArrowDown',
|
||||
ArrowLeft: 'Keyboard_Shortcut_Key_ArrowLeft',
|
||||
ArrowRight: 'Keyboard_Shortcut_Key_ArrowRight',
|
||||
};
|
||||
|
||||
const isMacPlatform = (): boolean =>
|
||||
typeof navigator !== 'undefined' && typeof navigator.platform === 'string' && navigator.platform.toLowerCase().includes('mac');
|
||||
|
||||
export type KeyboardShortcutsModalProps = {
|
||||
onClose: () => void;
|
||||
};
|
||||
|
||||
const KeyboardShortcutsModal = ({ onClose }: KeyboardShortcutsModalProps) => {
|
||||
const { t } = useTranslation();
|
||||
const isMac = isMacPlatform();
|
||||
|
||||
return (
|
||||
<GenericModal icon='keyboard' variant='info' title={t('Keyboard_Shortcuts_Title')} cancelText={t('Close')} onCancel={onClose}>
|
||||
<Box is='dl' aria-label={t('Keyboard_Shortcuts_Title')} margin={0}>
|
||||
{SHORTCUTS.map(({ id, descriptionKey, combos }) => (
|
||||
<Box key={id} marginBlockEnd={12}>
|
||||
<Box is='dt' fontScale='p2m' fontWeight='700' marginBlockEnd={4}>
|
||||
{t(descriptionKey)}
|
||||
</Box>
|
||||
<Box is='dd' fontScale='p2' margin={0} marginBlockEnd={8}>
|
||||
{combos.map((combo, comboIndex) => {
|
||||
const keys = isMac ? combo.mac : combo.other;
|
||||
return (
|
||||
<Fragment key={comboIndex}>
|
||||
{comboIndex > 0 && (
|
||||
<Box is='span' marginInline={8} color='hint'>
|
||||
{t('or')}
|
||||
</Box>
|
||||
)}
|
||||
<Box is='kbd'>
|
||||
{keys.map((token, tokenIndex) => (
|
||||
<Fragment key={tokenIndex}>
|
||||
{tokenIndex > 0 && (
|
||||
<Box is='span' marginInline={4} aria-hidden='true'>
|
||||
+
|
||||
</Box>
|
||||
)}
|
||||
<Box is='kbd'>{KEY_LABEL_TRANSLATIONS[token] ? t(KEY_LABEL_TRANSLATIONS[token]) : token}</Box>
|
||||
</Fragment>
|
||||
))}
|
||||
</Box>
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
<Divider aria-hidden='true' margin={0} />
|
||||
</Box>
|
||||
))}
|
||||
</Box>
|
||||
</GenericModal>
|
||||
);
|
||||
};
|
||||
|
||||
export default memo(KeyboardShortcutsModal);
|
||||
@@ -0,0 +1,38 @@
|
||||
import type { IUser } from '@rocket.chat/core-typings';
|
||||
import { GenericMenu, useHandleMenuAction } from '@rocket.chat/ui-client';
|
||||
import type { GenericMenuItemProps } from '@rocket.chat/ui-client';
|
||||
import type { ComponentProps } from 'react';
|
||||
import { memo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import UserMenuButton from './UserMenuButton';
|
||||
import { useUserMenu } from './hooks/useUserMenu';
|
||||
|
||||
export type UserMenuProps = { user: IUser } & Omit<ComponentProps<typeof GenericMenu>, 'sections' | 'items' | 'title'>;
|
||||
|
||||
const UserMenu = function UserMenu({ user, ...props }: UserMenuProps) {
|
||||
const { t } = useTranslation();
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
|
||||
const sections = useUserMenu(user);
|
||||
const items = sections.reduce((acc, { items }) => [...acc, ...items], [] as GenericMenuItemProps[]);
|
||||
|
||||
const handleAction = useHandleMenuAction(items, () => setIsOpen(false));
|
||||
|
||||
return (
|
||||
<GenericMenu
|
||||
{...props}
|
||||
is={UserMenuButton}
|
||||
placement='bottom-end'
|
||||
selectionMode='multiple'
|
||||
sections={sections}
|
||||
title={t('User_menu')}
|
||||
onAction={handleAction}
|
||||
isOpen={isOpen}
|
||||
onOpenChange={setIsOpen}
|
||||
aria-label={t('User_menu')}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default memo(UserMenu);
|
||||
@@ -0,0 +1,59 @@
|
||||
import { css } from '@rocket.chat/css-in-js';
|
||||
import { Box, IconButton } from '@rocket.chat/fuselage';
|
||||
import { UserAvatar } from '@rocket.chat/ui-avatar';
|
||||
import { useSetting, useUser } from '@rocket.chat/ui-contexts';
|
||||
import type { ComponentPropsWithoutRef, ForwardedRef } from 'react';
|
||||
import { forwardRef } from 'react';
|
||||
|
||||
import { UserStatus } from '../../../components/UserStatus';
|
||||
|
||||
const anon = {
|
||||
_id: '',
|
||||
username: 'Anonymous',
|
||||
status: 'online',
|
||||
avatarETag: undefined,
|
||||
} as const;
|
||||
|
||||
export type UserMenuButtonProps = ComponentPropsWithoutRef<typeof IconButton>;
|
||||
|
||||
const UserMenuButton = forwardRef(function UserMenuButton(props: UserMenuButtonProps, ref: ForwardedRef<HTMLElement>) {
|
||||
const user = useUser();
|
||||
|
||||
const { status = !user ? 'online' : 'offline', username, avatarETag } = user || anon;
|
||||
const presenceDisabled = useSetting('Presence_broadcast_disabled', false);
|
||||
|
||||
return (
|
||||
<IconButton
|
||||
{...props}
|
||||
ref={ref}
|
||||
position='relative'
|
||||
display='flex'
|
||||
flexDirection='column'
|
||||
overflow='visible'
|
||||
icon={username ? <UserAvatar size='x28' username={username} etag={avatarETag} /> : 'user'}
|
||||
>
|
||||
<Box
|
||||
position='absolute'
|
||||
role='status'
|
||||
className={css`
|
||||
bottom: 0;
|
||||
right: 0;
|
||||
transform: translate(30%, 30%);
|
||||
`}
|
||||
display='flex'
|
||||
justifyContent='center'
|
||||
alignItems='center'
|
||||
overflow='hidden'
|
||||
size='x12'
|
||||
borderWidth='default'
|
||||
backgroundColor='surface-tint'
|
||||
borderColor='extra-light'
|
||||
borderRadius='full'
|
||||
>
|
||||
<UserStatus small status={presenceDisabled ? 'disabled' : status} />
|
||||
</Box>
|
||||
</IconButton>
|
||||
);
|
||||
});
|
||||
|
||||
export default UserMenuButton;
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { IUser } from '@rocket.chat/core-typings';
|
||||
import { Box } from '@rocket.chat/fuselage';
|
||||
import { UserAvatar } from '@rocket.chat/ui-avatar';
|
||||
import { useUserDisplayName } from '@rocket.chat/ui-client';
|
||||
|
||||
export type UserMenuHeaderProps = { user: IUser };
|
||||
|
||||
const UserMenuHeader = ({ user }: UserMenuHeaderProps) => {
|
||||
const displayName = useUserDisplayName(user);
|
||||
|
||||
return (
|
||||
<Box display='flex' flexDirection='row' alignItems='center' minWidth='x208' marginBlockEnd='neg-x4' marginBlockStart='neg-x8'>
|
||||
<Box marginInlineEnd={4}>
|
||||
<UserAvatar size='x36' username={user?.username || ''} etag={user?.avatarETag} />
|
||||
</Box>
|
||||
<Box marginInlineStart={4} display='flex' overflow='hidden' flexDirection='column' fontScale='p2' flexGrow={1} flexShrink={1}>
|
||||
<Box withTruncatedText width='full' is='span' fontWeight='700'>
|
||||
{displayName}
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export default UserMenuHeader;
|
||||
@@ -0,0 +1,62 @@
|
||||
import { Badge } from '@rocket.chat/fuselage';
|
||||
import { useStableCallback } from '@rocket.chat/fuselage-hooks';
|
||||
import type { GenericMenuItemProps } from '@rocket.chat/ui-client';
|
||||
import { defaultFeaturesPreview, usePreferenceFeaturePreviewList } from '@rocket.chat/ui-client';
|
||||
import { useRouter } from '@rocket.chat/ui-contexts';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
export const useAccountItems = (): GenericMenuItemProps[] => {
|
||||
const { t } = useTranslation();
|
||||
const router = useRouter();
|
||||
|
||||
const { unseenFeatures, featurePreviewEnabled } = usePreferenceFeaturePreviewList();
|
||||
|
||||
const handleMyAccount = useStableCallback(() => {
|
||||
router.navigate('/account');
|
||||
});
|
||||
const handlePreferences = useStableCallback(() => {
|
||||
router.navigate('/account/preferences');
|
||||
});
|
||||
const handleFeaturePreview = useStableCallback(() => {
|
||||
router.navigate('/account/feature-preview');
|
||||
});
|
||||
const handleAccessibility = useStableCallback(() => {
|
||||
router.navigate('/account/accessibility-and-appearance');
|
||||
});
|
||||
|
||||
const featurePreviewItem = {
|
||||
id: 'feature-preview',
|
||||
icon: 'flask' as const,
|
||||
content: t('Feature_preview'),
|
||||
onClick: handleFeaturePreview,
|
||||
...(unseenFeatures > 0 && {
|
||||
addon: (
|
||||
<Badge variant='primary' aria-label={t('Unseen_features')}>
|
||||
{unseenFeatures}
|
||||
</Badge>
|
||||
),
|
||||
}),
|
||||
};
|
||||
|
||||
return [
|
||||
{
|
||||
id: 'profile',
|
||||
icon: 'user',
|
||||
content: t('Profile'),
|
||||
onClick: handleMyAccount,
|
||||
},
|
||||
{
|
||||
id: 'preferences',
|
||||
icon: 'customize',
|
||||
content: t('Preferences'),
|
||||
onClick: handlePreferences,
|
||||
},
|
||||
{
|
||||
id: 'accessibility',
|
||||
icon: 'person-arms-spread',
|
||||
content: t('Accessibility_and_Appearance'),
|
||||
onClick: handleAccessibility,
|
||||
},
|
||||
...(featurePreviewEnabled && defaultFeaturesPreview.length > 0 ? [featurePreviewItem] : []),
|
||||
];
|
||||
};
|
||||
@@ -0,0 +1,12 @@
|
||||
import { useSetModal } from '@rocket.chat/ui-contexts';
|
||||
|
||||
import EditStatusModal from '../EditStatusModal';
|
||||
|
||||
export const useCustomStatusModalHandler = () => {
|
||||
const setModal = useSetModal();
|
||||
|
||||
return () => {
|
||||
const handleModalClose = () => setModal(null);
|
||||
setModal(<EditStatusModal onClose={handleModalClose} />);
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,12 @@
|
||||
import { useSetModal } from '@rocket.chat/ui-contexts';
|
||||
|
||||
import KeyboardShortcutsModal from '../KeyboardShortcutsModal';
|
||||
|
||||
export const useKeyboardShortcutsModalHandler = () => {
|
||||
const setModal = useSetModal();
|
||||
|
||||
return () => {
|
||||
const handleModalClose = () => setModal(null);
|
||||
setModal(<KeyboardShortcutsModal onClose={handleModalClose} />);
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,189 @@
|
||||
import type { ICustomUserStatus, IUser, UserStatus as UserStatusEnum } from '@rocket.chat/core-typings';
|
||||
import { Box, Icon, RadioButton } from '@rocket.chat/fuselage';
|
||||
import type { GenericMenuItemProps } from '@rocket.chat/ui-client';
|
||||
import { clientCallbacks } from '@rocket.chat/ui-client';
|
||||
import { useEndpoint, useSetting, useStream } from '@rocket.chat/ui-contexts';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useCallback, useEffect, useMemo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useCustomStatusModalHandler } from './useCustomStatusModalHandler';
|
||||
import { useStatusVisibilityModalHandler } from './useStatusVisibilityModalHandler';
|
||||
import MarkdownText from '../../../../components/MarkdownText';
|
||||
import { UserStatus } from '../../../../components/UserStatus';
|
||||
import { useExpirationText } from '../../../../hooks/useExpirationText';
|
||||
import { useFireGlobalEvent } from '../../../../hooks/useFireGlobalEvent';
|
||||
import { userStatuses } from '../../../../lib/userStatuses';
|
||||
import type { UserStatusDescriptor } from '../../../../lib/userStatuses';
|
||||
import { mapCustomUserStatusFromApi } from '../../../../lib/utils/mapCustomUserStatusFromApi';
|
||||
import { useStatusDisabledModal } from '../../../../views/admin/customUserStatus/hooks/useStatusDisabledModal';
|
||||
|
||||
export const useStatusItems = (user?: IUser): GenericMenuItemProps[] => {
|
||||
// We should lift this up to somewhere else if we want to use it in other places
|
||||
|
||||
userStatuses.invisibleAllowed = useSetting('Accounts_AllowInvisibleStatusOption', true);
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
const stream = useStream('notify-logged');
|
||||
const listCustomUserStatusEndpoint = useEndpoint('GET', '/v1/custom-user-status.list');
|
||||
const listCustomUserStatus = useCallback(async (): Promise<ICustomUserStatus[]> => {
|
||||
const all: ICustomUserStatus[] = [];
|
||||
const count = 100;
|
||||
let offset = 0;
|
||||
// REST endpoint is paginated; loop until total reached.
|
||||
while (true) {
|
||||
const { statuses, total } = await listCustomUserStatusEndpoint({ count, offset });
|
||||
all.push(...statuses.map(mapCustomUserStatusFromApi));
|
||||
if (all.length >= total || statuses.length === 0) break;
|
||||
offset += statuses.length;
|
||||
}
|
||||
return all;
|
||||
}, [listCustomUserStatusEndpoint]);
|
||||
|
||||
useEffect(
|
||||
() =>
|
||||
userStatuses.watch(stream, () => {
|
||||
queryClient.setQueryData(['user-statuses'], Array.from(userStatuses));
|
||||
}),
|
||||
[queryClient, stream],
|
||||
);
|
||||
|
||||
const { t } = useTranslation();
|
||||
|
||||
const presenceDisabled = useSetting('Presence_broadcast_disabled', false);
|
||||
const allowUserStatusMessageChange = useSetting('Accounts_AllowUserStatusMessageChange', true);
|
||||
|
||||
const fireGlobalStatusEvent = useFireGlobalEvent('user-status-manually-set');
|
||||
const setStatus = useEndpoint('POST', '/v1/users.setStatus');
|
||||
const setStatusMutation = useMutation({
|
||||
mutationFn: async (status: UserStatusDescriptor) => {
|
||||
void setStatus({
|
||||
status: status.statusType,
|
||||
...(allowUserStatusMessageChange && { message: userStatuses.isValidType(status.id) ? '' : status.name }),
|
||||
});
|
||||
void clientCallbacks.run('userStatusManuallySet', status);
|
||||
await fireGlobalStatusEvent.mutateAsync(status);
|
||||
},
|
||||
});
|
||||
|
||||
const { data: statuses } = useQuery({
|
||||
queryKey: ['user-statuses'],
|
||||
queryFn: async () => {
|
||||
await userStatuses.sync(listCustomUserStatus);
|
||||
return Array.from(userStatuses);
|
||||
},
|
||||
staleTime: Infinity,
|
||||
});
|
||||
|
||||
const handleStatusDisabledModal = useStatusDisabledModal();
|
||||
const handleCustomStatus = useCustomStatusModalHandler();
|
||||
const handleStatusVisibility = useStatusVisibilityModalHandler();
|
||||
const statusVisibilityEnabled = useSetting('Accounts_StatusVisibility_Enabled', false);
|
||||
const customStatusExpiration = useExpirationText(user?.statusExpiresAt);
|
||||
|
||||
return useMemo<GenericMenuItemProps[]>(() => {
|
||||
if (presenceDisabled) {
|
||||
return [
|
||||
{
|
||||
id: 'presence-disabled',
|
||||
content: (
|
||||
<Box fontScale='p2'>
|
||||
<Box marginBlockEnd={4} wordBreak='break-word' style={{ whiteSpace: 'normal' }}>
|
||||
{t('User_status_disabled')}
|
||||
</Box>
|
||||
<Box is='a' color='info' onClick={handleStatusDisabledModal}>
|
||||
{t('Learn_more')}
|
||||
</Box>
|
||||
</Box>
|
||||
),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const items: GenericMenuItemProps[] = [];
|
||||
|
||||
// Top: user's currently-active custom status (display only — clicking does nothing, already selected).
|
||||
if (user?.statusText || customStatusExpiration) {
|
||||
const contentValue = user?.statusText || (user?.status ? t(user.status) : undefined);
|
||||
items.push({
|
||||
id: 'current-custom-status',
|
||||
status: <UserStatus status={user?.status} />,
|
||||
content: (
|
||||
<>
|
||||
{contentValue && <MarkdownText withTruncatedText content={contentValue} parseEmoji variant='inline' />}
|
||||
{customStatusExpiration && (
|
||||
<Box color='secondary-info' display='flex' alignItems='center'>
|
||||
<Icon name='clock' size='x16' marginInlineEnd={4} />
|
||||
{customStatusExpiration}
|
||||
</Box>
|
||||
)}
|
||||
</>
|
||||
),
|
||||
addon: <RadioButton checked readOnly />,
|
||||
});
|
||||
}
|
||||
|
||||
// "Custom..." action opens the edit modal
|
||||
if (allowUserStatusMessageChange) {
|
||||
items.push({
|
||||
id: 'custom-status-edit',
|
||||
icon: 'edit',
|
||||
content: t('Custom_Status'),
|
||||
onClick: handleCustomStatus,
|
||||
});
|
||||
}
|
||||
|
||||
const isPresetSelected = (statusType: UserStatusEnum): boolean =>
|
||||
!user?.statusText && !customStatusExpiration && user?.status === statusType;
|
||||
const presetItems = (statuses ?? [])
|
||||
.filter((s) => userStatuses.isValidType(s.id))
|
||||
.map((status): GenericMenuItemProps => ({
|
||||
id: status.id,
|
||||
status: <UserStatus status={status.statusType} />,
|
||||
content: <MarkdownText content={status.localizeName ? t(status.name) : status.name} parseEmoji variant='inline' />,
|
||||
addon: <RadioButton checked={isPresetSelected(status.statusType)} readOnly />,
|
||||
onClick: () => setStatusMutation.mutate(status),
|
||||
}));
|
||||
|
||||
// Admin-defined custom statuses
|
||||
const customItems = allowUserStatusMessageChange
|
||||
? (statuses ?? [])
|
||||
.filter((s) => !userStatuses.isValidType(s.id))
|
||||
.map((status): GenericMenuItemProps => ({
|
||||
id: status.id,
|
||||
status: <UserStatus status={status.statusType} />,
|
||||
content: (
|
||||
<MarkdownText withTruncatedText content={status.localizeName ? t(status.name) : status.name} parseEmoji variant='inline' />
|
||||
),
|
||||
addon: <RadioButton checked={user?.statusText === status.name} readOnly />,
|
||||
onClick: () => setStatusMutation.mutate(status),
|
||||
}))
|
||||
: [];
|
||||
|
||||
const actionItems: GenericMenuItemProps[] = [];
|
||||
|
||||
if (statusVisibilityEnabled) {
|
||||
actionItems.push({
|
||||
id: 'status-visibility-edit',
|
||||
icon: 'eye-off',
|
||||
content: t('Accounts_StatusVisibility_HideFrom'),
|
||||
onClick: handleStatusVisibility,
|
||||
});
|
||||
}
|
||||
|
||||
return [...items, ...presetItems, ...customItems, ...actionItems];
|
||||
}, [
|
||||
presenceDisabled,
|
||||
allowUserStatusMessageChange,
|
||||
t,
|
||||
handleStatusDisabledModal,
|
||||
user?.status,
|
||||
user?.statusText,
|
||||
customStatusExpiration,
|
||||
statuses,
|
||||
handleCustomStatus,
|
||||
handleStatusVisibility,
|
||||
statusVisibilityEnabled,
|
||||
setStatusMutation,
|
||||
]);
|
||||
};
|
||||
@@ -0,0 +1,9 @@
|
||||
import { useSetModal } from '@rocket.chat/ui-contexts';
|
||||
|
||||
import { EditStatusVisibilityModal } from '../EditStatusVisibilityModal';
|
||||
|
||||
export const useStatusVisibilityModalHandler = () => {
|
||||
const setModal = useSetModal();
|
||||
|
||||
return () => setModal(<EditStatusVisibilityModal onClose={() => setModal(null)} />);
|
||||
};
|
||||
@@ -0,0 +1,147 @@
|
||||
import { UIActionButtonContext } from '@rocket.chat/apps-engine/definition/ui';
|
||||
import { mockAppRoot } from '@rocket.chat/mock-providers';
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
|
||||
import { useUserMenu } from './useUserMenu';
|
||||
|
||||
// Mock userStatuses to avoid sdk.stream to call Meteor.connection.subscribe
|
||||
jest.mock('../../../../lib/userStatuses', () => ({
|
||||
userStatuses: {
|
||||
invisibleAllowed: true,
|
||||
watch: jest.fn(() => () => undefined),
|
||||
sync: jest.fn(() => Promise.resolve()),
|
||||
},
|
||||
}));
|
||||
|
||||
const fakeUser = {
|
||||
_id: 'john.doe',
|
||||
username: 'john.doe',
|
||||
name: 'John Doe',
|
||||
createdAt: new Date(),
|
||||
active: true,
|
||||
_updatedAt: new Date(),
|
||||
roles: ['admin'],
|
||||
type: 'user' as const,
|
||||
};
|
||||
|
||||
it('should return one action from the server with no conditions', async () => {
|
||||
const { result } = renderHook(() => useUserMenu(fakeUser), {
|
||||
wrapper: mockAppRoot()
|
||||
.withEndpoint('GET', '/apps/actionButtons', () => [
|
||||
{
|
||||
appId: 'APP_ID',
|
||||
actionId: 'ACTION_ID',
|
||||
labelI18n: 'LABEL_I18N',
|
||||
context: UIActionButtonContext.USER_DROPDOWN_ACTION,
|
||||
},
|
||||
])
|
||||
.build(),
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
const appsGroup = result.current.find((group) => group.title === 'Apps');
|
||||
expect(appsGroup).toBeDefined();
|
||||
expect(appsGroup?.items).toContainEqual(expect.objectContaining({ id: 'APP_ID_ACTION_ID' }));
|
||||
});
|
||||
});
|
||||
|
||||
describe('user menu with role conditions', () => {
|
||||
it('should return the action if the user has admin role', async () => {
|
||||
const { result } = renderHook(() => useUserMenu(fakeUser), {
|
||||
wrapper: mockAppRoot()
|
||||
.withJohnDoe()
|
||||
.withEndpoint('GET', '/apps/actionButtons', () => [
|
||||
{
|
||||
appId: 'APP_ID',
|
||||
actionId: 'ACTION_ID',
|
||||
labelI18n: 'LABEL_I18N',
|
||||
context: UIActionButtonContext.USER_DROPDOWN_ACTION,
|
||||
when: {
|
||||
hasOneRole: ['admin'],
|
||||
},
|
||||
},
|
||||
])
|
||||
.withRole('admin')
|
||||
.build(),
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
const appsGroup = result.current.find((group) => group.title === 'Apps');
|
||||
expect(appsGroup).toBeDefined();
|
||||
expect(appsGroup?.items).toContainEqual(expect.objectContaining({ id: 'APP_ID_ACTION_ID' }));
|
||||
});
|
||||
});
|
||||
|
||||
it('should filter out the action if the user does not have admin role', async () => {
|
||||
const { result } = renderHook(() => useUserMenu(fakeUser), {
|
||||
wrapper: mockAppRoot()
|
||||
.withEndpoint('GET', '/apps/actionButtons', () => [
|
||||
{
|
||||
appId: 'APP_ID',
|
||||
actionId: 'ACTION_ID',
|
||||
labelI18n: 'LABEL_I18N',
|
||||
context: UIActionButtonContext.USER_DROPDOWN_ACTION,
|
||||
when: {
|
||||
hasOneRole: ['admin'],
|
||||
},
|
||||
},
|
||||
])
|
||||
.build(),
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
const appsGroup = result.current.find((group) => group.title === 'Apps');
|
||||
expect(appsGroup).not.toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('user menu with permission conditions', () => {
|
||||
it('should return the action if the user has manage-apps permission', async () => {
|
||||
const { result } = renderHook(() => useUserMenu(fakeUser), {
|
||||
wrapper: mockAppRoot()
|
||||
.withEndpoint('GET', '/apps/actionButtons', () => [
|
||||
{
|
||||
appId: 'APP_ID',
|
||||
actionId: 'ACTION_ID',
|
||||
labelI18n: 'LABEL_I18N',
|
||||
context: UIActionButtonContext.USER_DROPDOWN_ACTION,
|
||||
when: {
|
||||
hasOnePermission: ['manage-apps'],
|
||||
},
|
||||
},
|
||||
])
|
||||
.withPermission('manage-apps')
|
||||
.build(),
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
const appsGroup = result.current.find((group) => group.title === 'Apps');
|
||||
expect(appsGroup).toBeDefined();
|
||||
expect(appsGroup?.items).toContainEqual(expect.objectContaining({ id: 'APP_ID_ACTION_ID' }));
|
||||
});
|
||||
});
|
||||
|
||||
it('should filter out the action if the user does not have any permission', async () => {
|
||||
const { result } = renderHook(() => useUserMenu(fakeUser), {
|
||||
wrapper: mockAppRoot()
|
||||
.withEndpoint('GET', '/apps/actionButtons', () => [
|
||||
{
|
||||
appId: 'APP_ID',
|
||||
actionId: 'ACTION_ID',
|
||||
labelI18n: 'LABEL_I18N',
|
||||
context: UIActionButtonContext.USER_DROPDOWN_ACTION,
|
||||
when: {
|
||||
hasOnePermission: ['any'],
|
||||
},
|
||||
},
|
||||
])
|
||||
.build(),
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
const appsGroup = result.current.find((group) => group.title === 'Apps');
|
||||
expect(appsGroup).not.toBeDefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import type { IUser } from '@rocket.chat/core-typings';
|
||||
import { useStableCallback } from '@rocket.chat/fuselage-hooks';
|
||||
import type { GenericMenuItemProps } from '@rocket.chat/ui-client';
|
||||
import { useLogout } from '@rocket.chat/ui-contexts';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import UserMenuHeader from '../UserMenuHeader';
|
||||
import { useAccountItems } from './useAccountItems';
|
||||
import { useKeyboardShortcutsModalHandler } from './useKeyboardShortcutsModalHandler';
|
||||
import { useStatusItems } from './useStatusItems';
|
||||
import { useUserDropdownAppsActionButtons } from '../../../../hooks/useUserDropdownAppsActionButtons';
|
||||
|
||||
export const useUserMenu = (user: IUser) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const statusItems = useStatusItems(user);
|
||||
const accountItems = useAccountItems();
|
||||
const appBoxItems = useUserDropdownAppsActionButtons();
|
||||
const handleKeyboardShortcuts = useKeyboardShortcutsModalHandler();
|
||||
|
||||
const logout = useLogout();
|
||||
const handleLogout = useStableCallback(() => {
|
||||
logout();
|
||||
});
|
||||
|
||||
const keyboardShortcutsItem: GenericMenuItemProps = {
|
||||
id: 'keyboardShortcuts',
|
||||
icon: 'keyboard',
|
||||
content: t('Keyboard_Shortcuts_Title'),
|
||||
onClick: handleKeyboardShortcuts,
|
||||
};
|
||||
|
||||
const logoutItem: GenericMenuItemProps = {
|
||||
id: 'logout',
|
||||
icon: 'sign-out',
|
||||
content: t('Logout'),
|
||||
onClick: handleLogout,
|
||||
};
|
||||
|
||||
return [
|
||||
{
|
||||
title: <UserMenuHeader user={user} />,
|
||||
items: [],
|
||||
},
|
||||
{
|
||||
title: t('Status'),
|
||||
items: statusItems,
|
||||
},
|
||||
{
|
||||
title: t('Account'),
|
||||
items: accountItems,
|
||||
},
|
||||
{
|
||||
items: [keyboardShortcutsItem],
|
||||
},
|
||||
...(appBoxItems.isSuccess && appBoxItems.data?.length ? [{ title: t('Apps'), items: appBoxItems.data }] : []),
|
||||
{
|
||||
items: [logoutItem],
|
||||
},
|
||||
].filter((section) => section !== undefined);
|
||||
};
|
||||
@@ -0,0 +1 @@
|
||||
export { default } from './UserMenu';
|
||||
@@ -0,0 +1,54 @@
|
||||
import { mockAppRoot } from '@rocket.chat/mock-providers';
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
|
||||
import { useAdministrationMenu } from './useAdministrationMenu';
|
||||
|
||||
it('should return omnichannel item if has `view-livechat-manager` permission', async () => {
|
||||
const { result } = renderHook(() => useAdministrationMenu(), {
|
||||
wrapper: mockAppRoot()
|
||||
.withEndpoint('GET', '/v1/licenses.info', () => ({
|
||||
// @ts-expect-error this is a mock
|
||||
license: {},
|
||||
}))
|
||||
.withEndpoint('GET', '/v1/cloud.registrationStatus', () => ({
|
||||
registrationStatus: {
|
||||
workspaceRegistered: false,
|
||||
} as any,
|
||||
}))
|
||||
.withPermission('view-livechat-manager')
|
||||
.build(),
|
||||
});
|
||||
|
||||
await waitFor(() =>
|
||||
expect(result.current.items[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
id: 'omnichannel',
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('should show administration item if has at least one admin permission', async () => {
|
||||
const { result } = renderHook(() => useAdministrationMenu(), {
|
||||
wrapper: mockAppRoot()
|
||||
.withEndpoint('GET', '/v1/licenses.info', () => ({
|
||||
// @ts-expect-error this is a mock
|
||||
license: {},
|
||||
}))
|
||||
.withEndpoint('GET', '/v1/cloud.registrationStatus', () => ({
|
||||
registrationStatus: {
|
||||
workspaceRegistered: false,
|
||||
} as any,
|
||||
}))
|
||||
.withPermission('access-permissions')
|
||||
.build(),
|
||||
});
|
||||
|
||||
await waitFor(() =>
|
||||
expect(result.current.items[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
id: 'workspace',
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { GenericMenuItemProps } from '@rocket.chat/ui-client';
|
||||
import { useAtLeastOnePermission, usePermission, useRouter } from '@rocket.chat/ui-contexts';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
const ADMIN_PERMISSIONS = [
|
||||
'view-statistics',
|
||||
'run-import',
|
||||
'view-user-administration',
|
||||
'view-room-administration',
|
||||
'create-invite-links',
|
||||
'manage-cloud',
|
||||
'view-logs',
|
||||
'manage-sounds',
|
||||
'view-federation-data',
|
||||
'manage-email-inbox',
|
||||
'manage-emoji',
|
||||
'manage-outgoing-integrations',
|
||||
'manage-own-outgoing-integrations',
|
||||
'manage-incoming-integrations',
|
||||
'manage-own-incoming-integrations',
|
||||
'manage-oauth-apps',
|
||||
'access-mailer',
|
||||
'manage-user-status',
|
||||
'access-permissions',
|
||||
'access-setting-permissions',
|
||||
'view-privileged-setting',
|
||||
'edit-privileged-setting',
|
||||
'manage-selected-settings',
|
||||
'view-engagement-dashboard',
|
||||
'view-moderation-console',
|
||||
];
|
||||
|
||||
export const useAdministrationMenu = () => {
|
||||
const router = useRouter();
|
||||
const { t } = useTranslation();
|
||||
|
||||
const isAdmin = useAtLeastOnePermission(ADMIN_PERMISSIONS);
|
||||
const isOmnichannel = usePermission('view-livechat-manager');
|
||||
|
||||
const workspace: GenericMenuItemProps = {
|
||||
id: 'workspace',
|
||||
content: t('Workspace'),
|
||||
onClick: () => router.navigate('/admin'),
|
||||
};
|
||||
const omnichannel: GenericMenuItemProps = {
|
||||
id: 'omnichannel',
|
||||
content: t('Omnichannel'),
|
||||
onClick: () => router.navigate('/omnichannel'),
|
||||
};
|
||||
|
||||
return {
|
||||
title: t('Manage'),
|
||||
items: [isAdmin && workspace, isOmnichannel && omnichannel].filter(Boolean) as GenericMenuItemProps[],
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,158 @@
|
||||
import { mockAppRoot } from '@rocket.chat/mock-providers';
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
|
||||
import { useAuditMenu } from './useAuditMenu';
|
||||
|
||||
it('should return an empty array of items if doesn`t have license', async () => {
|
||||
const { result } = renderHook(() => useAuditMenu(), {
|
||||
wrapper: mockAppRoot()
|
||||
.withEndpoint('GET', '/v1/licenses.info', () => ({
|
||||
// @ts-expect-error: just for testing
|
||||
license: {
|
||||
activeModules: [],
|
||||
},
|
||||
}))
|
||||
.withJohnDoe()
|
||||
.withPermission('can-audit')
|
||||
.withPermission('can-audit-log')
|
||||
.build(),
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.items).toEqual([]));
|
||||
});
|
||||
|
||||
it('should return an empty array of items if have license and not have permissions', async () => {
|
||||
const { result } = renderHook(() => useAuditMenu(), {
|
||||
wrapper: mockAppRoot()
|
||||
.withEndpoint('GET', '/v1/licenses.info', () => ({
|
||||
license: {
|
||||
license: {
|
||||
// @ts-expect-error: just for testing
|
||||
grantedModules: [{ module: 'auditing' }],
|
||||
},
|
||||
// @ts-expect-error: just for testing
|
||||
activeModules: ['auditing'],
|
||||
},
|
||||
}))
|
||||
.withMethod('license:getModules', () => ['auditing'])
|
||||
.withJohnDoe()
|
||||
.build(),
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.items).toEqual([]));
|
||||
});
|
||||
|
||||
it('should return auditItems if have license and permissions', async () => {
|
||||
const { result } = renderHook(() => useAuditMenu(), {
|
||||
wrapper: mockAppRoot()
|
||||
.withEndpoint('GET', '/v1/licenses.info', () => ({
|
||||
license: {
|
||||
license: {
|
||||
// @ts-expect-error: just for testing
|
||||
grantedModules: [{ module: 'auditing' }],
|
||||
},
|
||||
// @ts-expect-error: just for testing
|
||||
activeModules: ['auditing'],
|
||||
},
|
||||
}))
|
||||
.withJohnDoe()
|
||||
.withPermission('can-audit')
|
||||
.withPermission('can-audit-log')
|
||||
.build(),
|
||||
});
|
||||
|
||||
await waitFor(() =>
|
||||
expect(result.current.items[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
id: 'messages',
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
expect(result.current.items[1]).toEqual(
|
||||
expect.objectContaining({
|
||||
id: 'auditLog',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should return auditMessages item if have license and can-audit permission', async () => {
|
||||
const { result } = renderHook(() => useAuditMenu(), {
|
||||
wrapper: mockAppRoot()
|
||||
.withEndpoint('GET', '/v1/licenses.info', () => ({
|
||||
license: {
|
||||
license: {
|
||||
// @ts-expect-error: just for testing
|
||||
grantedModules: [{ module: 'auditing' }],
|
||||
},
|
||||
// @ts-expect-error: just for testing
|
||||
activeModules: ['auditing'],
|
||||
},
|
||||
}))
|
||||
.withJohnDoe()
|
||||
.withPermission('can-audit')
|
||||
.build(),
|
||||
});
|
||||
|
||||
await waitFor(() =>
|
||||
expect(result.current.items[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
id: 'messages',
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('should return audiLogs item if have license and can-audit-log permission', async () => {
|
||||
const { result } = renderHook(() => useAuditMenu(), {
|
||||
wrapper: mockAppRoot()
|
||||
.withEndpoint('GET', '/v1/licenses.info', () => ({
|
||||
license: {
|
||||
license: {
|
||||
// @ts-expect-error: just for testing
|
||||
grantedModules: [{ module: 'auditing' }],
|
||||
},
|
||||
// @ts-expect-error: just for testing
|
||||
activeModules: ['auditing'],
|
||||
},
|
||||
}))
|
||||
.withJohnDoe()
|
||||
.withPermission('can-audit-log')
|
||||
.build(),
|
||||
});
|
||||
|
||||
await waitFor(() =>
|
||||
expect(result.current.items[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
id: 'auditLog',
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('should return auditSecurityLog item if have license and can-audit-log permission', async () => {
|
||||
const { result } = renderHook(() => useAuditMenu(), {
|
||||
wrapper: mockAppRoot()
|
||||
.withEndpoint('GET', '/v1/licenses.info', () => ({
|
||||
license: {
|
||||
license: {
|
||||
// @ts-expect-error: just for testing
|
||||
grantedModules: [{ module: 'auditing' }],
|
||||
},
|
||||
// @ts-expect-error: just for testing
|
||||
activeModules: ['auditing'],
|
||||
},
|
||||
}))
|
||||
.withJohnDoe()
|
||||
.withPermission('can-audit')
|
||||
.build(),
|
||||
});
|
||||
|
||||
await waitFor(() =>
|
||||
expect(result.current.items[1]).toEqual(
|
||||
expect.objectContaining({
|
||||
id: 'auditSecurityLog',
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import type { GenericMenuItemProps } from '@rocket.chat/ui-client';
|
||||
import { usePermission, useRouter } from '@rocket.chat/ui-contexts';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { useHasLicenseModule } from '../../../hooks/useHasLicenseModule';
|
||||
|
||||
export const useAuditMenu = () => {
|
||||
const router = useRouter();
|
||||
const { t } = useTranslation();
|
||||
|
||||
const { data: hasAuditLicense = false } = useHasLicenseModule('auditing');
|
||||
|
||||
const hasAuditPermission = usePermission('can-audit') && hasAuditLicense;
|
||||
const hasAuditLogPermission = usePermission('can-audit-log') && hasAuditLicense;
|
||||
|
||||
const auditMessageItem: GenericMenuItemProps = {
|
||||
id: 'messages',
|
||||
content: t('Messages'),
|
||||
onClick: () => router.navigate('/audit'),
|
||||
};
|
||||
|
||||
const auditLogItem: GenericMenuItemProps = {
|
||||
id: 'auditLog',
|
||||
content: t('Logs'),
|
||||
onClick: () => router.navigate('/audit-log'),
|
||||
};
|
||||
|
||||
const auditSecurityLogsItem: GenericMenuItemProps = {
|
||||
id: 'auditSecurityLog',
|
||||
content: t('Security_logs'),
|
||||
onClick: () => router.navigate('/security-logs'),
|
||||
};
|
||||
|
||||
return {
|
||||
title: t('Audit'),
|
||||
items: [
|
||||
hasAuditPermission && auditMessageItem,
|
||||
hasAuditLogPermission && auditLogItem,
|
||||
hasAuditPermission && auditSecurityLogsItem,
|
||||
].filter(Boolean) as GenericMenuItemProps[],
|
||||
};
|
||||
};
|
||||
3
apps/meteor/client/navbar/NavBarSettingsToolbar/index.ts
Normal file
3
apps/meteor/client/navbar/NavBarSettingsToolbar/index.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
export { default as NavBarItemAdministrationMenu } from './NavBarItemAdministrationMenu';
|
||||
export { default as NavBarItemLoginPage } from './NavBarItemLoginPage';
|
||||
export { default as UserMenu } from './UserMenu';
|
||||
@@ -0,0 +1,27 @@
|
||||
import { NavBarGroup, NavBarItem } from '@rocket.chat/fuselage';
|
||||
import { useRouter } from '@rocket.chat/ui-contexts';
|
||||
import { useMediaCallAction } from '@rocket.chat/ui-voip';
|
||||
import { useCallback } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
const NavBarVoipGroup = () => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const callAction = useMediaCallAction();
|
||||
const router = useRouter();
|
||||
const openCallHistory = useCallback(() => {
|
||||
router.navigate('/call-history');
|
||||
}, [router]);
|
||||
if (!callAction) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<NavBarGroup aria-label={t('Voice_Call')}>
|
||||
<NavBarItem title={callAction.title} icon={callAction.icon} onClick={() => callAction.action()} />
|
||||
<NavBarItem title={t('Call_history')} icon='clock' onClick={openCallHistory} />
|
||||
</NavBarGroup>
|
||||
);
|
||||
};
|
||||
|
||||
export default NavBarVoipGroup;
|
||||
1
apps/meteor/client/navbar/NavBarVoipGroup/index.ts
Normal file
1
apps/meteor/client/navbar/NavBarVoipGroup/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { default } from './NavBarVoipGroup';
|
||||
1
apps/meteor/client/navbar/index.ts
Normal file
1
apps/meteor/client/navbar/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { default } from './NavBar';
|
||||
Reference in New Issue
Block a user