Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,14 @@ import {
SidebarSettingsFlags,
} from '../../../graphql/settings';

const mockSubscribe = jest.fn().mockResolvedValue(undefined);
const mockUnsubscribe = jest.fn().mockResolvedValue(undefined);
const mockDisplayToast = jest.fn();
const mockUseAuth = jest.fn();
const mockUseConditionalFeature = jest.fn();
const mockUseMajorHeadlinesSubscription = jest.fn();
const mockRouterPush = jest.fn();
const mockUpdateFlag = jest.fn().mockResolvedValue(undefined);
const mockUseSettingsContext = jest.fn();
const mockLogEvent = jest.fn();
const mockInvalidateQueries = jest.fn().mockResolvedValue(undefined);
const mockUseActiveFeedContext = jest.fn();

jest.mock('next/router', () => ({
useRouter: () => ({ push: mockRouterPush }),
}));

jest.mock('@tanstack/react-query', () => ({
...(jest.requireActual('@tanstack/react-query') as Iterable<unknown>),
useQueryClient: () => ({ invalidateQueries: mockInvalidateQueries }),
Expand All @@ -45,14 +36,6 @@ jest.mock('../../../contexts/LogContext', () => ({
useLogContext: () => ({ logEvent: mockLogEvent }),
}));

jest.mock('../../../hooks/useConditionalFeature', () => ({
useConditionalFeature: () => mockUseConditionalFeature(),
}));

jest.mock('../../../hooks/notifications/useMajorHeadlinesSubscription', () => ({
useMajorHeadlinesSubscription: () => mockUseMajorHeadlinesSubscription(),
}));

jest.mock('../../../hooks/useToastNotification', () => ({
useToastNotification: () => ({ displayToast: mockDisplayToast }),
}));
Expand Down Expand Up @@ -83,13 +66,6 @@ describe('HighlightCardOptions', () => {
beforeEach(() => {
jest.clearAllMocks();
mockUseAuth.mockReturnValue({ user: { id: '1' } });
mockUseConditionalFeature.mockReturnValue({ value: true });
mockUseMajorHeadlinesSubscription.mockReturnValue({
isSubscribed: false,
isLoading: false,
subscribe: mockSubscribe,
unsubscribe: mockUnsubscribe,
});
mockUseSettingsContext.mockReturnValue({
flags: { highlightsPlacement: HighlightsPlacement.Default },
updateFlag: mockUpdateFlag,
Expand All @@ -100,16 +76,13 @@ describe('HighlightCardOptions', () => {
});
});

it('should render the options menu with all items when feature is on and user is logged in', () => {
it('should render the placement options when the user is logged in', () => {
renderComponent();

expect(
screen.getByRole('button', { name: 'Pin to top' }),
).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Disable' })).toBeInTheDocument();
expect(
screen.getByRole('button', { name: 'Get real-time alerts' }),
).toBeInTheDocument();
});

it('should not render for guests', () => {
Expand All @@ -118,17 +91,7 @@ describe('HighlightCardOptions', () => {
renderComponent();

expect(
screen.queryByRole('button', { name: 'Get real-time alerts' }),
).not.toBeInTheDocument();
});

it('should not render when feature is off', () => {
mockUseConditionalFeature.mockReturnValue({ value: false });

renderComponent();

expect(
screen.queryByRole('button', { name: 'Get real-time alerts' }),
screen.queryByRole('button', { name: 'Pin to top' }),
).not.toBeInTheDocument();
});

Expand Down Expand Up @@ -196,65 +159,4 @@ describe('HighlightCardOptions', () => {
);
});
});

it('should subscribe and show toast with settings action when not subscribed', async () => {
renderComponent();

fireEvent.click(
screen.getByRole('button', { name: 'Get real-time alerts' }),
);

await waitFor(() => {
expect(mockSubscribe).toHaveBeenCalledWith('feed_card');
});
await waitFor(() => {
expect(mockDisplayToast).toHaveBeenCalledWith(
"You'll be the first to know when news breaks.",
expect.objectContaining({
action: expect.objectContaining({ copy: 'Settings' }),
}),
);
});
});

it('should navigate to notification settings when toast action is clicked', async () => {
renderComponent();

fireEvent.click(
screen.getByRole('button', { name: 'Get real-time alerts' }),
);

await waitFor(() => {
expect(mockDisplayToast).toHaveBeenCalled();
});

const toastArgs = mockDisplayToast.mock.calls[0][1];
toastArgs.action.onClick();

expect(mockRouterPush).toHaveBeenCalledWith('/settings/notifications');
});

it('should unsubscribe when subscribed', async () => {
mockUseMajorHeadlinesSubscription.mockReturnValue({
isSubscribed: true,
isLoading: false,
subscribe: mockSubscribe,
unsubscribe: mockUnsubscribe,
});

renderComponent();

fireEvent.click(
screen.getByRole('button', { name: 'Turn off real-time alerts' }),
);

await waitFor(() => {
expect(mockUnsubscribe).toHaveBeenCalledWith('feed_card');
});
await waitFor(() => {
expect(mockDisplayToast).toHaveBeenCalledWith(
'Real-time alerts turned off.',
);
});
});
});
Original file line number Diff line number Diff line change
@@ -1,30 +1,19 @@
import type { ReactElement } from 'react';
import React, { useMemo, useState } from 'react';
import React, { useState } from 'react';
import classNames from 'classnames';
import { useRouter } from 'next/router';
import { useQueryClient } from '@tanstack/react-query';
import { Button, ButtonSize, ButtonVariant } from '../../buttons/Button';
import {
BellAddIcon,
BellSubscribedIcon,
EyeCancelIcon,
MenuIcon as KebabIcon,
PinIcon,
} from '../../icons';
import { EyeCancelIcon, MenuIcon as KebabIcon, PinIcon } from '../../icons';
import { MenuIcon } from '../../MenuIcon';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuOptions,
DropdownMenuTrigger,
} from '../../dropdown/DropdownMenu';
import type { MenuItemProps } from '../../dropdown/common';
import { useActiveFeedContext } from '../../../contexts/ActiveFeedContext';
import { useAuthContext } from '../../../contexts/AuthContext';
import { useSettingsContext } from '../../../contexts/SettingsContext';
import { useMajorHeadlinesSubscription } from '../../../hooks/notifications/useMajorHeadlinesSubscription';
import { useConditionalFeature } from '../../../hooks/useConditionalFeature';
import { featureMajorHeadlinesPush } from '../../../lib/featureManagement';
import { useToastNotification } from '../../../hooks/useToastNotification';
import { useLogContext } from '../../../contexts/LogContext';
import {
Expand All @@ -34,27 +23,21 @@ import {
import { LogEvent, Origin } from '../../../lib/log';
import { labels } from '../../../lib';

const NOTIFICATION_SETTINGS_PATH = '/settings/notifications';

interface HighlightCardOptionsProps {
className?: string;
}

const HighlightCardOptionsContent = ({
className,
}: HighlightCardOptionsProps): ReactElement => {
const router = useRouter();
const [isPending, setIsPending] = useState(false);
const { displayToast } = useToastNotification();
const { logEvent } = useLogContext();
const { flags, updateFlag } = useSettingsContext();
const queryClient = useQueryClient();
const { queryKey: feedQueryKey } = useActiveFeedContext();
const { isSubscribed, isLoading, subscribe, unsubscribe } =
useMajorHeadlinesSubscription();

const placement = flags?.highlightsPlacement ?? HighlightsPlacement.Default;
const isPinned = placement === HighlightsPlacement.Pinned;
const isPinned = flags?.highlightsPlacement === HighlightsPlacement.Pinned;

const updatePlacement = async (next: HighlightsPlacement) => {
if (isPending) {
Expand All @@ -79,59 +62,6 @@ const HighlightCardOptionsContent = ({
}
};

const toggleSubscription = async () => {
if (isPending || isLoading) {
return;
}
setIsPending(true);
try {
if (isSubscribed) {
await unsubscribe('feed_card');
displayToast('Real-time alerts turned off.');
return;
}
await subscribe('feed_card');
displayToast("You'll be the first to know when news breaks.", {
action: {
copy: 'Settings',
onClick: () => router.push(NOTIFICATION_SETTINGS_PATH),
},
});
} finally {
setIsPending(false);
}
};

const options = useMemo<MenuItemProps[]>(() => {
const SubscribeIcon = isSubscribed ? BellSubscribedIcon : BellAddIcon;
return [
{
label: isPinned ? 'Unpin from top' : 'Pin to top',
icon: <MenuIcon Icon={PinIcon} />,
action: () =>
updatePlacement(
isPinned ? HighlightsPlacement.Default : HighlightsPlacement.Pinned,
),
disabled: isPending,
},
{
label: 'Disable',
icon: <MenuIcon Icon={EyeCancelIcon} />,
action: () => updatePlacement(HighlightsPlacement.Disabled),
disabled: isPending,
},
{
label: isSubscribed
? 'Turn off real-time alerts'
: 'Get real-time alerts',
icon: <MenuIcon Icon={SubscribeIcon} />,
action: toggleSubscription,
disabled: isPending || isLoading,
},
];
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isPinned, isSubscribed, isPending, isLoading]);

return (
<DropdownMenu>
<DropdownMenuTrigger tooltip={{ content: 'Options' }} asChild>
Expand All @@ -147,7 +77,27 @@ const HighlightCardOptionsContent = ({
/>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuOptions options={options} />
<DropdownMenuOptions
options={[
{
label: isPinned ? 'Unpin from top' : 'Pin to top',
icon: <MenuIcon Icon={PinIcon} />,
action: () =>
updatePlacement(
isPinned
? HighlightsPlacement.Default
: HighlightsPlacement.Pinned,
),
disabled: isPending,
},
{
label: 'Disable',
icon: <MenuIcon Icon={EyeCancelIcon} />,
action: () => updatePlacement(HighlightsPlacement.Disabled),
disabled: isPending,
},
]}
/>
</DropdownMenuContent>
</DropdownMenu>
);
Expand All @@ -157,13 +107,8 @@ export const HighlightCardOptions = ({
className,
}: HighlightCardOptionsProps): ReactElement | null => {
const auth = useAuthContext();
const user = auth?.user;
const { value: isFeatureEnabled } = useConditionalFeature({
feature: featureMajorHeadlinesPush,
shouldEvaluate: !!user,
});

if (!isFeatureEnabled || !user) {
if (!auth?.user) {
return null;
}

Expand Down
Loading
Loading