index
int64 0
0
| repo_id
stringlengths 16
181
| file_path
stringlengths 28
270
| content
stringlengths 1
11.6M
| __index_level_0__
int64 0
10k
|
|---|---|---|---|---|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/search
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/search/AdvancedSearchFields/SearchField.tsx
|
import { ChangeEventHandler, MouseEventHandler, ReactNode, forwardRef } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { Icon, InputFieldTwo } from '@proton/components';
interface Props {
onSubmit: MouseEventHandler<HTMLButtonElement>;
onChange: ChangeEventHandler<HTMLInputElement>;
value: string;
showSearchIcon?: boolean;
suffix?: ReactNode;
unstyled?: boolean;
esEnabled: boolean;
}
const SearchField = (
{ onSubmit, onChange, value, showSearchIcon = true, suffix, unstyled, esEnabled }: Props,
ref: React.Ref<HTMLInputElement>
) => (
<div className="relative flex-item-fluid">
<InputFieldTwo
id="search-keyword"
unstyled={unstyled}
title={c('Label').t`Keyword`}
prefix={
showSearchIcon && (
<Button onClick={onSubmit} shape="ghost" color="weak" size="small" icon>
<Icon name="magnifier" alt={c('action').t`Search messages`} />
</Button>
)
}
dense
placeholder={
esEnabled
? c('Placeholder').t`Search messages`
: c('Placeholder').t`Search date, name, email address, or subject line`
}
value={value}
autoFocus
onChange={onChange}
data-shorcut-target="searchbox-field"
suffix={suffix}
ref={ref}
/>
</div>
);
export default forwardRef(SearchField);
| 3,500
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/search
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/search/AdvancedSearchFields/useLocationFieldOptions.test.data.ts
|
import { ItemsGroup } from './useLocationFieldOptions';
export const expectedAll = [
{
value: '5',
text: 'All mail',
url: '/all-mail',
icon: 'envelopes',
},
{
value: '0',
text: 'Inbox',
url: '/inbox',
icon: 'inbox',
},
{
icon: 'clock',
text: 'Snooze',
url: '/snoozed',
value: '16',
},
{
value: '8',
text: 'Drafts',
url: '/drafts',
icon: 'file-lines',
},
{
value: '7',
text: 'Sent',
url: '/sent',
icon: 'paper-plane-horizontal',
},
{
value: '10',
text: 'Starred',
url: '/starred',
icon: 'star',
},
{
value: '6',
text: 'Archive',
url: '/archive',
icon: 'archive-box',
},
{
value: '4',
text: 'Spam',
url: '/spam',
icon: 'fire',
},
{
value: '3',
text: 'Trash',
url: '/trash',
icon: 'trash',
},
{
text: 'news',
value: '31dixxUc6tNkpKrI-abC_IQcnG4_K2brHumXkQb_Ib4-FEl5Q3n27dbhIkfBTnYrNonJ8DsySBbUM0RtQdhYhA==',
className: '',
folderEntity: {
ID: '31dixxUc6tNkpKrI-abC_IQcnG4_K2brHumXkQb_Ib4-FEl5Q3n27dbhIkfBTnYrNonJ8DsySBbUM0RtQdhYhA==',
Name: 'news',
Path: 'news',
Type: 3,
Color: '#54473f',
Order: 1,
Notify: 1,
Expanded: 0,
subfolders: [],
},
},
{
value: 'highlighted',
text: 'highlighted',
url: 'highlighted',
color: '#EC3E7C',
},
];
export const expectedGrouped: ItemsGroup = [
{
id: 'DEFAULT_FOLDERS',
title: 'Default folders',
items: [
{
value: '5',
text: 'All mail',
url: '/all-mail',
icon: 'envelopes',
},
{
value: '0',
text: 'Inbox',
url: '/inbox',
icon: 'inbox',
},
{
icon: 'clock',
text: 'Snooze',
url: '/snoozed',
value: '16',
},
{
value: '8',
text: 'Drafts',
url: '/drafts',
icon: 'file-lines',
},
{
value: '7',
text: 'Sent',
url: '/sent',
icon: 'paper-plane-horizontal',
},
{
value: '10',
text: 'Starred',
url: '/starred',
icon: 'star',
},
{
value: '6',
text: 'Archive',
url: '/archive',
icon: 'archive-box',
},
{
value: '4',
text: 'Spam',
url: '/spam',
icon: 'fire',
},
{
value: '3',
text: 'Trash',
url: '/trash',
icon: 'trash',
},
],
},
{
id: 'CUSTOM_FOLDERS',
title: 'Custom folders',
items: [
{
text: 'news',
value: '31dixxUc6tNkpKrI-abC_IQcnG4_K2brHumXkQb_Ib4-FEl5Q3n27dbhIkfBTnYrNonJ8DsySBbUM0RtQdhYhA==',
className: '',
folderEntity: {
ID: '31dixxUc6tNkpKrI-abC_IQcnG4_K2brHumXkQb_Ib4-FEl5Q3n27dbhIkfBTnYrNonJ8DsySBbUM0RtQdhYhA==',
Name: 'news',
Path: 'news',
Type: 3,
Color: '#54473f',
Order: 1,
Notify: 1,
Expanded: 0,
subfolders: [],
},
},
],
},
{
id: 'LABELS',
title: 'Labels',
items: [
{
value: 'highlighted',
text: 'highlighted',
url: 'highlighted',
color: '#EC3E7C',
},
],
},
];
| 3,501
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/search
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/search/AdvancedSearchFields/useLocationFieldOptions.test.ts
|
import { ALMOST_ALL_MAIL } from '@proton/shared/lib/mail/mailSettings';
import { mockUseFolders, mockUseLabels, mockUseMailSettings } from '@proton/testing/index';
import { mockUseScheduleSendFeature } from 'proton-mail/helpers/test/mockUseScheduleSendFeature';
import { useLocationFieldOptions } from './useLocationFieldOptions';
import { expectedAll, expectedGrouped } from './useLocationFieldOptions.test.data';
jest.mock('proton-mail/hooks/actions/useSnooze', () => ({
__esModule: true,
default: jest.fn().mockReturnValue({
canSnooze: true,
canUnsnooze: true,
isSnoozeEnabled: true,
snooze: jest.fn(),
unsnooze: jest.fn(),
handleClose: jest.fn(),
handleCustomClick: jest.fn(),
snoozeState: 'snooze-selection',
}),
}));
describe('useLocationFieldOptions', () => {
beforeEach(() => {
mockUseMailSettings();
mockUseScheduleSendFeature();
mockUseLabels([
[
{
ID: 'highlighted',
Name: 'highlighted',
Path: 'highlighted',
Type: 1,
Color: '#EC3E7C',
Order: 2,
Display: 1,
},
],
]);
mockUseFolders([
[
{
ID: '31dixxUc6tNkpKrI-abC_IQcnG4_K2brHumXkQb_Ib4-FEl5Q3n27dbhIkfBTnYrNonJ8DsySBbUM0RtQdhYhA==',
Name: 'news',
Path: 'news',
Type: 3,
Color: '#54473f',
Order: 1,
Notify: 1,
Expanded: 0,
},
],
]);
});
it('should return correct helper', () => {
const [defaults, customs, labels] = expectedGrouped;
const helper = useLocationFieldOptions();
expect(helper.all).toStrictEqual(expectedAll);
expect(helper.grouped).toStrictEqual(expectedGrouped);
expect(helper.findItemByValue('highlighted')).toStrictEqual(labels.items[0]);
expect(helper.isDefaultFolder(defaults.items[0])).toBe(true);
expect(helper.isDefaultFolder(customs.items[0])).toBe(false);
expect(helper.isCustomFolder(customs.items[0])).toBe(true);
expect(helper.isCustomFolder(defaults.items[0])).toBe(false);
expect(helper.isLabel(labels.items[0])).toBe(true);
expect(helper.isLabel(customs.items[0])).toBe(false);
});
describe('when Almost All Mail is true', () => {
beforeEach(() => {
mockUseMailSettings([{ AlmostAllMail: ALMOST_ALL_MAIL.ENABLED }]);
});
it('should return specific helper', () => {
const helper = useLocationFieldOptions();
expect(helper.all).toStrictEqual([
{
value: '15',
text: 'All mail',
url: '/almost-all-mail',
icon: 'envelopes',
},
...expectedAll.slice(1),
]);
});
});
});
| 3,502
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/search
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/search/AdvancedSearchFields/useLocationFieldOptions.ts
|
import { c } from 'ttag';
import { IconName, useFolders, useLabels } from '@proton/components';
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { hasBit } from '@proton/shared/lib/helpers/bitset';
import { buildTreeview, formatFolderName } from '@proton/shared/lib/helpers/folder';
import { FolderWithSubFolders } from '@proton/shared/lib/interfaces/Folder';
import { SHOW_MOVED } from '@proton/shared/lib/mail/mailSettings';
import useSnooze from 'proton-mail/hooks/actions/useSnooze';
import useMailModel from 'proton-mail/hooks/useMailModel';
import { getStandardFolders } from '../../../../helpers/labels';
import useScheduleSendFeature from '../../../composer/actions/scheduleSend/useScheduleSendFeature';
interface ItemBase {
text: string;
value: string;
}
export interface ItemDefaultFolder extends ItemBase {
icon: IconName;
url: string;
}
export interface ItemCustomFolder extends ItemBase {
folderEntity: FolderWithSubFolders;
className: string;
}
export interface ItemLabel extends ItemBase {
color: string;
url: string;
}
export type Item = ItemCustomFolder | ItemDefaultFolder | ItemLabel;
type ItemType = 'DEFAULT_FOLDERS' | 'CUSTOM_FOLDERS' | 'LABELS';
interface ItemGroup<T = Item> {
id: ItemType;
title: string;
items: T[];
}
export type ItemsGroup = [ItemGroup<ItemDefaultFolder>, ItemGroup<ItemCustomFolder>, ItemGroup<ItemLabel>];
interface UseLocationFieldOptionsReturn {
all: Item[];
grouped: ItemsGroup;
findItemByValue: (value: string) => Item | undefined;
isDefaultFolder(item: Item): item is ItemDefaultFolder;
isCustomFolder(item: Item): item is ItemCustomFolder;
isLabel(item: Item): item is ItemLabel;
}
const {
INBOX,
TRASH,
SPAM,
STARRED,
ARCHIVE,
ALL_MAIL,
ALMOST_ALL_MAIL,
ALL_SENT,
SENT,
ALL_DRAFTS,
DRAFTS,
SCHEDULED,
SNOOZED,
} = MAILBOX_LABEL_IDS;
const STANDARD_FOLDERS = getStandardFolders();
const getMarginByFolderLvl = (lvl: number) => {
switch (lvl) {
case 1:
return 'ml-2';
case 2:
case 3:
case 4:
return 'ml-4';
default:
return '';
}
};
function folderReducer(acc: ItemCustomFolder[], folder: FolderWithSubFolders, level = 0) {
acc.push({
text: formatFolderName(level, folder.Name),
value: folder.ID,
className: getMarginByFolderLvl(level),
folderEntity: folder,
});
if (Array.isArray(folder.subfolders)) {
folder.subfolders.forEach((folder) => folderReducer(acc, folder, level + 1));
}
return acc;
}
export function useLocationFieldOptions(): UseLocationFieldOptionsReturn {
const mailSettings = useMailModel('MailSettings');
const [labels = []] = useLabels();
const [folders] = useFolders();
const treeview = buildTreeview(folders);
const { canScheduleSend } = useScheduleSendFeature();
const { isSnoozeEnabled } = useSnooze();
const DRAFT_TYPE = hasBit(mailSettings.ShowMoved, SHOW_MOVED.DRAFTS) ? ALL_DRAFTS : DRAFTS;
const SENT_TYPE = hasBit(mailSettings.ShowMoved, SHOW_MOVED.SENT) ? ALL_SENT : SENT;
const { AlmostAllMail } = mailSettings;
const defaultFolders: ItemDefaultFolder[] = [
AlmostAllMail
? {
value: ALMOST_ALL_MAIL,
text: STANDARD_FOLDERS[ALMOST_ALL_MAIL].name,
url: STANDARD_FOLDERS[ALMOST_ALL_MAIL].to,
icon: STANDARD_FOLDERS[ALMOST_ALL_MAIL].icon,
}
: {
value: ALL_MAIL,
text: STANDARD_FOLDERS[ALL_MAIL].name,
url: STANDARD_FOLDERS[ALL_MAIL].to,
icon: STANDARD_FOLDERS[ALL_MAIL].icon,
},
{
value: INBOX,
text: STANDARD_FOLDERS[INBOX].name,
url: STANDARD_FOLDERS[INBOX].to,
icon: STANDARD_FOLDERS[INBOX].icon,
},
...(isSnoozeEnabled
? [
{
value: SNOOZED,
text: STANDARD_FOLDERS[SNOOZED].name,
url: STANDARD_FOLDERS[SNOOZED].to,
icon: STANDARD_FOLDERS[SNOOZED].icon,
},
]
: []),
{
value: DRAFT_TYPE,
text: DRAFT_TYPE === ALL_DRAFTS ? STANDARD_FOLDERS[ALL_DRAFTS].name : STANDARD_FOLDERS[DRAFTS].name,
url: STANDARD_FOLDERS[DRAFT_TYPE].to,
icon: STANDARD_FOLDERS[DRAFT_TYPE].icon,
},
...(canScheduleSend
? [
{
value: SCHEDULED,
text: STANDARD_FOLDERS[SCHEDULED].name,
url: STANDARD_FOLDERS[SCHEDULED].to,
icon: STANDARD_FOLDERS[SCHEDULED].icon,
},
]
: []),
{
value: SENT_TYPE,
text: SENT_TYPE === ALL_SENT ? STANDARD_FOLDERS[ALL_SENT].name : STANDARD_FOLDERS[SENT].name,
url: STANDARD_FOLDERS[SENT_TYPE].to,
icon: STANDARD_FOLDERS[SENT_TYPE].icon,
},
{
value: STARRED,
text: STANDARD_FOLDERS[STARRED].name,
url: STANDARD_FOLDERS[STARRED].to,
icon: STANDARD_FOLDERS[STARRED].icon,
},
{
value: ARCHIVE,
text: STANDARD_FOLDERS[ARCHIVE].name,
url: STANDARD_FOLDERS[ARCHIVE].to,
icon: STANDARD_FOLDERS[ARCHIVE].icon,
},
{
value: SPAM,
text: STANDARD_FOLDERS[SPAM].name,
url: STANDARD_FOLDERS[SPAM].to,
icon: STANDARD_FOLDERS[SPAM].icon,
},
{
value: TRASH,
text: STANDARD_FOLDERS[TRASH].name,
url: STANDARD_FOLDERS[TRASH].to,
icon: STANDARD_FOLDERS[TRASH].icon,
},
];
const customFolders: ItemCustomFolder[] = treeview.reduce(
(acc: ItemCustomFolder[], folder) => folderReducer(acc, folder),
[]
);
const labelOptions: ItemLabel[] = labels.map<ItemLabel>(({ ID: value, Name: text, Color: color }) => ({
value,
text,
url: value,
color,
}));
const all = [...defaultFolders, ...customFolders, ...labelOptions];
return {
all,
grouped: [
{
id: 'DEFAULT_FOLDERS',
title: c('Group').t`Default folders`,
items: defaultFolders,
},
{ id: 'CUSTOM_FOLDERS', title: c('Group').t`Custom folders`, items: customFolders },
{ id: 'LABELS', title: c('Group').t`Labels`, items: labelOptions },
],
findItemByValue: (value: string) => all.find((item) => item.value === value),
isDefaultFolder: (item: Item): item is ItemDefaultFolder => 'url' in item && 'icon' in item,
isCustomFolder: (item: Item): item is ItemCustomFolder => 'folderEntity' in item,
isLabel: (item: Item): item is ItemLabel => 'color' in item,
};
}
| 3,503
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/layout/PrivateLayout.tsx
|
import { ReactNode, Ref, forwardRef, useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import { DrawerApp, PrivateAppContainer, TopBanners } from '@proton/components';
import { Recipient } from '@proton/shared/lib/interfaces';
import { MESSAGE_ACTIONS } from '../../constants';
import { useOnCompose, useOnMailTo } from '../../containers/ComposeProvider';
import { ComposeTypes } from '../../hooks/composer/useCompose';
import { layoutActions } from '../../logic/layout/layoutSlice';
import { useAppDispatch } from '../../logic/store';
import { Breakpoints } from '../../models/utils';
import MailQuickSettings from '../drawer/MailQuickSettings';
import MailSidebar from '../sidebar/MailSidebar';
interface Props {
children: ReactNode;
breakpoints: Breakpoints;
labelID: string;
elementID: string | undefined;
}
const PrivateLayout = ({ children, labelID }: Props, ref: Ref<HTMLDivElement>) => {
const location = useLocation();
const dispatch = useAppDispatch();
const onCompose = useOnCompose();
const onMailTo = useOnMailTo();
const handleContactsCompose = (emails: Recipient[], attachments: File[]) => {
onCompose({
type: ComposeTypes.newMessage,
action: MESSAGE_ACTIONS.NEW,
referenceMessage: { data: { ToList: emails }, draftFlags: { initialAttachments: attachments } },
});
};
useEffect(() => {
dispatch(layoutActions.setSidebarExpanded(false));
}, [location.pathname, location.hash]);
const top = <TopBanners />;
const sidebar = <MailSidebar labelID={labelID} />;
return (
<PrivateAppContainer
top={top}
sidebar={sidebar}
containerRef={ref}
drawerApp={
<DrawerApp
onCompose={handleContactsCompose}
onMailTo={onMailTo}
customAppSettings={<MailQuickSettings />}
/>
}
>
{children}
</PrivateAppContainer>
);
};
export default forwardRef(PrivateLayout);
| 3,504
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/layout/PublicLayout.js
|
import PropTypes from 'prop-types';
import { Icons } from '@proton/components';
const PublicLayout = ({ children }) => {
return (
<>
<main className="main-full flex flex-column flex-nowrap reset4print">{children}</main>
<Icons />
</>
);
};
PublicLayout.propTypes = {
children: PropTypes.node.isRequired,
};
export default PublicLayout;
| 3,505
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/AttachmentThumbnail.scss
|
@import '~@proton/styles/scss/lib';
.attachment-thumbnail {
--button-default-background-color: transparent;
--button-default-text-color: inherit;
--button-default-border-color: var(--border-weak);
padding-block: rem(5);
transition: 0.15s easing(ease-out-quint), border-color 0s;
&:not(&--number) {
padding-inline: rem(5);
min-inline-size: rem(72);
max-inline-size: rem(180);
}
.item-is-selected & {
--button-default-background-color: transparent;
--button-hover-background-color: var(--interaction-default-hover);
--button-active-background-color: var(--interaction-default-active);
--button-hover-text-color: var(--email-item-selected-text-color);
--button-active-text-color: var(--email-item-selected-text-color);
--button-default-border-color: var(--interaction-norm-major-2);
--button-hover-border-color: var(--interaction-norm-major-2);
--button-active-border-color: var(--interaction-norm-major-2);
}
&-row {
padding-inline-end: rem(120);
}
&-name {
span span {
padding-block: var(--space-0-5);
}
}
}
.attachment-thumbnail-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(0, max-content));
}
| 3,506
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/AttachmentThumbnail.tsx
|
import { MouseEvent } from 'react';
import { Button } from '@proton/atoms/Button';
import { FileIcon, MiddleEllipsis } from '@proton/components/components';
import { AttachmentsMetadata } from '@proton/shared/lib/interfaces/mail/Message';
import './AttachmentThumbnail.scss';
interface Props {
attachmentMetadata: AttachmentsMetadata;
onClick: (attachmentsMetadata: AttachmentsMetadata) => void;
}
const AttachmentThumbnail = ({ attachmentMetadata, onClick, ...rest }: Props) => {
const handleClick = (e: MouseEvent) => {
e.stopPropagation();
onClick(attachmentMetadata);
};
return (
<Button
shape="outline"
onClick={handleClick}
className="text-sm flex flex-align-items-center flex-nowrap gap-2 attachment-thumbnail"
{...rest}
>
<FileIcon mimeType={attachmentMetadata?.MIMEType || 'unknown'} className="flex-item-noshrink" />
<span className="lh100 attachment-thumbnail-name">
<MiddleEllipsis charsToDisplayEnd={3} text={attachmentMetadata.Name} />
</span>
</Button>
);
};
export default AttachmentThumbnail;
| 3,507
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/Item.tsx
|
import { ChangeEvent, DragEvent, MouseEvent, memo, useMemo, useRef } from 'react';
import { ItemCheckbox, useLabels } from '@proton/components';
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { VIEW_MODE } from '@proton/shared/lib/mail/mailSettings';
import { getRecipients as getMessageRecipients, getSender, isDraft, isSent } from '@proton/shared/lib/mail/messages';
import clsx from '@proton/utils/clsx';
import { filterAttachmentToPreview } from 'proton-mail/helpers/attachment/attachmentThumbnails';
import useMailModel from 'proton-mail/hooks/useMailModel';
import { useEncryptedSearchContext } from '../../containers/EncryptedSearchProvider';
import { getRecipients as getConversationRecipients, getSenders } from '../../helpers/conversation';
import { isMessage, isUnread } from '../../helpers/elements';
import { isCustomLabel } from '../../helpers/labels';
import { useRecipientLabel } from '../../hooks/contact/useRecipientLabel';
import { selectSnoozeDropdownState } from '../../logic/snooze/snoozeSliceSelectors';
import { useAppSelector } from '../../logic/store';
import { Element } from '../../models/element';
import { ESMessage } from '../../models/encryptedSearch';
import { Breakpoints } from '../../models/utils';
import ItemColumnLayout from './ItemColumnLayout';
import ItemRowLayout from './ItemRowLayout';
import ItemSenders from './ItemSenders';
const { SENT, ALL_SENT, ALL_MAIL, ALMOST_ALL_MAIL, STARRED, DRAFTS, ALL_DRAFTS, SCHEDULED } = MAILBOX_LABEL_IDS;
const labelsWithIcons = [ALL_MAIL, ALMOST_ALL_MAIL, STARRED, ALL_SENT, ALL_DRAFTS] as string[];
interface Props {
conversationMode: boolean;
isCompactView: boolean;
labelID: string;
loading: boolean;
elementID?: string;
columnLayout: boolean;
element: Element;
checked?: boolean;
onCheck: (event: ChangeEvent, elementID: string) => void;
onClick: (elementID: string | undefined) => void;
onContextMenu: (event: React.MouseEvent<HTMLDivElement>, element: Element) => void;
onDragStart: (event: DragEvent, element: Element) => void;
onDragEnd: (event: DragEvent) => void;
onBack: () => void;
dragged: boolean;
index: number;
breakpoints: Breakpoints;
onFocus: (index: number) => void;
}
const Item = ({
conversationMode,
isCompactView,
labelID,
loading,
element,
elementID,
columnLayout,
checked = false,
onCheck,
onClick,
onContextMenu,
onDragStart,
onDragEnd,
onBack,
dragged,
index,
breakpoints,
onFocus,
}: Props) => {
const mailSettings = useMailModel('MailSettings');
const [labels] = useLabels();
const { shouldHighlight, esStatus } = useEncryptedSearchContext();
const { dbExists, esEnabled, contentIndexingDone } = esStatus;
const useContentSearch =
dbExists && esEnabled && shouldHighlight() && contentIndexingDone && !!(element as ESMessage)?.decryptedBody;
const snoozeDropdownState = useAppSelector(selectSnoozeDropdownState);
const elementRef = useRef<HTMLDivElement>(null);
const displayRecipients =
[SENT, ALL_SENT, DRAFTS, ALL_DRAFTS, SCHEDULED].includes(labelID as MAILBOX_LABEL_IDS) ||
isSent(element) ||
isDraft(element);
const { getRecipientLabel, getRecipientsOrGroups, getRecipientsOrGroupsLabels } = useRecipientLabel();
const isConversationContentView = mailSettings.ViewMode === VIEW_MODE.GROUP;
const isSelected =
isConversationContentView && isMessage(element)
? elementID === (element as Message).ConversationID
: elementID === element.ID;
const showIcon = labelsWithIcons.includes(labelID) || isCustomLabel(labelID, labels);
const senders = conversationMode
? getSenders(element)
: getSender(element as Message)
? [getSender(element as Message)]
: [];
const recipients = conversationMode ? getConversationRecipients(element) : getMessageRecipients(element as Message);
const sendersLabels = useMemo(() => senders.map((sender) => getRecipientLabel(sender, true)), [senders]);
const recipientsOrGroup = getRecipientsOrGroups(recipients);
const recipientsLabels = getRecipientsOrGroupsLabels(recipientsOrGroup);
const ItemLayout = columnLayout ? ItemColumnLayout : ItemRowLayout;
const unread = isUnread(element, labelID);
const firstRecipients = displayRecipients ? recipients : senders;
// Warning, spreading firstRecipients on Safari preview cause crash
// See MAILWEB-4079
const firstRecipient = firstRecipients[0];
const filteredThumbnails = filterAttachmentToPreview(element.AttachmentsMetadata || []);
const handleClick = (event: MouseEvent<HTMLDivElement>) => {
const target = event.target as HTMLElement;
if (target.closest('.stop-propagation') || snoozeDropdownState) {
event.stopPropagation();
return;
}
onClick(element.ID);
};
const handleCheck = (event: ChangeEvent) => {
onCheck(event, element.ID || '');
};
const handleFocus = () => {
onFocus(index);
};
const senderItem = (
<ItemSenders
element={element}
conversationMode={conversationMode}
loading={loading}
unread={unread}
displayRecipients={displayRecipients}
isSelected={isSelected}
/>
);
return (
<div
className={clsx(
'item-container-wrapper relative',
(isCompactView || !columnLayout) && 'border-bottom border-weak'
)}
>
<div
onContextMenu={(event) => onContextMenu(event, element)}
onClick={handleClick}
draggable
onDragStart={(event) => onDragStart(event, element)}
onDragEnd={onDragEnd}
className={clsx([
'flex-item-fluid flex flex-nowrap cursor-pointer',
columnLayout ? 'item-container item-container-column' : 'item-container-row',
isSelected && 'item-is-selected',
!unread && 'read',
unread && 'unread',
dragged && 'item-dragging',
loading && 'item-is-loading',
useContentSearch && columnLayout && 'es-three-rows',
useContentSearch && !columnLayout && 'es-row-results',
])}
style={{ '--index': index }}
ref={elementRef}
onFocus={handleFocus}
tabIndex={0}
data-element-id={element.ID}
data-shortcut-target="item-container"
data-shortcut-target-selected={isSelected}
data-testid={`message-item:${element.Subject}`}
data-testorder={element.Order}
>
<ItemCheckbox
ID={element.ID}
bimiSelector={firstRecipient?.BimiSelector || undefined}
name={displayRecipients ? recipientsLabels[0] : sendersLabels[0]}
email={firstRecipient?.Address}
displaySenderImage={!!firstRecipient?.DisplaySenderImage}
checked={checked}
onChange={handleCheck}
compactClassName="mr-3 stop-propagation"
normalClassName={clsx(['ml-0.5', columnLayout ? 'mr-2 mt-0.5' : 'mr-2'])}
/>
<ItemLayout
isCompactView={isCompactView}
labelID={labelID}
elementID={elementID}
labels={labels}
element={element}
conversationMode={conversationMode}
showIcon={showIcon}
senders={senderItem}
unread={unread}
breakpoints={breakpoints}
onBack={onBack}
isSelected={isSelected}
attachmentsMetadata={filteredThumbnails}
/>
</div>
</div>
);
};
export default memo(Item);
| 3,508
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/ItemAction.tsx
|
import { c } from 'ttag';
import { Icon, Tooltip } from '@proton/components';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import clsx from '@proton/utils/clsx';
import { isMessage } from '../../helpers/elements';
import { Element } from '../../models/element';
interface Props {
element?: Element;
className?: string;
}
const ItemAction = ({ element, className }: Props) => {
if (!isMessage(element)) {
return null;
}
const message = element as Message;
if (!message.IsReplied && !message.IsRepliedAll && !message.IsForwarded) {
return null;
}
return (
<div className={clsx(['flex flex-nowrap', className])}>
{!!message.IsReplied && (
<Tooltip title={c('Alt').t`Replied to`}>
<Icon
name="arrow-up-and-left-big"
alt={c('Alt').t`Replied to`}
className="flex-item-noshrink mr-1"
/>
</Tooltip>
)}
{!!message.IsRepliedAll && (
<Tooltip title={c('Alt').t`Replied to all`}>
<Icon
name="arrows-up-and-left-big"
alt={c('Alt').t`Replied to all`}
className="flex-item-noshrink mr-1"
/>
</Tooltip>
)}
{!!message.IsForwarded && (
<Tooltip title={c('Alt').t`Forwarded`}>
<Icon
name="arrow-up-and-left-big"
alt={c('Alt').t`Forwarded`}
className="mirror flex-item-noshrink mr-1"
/>
</Tooltip>
)}
</div>
);
};
export default ItemAction;
| 3,509
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/ItemAttachmentIcon.tsx
|
import { MouseEvent, createElement } from 'react';
import { c, msgid } from 'ttag';
import { Icon, IconName, Tooltip } from '@proton/components';
import humanSize from '@proton/shared/lib/helpers/humanSize';
import clsx from '@proton/utils/clsx';
import { getNumAttachments } from '../../helpers/elements';
import { Element } from '../../models/element';
interface Props {
element?: Element;
className?: string;
onClick?: (e: MouseEvent) => void;
icon?: IconName;
}
const ItemAttachmentIcon = ({ element, className, onClick, icon = 'paper-clip' }: Props) => {
const numAttachments = element ? getNumAttachments(element) : 0;
const numAttachmentsSize = element ? humanSize(element.Size) : 0;
const isButton = onClick !== undefined;
if (numAttachments === 0) {
return null;
}
const title = icon.includes('calendar')
? c('Calendar attachment tooltip').t`Has a calendar event`
: c('Info').ngettext(
msgid`Has ${numAttachments} attachment (${numAttachmentsSize})`,
`Has ${numAttachments} attachments (${numAttachmentsSize})`,
numAttachments
);
const commonProps = {
className: clsx(['flex', className]),
'data-testid': `item-attachment-icon-${icon}`,
};
const buttonProps = {
onClick,
type: 'button',
};
return (
<Tooltip title={title}>
{createElement(
isButton ? 'button' : 'div',
{ ...commonProps, ...(isButton ? buttonProps : {}) },
<Icon name={icon} size={16} alt={title} />
)}
</Tooltip>
);
};
export default ItemAttachmentIcon;
| 3,510
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/ItemAttachmentThumbnails.test.tsx
|
import { fireEvent, screen } from '@testing-library/react';
import { useFlag } from '@proton/components/index';
import { WorkerDecryptionResult } from '@proton/crypto';
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import downloadFile from '@proton/shared/lib/helpers/downloadFile';
import { AttachmentsMetadata } from '@proton/shared/lib/interfaces/mail/Message';
import { ATTACHMENT_DISPOSITION } from '@proton/shared/lib/mail/constants';
import { encryptAttachment } from '@proton/shared/lib/mail/send/attachments';
import isTruthy from '@proton/utils/isTruthy';
import mergeUint8Arrays from '@proton/utils/mergeUint8Arrays';
import ItemColumnLayout from 'proton-mail/components/list/ItemColumnLayout';
import { MAX_COLUMN_ATTACHMENT_THUMBNAILS } from 'proton-mail/constants';
import { filterAttachmentToPreview } from 'proton-mail/helpers/attachment/attachmentThumbnails';
import { arrayToBase64 } from 'proton-mail/helpers/base64';
import { addApiMock } from 'proton-mail/helpers/test/api';
import {
GeneratedKey,
addApiKeys,
addKeysToAddressKeysCache,
assertIcon,
clearAll,
createAttachment,
generateKeys,
releaseCryptoProxy,
setupCryptoProxyForTesting,
tick,
} from 'proton-mail/helpers/test/helper';
import { render } from 'proton-mail/helpers/test/render';
import { addAttachment } from 'proton-mail/logic/attachments/attachmentsActions';
import { store } from 'proton-mail/logic/store';
import { Conversation } from 'proton-mail/models/conversation';
import { Breakpoints } from 'proton-mail/models/utils';
jest.mock('@proton/shared/lib/helpers/downloadFile', () => {
return jest.fn();
});
const mockUseFlag = useFlag as unknown as jest.MockedFunction<any>;
const fileContent = `test-content`;
const generateAttachmentsMetadata = (numberOfAttachments: number, extension = 'png', mimeType = 'image/png') => {
const attachmentsMetadata: AttachmentsMetadata[] = [];
for (let i = 0; i < numberOfAttachments; i++) {
const metadata: AttachmentsMetadata = {
ID: i.toString(),
Disposition: ATTACHMENT_DISPOSITION.ATTACHMENT,
MIMEType: mimeType,
Size: 200000,
Name: `Attachment-${i}.${extension}`,
};
attachmentsMetadata.push(metadata);
}
return attachmentsMetadata;
};
const setup = async (attachmentsMetadata: AttachmentsMetadata[], numAttachments: number) => {
const element = {
ID: 'conversationID',
Subject: 'Conversation thumbnails',
Time: Date.now(),
Senders: [{ Address: 'sender@proton.me', Name: 'Sender' }],
Recipients: [{ Address: 'recipient@proton.me', Name: 'Recipient' }],
Labels: [{ ID: MAILBOX_LABEL_IDS.INBOX }],
NumAttachments: numAttachments,
AttachmentsMetadata: attachmentsMetadata,
} as Conversation;
await render(
<ItemColumnLayout
labelID={MAILBOX_LABEL_IDS.INBOX}
element={element}
conversationMode={true}
showIcon={true}
senders={<>Sender</>}
breakpoints={{} as Breakpoints}
unread={false}
onBack={jest.fn()}
isSelected={false}
attachmentsMetadata={filterAttachmentToPreview(attachmentsMetadata)}
/>
);
};
describe('ItemAttachmentThumbnails', () => {
beforeAll(() => {
// Mock feature flag
// TODO update when we'll have a better solution
mockUseFlag.mockReturnValue(true);
});
afterEach(() => clearAll());
it('should not display attachment thumbnails', async () => {
const elementTotalAttachments = 0;
// The conversation has no attachments.
await setup([], elementTotalAttachments);
// No attachment thumbnail displayed
expect(screen.queryByText(`Attachment-`)).toBeNull();
// +X should not be displayed
expect(screen.queryByTestId('attachment-thumbnail:other-attachment-number')).toBeNull();
// Paper clip icon is not displayed
expect(screen.queryByTestId('item-attachment-icon-paper-clip')).toBeNull();
});
it('should display attachment thumbnails', async () => {
const numberOfReceivedMetadata = 5;
const attachmentsMetadata = generateAttachmentsMetadata(numberOfReceivedMetadata);
// We received the metadata for 5 attachments, and we can display 2 thumbnails
await setup(attachmentsMetadata, numberOfReceivedMetadata);
const items = screen.getAllByTestId('attachment-thumbnail');
// 2 first attachments are displayed
for (let i = 0; i < MAX_COLUMN_ATTACHMENT_THUMBNAILS; i++) {
expect(items[i].textContent).toEqual(`Attachment-${i}.png`);
}
// Other received attachments are not displayed since we cannot display them
for (let i = MAX_COLUMN_ATTACHMENT_THUMBNAILS; i < numberOfReceivedMetadata; i++) {
// use title because text is split in multiple elements
expect(screen.queryByTitle(`Attachment-${i}.png`)).toBeNull();
}
// Since we have 5 attachment metadata, and we display 2 of them. So we should see +3
screen.getByText(`+${numberOfReceivedMetadata - MAX_COLUMN_ATTACHMENT_THUMBNAILS}`);
// Paper clip icon is displayed (in row mode paper clip can be rendered twice because of responsive)
screen.getAllByTestId('item-attachment-icon-paper-clip');
});
it('should not display +X attachment', async () => {
const numberOfReceivedMetadata = 1;
const attachmentsMetadata = generateAttachmentsMetadata(numberOfReceivedMetadata);
// The conversation has 1 attachment in total.
// We received the metadata for 1 of them, which will display 1 thumbnail
await setup(attachmentsMetadata, numberOfReceivedMetadata);
const items = screen.getAllByTestId('attachment-thumbnail');
// 2 first attachments are displayed
for (let i = 0; i < numberOfReceivedMetadata; i++) {
// use title because text is split in multiple elements
expect(items[i].textContent).toEqual(`Attachment-${i}.png`);
}
// No other thumbnail element is displayed
for (let i = numberOfReceivedMetadata; i < MAX_COLUMN_ATTACHMENT_THUMBNAILS; i++) {
expect(screen.queryByTitle(`Attachment-${i}.png`)).toBeNull();
}
// +X should not be displayed
expect(screen.queryByTestId('attachment-thumbnail:other-attachment-number')).toBeNull();
// Paper clip icon is displayed (in row mode paper clip can be rendered twice because of responsive)
screen.getAllByTestId('item-attachment-icon-paper-clip');
});
it('should should display paper clip icon and no thumbnails when no attachment can be previewed', async () => {
const elementTotalAttachments = 10;
// The conversation has 10 attachment in total.
// We received no metadata, so no thumbnail will be displayed
await setup([], elementTotalAttachments);
// No attachment thumbnail displayed
expect(screen.queryByText(`Attachment-`)).toBeNull();
// +X should not be displayed
expect(screen.queryByTestId('attachment-thumbnail:other-attachment-number')).toBeNull();
// Paper clip icons are displayed
expect(screen.getAllByTestId('item-attachment-icon-paper-clip').length).toBe(2);
});
it('should display the expected attachment icon', async () => {
const numAttachments = 2;
const attachmentsMetadata: AttachmentsMetadata[] = [
{
ID: '0',
Disposition: ATTACHMENT_DISPOSITION.ATTACHMENT,
MIMEType: 'image/png',
Size: 200000,
Name: `Attachment-0.png`,
},
{
ID: '1',
Disposition: ATTACHMENT_DISPOSITION.ATTACHMENT,
MIMEType: 'application/pdf',
Size: 200000,
Name: `Attachment-1.pdf`,
},
];
const icons = ['sm-image', 'sm-pdf'];
const extensions = ['png', 'pdf'];
await setup(attachmentsMetadata, numAttachments);
const items = screen.getAllByTestId('attachment-thumbnail');
for (let i = 0; i < 2; i++) {
expect(items[i].textContent).toEqual(`Attachment-${i}.${extensions[i]}`);
assertIcon(items[i].querySelector('svg'), icons[i], undefined, 'mime');
}
});
});
describe('ItemAttachmentThumbnails - Preview', () => {
const AddressID = 'AddressID';
const fromAddress = 'me@home.net';
let fromKeys: GeneratedKey;
beforeAll(async () => {
// Mock feature flag
// TODO update when we'll have a better solution
mockUseFlag.mockReturnValue(true);
addApiKeys(false, fromAddress, []);
});
beforeEach(async () => {
await setupCryptoProxyForTesting();
clearAll();
fromKeys = await generateKeys('me', fromAddress);
addKeysToAddressKeysCache(AddressID, fromKeys);
});
afterEach(async () => {
clearAll();
await releaseCryptoProxy();
});
const mockAttachmentThumbnailsAPICalls = async (
attachmentsMetadata: AttachmentsMetadata[],
keys: GeneratedKey,
decryptShouldFail = false
) => {
addApiMock('core/v4/keys/all', () => ({ Address: { Keys: [] } }));
return Promise.all(
attachmentsMetadata.map(async (metadata) => {
const { ID, Name, MIMEType } = metadata;
const attachmentID = ID;
const attachmentName = Name;
const attachmentType = MIMEType;
const file = new File([new Blob([fileContent])], attachmentName, { type: attachmentType });
const attachmentPackets = await encryptAttachment(fileContent, file, false, keys.publicKeys, []);
// Trigger a fail during decrypt (when necessary) to test some scenarios (e.g. decryption failed)
const concatenatedPackets = decryptShouldFail
? []
: mergeUint8Arrays(
[attachmentPackets.data, attachmentPackets.keys, attachmentPackets.signature].filter(isTruthy)
);
const attachmentSpy = jest.fn(() => concatenatedPackets);
const attachmentMetadataSpy = jest.fn(() => ({
Attachment: {
KeyPackets: arrayToBase64(attachmentPackets.keys),
Sender: { Address: fromAddress },
AddressID,
},
}));
addApiMock(`mail/v4/attachments/${attachmentID}`, attachmentSpy);
addApiMock(`mail/v4/attachments/${attachmentID}/metadata`, attachmentMetadataSpy);
return {
attachmentSpy,
attachmentMetadataSpy,
attachmentPackets,
};
})
);
};
it('should preview an attachment that was already in Redux state', async () => {
window.URL.createObjectURL = jest.fn();
const numAttachments = 1;
const attachmentsMetadata = generateAttachmentsMetadata(numAttachments, 'txt', 'text/plain');
const { attachment } = await createAttachment(
{
ID: attachmentsMetadata[0].ID,
Name: attachmentsMetadata[0].Name,
MIMEType: attachmentsMetadata[0].MIMEType,
data: new Uint8Array(),
},
fromKeys.publicKeys
);
store.dispatch(
addAttachment({
ID: attachment.ID as string,
attachment: {
data: attachment.data,
} as WorkerDecryptionResult<Uint8Array>,
})
);
// Mock to check that if attachment is in the state, no api call is done
const mocks = await mockAttachmentThumbnailsAPICalls(attachmentsMetadata, fromKeys);
await setup(attachmentsMetadata, numAttachments);
const item = screen.getByTestId('attachment-thumbnail');
fireEvent.click(item);
await tick();
const preview = screen.getByTestId('file-preview');
expect(preview?.textContent).toMatch(new RegExp(attachmentsMetadata[0].Name));
expect(mocks[0].attachmentSpy).not.toHaveBeenCalled();
expect(mocks[0].attachmentMetadataSpy).not.toHaveBeenCalled();
});
it('should preview an attachment that was not in Redux state', async () => {
window.URL.createObjectURL = jest.fn();
const numAttachments = 1;
const attachmentsMetadata = generateAttachmentsMetadata(numAttachments, 'txt', 'text/plain');
const mocks = await mockAttachmentThumbnailsAPICalls(attachmentsMetadata, fromKeys);
await setup(attachmentsMetadata, numAttachments);
const item = screen.getByTestId('attachment-thumbnail');
fireEvent.click(item);
await tick();
expect(mocks[0].attachmentSpy).toHaveBeenCalled();
expect(mocks[0].attachmentMetadataSpy).toHaveBeenCalled();
const preview = screen.getByTestId('file-preview');
expect(preview?.textContent).toMatch(new RegExp(attachmentsMetadata[0].Name));
// File content is visible
expect(preview?.textContent).toMatch(new RegExp(fileContent));
});
it('should be possible to switch between attachments when Redux state is filled', async () => {
window.URL.createObjectURL = jest.fn();
const numAttachments = 2;
const attachmentsMetadata = generateAttachmentsMetadata(numAttachments, 'txt', 'text/plain');
const { attachment: attachment1 } = await createAttachment(
{
ID: attachmentsMetadata[0].ID,
Name: attachmentsMetadata[0].Name,
MIMEType: attachmentsMetadata[0].MIMEType,
data: new Uint8Array(),
},
fromKeys.publicKeys
);
const { attachment: attachment2 } = await createAttachment(
{
ID: attachmentsMetadata[1].ID,
Name: attachmentsMetadata[1].Name,
MIMEType: attachmentsMetadata[1].MIMEType,
data: new Uint8Array(),
},
fromKeys.publicKeys
);
store.dispatch(
addAttachment({
ID: attachment1.ID as string,
attachment: {
data: attachment1.data,
} as WorkerDecryptionResult<Uint8Array>,
})
);
store.dispatch(
addAttachment({
ID: attachment2.ID as string,
attachment: {
data: attachment2.data,
} as WorkerDecryptionResult<Uint8Array>,
})
);
await setup(attachmentsMetadata, numAttachments);
const item = screen.getAllByTestId('attachment-thumbnail');
// Preview first item
fireEvent.click(item[0]);
await tick();
const preview = screen.getByTestId('file-preview');
expect(preview?.textContent).toMatch(new RegExp(attachmentsMetadata[0].Name));
// Switch to next item
const nextButton = screen.getByTestId('file-preview:navigation:next');
fireEvent.click(nextButton);
await tick();
expect(preview?.textContent).toMatch(new RegExp(attachmentsMetadata[1].Name));
});
it('should show a message instead of preview when attachment decryption failed', async () => {
window.URL.createObjectURL = jest.fn();
const numAttachments = 1;
const attachmentsMetadata = generateAttachmentsMetadata(numAttachments, 'txt', 'text/plain');
const mocks = await mockAttachmentThumbnailsAPICalls(attachmentsMetadata, fromKeys, true);
await setup(attachmentsMetadata, numAttachments);
const item = screen.getByTestId('attachment-thumbnail');
fireEvent.click(item);
await tick();
expect(mocks[0].attachmentSpy).toHaveBeenCalled();
expect(mocks[0].attachmentMetadataSpy).toHaveBeenCalled();
const preview = screen.getByTestId('file-preview');
expect(preview?.textContent).toMatch(new RegExp(attachmentsMetadata[0].Name));
// File preview cannot be displayed because decryption failed
expect(preview?.textContent).toMatch(new RegExp('Preview for this file type is not supported'));
});
it('should be possible to switch between attachments when not present in Redux state', async () => {
window.URL.createObjectURL = jest.fn();
const numAttachments = 2;
const attachmentsMetadata = generateAttachmentsMetadata(numAttachments, 'txt', 'text/plain');
const mocks = await mockAttachmentThumbnailsAPICalls(attachmentsMetadata, fromKeys);
await setup(attachmentsMetadata, numAttachments);
const item = screen.getAllByTestId('attachment-thumbnail');
// Preview first item
fireEvent.click(item[0]);
await tick();
expect(mocks[0].attachmentSpy).toHaveBeenCalled();
expect(mocks[0].attachmentMetadataSpy).toHaveBeenCalled();
const preview = screen.getByTestId('file-preview');
expect(preview?.textContent).toMatch(new RegExp(attachmentsMetadata[0].Name));
// Switch to next item
const nextButton = screen.getByTestId('file-preview:navigation:next');
fireEvent.click(nextButton);
await tick();
expect(mocks[1].attachmentSpy).toHaveBeenCalled();
expect(mocks[1].attachmentMetadataSpy).toHaveBeenCalled();
expect(preview?.textContent).toMatch(new RegExp(attachmentsMetadata[1].Name));
});
it('should download the attachment', async () => {
window.URL.createObjectURL = jest.fn();
const numAttachments = 1;
const attachmentsMetadata = generateAttachmentsMetadata(numAttachments, 'txt', 'text/plain');
const { attachment } = await createAttachment(
{
ID: attachmentsMetadata[0].ID,
Name: attachmentsMetadata[0].Name,
MIMEType: attachmentsMetadata[0].MIMEType,
data: new Uint8Array(),
},
fromKeys.publicKeys
);
store.dispatch(
addAttachment({
ID: attachment.ID as string,
attachment: {
data: attachment.data,
} as WorkerDecryptionResult<Uint8Array>,
})
);
await setup(attachmentsMetadata, numAttachments);
const item = screen.getByTestId('attachment-thumbnail');
fireEvent.click(item);
await tick();
const preview = screen.getByTestId('file-preview');
expect(preview?.textContent).toMatch(new RegExp(attachmentsMetadata[0].Name));
const downloadButton = screen.getByTestId('file-preview:actions:download');
fireEvent.click(downloadButton);
await tick();
expect(downloadFile).toHaveBeenCalled();
});
it('should download a pgp attachment when decryption failed', async () => {
window.URL.createObjectURL = jest.fn();
const numAttachments = 1;
const attachmentsMetadata = generateAttachmentsMetadata(numAttachments, 'txt', 'text/plain');
const mocks = await mockAttachmentThumbnailsAPICalls(attachmentsMetadata, fromKeys, true);
await setup(attachmentsMetadata, numAttachments);
const item = screen.getByTestId('attachment-thumbnail');
fireEvent.click(item);
await tick();
expect(mocks[0].attachmentSpy).toHaveBeenCalled();
expect(mocks[0].attachmentMetadataSpy).toHaveBeenCalled();
const preview = screen.getByTestId('file-preview');
expect(preview?.textContent).toMatch(new RegExp(attachmentsMetadata[0].Name));
// File preview cannot be displayed because decryption failed
expect(preview?.textContent).toMatch(new RegExp('Preview for this file type is not supported'));
// Download the encrypted attachment
const downloadButton = screen.getByTestId('file-preview:actions:download');
fireEvent.click(downloadButton);
await tick();
const blob = new Blob([mocks[0].attachmentPackets.data], {
type: 'application/pgp-encrypted',
});
expect(downloadFile).toHaveBeenCalledWith(blob, 'Attachment-0.txt.pgp');
});
});
| 3,511
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/ItemAttachmentThumbnails.tsx
|
import { useRef, useState } from 'react';
import { Tooltip } from '@proton/components/components';
import Portal from '@proton/components/components/portal/Portal';
import { FilePreview, NavigationControl } from '@proton/components/containers';
import { AttachmentsMetadata } from '@proton/shared/lib/interfaces/mail/Message';
import { VERIFICATION_STATUS } from '@proton/shared/lib/mail/constants';
import clsx from '@proton/utils/clsx';
import AttachmentThumbnail from 'proton-mail/components/list/AttachmentThumbnail';
import { MAX_COLUMN_ATTACHMENT_THUMBNAILS } from 'proton-mail/constants';
import { getOtherAttachmentsTitle } from 'proton-mail/helpers/attachment/attachmentThumbnails';
import { useAttachmentThumbnailDownload } from 'proton-mail/hooks/attachments/useAttachmentThumbnailDownload';
interface Preview {
attachment: AttachmentsMetadata;
contents?: Uint8Array[];
}
interface Props {
attachmentsMetadata?: AttachmentsMetadata[];
maxAttachment?: number;
className?: string;
}
/**
* This component is close to AttachmentPreview.tsx for the preview and download part.
* Some parts are duplicated on purpose because the download logic is quite different with the one we have in the attachment list.
* It will need a refactor to merge some logic, but it needs a refactor on the old download logic first.
*/
const ItemAttachmentThumbnails = ({
attachmentsMetadata = [],
maxAttachment = MAX_COLUMN_ATTACHMENT_THUMBNAILS,
className,
}: Props) => {
const [previewing, setPreviewing] = useState<Preview>();
const otherAttachmentNumber = attachmentsMetadata?.length - maxAttachment;
const { handleThumbnailPreview, handleThumbnailDownload, confirmDownloadModal } = useAttachmentThumbnailDownload();
const rootRef = useRef<HTMLDivElement>(null);
const handlePreview = async (attachmentsMetadata: AttachmentsMetadata) => {
setPreviewing({ attachment: attachmentsMetadata });
const download = await handleThumbnailPreview(attachmentsMetadata);
setPreviewing((previewing) => {
// Preview can be closed or changed during download;
// In attachment list, we do have the full attachment, so we can make sure the preview is the attachment (previewing.attachment !== attachment)
// Here we do not have it, so we can check that name and size are equals
if (
previewing === undefined ||
!(
previewing.attachment.Name === attachmentsMetadata.Name &&
previewing.attachment.Size === attachmentsMetadata.Size
)
) {
return previewing;
}
// Don't preview unverified attachment
if (download.verified === VERIFICATION_STATUS.SIGNED_AND_INVALID) {
return {
// Overriding mime type to prevent opening any visualizer with empty data, especially needed for pdfs
attachment: { ...attachmentsMetadata, MIMEType: '' },
contents: [],
};
}
return {
attachment: {
...previewing.attachment,
// Reuse download MIMEType because we update it in some cases (e.g. errors during decryption)
// If undefined, default to attachmentMetadata mimeType, otherwise use the download value (which can be an empty string)
MIMEType:
download.attachment.MIMEType === undefined
? previewing.attachment.MIMEType
: download.attachment.MIMEType,
},
contents: [download.data],
};
});
};
const otherAttachmentsTitle = getOtherAttachmentsTitle(attachmentsMetadata, maxAttachment);
const current = attachmentsMetadata.findIndex(
(attachmentMetadata) => attachmentMetadata.ID === previewing?.attachment.ID
);
const total = attachmentsMetadata.length;
const handleNext = () => handlePreview(attachmentsMetadata[current + 1]);
const handlePrevious = () => handlePreview(attachmentsMetadata[current - 1]);
const handleClose = () => setPreviewing(undefined);
const handleDownload = async () => {
if (previewing && previewing.attachment) {
const { attachment } = previewing;
await handleThumbnailDownload(attachment);
}
};
return (
<>
<div
data-testid="attachment-thumbnails"
className={clsx('flex flex-nowrap gap-2 attachment-thumbnail-grid', className)}
>
{attachmentsMetadata?.slice(0, maxAttachment).map((attachmentMetadata) => {
return (
<AttachmentThumbnail
attachmentMetadata={attachmentMetadata}
onClick={handlePreview}
key={attachmentMetadata.ID}
data-testid="attachment-thumbnail"
/>
);
})}
{otherAttachmentNumber > 0 && (
<span
className="rounded text-sm flex flex-item-noshrink flex-align-items-center flex-nowrap attachment-thumbnail attachment-thumbnail--number"
data-testid="attachment-thumbnail:other-attachment-number"
>
<Tooltip title={otherAttachmentsTitle} originalPlacement="bottom">
<span className="lh100">+{otherAttachmentNumber}</span>
</Tooltip>
</span>
)}
</div>
{previewing && (
// Need an additional div to prevent the event propagation (a click inside the portal would open the message)
<div onClick={(e) => e.stopPropagation()}>
<Portal>
<FilePreview
isLoading={!previewing.contents}
contents={previewing.contents}
fileName={previewing.attachment?.Name}
mimeType={previewing.attachment?.MIMEType}
fileSize={previewing.attachment?.Size}
onClose={handleClose}
ref={rootRef}
onDownload={handleDownload}
navigationControls={
<NavigationControl
current={current + 1}
total={total}
rootRef={rootRef}
onNext={handleNext}
onPrev={handlePrevious}
/>
}
/>
</Portal>
{confirmDownloadModal}
</div>
)}
</>
);
};
export default ItemAttachmentThumbnails;
| 3,512
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/ItemColumnLayout.tsx
|
import { ReactNode, useMemo } from 'react';
import { c, msgid } from 'ttag';
import { useFlag } from '@proton/components/containers/unleash';
import { useUserSettings } from '@proton/components/hooks/';
import { DENSITY } from '@proton/shared/lib/constants';
import { Label } from '@proton/shared/lib/interfaces/Label';
import { AttachmentsMetadata } from '@proton/shared/lib/interfaces/mail/Message';
import { getHasOnlyIcsAttachments } from '@proton/shared/lib/mail/messages';
import clsx from '@proton/utils/clsx';
import ItemAttachmentThumbnails from 'proton-mail/components/list/ItemAttachmentThumbnails';
import { canShowAttachmentThumbnails } from 'proton-mail/helpers/attachment/attachmentThumbnails';
import { useEncryptedSearchContext } from '../../containers/EncryptedSearchProvider';
import { getLabelIDs, isStarred as testIsStarred } from '../../helpers/elements';
import { useExpiringElement } from '../../hooks/useExpiringElement';
import { selectSnoozeDropdownState, selectSnoozeElement } from '../../logic/snooze/snoozeSliceSelectors';
import { useAppSelector } from '../../logic/store';
import { Element } from '../../models/element';
import { ESMessage } from '../../models/encryptedSearch';
import { Breakpoints } from '../../models/utils';
import NumMessages from '../conversation/NumMessages';
import ItemAction from './ItemAction';
import ItemAttachmentIcon from './ItemAttachmentIcon';
import ItemDate from './ItemDate';
import ItemHoverButtons from './ItemHoverButtons';
import ItemLabels from './ItemLabels';
import ItemLocation from './ItemLocation';
import ItemStar from './ItemStar';
import ItemUnread from './ItemUnread';
import ItemExpiration from './item-expiration/ItemExpiration';
interface Props {
labelID: string;
elementID?: string;
labels?: Label[];
element: Element;
conversationMode: boolean;
showIcon: boolean;
senders: ReactNode;
breakpoints: Breakpoints;
unread: boolean;
onBack: () => void;
isSelected: boolean;
attachmentsMetadata: AttachmentsMetadata[];
}
const ItemColumnLayout = ({
labelID,
elementID,
labels,
element,
conversationMode,
showIcon,
breakpoints,
unread,
onBack,
isSelected,
senders,
attachmentsMetadata,
}: Props) => {
const [userSettings] = useUserSettings();
const { shouldHighlight, highlightMetadata, esStatus } = useEncryptedSearchContext();
const highlightData = shouldHighlight();
const { contentIndexingDone } = esStatus;
const canSeeThumbnailsFeature = useFlag('AttachmentThumbnails');
const snoozedElement = useAppSelector(selectSnoozeElement);
const snoozeDropdownState = useAppSelector(selectSnoozeDropdownState);
const { expirationTime, hasExpiration } = useExpiringElement(element, labelID, conversationMode);
const body = contentIndexingDone ? (element as ESMessage).decryptedBody : undefined;
const { Subject } = element;
const subjectContent = useMemo(
() => (highlightData && Subject ? highlightMetadata(Subject, unread, true).resultJSX : Subject),
[Subject, highlightData, highlightMetadata, unread]
);
const { resultJSX, numOccurrences } = useMemo(
() =>
body && highlightData ? highlightMetadata(body, unread, true) : { resultJSX: undefined, numOccurrences: 0 },
[body, unread, highlightData, highlightMetadata]
);
// translator: This text is displayed in an Encrypted Search context. The user has searched for a specific keyword.
// In the message list, the user should see the part of the message "body" which contains the keyword. On hover, this text is displayed.
// The variable "numOccurrences" corresponds to the number of times the keyword has been found in the email content
const bodyTitle = c('Info').ngettext(
msgid`${numOccurrences} occurrence found in the mail content`,
`${numOccurrences} occurrences found in the mail content`,
numOccurrences
);
const hasOnlyIcsAttachments = getHasOnlyIcsAttachments(element?.AttachmentInfo);
const hasLabels = useMemo(() => {
const allLabelIDs = Object.keys(getLabelIDs(element, labelID));
const labelIDs = allLabelIDs.filter((ID) => labels?.find((label) => ID === label.ID));
return !!labelIDs.length;
}, [element, labels, labelID]);
const isStarred = testIsStarred(element || ({} as Element));
const isCompactView = userSettings.Density === DENSITY.COMPACT;
const isSnoozeDropdownOpen = snoozeDropdownState && snoozedElement?.ID === element.ID;
const showThumbnails = canShowAttachmentThumbnails(
isCompactView,
element,
attachmentsMetadata,
canSeeThumbnailsFeature
);
return (
<div
className="flex-item-fluid flex flex-nowrap flex-column flex-justify-center item-titlesender pr-1"
data-testid="message-list:message"
>
<div className="flex flex-align-items-center flex-nowrap">
<div className="flex-item-fluid">
<div className="flex flex-align-items-center item-firstline">
<div className="item-senders flex-item-fluid flex flex-align-items-center flex-nowrap pr-4">
<ItemUnread
element={element}
labelID={labelID}
className={clsx('item-unread-dot flex-item-noshrink', isCompactView && 'mr-1')}
isSelected={isSelected}
/>
<ItemAction element={element} className="mr-1 my-auto flex-item-noshrink" />
<span
className="inline-flex max-w-full text-ellipsis"
data-testid="message-column:sender-address"
>
{senders}
</span>
</div>
<span
className={clsx(
'item-firstline-infos flex-item-noshrink flex flex-nowrap flex-align-items-center',
isSnoozeDropdownOpen && 'invisible'
)}
>
<ItemDate
element={element}
labelID={labelID}
className="item-senddate-col text-sm"
isInListView
/>
</span>
</div>
<div className="flex flex-nowrap flex-align-items-center item-secondline max-w-full">
<div className="item-subject flex-item-fluid flex flex-nowrap flex-align-items-center">
{showIcon && (
<span className="flex flex-item-noshrink">
<ItemLocation element={element} labelID={labelID} />
</span>
)}
{conversationMode && (
<NumMessages className="mr-1 flex-item-noshrink" conversation={element} />
)}
<span
role="heading"
aria-level={2}
className="inline-block max-w-full mr-1 text-ellipsis"
title={Subject}
data-testid="message-column:subject"
>
{subjectContent}
</span>
</div>
<div className="item-icons hidden md:flex flex-item-noshrink flex-nowrap">
<span className="flex item-meta-infos">
{hasLabels && isCompactView && (
<ItemLabels
className="ml-2"
labels={labels}
element={element}
labelID={labelID}
maxNumber={1}
/>
)}
{hasExpiration && (
<ItemExpiration
expirationTime={expirationTime}
className="ml-1 flex-align-self-center"
element={element}
labelID={labelID}
/>
)}
<ItemAttachmentIcon
icon={hasOnlyIcsAttachments ? 'calendar-grid' : undefined}
element={element}
className="ml-1 flex-align-self-center"
/>
<span className="ml-1 flex-flex-children flex-item-centered-vert hidden-empty">
{isStarred && <ItemStar element={element} />}
</span>
</span>
</div>
<div className="item-icons flex flex-row flex-item-noshrink flex-nowrap md:hidden">
{hasExpiration && (
<ItemExpiration
element={element}
expirationTime={expirationTime}
className="ml-1 flex-align-self-center"
labelID={labelID}
/>
)}
<ItemAttachmentIcon
icon={hasOnlyIcsAttachments ? 'calendar-grid' : undefined}
element={element}
className="ml-1 flex-align-self-center"
/>
<span className="ml-1 flex-flex-children flex-item-centered-vert hidden-empty">
<ItemStar element={element} />
</span>
</div>
</div>
</div>
<ItemHoverButtons element={element} labelID={labelID} elementID={elementID} onBack={onBack} />
</div>
{showThumbnails && <ItemAttachmentThumbnails attachmentsMetadata={attachmentsMetadata} className="mt-1" />}
{hasLabels && !isCompactView && (
<div className="flex flex-nowrap flex-align-items-center max-w-full no-scroll">
<div className="item-icons flex flex-item-noshrink flex-nowrap mt-1">
<ItemLabels
className="ml-2"
labels={labels}
element={element}
labelID={labelID}
maxNumber={breakpoints.isNarrow ? 1 : 5}
isCollapsed={false}
/>
</div>
</div>
)}
{!!resultJSX && (
<>
<div
className={clsx([
'flex flex-nowrap flex-align-items-center item-secondline item-es-result max-w-4/5 no-scroll',
isCompactView && 'mb-3',
])}
aria-hidden="true"
>
<div className="item-subject flex-item-fluid flex flex-nowrap flex-align-items-center">
<span className="inline-block max-w-full text-ellipsis" title={bodyTitle}>
{resultJSX}
</span>
</div>
</div>
<div className="sr-only">{bodyTitle}</div>
</>
)}
</div>
);
};
export default ItemColumnLayout;
| 3,513
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/ItemContextMenu.tsx
|
import { RefObject, useMemo } from 'react';
import { useSelector } from 'react-redux';
import { c } from 'ttag';
import { ContextMenu, ContextMenuButton, ContextSeparator, DropdownSizeUnit } from '@proton/components';
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { MARK_AS_STATUS } from '../../hooks/actions/useMarkAs';
import { useLabelActions } from '../../hooks/useLabelActions';
import { elementsAreUnread as elementsAreUnreadSelector } from '../../logic/elements/elementsSelectors';
interface Props {
checkedIDs: string[];
elementID?: string;
labelID: string;
anchorRef: RefObject<HTMLElement>;
isOpen: boolean;
position?: {
top: number;
left: number;
};
open: () => void;
close: () => void;
onMarkAs: (status: MARK_AS_STATUS) => void;
onMove: (labelID: string) => void;
onDelete: () => void;
canShowBlockSender: boolean;
onBlockSender: () => Promise<void>;
conversationMode: boolean;
}
const ItemContextMenu = ({
checkedIDs,
elementID,
labelID,
onMove,
onDelete,
onMarkAs,
canShowBlockSender,
onBlockSender,
conversationMode,
...rest
}: Props) => {
const elementsAreUnread = useSelector(elementsAreUnreadSelector);
const buttonMarkAsRead = useMemo(() => {
const allRead = checkedIDs.every((elementID) => !elementsAreUnread[elementID]);
return !allRead;
}, [checkedIDs, elementsAreUnread]);
const [actions] = useLabelActions(labelID);
const handleMove = (labelID: string) => {
onMove(labelID);
rest.close();
};
const handleDelete = () => {
onDelete();
rest.close();
};
const handleMarkAs = (status: MARK_AS_STATUS) => {
onMarkAs(status);
rest.close();
};
const inbox = (
<ContextMenuButton
key="context-menu-inbox"
testId="context-menu-inbox"
icon="inbox"
name={c('Action').t`Move to inbox`}
action={() => handleMove(MAILBOX_LABEL_IDS.INBOX)}
/>
);
const nospam = (
<ContextMenuButton
key="context-menu-nospam"
testId="context-menu-nospam"
icon="fire-slash"
name={c('Action').t`Move to inbox (not spam)`}
action={() => handleMove(MAILBOX_LABEL_IDS.INBOX)}
/>
);
const archive = (
<ContextMenuButton
key="context-menu-archive"
testId="context-menu-archive"
icon="archive-box"
name={c('Action').t`Move to archive`}
action={() => handleMove(MAILBOX_LABEL_IDS.ARCHIVE)}
/>
);
const trash = (
<ContextMenuButton
key="context-menu-trash"
testId="context-menu-trash"
icon="trash"
name={c('Action').t`Move to trash`}
action={() => handleMove(MAILBOX_LABEL_IDS.TRASH)}
/>
);
const spam = (
<ContextMenuButton
key="context-menu-spam"
testId="context-menu-spam"
icon="fire"
name={c('Action').t`Move to spam`}
action={() => handleMove(MAILBOX_LABEL_IDS.SPAM)}
/>
);
const deleteButton = (
<ContextMenuButton
key="context-menu-delete"
testId="context-menu-delete"
icon="cross-circle"
name={c('Action').t`Delete`}
action={() => handleDelete()}
/>
);
const allMoveButtons = { inbox, trash, archive, spam, nospam, delete: deleteButton };
const moveButtons = actions.map((action) => allMoveButtons[action]);
return (
<>
<ContextMenu size={{ maxHeight: DropdownSizeUnit.Viewport }} {...rest}>
{moveButtons}
{canShowBlockSender && (
<ContextMenuButton
key="context-menu-block"
testId="context-menu-block"
icon="circle-slash"
name={c('Action').t`Block sender`}
action={onBlockSender}
/>
)}
<ContextSeparator />
{buttonMarkAsRead ? (
<ContextMenuButton
key="context-menu-read"
testId="context-menu-read"
icon="envelope-open"
name={c('Action').t`Mark as read`}
action={() => handleMarkAs(MARK_AS_STATUS.READ)}
/>
) : (
<ContextMenuButton
key="context-menu-unread"
testId="context-menu-unread"
icon="envelope-dot"
name={c('Action').t`Mark as unread`}
action={() => handleMarkAs(MARK_AS_STATUS.UNREAD)}
/>
)}
</ContextMenu>
</>
);
};
export default ItemContextMenu;
| 3,514
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/ItemDate.test.tsx
|
import { render } from '../../helpers/test/render';
import { Conversation } from '../../models/conversation';
import { Element } from '../../models/element';
import ItemDate from './ItemDate';
const element = {
ID: 'elementID',
Time: 1672531200,
} as Element;
const snoozedElement = {
ID: 'elementID',
Time: 1672531200,
Labels: [
{
ID: '16',
ContextSnoozeTime: 1704067200,
},
],
} as Conversation;
describe('ItemDate', () => {
it('Should display regular date with simple mode', async () => {
const { getByTestId } = await render(<ItemDate element={element} labelID="1" />);
expect(getByTestId('item-date-simple'));
});
it('Should display regular date with distance mode', async () => {
const { getByTestId } = await render(<ItemDate element={element} labelID="1" mode="distance" />);
expect(getByTestId('item-date-distance'));
});
it('Should display the snooze time when snooze time and in list view while in snooze folder', async () => {
const { getByTestId } = await render(<ItemDate element={snoozedElement} labelID="16" isInListView />);
expect(getByTestId('item-date-snoozed'));
});
it('Should not display the snooze time when snooze time and in list view and in inbox', async () => {
const { queryByTestId } = await render(<ItemDate element={snoozedElement} labelID="0" isInListView />);
expect(queryByTestId('item-date-snoozed')).toBeNull();
});
it('Should display regular date with simple mode when not in list', async () => {
const { getByTestId } = await render(<ItemDate element={snoozedElement} labelID="1" />);
expect(getByTestId('item-date-simple'));
});
it('Should display regular date with distance mode when not in list', async () => {
const { getByTestId } = await render(<ItemDate element={snoozedElement} labelID="1" mode="distance" />);
expect(getByTestId('item-date-distance'));
});
});
| 3,515
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/ItemDate.tsx
|
import { useEffect, useMemo, useState } from 'react';
import { useSelector } from 'react-redux';
import { formatDistanceToNow, formatFullDate, formatSimpleDate } from '../../helpers/date';
import { getDate } from '../../helpers/elements';
import { params } from '../../logic/elements/elementsSelectors';
import { getSnoozeTimeFromElement, isElementReminded, isElementSnoozed } from '../../logic/snoozehelpers';
import { Element } from '../../models/element';
import ItemDateRender from './ItemDateRender';
import ItemDateSnoozedMessage from './ItemDateSnoozedMessage';
const REFRESH_DATE_INTERVAL = 60 * 1000;
type FormaterType = 'simple' | 'full' | 'distance';
const FORMATTERS = {
simple: formatSimpleDate,
full: formatFullDate,
distance: formatDistanceToNow,
};
interface Props {
element: Element | undefined;
labelID: string;
className?: string;
mode?: FormaterType;
useTooltip?: boolean;
isInListView?: boolean;
}
const ItemDate = ({ element, labelID, className, mode = 'simple', useTooltip = false, isInListView }: Props) => {
const formatter = FORMATTERS[mode];
const { conversationMode } = useSelector(params);
const [formattedDate, setFormattedDate] = useState(() => {
const date = getDate(element, labelID);
return date.getTime() === 0 ? '' : formatter(date);
});
const fullDate = useMemo(() => {
const date = getDate(element, labelID);
return date.getTime() === 0 ? '' : FORMATTERS.full(date);
}, [element, labelID]);
useEffect(() => {
const date = getDate(element, labelID);
if (date.getTime() === 0) {
return;
}
const update = () => setFormattedDate(formatter(date));
update();
if (mode === 'distance' || mode === 'simple') {
const intervalID = setInterval(update, REFRESH_DATE_INTERVAL);
return () => clearInterval(intervalID);
}
}, [element, mode, labelID]);
// Displays the orange date when the element has a snooze label
// Displays the orange "Reminded" text when the element has DisplaySnoozedReminder
const snoozeTime = getSnoozeTimeFromElement(element);
const isReminded = isElementReminded(element);
const isSnoozed = isElementSnoozed(element, conversationMode);
if (isInListView && (isReminded || (isSnoozed && snoozeTime))) {
return (
<ItemDateSnoozedMessage
element={element}
labelID={labelID}
className={className}
snoozeTime={snoozeTime}
useTooltip={useTooltip}
/>
);
}
return (
<ItemDateRender
className={className}
useTooltip={useTooltip}
formattedDate={formattedDate}
fullDate={fullDate}
dataTestId={`item-date-${mode}`}
/>
);
};
export default ItemDate;
| 3,516
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/ItemDateRender.tsx
|
import { Tooltip } from '@proton/components/components';
interface Props {
className?: string;
useTooltip?: boolean;
fullDate: string;
formattedDate: string;
dataTestId: string;
}
const ItemDateRender = ({ className, useTooltip, formattedDate, fullDate, dataTestId }: Props) => {
const itemDate = (
<>
<time
dateTime={fullDate}
className={className}
title={useTooltip ? undefined : fullDate}
aria-hidden="true"
data-testid={dataTestId}
>
{formattedDate}
</time>
<span className="sr-only">{fullDate}</span>
</>
);
if (useTooltip) {
return (
<Tooltip title={fullDate}>
<span>{itemDate}</span>
</Tooltip>
);
}
return <>{itemDate}</>;
};
export default ItemDateRender;
| 3,517
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/ItemDateSnoozedMessage.scss
|
.item-date-snoozed {
color: var(--signal-warning-major-2);
.item-is-selected & {
color: inherit;
}
}
| 3,518
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/ItemDateSnoozedMessage.test.tsx
|
import { render } from '@testing-library/react';
import { addDays, addYears, getUnixTime } from 'date-fns';
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { formatFullDate, formatScheduledTimeString } from '../../helpers/date';
import { Conversation } from '../../models/conversation';
import ItemDateSnoozedMessage from './ItemDateSnoozedMessage';
const snoozedMessage = {
ID: '1',
ConversationID: '1',
SnoozeTime: 1672531200,
} as Message;
const remindedConversation = {
ID: '1',
DisplaySnoozedReminder: true,
} as Conversation;
describe('ItemDateSnoozedMessage', () => {
it('Should display the snooze time when user is in Snooze folder', () => {
const { getByTestId } = render(
<ItemDateSnoozedMessage
snoozeTime={snoozedMessage.SnoozeTime}
element={snoozedMessage}
labelID={MAILBOX_LABEL_IDS.SNOOZED}
useTooltip={false}
/>
);
expect(getByTestId('item-date-snoozed'));
});
it('Should display today when the snooze time is today', () => {
const today = new Date();
const formattedDate = formatScheduledTimeString(today);
const snoozeTime = getUnixTime(today);
const { getByText } = render(
<ItemDateSnoozedMessage
snoozeTime={snoozeTime}
element={{ ...snoozedMessage, SnoozeTime: snoozeTime }}
labelID={MAILBOX_LABEL_IDS.SNOOZED}
useTooltip={false}
/>
);
expect(getByText(`${formattedDate}`));
});
it('Should display tomorrow when the snooze time is tomorrow', () => {
const tomorrow = addDays(new Date(), 1);
const formattedDate = formatScheduledTimeString(tomorrow);
const snoozeTime = getUnixTime(tomorrow);
const { getByText } = render(
<ItemDateSnoozedMessage
snoozeTime={snoozeTime}
element={{ ...snoozedMessage, SnoozeTime: snoozeTime }}
labelID={MAILBOX_LABEL_IDS.SNOOZED}
useTooltip={false}
/>
);
expect(getByText(`Tomorrow, ${formattedDate}`));
});
it('Should display the full date when the snooze time is not today or tomorrow', () => {
const date = addYears(new Date(), 1);
const formattedDate = formatFullDate(date);
const snoozeTime = getUnixTime(date);
const { getByText } = render(
<ItemDateSnoozedMessage
snoozeTime={snoozeTime}
element={{ ...snoozedMessage, SnoozeTime: snoozeTime }}
labelID={MAILBOX_LABEL_IDS.SNOOZED}
useTooltip={false}
/>
);
expect(getByText(formattedDate));
});
it('Should not display the snooze time when user is in Inbox folder', () => {
const { queryByTestId } = render(
<ItemDateSnoozedMessage
snoozeTime={snoozedMessage.SnoozeTime}
element={snoozedMessage}
labelID={MAILBOX_LABEL_IDS.INBOX}
useTooltip={false}
/>
);
expect(queryByTestId('item-date-snooze')).toBeNull();
});
it('Should display reminded when message is a reminded conversation and user is in Inbox folder', () => {
const { getByTestId } = render(
<ItemDateSnoozedMessage
snoozeTime={snoozedMessage.SnoozeTime}
element={remindedConversation}
labelID={MAILBOX_LABEL_IDS.INBOX}
useTooltip={false}
/>
);
expect(getByTestId('item-date-reminded'));
});
it('Should not display reminded when message is a not a reminded conversation and user is in Inbox folder', () => {
const { queryByTestId } = render(
<ItemDateSnoozedMessage
snoozeTime={snoozedMessage.SnoozeTime}
element={{ ...remindedConversation, DisplaySnoozedReminder: false }}
labelID={MAILBOX_LABEL_IDS.INBOX}
useTooltip={false}
/>
);
expect(queryByTestId('item-date-reminded')).toBeNull();
});
});
| 3,519
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/ItemDateSnoozedMessage.tsx
|
import { useMemo } from 'react';
import { format, isToday, isTomorrow } from 'date-fns';
import { c } from 'ttag';
import { Icon } from '@proton/components';
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { dateLocale } from '@proton/shared/lib/i18n';
import clsx from '@proton/utils/clsx';
import { formatDateToHuman, formatFullDate, formatSimpleDate } from '../../helpers/date';
import { isElementReminded } from '../../logic/snoozehelpers';
import { Element } from '../../models/element';
import ItemDateRender from './ItemDateRender';
import './ItemDateSnoozedMessage.scss';
interface Props {
snoozeDate: Date;
className?: string;
useTooltip?: boolean;
}
const SnoozedDate = ({ snoozeDate, className, useTooltip = false }: Props) => {
const snoozeShortDate = useMemo(() => {
const { formattedTime } = formatDateToHuman(snoozeDate);
const dateString = formatSimpleDate(snoozeDate);
if (isToday(snoozeDate)) {
return formattedTime;
}
if (isTomorrow(snoozeDate)) {
return c('Info').t`Tomorrow, ${formattedTime}`;
}
return `${dateString}, ${formattedTime}`;
}, [snoozeDate]);
const fullDate = formatFullDate(snoozeDate);
return (
<ItemDateRender
className={clsx(className, 'item-date-snoozed')}
useTooltip={useTooltip}
fullDate={fullDate}
formattedDate={snoozeShortDate}
dataTestId="item-date-snoozed"
/>
);
};
const RemindedConversation = ({ className, snoozeDate }: { className?: string; snoozeDate: Date }) => {
const snoozeTime = useMemo(() => {
if (isToday(snoozeDate)) {
return format(snoozeDate, 'p', { locale: dateLocale });
}
return format(snoozeDate, 'PP', { locale: dateLocale });
}, [snoozeDate]);
return (
<span
className={clsx(className, 'item-date-snoozed flex flex-align-items-center')}
data-testid="item-date-reminded"
>
<Icon name="bell" className="mr-1" />
<span>{snoozeTime}</span>
</span>
);
};
const ItemDateSnoozeMessage = ({
element,
labelID,
snoozeTime,
useTooltip,
className,
}: {
element?: Element;
labelID: string;
useTooltip: boolean;
snoozeTime?: number;
className?: string;
}) => {
if (!element) {
return null;
}
const isReminded = isElementReminded(element);
const snoozeDate = snoozeTime ? new Date(snoozeTime * 1000) : undefined;
if (!snoozeDate) {
return null;
}
if (snoozeTime && labelID !== MAILBOX_LABEL_IDS.INBOX && !isReminded) {
return <SnoozedDate snoozeDate={snoozeDate} className={className} useTooltip={useTooltip} />;
} else if (isReminded) {
return <RemindedConversation className={className} snoozeDate={snoozeDate} />;
}
return null;
};
export default ItemDateSnoozeMessage;
| 3,520
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/ItemHoverButtons.tsx
|
import { MouseEvent } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { Icon, Tooltip } from '@proton/components';
import { useLoading } from '@proton/hooks';
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import clsx from '@proton/utils/clsx';
import { isMessage, isStarred as testIsStarred, isUnread as testIsUnread } from '../../helpers/elements';
import { MARK_AS_STATUS, useMarkAs } from '../../hooks/actions/useMarkAs';
import { useMoveToFolder } from '../../hooks/actions/useMoveToFolder';
import { useStar } from '../../hooks/actions/useStar';
import { selectSnoozeDropdownState, selectSnoozeElement } from '../../logic/snooze/snoozeSliceSelectors';
import { useAppSelector } from '../../logic/store';
import { Element } from '../../models/element';
import SnoozeDropdown from './snooze/containers/SnoozeDropdown';
const { READ, UNREAD } = MARK_AS_STATUS;
const { ARCHIVE, TRASH } = MAILBOX_LABEL_IDS;
interface Props {
element: Element; // Element of the current line
labelID: string;
elementID?: string; // ElementID of the currently selected element
className?: string;
onBack: () => void;
hasStar?: boolean;
size?: 'small' | 'medium';
}
const ItemHoverButtons = ({
element,
labelID,
elementID,
className,
onBack,
hasStar = true,
size = 'medium',
}: Props) => {
const markAs = useMarkAs();
const { moveToFolder, moveScheduledModal, moveSnoozedModal } = useMoveToFolder();
const star = useStar();
const snoozedElement = useAppSelector(selectSnoozeElement);
const snoozeDropdownState = useAppSelector(selectSnoozeDropdownState);
const [loadingStar, withLoadingStar] = useLoading();
const isUnread = testIsUnread(element, labelID);
const isStarred = testIsStarred(element || ({} as Element));
const handleMarkAs = (event: MouseEvent) => {
event.stopPropagation();
if (element.ID === elementID && !isUnread) {
onBack();
}
markAs([element], labelID, isUnread ? READ : UNREAD);
};
const handleArchive = (event: MouseEvent) => {
event.stopPropagation();
void moveToFolder([element], ARCHIVE, c('Title').t`Archive`, labelID, false);
};
const handleTrash = (event: MouseEvent) => {
event.stopPropagation();
void moveToFolder([element], TRASH, c('Title').t`Trash`, labelID, false);
};
const handleStar = (event: MouseEvent) => {
event.stopPropagation();
if (!loadingStar) {
void withLoadingStar(star([element], !isStarred));
}
};
const unreadIcon = isUnread ? 'envelope-open' : 'envelope-dot';
const unreadAlt = isUnread ? c('Title').t`Mark as read` : c('Title').t`Mark as unread`;
const starIcon = isStarred ? 'star-filled' : 'star';
const starAlt = isMessage(element)
? isStarred
? c('Alt').t`Unstar message`
: c('Alt').t`Star message`
: isStarred
? c('Alt').t`Unstar conversation`
: c('Alt').t`Star conversation`;
const buttonTxt = isMessage(element) ? c('Alt').t`Star message` : c('Alt').t`Star conversation`;
return (
<>
<div
className={clsx(
'hidden md:flex flex-nowrap flex-justify-space-between relative item-hover-action-buttons',
snoozeDropdownState && snoozedElement?.ID === element.ID
? 'item-hover-action-buttons--dropdown-open'
: '',
className
)}
>
<Tooltip title={unreadAlt} tooltipClassName="no-pointer-events">
<Button icon shape="ghost" size={size} className="color-inherit" onClick={handleMarkAs}>
<Icon name={unreadIcon} alt={unreadAlt} />
</Button>
</Tooltip>
<Tooltip title={c('Action').t`Move to trash`} tooltipClassName="no-pointer-events">
<Button
icon
shape="ghost"
size={size}
className="color-inherit"
onClick={handleTrash}
disabled={labelID === TRASH}
>
<Icon name="trash" alt={c('Action').t`Move to trash`} />
</Button>
</Tooltip>
<Tooltip title={c('Action').t`Move to archive`} tooltipClassName="no-pointer-events">
<Button
icon
shape="ghost"
size={size}
className="color-inherit"
onClick={handleArchive}
disabled={labelID === ARCHIVE}
>
<Icon name="archive-box" alt={c('Action').t`Move to archive`} />
</Button>
</Tooltip>
<SnoozeDropdown elements={[element]} size={size} labelID={labelID} />
{hasStar && (
<Tooltip title={starAlt} tooltipClassName="no-pointer-events">
<Button
icon
shape="ghost"
size={size}
onClick={handleStar}
className={clsx(
'color-inherit starbutton item-star',
isStarred && 'starbutton--is-starred'
)}
aria-pressed={isStarred}
>
<Icon name={starIcon} alt={buttonTxt} />
</Button>
</Tooltip>
)}
</div>
{moveScheduledModal}
{moveSnoozedModal}
</>
);
};
export default ItemHoverButtons;
| 3,521
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/ItemIcon.tsx
|
import { Icon, useFolderColor } from '@proton/components';
import { Folder } from '@proton/shared/lib/interfaces/Folder';
import { FolderInfo } from '../../helpers/labels';
interface Props {
folderInfo: FolderInfo;
}
const ItemIcon = ({ folderInfo }: Props) => {
const folder = { Name: folderInfo.name, Color: folderInfo.color, ParentID: folderInfo.parentID } as Folder;
const color = useFolderColor(folder);
if (folderInfo.icon !== 'folder') {
return <Icon name={folderInfo.icon} alt={folderInfo.name} />;
}
return <Icon name={color ? 'folder-filled' : 'folder'} color={color} alt={folderInfo.name} />;
};
export default ItemIcon;
| 3,522
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/ItemLabels.tsx
|
import { useHistory } from 'react-router-dom';
import { LabelStack } from '@proton/components';
import { toMap } from '@proton/shared/lib/helpers/object';
import { Label } from '@proton/shared/lib/interfaces/Label';
import clsx from '@proton/utils/clsx';
import isTruthy from '@proton/utils/isTruthy';
import orderBy from '@proton/utils/orderBy';
import { getLabelIDs } from '../../helpers/elements';
import { useApplyLabels } from '../../hooks/actions/useApplyLabels';
import { Element } from '../../models/element';
interface Props {
element?: Element;
labelID: string;
labels?: Label[];
className?: string;
isCollapsed?: boolean;
maxNumber?: number;
showDropdown?: boolean;
}
const ItemLabels = ({
element,
labelID,
labels = [],
className = '',
isCollapsed = true,
maxNumber,
showDropdown = true,
}: Props) => {
const applyLabels = useApplyLabels();
const labelIDs = Object.keys(getLabelIDs(element, labelID));
const labelsMap = toMap(labels);
const labelsObjects = labelIDs.map((ID) => labelsMap[ID]).filter(isTruthy);
const labelsSorted = orderBy(labelsObjects, 'Order') as Label[];
const history = useHistory();
if (!labelsSorted.length) {
return null;
}
const handleGo = (label: Label) => () => history.push(`/${label.ID}`);
const handleUnlabel = (labelID: string) => () =>
applyLabels([element || ({} as Element)], { [labelID]: false }, false);
const labelsDescription = labelsSorted.map((label) => ({
name: label.Name,
color: label.Color,
title: label.Name,
onClick: handleGo(label),
onDelete: handleUnlabel(label.ID),
}));
return (
<LabelStack
labels={labelsDescription}
className={clsx([className, isCollapsed && 'flex-justify-end'])}
isStacked={isCollapsed}
maxNumber={maxNumber}
showDropDown={showDropdown}
/>
);
};
export default ItemLabels;
| 3,523
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/ItemLocation.tsx
|
import { Tooltip, useFolders } from '@proton/components';
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import clsx from '@proton/utils/clsx';
import useMailModel from 'proton-mail/hooks/useMailModel';
import { getCurrentFolders, getStandardFolders } from '../../helpers/labels';
import { Element } from '../../models/element';
import ItemIcon from './ItemIcon';
const { ALL_SENT, ALL_DRAFTS } = MAILBOX_LABEL_IDS;
interface Props {
element: Element | undefined;
labelID: string;
shouldStack?: boolean;
showTooltip?: boolean;
withDefaultMargin?: boolean;
ignoreIconFilter?: boolean;
}
const ItemLocation = ({
element,
labelID,
shouldStack = false,
showTooltip = true,
withDefaultMargin = true,
ignoreIconFilter = false,
}: Props) => {
const mailSettings = useMailModel('MailSettings');
const [customFolders = []] = useFolders();
let infos = getCurrentFolders(element, labelID, customFolders, mailSettings);
// At some places, we want to display all icons except the current location for some folders (all sent and all drafts)
if (!ignoreIconFilter) {
const labelsWithoutIcons: string[] = [ALL_SENT, ALL_DRAFTS];
if (labelsWithoutIcons.includes(labelID)) {
const STANDARD_FOLDERS = getStandardFolders();
const labelsWithoutIconsToI18N = [STANDARD_FOLDERS[ALL_SENT].name, STANDARD_FOLDERS[ALL_DRAFTS].name];
infos = infos.filter((info) => !labelsWithoutIconsToI18N.includes(info.name));
}
}
if (infos.length > 1 && shouldStack) {
infos = [
{
to: infos.map((info) => info.to).join(','),
name: infos.map((info) => info.name).join(', '),
icon: 'folders',
},
];
}
return (
<>
{infos.map((folderInfo) => (
<Tooltip title={showTooltip ? folderInfo.name : undefined} key={folderInfo.to}>
<span
className={clsx(['flex flex-item-noshrink pt-0.5', withDefaultMargin && 'mr-1'])}
data-testid={`item-location-${folderInfo.name}`}
>
<ItemIcon folderInfo={folderInfo} />
</span>
</Tooltip>
))}
</>
);
};
export default ItemLocation;
| 3,524
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/ItemRowLayout.tsx
|
import { ReactNode, useMemo } from 'react';
import { c, msgid } from 'ttag';
import { useFlag } from '@proton/components/containers/unleash';
import { Label } from '@proton/shared/lib/interfaces/Label';
import { AttachmentsMetadata } from '@proton/shared/lib/interfaces/mail/Message';
import { getHasOnlyIcsAttachments } from '@proton/shared/lib/mail/messages';
import clsx from '@proton/utils/clsx';
import ItemAttachmentThumbnails from 'proton-mail/components/list/ItemAttachmentThumbnails';
import { MAX_ROW_ATTACHMENT_THUMBNAILS } from 'proton-mail/constants';
import { canShowAttachmentThumbnails } from 'proton-mail/helpers/attachment/attachmentThumbnails';
import { useEncryptedSearchContext } from '../../containers/EncryptedSearchProvider';
import { useExpiringElement } from '../../hooks/useExpiringElement';
import { selectSnoozeDropdownState, selectSnoozeElement } from '../../logic/snooze/snoozeSliceSelectors';
import { useAppSelector } from '../../logic/store';
import { Element } from '../../models/element';
import { ESMessage } from '../../models/encryptedSearch';
import NumMessages from '../conversation/NumMessages';
import ItemAction from './ItemAction';
import ItemAttachmentIcon from './ItemAttachmentIcon';
import ItemDate from './ItemDate';
import ItemHoverButtons from './ItemHoverButtons';
import ItemLabels from './ItemLabels';
import ItemLocation from './ItemLocation';
import ItemStar from './ItemStar';
import ItemUnread from './ItemUnread';
import ItemExpiration from './item-expiration/ItemExpiration';
interface Props {
isCompactView: boolean;
labelID: string;
elementID?: string;
labels?: Label[];
element: Element;
conversationMode: boolean;
showIcon: boolean;
senders: ReactNode;
unread: boolean;
onBack: () => void;
attachmentsMetadata: AttachmentsMetadata[];
}
const ItemRowLayout = ({
isCompactView,
labelID,
elementID,
labels,
element,
conversationMode,
showIcon,
senders,
unread,
onBack,
attachmentsMetadata,
}: Props) => {
const { shouldHighlight, highlightMetadata, esStatus } = useEncryptedSearchContext();
const highlightData = shouldHighlight();
const { contentIndexingDone } = esStatus;
const canSeeThumbnailsFeature = useFlag('AttachmentThumbnails');
const snoozedElement = useAppSelector(selectSnoozeElement);
const snoozeDropdownState = useAppSelector(selectSnoozeDropdownState);
const { expirationTime, hasExpiration } = useExpiringElement(element, labelID, conversationMode);
const body = contentIndexingDone ? (element as ESMessage).decryptedBody : undefined;
const { Subject } = element;
const subjectContent = useMemo(
() => (highlightData && Subject ? highlightMetadata(Subject, unread, true).resultJSX : Subject),
[Subject, highlightData, highlightMetadata, unread]
);
const { resultJSX, numOccurrences } = useMemo(
() =>
body && highlightData ? highlightMetadata(body, unread, true) : { resultJSX: undefined, numOccurrences: 0 },
[body, unread, highlightData, highlightMetadata]
);
const bodyTitle = c('Info').ngettext(
msgid`${numOccurrences} occurrence found`,
`${numOccurrences} occurrences found`,
numOccurrences
);
const hasOnlyIcsAttachments = getHasOnlyIcsAttachments(element?.AttachmentInfo);
const showThumbnails = canShowAttachmentThumbnails(
isCompactView,
element,
attachmentsMetadata,
canSeeThumbnailsFeature
);
return (
<div className="flex-nowrap flex-column w-full">
<div className="flex-item-fluid flex flex-align-items-center flex-nowrap flex-row item-titlesender">
<div className="my-auto flex w-custom" style={{ '--w-custom': '2em' }} data-testid={unread}>
<ItemStar element={element} />
</div>
<div className={clsx(['item-senders flex flex-nowrap m-auto pr-4', unread && 'text-bold'])}>
<ItemUnread element={element} labelID={labelID} className="mr-0.5 item-unread-dot" />
<ItemAction element={element} className="mr-2 flex-item-noshrink my-auto" />
<span
className="max-w-full text-ellipsis flex flex-align-items-center"
data-testid="message-row:sender-address"
>
{senders}
</span>
</div>
<div className="item-subject flex-item-fluid flex flex-align-items-center flex-nowrap m-auto">
<div className="flex flex-column inline-block w-full">
<span
role="heading"
aria-level={2}
className={clsx(['max-w-full text-ellipsis mr-4', unread && 'text-bold'])}
title={Subject}
data-testid="message-row:subject"
>
{showIcon && (
<span className="mr-1 inline-flex flex-item-noshrink align-bottom">
<ItemLocation element={element} labelID={labelID} />
</span>
)}
{conversationMode && (
<NumMessages
className={clsx(['mr-1 flex-item-noshrink', unread && 'text-bold'])}
conversation={element}
/>
)}
{subjectContent}
</span>
{!!resultJSX && highlightData && (
<>
<span
className={clsx(['max-w-full text-ellipsis mr-4', unread && 'text-bold'])}
title={bodyTitle}
aria-hidden="true"
>
{resultJSX}
</span>
<span className="sr-only">{bodyTitle}</span>
</>
)}
</div>
</div>
<ItemLabels
labels={labels}
element={element}
labelID={labelID}
maxNumber={1}
className="flex-item-noshrink ml-auto"
showDropdown={false}
isCollapsed={false}
/>
<span
className="flex flex-nowrap w-custom ml-2 text-center flex-justify-end"
style={{ '--w-custom': '7em' }}
>
{hasExpiration && (
<ItemExpiration expirationTime={expirationTime} element={element} labelID={labelID} />
)}
<ItemAttachmentIcon
icon={hasOnlyIcsAttachments ? 'calendar-grid' : undefined}
element={element}
className="flex-item-noshrink ml-2"
/>
</span>
<span
className="ml-4 flex w-custom flex-nowrap flex-align-items-center flex-justify-end"
style={{ '--w-custom': '13em' }}
>
<ItemHoverButtons
element={element}
labelID={labelID}
elementID={elementID}
onBack={onBack}
hasStar={false}
size={isCompactView ? 'small' : 'medium'}
/>
<span
className={clsx(
'item-senddate-row ml-2 flex flex-item-fluid flex-nowrap flex-justify-end flex-align-items-center',
snoozeDropdownState && snoozedElement?.ID === element.ID && 'invisible'
)}
>
<ItemDate
element={element}
labelID={labelID}
className={unread ? 'text-bold' : undefined}
isInListView
/>
</span>
</span>
</div>
<div className="flex-item-fluid flex flex-align-items-center flex-nowrap flex-row">
<div className="my-auto flex w-custom" style={{ '--w-custom': '2em' }}></div>
<div className={clsx(['item-senders flex pr-4'])}></div>
{showThumbnails && (
<ItemAttachmentThumbnails
attachmentsMetadata={attachmentsMetadata}
maxAttachment={MAX_ROW_ATTACHMENT_THUMBNAILS}
className="flex-item-fluid attachment-thumbnail-row"
/>
)}
</div>
</div>
);
};
export default ItemRowLayout;
| 3,525
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/ItemSenders.tsx
|
import { useMemo } from 'react';
import { c } from 'ttag';
import { ProtonBadgeType } from '@proton/components/components';
import { canonicalizeInternalEmail } from '@proton/shared/lib/helpers/email';
import { Recipient } from '@proton/shared/lib/interfaces';
import uniqueBy from '@proton/utils/uniqueBy';
import { useEncryptedSearchContext } from '../../containers/EncryptedSearchProvider';
import { getElementSenders } from '../../helpers/recipients';
import { useRecipientLabel } from '../../hooks/contact/useRecipientLabel';
import { Element } from '../../models/element';
interface Props {
element: Element;
conversationMode: boolean;
loading: boolean;
unread: boolean;
displayRecipients: boolean;
isSelected: boolean;
}
const ItemSenders = ({ element, conversationMode, loading, unread, displayRecipients, isSelected }: Props) => {
const { shouldHighlight, highlightMetadata } = useEncryptedSearchContext();
const highlightData = shouldHighlight();
const { getRecipientsOrGroups, getRecipientOrGroupLabel } = useRecipientLabel();
const senders = useMemo(() => {
const senders = getElementSenders(element, conversationMode, displayRecipients);
return uniqueBy(senders, ({ Address }: Recipient) => canonicalizeInternalEmail(Address));
}, [element, conversationMode, displayRecipients]);
const sendersAsRecipientOrGroup = useMemo(() => {
return getRecipientsOrGroups(senders);
}, [senders]);
const recipientsAddresses = useMemo(() => {
return sendersAsRecipientOrGroup
.map(({ recipient, group }) =>
recipient ? recipient.Address : group?.recipients.map((recipient) => recipient.Address)
)
.flat()
.join(', ');
}, [sendersAsRecipientOrGroup]);
if (!loading && displayRecipients && senders.length === 0) {
return <>{c('Info').t`(No Recipient)`}</>;
}
return (
<span
className="inline-block max-w-full text-ellipsis"
title={recipientsAddresses}
data-testid="message-column:sender-address"
>
{sendersAsRecipientOrGroup.map((sender, index) => {
const isLastItem = index === sendersAsRecipientOrGroup.length - 1;
const recipientLabel = getRecipientOrGroupLabel(sender);
// this fix works when there is 1 official recipient only (not with multiple), to be sure the official badge is shown
if (isLastItem && index === 0 && !!sender.recipient?.IsProton) {
return (
<span className="inline-flex flex-nowrap max-w-full" key={`${recipientLabel}-${index}`}>
<span className="flex-item-fluid text-ellipsis">
{highlightData
? highlightMetadata(recipientLabel, unread, true).resultJSX
: recipientLabel}{' '}
</span>
{sender.recipient && <ProtonBadgeType recipient={sender.recipient} selected={isSelected} />}
</span>
);
}
return (
<span key={`${recipientLabel}-${index}`}>
{highlightData ? highlightMetadata(recipientLabel, unread, true).resultJSX : recipientLabel}
{sender.recipient && <ProtonBadgeType recipient={sender.recipient} selected={isSelected} />}
{!isLastItem && <span className="mr-1">,</span>}
</span>
);
})}
</span>
);
};
export default ItemSenders;
| 3,526
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/ItemStar.tsx
|
import { MouseEvent } from 'react';
import { c } from 'ttag';
import { Kbd } from '@proton/atoms';
import { Icon, IconSize, Tooltip } from '@proton/components';
import { useLoading } from '@proton/hooks';
import clsx from '@proton/utils/clsx';
import useMailModel from 'proton-mail/hooks/useMailModel';
import { isMessage, isStarred as testIsStarred } from '../../helpers/elements';
import { useStar } from '../../hooks/actions/useStar';
import { Element } from '../../models/element';
interface Props {
element?: Element;
size?: IconSize;
}
const ItemStar = ({ element, size }: Props) => {
const [loading, withLoading] = useLoading();
const star = useStar();
const { Shortcuts } = useMailModel('MailSettings');
const isStarred = testIsStarred(element || ({} as Element));
const title = isMessage(element)
? isStarred
? c('Alt').t`Unstar message`
: c('Alt').t`Star message`
: isStarred
? c('Alt').t`Unstar conversation`
: c('Alt').t`Star conversation`;
const buttonTxt = isMessage(element) ? c('Alt').t`Star message` : c('Alt').t`Star conversation`;
const handleClick = async (event: MouseEvent) => {
event.stopPropagation();
// Programmatically block the action instead of disabling the action
// Perhaps a bit less accessible but prevent to collapse a message on a second click
if (!loading) {
void withLoading(star([element || ({} as Element)], !isStarred));
}
};
return (
<Tooltip
title={
Shortcuts ? (
<>
{title}
<br />
<Kbd shortcut="*" />
</>
) : (
title
)
}
>
<button
data-testid={`item-star-${isStarred}`}
type="button"
className={clsx([
'starbutton relative item-star flex stop-propagation',
isStarred && 'starbutton--is-starred',
])}
onClick={handleClick}
aria-pressed={isStarred}
>
<Icon size={size} name={isStarred ? 'star-filled' : 'star'} />
<span className="sr-only">{buttonTxt}</span>
</button>
</Tooltip>
);
};
export default ItemStar;
| 3,527
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/ItemUnread.tsx
|
import { c } from 'ttag';
import { Icon, Tooltip } from '@proton/components';
import { isUnread } from '../../helpers/elements';
import { Element } from '../../models/element';
interface Props {
element: Element | undefined;
labelID: string;
className?: string;
isSelected?: boolean;
}
const ItemUnread = ({ element, labelID, className, isSelected }: Props) => {
const unread = isUnread(element, labelID);
if (!unread) {
return null;
}
return (
<Tooltip title={c('Alt').t`Unread email`}>
<span className={className}>
<Icon
name="circle-filled"
size={12}
className={!isSelected ? 'color-primary' : undefined}
alt={c('Alt').t`Unread email`}
/>
</span>
</Tooltip>
);
};
export default ItemUnread;
| 3,528
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/List.tsx
|
import { ChangeEvent, Fragment, ReactNode, Ref, RefObject, forwardRef, memo, useEffect, useMemo } from 'react';
import { c, msgid } from 'ttag';
import { PaginationRow, useConversationCounts, useItemsDraggable, useMessageCounts } from '@proton/components';
import { DENSITY } from '@proton/shared/lib/constants';
import { CHECKLIST_DISPLAY_TYPE, UserSettings } from '@proton/shared/lib/interfaces';
import clsx from '@proton/utils/clsx';
import useMailModel from 'proton-mail/hooks/useMailModel';
import { useEncryptedSearchContext } from '../../containers/EncryptedSearchProvider';
import { useGetStartedChecklist } from '../../containers/onboardingChecklist/provider/GetStartedChecklistProvider';
import { isMessage as testIsMessage } from '../../helpers/elements';
import { isColumnMode } from '../../helpers/mailSettings';
import { MARK_AS_STATUS } from '../../hooks/actions/useMarkAs';
import { usePaging } from '../../hooks/usePaging';
import { usePlaceholders } from '../../hooks/usePlaceholders';
import { Element } from '../../models/element';
import { Filter } from '../../models/tools';
import { Breakpoints } from '../../models/utils';
import UsersOnboardingChecklist from '../checklist/UsersOnboardingChecklist';
import EmptyListPlaceholder from '../view/EmptyListPlaceholder';
import Item from './Item';
import ListBanners from './ListBanners';
import { ResizeHandle } from './ResizeHandle';
import useEncryptedSearchList from './useEncryptedSearchList';
import { useItemContextMenu } from './useItemContextMenu';
const defaultCheckedIDs: string[] = [];
const defaultElements: Element[] = [];
const { FULL, REDUCED } = CHECKLIST_DISPLAY_TYPE;
interface Props {
show: boolean;
labelID: string;
loading: boolean;
placeholderCount: number;
elementID?: string;
columnLayout: boolean;
elements?: Element[];
checkedIDs?: string[];
onCheck: (ID: string[], checked: boolean, replace: boolean) => void;
onCheckOne: (event: ChangeEvent, ID: string) => void;
onClick: (elementID: string | undefined) => void;
onFocus: (number: number) => void;
conversationMode: boolean;
isSearch: boolean;
breakpoints: Breakpoints;
page: number;
total: number | undefined;
onPage: (page: number) => void;
filter: Filter;
resizeAreaRef: Ref<HTMLButtonElement>;
enableResize: () => void;
resetWidth: () => void;
showContentPanel: boolean;
scrollBarWidth: number;
onMarkAs: (status: MARK_AS_STATUS) => void;
onMove: (labelID: string) => void;
onDelete: () => void;
onBack: () => void;
userSettings: UserSettings;
toolbar?: ReactNode | undefined;
}
const List = (
{
show,
labelID,
loading,
placeholderCount,
elementID,
columnLayout,
elements: inputElements = defaultElements,
checkedIDs = defaultCheckedIDs,
onCheck,
onClick,
conversationMode,
isSearch,
breakpoints,
page: inputPage,
total: inputTotal,
onPage,
onFocus,
onCheckOne,
filter,
resizeAreaRef,
enableResize,
resetWidth,
showContentPanel,
scrollBarWidth,
onMarkAs,
onDelete,
onMove,
onBack,
userSettings,
toolbar,
}: Props,
ref: Ref<HTMLDivElement>
) => {
const mailSettings = useMailModel('MailSettings');
const { shouldHighlight, esStatus } = useEncryptedSearchContext();
// Override compactness of the list view to accomodate body preview when showing encrypted search results
const { contentIndexingDone, esEnabled } = esStatus;
const shouldOverrideCompactness = shouldHighlight() && contentIndexingDone && esEnabled;
const isCompactView = userSettings.Density === DENSITY.COMPACT && !shouldOverrideCompactness;
const { displayState, changeChecklistDisplay } = useGetStartedChecklist();
// We want to display placeholders only when we are currently loading elements AND we don't have elements already
const displayPlaceholders = loading && inputElements?.length === 0;
const elements = usePlaceholders(inputElements, displayPlaceholders, placeholderCount);
const pagingHandlers = usePaging(inputPage, inputTotal, onPage);
const { total, page } = pagingHandlers;
const [messageCounts] = useMessageCounts();
const [conversationCounts] = useConversationCounts();
// Reduce the checklist if there are more than 4 elements in the view
useEffect(() => {
if (inputElements.length >= 5 && displayState === FULL) {
changeChecklistDisplay(REDUCED);
}
}, [elements]);
// ES options: offer users the option to turn off ES if it's taking too long, and
// enable/disable UI elements for incremental partial searches
const { isESLoading, showESSlowToolbar, loadingElement, disableGoToLast, useLoadingElement } =
useEncryptedSearchList(isSearch, loading, page, total);
const { draggedIDs, handleDragStart, handleDragEnd } = useItemsDraggable(
elements,
checkedIDs,
onCheck,
(draggedIDs) => {
const isMessage = elements.length && testIsMessage(elements[0]);
const selectionCount = draggedIDs.length;
return isMessage
? c('Success').ngettext(
msgid`Move ${selectionCount} message`,
`Move ${selectionCount} messages`,
selectionCount
)
: c('Success').ngettext(
msgid`Move ${selectionCount} conversation`,
`Move ${selectionCount} conversations`,
selectionCount
);
}
);
const { contextMenu, onContextMenu, blockSenderModal } = useItemContextMenu({
elementID,
labelID,
anchorRef: ref as RefObject<HTMLElement>,
checkedIDs,
onCheck,
onMarkAs,
onMove,
onDelete,
conversationMode,
});
const unreads = useMemo(() => {
const counters = conversationMode ? conversationCounts : messageCounts;
return (counters || []).find((counter) => counter.LabelID === labelID)?.Unread || 0;
}, [conversationMode, labelID, conversationCounts, messageCounts]);
return (
<div className={clsx(['relative items-column-list', !show && 'hidden'])}>
<div ref={ref} className={clsx(['h-full', isCompactView && 'list-compact'])}>
<h1 className="sr-only">
{conversationMode ? c('Title').t`Conversation list` : c('Title').t`Message list`}{' '}
{c('Title').ngettext(msgid`${unreads} unread message`, `${unreads} unread messages`, unreads)}
</h1>
<div
className={clsx(
breakpoints.isDesktop && 'items-column-list-inner bg-norm',
!columnLayout && 'items-column-list-inner--border-none',
'flex flex-nowrap flex-column relative items-column-list-inner--mail overflow-hidden h-full'
)}
data-testid={`message-list-${displayPlaceholders ? 'loading' : 'loaded'}`}
>
<div className="flex-item-noshrink">{toolbar}</div>
<div className="h-full scroll-if-needed flex flex-column flex-nowrap w-full">
<div className="flex-item-noshrink">
<ListBanners
labelID={labelID}
columnLayout={columnLayout}
userSettings={userSettings}
esState={{ isESLoading, isSearch, showESSlowToolbar }}
/>
</div>
{elements.length === 0 && displayState !== FULL && (
<EmptyListPlaceholder
labelID={labelID}
isSearch={isSearch}
isUnread={filter.Unread === 1}
/>
)}
{elements.length === 0 && displayState === FULL && <UsersOnboardingChecklist />}
{elements.length > 0 && (
<>
{/* div needed here for focus management */}
<div
className={clsx(
!columnLayout && 'border-right border-weak',
'w-full flex-item-noshrink'
)}
>
{elements.map((element, index) => (
<Fragment key={element.ID}>
<Item
conversationMode={conversationMode}
isCompactView={isCompactView}
labelID={labelID}
loading={displayPlaceholders}
columnLayout={columnLayout}
elementID={elementID}
element={element}
checked={checkedIDs.includes(element.ID || '')}
onCheck={onCheckOne}
onClick={onClick}
onContextMenu={onContextMenu}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
dragged={draggedIDs.includes(element.ID || '')}
index={index}
breakpoints={breakpoints}
onFocus={onFocus}
onBack={onBack}
/>
</Fragment>
))}
</div>
{!loading && !(total > 1) && (
<>
{displayState === FULL && (
<UsersOnboardingChecklist displayOnMobile={isColumnMode(mailSettings)} />
)}
</>
)}
{useLoadingElement && loadingElement}
{!loading && total > 1 && (
<div className="p-5 flex flex-column flex-align-items-center flex-item-noshrink">
<PaginationRow
{...pagingHandlers}
disabled={loading}
disableGoToLast={disableGoToLast}
/>
</div>
)}
</>
)}
</div>
</div>
</div>
{elements.length !== 0 && showContentPanel && (
<ResizeHandle
resizeAreaRef={resizeAreaRef}
enableResize={enableResize}
resetWidth={resetWidth}
scrollBarWidth={scrollBarWidth}
/>
)}
{contextMenu}
{blockSenderModal}
</div>
);
};
export default memo(forwardRef(List));
| 3,529
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/ListBanners.test.tsx
|
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { DENSITY, MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { UserSettings } from '@proton/shared/lib/interfaces';
import { mockUseApi, mockUseEventManager, mockUseHistory, mockUseSelector, mockUseUser } from '@proton/testing/index';
import { mockUseEncryptedSearchContext } from 'proton-mail/helpers/test/mockUseEncryptedSearchContext';
import ListBanners from './ListBanners';
import { mockUseAutoDeleteBanner, mockUseShowUpsellBanner } from './ListBanners.test.utils';
const baseProps = {
labelID: MAILBOX_LABEL_IDS.INBOX,
columnLayout: false,
userSettings: { Density: DENSITY.COMFORTABLE } as UserSettings,
esState: {
isESLoading: false,
isSearch: false,
showESSlowToolbar: false,
},
};
describe('ListBanners', () => {
beforeEach(() => {
mockUseEncryptedSearchContext();
mockUseAutoDeleteBanner();
mockUseSelector();
mockUseShowUpsellBanner();
mockUseUser();
});
it('should display no banner', () => {
const { container } = render(<ListBanners {...baseProps} />);
expect(container).toBeEmptyDOMElement();
});
describe('when showESSlowToolbar is true', () => {
let mockedOpenDropdown = jest.fn();
let mockedSetTemporaryToggleOff = jest.fn();
beforeEach(() => {
mockUseEncryptedSearchContext({
openDropdown: mockedOpenDropdown,
setTemporaryToggleOff: mockedSetTemporaryToggleOff,
});
});
it('should display es slow banner', async () => {
render(
<ListBanners
{...baseProps}
esState={{
isESLoading: false,
isSearch: false,
showESSlowToolbar: true,
}}
/>
);
expect(screen.getByText(/Search taking too long\?/i)).toBeInTheDocument();
const refineButton = screen.getByRole('button', { name: /Refine it/ });
await userEvent.click(refineButton);
await waitFor(() => {
expect(mockedOpenDropdown).toHaveBeenCalledTimes(1);
});
const excludeButton = screen.getByRole('button', { name: /exclude message content/ });
await userEvent.click(excludeButton);
await waitFor(() => {
expect(mockedSetTemporaryToggleOff).toHaveBeenCalledTimes(1);
});
expect(screen.getByText(/from this search session./i)).toBeInTheDocument();
});
});
describe('when user is in almost all mail and using es', () => {
const mockedPush = jest.fn();
beforeEach(() => {
mockUseHistory({ push: mockedPush });
});
it('should display almost all mail banner', async () => {
render(
<ListBanners
{...baseProps}
labelID={MAILBOX_LABEL_IDS.ALMOST_ALL_MAIL}
esState={{
isESLoading: false,
isSearch: false,
showESSlowToolbar: false,
}}
/>
);
expect(screen.getByText(/Can't find what you're looking for\?/i)).toBeInTheDocument();
const includeButton = screen.getByRole('button', { name: /Include Spam\/Trash/i });
await userEvent.click(includeButton);
await waitFor(() => {
expect(mockedPush).toHaveBeenCalledTimes(1);
});
expect(mockedPush).toHaveBeenCalledWith('/all-mail');
});
});
describe('when canDisplayUpsellBanner is true', () => {
beforeEach(() => {
mockUseShowUpsellBanner({ canDisplayUpsellBanner: true });
jest.spyOn(global.Math, 'random').mockReturnValue(0.349);
});
it('should render upsell banner', () => {
render(<ListBanners {...baseProps} />);
expect(screen.getByText(/Use keyboard shortcuts to manage your email faster./i)).toBeInTheDocument();
expect(screen.getByText(/Learn more/i)).toBeInTheDocument();
});
});
describe('when canDisplayTaskRunningBanner is true', () => {
it('should display task running banner', async () => {
mockUseSelector(true);
render(<ListBanners {...baseProps} />);
expect(screen.getByText(/Moving messages. This may take a while./i)).toBeInTheDocument();
});
});
describe('when condition for auto delete is true', () => {
beforeEach(() => {
mockUseApi();
mockUseEventManager();
mockUseAutoDeleteBanner('paid-banner');
});
it('should display auto delete banner', async () => {
render(<ListBanners {...baseProps} labelID={MAILBOX_LABEL_IDS.TRASH} />);
expect(
screen.getByText(
/Automatically delete messages that have been in trash and spam for more than 30 days./i
)
).toBeInTheDocument();
});
});
});
| 3,530
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/ListBanners.test.utils.ts
|
import * as useShowUpsellBannerModule from 'proton-mail/hooks/useShowUpsellBanner';
import * as useAutoDeleteBannerModule from './banners/auto-delete/useAutodeleteBanner';
export const mockUseAutoDeleteBanner = (value?: Partial<ReturnType<typeof useAutoDeleteBannerModule.default>>) => {
const mockedUseAutoDeleteBanner = jest.spyOn(useAutoDeleteBannerModule, 'default');
mockedUseAutoDeleteBanner.mockReturnValue(value ?? 'hide');
return mockedUseAutoDeleteBanner;
};
export const mockUseShowUpsellBanner = (value?: Partial<ReturnType<typeof useShowUpsellBannerModule.default>>) => {
const mockedUseShowUpsellBanner = jest.spyOn(useShowUpsellBannerModule, 'default');
mockedUseShowUpsellBanner.mockReturnValue({
canDisplayUpsellBanner: false,
needToShowUpsellBanner: { current: false },
handleDismissBanner: jest.fn(),
...value,
});
return mockedUseShowUpsellBanner;
};
| 3,531
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/ListBanners.tsx
|
import { ReactNode, memo } from 'react';
import { useSelector } from 'react-redux';
import { DENSITY, MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { UserSettings } from '@proton/shared/lib/interfaces';
import clsx from '@proton/utils/clsx';
import { isAllowedAutoDeleteLabelID } from 'proton-mail/helpers/autoDelete';
import { useEncryptedSearchContext } from '../../containers/EncryptedSearchProvider';
import useShowUpsellBanner from '../../hooks/useShowUpsellBanner';
import { showLabelTaskRunningBanner } from '../../logic/elements/elementsSelectors';
import {
AlmostAllMailBanner,
AutoDeleteBanner,
EsSlowBanner,
MailUpsellBanner,
TaskRunningBanner,
useAutoDeleteBanner,
} from './banners';
interface Props {
labelID: string;
columnLayout: boolean;
userSettings: UserSettings;
esState: {
isESLoading: boolean;
isSearch: boolean;
showESSlowToolbar: boolean;
};
}
type BannerId = 'es-slow' | 'almost-all-mail' | 'mail-upsell' | 'task-running' | 'auto-delete';
interface Banner {
id: BannerId;
banner: () => ReactNode;
condition: () => boolean;
canWith?: BannerId[];
}
const ListBanners = ({
labelID,
columnLayout,
userSettings,
esState: { isESLoading, showESSlowToolbar: canDisplayESSlowToolbar },
}: Props) => {
const { shouldHighlight, esStatus } = useEncryptedSearchContext();
// Override compactness of the list view to accomodate body preview when showing encrypted search results
const { contentIndexingDone, esEnabled } = esStatus;
const shouldOverrideCompactness = shouldHighlight() && contentIndexingDone && esEnabled;
const isCompactView = userSettings.Density === DENSITY.COMPACT && !shouldOverrideCompactness;
const bannerType = useAutoDeleteBanner(labelID);
const canDisplayTaskRunningBanner = useSelector(showLabelTaskRunningBanner);
const { canDisplayUpsellBanner, needToShowUpsellBanner, handleDismissBanner } = useShowUpsellBanner(labelID);
/**
* By default every banner is not stackable, and is displayed by ascending priority order
* `canWith` field can enable a banner stacking under a whitelisted other
*/
const banners: Banner[] = [
{
id: 'es-slow',
banner: () => (
<EsSlowBanner
key="es-slow"
className={clsx([columnLayout ? 'mt-2' : 'my-3', isCompactView && 'mb-2'])}
/>
),
condition: () => canDisplayESSlowToolbar,
},
{
id: 'almost-all-mail',
banner: () => (
<AlmostAllMailBanner
key="almost-all-mail"
className={clsx([columnLayout ? 'mt-2' : 'my-3', isCompactView && 'mb-2'])}
/>
),
condition: () => !isESLoading && labelID === MAILBOX_LABEL_IDS.ALMOST_ALL_MAIL,
},
{
id: 'mail-upsell',
banner: () => (
<MailUpsellBanner
key="mail-upsell"
needToShowUpsellBanner={needToShowUpsellBanner}
columnMode={columnLayout}
onClose={handleDismissBanner}
/>
),
condition: () => canDisplayUpsellBanner,
},
{
id: 'task-running',
banner: () => (
<TaskRunningBanner
key="task-running"
className={clsx([
!canDisplayESSlowToolbar && 'mt-3',
columnLayout ? 'mb-0' : 'my-3',
isCompactView && 'mb-3',
])}
/>
),
condition: () => canDisplayTaskRunningBanner,
canWith: ['es-slow'],
},
{
id: 'auto-delete',
banner: () => (
<AutoDeleteBanner
key="auto-delete"
columnLayout={columnLayout}
isCompactView={isCompactView}
bannerType={bannerType}
/>
),
condition: () => isAllowedAutoDeleteLabelID(labelID) && !['hide', 'disabled'].includes(bannerType),
},
];
return (
<>
{banners
.reduce((displayedBanners: Banner[], current) => {
// to be displayed, a banner condition must be fulfilled,
// and if other banners more prioritized are already displayed,
// it must have them whitelisted
const canDisplayBanner =
current.condition() && displayedBanners.every(({ id }) => current.canWith?.includes(id));
return canDisplayBanner ? [...displayedBanners, current] : displayedBanners;
}, [])
.map(({ banner }) => banner())}
</>
);
};
export default memo(ListBanners);
| 3,532
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/ListSettings.tsx
|
import { ReactElement, memo } from 'react';
import { MailSettings } from '@proton/shared/lib/interfaces';
import { Filter, Sort } from '../../models/tools';
import FilterActions from '../toolbar/FilterActions';
import SortDropdown from '../toolbar/SortDropdown';
export interface Props {
sort: Sort;
onSort: (sort: Sort) => void;
filter: Filter;
onFilter: (filter: Filter) => void;
conversationMode: boolean;
mailSettings: MailSettings;
isSearch: boolean;
labelID?: string;
selectAll?: ReactElement;
filterAsDropdown?: boolean;
}
const ListSettings = ({
sort,
onSort,
onFilter,
filter,
conversationMode,
mailSettings,
isSearch,
labelID,
selectAll,
filterAsDropdown,
}: Props) => {
return (
<div className="flex flex-nowrap flex-justify-space-between flex-align-items-center gap-2 m-auto">
{selectAll && <div className="mr-auto">{selectAll}</div>}
<FilterActions filter={filter} onFilter={onFilter} mailSettings={mailSettings} dropdown={filterAsDropdown} />
<SortDropdown
conversationMode={conversationMode}
sort={sort}
onSort={onSort}
hasCaret={false}
isSearch={isSearch}
labelID={labelID}
/>
</div>
);
};
export default memo(ListSettings);
| 3,533
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/ResizeHandle.tsx
|
import { Ref } from 'react';
import { c } from 'ttag';
interface Props {
resizeAreaRef: Ref<HTMLButtonElement>;
enableResize: () => void;
resetWidth: () => void;
scrollBarWidth: number;
}
export const ResizeHandle = ({ resizeAreaRef, enableResize, resetWidth, scrollBarWidth }: Props) => {
return (
<div className="resize-area-container" style={{ '--scrollbar-width': scrollBarWidth }}>
<button
type="button"
ref={resizeAreaRef}
className="resize-area-button cursor-col-resize"
onMouseDown={enableResize}
onDoubleClick={resetWidth}
>
<span className="sr-only">{c('Action')
.t`Use your mouse to resize the view. If you're using your keyboard, you can use left and right arrow keys to resize.`}</span>
</button>
</div>
);
};
| 3,534
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/useEncryptedSearchList.tsx
|
import { useEffect, useState } from 'react';
import { c } from 'ttag';
import { EllipsisLoader } from '@proton/components';
import { SECOND } from '@proton/shared/lib/constants';
import { useEncryptedSearchContext } from '../../containers/EncryptedSearchProvider';
const useEncryptedSearchList = (isSearch: boolean, loading: boolean, page: number, total: number) => {
const { esStatus } = useEncryptedSearchContext();
const { dbExists, esEnabled, isSearchPartial, isSearching, getCacheStatus } = esStatus;
const [esTimer, setESTimer] = useState<NodeJS.Timeout>(setTimeout(() => {}));
const [esTimerExpired, setESTimerExpired] = useState<boolean>(false);
const { isCacheLimited, isCacheReady } = getCacheStatus();
const [ESCacheReady, setESCacheReady] = useState(isCacheReady);
const isLastPage = page === total;
const isESLoading = isSearch && loading && dbExists && esEnabled && isSearching;
const showESSlowToolbar = esTimerExpired && isESLoading;
const searchLimitedMode = isSearch && !loading && dbExists && esEnabled && isCacheLimited;
const disableGoToLast = searchLimitedMode && isSearchPartial;
const useLoadingElement =
isSearch &&
esEnabled &&
isLastPage &&
(!isCacheReady || searchLimitedMode) &&
(isSearching || !isSearchPartial);
const loadingText = isSearching ? c('Info').t`Loading` : c('Info').t`No more results found`;
const loadingElement = (
<div className="flex flex-nowrap flex-align-items-center flex-justify-center color-weak my-6">
{loadingText}
{isSearching && <EllipsisLoader />}
</div>
);
useEffect(() => {
if (isESLoading) {
setESTimer(() =>
setTimeout(() => {
setESTimerExpired(() => true);
}, 5 * SECOND)
);
} else {
clearTimeout(esTimer);
setESTimerExpired(() => false);
}
}, [isESLoading]);
useEffect(() => {
if (!esEnabled || (esEnabled && ESCacheReady)) {
return;
}
// If ES is enabled and cache not ready, wait until it becomes ready
const interval = setInterval(() => {
const { isCacheReady } = getCacheStatus();
if (isCacheReady) {
setESCacheReady(true);
clearInterval(interval);
}
}, 1000);
return () => {
clearInterval(interval);
};
}, [esEnabled]);
return {
isESLoading,
showESSlowToolbar,
loadingElement,
disableGoToLast,
useLoadingElement,
ESCacheReady,
};
};
export default useEncryptedSearchList;
| 3,535
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/useItemContextMenu.tsx
|
import { RefObject, useCallback, useState } from 'react';
import { MARK_AS_STATUS } from '../../hooks/actions/useMarkAs';
import { useGetElementsFromIDs } from '../../hooks/mailbox/useElements';
import useBlockSender from '../../hooks/useBlockSender';
import { Element } from '../../models/element';
import ItemContextMenu from './ItemContextMenu';
interface Props {
elementID?: string;
labelID: string;
anchorRef: RefObject<HTMLElement>;
checkedIDs: string[];
onCheck: (IDs: string[], checked: boolean, replace: boolean) => void;
onMarkAs: (status: MARK_AS_STATUS) => void;
onMove: (labelID: string) => void;
onDelete: () => void;
conversationMode: boolean;
}
export const useItemContextMenu = ({
elementID,
labelID,
anchorRef,
checkedIDs,
onCheck,
onMarkAs,
onMove,
onDelete,
conversationMode,
}: Props) => {
const [selectedElement, setSelectedElement] = useState<Element>();
const [isContextMenuOpen, setIsOpen] = useState(false);
const [contextMenuPosition, setContextMenuPosition] = useState<{ top: number; left: number }>();
const closeContextMenu = useCallback(() => setIsOpen(false), [setIsOpen]);
const openContextMenu = useCallback(() => setIsOpen(true), [setIsOpen]);
const getElementsFromIDs = useGetElementsFromIDs();
const { canShowBlockSender, handleClickBlockSender, blockSenderModal } = useBlockSender({
elements: [...(getElementsFromIDs([selectedElement?.ID || '']) || ({} as Element))],
onCloseDropdown: closeContextMenu,
});
const handleContextMenu = useCallback(
(e: React.MouseEvent<HTMLDivElement>, element: Element) => {
e.stopPropagation();
e.preventDefault();
if (!checkedIDs.includes(element.ID)) {
onCheck([element.ID], true, true);
}
setContextMenuPosition({ top: e.clientY, left: e.clientX });
setSelectedElement(element);
openContextMenu();
},
[checkedIDs]
);
const contextMenu = (
<ItemContextMenu
anchorRef={anchorRef}
isOpen={isContextMenuOpen}
open={openContextMenu}
close={closeContextMenu}
position={contextMenuPosition}
elementID={elementID}
labelID={labelID}
checkedIDs={checkedIDs}
onMarkAs={onMarkAs}
onMove={onMove}
onDelete={onDelete}
canShowBlockSender={canShowBlockSender}
onBlockSender={handleClickBlockSender}
conversationMode={conversationMode}
/>
);
return {
contextMenu,
onContextMenu: handleContextMenu,
blockSenderModal,
};
};
| 3,536
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/useScrollToTop.test.ts
|
import { useState } from 'react';
import { renderHook } from '@testing-library/react-hooks';
import useScrollToTop from './useScrollToTop';
describe('useScrollToTop', () => {
it('should scroll to top', () => {
renderHook(() => {
const ref = { current: { scrollTop: 10 } } as React.RefObject<HTMLElement>;
useScrollToTop(ref, []);
if (!ref.current) {
throw new Error('ref.current is undefined');
}
expect(ref.current.scrollTop).toBe(0);
});
});
it('should scroll to top if dependencies are changing', () => {
renderHook(() => {
const ref = { current: { scrollTop: 10 } } as React.RefObject<HTMLElement>;
const [dependencies, setDependencies] = useState([1]);
if (!ref.current) {
throw new Error('ref.current is undefined');
}
useScrollToTop(ref, dependencies);
expect(ref.current.scrollTop).toBe(0);
ref.current.scrollTop = 10;
expect(ref.current.scrollTop).toBe(10);
setDependencies([2]);
expect(ref.current.scrollTop).toBe(0);
});
});
});
| 3,537
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/useScrollToTop.ts
|
import { DependencyList, RefObject, useEffect } from 'react';
// Scroll to top of list when page or label changes
const useScrollToTop = (ref: RefObject<HTMLElement>, dependencies: DependencyList) => {
const scrollTop = () => {
if (ref.current && ref.current.scrollTop !== 0) {
ref.current.scrollTop = 0;
}
};
useEffect(() => {
scrollTop();
}, dependencies);
};
export default useScrollToTop;
| 3,538
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners/index.ts
|
export { default as AlmostAllMailBanner } from './almost-all-mail/AlmostAllMailBanner';
export { default as AutoDeleteBanner } from './auto-delete/AutoDeleteBanner';
export { default as useAutoDeleteBanner } from './auto-delete/useAutodeleteBanner';
export { default as EsSlowBanner } from './es-slow/EsSlowBanner';
export { default as MailUpsellBanner } from './mail-upsell/MailUpsellBanner';
export { default as TaskRunningBanner } from './task-running/TaskRunningBanner';
| 3,539
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners/almost-all-mail/AlmostAllMailBanner.test.tsx
|
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { mockUseHistory } from '@proton/testing/index';
import { getHumanLabelID } from 'proton-mail/helpers/labels';
import AlmostAllMailBanner from './AlmostAllMailBanner';
describe('AlmostAllMailBanner', () => {
beforeEach(() => {
mockUseHistory({
location: {
pathname: `/${getHumanLabelID(MAILBOX_LABEL_IDS.INBOX)}`,
search: '',
state: {},
hash: '',
},
});
});
describe('when use is in AlmostAllMail location', () => {
let mockedPush: jest.Mock;
beforeEach(() => {
mockedPush = jest.fn();
mockUseHistory({
push: mockedPush,
});
});
it('should render banner', () => {
render(<AlmostAllMailBanner />);
expect(screen.getByText("Can't find what you're looking for?")).toBeInTheDocument();
const button = screen.getByRole('button', { name: /Include Spam\/Trash/ });
expect(button).toBeInTheDocument();
});
describe('when user click on banner button', () => {
it('should push new route to history', async () => {
render(<AlmostAllMailBanner />);
const button = screen.getByRole('button', { name: /Include Spam\/Trash/ });
expect(button).toBeInTheDocument();
await userEvent.click(button);
await waitFor(() => {
expect(mockedPush).toHaveBeenCalledTimes(1);
});
expect(mockedPush).toHaveBeenCalledWith('/all-mail');
});
});
});
});
| 3,540
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners/almost-all-mail/AlmostAllMailBanner.tsx
|
import { useHistory } from 'react-router-dom';
import { c } from 'ttag';
import { Icon, InlineLinkButton } from '@proton/components/components';
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { changeSearchParams } from '@proton/shared/lib/helpers/url';
import clsx from '@proton/utils/clsx';
import { getHumanLabelID } from 'proton-mail/helpers/labels';
interface Props {
className?: string;
}
const AlmostAllMailBanner = ({ className }: Props) => {
const history = useHistory();
const { push, location } = history;
const displayAllMailButton = (
<InlineLinkButton
key="redirect-all-mail"
onClick={() => {
push(changeSearchParams(`/${getHumanLabelID(MAILBOX_LABEL_IDS.ALL_MAIL)}`, location.hash));
}}
>{c('Info').t`Include Spam/Trash.`}</InlineLinkButton>
);
return (
<div className={clsx(['bg-weak rounded mx-2 px-4 py-2 flex flex-nowrap', className])}>
<div className="flex-item-noshrink">
<Icon name="magnifier" className="mr-2" />
</div>
<div className="flex-item-fluid pl-1">
{
// translator: sentence appear when a user has AlmostAllMail setting on, excluding spam/trash. Complete sentence example: "Can't find what you're looking for? <Include Spam/Trash.>"
c('Info').jt`Can't find what you're looking for? ${displayAllMailButton}`
}
</div>
</div>
);
};
export default AlmostAllMailBanner;
| 3,541
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners/auto-delete/AutoDeleteBanner.test.tsx
|
import { render, screen } from '@testing-library/react';
import AutoDeleteBanner from './AutoDeleteBanner';
describe('AutoDeleteBanner', () => {
describe('when bannerType is paid', () => {
it('should render correct banner', () => {
render(<AutoDeleteBanner bannerType="paid-banner" />);
expect(
screen.getByText(
/Automatically delete messages that have been in trash and spam for more than 30 days./i
)
).toBeInTheDocument();
});
});
describe('when bannerType is free', () => {
it('should render correct banner', () => {
render(<AutoDeleteBanner bannerType="free-banner" />);
expect(
screen.getByText(
/Upgrade to automatically delete messages that have been in trash and spam for more than 30 days./i
)
).toBeInTheDocument();
});
});
describe('when bannerType is enabled', () => {
it('should render correct banner', () => {
render(<AutoDeleteBanner bannerType="enabled" />);
expect(
screen.getByText(
/Messages that have been in trash and spam more than 30 days will be automatically deleted./i
)
).toBeInTheDocument();
});
});
});
| 3,542
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners/auto-delete/AutoDeleteBanner.tsx
|
import { AutoDeleteBannerType } from './useAutodeleteBanner';
import AutoDeleteEnabledBanner from './variations/AutoDeleteEnabledBanner';
import AutoDeleteFreeBanner from './variations/AutoDeleteFreeBanner';
import AutoDeletePaidBanner from './variations/AutoDeletePaidBanner';
interface Props {
columnLayout?: boolean;
isCompactView?: boolean;
bannerType: AutoDeleteBannerType;
}
const AutoDeleteBanner = ({ bannerType, columnLayout = false, isCompactView = false }: Props) => {
return (
<div data-testid="auto-delete:banner">
{bannerType === 'free-banner' && <AutoDeleteFreeBanner />}
{bannerType === 'paid-banner' && <AutoDeletePaidBanner />}
{bannerType === 'enabled' && (
<AutoDeleteEnabledBanner columnLayout={columnLayout} isCompactView={isCompactView} />
)}
</div>
);
};
export default AutoDeleteBanner;
| 3,543
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners/auto-delete/useAutoDeleteBanner.test.ts
|
import { renderHook } from '@testing-library/react-hooks';
import { MAILBOX_LABEL_IDS as IDS } from '@proton/shared/lib/constants';
import { mockUseFeature, mockUseMailSettings, mockUseUser } from '@proton/testing/index';
import { LABEL_IDS_TO_HUMAN as TO_HUMAN } from '../../../../constants';
import useAutoDeleteBanner from './useAutodeleteBanner';
describe('AutoDeleteBanner', () => {
beforeEach(() => {
mockUseFeature({ feature: { Value: true } as any });
mockUseUser();
mockUseMailSettings();
});
describe('when feature is not active', () => {
it('should not render when', async () => {
mockUseFeature({ feature: { Value: false } as any });
mockUseUser([{ isFree: true }]);
const { result } = await renderHook(() => useAutoDeleteBanner(IDS.SPAM));
expect(result.current).toBe('hide');
});
});
describe('when setting is deactivated and user is paid', () => {
it('should not render banner', async () => {
mockUseFeature({ feature: { Value: true } as any });
mockUseUser([{ isPaid: true }]);
const { result } = await renderHook(() => useAutoDeleteBanner(IDS.SPAM));
expect(result.current).toBe('disabled');
});
});
describe('user is not in enabled location', () => {
it.each`
labelID | labelName
${IDS.ALL_DRAFTS} | ${TO_HUMAN[IDS.ALL_DRAFTS] + ' label'}
${IDS.ALL_MAIL} | ${TO_HUMAN[IDS.ALL_MAIL] + ' label'}
${IDS.ALL_SENT} | ${TO_HUMAN[IDS.ALL_SENT] + ' label'}
${IDS.ALMOST_ALL_MAIL} | ${TO_HUMAN[IDS.ALMOST_ALL_MAIL] + ' label'}
${IDS.ARCHIVE} | ${TO_HUMAN[IDS.ARCHIVE] + ' label'}
${IDS.DRAFTS} | ${TO_HUMAN[IDS.DRAFTS] + ' label'}
${IDS.INBOX} | ${TO_HUMAN[IDS.INBOX] + ' label'}
${IDS.OUTBOX} | ${TO_HUMAN[IDS.OUTBOX] + ' label'}
${IDS.SCHEDULED} | ${TO_HUMAN[IDS.SCHEDULED] + ' label'}
${IDS.SENT} | ${TO_HUMAN[IDS.SENT] + ' label'}
${IDS.STARRED} | ${TO_HUMAN[IDS.STARRED] + ' label'}
${'qwdiwfsdas'} | ${'random folder or label id'}
`('should not render banner inside $labelName', async ({ labelID }) => {
mockUseFeature({ feature: { Value: true } as any });
mockUseUser([{ isFree: true }]);
const { result } = await renderHook(() => useAutoDeleteBanner(labelID));
expect(result.current).toBe('hide');
});
});
describe('user is in enabled location', () => {
it.each`
labelID | labelName
${IDS.SPAM} | ${TO_HUMAN[IDS.SPAM]}
${IDS.TRASH} | ${TO_HUMAN[IDS.TRASH]}
`('should render banner inside $labelName', async ({ labelID }) => {
mockUseFeature({ feature: { Value: true } as any });
mockUseUser([{ hasPaidMail: false, isFree: true }]);
const { result } = await renderHook(() => useAutoDeleteBanner(labelID));
expect(result.current).toBe('free-banner');
});
});
describe('When user is free', () => {
const isFree = true;
describe('Setting is null', () => {
it('Should rneder free banner', async () => {
mockUseFeature({ feature: { Value: true } as any });
mockUseUser([{ hasPaidMail: !isFree, isFree }]);
const { result } = await renderHook(() => useAutoDeleteBanner(IDS.SPAM));
expect(result.current).toBe('free-banner');
});
});
describe('Setting is enabled (API should not allow this case)', () => {
it('should rneder free banner', async () => {
mockUseFeature({ feature: { Value: true } as any });
mockUseUser([{ hasPaidMail: !isFree, isFree }]);
mockUseMailSettings([{ AutoDeleteSpamAndTrashDays: 30 }]);
const { result } = await renderHook(() => useAutoDeleteBanner(IDS.SPAM));
expect(result.current).toBe('free-banner');
});
});
describe('Setting is explicitly deactivated (API should not allow this case)', () => {
it('Should rneder free banner', async () => {
mockUseFeature({ feature: { Value: true } as any });
mockUseUser([{ hasPaidMail: !isFree, isFree }]);
mockUseMailSettings([{ AutoDeleteSpamAndTrashDays: 0 }]);
const { result } = await renderHook(() => useAutoDeleteBanner(IDS.SPAM));
expect(result.current).toBe('free-banner');
});
});
});
describe('User is paid', () => {
const isFree = false;
describe('Setting is null and user is paid', () => {
it('Should render paid banner', async () => {
mockUseFeature({ feature: { Value: true } as any });
mockUseUser([{ hasPaidMail: !isFree, isFree }]);
mockUseMailSettings([{ AutoDeleteSpamAndTrashDays: null }]);
const { result } = await renderHook(() => useAutoDeleteBanner(IDS.SPAM));
expect(result.current).toBe('paid-banner');
});
});
describe('Setting is enabled and user is paid', () => {
it('Should render enabled banner', async () => {
mockUseUser([{ hasPaidMail: !isFree, isFree }]);
mockUseFeature({ feature: { Value: true } as any });
mockUseMailSettings([{ AutoDeleteSpamAndTrashDays: 30 }]);
const { result } = await renderHook(() => useAutoDeleteBanner(IDS.SPAM));
expect(result.current).toBe('enabled');
});
});
});
});
| 3,544
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners/auto-delete/useAutodeleteBanner.ts
|
import { FeatureCode } from '@proton/components/containers';
import { useFeature, useUser } from '@proton/components/hooks';
import { AUTO_DELETE_SPAM_AND_TRASH_DAYS } from '@proton/shared/lib/mail/mailSettings';
import useMailModel from 'proton-mail/hooks/useMailModel';
import { isAllowedAutoDeleteLabelID } from '../../../../helpers/autoDelete';
export type AutoDeleteBannerType = 'disabled' | 'enabled' | 'paid-banner' | 'free-banner' | 'hide';
const useAutoDeleteBanner = (labelID: string) => {
const { feature } = useFeature(FeatureCode.AutoDelete);
const [user, userLoading] = useUser();
const mailSetting = useMailModel('MailSettings');
const type: AutoDeleteBannerType = (() => {
const isFeatureActive = feature?.Value === true;
if (!isAllowedAutoDeleteLabelID(labelID) || !isFeatureActive || userLoading) {
return 'hide';
}
if (!user.hasPaidMail) {
return 'free-banner';
}
// User explicitly disabled
if (mailSetting.AutoDeleteSpamAndTrashDays === AUTO_DELETE_SPAM_AND_TRASH_DAYS.DISABLED) {
return 'disabled';
}
// User has not enabled yet
if (user.hasPaidMail && mailSetting.AutoDeleteSpamAndTrashDays === null) {
return 'paid-banner';
}
if (
user.hasPaidMail &&
mailSetting.AutoDeleteSpamAndTrashDays &&
mailSetting.AutoDeleteSpamAndTrashDays > AUTO_DELETE_SPAM_AND_TRASH_DAYS.DISABLED
) {
return 'enabled';
}
return 'hide';
})();
return type;
};
export default useAutoDeleteBanner;
| 3,545
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners/auto-delete
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners/auto-delete/variations/AutoDeleteEnabledBanner.tsx
|
import { c } from 'ttag';
import clsx from '@proton/utils/clsx';
interface Props {
columnLayout: boolean;
isCompactView: boolean;
}
const AutoDeleteEnabledBanner = ({ columnLayout, isCompactView }: Props) => {
return (
<div
data-testid="auto-delete:banner:enabled"
className={clsx(
'p-2 color-hint text-center text-sm auto-delete-banner-enabled',
columnLayout && 'auto-delete-banner-enabled--column',
isCompactView && 'auto-delete-banner-enabled--compact'
)}
>
{c('Info').t`Messages that have been in trash and spam more than 30 days will be automatically deleted.`}
</div>
);
};
export default AutoDeleteEnabledBanner;
| 3,546
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners/auto-delete
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners/auto-delete/variations/AutoDeleteFreeBanner.tsx
|
import React from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms/Button';
import { AutoDeleteUpsellModal, useModalState } from '@proton/components/components';
import { PromotionBanner } from '@proton/components/containers';
const AutoDeleteFreeBanner = () => {
const [upsellModalProps, toggleUpsellModal, renderUpsellModal] = useModalState();
return (
<>
{renderUpsellModal && <AutoDeleteUpsellModal modalProps={upsellModalProps} />}
<PromotionBanner
contentCentered
description={c('Info')
.t`Upgrade to automatically delete messages that have been in trash and spam for more than 30 days.`}
data-testid="auto-delete:banner:free"
cta={
<Button
type="button"
className="text-bold"
shape="underline"
color="norm"
onClick={() => {
toggleUpsellModal(true);
}}
>
{c('Action').t`Upgrade`}
</Button>
}
/>
</>
);
};
export default AutoDeleteFreeBanner;
| 3,547
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners/auto-delete
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners/auto-delete/variations/AutoDeletePaidBanner.tsx
|
import { c } from 'ttag';
import { Button } from '@proton/atoms/Button';
import { PromotionBanner } from '@proton/components/containers';
import { useApi, useEventManager } from '@proton/components/hooks';
import { useLoading } from '@proton/hooks';
import { updateAutoDelete } from '@proton/shared/lib/api/mailSettings';
import { AUTO_DELETE_SPAM_AND_TRASH_DAYS } from '@proton/shared/lib/mail/mailSettings';
const AutoDeletePaidBanner = () => {
const api = useApi();
const { call } = useEventManager();
const [loadingEnable, withLoadingEnable] = useLoading();
const [loadingDisable, withLoadingDisable] = useLoading();
const handleChangeAutoDelete = async (autoDelete: AUTO_DELETE_SPAM_AND_TRASH_DAYS) => {
await api(updateAutoDelete(autoDelete));
await call();
};
return (
<PromotionBanner
contentCentered
description={c('Info')
.t`Automatically delete messages that have been in trash and spam for more than 30 days.`}
data-testid="auto-delete:banner:paid"
hasDismissAction
onClose={() => {
if (!loadingDisable) {
void withLoadingDisable(handleChangeAutoDelete(AUTO_DELETE_SPAM_AND_TRASH_DAYS.DISABLED));
}
}}
cta={
<Button
loading={loadingEnable}
disabled={loadingDisable}
type="button"
color="norm"
className="text-bold"
shape="underline"
onClick={() => {
void withLoadingEnable(handleChangeAutoDelete(AUTO_DELETE_SPAM_AND_TRASH_DAYS.ACTIVE));
}}
>
{c('Action').t`Enable`}
</Button>
}
/>
);
};
export default AutoDeletePaidBanner;
| 3,548
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners/es-slow/EsSlowBanner.tsx
|
import { memo, useMemo } from 'react';
import { c } from 'ttag';
import { Icon, InlineLinkButton, useUser } from '@proton/components';
import { sendSlowSearchReport } from '@proton/encrypted-search';
import clsx from '@proton/utils/clsx';
import { useEncryptedSearchContext } from '../../../../containers/EncryptedSearchProvider';
interface Props {
className?: string;
}
const EsSlowBanner = ({ className }: Props) => {
const [{ ID: userID }] = useUser();
const { openDropdown, setTemporaryToggleOff } = useEncryptedSearchContext();
useMemo(() => {
void sendSlowSearchReport(userID);
}, []);
const dropdownButton = (
<InlineLinkButton className="px-1" onClick={openDropdown} key="dropdownButton">
{
// translator: sentence appears when a message content search takes too long . Complete sentence example: "Search taking too long? <Refine it> or <exclude message content> from this search session.
c('Action').t`Refine it`
}
</InlineLinkButton>
);
const toggleOffButton = (
<InlineLinkButton className="px-1" onClick={setTemporaryToggleOff} key="toggleOffButton">
{
// translator: sentence appears when a message content search takes too long . Complete sentence example: "Search taking too long? <Refine it> or <exclude message content> from this search session.
c('Action').t`exclude message content`
}
</InlineLinkButton>
);
return (
<div className={clsx(['bg-weak rounded mx-2 px-4 py-2 flex flex-nowrap', className])}>
<div className="flex-item-noshrink">
<Icon name="magnifier" className="mr-2" />
</div>
<div className="flex-item-fluid pl-1">
{
// translator: sentence appears when a message content search takes too long . Complete sentence example: "Search taking too long? <Refine it> or <exclude message content> from this search session.
c('Info')
.jt`Search taking too long? ${dropdownButton} or ${toggleOffButton} from this search session.`
}
</div>
</div>
);
};
export default memo(EsSlowBanner);
| 3,549
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners/mail-upsell/MailUpsellBanner.test.tsx
|
import { screen } from '@testing-library/react';
import { removeItem, setItem } from '@proton/shared/lib/helpers/storage';
import range from '@proton/utils/range';
import { render } from '../../../../helpers/test/render';
import MailUpsellBanner from './MailUpsellBanner';
const props = {
columnMode: true,
needToShowUpsellBanner: { current: true },
onClose: jest.fn(),
};
describe('Mail upsell banner', () => {
afterAll(() => {
removeItem('WelcomePaneEncounteredMessages');
});
it('should display a banner', async () => {
await render(<MailUpsellBanner {...props} />);
screen.getByTestId('promotion-banner');
});
it('should display the expected banner', async () => {
// Fake localStorage so that we can predict which banner will be displayed
// Added more ids in the array (1 to 100) in case we add more banners in the future
// Here we expect to see the banner with the id "2"
setItem('WelcomePaneEncounteredMessages', JSON.stringify([0, 1, ...range(3, 100)]));
await render(<MailUpsellBanner {...props} />);
screen.getByText('Upgrade to send email from @pm.me addresses.');
});
});
| 3,550
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners/mail-upsell/MailUpsellBanner.tsx
|
import { MutableRefObject, ReactNode, useEffect, useMemo, useState } from 'react';
import { c } from 'ttag';
import { Href } from '@proton/atoms';
import { MailShortcutsModal, PromotionBanner, SettingsLink, useModalState, useTheme } from '@proton/components';
import ThemesModal from '@proton/components/containers/themes/ThemesModal';
import {
APP_UPSELL_REF_PATH,
MAIL_APP_NAME,
PROTON_SENTINEL_NAME,
UPSELL_COMPONENT,
VPN_APP_NAME,
} from '@proton/shared/lib/constants';
import { getItem, setItem } from '@proton/shared/lib/helpers/storage';
import { addUpsellPath, getUpsellRef } from '@proton/shared/lib/helpers/upsell';
import isTruthy from '@proton/utils/isTruthy';
import { MAIL_UPSELL_BANNERS_OPTIONS_URLS } from '../../../../constants';
const { plansSelection, vpn, protonBusiness, drive, securityAndPrivacy } = MAIL_UPSELL_BANNERS_OPTIONS_URLS;
enum UPSELL_MAIL_BANNER_LINK_ID {
SEND_FROM_PM_ADDRESS = 3,
GET_MORE_FOLDERS_FILTERS_AND_ADDRESSES = 4,
AUTO_REPLY = 5,
THIRD_PARTY_CLIENTS = 7,
GET_MORE_FEATURES = 9,
HOST_EMAILS_FROM_YOUR_DOMAINS = 15,
PROTECT_YOUR_BUSINESS = 16,
ADD_MORE_ADDRESSES = 17,
CONTACT_GROUPS = 18,
PRIVACY_FIRST_INTERNET = 19,
PRIVACY_FOR_ALL = 20,
PREMIUM_FEATURES = 23,
LVL_UP_PRIVACY = 24,
PROTON_SENTINEL = 25,
}
interface MessageOption {
id: number;
text: string | ReactNode;
cta: ReactNode;
condition?: number;
}
interface Props {
needToShowUpsellBanner: MutableRefObject<boolean>;
columnMode: boolean;
onClose: () => void;
}
const MailUpsellBanner = ({ needToShowUpsellBanner, columnMode, onClose }: Props) => {
const theme = useTheme();
const [option, setOption] = useState<MessageOption>();
const [mailShortcutsProps, setMailShortcutsModalOpen, renderShortcutModal] = useModalState();
const [themesModalProps, setThemesModalOpen, renderThemesModal] = useModalState();
const encounteredMessagesIDs = getItem('WelcomePaneEncounteredMessages');
const callToActionTexts = {
upgrade: c('Action').t`Upgrade`,
business: c('Action').t`See business plans`,
learnMore: c('Action').t`Learn more`,
};
const getLink = (url: string, optionID: number) => {
const upsellPath = getUpsellRef({
app: APP_UPSELL_REF_PATH.MAIL_UPSELL_REF_PATH,
component: UPSELL_COMPONENT.BANNER,
feature: optionID.toString(),
});
return addUpsellPath(url, upsellPath);
};
const messagesOptions: MessageOption[] = useMemo(
() => [
{
id: 2,
text: c('Info').t`Upgrade to send email from @pm.me addresses.`,
cta: (
<SettingsLink
path={getLink(plansSelection, UPSELL_MAIL_BANNER_LINK_ID.SEND_FROM_PM_ADDRESS)}
className="text-bold link align-baseline"
tabIndex={0}
>
{callToActionTexts.upgrade}
</SettingsLink>
),
},
{
id: 3,
text: c('Info').t`Upgrade to create more folders, filters, and addresses.`,
cta: (
<SettingsLink
path={getLink(
plansSelection,
UPSELL_MAIL_BANNER_LINK_ID.GET_MORE_FOLDERS_FILTERS_AND_ADDRESSES
)}
className="text-bold link align-baseline"
>
{callToActionTexts.upgrade}
</SettingsLink>
),
},
{
id: 4,
text: c('Info').t`Upgrade to use auto-reply when you're away.`,
cta: (
<SettingsLink
path={getLink(plansSelection, UPSELL_MAIL_BANNER_LINK_ID.AUTO_REPLY)}
className="text-bold link align-baseline"
tabIndex={0}
>
{callToActionTexts.upgrade}
</SettingsLink>
),
},
{
id: 5,
text: c('Info').t`Upgrade to use ${MAIL_APP_NAME} with Apple Mail, Outlook or Thunderbird.`,
cta: (
<SettingsLink
path={getLink(plansSelection, UPSELL_MAIL_BANNER_LINK_ID.THIRD_PARTY_CLIENTS)}
className="text-bold link align-baseline"
tabIndex={0}
>
{callToActionTexts.upgrade}
</SettingsLink>
),
},
{
id: 7,
text: c('Info').t`Upgrade to support privacy and get more features.`,
cta: (
<SettingsLink
path={getLink(plansSelection, UPSELL_MAIL_BANNER_LINK_ID.GET_MORE_FEATURES)}
className="text-bold link align-baseline"
tabIndex={0}
>
{callToActionTexts.upgrade}
</SettingsLink>
),
},
{
id: 11,
text: c('Info').t`Use keyboard shortcuts to manage your email faster.`,
cta: (
<span
onClick={() => setMailShortcutsModalOpen(true)}
className="text-bold link align-baseline"
tabIndex={0}
>
{callToActionTexts.learnMore}
</span>
),
},
theme.information.default && {
id: 12,
text: c('Info').t`Themes can give your inbox a new look.`,
cta: (
<span
onClick={() => setThemesModalOpen(true)}
className="text-bold link align-baseline"
tabIndex={0}
>
{callToActionTexts.learnMore}
</span>
),
},
{
id: 13,
text: c('Info').t`Upgrade to send emails from your custom email domain.`,
cta: (
<SettingsLink
path={getLink(plansSelection, UPSELL_MAIL_BANNER_LINK_ID.HOST_EMAILS_FROM_YOUR_DOMAINS)}
className="text-bold link align-baseline"
tabIndex={0}
>
{callToActionTexts.upgrade}
</SettingsLink>
),
},
{
id: 14,
text: c('Info').t`${MAIL_APP_NAME} can protect your business as well.`,
cta: (
<SettingsLink
path={getLink(protonBusiness, UPSELL_MAIL_BANNER_LINK_ID.PROTECT_YOUR_BUSINESS)}
className="text-bold link align-baseline"
tabIndex={0}
>
{callToActionTexts.business}
</SettingsLink>
),
},
{
id: 15,
text: c('Info').t`Upgrade to add more addresses to your account.`,
cta: (
<SettingsLink
path={getLink(plansSelection, UPSELL_MAIL_BANNER_LINK_ID.ADD_MORE_ADDRESSES)}
className="text-bold link align-baseline"
tabIndex={0}
>
{callToActionTexts.upgrade}
</SettingsLink>
),
},
{
id: 16,
text: c('Info').t`Upgrade to send emails to contact groups easily.`,
cta: (
<SettingsLink
path={getLink(plansSelection, UPSELL_MAIL_BANNER_LINK_ID.CONTACT_GROUPS)}
className="text-bold link align-baseline"
tabIndex={0}
>
{callToActionTexts.upgrade}
</SettingsLink>
),
},
{
id: 17,
text: c('Info').t`Upgrade to support a privacy-first internet.`,
cta: (
<SettingsLink
path={getLink(plansSelection, UPSELL_MAIL_BANNER_LINK_ID.PRIVACY_FIRST_INTERNET)}
className="text-bold link align-baseline"
tabIndex={0}
>
{callToActionTexts.upgrade}
</SettingsLink>
),
},
{
id: 18,
text: c('Info').t`Upgrade to support our mission of privacy for all.`,
cta: (
<SettingsLink
path={getLink(plansSelection, UPSELL_MAIL_BANNER_LINK_ID.PRIVACY_FOR_ALL)}
className="text-bold link align-baseline"
tabIndex={0}
>
{callToActionTexts.upgrade}
</SettingsLink>
),
},
{
id: 19,
text: c('Info').t`Secure your files with encrypted cloud storage for free, today.`,
cta: (
<Href href={drive} className="text-bold link align-baseline" tabIndex={0}>
{callToActionTexts.learnMore}
</Href>
),
},
{
id: 20,
text: c('Info').t`You can use ${VPN_APP_NAME} for free, today.`,
cta: (
<Href href={vpn} className="text-bold link align-baseline" tabIndex={0}>
{callToActionTexts.learnMore}
</Href>
),
},
{
id: 23,
text: c('Info').t`Upgrade to unlock premium features.`,
cta: (
<SettingsLink
path={getLink(plansSelection, UPSELL_MAIL_BANNER_LINK_ID.PREMIUM_FEATURES)}
className="text-bold link align-baseline"
tabIndex={0}
>
{callToActionTexts.upgrade}
</SettingsLink>
),
},
{
id: 24,
text: c('Info').t`Upgrade to level up your privacy.`,
cta: (
<SettingsLink
path={getLink(plansSelection, UPSELL_MAIL_BANNER_LINK_ID.LVL_UP_PRIVACY)}
className="text-bold link align-baseline"
tabIndex={0}
>
{callToActionTexts.upgrade}
</SettingsLink>
),
},
{
id: 25,
// translator: full sentence: "Join Proton Sentinel program for the highest level of account security and support."
text: c('Info')
.t`Join ${PROTON_SENTINEL_NAME} program for the highest level of account security and support.`,
cta: (
<SettingsLink
path={getLink(securityAndPrivacy, UPSELL_MAIL_BANNER_LINK_ID.PROTON_SENTINEL)}
className="text-bold link align-baseline"
tabIndex={0}
>
{callToActionTexts.learnMore}
</SettingsLink>
),
},
],
[]
).filter(isTruthy);
const getRandomOption = (): MessageOption => {
let hasSeenAllMessages = false;
/*
* Message options can contain less element than the localstorage in the case where the user has triggered a condition in the meantime
* For example, if the user did not have any calendar items, and had all messages displayed, messageOptions now contains fewer items than the
* localStorage array. Instead of checking if length are equals, check if every item of messageOptions have been encountered.
*/
if (encounteredMessagesIDs) {
const idsArray = JSON.parse(encounteredMessagesIDs);
hasSeenAllMessages = messagesOptions.every((option) => idsArray.includes(option.id));
}
const encounteredMessages =
!encounteredMessagesIDs || hasSeenAllMessages ? [] : JSON.parse(encounteredMessagesIDs);
const filteredOptions = messagesOptions.filter((option) => !encounteredMessages.includes(option.id));
// We should never have a filteredOptions empty, but in case it is, display the first option as a fallback
const randomOption = filteredOptions.length
? filteredOptions[Math.floor(Math.random() * filteredOptions.length)]
: messagesOptions[0];
setItem('WelcomePaneEncounteredMessages', JSON.stringify([...encounteredMessages, randomOption.id]));
return randomOption;
};
useEffect(() => {
try {
setOption(getRandomOption());
} catch (e: any) {
console.error(e);
}
}, []);
useEffect(() => {
// On banner unmount, set the ref to false so that we don't show the banner anymore
return () => {
needToShowUpsellBanner.current = false;
};
}, []);
return (
<>
<PromotionBanner
description={option?.text}
cta={option?.cta}
contentCentered={!columnMode}
data-testid="promotion-banner"
hasDismissAction
onClose={onClose}
/>
{renderShortcutModal && <MailShortcutsModal {...mailShortcutsProps} />}
{renderThemesModal && <ThemesModal {...themesModalProps} />}
</>
);
};
export default MailUpsellBanner;
| 3,551
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/banners/task-running/TaskRunningBanner.tsx
|
import { c } from 'ttag';
import { Icon } from '@proton/components';
import clsx from '@proton/utils/clsx';
interface Props {
className?: string;
}
const TaskRunningBanner = ({ className }: Props) => {
return (
<div
className={clsx([
'bg-weak rounded mx-2 px-4 py-2 flex flex-wrap flex-justify-start flex-align-items-center',
className,
])}
>
<div className="flex-item-noshrink flex">
<Icon name="clock" className="mr-2" />
</div>
<div className="flex-item-fluid pl-1">{c('Info').t`Moving messages. This may take a while.`}</div>
</div>
);
};
export default TaskRunningBanner;
| 3,552
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/item-expiration/ItemExpiration.scss
|
.pill-icon {
display: inline-flex;
line-height: 1;
}
| 3,553
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/item-expiration/ItemExpiration.test.tsx
|
import { screen } from '@testing-library/react';
import { addDays, addHours, addMinutes, getUnixTime } from 'date-fns';
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import { MessageMetadata } from '@proton/shared/lib/interfaces/mail/Message';
import { AUTO_DELETE_SPAM_AND_TRASH_DAYS } from '@proton/shared/lib/mail/mailSettings';
import { addToCache } from '@proton/testing/index';
import { minimalCache } from '../../../helpers/test/cache';
import { render } from '../../../helpers/test/render';
import { Element } from '../../../models/element';
import ItemExpiration from './ItemExpiration';
const defaultLabelID = MAILBOX_LABEL_IDS.INBOX;
const getElement = (type: 'message' | 'conversation' = 'conversation', elementProps?: Partial<Element>) => {
const element =
type === 'message'
? ({
// We consider an element as a message if it has conversationID
ConversationID: '',
...elementProps,
} as MessageMetadata)
: ({ ...elementProps } as Element);
return element;
};
describe('ItemExpiration', () => {
it('should not render if expirationTime is not provided', async () => {
await render(<ItemExpiration labelID={defaultLabelID} element={getElement()} />);
expect(screen.queryByTestId('item-expiration')).not.toBeInTheDocument();
});
it('should have color-danger class if it is expiring in less than a day', async () => {
const date = addHours(new Date(), 1);
const expirationTime = getUnixTime(date);
await render(
<ItemExpiration labelID={defaultLabelID} element={getElement()} expirationTime={expirationTime} />
);
expect(screen.getByTestId('item-expiration')).toHaveClass('color-danger');
});
it('should not have color-danger class if it is expiring in more than a day', async () => {
const date = addHours(new Date(), 25);
const expirationTime = getUnixTime(date);
await render(
<ItemExpiration labelID={defaultLabelID} element={getElement()} expirationTime={expirationTime} />
);
expect(screen.getByTestId('item-expiration')).not.toHaveClass('color-danger');
});
it('should show a short remaining time', async () => {
const date = addMinutes(new Date(), 10);
const expirationTime = getUnixTime(date);
await render(
<ItemExpiration labelID={defaultLabelID} element={getElement()} expirationTime={expirationTime} />
);
expect(screen.getByText('<1 d')).toBeInTheDocument();
});
it('should diplay 30 days', async () => {
const date = addDays(new Date(), 30);
const expirationTime = getUnixTime(date);
await render(
<ItemExpiration labelID={defaultLabelID} element={getElement()} expirationTime={expirationTime} />
);
expect(screen.getByText('30 d')).toBeInTheDocument();
});
describe('Element is conversation', () => {
it('Should display Trash icon when label ID is valid and setting is not null', async () => {
const expirationTime = getUnixTime(addDays(new Date(), 30));
minimalCache();
addToCache('MailSettings', { AutoDeleteSpamAndTrashDays: AUTO_DELETE_SPAM_AND_TRASH_DAYS.ACTIVE });
await render(
<ItemExpiration
element={getElement()}
expirationTime={expirationTime}
labelID={MAILBOX_LABEL_IDS.TRASH}
/>,
false
);
expect(screen.getByTestId('item-expiration').querySelector('use')?.getAttribute('xlink:href')).toBe(
'#ic-trash-clock'
);
});
it('Should display Hourglass if label ID is not valid', async () => {
const expirationTime = getUnixTime(addDays(new Date(), 30));
minimalCache();
addToCache('MailSettings', { AutoDeleteSpamAndTrashDays: AUTO_DELETE_SPAM_AND_TRASH_DAYS.ACTIVE });
await render(
<ItemExpiration
labelID={MAILBOX_LABEL_IDS.INBOX}
element={getElement()}
expirationTime={expirationTime}
/>,
false
);
expect(screen.getByTestId('item-expiration').querySelector('use')?.getAttribute('xlink:href')).toBe(
'#ic-hourglass'
);
});
it('Should display Hourglass icon if label ID is valid and setting is null', async () => {
const expirationTime = getUnixTime(addDays(new Date(), 30));
minimalCache();
addToCache('MailSettings', { AutoDeleteSpamAndTrashDays: null });
await render(
<ItemExpiration
labelID={MAILBOX_LABEL_IDS.TRASH}
element={getElement()}
expirationTime={expirationTime}
/>,
false
);
expect(screen.getByTestId('item-expiration').querySelector('use')?.getAttribute('xlink:href')).toBe(
'#ic-hourglass'
);
});
});
describe('Element is message', () => {
it('Should display Trash icon if expire flag is not frozen', async () => {
const expirationTime = getUnixTime(addDays(new Date(), 30));
minimalCache();
addToCache('MailSettings', { AutoDeleteSpamAndTrashDays: AUTO_DELETE_SPAM_AND_TRASH_DAYS.ACTIVE });
await render(
<ItemExpiration
labelID={MAILBOX_LABEL_IDS.TRASH}
element={getElement('message')}
expirationTime={expirationTime}
/>,
false
);
expect(screen.getByTestId('item-expiration').querySelector('use')?.getAttribute('xlink:href')).toBe(
'#ic-trash-clock'
);
});
});
});
| 3,554
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/item-expiration/ItemExpiration.tsx
|
import { Icon, IconName, Tooltip } from '@proton/components';
import { isFrozenExpiration } from '@proton/shared/lib/mail/messages';
import clsx from '@proton/utils/clsx';
import useMailModel from 'proton-mail/hooks/useMailModel';
import { isAllowedAutoDeleteLabelID } from '../../../helpers/autoDelete';
import { isConversation, isMessage } from '../../../helpers/elements';
import { Element } from '../../../models/element';
import useItemExpiration from './useItemExpiration';
import './ItemExpiration.scss';
interface Props {
className?: string;
expirationTime?: number;
element: Element;
labelID: string;
}
const ItemExpiration = ({ className, expirationTime, element, labelID }: Props) => {
const { tooltipMessage, shortMessage, expiresInLessThan24Hours } = useItemExpiration(element, expirationTime);
const mailSettings = useMailModel('MailSettings');
if (!expirationTime) {
return null;
}
const iconName: Extract<IconName, 'hourglass' | 'trash-clock'> = (() => {
if (
isAllowedAutoDeleteLabelID(labelID) &&
((isMessage(element) && !isFrozenExpiration(element)) ||
(isConversation(element) && mailSettings.AutoDeleteSpamAndTrashDays !== null))
) {
return 'trash-clock';
}
return 'hourglass';
})();
return (
<Tooltip title={tooltipMessage}>
<div
className={clsx([
'pill-icon flex flex-align-items-center flex-nowrap',
className,
expiresInLessThan24Hours && 'color-danger',
])}
data-testid="item-expiration"
>
<Icon name={iconName} className="flex-item-noshrink" size={14} alt={tooltipMessage} />
<span className="ml-1 text-sm text-nowrap">{shortMessage}</span>
</div>
</Tooltip>
);
};
export default ItemExpiration;
| 3,555
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/item-expiration/useItemExpiration.ts
|
import { useState } from 'react';
import { differenceInDays, differenceInHours, endOfDay, fromUnixTime, isAfter } from 'date-fns';
import { c, msgid } from 'ttag';
import useInterval from '@proton/hooks/useInterval';
import { formatFullDate } from '../../../helpers/date';
import { isConversation } from '../../../helpers/elements';
import { Conversation } from '../../../models/conversation';
import { Element } from '../../../models/element';
const EVERY_MINUTE = 60 * 1000;
const getShortMessage = (date: Date, now: Date, expiresInLessThan24Hours: boolean) => {
const hasEnded = isAfter(now, date);
if (hasEnded) {
return '';
}
const remainingDays = differenceInDays(endOfDay(date), now); // Using endOfDay since differenceInDays count full days
if (expiresInLessThan24Hours) {
//translator: This indicates that the message will expires in less than 1 day. Value is hardcoded to make sure we always show that
return c('Remaining days before the message expire').t`<1 d`;
}
//translator: We want to indicate the number of days that are remaining before expiration but only show '10 d' and not '10 days'. Plural is here to accommodate languages that might have different words or conventions for single or multiple days
return c('Remaining days before the message expire').ngettext(
msgid`${remainingDays} d`,
`${remainingDays} d`,
remainingDays
);
};
const useItemExpiration = (element: Element, expirationTime?: number) => {
const [now, setNow] = useState(new Date());
const expirationDate = fromUnixTime(expirationTime || 0);
const formattedDate = formatFullDate(expirationDate);
const expiresInLessThan24Hours = differenceInHours(expirationDate, now) < 24;
const isConversationWithSeveralMessages =
isConversation(element) && ((element as Conversation)?.NumMessages || 0) > 1;
useInterval(() => setNow(new Date()), EVERY_MINUTE);
return {
tooltipMessage: isConversationWithSeveralMessages
? c('Info').t`This conversation contains one or more expiring messages`
: c('Info').t`This message will expire ${formattedDate}`,
shortMessage: getShortMessage(expirationDate, now, expiresInLessThan24Hours),
expiresInLessThan24Hours,
};
};
export default useItemExpiration;
| 3,556
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/snooze
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/snooze/components/MoveSnoozedModal.tsx
|
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { ModalProps, Prompt } from '@proton/components';
interface Props extends ModalProps {
isMessage: boolean;
onResolve: () => void;
onReject: () => void;
onCloseCustomAction?: () => void;
}
const MoveSnoozedModal = ({ isMessage, onResolve, onReject, onCloseCustomAction, ...rest }: Props) => {
const handleClose = () => {
onCloseCustomAction?.();
onReject();
};
return (
<Prompt
title={c('Title').t`Moving a snoozed message`}
buttons={[
<Button color="norm" onClick={onResolve} data-testid="moveSnoozedConvesation">{c('Action')
.t`OK`}</Button>,
<Button onClick={handleClose}>{c('Action').t`Cancel`}</Button>,
]}
{...rest}
>
{c('Info').t`Snoozing this conversation will be cancelled.`}
</Prompt>
);
};
export default MoveSnoozedModal;
| 3,557
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/snooze
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/snooze/components/SnoozeCustomTime.tsx
|
import { MouseEvent, useEffect, useState } from 'react';
import { addDays, endOfToday, isToday, set } from 'date-fns';
import { c } from 'ttag';
import { Button } from '@proton/atoms/Button';
import { DateInputTwo, InputFieldTwo, PrimaryButton, TimeInput } from '@proton/components/components';
import { generateUID } from '@proton/components/helpers';
import { useUserSettings } from '@proton/components/hooks';
import { getWeekStartsOn } from '@proton/shared/lib/settings/helper';
import { getMinScheduleTime } from '../../../../helpers/schedule';
import { SNOOZE_DURATION } from '../../../../hooks/actions/useSnooze';
import useFutureTimeDate from '../../../../hooks/message/useFutureTimeDate';
import SnoozeHeader from './SnoozeHeader';
interface Props {
onClose: () => void;
onLock?: (value: boolean) => void;
handleSnooze: (event: MouseEvent, duration: SNOOZE_DURATION, snoozeTime: Date) => void;
}
const SnoozeCustomTime = ({ onClose, onLock, handleSnooze }: Props) => {
const [userSettings] = useUserSettings();
const [uid] = useState(generateUID('snooze-message-modal'));
useEffect(() => {
onLock?.(true);
}, []);
// default date is the next day at 9:00AM
const defaultDate = set(addDays(new Date(), 1), { hours: 9, minutes: 0, seconds: 0 });
const {
date,
time,
scheduleDateTime,
minDate,
disabled,
handleChangeDate,
handleChangeTime,
formatDateInput,
errorDate,
errorTime,
updateDateAndTime,
} = useFutureTimeDate({ defaultDate });
const handleClose = () => {
updateDateAndTime(defaultDate);
onLock?.(false);
onClose();
};
return (
<div className="p-6" data-testid="snooze-custom-duration-form">
<SnoozeHeader headerClasses="mb-4" />
<div className="flex gap-2 flex-row flex-nowrap mb-6">
<InputFieldTwo
as={DateInputTwo}
id={`snooze-message-${uid}`}
label={c('Label').t`Date`}
onChange={handleChangeDate}
value={date}
min={minDate}
weekStartsOn={getWeekStartsOn(userSettings)}
toFormatter={formatDateInput}
preventValueReset
error={errorDate}
data-testid="snooze-date-input"
/>
<InputFieldTwo
as={TimeInput}
id={`snooze-message-${uid}`}
label={c('Label').t`Time`}
onChange={handleChangeTime}
value={time}
min={getMinScheduleTime(date)}
max={isToday(date) ? endOfToday() : undefined}
error={errorTime}
data-testid="snooze-time-input"
/>
</div>
<div className="flex flex-column gap-2">
<PrimaryButton
disabled={disabled}
onClick={(event: MouseEvent) => handleSnooze(event, 'custom', scheduleDateTime)}
>{c('Action').t`Snooze`}</PrimaryButton>
<Button onClick={handleClose}>{c('Action').t`Cancel`}</Button>
</div>
</div>
);
};
export default SnoozeCustomTime;
| 3,558
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/snooze
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/snooze/components/SnoozeDurationSelection.test.tsx
|
import { render } from '@testing-library/react';
import { nextFriday, nextMonday, nextSaturday, nextSunday, nextThursday, nextTuesday, nextWednesday } from 'date-fns';
import { useUser, useUserSettings } from '@proton/components/hooks';
import { MAIL_APP_NAME } from '@proton/shared/lib/constants';
import { SETTINGS_WEEK_START } from '@proton/shared/lib/interfaces';
import SnoozeDurationSelection from './SnoozeDurationSelection';
jest.mock('@proton/components/hooks/useUser');
jest.mock('@proton/components/hooks/useUserSettings');
const renderComponent = (canUnsnooze: boolean) => {
return render(
<SnoozeDurationSelection
canUnsnooze={canUnsnooze}
handleCustomClick={jest.fn}
handleSnooze={jest.fn}
handleUnsnoozeClick={jest.fn}
/>
);
};
describe('SnoozeDurationSelection when start of week is Monday', () => {
const useUserMock = useUser as jest.Mock;
const useUserSettingsMock = useUserSettings as jest.Mock;
beforeAll(() => {
useUserMock.mockImplementation(() => [{ hasPaidMail: false }, jest.fn]);
useUserSettingsMock.mockImplementation(() => [{ WeekStart: 1 }]);
});
afterAll(() => {
useUserMock.mockReset();
useUserSettingsMock.mockReset();
});
it('should render all Monday options', () => {
const date = nextMonday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(getByTestId('snooze-duration-later'));
expect(getByTestId('snooze-duration-weekend'));
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-custom'));
});
it('should render all Tuesday options', () => {
const date = nextTuesday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(getByTestId('snooze-duration-later'));
expect(getByTestId('snooze-duration-weekend'));
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-custom'));
});
it('should render all Wednesday options', () => {
const date = nextWednesday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(getByTestId('snooze-duration-later'));
expect(getByTestId('snooze-duration-weekend'));
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-custom'));
});
it('should render all Thursday options', () => {
const date = nextThursday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(queryByTestId('snooze-duration-later')).toBeNull();
expect(getByTestId('snooze-duration-weekend'));
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-custom'));
});
it('should render all Friday options', () => {
const date = nextFriday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(getByTestId('snooze-duration-later'));
expect(queryByTestId('snooze-duration-weekend')).toBeNull();
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-custom'));
});
it('should render all Saturday options', () => {
const date = nextSaturday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(queryByTestId('snooze-duration-later')).toBeNull();
expect(queryByTestId('snooze-duration-weekend')).toBeNull();
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-custom'));
});
it('should render all Sunday options', () => {
const date = nextSunday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(queryByTestId('snooze-duration-later')).toBeNull();
expect(queryByTestId('snooze-duration-weekend')).toBeNull();
expect(queryByTestId('snooze-duration-nextweek')).toBeNull();
expect(getByTestId('snooze-duration-custom'));
});
it('should render the unsnooze option', () => {
const { getByTestId } = renderComponent(true);
expect(getByTestId('snooze-duration-unsnooze'));
});
it('should render the upsell button for free users', () => {
const { getByAltText } = renderComponent(false);
expect(getByAltText(`Upgrade to ${MAIL_APP_NAME} Plus to unlock`));
});
it('should not render the upsell button for free users', () => {
useUserMock.mockImplementation(() => [{ hasPaidMail: true }, jest.fn]);
const { queryByAltText } = renderComponent(false);
expect(queryByAltText(`Upgrade to ${MAIL_APP_NAME} Plus to unlock`)).toBeNull();
});
});
describe('SnoozeDurationSelection when start of week is Saturday', () => {
const useUserMock = useUser as jest.Mock;
const useUserSettingsMock = useUserSettings as jest.Mock;
beforeAll(() => {
useUserMock.mockImplementation(() => [{ hasPaidMail: false }, jest.fn]);
useUserSettingsMock.mockImplementation(() => [{ WeekStart: SETTINGS_WEEK_START.SATURDAY }]);
});
afterAll(() => {
useUserMock.mockReset();
useUserSettingsMock.mockReset();
});
it('should render all Monday options', () => {
const date = nextMonday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(getByTestId('snooze-duration-later'));
expect(queryByTestId('snooze-duration-weekend')).toBeNull();
expect(getByTestId('snooze-duration-nextweek'));
});
it('should render all Tuesday options', () => {
const date = nextTuesday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(getByTestId('snooze-duration-later'));
expect(queryByTestId('snooze-duration-weekend')).toBeNull();
expect(getByTestId('snooze-duration-nextweek'));
});
it('should render all Wednesday options', () => {
const date = nextWednesday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(getByTestId('snooze-duration-later'));
expect(queryByTestId('snooze-duration-weekend')).toBeNull();
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-custom'));
});
it('should render all Thursday options', () => {
const date = nextThursday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(queryByTestId('snooze-duration-later')).toBeNull();
expect(queryByTestId('snooze-duration-weekend')).toBeNull();
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-custom'));
});
it('should render all Friday options', () => {
const date = nextFriday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(getByTestId('snooze-duration-later'));
expect(queryByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-custom'));
});
it('should render all Saturday options', () => {
const date = nextSaturday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(queryByTestId('snooze-duration-later')).toBeNull();
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-custom'));
});
it('should render all Sunday options', () => {
const date = nextSunday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(queryByTestId('snooze-duration-later')).toBeNull();
expect(queryByTestId('snooze-duration-nextweek')).toBeNull();
expect(queryByTestId('snooze-duration-nextweek')).toBeNull();
expect(getByTestId('snooze-duration-custom'));
});
});
describe('SnoozeDurationSelection when start of week is Sunday', () => {
const useUserMock = useUser as jest.Mock;
const useUserSettingsMock = useUserSettings as jest.Mock;
beforeAll(() => {
useUserMock.mockImplementation(() => [{ hasPaidMail: false }, jest.fn]);
useUserSettingsMock.mockImplementation(() => [{ WeekStart: SETTINGS_WEEK_START.SUNDAY }]);
});
afterAll(() => {
useUserMock.mockReset();
useUserSettingsMock.mockReset();
});
it('should render all Monday options', () => {
const date = nextMonday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(getByTestId('snooze-duration-later'));
expect(queryByTestId('snooze-duration-weekend')).toBeNull();
expect(getByTestId('snooze-duration-nextweek'));
});
it('should render all Tuesday options', () => {
const date = nextTuesday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(getByTestId('snooze-duration-later'));
expect(queryByTestId('snooze-duration-weekend')).toBeNull();
expect(getByTestId('snooze-duration-nextweek'));
});
it('should render all Wednesday options', () => {
const date = nextWednesday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(getByTestId('snooze-duration-later'));
expect(queryByTestId('snooze-duration-weekend')).toBeNull();
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-custom'));
});
it('should render all Thursday options', () => {
const date = nextThursday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(queryByTestId('snooze-duration-later')).toBeNull();
expect(queryByTestId('snooze-duration-weekend')).toBeNull();
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-custom'));
});
it('should render all Friday options', () => {
const date = nextFriday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(getByTestId('snooze-duration-later'));
expect(queryByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-custom'));
});
it('should render all Saturday options', () => {
const date = nextSaturday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(queryByTestId('snooze-duration-later')).toBeNull();
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-custom'));
});
it('should render all Sunday options', () => {
const date = nextSunday(new Date());
jest.useFakeTimers({ now: date.getTime() });
const { getByTestId, queryByTestId } = renderComponent(false);
expect(getByTestId('snooze-duration-tomorrow'));
expect(queryByTestId('snooze-duration-later')).toBeNull();
expect(queryByTestId('snooze-duration-nextweek')).toBeNull();
expect(queryByTestId('snooze-duration-nextweek')).toBeNull();
expect(getByTestId('snooze-duration-custom'));
});
});
| 3,559
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/snooze
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/snooze/components/SnoozeDurationSelection.tsx
|
import { MouseEvent } from 'react';
import {
addDays,
differenceInDays,
format,
isSaturday,
isSunday,
isWeekend,
nextMonday,
nextSaturday,
set,
startOfWeek,
} from 'date-fns';
import { c } from 'ttag';
import { Button } from '@proton/atoms/Button';
import { useUser, useUserSettings } from '@proton/components/hooks';
import { MAIL_APP_NAME } from '@proton/shared/lib/constants';
import { getWeekStartsOn } from '@proton/shared/lib/settings/helper';
import plusLogo from '@proton/styles/assets/img/illustrations/mail-plus-logo.svg';
import clsx from '@proton/utils/clsx';
import { formatSimpleDate } from '../../../../helpers/date';
import { SNOOZE_DURATION } from '../../../../hooks/actions/useSnooze';
import SnoozeHeader from './SnoozeHeader';
interface Props {
canUnsnooze: boolean;
handleUnsnoozeClick: (event: MouseEvent) => void;
handleCustomClick: (event: MouseEvent) => void;
handleSnooze: (event: MouseEvent, duration: SNOOZE_DURATION, snoozeDate?: Date) => void;
}
interface ButtonProps {
duration?: SNOOZE_DURATION;
onClick: (event: MouseEvent, duration?: SNOOZE_DURATION) => void;
leftText: string;
rightText?: string;
showUpsellButton?: boolean;
}
const getShortDayText = (day: Date, formatTime: string) => {
if (isSaturday(day)) {
// translator: formatTime will always be at 9:00 AM. Will display "Sat, 9:00 AM" (if 12 hours is set) or "Sat, 09:00" (if 24 hours is set)
return c('WeekDay').t`Sat, ${formatTime}`;
}
if (isSunday(day)) {
// translator: formatTime will always be at 9:00 AM. Will display "Sun, 9:00 AM" (if 12 hours is set) or "Sun, 09:00" (if 24 hours is set)
return c('WeekDay').t`Sun, ${formatTime}`;
}
// translator: formatTime will always be at 9:00 AM. Will display "Mon, 9:00 AM" (if 12 hours is set) or "Mon, 09:00" (if 24 hours is set)
return c('WeekDay').t`Mon, ${formatTime}`;
};
const SnoozeButton = ({ onClick, duration, leftText, rightText, showUpsellButton }: ButtonProps) => (
<Button
fullWidth
shape="ghost"
data-testid={`snooze-duration-${duration}`}
className={clsx('flex rounded-none', showUpsellButton ? 'gap-2' : 'flex-justify-space-between')}
onClick={(e) => onClick(e, duration)}
>
<span>{leftText}</span>
{rightText && <span className="color-weak">{rightText}</span>}
{showUpsellButton && (
<span>
<img src={plusLogo} alt={c('Info').t`Upgrade to ${MAIL_APP_NAME} Plus to unlock`} />
</span>
)}
</Button>
);
const SnoozeDurationSelection = ({ canUnsnooze, handleUnsnoozeClick, handleSnooze, handleCustomClick }: Props) => {
const [{ hasPaidMail }] = useUser();
const [userSettings] = useUserSettings();
const today = new Date();
const weekStartsOn = getWeekStartsOn(userSettings);
const startOfNextWeek = startOfWeek(addDays(today, 7), { weekStartsOn: weekStartsOn }); // We add 7 days to get the start of the next week
const weekStartInWeekend = isWeekend(startOfNextWeek);
const nextMon = nextMonday(today);
const nextSat = nextSaturday(today);
const daysUntilNextMon = differenceInDays(nextMon, today);
const daysUntilNextSat = differenceInDays(nextSat, today);
const formattedDayOfWeek = format(addDays(today, 2), 'EEE');
const time = set(today, { hours: 9, minutes: 0, seconds: 0, milliseconds: 0 });
const formatTime = formatSimpleDate(time);
const nextWeekShortDay = getShortDayText(startOfNextWeek, formatTime);
const dropdownOptions: { leftText: string; rightText: string; duration: SNOOZE_DURATION; visible: boolean }[] = [
{
leftText: c('Action').t`Tomorrow`,
rightText: formatTime,
duration: 'tomorrow',
visible: true,
},
{
leftText: c('Action').t`Later this week`,
// translator: Shows the day of week and the time, e.g. "Mon, 9:00", "Fri, 9:00 AM" (if 12 hours is set)
rightText: `${formattedDayOfWeek}, ${formatTime}`,
duration: 'later',
visible: daysUntilNextMon > 2 && daysUntilNextSat !== 2,
},
{
leftText: c('Action').t`This weekend`,
// translator: This will always be saturday at 9:00, will display "Sat, 9:00 AM" (if 12 hours is set) or "Sat, 09:00" (if 24 hours is set)
rightText: c('Info').t`Sat, ${formatTime}`,
duration: 'weekend',
visible: !weekStartInWeekend && daysUntilNextMon > 2 && daysUntilNextSat !== 1,
},
{
leftText: c('Action').t`Next week`,
// translator: This will always be at 9:00 AM but can be monday, saturday or sunday depending on user settings. Will display "Mon, 9:00 AM" (if 12 hours is set) or "Mon, 09:00" (if 24 hours is set)
rightText: nextWeekShortDay,
duration: 'nextweek',
visible: daysUntilNextMon > 1,
},
];
/**
* When the WeekStarts is set to Sat or Sun we need to send a custom snooze time to set it to the defined day at 09:00AM
* Otherwise we can send the predifined duration
*/
const handleSnoozeDurationClick = (event: MouseEvent, duration: SNOOZE_DURATION) => {
if (weekStartInWeekend && duration === 'nextweek') {
const snoozeTime = set(startOfNextWeek, { hours: 9, minutes: 0, seconds: 0, milliseconds: 0 });
handleSnooze(event, 'custom', snoozeTime);
} else {
handleSnooze(event, duration);
}
};
return (
<>
<SnoozeHeader headerClasses="px-4 pt-2" />
<hr className="my-2" />
<div className="flex gap-2">
{dropdownOptions
.filter((item) => item.visible)
.map(({ duration, leftText, rightText }) => (
<SnoozeButton
key={duration}
leftText={leftText}
rightText={rightText}
duration={duration}
onClick={(e, duration) => {
if (e && duration) {
handleSnoozeDurationClick(e, duration);
}
}}
/>
))}
</div>
<hr className="my-2" />
<div className="mb-2">
<SnoozeButton
key="custom"
duration="custom"
leftText={c('Action').t`Select date and time`}
onClick={handleCustomClick}
showUpsellButton={!hasPaidMail}
/>
</div>
{canUnsnooze && (
<>
<hr className="my-2" />
<div className="mb-2">
<Button
key="unsnooze"
fullWidth
shape="ghost"
data-testid="snooze-duration-unsnooze"
className="flex rounded-none flex-justify-space-between"
onClick={handleUnsnoozeClick}
>
{c('Action').t`Unsnooze`}
</Button>
</div>
</>
)}
</>
);
};
export default SnoozeDurationSelection;
| 3,560
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/snooze
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/snooze/components/SnoozeHeader.tsx
|
import { c } from 'ttag';
interface Props {
headerClasses: string;
}
const SnoozeHeader = ({ headerClasses }: Props) => {
return (
<div className={headerClasses}>
<h2 className="mb-1 text-rg text-bold">{c('Snooze message').t`Snooze Message`}</h2>
<p className="m-0 color-weak">{c('Snooze message').t`When should the message reappear in your inbox?`}</p>
</div>
);
};
export default SnoozeHeader;
| 3,561
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/snooze
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/snooze/components/SnoozeSpotlight.tsx
|
import React, { useRef } from 'react';
import { c } from 'ttag';
import { Href } from '@proton/atoms/Href';
import { Spotlight } from '@proton/components/components';
import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url';
interface Props {
show: boolean;
onDisplayed: () => void;
onClose: () => void;
children: React.ReactNode;
}
const SnoozeSpotlight = ({ children, show, onDisplayed, onClose }: Props) => {
const ref = useRef<HTMLDivElement>(null);
return (
<Spotlight
originalPlacement="bottom-end"
show={show}
onDisplayed={onDisplayed}
onClose={(e) => {
e.stopPropagation();
onClose();
}}
anchorRef={ref}
type="new"
content={
<>
<p className="text-lg text-bold mb-1 mt-0">{c('Spotlight').t`Snooze it for later`}</p>
<p className="m-0">{c('Spotlight')
.t`Set when an email should reappear in your inbox with the new snooze feature.`}</p>
<Href href={getKnowledgeBaseUrl('/snooze-emails')} onClick={(e) => e.stopPropagation()}>{c('Link')
.t`Learn more`}</Href>
</>
}
>
<div ref={ref}>{children}</div>
</Spotlight>
);
};
export default SnoozeSpotlight;
| 3,562
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/snooze
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/snooze/components/SnoozeUpsellModal.tsx
|
import { c } from 'ttag';
import { ModalStateProps, UpsellModal } from '@proton/components/components';
import { APP_UPSELL_REF_PATH, MAIL_UPSELL_PATHS, UPSELL_COMPONENT } from '@proton/shared/lib/constants';
import { getUpsellRef } from '@proton/shared/lib/helpers/upsell';
const SnoozeDurationSelection = (props: ModalStateProps) => {
const upsellRef = getUpsellRef({
app: APP_UPSELL_REF_PATH.MAIL_UPSELL_REF_PATH,
component: UPSELL_COMPONENT.MODAL,
feature: MAIL_UPSELL_PATHS.SNOOZE_MESSAGE,
});
return (
<div onClick={(e) => e.stopPropagation()}>
<UpsellModal
data-testid="composer:snooze-message:upsell-modal"
title={c('Title').t`Want to snooze any time?`}
description={c('Description').t`Unlock custom snooze times when you upgrade your plan.`}
modalProps={props}
upsellRef={upsellRef}
features={[
'snooze-messages',
'more-storage',
'more-email-addresses',
'unlimited-folders-and-labels',
'custom-email-domains',
]}
/>
</div>
);
};
export default SnoozeDurationSelection;
| 3,563
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/snooze
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/snooze/containers/SnoozeDropdown.test.tsx
|
import { fireEvent, render } from '@testing-library/react';
import { nextMonday } from 'date-fns';
import { useUser, useUserSettings } from '@proton/components/hooks';
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import useSnooze from '../../../../hooks/actions/useSnooze';
import { useAppDispatch } from '../../../../logic/store';
import { Element } from '../../../../models/element';
import SnoozeDropdown from './SnoozeDropdown';
jest.mock('@proton/components/hooks/useUser');
jest.mock('@proton/components/hooks/useUserSettings');
jest.mock('@proton/components/components/link/useSettingsLink');
jest.mock('proton-mail/logic/store', () => ({
useAppDispatch: jest.fn().mockReturnValue(jest.fn()),
}));
jest.mock('proton-mail/hooks/actions/useSnooze', () => ({
__esModule: true,
default: jest.fn().mockReturnValue({
canSnooze: true,
canUnsnooze: true,
isSnoozeEnabled: true,
snooze: jest.fn(),
unsnooze: jest.fn(),
handleClose: jest.fn(),
handleCustomClick: jest.fn(),
snoozeState: 'snooze-selection',
}),
}));
const useSnoozeProps = {
canSnooze: true,
canUnsnooze: true,
isSnoozeEnabled: true,
snooze: jest.fn(),
unsnooze: jest.fn(),
handleClose: jest.fn(),
handleCustomClick: jest.fn(),
snoozeState: 'snooze-selection',
};
const element: Element = {
ID: 'id',
ConversationID: 'conversationId',
Subject: 'subject',
Unread: 0,
};
describe('Snooze dropdown', () => {
const useUserMock = useUser as jest.Mock;
const useSnoozeMock = useSnooze as jest.Mock;
const useAppDispatchMock = useAppDispatch as jest.Mock;
const useUserSettingsMock = useUserSettings as jest.Mock;
beforeAll(() => {
useUserMock.mockImplementation(() => [{ hasPaidMail: false }, jest.fn]);
useUserSettingsMock.mockImplementation(() => [{ WeekStart: 1 }, jest.fn]);
});
afterAll(() => {
useUserMock.mockClear();
useSnoozeMock.mockClear();
useAppDispatchMock.mockClear();
useUserSettingsMock.mockClear();
});
it('should not return anything when flag is disabled', async () => {
useSnoozeMock.mockReturnValue({ ...useSnoozeProps, isSnoozeEnabled: false });
const { queryByTestId } = render(<SnoozeDropdown labelID={MAILBOX_LABEL_IDS.INBOX} elements={[element]} />);
expect(queryByTestId('dropdown-button')).toBeNull();
});
it('should not return anything when cannot snooze or unsnooze', async () => {
useSnoozeMock.mockReturnValue({ ...useSnoozeProps, canSnooze: false, canUnsnooze: false });
const { queryByTestId } = render(<SnoozeDropdown labelID={MAILBOX_LABEL_IDS.INBOX} elements={[element]} />);
expect(queryByTestId('dropdown-button')).toBeNull();
});
it('should not return anything when element is an empty array', async () => {
useSnoozeMock.mockReturnValue({ ...useSnoozeProps });
const { queryByTestId } = render(<SnoozeDropdown labelID={MAILBOX_LABEL_IDS.INBOX} elements={[]} />);
expect(queryByTestId('dropdown-button')).toBeNull();
});
it('should open dropdown with all Monday options', async () => {
jest.useFakeTimers({ now: nextMonday(new Date()).getTime() });
const { getByTestId } = render(<SnoozeDropdown labelID={MAILBOX_LABEL_IDS.INBOX} elements={[element]} />);
const button = getByTestId('dropdown-button');
fireEvent.click(button);
expect(useAppDispatchMock).toHaveBeenCalled();
expect(getByTestId('snooze-duration-tomorrow'));
expect(getByTestId('snooze-duration-later'));
expect(getByTestId('snooze-duration-weekend'));
expect(getByTestId('snooze-duration-nextweek'));
});
it('should open dropdown with all Monday options and unsnooze', async () => {
jest.useFakeTimers({ now: nextMonday(new Date()).getTime() });
useSnoozeMock.mockReturnValue({ ...useSnoozeProps, canUnsnooze: true });
const { getByTestId } = render(<SnoozeDropdown labelID={MAILBOX_LABEL_IDS.INBOX} elements={[element]} />);
const button = getByTestId('dropdown-button');
fireEvent.click(button);
expect(useAppDispatchMock).toHaveBeenCalled();
expect(getByTestId('snooze-duration-tomorrow'));
expect(getByTestId('snooze-duration-later'));
expect(getByTestId('snooze-duration-weekend'));
expect(getByTestId('snooze-duration-nextweek'));
expect(getByTestId('snooze-duration-unsnooze'));
});
it('should call snooze method when pressing any option', async () => {
const spySnooze = jest.fn();
useUserMock.mockImplementation(() => [{ hasPaidMail: true }, jest.fn]);
useSnoozeMock.mockReturnValue({ ...useSnoozeProps, snooze: spySnooze });
const { getByTestId } = render(<SnoozeDropdown labelID={MAILBOX_LABEL_IDS.INBOX} elements={[element]} />);
const button = getByTestId('dropdown-button');
fireEvent.click(button);
fireEvent.click(getByTestId('snooze-duration-tomorrow'));
expect(spySnooze).toHaveBeenCalledTimes(1);
expect(spySnooze).toHaveBeenCalledWith({ elements: [element], duration: 'tomorrow', snoozeTime: undefined });
});
it('should call unsnooze method when pressing the button', async () => {
const spySnooze = jest.fn();
useUserMock.mockImplementation(() => [{ hasPaidMail: true }, jest.fn]);
useSnoozeMock.mockReturnValue({ ...useSnoozeProps, unsnooze: spySnooze, canUnsnooze: true });
const { getByTestId } = render(<SnoozeDropdown labelID={MAILBOX_LABEL_IDS.INBOX} elements={[element]} />);
const button = getByTestId('dropdown-button');
fireEvent.click(button);
fireEvent.click(getByTestId('snooze-duration-unsnooze'));
expect(spySnooze).toHaveBeenCalledTimes(1);
expect(spySnooze).toHaveBeenCalledWith([element]);
});
it('should call custom click method when pressing button', async () => {
const spyCustom = jest.fn();
useUserMock.mockImplementation(() => [{ hasPaidMail: true }, jest.fn]);
useSnoozeMock.mockReturnValue({ ...useSnoozeProps, handleCustomClick: spyCustom });
const { getByTestId } = render(<SnoozeDropdown labelID={MAILBOX_LABEL_IDS.INBOX} elements={[element]} />);
const button = getByTestId('dropdown-button');
fireEvent.click(button);
const customButton = getByTestId('snooze-duration-custom');
fireEvent.click(customButton);
expect(spyCustom).toHaveBeenCalledTimes(1);
});
it('should open upsell modal when free user press the custom button', async () => {
const { getByTestId } = render(<SnoozeDropdown labelID={MAILBOX_LABEL_IDS.INBOX} elements={[element]} />);
const button = getByTestId('dropdown-button');
fireEvent.click(button);
const customButton = getByTestId('snooze-duration-custom');
fireEvent.click(customButton);
setTimeout(() => {
getByTestId('composer:snooze-message:upsell-modal');
}, 1);
});
});
| 3,564
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/snooze
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/snooze/containers/SnoozeDropdown.tsx
|
import { MouseEvent } from 'react';
import { c } from 'ttag';
import { Dropdown, DropdownButton, Icon, Tooltip, useModalState, usePopperAnchor } from '@proton/components/components';
import { useUser } from '@proton/components/hooks';
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants';
import useSnooze, { SNOOZE_DURATION } from '../../../../hooks/actions/useSnooze';
import { snoozeActions } from '../../../../logic/snooze/snoozeSlice';
import { useAppDispatch } from '../../../../logic/store';
import { Element } from '../../../../models/element';
import SnoozeCustomTime from '../components/SnoozeCustomTime';
import SnoozeDurationSelection from '../components/SnoozeDurationSelection';
import SnoozeUpsellModal from '../components/SnoozeUpsellModal';
interface Props {
elements: Element[];
labelID: string;
size?: 'small' | 'medium';
}
const SnoozeDropdown = ({ elements, size, labelID }: Props) => {
const dispatch = useAppDispatch();
const [{ hasPaidMail }] = useUser();
const [upsellModalProps, handleUpsellModalDisplay, renderUpsellModal] = useModalState();
const { anchorRef, isOpen, toggle, close: dropdownClose } = usePopperAnchor<HTMLButtonElement>();
const { canSnooze, canUnsnooze, isSnoozeEnabled, snooze, unsnooze, handleClose, handleCustomClick, snoozeState } =
useSnooze();
if (!elements.length || !isSnoozeEnabled || (!canSnooze && !canUnsnooze)) {
return null;
}
const onClose = () => {
dispatch(snoozeActions.resetSnoozeDropdown());
handleClose();
dropdownClose();
};
const handleSnooze = (event: MouseEvent, duration: SNOOZE_DURATION, snoozeTime?: Date) => {
event.stopPropagation();
snooze({ elements, duration, snoozeTime });
onClose();
};
const handleUnsnooze = (event: MouseEvent) => {
event.stopPropagation();
unsnooze(elements);
onClose();
};
const handleCustom = (event: MouseEvent) => {
event.stopPropagation();
if (hasPaidMail) {
handleCustomClick();
return;
}
handleUpsellModalDisplay(true);
onClose();
};
const handleDropdownClick = (event: MouseEvent) => {
event.stopPropagation();
// We want to reset state when the dropdown is open
const action = isOpen ? onClose : toggle;
if (!isOpen) {
dispatch(
snoozeActions.setSnoozeDropdown({
dropdownState: true,
element: elements[0],
})
);
}
action();
};
const labelText = labelID === MAILBOX_LABEL_IDS.SNOOZED ? c('Action').t`Manage Snooze` : c('Action').t`Snooze`;
return (
<>
<Tooltip title={labelText} tooltipClassName="no-pointer-events">
<DropdownButton
ref={anchorRef}
isOpen={isOpen}
className="color-inherit"
onClick={handleDropdownClick}
shape="ghost"
size={size}
icon
>
<Icon name="clock" alt={labelText} />
</DropdownButton>
</Tooltip>
<Dropdown
isOpen={isOpen && snoozeState === 'snooze-selection'}
anchorRef={anchorRef}
onClose={onClose}
size={{
width: '22em',
maxWidth: '22em',
}}
>
<SnoozeDurationSelection
canUnsnooze={canUnsnooze}
handleUnsnoozeClick={handleUnsnooze}
handleSnooze={handleSnooze}
handleCustomClick={handleCustom}
/>
</Dropdown>
<Dropdown
isOpen={isOpen && snoozeState === 'custom-snooze'}
anchorRef={anchorRef}
onClose={onClose}
autoClose={false}
autoCloseOutside={false}
size={{
width: '22em',
maxWidth: '22em',
}}
>
<SnoozeCustomTime onClose={onClose} handleSnooze={handleSnooze} />
</Dropdown>
{renderUpsellModal && (
<SnoozeUpsellModal {...upsellModalProps} onClose={() => handleUpsellModalDisplay(false)} />
)}
</>
);
};
export default SnoozeDropdown;
| 3,565
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/snooze
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/snooze/containers/SnoozeToolbarDropdown.tsx
|
import { c } from 'ttag';
import { Vr } from '@proton/atoms/Vr';
import { Icon, useModalState, useSpotlightShow } from '@proton/components/components';
import { FeatureCode } from '@proton/components/containers';
import { useSpotlightOnFeature } from '@proton/components/hooks';
import useSnooze from '../../../../hooks/actions/useSnooze';
import ToolbarDropdown, { DropdownRenderProps } from '../../../toolbar/ToolbarDropdown';
import SnoozeSpotlight from '../components/SnoozeSpotlight';
import SnoozeUpsellModal from '../components/SnoozeUpsellModal';
import SnoozeToolbarDropdownStepWrapper, {
SnoozeToolbarDropdownStepWrapperProps,
} from './SnoozeToolbarDropdownStepWrapper';
interface Props {
labelID: string;
selectedIDs: string[];
}
const SnoozeToolbarDropdown = ({ selectedIDs }: Props) => {
const { canSnooze, canUnsnooze, isSnoozeEnabled } = useSnooze();
const [upsellModalProps, handleUpsellModalDisplay, renderUpsellModal] = useModalState();
const { show: showSpotlight, onDisplayed, onClose } = useSpotlightOnFeature(FeatureCode.SpotlightSnooze, canSnooze);
const show = useSpotlightShow(showSpotlight);
// The title is set to undefined when the spotlight is present to avoid having the tooltip displayed when hovering the spotlight
const tooltipTitle = show ? undefined : c('Title').t`Snooze`;
if (!selectedIDs.length || !isSnoozeEnabled || (!canSnooze && !canUnsnooze)) {
return null;
}
return (
<>
<Vr />
<ToolbarDropdown
disabled={!selectedIDs || !selectedIDs.length}
content={
<SnoozeSpotlight show={show} onDisplayed={onDisplayed} onClose={onClose}>
<Icon className="toolbar-icon" name="clock" />
</SnoozeSpotlight>
}
title={tooltipTitle}
data-testid="toolbar:snooze"
hasCaret={false}
autoClose={false}
>
{{
contentProps: SnoozeToolbarDropdownStepWrapperProps,
render: ({ onClose, onLock }: DropdownRenderProps) => (
<>
<SnoozeToolbarDropdownStepWrapper
onClose={onClose}
onLock={onLock}
selectedIDs={selectedIDs}
displayUpsellModal={() => handleUpsellModalDisplay(true)}
/>
</>
),
}}
</ToolbarDropdown>
{renderUpsellModal && <SnoozeUpsellModal {...upsellModalProps} />}
</>
);
};
export default SnoozeToolbarDropdown;
| 3,566
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/snooze
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/snooze/containers/SnoozeToolbarDropdownStepWrapper.tsx
|
import { MouseEvent, useMemo } from 'react';
import { useUser } from '@proton/components/hooks';
import useSnooze, { SNOOZE_DURATION } from '../../../../hooks/actions/useSnooze';
import { useGetElementsFromIDs } from '../../../../hooks/mailbox/useElements';
import SnoozeCustomTime from '../components/SnoozeCustomTime';
import SnoozeDurationSelection from '../components/SnoozeDurationSelection';
export const SnoozeToolbarDropdownStepWrapperProps = {
className: 'min-w-custom h-auto',
style: { '--min-w-custom': '20rem', width: 'min-content' },
};
interface Props {
onClose: () => void;
onLock: (lock: boolean) => void;
selectedIDs: string[];
displayUpsellModal: () => void;
}
const SnoozeToolbarDropdownStepWrapper = ({ onClose, onLock, selectedIDs, displayUpsellModal }: Props) => {
const [{ hasPaidMail }] = useUser();
const getElementsFromIDs = useGetElementsFromIDs();
const elements = useMemo(() => getElementsFromIDs(selectedIDs), [selectedIDs]);
const { canUnsnooze, snooze, handleCustomClick, snoozeState, unsnooze, handleClose } = useSnooze();
const handleSnooze = (event: MouseEvent, duration: SNOOZE_DURATION, snoozeTime?: Date) => {
event.stopPropagation();
snooze({ elements, duration, snoozeTime });
onClose();
};
const handleCustom = (event: MouseEvent) => {
event.stopPropagation();
if (hasPaidMail) {
handleCustomClick();
return;
}
onClose();
displayUpsellModal();
};
const handleUnsnoozeClick = (event: MouseEvent) => {
event.stopPropagation();
unsnooze(elements);
onClose();
};
const closeDropdown = () => {
handleClose();
onClose();
};
return (
<>
{snoozeState === 'snooze-selection' && (
<SnoozeDurationSelection
handleUnsnoozeClick={handleUnsnoozeClick}
handleCustomClick={handleCustom}
handleSnooze={handleSnooze}
canUnsnooze={canUnsnooze}
/>
)}
{snoozeState === 'custom-snooze' && (
<SnoozeCustomTime handleSnooze={handleSnooze} onClose={closeDropdown} onLock={onLock} />
)}
</>
);
};
export default SnoozeToolbarDropdownStepWrapper;
| 3,567
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/spy-tracker/ItemSpyTrackerIcon.test.tsx
|
import { fireEvent, getByText, screen } from '@testing-library/react';
import { IMAGE_PROXY_FLAGS } from '@proton/shared/lib/mail/mailSettings';
import { MessageUTMTracker } from '@proton/shared/lib/models/mailUtmTrackers';
import { addToCache, minimalCache } from '../../../helpers/test/cache';
import { clearAll } from '../../../helpers/test/helper';
import { render } from '../../../helpers/test/render';
import { MessageState } from '../../../logic/messages/messagesTypes';
import ItemSpyTrackerIcon from './ItemSpyTrackerIcon';
jest.mock('@proton/components/hooks/useProgressiveRollout', () => {
return {
__esModule: true,
default: jest.fn(() => true),
};
});
const messageWithTrackers: MessageState = {
localID: 'messageWithTrackerId',
messageImages: {
hasEmbeddedImages: true,
hasRemoteImages: false,
showEmbeddedImages: true,
showRemoteImages: true,
trackersStatus: 'loaded',
images: [
{
type: 'embedded',
id: 'imageID',
status: 'loaded',
tracker: 'Tracker 1',
cid: 'cid',
cloc: 'cloc',
attachment: {},
},
{
type: 'embedded',
id: 'imageID',
status: 'loaded',
tracker: 'Tracker 2',
cid: 'cid',
cloc: 'cloc',
attachment: {},
},
],
},
messageUTMTrackers: [
{
originalURL: 'http://tracker.com/utm_content=tracker',
cleanedURL: 'http://tracker.com',
removed: [{ key: 'utm_source', value: 'tracker' }],
},
] as MessageUTMTracker[],
};
const messageWithoutTrackers: MessageState = {
localID: 'messageWithoutTrackerId',
messageImages: {
hasEmbeddedImages: true,
hasRemoteImages: false,
showEmbeddedImages: true,
showRemoteImages: true,
trackersStatus: 'loaded',
images: [
{
type: 'embedded',
id: 'imageID',
status: 'loaded',
tracker: undefined,
cid: 'cid',
cloc: 'cloc',
attachment: {},
},
],
},
};
describe('ItemSpyTrackerIcon', () => {
afterEach(() => {
clearAll();
});
it.each`
imageProxy | message | isIconDisplayed | isNumberDisplayed | expectedTooltip
${IMAGE_PROXY_FLAGS.ALL} | ${messageWithTrackers} | ${true} | ${true} | ${'2 email trackers blocked'}
${IMAGE_PROXY_FLAGS.ALL} | ${messageWithoutTrackers} | ${true} | ${false} | ${'No email trackers found'}
${IMAGE_PROXY_FLAGS.NONE} | ${messageWithTrackers} | ${true} | ${true} | ${'Email tracker protection is disabled'}
${IMAGE_PROXY_FLAGS.NONE} | ${messageWithoutTrackers} | ${true} | ${false} | ${'Email tracker protection is disabled'}
`(
'should display the icon [$isIconDisplayed] with number [$isNumberDisplayed] when proxy is [$imageProxy]',
async ({ imageProxy, message, isIconDisplayed, isNumberDisplayed }) => {
minimalCache();
addToCache('MailSettings', { ImageProxy: imageProxy });
const { queryByTestId } = await render(<ItemSpyTrackerIcon message={message} />, false);
const icon = queryByTestId('privacy:tracker-icon');
if (!isIconDisplayed) {
// When icon is not displayed, we don't have a tooltip or the number either
expect(icon).toBeNull();
} else {
// In every other cases, the icon should be displayed
expect(icon).toBeTruthy();
// Check that the number of trackers is displayed when we want to display it
const numberOfTrackers = queryByTestId('privacy:icon-number-of-trackers');
if (isNumberDisplayed) {
expect(numberOfTrackers).toBeTruthy();
expect(numberOfTrackers?.innerHTML).toEqual('3');
} else {
expect(numberOfTrackers).toBeNull();
}
}
}
);
it('should open the privacy dropdown with trackers info', async () => {
minimalCache();
addToCache('MailSettings', { ImageProxy: IMAGE_PROXY_FLAGS.ALL });
await render(<ItemSpyTrackerIcon message={messageWithTrackers} />, false);
const icon = await screen.findByTestId('privacy:tracker-icon');
fireEvent.click(icon);
// Dropdown title
const title = screen.getByTestId('privacy:title');
getByText(title, 'We protected you from 3 trackers');
const imageTrackerRow = screen.getByTestId('privacy:image-row');
const utmTrackerRow = screen.getByTestId('privacy:utm-row');
getByText(imageTrackerRow, '2 trackers blocked');
getByText(utmTrackerRow, '1 link cleaned');
});
it('should open the privacy dropdown with no trackers found', async () => {
minimalCache();
addToCache('MailSettings', { ImageProxy: IMAGE_PROXY_FLAGS.ALL });
await render(<ItemSpyTrackerIcon message={messageWithoutTrackers} />, false);
const icon = await screen.findByTestId('privacy:tracker-icon');
fireEvent.click(icon);
// Dropdown title
const title = screen.getByTestId('privacy:title');
getByText(title, 'No trackers found');
// Description is displayed
screen.getByText("We didn't find any known trackers and tracking URLs in this email.");
});
it('should open the privacy dropdown with no protection', async () => {
minimalCache();
addToCache('MailSettings', { ImageProxy: IMAGE_PROXY_FLAGS.NONE });
await render(<ItemSpyTrackerIcon message={messageWithTrackers} />, false);
const icon = await screen.findByTestId('privacy:tracker-icon');
fireEvent.click(icon);
// Dropdown title
const title = screen.getByTestId('privacy:title');
getByText(title, 'Protect yourself from trackers');
screen.getByTestId('privacy:prevent-tracking-toggle');
// Description is displayed
screen.getByText(
'Turn on email tracker protection to prevent advertisers and others from tracking your location and online activity.'
);
});
it('should open the image tracker modal and list expected info', async () => {
minimalCache();
addToCache('MailSettings', { ImageProxy: IMAGE_PROXY_FLAGS.ALL });
await render(<ItemSpyTrackerIcon message={messageWithTrackers} />, false);
const icon = await screen.findByTestId('privacy:tracker-icon');
fireEvent.click(icon);
const imageTrackerRow = screen.getByTestId('privacy:image-row');
// Open the image tracker modal
fireEvent.click(imageTrackerRow);
const modal = screen.getByTestId('spyTrackerModal:trackers');
getByText(
modal,
'We blocked the following advertisers and organizations from seeing when you open this email, what device you’re using, and where you’re located.'
);
// Trackers are visible
getByText(modal, 'Tracker 1');
getByText(modal, 'Tracker 2');
});
it('should open the utm tracker modal and list expected info', async () => {
minimalCache();
addToCache('MailSettings', { ImageProxy: IMAGE_PROXY_FLAGS.ALL });
await render(<ItemSpyTrackerIcon message={messageWithTrackers} />, false);
const icon = await screen.findByTestId('privacy:tracker-icon');
fireEvent.click(icon);
const utmTrackerRow = screen.getByTestId('privacy:utm-row');
// Open the utm tracker modal
fireEvent.click(utmTrackerRow);
const modal = screen.getByTestId('utmTrackerModal:trackers');
getByText(
modal,
'We removed tracking information from the following links to help protect you from advertisers and others trying to track your online activity.'
);
// Trackers are visible
getByText(modal, 'http://tracker.com/utm_content=tracker');
});
});
| 3,568
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/spy-tracker/ItemSpyTrackerIcon.tsx
|
import { useRef } from 'react';
import { c } from 'ttag';
import { FeatureCode, Tooltip, useSpotlightOnFeature } from '@proton/components';
import useUser from '@proton/components/hooks/useUser';
import { MONTH } from '@proton/shared/lib/constants';
import { isPlainText, isSent } from '@proton/shared/lib/mail/messages';
import { useMessageTrackers } from '../../../hooks/message/useMessageTrackers';
import { MessageState } from '../../../logic/messages/messagesTypes';
import LoadContentSpotlight from '../../message/LoadContentSpotlight';
import PrivacyDropdown from './PrivacyDropdown';
interface Props {
message: MessageState;
}
const ItemSpyTrackerIcon = ({ message }: Props) => {
const [user] = useUser();
const anchorRef = useRef(null);
const sent = isSent(message.data);
const {
numberOfImageTrackers,
numberOfUTMTrackers,
needsMoreProtection,
imageTrackersLoaded,
canCleanUTMTrackers,
} = useMessageTrackers(message);
// Load content spotlight needs to be displayed if account is older than one month
const userCreateTime = user.CreateTime || 0;
const isAccountOlderThanOneMonth = Date.now() > userCreateTime * 1000 + MONTH;
const { show: showLoadContentSpotlight, onDisplayed: onLoadContentSpotlightDisplayed } = useSpotlightOnFeature(
FeatureCode.SpotlightLoadContent,
isAccountOlderThanOneMonth
);
const trackerText = needsMoreProtection ? (
<span>{c('Info').t`Email tracker protection is disabled`}</span>
) : (
<>
<div className="flex flex-justify-space-between">
<span>{c('Info').t`Trackers blocked:`}</span>
<span className="pl-4 text-tabular-nums">{numberOfImageTrackers}</span>
</div>
{canCleanUTMTrackers && (
<div className="flex flex-justify-space-between">
<span>{c('Info').t`Links cleaned:`}</span>
<span className="pl-4 text-tabular-nums">{numberOfUTMTrackers}</span>
</div>
)}
</>
);
/*
* Don't display the tracker icon on sent mail messages
* OR when trackers are not loaded (but we need to display it when user is not using proxy and in plaintext messages)
*/
if (sent || (!imageTrackersLoaded && !needsMoreProtection && !isPlainText(message.data))) {
return null;
}
return (
<span className="absolute message-header-security-icons flex flex-row flex-nowrap">
<LoadContentSpotlight
show={showLoadContentSpotlight}
onDisplayed={onLoadContentSpotlightDisplayed}
anchorRef={anchorRef}
>
<div>
{/* Need to wrap the Tooltip by a div to avoid ref warning because Spotlight is cloning the element and applying refs on top of it */}
<Tooltip title={trackerText}>
<div className="flex" ref={anchorRef}>
<PrivacyDropdown message={message} />
</div>
</Tooltip>
</div>
</LoadContentSpotlight>
</span>
);
};
export default ItemSpyTrackerIcon;
| 3,569
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/spy-tracker/NumberOfElementsBubble.scss
|
@use 'sass:math';
@import '~@proton/styles/scss/lib';
$size-tracker: 1rem !default;
.number-of-elements {
&-link {
block-size: 1.3rem; // just a trick to avoid tooltip positionned on the bubble
}
&-icon-bubble {
display: flex;
justify-content: center;
align-items: center;
inline-size: $size-tracker;
block-size: $size-tracker;
// container is a bit higher than the usual icon size, this is why positionned from bottom
inset-block-end: #{math.div($size-tracker, 2) + rem(1)}; // visual trick for better display
inset-inline-start: 50%;
font-variant: tabular-nums;
&--9plus {
letter-spacing: -0.1rem; // for 9+ case
}
}
}
| 3,570
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/spy-tracker/NumberOfElementsBubble.tsx
|
import clsx from '@proton/utils/clsx';
import './NumberOfElementsBubble.scss';
interface Props {
numberOfElements: number;
className?: string;
}
const NumberOfElementsBubble = ({ numberOfElements, className, ...rest }: Props) => {
return (
<span
{...rest}
className={clsx([
className,
'number-of-elements-icon-bubble bg-primary rounded-50 text-center text-sm m-0 lh130',
numberOfElements > 9 && 'number-of-elements-icon-bubble--9plus',
])}
>
{numberOfElements > 9 ? '9+' : numberOfElements}
</span>
);
};
export default NumberOfElementsBubble;
| 3,571
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/spy-tracker/PrivacyDropdown.tsx
|
import { useEffect } from 'react';
import { c, msgid } from 'ttag';
import { Href } from '@proton/atoms/Href';
import { Dropdown, Icon, useModalState, usePopperAnchor } from '@proton/components/components';
import { FeatureCode } from '@proton/components/containers';
import PreventTrackingToggle from '@proton/components/containers/emailPrivacy/PreventTrackingToggle';
import { useApi, useSpotlightOnFeature } from '@proton/components/hooks';
import { TelemetryMailEvents, TelemetryMeasurementGroups } from '@proton/shared/lib/api/telemetry';
import { sendTelemetryReport } from '@proton/shared/lib/helpers/metrics';
import noTrackersImage from '@proton/styles/assets/img/illustrations/no-trackers-found.svg';
import trackersImage from '@proton/styles/assets/img/illustrations/trackers-found.svg';
import useMailModel from 'proton-mail/hooks/useMailModel';
import { emailTrackerProtectionURL } from '../../../constants';
import { useMessageTrackers } from '../../../hooks/message/useMessageTrackers';
import { loadFakeTrackers } from '../../../logic/messages/images/messagesImagesActions';
import { MessageState } from '../../../logic/messages/messagesTypes';
import { useAppDispatch } from '../../../logic/store';
import SpyTrackerIcon from './SpyTrackerIcon';
import SpyTrackerModal from './SpyTrackerModal';
import UTMTrackerModal from './UTMTrackerModal';
const getTitle = (needsMoreProtection: boolean, trackersCount: number) => {
if (needsMoreProtection) {
return c('Title').t`Protect yourself from trackers`;
} else {
if (trackersCount > 0) {
// translator: trackersCount refers to the number of image trackers + utm trackers found in the message
return c('Title').ngettext(
msgid`We protected you from ${trackersCount} tracker`,
`We protected you from ${trackersCount} trackers`,
trackersCount
);
} else {
return c('Title').t`No trackers found`;
}
}
};
const getDescription = (needsMoreProtection: boolean, hasTrackers: boolean) => {
if (needsMoreProtection) {
return c('Description')
.t`Turn on email tracker protection to prevent advertisers and others from tracking your location and online activity.`;
} else if (!hasTrackers) {
return c('Description').t`We didn't find any known trackers and tracking URLs in this email.`;
}
return undefined;
};
interface Props {
message: MessageState;
}
const PrivacyDropdown = ({ message }: Props) => {
const api = useApi();
const dispatch = useAppDispatch();
const mailSettings = useMailModel('MailSettings');
const [spyTrackerModalProps, setSpyTrackerModalOpen, renderSpyTrackerModal] = useModalState();
const [utmTrackerModalProps, setUTMTrackerModalOpen, renderUTMTrackerModal] = useModalState();
const { anchorRef, isOpen, toggle, close } = usePopperAnchor<HTMLButtonElement>();
const {
numberOfImageTrackers,
imageTrackerText,
needsMoreProtection,
hasImageTrackers,
numberOfUTMTrackers,
utmTrackerText,
hasUTMTrackers,
hasTrackers,
canCleanUTMTrackers,
} = useMessageTrackers(message);
const { show: showSpotlight, onDisplayed } = useSpotlightOnFeature(FeatureCode.PrivacyDropdownOpened, hasTrackers);
// On the first email opened with trackers, we want to open the privacy dropdown
useEffect(() => {
if (showSpotlight) {
toggle();
onDisplayed();
}
}, [showSpotlight]);
const title = getTitle(needsMoreProtection, numberOfImageTrackers + numberOfUTMTrackers);
const description = getDescription(needsMoreProtection, hasTrackers);
const handleShowImageTrackersDetails = () => {
if (numberOfImageTrackers > 0) {
setSpyTrackerModalOpen(true);
}
};
const handleShowUTMTrackersDetails = () => {
if (numberOfUTMTrackers > 0) {
setUTMTrackerModalOpen(true);
}
};
const imageTrackerRow = (
<span className="flex flex-nowrap flex-align-items-center text-left px-2 py-2" data-testid="privacy:image-row">
<span className="flex mr-2 flex-item-noshrink color-success">
<Icon name={'checkmark-circle-filled'} className="my-auto" />
</span>
<span className="flex-item-fluid">{imageTrackerText}</span>
{hasImageTrackers && (
<span className="flex on-rtl-mirror ml-4">
<Icon name="chevron-right" />
</span>
)}
</span>
);
const utmTrackerRow = (
<span className="flex flex-nowrap flex-align-items-center text-left px-2 py-2" data-testid="privacy:utm-row">
<span className="flex mr-2 flex-item-noshrink color-success">
<Icon name={'checkmark-circle-filled'} />
</span>
<span className="flex-item-fluid">{utmTrackerText}</span>
{hasUTMTrackers && (
<span className="flex on-rtl-mirror ml-4">
<Icon name="chevron-right" />
</span>
)}
</span>
);
// When the user enable the setting, the shield icon should not be displayed because we never check for trackers
// A workaround for that is to set the trackerStatus to true for the current message
const handleEnableProxy = async () => {
dispatch(loadFakeTrackers({ ID: message.localID }));
};
const handleOpenDropdown = () => {
toggle();
void sendTelemetryReport({
api,
measurementGroup: TelemetryMeasurementGroups.mailPrivacyDropdown,
event: TelemetryMailEvents.privacy_dropdown_opened,
});
};
return (
<>
<SpyTrackerIcon
numberOfTrackers={numberOfImageTrackers + numberOfUTMTrackers}
needsMoreProtection={needsMoreProtection}
title={imageTrackerText.concat(',', utmTrackerText)}
onClick={handleOpenDropdown}
ref={anchorRef}
/>
<Dropdown anchorRef={anchorRef} isOpen={isOpen} onClose={close} originalPlacement="bottom-end">
<div className="p-4" data-testid="privacy:dropdown-content">
<img src={hasTrackers ? trackersImage : noTrackersImage} alt={title} className="block m-auto" />
<div className="flex text-center flex-justify-center">
<span className="my-4">
<h5 className="text-bold mb-2" tabIndex={-2} data-testid="privacy:title">
{title}
</h5>
{description && <span data-testid="privacy:description">{description}</span>}
<br />
<Href className="ml-1" href={emailTrackerProtectionURL} data-testid="privacy:learn-more">{c(
'Info'
).t`Learn more`}</Href>
</span>
</div>
{needsMoreProtection ? (
<>
<hr className="my-4" />
<div className="text-center">
<div className="inline-flex flex-nowrap flex-align-items-center flex-justify-center">
<PreventTrackingToggle
id="preventTrackingToggle"
preventTracking={mailSettings.ImageProxy}
data-testid="privacy:prevent-tracking-toggle"
onEnable={handleEnableProxy}
/>
<span className="ml-2">{c('Action').t`Block email tracking`}</span>
</div>
</div>
<hr className="mt-4 mb-2" />
</>
) : (
hasTrackers && (
<>
<hr className="my-1" />
{hasImageTrackers && (
<>
<button
onClick={handleShowImageTrackersDetails}
className="interactive w-full rounded-sm"
data-testid="privacy:spy-trackers-row"
>
{imageTrackerRow}
</button>
<hr className="my-1" />
</>
)}
{canCleanUTMTrackers && hasUTMTrackers && (
<>
<button
onClick={handleShowUTMTrackersDetails}
className="interactive w-full rounded-sm"
data-testid="privacy:link-trackers-row"
>
{utmTrackerRow}
</button>
<hr className="my-1" />
</>
)}
</>
)
)}
</div>
</Dropdown>
{renderSpyTrackerModal && <SpyTrackerModal message={message} {...spyTrackerModalProps} />}
{renderUTMTrackerModal && <UTMTrackerModal message={message} {...utmTrackerModalProps} />}
</>
);
};
export default PrivacyDropdown;
| 3,572
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/spy-tracker/SpyTrackerIcon.tsx
|
import { Ref, forwardRef } from 'react';
import { Icon } from '@proton/components';
import clsx from '@proton/utils/clsx';
interface Props {
numberOfTrackers: number;
needsMoreProtection: boolean;
title: string;
className?: string;
onClick?: () => void;
isStandaloneIcon?: boolean;
}
const SpyTrackerIcon = (
{ numberOfTrackers, needsMoreProtection, title, className, onClick, isStandaloneIcon = false }: Props,
ref: Ref<HTMLButtonElement>
) => {
const trackersText = (
<span data-testid="privacy:icon-number-of-trackers">{numberOfTrackers > 99 ? '99+' : numberOfTrackers}</span>
);
const icon = (
<Icon
name={needsMoreProtection ? 'shield-2' : 'shield-2-check-filled'}
size={16}
alt={title}
data-testid="privacy:tracker-icon"
className={clsx(
needsMoreProtection ? 'color-weak' : 'color-primary',
'relative inline-flex item-spy-tracker-link flex-align-items-center',
isStandaloneIcon && 'mr-0.5',
className
)}
/>
);
return (
<div className={clsx(['relative inline-flex item-spy-tracker-link flex-align-items-center', className])}>
{onClick ? (
<button ref={ref} onClick={onClick} className="flex flex-align-items-center">
{icon}
{numberOfTrackers > 0 ? trackersText : undefined}
</button>
) : (
icon
)}
</div>
);
};
export default forwardRef<HTMLButtonElement, Props>(SpyTrackerIcon);
| 3,573
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/spy-tracker/SpyTrackerModal.tsx
|
import { c, msgid } from 'ttag';
import { Href } from '@proton/atoms';
import {
Collapsible,
CollapsibleContent,
CollapsibleHeader,
CollapsibleHeaderIconButton,
Icon,
ModalProps,
ModalTwo,
ModalTwoContent,
ModalTwoFooter,
ModalTwoHeader,
} from '@proton/components';
import trackersImg from '@proton/styles/assets/img/illustrations/trackers-found.svg';
import clsx from '@proton/utils/clsx';
import { emailTrackerProtectionURL } from '../../../constants';
import { Tracker, useMessageTrackers } from '../../../hooks/message/useMessageTrackers';
import { MessageState } from '../../../logic/messages/messagesTypes';
import NumberOfElementsBubble from './NumberOfElementsBubble';
interface Props extends ModalProps {
message: MessageState;
}
const SpyTrackerModal = ({ message, ...rest }: Props) => {
const { numberOfImageTrackers, imageTrackerText, imageTrackers } = useMessageTrackers(message);
const getHeaderContent = (tracker: Tracker) => {
return (
<div className="flex flex-align-items-center">
<div className="flex-item-fluid text-break">{tracker.name}</div>
<NumberOfElementsBubble
numberOfElements={tracker.urls.length}
className="flex-item-noshrink"
data-testid="privacy:icon-number-of-trackers"
aria-label={c('Info').ngettext(
msgid`${numberOfImageTrackers} email tracker blocked`,
`${numberOfImageTrackers} email trackers blocked`,
numberOfImageTrackers
)}
/>
</div>
);
};
const learnMoreLink = (
<Href href={emailTrackerProtectionURL} data-testid="trackersModal:learn-more">{c('Info').t`Learn more`}</Href>
);
return (
<ModalTwo data-testid="spyTrackerModal:trackers" {...rest}>
<ModalTwoHeader title={imageTrackerText} data-testid="trackersModal:title" />
<ModalTwoContent>
<div className="border rounded-lg mb-4 p-4 flex flex-nowrap flex-align-items-center">
<img src={trackersImg} alt={imageTrackerText} className="flex-item-noshrink" />
<p className="color-weak flex-item-fluid pl-4 my-0" data-testid="trackersModal:description">
{c('Info')
.t`We blocked the following advertisers and organizations from seeing when you open this email, what device you’re using, and where you’re located.`}
<br />
<span>{learnMoreLink}</span>
</p>
</div>
{imageTrackers.map((tracker, index) => {
return (
<Collapsible
key={tracker.name}
className={clsx(['border-bottom border-weak', index === 0 && 'border-top'])}
>
<CollapsibleHeader
suffix={
<CollapsibleHeaderIconButton
expandText={c('Action').t`Expand URL`}
collapseText={c('Action').t`Collapse URL`}
>
<Icon name="chevron-down" />
</CollapsibleHeaderIconButton>
}
>
{getHeaderContent(tracker)}
</CollapsibleHeader>
<CollapsibleContent>
{tracker.urls.map((url, index) => (
<p
className="color-weak text-break my-2"
key={`${tracker.name}-${index}-tracker`} // eslint-disable-line react/no-array-index-key
>
{url}
</p>
))}
</CollapsibleContent>
</Collapsible>
);
})}
</ModalTwoContent>
<ModalTwoFooter />
</ModalTwo>
);
};
export default SpyTrackerModal;
| 3,574
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/list/spy-tracker/UTMTrackerModal.tsx
|
import { c } from 'ttag';
import { Button } from '@proton/atoms/Button';
import { Href } from '@proton/atoms/Href';
import {
Icon,
ModalProps,
ModalTwo,
ModalTwoContent,
ModalTwoFooter,
ModalTwoHeader,
Tooltip,
} from '@proton/components/components';
import { openNewTab } from '@proton/shared/lib/helpers/browser';
import cleanLinkImg from '@proton/styles/assets/img/illustrations/clean-utm-trackers.svg';
import { emailTrackerProtectionURL } from '../../../constants';
import { useMessageTrackers } from '../../../hooks/message/useMessageTrackers';
import { MessageState } from '../../../logic/messages/messagesTypes';
interface Props extends ModalProps {
message: MessageState;
}
const UTMTrackerModal = ({ message, ...rest }: Props) => {
const { utmTrackerText, utmTrackers } = useMessageTrackers(message);
const handleOpenLink = (link: string) => {
openNewTab(link);
};
const learnMoreLink = (
<Href href={emailTrackerProtectionURL} data-testid="trackersModal:learn-more">{c('Info').t`Learn more`}</Href>
);
return (
<ModalTwo data-testid="utmTrackerModal:trackers" {...rest}>
<ModalTwoHeader title={utmTrackerText} data-testid="trackersModal:title" />
<ModalTwoContent>
<div className="border rounded-lg mb-4 p-4 flex flex-nowrap flex-align-items-center">
<img src={cleanLinkImg} alt="" className="flex-item-noshrink" />
<p className="color-weak flex-item-fluid pl-4 my-0" data-testid="trackersModal:description">
{c('Info')
.t`We removed tracking information from the following links to help protect you from advertisers and others trying to track your online activity.`}
<br />
<span>{learnMoreLink}</span>
</p>
</div>
{utmTrackers.map((tracker) => {
return (
<div key={`${tracker.originalURL}`} className="mb-4">
<div className="flex flex-column mb-1">
<span className="color-weak text-sm">{c('Label').t`Original link`}</span>
<div className="flex flex-nowrap group-hover-opacity-container max-w-full flex-align-items-center">
<div className="text-ellipsis w-full flex-item-fluid" title={tracker.originalURL}>
{tracker.originalURL}
</div>
<div className="group-hover:opacity-100 group-hover:opacity-100-no-width flex-item-noshrink">
<Tooltip title={c('Label').t`Open in a new tab`}>
<Button
icon
color="weak"
shape="outline"
size="small"
onClick={() => handleOpenLink(tracker.originalURL)}
>
<Icon name="arrow-out-square" alt={c('Label').t`Open in a new tab`} />
</Button>
</Tooltip>
</div>
</div>
</div>
<div className="flex flex-column">
<span className="color-primary text-sm">{c('Label').t`Cleaned`}</span>
<div className="flex flex-nowrap group-hover-opacity-container max-w-full flex-align-items-center">
<div className="text-ellipsis w-full flex-item-fluid" title={tracker.cleanedURL}>
{tracker.cleanedURL}
</div>
<div className="group-hover:opacity-100 group-hover:opacity-100-no-width flex-item-noshrink">
<Tooltip title={c('Label').t`Open in a new tab`}>
<Button
icon
color="weak"
shape="outline"
size="small"
onClick={() => handleOpenLink(tracker.cleanedURL)}
>
<Icon name="arrow-out-square" alt={c('Label').t`Open in a new tab`} />
</Button>
</Tooltip>
</div>
</div>
</div>
</div>
);
})}
</ModalTwoContent>
<ModalTwoFooter />
</ModalTwo>
);
};
export default UTMTrackerModal;
| 3,575
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/EncryptionStatusIcon.test.tsx
|
import { render, within } from '@testing-library/react';
import EncryptionStatusIcon from './EncryptionStatusIcon';
describe('EncryptionStatusIcon', () => {
describe('when loading is true', () => {
it('should render loader', () => {
const { getByTestId, getByText } = render(<EncryptionStatusIcon loading />);
getByTestId('circle-loader');
getByText('Loading');
});
});
describe('when fill or encrypted is undefined', () => {
it('should not render anything', () => {
const { container } = render(<EncryptionStatusIcon fill={undefined} loading={false} />);
expect(container.firstChild).toBeNull();
});
it('should not render anything', () => {
const { container } = render(<EncryptionStatusIcon isEncrypted={undefined} loading={false} />);
expect(container.firstChild).toBeNull();
});
});
describe('when isDetailsModal is true', () => {
it('should not render icon in span', () => {
const props = {
isEncrypted: true,
fill: 2,
text: 'End to End encrypted',
loading: false,
isDetailsModal: true,
};
const { queryByTestId, getByTestId, getByText } = render(<EncryptionStatusIcon {...props} />);
getByTestId('encryption-icon');
getByText('End to End encrypted');
expect(queryByTestId('encryption-icon-tooltip')).toBeNull();
});
});
describe('when there is a href', () => {
it('should render inside <a> tag and tooltip', () => {
const props = {
isEncrypted: false,
fill: 2,
loading: false,
text: 'This email adress is invalid',
};
const { getByTestId } = render(<EncryptionStatusIcon {...props} />);
const tooltip = getByTestId('encryption-icon-tooltip');
// workaround to be able to get by tag
const href = within(tooltip).getByText((_, el) => el?.tagName.toLowerCase() === 'a');
within(href).getByText('This email adress is invalid');
within(href).getByTestId('encryption-icon');
});
});
describe('when shouldHaveHref is false', () => {
it('should render only inside tooltip', () => {
const props = {
isEncrypted: false,
fill: 2,
loading: false,
text: 'This email adress is invalid',
shouldHaveHref: false,
};
const { getByTestId } = render(<EncryptionStatusIcon {...props} />);
const tooltip = getByTestId('encryption-icon-tooltip');
within(tooltip).getByText('This email adress is invalid');
within(tooltip).getByTestId('encryption-icon');
expect(within(tooltip).queryByText((_, el) => el?.tagName.toLowerCase() === 'a')).toBeNull();
});
});
});
| 3,576
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/EncryptionStatusIcon.tsx
|
import { Href } from '@proton/atoms';
import { Icon, Loader, Tooltip } from '@proton/components';
import clsx from '@proton/utils/clsx';
import { getSendIconHref, getStatusIconName } from '../../helpers/message/icon';
import { StatusIcon } from '../../models/crypto';
interface Props extends Partial<StatusIcon> {
loading?: boolean;
disabled?: boolean;
useTooltip?: boolean;
className?: string;
isDetailsModal?: boolean;
shouldHaveHref?: boolean;
}
const EncryptionStatusIcon = ({
isEncrypted,
fill,
text,
loading,
shouldHaveHref = true,
/**
* Disabled is for the case when composer is fully disabled
*/
disabled,
useTooltip = true,
className,
isDetailsModal = false,
colorClassName,
}: Props) => {
if (loading) {
return <Loader className="icon-16p m-auto flex" />;
}
if (fill === undefined && isEncrypted === undefined) {
return null;
}
const href = shouldHaveHref && getSendIconHref({ isEncrypted, fill });
const iconName = getStatusIconName({ isEncrypted, fill });
const tooltip = useTooltip ? text : undefined;
const spanClassNames = clsx(['inline-flex flex-item-noshrink align-middle', className]);
const icon = iconName && (
<Icon size={16} name={iconName} className={colorClassName} alt={text || ''} data-testid="encryption-icon" />
);
if (isDetailsModal) {
return <span className={spanClassNames}>{icon}</span>;
}
return (
<Tooltip title={tooltip} data-testid="encryption-icon-tooltip">
<span className={spanClassNames}>
{href ? (
<Href href={href} className="flex flex-item-noshrink m-auto" tabIndex={disabled ? -1 : undefined}>
{icon}
</Href>
) : (
icon
)}
</span>
</Tooltip>
);
};
export default EncryptionStatusIcon;
| 3,577
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/LoadContentSpotlight.tsx
|
import { ReactElement, RefObject } from 'react';
import { c } from 'ttag';
import { SettingsLink, Spotlight } from '@proton/components/components';
import { APPS } from '@proton/shared/lib/constants';
import loadContentImg from '@proton/styles/assets/img/illustrations/spotlight-load-content.svg';
interface Props {
children: ReactElement;
anchorRef: RefObject<HTMLElement>;
show: boolean;
onDisplayed: () => void;
}
const LoadContentSpotlight = ({ children, anchorRef, show, onDisplayed }: Props) => {
// translator: This string is part of a longer string and is used to redirect the user to the settings
// Full string for reference: We now load images by default and block senders from tracking you. This can be changed in the settings.
const settingsLink = (
<SettingsLink path="/email-privacy" app={APPS.PROTONMAIL} key="load-content-settings-link">{c(
'Link to settings'
).t`settings`}</SettingsLink>
);
// translator: The variable "settingsLink" is a link used to redirect the user to the settings. It should contain "settings"
// Full string for reference: We now load images by default and block senders from tracking you. This can be changed in the settings.
const text = c('Spotlight')
.jt`We now load images by default and block senders from tracking you. This can be changed in the ${settingsLink}.`;
return (
<Spotlight
originalPlacement="bottom-end"
show={show}
onDisplayed={onDisplayed}
anchorRef={anchorRef}
style={{ maxWidth: '25rem' }}
content={
<>
<div className="flex flex-nowrap my-2">
<div className="flex-item-noshrink mr-4">
<img src={loadContentImg} className="w-custom" style={{ '--w-custom': '4em' }} alt="" />
</div>
<div>
<p className="mt-0 mb-2 text-bold">{c('Spotlight').t`Email tracking protection`}</p>
<p className="m-0">{text}</p>
</div>
</div>
</>
}
>
{children}
</Spotlight>
);
};
export default LoadContentSpotlight;
| 3,578
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/MessageBody.tsx
|
import { RefObject, useEffect, useMemo, useRef, useState } from 'react';
import { useTheme } from '@proton/components';
import { scrollIntoView } from '@proton/shared/lib/helpers/dom';
import { isPlainText } from '@proton/shared/lib/mail/messages';
import clsx from '@proton/utils/clsx';
import useMailModel from 'proton-mail/hooks/useMailModel';
import { useOnMailTo } from '../../containers/ComposeProvider';
import { useEncryptedSearchContext } from '../../containers/EncryptedSearchProvider';
import { locateBlockquote } from '../../helpers/message/messageBlockquote';
import { MessageState } from '../../logic/messages/messagesTypes';
import MessageBodyIframe from './MessageBodyIframe';
import useMessageDarkStyles from './hooks/useMessageDarkStyles';
interface Props {
labelID: string;
messageLoaded: boolean;
bodyLoaded: boolean;
sourceMode: boolean;
message: MessageState;
originalMessageMode: boolean;
toggleOriginalMessage?: () => void;
/**
* Needed for print message
* true: don't show button, show full content
* false: (default) show button and collapse blockquote (if one founded)
*/
forceBlockquote?: boolean;
onMessageReady?: () => void;
isPrint?: boolean;
onIframeReady?: (iframeRef: RefObject<HTMLIFrameElement>) => void;
onFocusIframe?: () => void;
hasQuickReply?: boolean;
}
const MessageBody = ({
messageLoaded,
bodyLoaded,
sourceMode: inputSourceMode,
message,
forceBlockquote = false,
originalMessageMode,
toggleOriginalMessage,
onMessageReady,
isPrint = false,
labelID,
onIframeReady,
onFocusIframe,
hasQuickReply = false,
}: Props) => {
const [isIframeContentSet, setIsIframeContentSet] = useState(false);
const bodyRef = useRef<HTMLDivElement>(null);
const iframeRef = useRef<HTMLIFrameElement>(null);
const theme = useTheme();
const { highlightString, shouldHighlight } = useEncryptedSearchContext();
const onMailTo = useOnMailTo();
const mailSettings = useMailModel('MailSettings');
const highlightBody = shouldHighlight();
const plain = isPlainText(message.data);
const { support: hasDarkStyles, loading: hasDarkStylesLoading } = useMessageDarkStyles(
message,
isIframeContentSet,
iframeRef
);
const [content, blockquote] = useMemo(
() =>
plain
? [message.messageDocument?.plainText as string, '']
: locateBlockquote(message.messageDocument?.document),
[message.messageDocument?.document?.innerHTML, message.messageDocument?.plainText, plain]
);
const encryptedMode = messageLoaded && !!message.errors?.decryption?.length;
const sourceMode = !encryptedMode && inputSourceMode;
const decryptingMode = !encryptedMode && !sourceMode && !bodyLoaded && messageLoaded;
const loadingMode = !messageLoaded;
const contentMode = !encryptedMode && !sourceMode && bodyLoaded;
const contentModeShow = contentMode && isIframeContentSet && !hasDarkStylesLoading;
const placeholderMode = (loadingMode || decryptingMode || !contentModeShow) && !sourceMode;
const isBlockquote = blockquote !== '';
const showButton = !forceBlockquote && isBlockquote;
const showBlockquote = forceBlockquote || originalMessageMode || hasDarkStylesLoading;
const highlightedContent = useMemo(
() => (!!content && highlightBody ? highlightString(content, true) : content),
[content, highlightBody]
);
const highlightedBlockquote = useMemo(
() =>
!!blockquote && highlightBody
? highlightString(blockquote, !highlightedContent.includes('data-auto-scroll'))
: blockquote,
[blockquote, highlightBody]
);
const showBlockquoteResults = highlightedBlockquote !== blockquote;
useEffect(() => {
if (!loadingMode && !decryptingMode && onMessageReady) {
setTimeout(onMessageReady);
}
}, [loadingMode, decryptingMode, message.data?.ID]);
const handleContentLoaded = () => {
setIsIframeContentSet(true);
};
useEffect(() => {
if (contentModeShow && !!content && highlightBody) {
const el = iframeRef.current?.contentDocument?.querySelector('[data-auto-scroll]') as HTMLElement;
scrollIntoView(el, { block: 'center', behavior: 'smooth' });
}
}, [contentModeShow, content, highlightBody]);
return (
<div
ref={bodyRef}
className={clsx([
'message-content relative bg-norm color-norm overflow-hidden',
plain && 'plain',
isPrint && 'message-content-print',
isPrint || !isIframeContentSet ? '' : 'py-4 px-5',
!placeholderMode && !hasDarkStyles && theme.information.dark && !plain && !sourceMode && 'dark-style', // Required for the iframe margin reserved for the horizontal scroll
hasQuickReply && 'message-content-has-quick-reply',
])}
data-testid="message-content:body"
>
{encryptedMode && <pre className="m-0 p-4">{message.data?.Body}</pre>}
{sourceMode && <pre className="m-0 p-4">{message.decryption?.decryptedBody}</pre>}
{placeholderMode && !encryptedMode && (
<div className="bg-norm color-norm p-4">
<div
className="message-content-loading-placeholder mx-4 mb-4 max-w-custom"
style={{ '--max-w-custom': '8em' }}
/>
<div
className="message-content-loading-placeholder mx-4 mb-4 max-w-custom"
style={{ '--max-w-custom': '50em' }}
/>
<div
className="message-content-loading-placeholder mx-4 mb-4 max-w-custom"
style={{ '--max-w-custom': '40em' }}
/>
<div
className="message-content-loading-placeholder mx-4 mb-4 max-w-custom"
style={{ '--max-w-custom': '50em' }}
/>
<div
className="message-content-loading-placeholder mx-4 mb-4 max-w-custom"
style={{ '--max-w-custom': '15em' }}
/>
<div
className="message-content-loading-placeholder mx-4 mb-4 max-w-custom"
style={{ '--max-w-custom': '8em' }}
/>
</div>
)}
{contentMode && (
<div
className={clsx([
'message-iframe',
!contentModeShow && 'message-iframe--hidden',
!isPrint && isIframeContentSet && 'p-4',
])}
>
<MessageBodyIframe
iframeRef={iframeRef}
content={highlightedContent}
blockquoteContent={highlightedBlockquote}
showBlockquoteToggle={showButton}
showBlockquote={showBlockquote || showBlockquoteResults}
onBlockquoteToggle={toggleOriginalMessage}
onContentLoaded={handleContentLoaded}
isPlainText={plain}
hasDarkStyles={hasDarkStyles}
isPrint={isPrint}
message={message}
labelID={labelID}
onReady={onIframeReady}
onMailTo={onMailTo}
mailSettings={mailSettings}
onFocus={onFocusIframe}
/>
</div>
)}
</div>
);
};
export default MessageBody;
| 3,579
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/MessageBodyIframe.tsx
|
import { RefObject, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { c } from 'ttag';
import { Icon, Tooltip, useSyncIframeStyles, useTheme } from '@proton/components';
import { useLinkHandler } from '@proton/components/hooks/useLinkHandler';
import { MailSettings } from '@proton/shared/lib/interfaces';
import { hasAttachments, isAutoFlaggedPhishing, isSuspicious } from '@proton/shared/lib/mail/messages';
import clsx from '@proton/utils/clsx';
import { useMailboxContainerContext } from '../../containers/mailbox/MailboxContainerProvider';
import { MessageState } from '../../logic/messages/messagesTypes';
import MessageBodyImages from './MessageBodyImages';
import MessagePrintFooter from './MessagePrintFooter';
import MessagePrintHeader from './MessagePrintHeader';
import { MESSAGE_IFRAME_PRINT_FOOTER_ID, MESSAGE_IFRAME_PRINT_HEADER_ID } from './constants';
import getIframeSandboxAttributes from './helpers/getIframeSandboxAttributes';
import useIframeDispatchEvents from './hooks/useIframeDispatchEvents';
import useIframeShowBlockquote from './hooks/useIframeShowBlockquote';
import useInitIframeContent from './hooks/useInitIframeContent';
import useObserveIframeHeight from './hooks/useObserveIframeHeight';
interface Props {
iframeRef: RefObject<HTMLIFrameElement>;
content: string;
showBlockquote: boolean;
showBlockquoteToggle: boolean;
blockquoteContent: string;
isPlainText: boolean;
onBlockquoteToggle?: () => void;
onContentLoaded: (iframeRootElement: HTMLDivElement) => void;
isPrint?: boolean;
hasDarkStyles?: boolean;
message: MessageState;
labelID: string;
onReady?: (iframeRef: RefObject<HTMLIFrameElement>) => void;
onMailTo?: (src: string) => void;
isOutside?: boolean;
mailSettings: MailSettings;
onFocus?: () => void;
}
const MessageBodyIframe = ({
iframeRef,
content,
blockquoteContent,
showBlockquote: showBlockquoteProp,
showBlockquoteToggle,
onBlockquoteToggle,
onContentLoaded,
isPlainText,
hasDarkStyles,
isPrint = false,
message,
labelID,
onReady,
onMailTo,
isOutside,
mailSettings,
onFocus,
}: Props) => {
const theme = useTheme();
const hasAttachment = hasAttachments(message.data);
useSyncIframeStyles(iframeRef.current?.contentWindow?.document.documentElement, document.documentElement);
const { isResizing } = useMailboxContainerContext();
const { initStatus, iframeRootDivRef } = useInitIframeContent({
messageID: message.data?.ID,
content,
message,
iframeRef,
onContentLoaded,
isPlainText,
onReady,
isPrint,
});
const { showToggle, iframeToggleDiv, showBlockquote, setShowBlockquote } = useIframeShowBlockquote({
blockquoteContent,
iframeRef,
initStatus,
showBlockquoteProp,
showBlockquoteToggle,
onBlockquoteToggle,
});
const iframePrintHeaderDiv = iframeRef.current?.contentDocument?.getElementById(MESSAGE_IFRAME_PRINT_HEADER_ID);
const iframePrintFooterDiv = iframeRef.current?.contentDocument?.getElementById(MESSAGE_IFRAME_PRINT_FOOTER_ID);
const { modal: linkModal } = useLinkHandler(iframeRootDivRef, mailSettings, {
onMailTo,
startListening: initStatus === 'done' && iframeRootDivRef.current !== undefined,
isOutside,
isPhishingAttempt: isAutoFlaggedPhishing(message.data) || isSuspicious(message.data),
});
useIframeDispatchEvents(initStatus === 'done', iframeRef, onFocus);
useObserveIframeHeight(initStatus === 'done', iframeRef);
useEffect(() => {
if (iframeRootDivRef.current) {
iframeRootDivRef.current?.classList[hasDarkStyles ? 'add' : 'remove']('proton-dark-style');
}
}, [hasDarkStyles]);
useEffect(() => {
/** Add class in case the user theme is dark. Helps fixing issues with dark themes */
iframeRootDivRef.current?.classList[theme.information.dark ? 'add' : 'remove']('proton-dark-theme');
}, [theme.information.dark]);
return (
<>
<iframe
title={c('Title').t`Email content`}
src="about:blank"
scrolling="yes"
frameBorder="0"
ref={iframeRef}
className={clsx([initStatus !== 'start' ? 'w-full' : 'w-0 h-0', isResizing && 'no-pointer-events'])}
data-testid="content-iframe"
data-subject={message.data?.Subject}
sandbox={getIframeSandboxAttributes(isPrint)}
allowFullScreen={false}
/>
{initStatus !== 'start' && (
<MessageBodyImages
iframeRef={iframeRef}
isPrint={isPrint}
messageImages={message.messageImages}
localID={message.localID}
useProxy={!!mailSettings.ImageProxy}
/>
)}
{showToggle &&
iframeToggleDiv &&
createPortal(
<Tooltip
title={showBlockquote ? c('Info').t`Hide original message` : c('Info').t`Show original message`}
relativeReference={iframeRef}
>
<button
type="button"
className="proton-toggle-button inline-flex"
onClick={() => {
setShowBlockquote(!showBlockquote);
}}
data-testid="message-view:expand-codeblock"
>
<Icon name="three-dots-horizontal" size={14} className="m-auto" />
<span className="proton-sr-only">
{showBlockquote
? c('Info').t`Hide original message`
: c('Info').t`Show original message`}
</span>
</button>
</Tooltip>,
iframeToggleDiv
)}
{isPrint &&
iframePrintHeaderDiv &&
createPortal(<MessagePrintHeader message={message} labelID={labelID} />, iframePrintHeaderDiv)}
{hasAttachment &&
isPrint &&
iframePrintFooterDiv &&
createPortal(<MessagePrintFooter message={message} />, iframePrintFooterDiv)}
{linkModal}
</>
);
};
export default MessageBodyIframe;
| 3,580
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/MessageBodyImage.tsx
|
import { CSSProperties, RefObject, useEffect, useRef } from 'react';
import { createPortal } from 'react-dom';
import { c } from 'ttag';
import { Icon, Tooltip, useApi } from '@proton/components';
import { SimpleMap } from '@proton/shared/lib/interfaces';
import clsx from '@proton/utils/clsx';
import { getAnchor } from '../../helpers/message/messageImages';
import { failedRemoteDirectLoading, loadRemoteProxy } from '../../logic/messages/images/messagesImagesActions';
import { MessageImage } from '../../logic/messages/messagesTypes';
import { useAppDispatch } from '../../logic/store';
const sizeProps: ['width', 'height'] = ['width', 'height'];
const spineToCamelCase = (value: string) => value.replaceAll(/-([a-z])/g, (_, letter) => letter.toUpperCase());
const forEachStyle = (style: CSSStyleDeclaration | undefined, iterator: (property: string, value: string) => void) => {
if (!style) {
return;
}
for (let i = 0; i < (style.length || 0); i++) {
const prop = style.item(i);
iterator(prop, style[prop as any]);
}
};
const extractStyle = (original: HTMLElement | undefined, documentWidth: number | undefined): CSSProperties => {
if (!original) {
return {};
}
const style: CSSProperties = {};
forEachStyle(original.style, (prop, value) => {
if (
prop !== 'display' &&
!prop.startsWith('border') &&
!prop.startsWith('outline') &&
!prop.startsWith('background') &&
!prop.startsWith('padding')
) {
style[spineToCamelCase(prop)] = value;
}
});
sizeProps.forEach((prop) => {
const value = original?.getAttribute(prop)?.trim();
if (value?.endsWith('%') || value === 'auto') {
style[prop] = value;
} else if (value) {
if (documentWidth && Number(value.replace('px', '') || 0) > documentWidth) {
style[prop] = '100%';
} else {
style[prop] = `${value}px`;
}
} else if (!style[prop]) {
style[prop] = '30px';
}
});
return style;
};
interface Props {
showRemoteImages: boolean;
showEmbeddedImages: boolean;
image: MessageImage;
anchor: HTMLElement;
isPrint?: boolean;
iframeRef: RefObject<HTMLIFrameElement>;
localID: string;
useProxy: boolean;
}
const MessageBodyImage = ({
showRemoteImages,
showEmbeddedImages,
image,
anchor,
isPrint,
iframeRef,
localID,
useProxy,
}: Props) => {
const dispatch = useAppDispatch();
const api = useApi();
const imageRef = useRef<HTMLImageElement>(null);
// Ref used to trigger an action after a onError while trying to load the image
const hasLoadedAfterError = useRef({ hasLoadedProxy: false, hasLoadedDirect: false });
const { type, error, url, status, original } = image;
const showPlaceholder =
error || status !== 'loaded' || (type === 'remote' ? !showRemoteImages : !showEmbeddedImages);
const showImage = !showPlaceholder;
const attributes =
original?.getAttributeNames().reduce<SimpleMap<string>>((acc, name) => {
acc[name] = original?.getAttribute(name) as string;
return acc;
}, {}) || {};
forEachStyle(original?.style, (prop, value) => {
anchor.style[prop as any] = value;
});
useEffect(() => {
if (showImage) {
Object.entries(attributes)
.filter(([key]) => !key.endsWith('src'))
.forEach(([key, value]) => {
imageRef.current?.setAttribute(key, value as string);
});
}
}, [showImage]);
const handleError = async () => {
// If the image fails to load from the URL, we have no way to know why it has failed
// But depending on the error, we want to handle it differently
// In that case, we try to load the image "the old way", we will have more control on the error
// Only make this call when user is using proxy.
// - Without proxy we are already trying to load direct
// - With EO, we are also already trying to load direct
// However, if we are trying to load the image without the proxy, we don't want to trigger the load remote onError
if (type === 'remote' && useProxy && !hasLoadedAfterError.current.hasLoadedProxy) {
hasLoadedAfterError.current.hasLoadedProxy = true;
await dispatch(loadRemoteProxy({ ID: localID, imageToLoad: image, api }));
} else if (type === 'remote' && !hasLoadedAfterError.current.hasLoadedDirect) {
// Instead, we want to add an error to the image in the state to display a placeholder
hasLoadedAfterError.current.hasLoadedDirect = true;
await dispatch(failedRemoteDirectLoading({ ID: localID, image }));
}
};
if (showImage) {
// attributes are the provided by the code just above, coming from original message source
// eslint-disable-next-line jsx-a11y/alt-text
return <img ref={imageRef} src={url} loading="lazy" onError={handleError} />;
}
const showLoader = status === 'loading';
const errorMessage = error?.data?.Error
? error?.data?.Error
: c('Message image')
.t`Your browser could not verify the remote server's identity. The image might be hosted using the http protocol.`;
const placeholderTooltip = error
? errorMessage
: c('Message image').t`Image has not been loaded in order to protect your privacy.`;
const icon = error ? 'cross-circle' : 'file-shapes';
const style = extractStyle(original, iframeRef.current?.contentWindow?.innerWidth);
const placeholder = (
<span
style={style}
className={clsx(['proton-image-placeholder', !!error && 'proton-image-placeholder--error border-danger'])}
>
{!showLoader ? <Icon name={icon} size={20} /> : null}
{showLoader ? (
<>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" className="proton-circle-loader">
<circle cx="100" cy="100" r="70" className="proton-circle-loader-track" />
<circle cx="100" cy="100" r="70" className="proton-circle-loader-circle" />
</svg>
<span className="proton-sr-only">{c('Info').t`Loading`}</span>
</>
) : null}
</span>
);
if (isPrint) {
return placeholder;
}
return (
<Tooltip title={placeholderTooltip} relativeReference={iframeRef}>
{placeholder}
</Tooltip>
);
};
const MessageBodyImagePortal = ({ iframeRef, ...props }: Omit<Props, 'anchor'>) => {
const iframeBody = iframeRef.current?.contentWindow?.document.body;
const anchor = getAnchor(iframeBody, props.image);
if (!anchor) {
return null;
}
return createPortal(<MessageBodyImage {...props} anchor={anchor} iframeRef={iframeRef} />, anchor);
};
export default MessageBodyImagePortal;
| 3,581
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/MessageBodyImages.tsx
|
import { RefObject, useEffect, useRef } from 'react';
import { MessageImages } from '../../logic/messages/messagesTypes';
import MessageBodyImage from './MessageBodyImage';
interface Props {
messageImages: MessageImages | undefined;
iframeRef: RefObject<HTMLIFrameElement>;
isPrint: boolean;
onImagesLoaded?: () => void;
localID: string;
useProxy: boolean;
}
const MessageBodyImages = ({ messageImages, iframeRef, isPrint, onImagesLoaded, localID, useProxy }: Props) => {
const hasTriggeredLoaded = useRef<boolean>(false);
useEffect(() => {
if (!hasTriggeredLoaded.current && messageImages?.images.every((img) => img.status === 'loaded')) {
onImagesLoaded?.();
hasTriggeredLoaded.current = true;
}
}, [messageImages?.images]);
return (
<>
{messageImages
? messageImages.images.map((image) => (
<MessageBodyImage
key={image.id}
iframeRef={iframeRef}
showRemoteImages={messageImages?.showRemoteImages || false}
showEmbeddedImages={messageImages?.showEmbeddedImages || false}
image={image}
isPrint={isPrint}
localID={localID}
useProxy={useProxy}
/>
))
: null}
</>
);
};
export default MessageBodyImages;
| 3,582
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/MessageFooter.tsx
|
import { getAttachments } from '@proton/shared/lib/mail/messages';
import clsx from '@proton/utils/clsx';
import { MessageState, MessageStateWithData, OutsideKey } from '../../logic/messages/messagesTypes';
import AttachmentList, { AttachmentAction } from '../attachment/AttachmentList';
interface Props {
message: MessageState;
outsideKey?: OutsideKey;
}
const MessageFooter = ({ message, outsideKey }: Props) => {
const attachments = getAttachments(message.data);
return (
<div className={clsx(['message-attachments bg-norm color-norm p-4 mx-3'])} data-testid="message-attachments">
<AttachmentList
attachments={attachments}
message={message as MessageStateWithData}
primaryAction={AttachmentAction.Preview}
secondaryAction={AttachmentAction.Download}
collapsable={false}
className="message-attachments-list"
outsideKey={outsideKey}
/>
</div>
);
};
export default MessageFooter;
| 3,583
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/MessageIframe.raw.scss
|
$use-vertical-align-img-iframe: false;
@import '~@proton/styles/scss/lib';
@import '@proton/styles/scss/base/reset';
@import '@proton/styles/scss/base/scrollbar';
@import '@proton/styles/scss/base/custom-properties';
/* ----------------------
EMAIL RESET
------------------------ */
body {
/* in case nothing is set, set a default font and size */
font-family: system-ui, sans-serif;
font-size: em($base-font-size, $root-default-font-size);
/* this is clearly needed if we want consistency */
text-rendering: geometricprecision;
-webkit-font-smoothing: antialiased;
overflow: auto hidden;
}
/* override reset.scss */
body * {
line-height: 1.5;
}
code {
line-height: 1;
}
/* Forbidden property on almost ALL clients IE add a space :) */
[style*='position:absolute'],
[style*='position: absolute'] {
position: relative !important;
}
/* Forbidden height with pourcentage on images */
img[height$='%'] {
block-size: unset !important;
}
// remove reset margins
blockquote,
dl,
ol,
p,
pre,
td,
th,
ul {
margin-block: 0;
}
p {
margin-block: 1em;
}
table {
margin-block-end: 0;
table-layout: auto;
}
blockquote {
padding-block: 0;
padding-inline: rem(16) 0;
margin: 0;
border-inline-start: 4px solid #e5e5e5;
&::after,
&::before {
content: none;
}
}
// fix for some embedded images bugs
img {
max-inline-size: none;
}
pre,
code {
white-space: pre-wrap;
background-color: transparent;
}
ul,
ol {
/**
* Overrides app reset in order to get back to native browser spacing
* Fix issue when ordered list has more than 10 items
*/
padding-inline-start: em(40);
}
/* ---------------------------------
CUSTOM STYLES AND HELPERS
----------------------------------- */
a {
color: var(--interaction-norm);
text-decoration: underline;
cursor: pointer;
}
a:hover,
a:focus {
color: var(--interaction-norm-hover);
text-decoration: none;
}
a:active {
color: var(--interaction-norm-active);
text-decoration: none;
}
/** Links without href attributes */
a:not([href]) {
text-decoration: none !important;
color: inherit !important;
cursor: default !important;
pointer-events: none;
}
/**
* Avoid overflow management on #proton-root.
* Better to handle it in body because risk of wrong height calculation
*/
#proton-root {
box-sizing: content-box;
max-inline-size: none;
}
.proton-dark-style {
color: var(--text-norm);
background-color: var(--background-norm);
}
.proton-hidden {
display: none;
}
.proton-sr-only {
border: 0;
clip: rect(0 0 0 0);
block-size: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
inline-size: 1px;
inset-block-start: 0; // needed for Safari dumb and 💩 behaviour
}
.icon-14p {
inline-size: 14px;
block-size: 14px;
}
/*
* 1. do not handle responsivess if there is a width attribute / inline width style
* 2. do not set auto height as long as it's not need to handle our embedded images (no height attribute)
* 3. set at least a min width or it's possible it won't be shown
* 4. remove min-inline-size when image loaded - for tiny images
*/
.proton-embedded:not([width], [style*='width']) {
max-inline-size: 100%;
min-inline-size: 38px;
}
.proton-embedded:not([width], [style*='width'])[src] {
min-inline-size: 0;
}
blockquote.protonmail_quote {
padding-block: 0.2em;
padding-inline: 1.2em 0;
border-color: #657ee4;
border-inline-start-width: 3px;
border-inline-start-style: solid;
}
blockquote.protonmail_quote
blockquote.protonmail_quote
blockquote.protonmail_quote
blockquote.protonmail_quote
blockquote.protonmail_quote
blockquote.protonmail_quote {
padding-inline: 0;
border-inline-start-width: 0;
}
/* -----------------------
PLAIN TEXT
------------------------- */
.proton-plain-text {
font-family: $font-family-monospace;
background: var(--background-norm);
color: var(--text-norm);
white-space: pre-wrap;
text-rendering: geometricprecision;
-webkit-font-smoothing: antialiased;
}
/* ---------------------------------
BUTTONS
----------------------------------- */
.proton-toggle-button {
display: inline-block;
padding-block: rem(4);
padding-inline: rem(8);
margin: 1em;
margin-inline-start: 0;
box-shadow: inset 0 0 0 1px silver;
border: none;
border-radius: var(--border-radius-md);
outline: none;
background-color: transparent;
text-align: center;
transition:
0.15s cubic-bezier(0.22, 1, 0.36, 1),
background-position 0s;
&:hover,
&:focus,
&:focus-within &.is-hover &:active,
&.is-active,
&[aria-expanded='true']:not([aria-controls]) {
text-decoration: none;
box-shadow: inset 0 0 0 2px silver;
background-color: transparent;
}
}
@supports selector(:focus-visible) {
.proton-toggle-button {
outline: unset;
}
}
/* ---------------------------------
IMAGE PLACEHOLDER
----------------------------------- */
.proton-image-placeholder {
/* stylelint-disable-next-line color-hex-length */
background-color: #00000011;
box-sizing: border-box;
display: inline-flex;
border: 1px solid var(--border-norm);
border-radius: var(--border-radius-md);
justify-content: center;
align-items: center;
color: black;
margin-block-end: 7px;
margin-inline-end: 7px;
}
.proton-image-placeholder--error {
color: #d42f34;
border-color: #d42f34;
}
.proton-image-placeholder .icon-20p {
inline-size: 1.25rem;
block-size: 1.25rem;
display: inline-block;
vertical-align: middle;
fill: currentcolor;
}
@keyframes anime-loader-rotation {
from {
transform: rotate(0);
}
to {
transform: rotate(360deg);
}
}
.proton-circle-loader {
font-size: 20px;
display: inline-block;
inline-size: 1em;
block-size: 1em;
transform-origin: 50%;
vertical-align: middle;
animation: anime-loader-rotation 2s linear infinite;
}
.proton-circle-loader-track {
stroke: currentcolor;
opacity: 0.2;
}
.proton-circle-loader-track,
.proton-circle-loader-circle {
fill: none;
stroke-width: 20;
stroke-linecap: round;
}
@keyframes anime-loader-stroke {
0% {
stroke-dashoffset: 440;
}
50% {
stroke-dashoffset: 0;
}
50.1% {
stroke-dashoffset: 880;
}
}
.proton-circle-loader-circle {
stroke: currentcolor;
stroke-dasharray: 440;
stroke-dashoffset: 440;
animation: anime-loader-stroke 4s linear infinite;
}
/* ---------------------
PRINT
------------------------ */
.proton-print {
/* stylelint-disable-next-line no-invalid-position-at-import-rule */
@import '~@proton/styles/scss/utilities/flex';
/* stylelint-disable-next-line no-invalid-position-at-import-rule */
@import '~@proton/styles/scss/utilities/outline';
.sr-only {
border: 0;
clip: rect(0 0 0 0);
block-size: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
inline-size: 1px;
inset-block-start: 0; // needed for Safari dumb and 💩 behaviour
}
font-family: var(--font-family);
font-size: 14px;
line-height: 1.5;
color: var(--text-norm);
background-color: white;
text-rendering: geometricprecision;
-webkit-font-smoothing: antialiased;
padding-block-end: 1em;
overflow: auto;
&.proton-plain-text {
&,
.proton-print {
background-color: transparent;
}
}
.message-print-subject {
font-size: 20px;
border-block-end: 1px solid var(--border-norm);
padding-block-end: 0.5em;
margin: 0;
background-color: var(--background-norm);
}
.message-print-header {
border-block-end: 1px solid var(--border-weak);
padding-block-end: 1em;
background-color: var(--background-norm);
}
.message-recipient-item-expanded {
margin-block-start: 0.75em;
}
// trick to get elements aligned, whatever is the length of first cell
.message-print-recipient-container {
display: table;
> * {
display: table-row;
padding-block: 0.5em;
> * {
display: table-cell;
padding-block: 0.25em;
}
}
}
.container-to {
padding-inline-end: 1em;
text-align: start;
}
.item-icon,
.container-to.container-to--item {
display: none;
}
.item-date {
font-size: 1em;
}
.color-weak {
color: var(--text-norm);
}
.maxw-100 {
max-inline-size: 100%;
}
.text-ellipsis {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.inline-block {
display: inline-block;
}
.text-pre {
white-space: pre;
}
&.proton-dark-theme .proton-print-content {
// only dark styles
color: black;
}
.proton-print-footer {
margin-block-start: 1em;
border-block-start: 1px solid var(--border-weak);
padding-block-start: 1em;
background-color: var(--background-norm);
&-sizes {
margin-block-end: 1em;
&-label {
margin-inline-end: 1em;
}
&-label,
&-count,
&-embedded-count {
align-items: baseline;
}
}
&-item {
max-inline-size: 100%;
border: 1px solid var(--border-weak);
padding-block: 0.5em;
padding-inline: 0.25em;
border-radius: var(--border-radius-md);
}
&-item-size {
margin-inline-start: 0.25rem;
font-size: 0.75em;
color: var(--text-weak);
}
}
.proton-search-highlight {
background: transparent;
font: inherit;
}
}
@include media('print') {
/**
* add in this all elements which need to be hardly reseted for print
*/
body,
html {
background-color: white;
background-image: none;
border: 0;
box-shadow: none;
color: black;
float: none;
block-size: auto;
margin: 0;
max-inline-size: 100%;
min-block-size: 0;
padding: 0;
position: static;
inline-size: auto;
opacity: 1;
visibility: visible;
max-block-size: none;
display: block;
}
.proton-print .message-print-header,
.proton-print .message-print-subject {
background-color: white;
color: black;
}
body {
padding: 0.5em;
overflow: auto;
}
/**
* avoid problematic page break
*/
ul,
ol {
page-break-inside: avoid;
}
h1,
h2,
h3,
caption {
page-break-after: avoid;
}
.proton-print,
.proton-plain-text {
color: black;
background-color: white;
}
.proton-search-highlight {
background: transparent;
font: inherit;
}
.sr-only,
.no-print {
display: none;
}
}
| 3,584
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/MessageOnlyView.tsx
|
import { useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import { Scroll } from '@proton/atoms';
import { useHotkeys, useLabels } from '@proton/components';
import { MailSettings } from '@proton/shared/lib/interfaces';
import { Message } from '@proton/shared/lib/interfaces/mail/Message';
import { isDraft } from '@proton/shared/lib/mail/messages';
import clsx from '@proton/utils/clsx';
import useClickOutsideFocusedMessage from '../../hooks/conversation/useClickOutsideFocusedMessage';
import { useLoadMessage } from '../../hooks/message/useLoadMessage';
import { useMessage } from '../../hooks/message/useMessage';
import useShouldMoveOut from '../../hooks/useShouldMoveOut';
import { removeAllQuickReplyFlags } from '../../logic/messages/draft/messagesDraftActions';
import { MessageWithOptionalBody } from '../../logic/messages/messagesTypes';
import { Breakpoints } from '../../models/utils';
import ConversationHeader from '../conversation/ConversationHeader';
import MessageView, { MessageViewRef } from './MessageView';
interface Props {
hidden: boolean;
labelID: string;
messageID: string;
elementIDs: string[];
loadingElements: boolean;
mailSettings: MailSettings;
onBack: () => void;
breakpoints: Breakpoints;
onMessageReady: () => void;
columnLayout: boolean;
isComposerOpened: boolean;
}
const MessageOnlyView = ({
hidden,
labelID,
messageID,
elementIDs,
loadingElements,
mailSettings,
onBack,
breakpoints,
onMessageReady,
columnLayout,
isComposerOpened,
}: Props) => {
const [labels = []] = useLabels();
const [isMessageFocused, setIsMessageFocused] = useState(false);
const [isMessageReady, setIsMessageReady] = useState(false);
const { message, messageLoaded } = useMessage(messageID);
const load = useLoadMessage(message.data || ({ ID: messageID } as MessageWithOptionalBody));
const dispatch = useDispatch();
useShouldMoveOut({ elementIDs, elementID: messageID, loadingElements, onBack });
// Manage loading the message
useEffect(() => {
if (!messageLoaded) {
void load();
}
}, [messageLoaded]);
useEffect(() => {
// When the user is switching message we need to remove potential quick replies draft flags
dispatch(removeAllQuickReplyFlags());
}, [messageID]);
// Message content could be undefined
const data = message.data || ({ ID: messageID } as Message);
const messageContainerRef = useRef(null);
useHotkeys(messageContainerRef, [
[
'ArrowLeft',
(e) => {
e.preventDefault();
e.stopPropagation();
const element = document.querySelector('[data-shortcut-target="navigation-link inbox"]') as HTMLElement;
if (element) {
element.focus();
setIsMessageFocused(false);
}
},
],
]);
const messageRef = useRef<MessageViewRef>(null);
useClickOutsideFocusedMessage(messageID, () => {
setIsMessageFocused(false);
});
const handleBlurCallback = () => {
setIsMessageFocused(false);
};
const handleFocusCallback = () => {
setIsMessageFocused(true);
};
const handleMessageReadyCallback = () => {
setIsMessageReady(true);
onMessageReady();
};
useEffect(() => {
if (!isDraft(message.data)) {
messageRef?.current?.expand();
}
return () => {
setIsMessageReady(false);
};
}, [messageID]);
const handleGetMessageElement = () => {
const selector = `[data-shortcut-target="message-container"][data-message-id="${messageID}"]`;
return document.querySelector(selector) as HTMLElement;
};
const handleOpenQuickReply = () => {
const element = handleGetMessageElement();
element?.scrollIntoView({ block: 'end', behavior: 'smooth' });
};
useEffect(() => {
if (messageID && isMessageReady) {
const element = handleGetMessageElement();
element?.focus({ preventScroll: true });
setIsMessageFocused(true);
}
}, [messageID, isMessageReady]);
return (
<Scroll className={clsx([hidden && 'hidden'])}>
<ConversationHeader
className={clsx([hidden && 'hidden'])}
loading={!messageLoaded}
element={message.data}
/>
<div className="flex-item-fluid px-4 mt-4 max-w-full outline-none" ref={messageContainerRef} tabIndex={-1}>
<MessageView
// Break the reuse of the MessageView accross multiple message
// Solve a lot of reuse issues, reproduce the same as in conversation mode with a map on conversation messages
key={message.localID}
ref={messageRef}
labelID={labelID}
conversationMode={false}
loading={!messageLoaded}
message={data}
labels={labels}
mailSettings={mailSettings}
onBack={onBack}
breakpoints={breakpoints}
onMessageReady={handleMessageReadyCallback}
columnLayout={columnLayout}
isComposerOpened={isComposerOpened}
onBlur={handleBlurCallback}
onFocus={handleFocusCallback}
hasFocus={isMessageFocused}
onOpenQuickReply={handleOpenQuickReply}
/>
</div>
</Scroll>
);
};
export default MessageOnlyView;
| 3,585
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/MessagePrintFooter.tsx
|
import { c, msgid } from 'ttag';
import { FeatureCode, FileNameDisplay, useFeature } from '@proton/components';
import humanSize from '@proton/shared/lib/helpers/humanSize';
import { rtlSanitize } from '@proton/shared/lib/helpers/string';
import { Attachment } from '@proton/shared/lib/interfaces/mail/Message';
import { getAttachments } from '@proton/shared/lib/mail/messages';
import { getAttachmentCounts } from '../../helpers/message/messages';
import { MessageState } from '../../logic/messages/messagesTypes';
interface Props {
message: MessageState;
}
interface ItemProps {
attachment: Attachment;
}
const MessagePrintFooterItem = ({ attachment }: ItemProps) => {
const nameRaw = `${attachment ? attachment.Name : ''}`;
const name = rtlSanitize(nameRaw);
const humanAttachmentSize = humanSize(attachment?.Size);
return (
<div className="proton-print-footer-item flex flex-nowrap rounded">
<div className="flex flex-align-items-baseline flex-nowrap">
<FileNameDisplay text={name} />
<div className="proton-print-footer-item-size flex-item-noshrink">{humanAttachmentSize}</div>
</div>
</div>
);
};
const MessagePrintFooter = ({ message }: Props) => {
const isNumAttachmentsWithoutEmbedded = useFeature(FeatureCode.NumAttachmentsWithoutEmbedded).feature?.Value;
const attachments = getAttachments(message.data);
const { size, sizeLabel, pureAttachments, pureAttachmentsCount, embeddedAttachmentsCount } = getAttachmentCounts(
attachments,
message.messageImages
);
const attachmentsToShow = isNumAttachmentsWithoutEmbedded ? pureAttachments : attachments;
return (
<div className="proton-print">
<div className="proton-print-footer">
<div className="proton-print-footer-sizes flex flex-align-items-center outline-none">
{size !== 0 && <strong className="proton-print-footer-sizes-label">{sizeLabel}</strong>}
{pureAttachmentsCount > 0 && (
<span className="proton-print-footer-sizes-count">
<span>{pureAttachmentsCount}</span>
<span>
{c('Info').ngettext(msgid`file attached`, `files attached`, pureAttachmentsCount)}
</span>
</span>
)}
{embeddedAttachmentsCount > 0 && (
<span className="proton-print-footer-sizes-embedded-count">
<span>{embeddedAttachmentsCount}</span>
<span>
{c('Info').ngettext(msgid`embedded image`, `embedded images`, embeddedAttachmentsCount)}
</span>
</span>
)}
</div>
<div className="proton-print-footer-items flex gap-2">
{attachmentsToShow.map((attachment) => (
<MessagePrintFooterItem key={attachment.ID} attachment={attachment} />
))}
</div>
</div>
</div>
);
};
export default MessagePrintFooter;
| 3,586
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/MessagePrintHeader.tsx
|
import { c } from 'ttag';
import { Recipient } from '@proton/shared/lib/interfaces';
import { getSender } from '@proton/shared/lib/mail/messages';
import noop from '@proton/utils/noop';
import { useRecipientLabel } from '../../hooks/contact/useRecipientLabel';
import { MessageState } from '../../logic/messages/messagesTypes';
import ItemDate from '../list/ItemDate';
import RecipientType from './recipients/RecipientType';
import RecipientsDetails from './recipients/RecipientsDetails';
interface Props {
message: MessageState;
labelID: string;
}
const MessagePrintHeader = ({ message, labelID }: Props) => {
const { getRecipientLabel } = useRecipientLabel();
const sender = getSender(message.data);
return (
<div className="proton-print">
<div className="message-print-header">
<h2 className="message-print-subject">{message.data?.Subject}</h2>
<div className="message-print-recipient-container">
<RecipientType label={c('Label').t`From`}>
{getRecipientLabel(sender as Recipient, true)}{' '}
<span className="color-weak"><{sender?.Address}></span>
</RecipientType>
<RecipientsDetails
message={message}
isLoading={false}
showDropdown={false}
isPrintModal
onContactDetails={noop}
onContactEdit={noop}
/>
<RecipientType label={c('Label').t`Date`}>
<ItemDate element={message.data} labelID={labelID} mode="full" />
</RecipientType>
</div>
</div>
</div>
);
};
export default MessagePrintHeader;
| 3,587
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/MessageView.scss
|
article.message-container {
animation: none;
}
| 3,588
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/MessageView.tsx
|
import {
FocusEvent,
FocusEventHandler,
Ref,
RefObject,
forwardRef,
memo,
useEffect,
useImperativeHandle,
useMemo,
useRef,
useState,
} from 'react';
import { FeatureCode, useFeature, useKeyTransparencyContext } from '@proton/components';
import createScrollIntoView from '@proton/components/helpers/createScrollIntoView';
import { MailSettings } from '@proton/shared/lib/interfaces';
import { Label } from '@proton/shared/lib/interfaces/Label';
import { hasAttachments, isDraft, isOutbox, isScheduled, isSent } from '@proton/shared/lib/mail/messages';
import clsx from '@proton/utils/clsx';
import noop from '@proton/utils/noop';
import { LOAD_RETRY_COUNT } from '../../constants';
import { useOnCompose } from '../../containers/ComposeProvider';
import { isUnread } from '../../helpers/elements';
import { MessageViewIcons, getReceivedStatusIcon, getSentStatusIconInfo } from '../../helpers/message/icon';
import { MARK_AS_STATUS, useMarkAs } from '../../hooks/actions/useMarkAs';
import { ComposeTypes } from '../../hooks/composer/useCompose';
import { useQuickReplyFocus } from '../../hooks/composer/useQuickReplyFocus';
import { useInitializeMessage } from '../../hooks/message/useInitializeMessage';
import { useLoadEmbeddedImages, useLoadRemoteImages } from '../../hooks/message/useLoadImages';
import { useLoadMessage } from '../../hooks/message/useLoadMessage';
import { useMessage } from '../../hooks/message/useMessage';
import { useMessageHotkeys } from '../../hooks/message/useMessageHotkeys';
import { useResignContact } from '../../hooks/message/useResignContact';
import { useVerifyMessage } from '../../hooks/message/useVerifyMessage';
import { MessageWithOptionalBody } from '../../logic/messages/messagesTypes';
import { isElementReminded } from '../../logic/snoozehelpers';
import { Element } from '../../models/element';
import { Breakpoints } from '../../models/utils';
import QuickReplyContainer from '../composer/quickReply/QuickReplyContainer';
import MessageBody from './MessageBody';
import MessageFooter from './MessageFooter';
import HeaderCollapsed from './header/HeaderCollapsed';
import HeaderExpanded from './header/HeaderExpanded';
import './MessageView.scss';
interface Props {
labelID: string;
conversationMode: boolean;
loading: boolean;
labels: Label[];
message: MessageWithOptionalBody;
mailSettings: MailSettings;
conversationIndex?: number;
conversationID?: string;
onBack: () => void;
breakpoints: Breakpoints;
hasFocus?: boolean;
onFocus?: (messageId: number) => void;
onBlur?: (event: FocusEvent<HTMLElement>, messageRef: RefObject<HTMLElement>) => void;
onMessageReady?: () => void;
columnLayout?: boolean;
isComposerOpened: boolean;
containerRef?: React.RefObject<HTMLElement>;
wrapperRef?: React.RefObject<HTMLDivElement>;
onOpenQuickReply?: (index?: number) => void;
}
export interface MessageViewRef {
expand: () => void;
}
const OFFSET_PERCENTAGE = 0.05; // 5%
const MessageView = (
{
labelID,
conversationMode,
loading,
labels = [],
message: inputMessage,
mailSettings,
conversationIndex = 0,
conversationID,
onBack,
breakpoints,
hasFocus,
onFocus = noop,
onBlur = noop,
onMessageReady,
columnLayout = false,
isComposerOpened,
containerRef,
wrapperRef,
onOpenQuickReply,
}: Props,
ref: Ref<MessageViewRef>
) => {
const { feature: quickReplyFeature } = useFeature(FeatureCode.QuickReply);
const getInitialExpand = () => !conversationMode && !isDraft(inputMessage) && !isOutbox(inputMessage);
// Actual expanded state
const [expanded, setExpanded] = useState(getInitialExpand);
// Show or not the blockquote content
const [originalMessageMode, setOriginalMessageMode] = useState(false);
// HTML source should be shown instead of normal rendered content
const [sourceMode, setSourceMode] = useState(false);
const elementRef = useRef<HTMLElement>(null);
const { ktActivation } = useKeyTransparencyContext();
const { message, messageLoaded, bodyLoaded } = useMessage(inputMessage.ID, conversationID);
const load = useLoadMessage(inputMessage);
const initialize = useInitializeMessage();
const verify = useVerifyMessage(message.localID);
const loadRemoteImages = useLoadRemoteImages(message.localID);
const loadEmbeddedImages = useLoadEmbeddedImages(message.localID);
const resignContact = useResignContact(message.localID);
const markAs = useMarkAs();
const onCompose = useOnCompose();
const draft = !loading && isDraft(message.data);
const outbox = !loading && (isOutbox(message.data) || message.draftFlags?.sending);
const sent = isSent(message.data);
const unread = isUnread(message.data, labelID);
// It can be attachments but not yet loaded
const showFooter = hasAttachments(message.data) && Array.isArray(message.data?.Attachments);
const messageViewIcons = useMemo<MessageViewIcons>(() => {
if (sent) {
return getSentStatusIconInfo(message);
}
// else it's a received message
return {
globalIcon: getReceivedStatusIcon(message.data, message.verification, ktActivation),
mapStatusIcon: {},
};
}, [message, ktActivation]);
const handleLoadRemoteImages = async () => {
await loadRemoteImages();
};
const handleResignContact = async () => {
await resignContact();
};
const handleLoadEmbeddedImages = async () => {
await loadEmbeddedImages();
};
const handleToggle = (value: boolean) => () => {
if (draft && !outbox) {
onCompose({ type: ComposeTypes.existingDraft, existingDraft: message, fromUndo: false });
return;
}
// Do not allow message expand during sending. Because if the user expands it during this step,
// he will have a flash due to messageDocument computation after receiving API response
if (!message.draftFlags?.sending) {
setExpanded(value);
}
};
const toggleOriginalMessage = () => setOriginalMessageMode(!originalMessageMode);
const setParentBottomPadding = (value: number) => {
if (!elementRef.current) {
return;
}
const parent = elementRef.current.parentNode as HTMLElement;
parent.classList.add('pb-custom');
parent.style.setProperty('--padding-bottom-custom', `${value}px`);
};
const resetParentBottomPadding = () => {
setParentBottomPadding(0);
};
const scrollToMessage = () => {
if (!elementRef.current || !containerRef?.current || !wrapperRef?.current) {
return;
}
resetParentBottomPadding();
const { offsetHeight: containerHeight } = containerRef.current;
const offset = containerHeight * OFFSET_PERCENTAGE;
// If the message is already in the offset area of the container,
// Or is in message only view
// Or is focusing the first item of a conversation
// Then abort the scroll
if (
elementRef.current.offsetTop - offset < containerRef.current.scrollTop ||
!conversationMode ||
(conversationMode && conversationIndex === 0)
) {
return;
}
createScrollIntoView(elementRef.current, containerRef.current, false, offset);
};
// Setup ref to allow opening the message from outside, typically the ConversationView
useImperativeHandle(ref, () => ({
expand: () => {
// Should be prevented before, but as an extra security...
if (!isDraft(message.data)) {
setExpanded(true);
}
},
}));
const { hasFocus: hasQuickReplyFocus, setHasFocus: setHasQuickReplyFocus } = useQuickReplyFocus();
// 1- If on conversation mode
// If we click inside another message body (which is an iframe), we will change the hasFocus in that case, the conversation is not focused.
// Else, if focused conversation is the one of the quick reply, the focused is managed by hasQuickReplyFocus
// 2- If on message mode, we only rely on the hasQuickReplyFocus
const quickReplyIsFocused = hasFocus !== undefined ? hasQuickReplyFocus && hasFocus : hasQuickReplyFocus;
const canShowQuickReply =
quickReplyFeature?.Value &&
!isDraft(message.data) &&
!isScheduled(message.data) &&
!isOutbox(message.data) &&
!isUnread(message.data, labelID);
// Manage loading the message
useEffect(() => {
if (!loading && !messageLoaded) {
void load();
}
if (!isComposerOpened && isDraft(message.data) && messageLoaded) {
// unblock J/K shortcuts
if (onMessageReady) {
setTimeout(onMessageReady);
}
if (!columnLayout) {
elementRef.current?.parentElement?.focus();
}
}
}, [loading, messageLoaded, bodyLoaded, message.data?.ID]);
// Manage preparing the content of the message
useEffect(() => {
if (!loading && expanded && message.messageDocument?.initialized === undefined) {
if ((message.loadRetry || 0) > LOAD_RETRY_COUNT) {
// Max retries reach, aborting
return;
}
void initialize(message.localID, labelID);
}
}, [loading, expanded, message.messageDocument?.initialized, message.localID, labelID]);
// Manage recomputing signature verification (happens when invalidated after initial load)
useEffect(() => {
if (
!loading &&
expanded &&
message.messageDocument?.initialized &&
message.data &&
message.verification === undefined
) {
void verify(message.decryption?.decryptedRawContent, message.decryption?.signature);
}
}, [loading, expanded, message.messageDocument?.initialized, message.verification]);
useEffect(() => {
if (expanded) {
scrollToMessage();
}
}, [expanded]);
/**
* Two cases here,
* If the message is unread: mark as read a message already loaded (when user marked as unread)
* If the message is read: mark message or conversation as read again if DisplaySnoozedReminder present (snooze feature)
*/
useEffect(() => {
const element = message.data as Element;
if (expanded && unread && bodyLoaded) {
markAs([element], labelID, MARK_AS_STATUS.READ);
}
// Mark the message as read again when DisplaySnoozedReminder is true (snooze feature)
const isReminded = isElementReminded(element);
if (!unread && isReminded && !conversationMode) {
markAs([element], labelID, MARK_AS_STATUS.READ);
}
}, [expanded, unread, bodyLoaded]);
// Re-initialize context if message is changed without disposing the component
useEffect(() => {
if (message.data?.ID) {
setExpanded(getInitialExpand);
setSourceMode(false);
setOriginalMessageMode(false);
}
}, [message.data?.ID]);
/**
* When message pass from sending to draft (for ex when undo send)
* we need to go back to non expanded state
*/
useEffect(() => {
if (draft === true) {
setExpanded(false);
}
}, [draft]);
// Automatically activate source mode when processing errors
const hasProcessingErrors = !!message.errors?.processing?.length;
useEffect(() => {
if (hasProcessingErrors) {
setSourceMode(true);
}
}, [hasProcessingErrors]);
const {
labelDropdownToggleRef,
moveDropdownToggleRef,
filterDropdownToggleRef,
moveScheduledModal,
moveSnoozedModal,
moveAllModal,
moveToSpamModal,
} = useMessageHotkeys(
elementRef,
{
labelID,
conversationIndex,
message,
bodyLoaded,
expanded,
messageLoaded,
draft,
conversationMode,
mailSettings,
messageRef: elementRef,
},
{
hasFocus: !!hasFocus,
setExpanded,
toggleOriginalMessage,
handleLoadRemoteImages,
handleLoadEmbeddedImages,
onBack,
}
);
function handleFocus(context: 'IFRAME'): () => void;
function handleFocus(context: 'BUBBLED_EVENT'): (event: FocusEvent) => void;
function handleFocus(context: 'IFRAME' | 'BUBBLED_EVENT') {
if (context === 'IFRAME') {
return () => {
onFocus(conversationIndex);
setHasQuickReplyFocus(false);
};
}
if (context === 'BUBBLED_EVENT') {
return (event: FocusEvent) => {
// We ensure that the clicked element is in the message view
// The event can be returned by a bubbled event from a modal
if (elementRef.current?.contains(event.target)) {
onFocus(conversationIndex);
}
};
}
}
const handleBlur: FocusEventHandler<HTMLElement> = (event) => {
onBlur(event, elementRef);
};
return (
<article
ref={elementRef}
className={clsx([
'message-container mx-2 my-4 relative',
expanded && 'is-opened',
showFooter && 'has-attachments',
unread && 'is-unread',
])}
style={{ '--index': conversationIndex * 2 }}
data-testid={`message-view-${conversationIndex}`}
tabIndex={0}
data-message-id={message.data?.ID}
data-shortcut-target="message-container"
onFocus={handleFocus('BUBBLED_EVENT')}
onBlur={handleBlur}
data-hasfocus={hasFocus}
data-expanded={expanded}
>
{expanded ? (
<>
<HeaderExpanded
labelID={labelID}
message={message}
messageViewIcons={messageViewIcons}
messageLoaded={messageLoaded}
bodyLoaded={bodyLoaded}
isSentMessage={sent}
sourceMode={sourceMode}
onLoadRemoteImages={handleLoadRemoteImages}
onLoadEmbeddedImages={handleLoadEmbeddedImages}
onResignContact={handleResignContact}
labels={labels}
mailSettings={mailSettings}
onToggle={handleToggle(false)}
onBack={onBack}
onSourceMode={setSourceMode}
breakpoints={breakpoints}
labelDropdownToggleRef={labelDropdownToggleRef}
moveDropdownToggleRef={moveDropdownToggleRef}
filterDropdownToggleRef={filterDropdownToggleRef}
parentMessageRef={elementRef}
conversationIndex={conversationIndex}
/>
<MessageBody
labelID={labelID}
messageLoaded={messageLoaded}
bodyLoaded={bodyLoaded}
sourceMode={sourceMode}
message={message}
originalMessageMode={originalMessageMode}
toggleOriginalMessage={toggleOriginalMessage}
onMessageReady={onMessageReady}
onFocusIframe={handleFocus('IFRAME')}
hasQuickReply={canShowQuickReply}
/>
{showFooter ? <MessageFooter message={message} /> : null}
{canShowQuickReply && (
<QuickReplyContainer
referenceMessageID={message.data?.ID || ''}
conversationID={conversationID}
conversationIndex={conversationIndex}
onOpenQuickReply={onOpenQuickReply}
onFocus={handleFocus('IFRAME')}
hasFocus={quickReplyIsFocused}
setHasFocus={setHasQuickReplyFocus}
/>
)}
</>
) : (
<HeaderCollapsed
labelID={labelID}
labels={labels}
message={message}
messageLoaded={messageLoaded}
isSentMessage={sent}
isUnreadMessage={unread}
onExpand={handleToggle(true)}
breakpoints={breakpoints}
conversationIndex={conversationIndex}
/>
)}
{moveScheduledModal}
{moveSnoozedModal}
{moveAllModal}
{moveToSpamModal}
</article>
);
};
export default memo(forwardRef(MessageView));
| 3,589
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/constants.ts
|
export const MESSAGE_IFRAME_ROOT_ID = 'proton-root';
export const MESSAGE_IFRAME_BLOCKQUOTE_ID = 'proton-blockquote';
export const MESSAGE_IFRAME_TOGGLE_ID = 'proton-toggle';
export const MESSAGE_IFRAME_PRINT_CLASS = 'proton-print';
export const MESSAGE_IFRAME_PRINT_HEADER_ID = 'proton-print-header';
export const MESSAGE_IFRAME_PRINT_FOOTER_ID = 'proton-print-footer';
| 3,590
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/ExtraAskResign.test.tsx
|
import { fireEvent } from '@testing-library/react';
import { PublicKeyReference } from '@proton/crypto';
import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../helpers/test/crypto';
import { addApiMock, clearAll, generateKeys, render, tick } from '../../../helpers/test/helper';
import { contactEmails, message, setupContactsForPinKeys } from '../../../helpers/test/pinKeys';
import { refresh } from '../../../logic/contacts/contactsActions';
import { MessageVerification } from '../../../logic/messages/messagesTypes';
import { store } from '../../../logic/store';
import ExtraAskResign from './ExtraAskResign';
const getMessageVerification = (pinnedKeysVerified: boolean, pinnedKeys?: PublicKeyReference[]) => {
return {
pinnedKeysVerified,
senderPinnedKeys: pinnedKeys,
} as MessageVerification;
};
const setup = async (messageVerification: MessageVerification) => {
const onResignContact = jest.fn();
const component = await render(
<ExtraAskResign message={message} messageVerification={messageVerification} onResignContact={onResignContact} />
);
return component;
};
describe('Extra ask resign banner', () => {
beforeAll(async () => {
await setupCryptoProxyForTesting();
});
afterAll(async () => {
await releaseCryptoProxy();
});
beforeEach(clearAll);
it('should not display the extra ask resign banner when sender is verified and keys are pinned', async () => {
const senderKey = await generateKeys('sender', message.Sender.Address);
const messageVerification = getMessageVerification(true, [senderKey.publicKeys[0]]);
const { queryByTestId } = await setup(messageVerification);
const banner = queryByTestId('extra-ask-resign:banner');
expect(banner).toBeNull();
});
it('should not display the extra ask resign banner when sender is verified and no keys are pinned', async () => {
const messageVerification = getMessageVerification(true);
const { queryByTestId } = await setup(messageVerification);
const banner = queryByTestId('extra-ask-resign:banner');
expect(banner).toBeNull();
});
it('should not display the extra ask resign banner when sender is not verified and no keys are pinned', async () => {
const messageVerification = getMessageVerification(false);
const { queryByTestId } = await setup(messageVerification);
const banner = queryByTestId('extra-ask-resign:banner');
expect(banner).toBeNull();
});
it('should display the extra ask resign banner when sender is not verified and keys are pinned', async () => {
const { senderKeys } = await setupContactsForPinKeys();
addApiMock('core/v4/keys/all', () => ({ Address: { Keys: [{ PublicKey: senderKeys.publicKeyArmored }] } }));
// Initialize contactsMap
store.dispatch(refresh({ contacts: [...contactEmails], contactGroups: [] }));
const messageVerification = getMessageVerification(false, [senderKeys.publicKeys[0]]);
const { getByTestId, getByText } = await setup(messageVerification);
// Banner is displayed
getByTestId('extra-ask-resign:banner');
// Modal is opened
const trustKeyButton = getByText('Verify');
fireEvent.click(trustKeyButton);
await tick();
getByText('Trust pinned keys?');
});
});
| 3,591
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/ExtraAskResign.tsx
|
import { useMemo, useState } from 'react';
import { c } from 'ttag';
import { Button, Href } from '@proton/atoms';
import { Icon, useModalState } from '@proton/components';
import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url';
import { getContactEmail } from '../../../helpers/message/messageRecipients';
import { useContactsMap } from '../../../hooks/contact/useContacts';
import { MessageVerification, MessageWithOptionalBody } from '../../../logic/messages/messagesTypes';
import ContactResignModal from '../modals/ContactResignModal';
interface Props {
message: MessageWithOptionalBody;
messageVerification: MessageVerification | undefined;
onResignContact: () => void;
}
const ExtraAskResign = ({ message, messageVerification, onResignContact }: Props) => {
const { pinnedKeysVerified, senderPinnedKeys } = messageVerification || {};
const { Address = '' } = message.Sender || {};
const contactsMap = useContactsMap();
const [contactID, setContactID] = useState<string>('');
const [contactResignModalProps, setContactResignModalOpen, render] = useModalState();
const contactEmail = useMemo(() => getContactEmail(contactsMap, Address), [contactsMap, Address]);
const senderName = message?.Sender?.Name || message?.Sender?.Address; // No optional in translations
if (pinnedKeysVerified || !senderPinnedKeys?.length) {
return null;
}
const handleClick = () => {
if (!contactEmail) {
return;
}
setContactID(contactEmail.ContactID);
setContactResignModalOpen(true);
};
return (
<div
className="bg-norm rounded border pr-2 md:pr-1 pb-2 md:pb-1 pt-1 pl-2 mb-3 flex flex-nowrap on-mobile-flex-column"
data-testid="extra-ask-resign:banner"
>
<div className="flex-item-fluid flex flex-nowrap mb-2 md:mb-0">
<Icon name="exclamation-circle-filled" className="flex-item-noshrink ml-0.5 mt-1 color-danger" />
<span className="px-2 mt-0 flex-item-fluid flex-align-self-center">
<span className="mr-1">{c('Info').t`We could not verify the sender's trusted keys.`}</span>
<Href className="mr-4 inline-block" href={getKnowledgeBaseUrl('/address-verification')}>
{c('Info').t`Learn more`}
</Href>
</span>
</div>
<span className="flex-item-noshrink flex-align-items-start flex w-full md:w-auto">
<Button
size="small"
color="weak"
shape="outline"
fullWidth
className="rounded-sm"
onClick={handleClick}
data-testid="ask-resign-banner:verify-button"
>{c('Action').t`Verify`}</Button>
</span>
{render && (
<ContactResignModal
title={c('Title').t`Trust pinned keys?`}
submit={c('Action').t`Trust`}
onResign={onResignContact}
contacts={[{ contactID }]}
{...contactResignModalProps}
>
{c('Info')
.t`When you enabled trusted keys for ${senderName}, the public keys were added to the contact details.`}
<br />
{c('Info')
.t`There has been an error with the signature used to verify the contact details, which may be the result of a password reset.`}
</ContactResignModal>
)}
</div>
);
};
export default ExtraAskResign;
| 3,592
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/ExtraAutoReply.tsx
|
import { c } from 'ttag';
import { Href } from '@proton/atoms';
import { Icon } from '@proton/components';
import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url';
import { isAutoReply } from '@proton/shared/lib/mail/messages';
import { MessageWithOptionalBody } from '../../../logic/messages/messagesTypes';
interface Props {
message: MessageWithOptionalBody;
}
const ExtraAutoReply = ({ message }: Props) => {
if (!isAutoReply(message)) {
return null;
}
return (
<div
className="bg-norm rounded border pr-2 md:pr-1 pb-2 md:pb-1 pt-1 pl-2 mb-3 flex flex-nowrap"
data-testid="auto-reply-banner"
>
<Icon name="robot" className="flex-item-noshrink ml-1 mt-1" />
<span className="px-2 mt-1 pb-1 flex-item-fluid">
{c('Info').t`This message is automatically generated as a response to a previous message.`}{' '}
<Href href={getKnowledgeBaseUrl('/auto-reply')}>{c('Info').t`Learn more`}</Href>
</span>
</div>
);
};
export default ExtraAutoReply;
| 3,593
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/ExtraBlockedSender.tsx
|
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { Icon, useNotifications } from '@proton/components';
import { getBlockedIncomingDefaultByAddress } from '@proton/shared/lib/helpers/incomingDefaults';
import { getSender } from '@proton/shared/lib/mail/messages';
import {
useIncomingDefaultsAddresses,
useIncomingDefaultsStatus,
} from '../../../hooks/incomingDefaults/useIncomingDefaults';
import { remove } from '../../../logic/incomingDefaults/incomingDefaultsActions';
import { MessageState } from '../../../logic/messages/messagesTypes';
import { useAppDispatch } from '../../../logic/store';
interface Props {
message: MessageState;
}
const ExtraBlockedSender = ({ message }: Props) => {
const dispatch = useAppDispatch();
const { createNotification } = useNotifications();
const senderAddress = getSender(message.data)?.Address;
const incomingDefaultsAddresses = useIncomingDefaultsAddresses();
const incomingDefaultsStatus = useIncomingDefaultsStatus();
const blockedIncomingDefault = getBlockedIncomingDefaultByAddress(incomingDefaultsAddresses, senderAddress || '');
const handleUnblock = async () => {
// Need to handle blocked by domain case
if (!blockedIncomingDefault || !blockedIncomingDefault.Email) {
return;
}
await dispatch(remove({ ID: blockedIncomingDefault.ID }));
createNotification({
text: c('Notification').t`Block removed`,
type: 'success',
});
};
return incomingDefaultsStatus === 'loaded' && blockedIncomingDefault ? (
<div className="bg-norm rounded border pr-2 md:pr-1 pb-2 md:pb-1 pt-1 pl-2 mb-3 flex flex-nowrap on-mobile-flex-column">
<div className="flex-item-fluid flex flex-nowrap mb-2 md:mb-0">
<Icon name="exclamation-circle-filled" className="mt-1 ml-0.5 flex-item-noshrink" />
<span className="px-2 flex flex-item-fluid flex-align-items-center">
{c('Info').t`Sender has been blocked.`}
</span>
</div>
<span className="flex-item-noshrink flex-align-items-start flex w-full md:w-auto pt-0.5">
<Button
className="rounded-sm"
color="weak"
data-testid="block-sender:unblock"
onClick={handleUnblock}
shape="outline"
size="small"
>
{c('Action').t`Unblock`}
</Button>
</span>
</div>
) : null;
};
export default ExtraBlockedSender;
| 3,594
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/ExtraDarkStyle.tsx
|
import { useEffect } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { Icon, Tooltip, useApi } from '@proton/components';
import { METRICS_LOG } from '@proton/shared/lib/constants';
import { sendMetricsReport } from '@proton/shared/lib/helpers/metrics';
import { MessageStateWithData } from '../../../logic/messages/messagesTypes';
import { removeDarkStyle } from '../../../logic/messages/read/messagesReadActions';
import { useAppDispatch } from '../../../logic/store';
interface Props {
message: MessageStateWithData;
}
const ExtraDarkStyle = ({ message }: Props) => {
const dispatch = useAppDispatch();
const api = useApi();
const showBanner = message.messageDocument?.hasDarkStyle && !message.messageDocument?.noDarkStyle;
useEffect(() => {
if (showBanner) {
void sendMetricsReport(api, METRICS_LOG.DARK_STYLES, 'update_dark_styles', { action: 'apply_dark_styles' });
}
}, [showBanner]);
if (!showBanner) {
return null;
}
const handleClick = () => {
dispatch(removeDarkStyle({ ID: message.localID, noDarkStyle: true }));
void sendMetricsReport(api, METRICS_LOG.DARK_STYLES, 'update_dark_styles', { action: 'remove_dark_styles' });
};
return (
<Tooltip title={c('Info').t`This message has been adjusted to comply with a dark background.`}>
<Button
onClick={handleClick}
data-testid="message-view:remove-dark-style"
className="inline-flex flex-align-items-center w-full md:w-auto on-mobile-flex-justify-center mr-0 md:mr-2 mb-3 px-2"
>
<Icon name="circle-half-filled" className="flex-item-noshrink ml-1" />
<span className="ml-2">{c('Action').t`Revert to original display`}</span>
</Button>
</Tooltip>
);
};
export default ExtraDarkStyle;
| 3,595
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/ExtraDecryptedSubject.tsx
|
import { useMemo } from 'react';
import { c } from 'ttag';
import { Icon, Tooltip } from '@proton/components';
import { useEncryptedSearchContext } from '../../../containers/EncryptedSearchProvider';
import { MessageStateWithData } from '../../../logic/messages/messagesTypes';
interface Props {
message: MessageStateWithData;
}
const ExtraDecryptedSubject = ({ message }: Props) => {
const { highlightMetadata, shouldHighlight } = useEncryptedSearchContext();
const highlightSubject = shouldHighlight();
const subjectElement = useMemo(() => {
if (!!message.decryption?.decryptedSubject) {
const { decryptedSubject } = message.decryption;
if (highlightSubject) {
return highlightMetadata(decryptedSubject, true).resultJSX;
}
return <span>{decryptedSubject}</span>;
}
}, [message.decryption?.decryptedSubject, highlightSubject]);
if (message.data.Subject !== '...' || !subjectElement) {
return null;
}
return (
<div className="bg-norm rounded border px-2 py-1 mb-3 flex flex-nowrap" data-testid="encrypted-subject-banner">
<div className="flex">
<Tooltip title={c('Info').t`Subject is end-to-end encrypted`}>
<Icon
name="lock"
className="mt-1 mr-2 ml-1 flex-item-noshrink"
alt={c('Info').t`Subject is end-to-end encrypted`}
/>
</Tooltip>
<div className="mr-2 mt-1 flex-item-fluid pb-1">
{c('Info').t`Subject:`} {subjectElement}
</div>
</div>
</div>
);
};
export default ExtraDecryptedSubject;
| 3,596
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/ExtraErrors.test.tsx
|
import { render } from '../../../helpers/test/helper';
import { MessageErrors, MessageState } from '../../../logic/messages/messagesTypes';
import ExtraErrors from './ExtraErrors';
describe('Errors banner', () => {
const setup = async (errors: MessageErrors) => {
const message = { localID: 'localID', errors } as MessageState;
const { getByTestId } = await render(<ExtraErrors message={message} />);
return getByTestId('errors-banner');
};
it('should show error banner for network error', async () => {
const banner = await setup({ network: [new Error('test')] });
expect(banner.textContent).toMatch(/Network error/);
});
it('should show error banner for decryption error', async () => {
const banner = await setup({ decryption: [new Error('test')] });
expect(banner.textContent).toMatch(/Decryption error/);
});
it('should show error banner for processing error', async () => {
const banner = await setup({ processing: [new Error('test')] });
expect(banner.textContent).toMatch(/processing error/);
});
it('should show error banner for signature error', async () => {
const banner = await setup({ signature: [new Error('test')] });
expect(banner.textContent).toMatch(/Signature verification error/);
});
});
| 3,597
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/ExtraErrors.tsx
|
import { useState } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { Icon, SettingsLink } from '@proton/components';
import { APPS, BRAND_NAME } from '@proton/shared/lib/constants';
import { useReloadMessage } from '../../../hooks/message/useLoadMessage';
import { MessageErrors, MessageState } from '../../../logic/messages/messagesTypes';
const getTranslations = (key: keyof MessageErrors, alreadyTried: boolean) => {
switch (key) {
case 'network':
return c('Error').t`Network error: Please check your connection and try again.`;
case 'decryption':
return alreadyTried
? c('Error')
.t`Sorry, ${BRAND_NAME} can't decrypt your message. Please check that all your keys are active.`
: c('Error').t`Decryption error: decryption of this message's encrypted content failed.`;
case 'processing':
return c('Error').t`Message processing error.`;
case 'signature':
return c('Error').t`Signature verification error.`;
default:
return c('Error').t`Unknown error.`;
}
};
interface Props {
message: MessageState;
}
const ExtraErrors = ({ message }: Props) => {
const reloadMessage = useReloadMessage(message.localID);
const [alreadyTried, setAlreadyTried] = useState(false);
const errorTypes = (Object.keys(message.errors || {}) as (keyof MessageErrors)[]).filter(
(type) => message.errors?.[type]?.length
);
if (errorTypes.length === 0) {
return null;
}
const handleReload = () => {
void reloadMessage();
setAlreadyTried(true);
};
// Using a Fragment here, is only to satisfy TS :(
return (
<>
{errorTypes.map((errorType) => {
const showReload = errorType === 'network' || (errorType === 'decryption' && !alreadyTried);
const showKeysLink = errorType === 'decryption' && alreadyTried;
return (
<div
key={errorType}
className="bg-norm border rounded pr-2 md:pr-1 pb-2 md:pb-1 pt-1 pl-2 mb-3 flex flex-nowrap on-mobile-flex-column"
data-testid="errors-banner"
>
<div className="flex-item-fluid flex flex-nowrap mb-2 md:mb-0">
<Icon
name="exclamation-circle-filled"
className="flex-item-noshrink mt-1 ml-0.5 color-danger"
/>
<span className="px-2 mt-1 flex-item-fluid" data-testid="errors-banner:content">
{getTranslations(errorType, alreadyTried)}
</span>
</div>
{showReload && (
<span className="flex-item-noshrink flex-align-items-start flex w-full md:w-auto">
<Button
size="small"
color="weak"
shape="outline"
fullWidth
className="rounded-sm"
onClick={handleReload}
data-testid="errors-banner:reload"
>{c('Action').t`Try again`}</Button>
</span>
)}
{showKeysLink && (
<span className="flex-item-noshrink flex-align-items-start flex w-full md:w-auto">
<SettingsLink
path="/encryption-keys"
app={APPS.PROTONMAIL}
className="text-underline color-inherit w-full md:w-auto"
>
{c('Action').t`View keys`}
</SettingsLink>
</span>
)}
</div>
);
})}
</>
);
};
export default ExtraErrors;
| 3,598
|
0
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
|
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/ExtraEvents.test.tsx
|
import { screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { useCalendarUserSettings } from '@proton/components/hooks/useCalendarUserSettings';
import { useGetVtimezonesMap } from '@proton/components/hooks/useGetVtimezonesMap';
import { getAppName } from '@proton/shared/lib/apps/helper';
import { generateAttendeeToken } from '@proton/shared/lib/calendar/attendees';
import {
CALENDAR_DISPLAY,
CALENDAR_FLAGS,
CALENDAR_TYPE,
ICAL_ATTENDEE_RSVP,
ICAL_ATTENDEE_STATUS,
ICAL_METHOD,
SETTINGS_VIEW,
} from '@proton/shared/lib/calendar/constants';
import { MEMBER_PERMISSIONS } from '@proton/shared/lib/calendar/permissions';
import { ACCENT_COLORS } from '@proton/shared/lib/colors';
import { ADDRESS_STATUS, API_CODES, APPS, BRAND_NAME } from '@proton/shared/lib/constants';
import { canonicalizeInternalEmail } from '@proton/shared/lib/helpers/email';
import { uint8ArrayToBase64String } from '@proton/shared/lib/helpers/encoding';
import { SETTINGS_WEEK_START } from '@proton/shared/lib/interfaces';
import {
CalendarKeyFlags,
CalendarUserSettings,
CalendarWithOwnMembers,
VcalVeventComponent,
} from '@proton/shared/lib/interfaces/calendar';
import { encryptAttachment } from '@proton/shared/lib/mail/send/attachments';
import isTruthy from '@proton/utils/isTruthy';
import mergeUint8Arrays from '@proton/utils/mergeUint8Arrays';
import * as inviteApi from '../../../helpers/calendar/inviteApi';
import { generateApiCalendarEvent } from '../../../helpers/test/calendar';
import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../helpers/test/crypto';
import {
GeneratedKey,
addAddressToCache,
addApiMock,
addKeysToAddressKeysCache,
clearAll,
generateKeys as generateAddressKeys,
generateCalendarKeysAndPassphrase,
minimalCache,
render,
} from '../../../helpers/test/helper';
import { MessageStateWithData } from '../../../logic/messages/messagesTypes';
import ExtraEvents from './ExtraEvents';
jest.setTimeout(20000);
jest.mock('@proton/components/hooks/useSendIcs', () => {
return {
__esModule: true,
default: jest.fn(() => () => Promise.resolve(undefined)),
};
});
jest.mock('@proton/components/hooks/useCalendarUserSettings', () => ({
...jest.requireActual('@proton/components/hooks/useCalendarUserSettings'),
useCalendarUserSettings: jest.fn(),
}));
jest.mock('@proton/components/hooks/useGetVtimezonesMap');
const nextYear = new Date().getFullYear() + 1;
const dummyUserName = 'test';
const dummyUserEmailAddress = 'test@pm.me';
const dummySenderEmailAddress = 'sender@protonmail.com';
const dummySenderExternalEmailAddress = 'sender@gmail.com';
const dummyRecipientExternalEmailAddress = 'recipient@gmail.com';
const dummyUserPrimaryAddressID = 'default-address-id';
const dummyCalendarID = 'default-calendar-id';
const dummyCalendarName = 'My calendar';
const dummyCalendarUserSettings = {
WeekLength: 7,
WeekStart: SETTINGS_WEEK_START.MONDAY,
DisplayWeekNumber: 1,
DefaultCalendarID: dummyCalendarID,
AutoDetectPrimaryTimezone: 1,
PrimaryTimezone: 'America/New_York',
DisplaySecondaryTimezone: 0,
SecondaryTimezone: null,
ViewPreference: SETTINGS_VIEW.WEEK,
InviteLocale: null,
AutoImportInvite: 0,
};
const dummyMemberID = 'member-id';
const dummyCalendar = {
ID: dummyCalendarID,
Name: dummyCalendarName,
Description: '',
Type: CALENDAR_TYPE.PERSONAL,
Owner: { Email: dummyUserEmailAddress },
Members: [
{
ID: dummyMemberID,
AddressID: dummyUserPrimaryAddressID,
Flags: CALENDAR_FLAGS.ACTIVE,
Permissions: MEMBER_PERMISSIONS.OWNS,
Email: dummyUserEmailAddress,
CalendarID: dummyCalendarID,
Color: ACCENT_COLORS[1],
Display: CALENDAR_DISPLAY.HIDDEN,
Name: dummyCalendarName,
Description: '',
Priority: 1,
},
],
};
const dummyAttachmentID = 'attachment-id';
const dummyCalendarKeyID = 'calendar-key-id';
const dummyEventID = 'event-id';
const dummySharedEventID = 'shared-event-id';
const dummyPassphraseID = 'passphrase-id';
const dummyFileName = 'invite.ics';
const generateCalendars = (numberOfCalendars: number, disableCalendars = false) => {
const calendars: CalendarWithOwnMembers[] = [];
for (let i = 0; i < numberOfCalendars; i++) {
const calendar = {
ID: `${dummyCalendarID}-${i}`,
Name: `${dummyCalendarName}-${i}`,
Description: '',
Type: CALENDAR_TYPE.PERSONAL,
Owner: { Email: dummyUserEmailAddress },
Members: [
{
ID: dummyMemberID,
AddressID: dummyUserPrimaryAddressID,
Flags: disableCalendars ? CALENDAR_FLAGS.SELF_DISABLED : CALENDAR_FLAGS.ACTIVE,
Permissions: MEMBER_PERMISSIONS.OWNS,
Email: dummyUserEmailAddress,
CalendarID: `${dummyCalendarID}-${i}`,
Color: ACCENT_COLORS[1],
Display: CALENDAR_DISPLAY.HIDDEN,
Name: dummyCalendarName,
Description: '',
Priority: 1,
},
],
};
calendars.push(calendar);
}
return calendars;
};
let dummyAddressKey: GeneratedKey;
let dummyCalendarKeysAndPassphrasePromise: ReturnType<typeof generateCalendarKeysAndPassphrase>;
const getSetup = async ({
userEmailAddress = dummyUserEmailAddress,
senderEmailAddress = dummySenderEmailAddress,
attachments,
methodInMimeType,
emailSubject = 'A new invitation',
userAddressKey,
userPrimaryAddressID = dummyUserPrimaryAddressID,
userCalendars = [dummyCalendar],
userCalendarSettings = dummyCalendarUserSettings,
defaultCalendarID = dummyCalendarID,
eventCalendarID,
eventID = dummyEventID,
sharedEventID = dummySharedEventID,
veventsApi = [],
memberID = dummyMemberID,
alternativeCalendarKeysAndPassphrasePromise,
alternativeAddressKeyPromise,
userAddressEnabled = true,
isSimpleLogin = false,
}: {
userEmailAddress?: string;
senderEmailAddress?: string;
attachments: { filename: string; ics: string; attachmentID: string }[];
methodInMimeType?: ICAL_METHOD;
emailSubject?: string;
userAddressKey?: GeneratedKey;
userPrimaryAddressID?: string;
userCalendars?: CalendarWithOwnMembers[];
userCalendarSettings?: CalendarUserSettings;
defaultCalendarID?: string | null;
eventCalendarID?: string;
eventID?: string;
sharedEventID?: string;
veventsApi?: VcalVeventComponent[];
memberID?: string;
alternativeCalendarKeysAndPassphrasePromise?: ReturnType<typeof generateCalendarKeysAndPassphrase>;
alternativeAddressKeyPromise?: ReturnType<typeof generateAddressKeys>;
userAddressEnabled?: boolean;
isSimpleLogin?: boolean;
}) => {
const addressKey = userAddressKey || dummyAddressKey;
const alternativeAddressKey = await alternativeAddressKeyPromise;
const { calendarKey, passphrase } = await dummyCalendarKeysAndPassphrasePromise;
const { calendarKey: alternativeCalendarKey } = (await alternativeCalendarKeysAndPassphrasePromise) || {};
const encryptedAttachments = await Promise.all(
attachments.map(async ({ attachmentID, filename, ics }) => {
let mimeType = 'text/calendar';
if (methodInMimeType) {
mimeType += `; method=${methodInMimeType}`;
}
const inviteAttachment = new File([new Blob([ics])], filename, { type: mimeType });
const attachmentPackets = await encryptAttachment(ics, inviteAttachment, false, addressKey.publicKeys, []);
const concatenatedPackets = mergeUint8Arrays(
[attachmentPackets.data, attachmentPackets.keys, attachmentPackets.signature].filter(isTruthy)
);
// Mock API calls to get attachment
addApiMock(`mail/v4/attachments/${attachmentID}`, () => concatenatedPackets);
return {
attachmentID,
filename,
ics,
attachmentPackets,
};
})
);
// Mock calendar API calls
addApiMock('calendar/v1', () => ({
Calendars: userCalendars,
}));
addApiMock('settings/calendar', () => ({
CalendarUserSettings: userCalendarSettings,
}));
const bootstrapCalendarID = eventCalendarID || defaultCalendarID;
if (bootstrapCalendarID) {
addApiMock(`calendar/v1/${bootstrapCalendarID}/events/${eventID}/upgrade`, () => ({
Calendars: userCalendars,
}));
addApiMock(`calendar/v1/${bootstrapCalendarID}/bootstrap`, () => ({
Keys: [
{
ID: dummyCalendarKeyID,
CalendarID: defaultCalendarID,
PrivateKey: calendarKey.privateKeyArmored,
PassphraseID: dummyPassphraseID,
Flags: CalendarKeyFlags.PRIMARY + CalendarKeyFlags.ACTIVE,
},
],
Passphrase: {
ID: dummyPassphraseID,
Flags: 1,
MemberPassphrases: [
{
MemberID: memberID,
Passphrase: passphrase.armored,
Signature: passphrase.signature,
},
],
Invitations: [],
},
Members: [
{
ID: memberID,
Email: userEmailAddress,
Permissions: 1,
},
],
CalendarSettings: {
CalendarID: dummyCalendarKeyID,
DefaultEventDuration: 30,
DefaultFullDayNotifications: [
{ Trigger: '-PT17H', Type: 1 },
{ Trigger: '-PT17H', Type: 0 },
],
DefaultPartDayNotifications: [
{ Trigger: '-PT17M', Type: 1 },
{ Trigger: '-PT17M', Type: 0 },
],
ID: dummyCalendarKeyID,
},
}));
}
// mock call to get calendar events
const events = await Promise.all(
veventsApi.map((eventComponent) =>
generateApiCalendarEvent({
eventComponent,
author: userEmailAddress,
publicKey: alternativeCalendarKey?.publicKeys[0] || calendarKey.publicKeys[0],
privateKey: alternativeAddressKey?.privateKeys[0] || addressKey.privateKeys[0],
eventID,
sharedEventID,
calendarID: dummyCalendarID,
})
)
);
addApiMock('calendar/v1/events', () => ({
Code: API_CODES.SINGLE_SUCCESS,
Events: events,
}));
// mock address keys to encrypt ICS attachment
minimalCache();
addAddressToCache({
ID: userPrimaryAddressID,
Email: userEmailAddress,
Status: userAddressEnabled ? ADDRESS_STATUS.STATUS_ENABLED : ADDRESS_STATUS.STATUS_DISABLED,
});
addKeysToAddressKeysCache(userPrimaryAddressID, addressKey);
return {
localID: '1',
data: {
ID: '1',
Sender: { Name: senderEmailAddress, Address: senderEmailAddress, IsSimpleLogin: isSimpleLogin ? 1 : 0 },
AddressID: userPrimaryAddressID,
Subject: emailSubject,
Time: new Date().getTime() / 1000,
Attachments: encryptedAttachments.map(({ attachmentID, filename, attachmentPackets }) => ({
ID: attachmentID,
Name: filename,
KeyPackets: uint8ArrayToBase64String(attachmentPackets.keys),
MIMEType: 'text/calendar',
})),
ParsedHeaders: {
'X-Original-To': userEmailAddress,
},
},
} as unknown as MessageStateWithData;
};
describe('ICS widget', () => {
beforeAll(async () => {
await setupCryptoProxyForTesting();
dummyAddressKey = await generateAddressKeys(dummyUserName, dummyUserEmailAddress);
dummyCalendarKeysAndPassphrasePromise = generateCalendarKeysAndPassphrase(dummyAddressKey);
});
afterAll(async () => {
await releaseCryptoProxy();
});
beforeEach(() => {
jest.spyOn(inviteApi, 'createCalendarEventFromInvitation');
// @ts-ignore
useCalendarUserSettings.mockReturnValue([{}, false]);
});
afterEach(clearAll);
it('should not duplicate error banners', async () => {
// constants
const dummyUID = 'testUID@example.domain';
const dummyToken = await generateAttendeeToken(canonicalizeInternalEmail(dummyUserEmailAddress), dummyUID);
// ics with unsupported time zone
const ics = `BEGIN:VCALENDAR
PRODID:-//Proton AG//WebCalendar 4.5.0//EN
VERSION:2.0
METHOD:REQUEST
CALSCALE:GREGORIAN
BEGIN:VEVENT
SEQUENCE:1
STATUS:CONFIRMED
SUMMARY:Walk on Mars
UID:${dummyUID}
DTSTART;TZID=Mars/Olympus:20220310T114500
ORGANIZER;CN=ORGO:mailto:${dummySenderEmailAddress}
ATTENDEE;ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=NEEDS-ACTION;X-PM-TOKEN=${dummyToken}:mailto:${dummyUserEmailAddress}
DTSTAMP:20210917T133417Z
END:VEVENT
END:VCALENDAR`;
const message = await getSetup({
attachments: [
{ attachmentID: 'attachment-id-1', filename: 'invite.ics', ics },
{ attachmentID: 'attachment-id-2', filename: 'calendar.ics', ics },
],
veventsApi: [],
eventCalendarID: dummyCalendarID,
});
await render(<ExtraEvents message={message} />, false);
// test single banner
expect(screen.getAllByText('Unsupported invitation')).toHaveLength(1);
});
describe('organizer mode', () => {
it('method=reply: displays the correct UI for the case with no calendars', async () => {
const dummyUID = 'testUID@example.domain';
const dummyToken = await generateAttendeeToken(canonicalizeInternalEmail(dummyUserEmailAddress), dummyUID);
const ics = `BEGIN:VCALENDAR
PRODID:-//Proton AG//WebCalendar 4.5.0//EN
VERSION:2.0
METHOD:REPLY
CALSCALE:GREGORIAN
BEGIN:VEVENT
SEQUENCE:1
STATUS:CONFIRMED
SUMMARY:Walk on Mars
UID:${dummyUID}
DTSTART;VALUE=DATE:${nextYear}0920
ORGANIZER;CN=ORGO:mailto:${dummyUserEmailAddress}
ATTENDEE;ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=NEEDS-ACTION;X-PM-TOKEN=${dummyToken}:mailto:${dummyUserEmailAddress}
DTSTAMP:20100917T133417Z
END:VEVENT
END:VCALENDAR`;
const message = await getSetup({
attachments: [{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics }],
userCalendars: [],
veventsApi: [],
eventCalendarID: dummyCalendarID,
userEmailAddress: dummyUserEmailAddress,
senderEmailAddress: dummyUserEmailAddress,
});
await render(<ExtraEvents message={message} />, false);
expect(screen.getByText(/This response is out of date. You have no calendars./)).toBeInTheDocument();
});
it('method=counter: decryption error', async () => {
const alternativeCalendarKeysAndPassphrasePromise = generateCalendarKeysAndPassphrase(dummyAddressKey);
const dummyUID = 'testUID@example.domain';
const dummyToken = await generateAttendeeToken(
canonicalizeInternalEmail(dummySenderEmailAddress),
dummyUID
);
const ics = `BEGIN:VCALENDAR
PRODID:-//Proton AG//WebCalendar 4.5.0//EN
VERSION:2.0
METHOD:COUNTER
CALSCALE:GREGORIAN
BEGIN:VEVENT
SEQUENCE:1
STATUS:CONFIRMED
SUMMARY:Walk on Mars
UID:${dummyUID}
DTSTART;VALUE=DATE:${nextYear}0920
ORGANIZER;CN=ORGO:mailto:${dummyUserEmailAddress}
ATTENDEE;ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=ACCEPTED;X-PM-TOKEN=${dummyToken}:mailto:${dummySenderEmailAddress}
DTSTAMP:20211013T144456Z
DTSTAMP:20210917T133417Z
END:VEVENT
END:VCALENDAR`;
// random event not matching ICS (doesn't matter for the decryption error case)
const eventComponent: VcalVeventComponent = {
component: 'vevent',
uid: { value: dummyUID },
sequence: { value: 1 },
dtstart: {
value: { year: 2021, month: 9, day: 20 },
parameters: { type: 'date' },
},
dtstamp: {
value: { year: 2021, month: 9, day: 17, hours: 13, minutes: 34, seconds: 17, isUTC: true },
},
organizer: {
value: `mailto:${dummyUserEmailAddress}`,
parameters: {
cn: 'ORGO',
},
},
attendee: [
{
value: `mailto:${dummySenderEmailAddress}`,
parameters: {
'x-pm-token': dummyToken,
partstat: ICAL_ATTENDEE_STATUS.ACCEPTED,
rsvp: ICAL_ATTENDEE_RSVP.TRUE,
},
},
],
};
const message = await getSetup({
attachments: [{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics }],
methodInMimeType: ICAL_METHOD.REQUEST,
veventsApi: [eventComponent],
eventCalendarID: dummyCalendarID,
alternativeCalendarKeysAndPassphrasePromise,
});
await render(<ExtraEvents message={message} />, false);
expect(
await screen.findByText(
`${dummySenderEmailAddress} accepted your invitation and proposed a new time for this event.`
)
).toBeInTheDocument();
});
it('no event in db already exists', async () => {
const dummyUID = 'testUID@example.domain';
const dummyToken = await generateAttendeeToken(canonicalizeInternalEmail(dummyUserEmailAddress), dummyUID);
const ics = `BEGIN:VCALENDAR
PRODID:-//Proton AG//WebCalendar 4.5.0//EN
VERSION:2.0
METHOD:REPLY
CALSCALE:GREGORIAN
BEGIN:VEVENT
SEQUENCE:1
STATUS:CONFIRMED
SUMMARY:Walk on Mars
UID:${dummyUID}
DTSTART;VALUE=DATE:${nextYear}0920
ORGANIZER;CN=ORGO:mailto:${dummyUserEmailAddress}
ATTENDEE;ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=NEEDS-ACTION;X-PM-TOKEN=${dummyToken}:mailto:${dummyUserEmailAddress}
DTSTAMP:20211013T144456Z
DTSTAMP:20210917T133417Z
END:VEVENT
END:VCALENDAR`;
const message = await getSetup({
attachments: [{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics }],
veventsApi: [],
eventCalendarID: dummyCalendarID,
userEmailAddress: dummyUserEmailAddress,
senderEmailAddress: dummyUserEmailAddress,
});
await render(<ExtraEvents message={message} />, false);
expect(
await screen.findByText(
/This response is out of date. The event does not exist in your calendar anymore./
)
).toBeInTheDocument();
});
it('method=refresh from future', async () => {
const dummyUID = 'testUID@example.domain';
const dummyToken = await generateAttendeeToken(
canonicalizeInternalEmail(dummySenderEmailAddress),
dummyUID
);
const ics = `BEGIN:VCALENDAR
PRODID:-//Proton AG//WebCalendar 4.5.0//EN
VERSION:2.0
METHOD:REFRESH
CALSCALE:GREGORIAN
BEGIN:VEVENT
SEQUENCE:3
STATUS:CONFIRMED
SUMMARY:Walk on Mars
UID:${dummyUID}
DTSTART;VALUE=DATE:${nextYear}0920
ORGANIZER;CN=ORGO:mailto:${dummyUserEmailAddress}
ATTENDEE;ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=NEEDS-ACTION;X-PM-TOKEN=${dummyToken}:mailto:${dummySenderEmailAddress}
DTSTAMP:${nextYear}1013T144456Z
END:VEVENT
END:VCALENDAR`;
const eventComponent: VcalVeventComponent = {
component: 'vevent',
uid: { value: dummyUID },
sequence: { value: 1 },
dtstart: {
value: { year: nextYear, month: 9, day: 20 },
parameters: { type: 'date' },
},
dtstamp: {
value: { year: nextYear, month: 9, day: 17, hours: 13, minutes: 34, seconds: 17, isUTC: true },
},
organizer: {
value: `mailto:${dummySenderEmailAddress}`,
parameters: {
cn: 'ORGO',
},
},
attendee: [
{
value: `mailto:${dummyUserEmailAddress}`,
parameters: {
'x-pm-token': dummyToken,
partstat: ICAL_ATTENDEE_STATUS.ACCEPTED,
rsvp: ICAL_ATTENDEE_RSVP.TRUE,
},
},
],
};
const message = await getSetup({
attachments: [{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics }],
veventsApi: [eventComponent],
eventCalendarID: dummyCalendarID,
});
await render(<ExtraEvents message={message} />, false);
expect(
await screen.findByText(
`${dummySenderEmailAddress} asked for the latest updates to an event which doesn't match your invitation details. Please verify the invitation details in your calendar.`
)
).toBeInTheDocument();
});
it('method=reply outdated', async () => {
const dummyUID = 'testUID@example.domain';
const dummyToken = await generateAttendeeToken(
canonicalizeInternalEmail(dummySenderEmailAddress),
dummyUID
);
const ics = `BEGIN:VCALENDAR
PRODID:-//Proton AG//WebCalendar 4.5.0//EN
VERSION:2.0
METHOD:REPLY
CALSCALE:GREGORIAN
BEGIN:VEVENT
SEQUENCE:1
STATUS:CONFIRMED
SUMMARY:Walk on Mars
UID:${dummyUID}
DTSTART;VALUE=DATE:${nextYear}0920
ORGANIZER;CN=ORGO:mailto:${dummyUserEmailAddress}
ATTENDEE;ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=ACCEPTED;X-PM-TOKEN=${dummyToken}:mailto:${dummySenderEmailAddress}
DTSTAMP:${nextYear}1013T144456Z
END:VEVENT
END:VCALENDAR`;
const eventComponent: VcalVeventComponent = {
component: 'vevent',
uid: { value: dummyUID },
sequence: { value: 2 },
dtstart: {
value: { year: nextYear, month: 9, day: 20 },
parameters: { type: 'date' },
},
dtstamp: {
value: { year: nextYear, month: 9, day: 17, hours: 13, minutes: 34, seconds: 17, isUTC: true },
},
organizer: {
value: `mailto:${dummyUserEmailAddress}`,
parameters: {
cn: 'ORGO',
},
},
attendee: [
{
value: `mailto:${dummySenderEmailAddress}`,
parameters: {
'x-pm-token': dummyToken,
partstat: ICAL_ATTENDEE_STATUS.ACCEPTED,
rsvp: ICAL_ATTENDEE_RSVP.TRUE,
},
},
],
};
const message = await getSetup({
attachments: [{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics }],
veventsApi: [eventComponent],
eventCalendarID: dummyCalendarID,
});
await render(<ExtraEvents message={message} />, false);
expect(
await screen.findByText(`${dummySenderEmailAddress} had previously accepted your invitation.`)
).toBeInTheDocument();
});
});
describe('attendee mode', () => {
it('should display the expected fields for the "new invitation" happy case', async () => {
// constants
const anotherEmailAddress = 'another@protonmail.ch';
const ics = `BEGIN:VCALENDAR
PRODID:-//Proton AG//WebCalendar 4.6.1//EN
VERSION:2.0
METHOD:REQUEST
CALSCALE:GREGORIAN
BEGIN:VTIMEZONE
TZID:Europe/Zurich
LAST-MODIFIED:20210410T122212Z
X-LIC-LOCATION:Europe/Zurich
BEGIN:DAYLIGHT
TZNAME:CEST
TZOFFSETFROM:+0100
TZOFFSETTO:+0200
DTSTART:19700329T020000
RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU
END:DAYLIGHT
BEGIN:STANDARD
TZNAME:CET
TZOFFSETFROM:+0200
TZOFFSETTO:+0100
DTSTART:19701025T030000
RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
SEQUENCE:0
STATUS:CONFIRMED
SUMMARY:Walk on the moon
UID:testUID@example.domain
DESCRIPTION:Recommended by Matthieu
DTSTART;TZID=Europe/Zurich:20211018T110000
DTEND;TZID=Europe/Zurich:20211018T120000
ORGANIZER;CN=${dummySenderEmailAddress}:mailto:${dummySenderEmailAddress}
ATTENDEE;CN=TEST;ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=NEEDS-ACTION;X-PM-
TOKEN=8c1a8462577e2be791f3a0286436e89c70d428f7:mailto:${dummyUserEmailAddress}
ATTENDEE;ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=NEEDS-ACTION;X-PM-TOKEN=32
f76161336da5e2c44e4d58c40e5015bba1da9d:mailto:${anotherEmailAddress}
DTSTAMP:20211013T144456Z
X-PM-SHARED-EVENT-ID:CDr63-NYMQl8L_dbp9qzbaSXmb9e6L8shmaxZfF3hWz9vVD3FX0j4l
kmct4zKnoOX7KgYBPbcZFccjIsD34lAZXTuO99T1XXd7WE8B36T7s=
X-PM-SESSION-KEY:IAhhZBd+KXKPm95M2QRJK7WgGHovpnVdJZb2mMoiwMM=
END:VEVENT
END:VCALENDAR`;
const message = await getSetup({
attachments: [{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics }],
methodInMimeType: ICAL_METHOD.REQUEST,
userCalendarSettings: dummyCalendarUserSettings,
});
await render(<ExtraEvents message={message} />, false);
// test event title
await screen.findByText('Walk on the moon');
// test event date
/**
* The exact text displayed in the event date field depends on the timezone and locale of the
* machine that runs the code. So here we just check that the date header is present. See
* dedicated tests of the date header component for tests of the text displayed.
*/
expect(screen.getByTestId('extra-event-date-header')).toBeInTheDocument();
// test event warning
expect(screen.getByText('Event already ended')).toBeInTheDocument();
// test link
expect(screen.queryByText(`Open in ${getAppName(APPS.PROTONCALENDAR)}`)).not.toBeInTheDocument();
// test buttons
expect(screen.getByText(/Attending?/)).toBeInTheDocument();
expect(screen.getByText(/Yes/, { selector: 'button' })).toBeInTheDocument();
expect(screen.getByText(/Maybe/, { selector: 'button' })).toBeInTheDocument();
expect(screen.getByText(/No/, { selector: 'button' })).toBeInTheDocument();
// test calendar
expect(screen.getByText(dummyCalendarName)).toBeInTheDocument();
// test organizer
expect(screen.getByText('Organizer:')).toBeInTheDocument();
const organizerElement = screen.getByTitle(dummySenderEmailAddress);
expect(organizerElement).toHaveAttribute(
'href',
expect.stringMatching(`mailto:${dummySenderEmailAddress}`)
);
expect(organizerElement).toHaveTextContent(dummySenderEmailAddress);
// test collapsed attendees
const showAttendeesButton = screen.getByText('Show');
expect(screen.queryByText(new RegExp(dummyUserEmailAddress))).not.toBeInTheDocument();
await userEvent.click(showAttendeesButton);
expect(screen.getByText('Show less')).toBeInTheDocument();
expect(screen.getByText(new RegExp(anotherEmailAddress))).toBeInTheDocument();
const selfAttendeeElement = screen.getByTitle(`You <${dummyUserEmailAddress}>`);
expect(selfAttendeeElement).toHaveTextContent(`You <${dummyUserEmailAddress}>`);
expect(selfAttendeeElement).toHaveAttribute(
'href',
expect.stringMatching(`mailto:${dummyUserEmailAddress}`)
);
});
it('should display the expected fields for the "already accepted invitation" happy case', async () => {
// constants
const dummyUID = 'testUID@example.domain';
const dummyToken = await generateAttendeeToken(canonicalizeInternalEmail(dummyUserEmailAddress), dummyUID);
const ics = `BEGIN:VCALENDAR
PRODID:-//Proton AG//WebCalendar 4.5.0//EN
VERSION:2.0
METHOD:REQUEST
CALSCALE:GREGORIAN
BEGIN:VEVENT
SEQUENCE:1
STATUS:CONFIRMED
SUMMARY:Walk on Mars
UID:${dummyUID}
DTSTART;VALUE=DATE:20210920
ORGANIZER;CN=ORGO:mailto:${dummySenderEmailAddress}
ATTENDEE;ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=NEEDS-ACTION;X-PM-TOKEN=${dummyToken}:mailto:${dummyUserEmailAddress}
DTSTAMP:20210917T133417Z
END:VEVENT
END:VCALENDAR`;
const eventComponent: VcalVeventComponent = {
component: 'vevent',
uid: { value: dummyUID },
sequence: { value: 1 },
dtstart: {
value: { year: 2021, month: 9, day: 20 },
parameters: { type: 'date' },
},
dtstamp: {
value: { year: 2021, month: 9, day: 17, hours: 13, minutes: 34, seconds: 17, isUTC: true },
},
organizer: {
value: `mailto:${dummySenderEmailAddress}`,
parameters: {
cn: 'ORGO',
},
},
attendee: [
{
value: `mailto:${dummyUserEmailAddress}`,
parameters: {
'x-pm-token': dummyToken,
partstat: ICAL_ATTENDEE_STATUS.ACCEPTED,
rsvp: ICAL_ATTENDEE_RSVP.TRUE,
},
},
],
};
const message = await getSetup({
attachments: [{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics }],
methodInMimeType: ICAL_METHOD.REQUEST,
veventsApi: [eventComponent],
eventCalendarID: dummyCalendarID,
});
await render(<ExtraEvents message={message} />, false);
// test event title
await screen.findByText('Walk on Mars');
// test event warning
expect(screen.getByText('Event already ended')).toBeInTheDocument();
// test link
expect(screen.getByText(`Open in ${getAppName(APPS.PROTONCALENDAR)}`)).toBeInTheDocument();
// test buttons
expect(screen.getByText('Attending?')).toBeInTheDocument();
expect(screen.getByTitle('Change my answer')).toHaveTextContent("Yes, I'll attend");
// test summary
expect(screen.getByText(/You already accepted this invitation./)).toBeInTheDocument();
});
it('shows the correct UI for an outdated invitation', async () => {
const dummyUID = 'testUID@example.domain';
const dummyToken = await generateAttendeeToken(canonicalizeInternalEmail(dummyUserEmailAddress), dummyUID);
const ics = `BEGIN:VCALENDAR
PRODID:-//Proton AG//WebCalendar 4.5.0//EN
VERSION:2.0
METHOD:REQUEST
CALSCALE:GREGORIAN
BEGIN:VEVENT
SEQUENCE:1
STATUS:CONFIRMED
SUMMARY:Walk on Mars
UID:${dummyUID}
DTSTART;VALUE=DATE:20100920
ORGANIZER;CN=ORGO:mailto:${dummySenderEmailAddress}
ATTENDEE;ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=NEEDS-ACTION;X-PM-TOKEN=${dummyToken}:mailto:${dummyUserEmailAddress}
DTSTAMP:20100917T133417Z
END:VEVENT
END:VCALENDAR`;
const eventComponent: VcalVeventComponent = {
component: 'vevent',
uid: { value: dummyUID },
sequence: { value: 1 },
dtstart: {
value: { year: 2021, month: 9, day: 20 },
parameters: { type: 'date' },
},
dtstamp: {
// The event was updated in the DB with respect to the invite. Notice DTSTAMP has changed with respect to the ics.
value: { year: 2021, month: 9, day: 17, hours: 13, minutes: 34, seconds: 17, isUTC: true },
},
organizer: {
value: `mailto:${dummySenderEmailAddress}`,
parameters: {
cn: 'ORGO',
},
},
attendee: [
{
value: `mailto:${dummyUserEmailAddress}`,
parameters: {
'x-pm-token': dummyToken,
partstat: ICAL_ATTENDEE_STATUS.ACCEPTED,
rsvp: ICAL_ATTENDEE_RSVP.TRUE,
},
},
],
};
const defaultCalendar = {
ID: dummyCalendarID,
Name: dummyCalendarName,
Description: '',
Type: CALENDAR_TYPE.PERSONAL,
Owner: { Email: dummyUserEmailAddress },
Members: [
{
ID: dummyMemberID,
AddressID: dummyUserPrimaryAddressID,
Permissions: 127 as const,
Email: dummyUserEmailAddress,
Flags: CALENDAR_FLAGS.ACTIVE,
CalendarID: dummyCalendarID,
Color: '#f00',
Display: CALENDAR_DISPLAY.HIDDEN,
Name: dummyCalendarName,
Description: '',
Priority: 1,
},
],
};
const message = await getSetup({
attachments: [{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics }],
userCalendars: [defaultCalendar],
userCalendarSettings: dummyCalendarUserSettings,
veventsApi: [eventComponent],
eventCalendarID: dummyCalendarID,
});
await render(<ExtraEvents message={message} />, false);
expect(
await screen.findByText(/This invitation is out of date. The event has been updated./)
).toBeInTheDocument();
});
it('does not display a summary when responding to an invitation', async () => {
const dummyUID = 'testUID@example.domain';
const anotherEmailAddress = 'another@protonmail.ch';
const [dummyToken, anotherToken] = await Promise.all(
[dummyUserEmailAddress, anotherEmailAddress].map((address) =>
generateAttendeeToken(canonicalizeInternalEmail(address), dummyUID)
)
);
const ics = `BEGIN:VCALENDAR
PRODID:-//Proton AG//WebCalendar 4.6.1//EN
VERSION:2.0
METHOD:REQUEST
CALSCALE:GREGORIAN
BEGIN:VTIMEZONE
TZID:Europe/Zurich
LAST-MODIFIED:20210410T122212Z
X-LIC-LOCATION:Europe/Zurich
BEGIN:DAYLIGHT
TZNAME:CEST
TZOFFSETFROM:+0100
TZOFFSETTO:+0200
DTSTART:19700329T020000
RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU
END:DAYLIGHT
BEGIN:STANDARD
TZNAME:CET
TZOFFSETFROM:+0200
TZOFFSETTO:+0100
DTSTART:19701025T030000
RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
SEQUENCE:0
STATUS:CONFIRMED
SUMMARY:Walk on the moon
UID:${dummyUID}
DESCRIPTION:Recommended by Matthieu
DTSTART;TZID=Europe/Zurich:20221018T110000
DTEND;TZID=Europe/Zurich:20221018T120000
ORGANIZER;CN=${dummySenderEmailAddress}:mailto:${dummySenderEmailAddress}
ATTENDEE;CN=TEST;ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=NEEDS-ACTION;X-PM-
TOKEN=${dummyToken}:mailto:${dummyUserEmailAddress}
ATTENDEE;ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=NEEDS-ACTION;X-PM-TOKEN=
${anotherToken}:mailto:${anotherEmailAddress}
DTSTAMP:20211013T144456Z
X-PM-SHARED-EVENT-ID:CDr63-NYMQl8L_dbp9qzbaSXmb9e6L8shmaxZfF3hWz9vVD3FX0j4l
kmct4zKnoOX7KgYBPbcZFccjIsD34lAZXTuO99T1XXd7WE8B36T7s=
X-PM-SESSION-KEY:IAhhZBd+KXKPm95M2QRJK7WgGHovpnVdJZb2mMoiwMM=
END:VEVENT
END:VCALENDAR`;
const savedAttendee = {
value: `mailto:${dummyUserEmailAddress}`,
parameters: {
cn: 'test',
'x-pm-token': dummyToken,
partstat: ICAL_ATTENDEE_STATUS.ACCEPTED,
rsvp: ICAL_ATTENDEE_RSVP.TRUE,
},
};
const savedVevent: VcalVeventComponent = {
component: 'vevent',
uid: { value: dummyUID },
sequence: { value: 0 },
dtstart: {
value: { year: 2022, month: 10, day: 18, hours: 11, minutes: 0, seconds: 0, isUTC: false },
parameters: { tzid: 'Europe/Zurich' },
},
dtend: {
value: { year: 2022, month: 10, day: 18, hours: 12, minutes: 0, seconds: 0, isUTC: false },
parameters: { tzid: 'Europe/Zurich' },
},
dtstamp: {
value: { year: 2021, month: 10, day: 13, hours: 14, minutes: 44, seconds: 56, isUTC: true },
},
organizer: {
value: `mailto:${dummySenderEmailAddress}`,
parameters: {
cn: dummySenderEmailAddress,
},
},
attendee: [
savedAttendee,
{
value: `mailto:${anotherEmailAddress}`,
parameters: {
cn: anotherEmailAddress,
'x-pm-token': anotherToken,
partstat: ICAL_ATTENDEE_STATUS.NEEDS_ACTION,
rsvp: ICAL_ATTENDEE_RSVP.TRUE,
},
},
],
};
const savedEvent = await generateApiCalendarEvent({
eventComponent: savedVevent,
author: dummyUserEmailAddress,
publicKey: (await dummyCalendarKeysAndPassphrasePromise).calendarKey.publicKeys[0],
privateKey: dummyAddressKey.privateKeys[0],
eventID: dummyEventID,
sharedEventID:
'CDr63-NYMQl8L_dbp9qzbaSXmb9e6L8shmaxZfF3hWz9vVD3FX0j4lkmct4zKnoOX7KgYBPbcZFccjIsD34lAZXTuO99T1XXd7WE8B36T7s=',
calendarID: dummyCalendarID,
});
// @ts-ignore
inviteApi.createCalendarEventFromInvitation.mockReturnValueOnce(
Promise.resolve({ savedEvent, savedVevent, savedAttendee })
);
// @ts-ignore
useGetVtimezonesMap.mockReturnValueOnce(() =>
Promise.resolve({
'Europe/Zurich': { vtimezone: {}, vtimezoneString: '' },
})
);
const message = await getSetup({
attachments: [{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics }],
});
await render(<ExtraEvents message={message} />, false);
await userEvent.click(await screen.findByTitle(`Yes, I'll attend`));
await waitFor(() => expect(screen.queryByTestId('ics-widget-summary')).not.toBeInTheDocument());
});
it('should show the correct UI for an unsupported ics with import PUBLISH', async () => {
// constants
const dummyUID = 'testUID@example.domain';
const dummyToken = await generateAttendeeToken(canonicalizeInternalEmail(dummyUserEmailAddress), dummyUID);
// ics with unsupported time zone
const ics = `BEGIN:VCALENDAR
PRODID:-//Proton AG//WebCalendar 4.5.0//EN
VERSION:2.0
METHOD:PUBLISH
CALSCALE:GREGORIAN
BEGIN:VEVENT
SEQUENCE:1
STATUS:CONFIRMED
SUMMARY:Walk on Mars
UID:${dummyUID}
DTSTART;TZID=Mars/Olympus:20220310T114500
ORGANIZER;CN=ORGO:mailto:${dummySenderEmailAddress}
ATTENDEE;ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=NEEDS-ACTION;X-PM-TOKEN=${dummyToken}:mailto:${dummyUserEmailAddress}
DTSTAMP:20210917T133417Z
END:VEVENT
END:VCALENDAR`;
const message = await getSetup({
attachments: [{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics }],
veventsApi: [],
eventCalendarID: dummyCalendarID,
});
await render(<ExtraEvents message={message} />, false);
expect(screen.queryByTestId('ics-widget-summary')).not.toBeInTheDocument();
await screen.findByText('Unsupported event');
});
it('should show the correct UI for a supported ics with import PUBLISH', async () => {
// constants
const dummyUID = 'testUID@example.domain';
const dummyToken = await generateAttendeeToken(canonicalizeInternalEmail(dummyUserEmailAddress), dummyUID);
const ics = `BEGIN:VCALENDAR
PRODID:-//Proton AG//WebCalendar 4.5.0//EN
VERSION:2.0
METHOD:PUBLISH
CALSCALE:GREGORIAN
BEGIN:VEVENT
SEQUENCE:1
STATUS:CONFIRMED
SUMMARY:Walk on Mars
UID:${dummyUID}
DTSTART;TZID=Europe/Zurich:20220310T114500
ORGANIZER;CN=ORGO:mailto:${dummySenderEmailAddress}
ATTENDEE;ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=NEEDS-ACTION;X-PM-TOKEN=${dummyToken}:mailto:${dummyUserEmailAddress}
DTSTAMP:20210917T133417Z
END:VEVENT
END:VCALENDAR`;
const message = await getSetup({
attachments: [{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics }],
veventsApi: [],
eventCalendarID: dummyCalendarID,
});
await render(<ExtraEvents message={message} />, false);
expect(screen.queryByTestId('ics-widget-summary')).not.toBeInTheDocument();
});
describe('Party crasher ICS widget', () => {
describe('Internal organizer', () => {
it('should not be possible to accept the event when the attendee is a party crasher and the organizer is internal', async () => {
const ics = `BEGIN:VCALENDAR
PRODID:-//Proton AG//WebCalendar 4.5.0//EN
VERSION:2.0
METHOD:REQUEST
CALSCALE:GREGORIAN
BEGIN:VTIMEZONE
TZID:Europe/Zurich
LAST-MODIFIED:20210410T122212Z
X-LIC-LOCATION:Europe/Zurich
BEGIN:DAYLIGHT
TZNAME:CEST
TZOFFSETFROM:+0100
TZOFFSETTO:+0200
DTSTART:19700329T020000
RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU
END:DAYLIGHT
BEGIN:STANDARD
TZNAME:CET
TZOFFSETFROM:+0200
TZOFFSETTO:+0100
DTSTART:19701025T030000
RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
SEQUENCE:0
STATUS:CONFIRMED
SUMMARY:Walk on the moon
UID:testUID@proton.me
DESCRIPTION:Recommended by Matthieu
DTSTART;TZID=Europe/Zurich:20211018T110000
DTEND;TZID=Europe/Zurich:20211018T120000
ORGANIZER;CN=${dummySenderEmailAddress}:mailto:${dummySenderEmailAddress}
ATTENDEE;CN=${dummyRecipientExternalEmailAddress};ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=ACCEPTED:mailto:${dummyRecipientExternalEmailAddress}
END:VEVENT
END:VCALENDAR`;
// dummySenderEmailAddress sends an invitation to dummyRecipientExternalEmailAddress
// Then dummyRecipientExternalEmailAddress forwards the invite to dummyUserEmailAddress.
// => dummyUserEmailAddress is now a party crasher
const message = await getSetup({
attachments: [{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics }],
methodInMimeType: ICAL_METHOD.REQUEST,
userCalendarSettings: dummyCalendarUserSettings,
senderEmailAddress: dummyRecipientExternalEmailAddress,
});
await render(<ExtraEvents message={message} />, false);
// Alert is displayed
expect(
await screen.findByText(
`You cannot respond to ${BRAND_NAME} invites if you're not on the participants list at the moment.`
)
).toBeInTheDocument();
// test buttons
expect(screen.queryByText(/Attending?/)).not.toBeInTheDocument();
expect(screen.queryByText(/Yes/, { selector: 'button' })).not.toBeInTheDocument();
expect(screen.queryByText(/Maybe/, { selector: 'button' })).not.toBeInTheDocument();
expect(screen.queryByText(/No/, { selector: 'button' })).not.toBeInTheDocument();
});
});
describe('External organizer', () => {
const partyCrasherExternalICS = `BEGIN:VCALENDAR
PRODID:-//Google Inc//Google Calendar 70.9054//EN
VERSION:2.0
METHOD:REQUEST
CALSCALE:GREGORIAN
BEGIN:VTIMEZONE
TZID:Europe/Zurich
LAST-MODIFIED:20210410T122212Z
X-LIC-LOCATION:Europe/Zurich
BEGIN:DAYLIGHT
TZNAME:CEST
TZOFFSETFROM:+0100
TZOFFSETTO:+0200
DTSTART:19700329T020000
RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU
END:DAYLIGHT
BEGIN:STANDARD
TZNAME:CET
TZOFFSETFROM:+0200
TZOFFSETTO:+0100
DTSTART:19701025T030000
RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
SEQUENCE:0
STATUS:CONFIRMED
SUMMARY:Walk on the moon
UID:testUID@example.domain
DESCRIPTION:Recommended by Matthieu
DTSTART;TZID=Europe/Zurich:20211018T110000
DTEND;TZID=Europe/Zurich:20211018T120000
ORGANIZER;CN=${dummySenderExternalEmailAddress}:mailto:${dummySenderExternalEmailAddress}
ATTENDEE;CN=${dummyRecipientExternalEmailAddress};ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=ACCEPTED:mailto:${dummyRecipientExternalEmailAddress}
END:VEVENT
END:VCALENDAR`;
it('should be possible to accept the event when the attendee is a party crasher and the organizer is external', async () => {
// dummySenderExternalEmailAddress sends an invitation to dummyRecipientExternalEmailAddress
// Then dummyRecipientExternalEmailAddress forwards the invite to dummyUserEmailAddress.
// => dummyUserEmailAddress is now a party crasher
const message = await getSetup({
attachments: [
{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics: partyCrasherExternalICS },
],
methodInMimeType: ICAL_METHOD.REQUEST,
userCalendarSettings: dummyCalendarUserSettings,
senderEmailAddress: dummyRecipientExternalEmailAddress,
});
await render(<ExtraEvents message={message} />, false);
// Alert is displayed
expect(
await screen.findByText('Your email address is not in the original participants list.')
).toBeInTheDocument();
// test buttons
expect(screen.getByText(/Attending?/)).toBeInTheDocument();
expect(screen.getByText(/Yes/, { selector: 'button' })).toBeInTheDocument();
expect(screen.getByText(/Maybe/, { selector: 'button' })).toBeInTheDocument();
expect(screen.getByText(/No/, { selector: 'button' })).toBeInTheDocument();
});
it('should show widget when the attendee is a party crasher which accepted the invite, and the organizer is external', async () => {
const dummyUID = 'testUID@example.domain';
const dummyToken = await generateAttendeeToken(
canonicalizeInternalEmail(dummyUserEmailAddress),
dummyUID
);
const ics = `BEGIN:VCALENDAR
PRODID:-//Google Inc//Google Calendar 70.9054//EN
VERSION:2.0
METHOD:REQUEST
CALSCALE:GREGORIAN
BEGIN:VEVENT
DTSTART;VALUE=DATE:20210920
SEQUENCE:1
STATUS:CONFIRMED
SUMMARY:Walk on the moon
UID:${dummyUID}
DESCRIPTION:Recommended by Matthieu
ORGANIZER;CN=${dummySenderExternalEmailAddress}:mailto:${dummySenderExternalEmailAddress}
ATTENDEE;CN=${dummyRecipientExternalEmailAddress};ROLE=REQ-PARTICIPANT;RSVP=TRUE;PARTSTAT=ACCEPTED:mailto:${dummyRecipientExternalEmailAddress}
DTSTAMP:20210917T133417Z
END:VEVENT
END:VCALENDAR`;
const eventComponent: VcalVeventComponent = {
component: 'vevent',
uid: { value: dummyUID },
sequence: { value: 1 },
dtstart: {
value: { year: 2021, month: 9, day: 20 },
parameters: { type: 'date' },
},
dtstamp: {
value: { year: 2021, month: 9, day: 17, hours: 13, minutes: 34, seconds: 17, isUTC: true },
},
organizer: {
value: `mailto:${dummySenderExternalEmailAddress}`,
parameters: {
cn: 'ORGO',
},
},
attendee: [
{
value: `mailto:${dummyRecipientExternalEmailAddress}`,
parameters: {
partstat: ICAL_ATTENDEE_STATUS.ACCEPTED,
rsvp: ICAL_ATTENDEE_RSVP.TRUE,
},
},
{
value: `mailto:${dummyUserEmailAddress}`,
parameters: {
'x-pm-token': dummyToken,
partstat: ICAL_ATTENDEE_STATUS.ACCEPTED,
rsvp: ICAL_ATTENDEE_RSVP.TRUE,
},
},
],
};
// dummySenderExternalEmailAddress sends an invitation to dummyRecipientExternalEmailAddress
// Then dummyRecipientExternalEmailAddress forwards the invite to dummyUserEmailAddress.
// => dummyUserEmailAddress is now a party crasher, and he accepted the invite.
const message = await getSetup({
attachments: [{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics }],
methodInMimeType: ICAL_METHOD.REQUEST,
userCalendarSettings: dummyCalendarUserSettings,
senderEmailAddress: dummyRecipientExternalEmailAddress,
veventsApi: [eventComponent],
});
await render(<ExtraEvents message={message} />, false);
await screen.findByText('Walk on the moon');
// Alert is displayed
expect(
screen.getByText('Your email address is not in the original participants list.')
).toBeInTheDocument();
// test buttons
expect(screen.getByText(/Attending?/)).toBeInTheDocument();
expect(screen.getByTitle('Change my answer')).toHaveTextContent("Yes, I'll attend");
});
it('should show widget when the attendee is a party crasher with disabled address, and organizer is external', async () => {
// dummySenderExternalEmailAddress sends an invitation to dummyRecipientExternalEmailAddress
// Then dummyRecipientExternalEmailAddress forwards the invite to dummyUserEmailAddress.
// => dummyUserEmailAddress is now a party crasher
const message = await getSetup({
attachments: [
{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics: partyCrasherExternalICS },
],
methodInMimeType: ICAL_METHOD.REQUEST,
userCalendarSettings: dummyCalendarUserSettings,
senderEmailAddress: dummyRecipientExternalEmailAddress,
userAddressEnabled: false,
});
await render(<ExtraEvents message={message} />, false);
// Alert is displayed
expect(await screen.findByText('You cannot reply from the invited address.')).toBeInTheDocument();
// test buttons
expect(screen.queryByText(/Attending?/)).not.toBeInTheDocument();
expect(screen.queryByText(/Yes/, { selector: 'button' })).not.toBeInTheDocument();
expect(screen.queryByText(/Maybe/, { selector: 'button' })).not.toBeInTheDocument();
expect(screen.queryByText(/No/, { selector: 'button' })).not.toBeInTheDocument();
});
it('should show widget when the attendee is a party crasher with disabled calendars, and organizer is external', async () => {
// dummySenderExternalEmailAddress sends an invitation to dummyRecipientExternalEmailAddress
// Then dummyRecipientExternalEmailAddress forwards the invite to dummyUserEmailAddress.
// => dummyUserEmailAddress is now a party crasher
const message = await getSetup({
attachments: [
{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics: partyCrasherExternalICS },
],
methodInMimeType: ICAL_METHOD.REQUEST,
userCalendarSettings: dummyCalendarUserSettings,
senderEmailAddress: dummyRecipientExternalEmailAddress,
defaultCalendarID: 'calendar-key-id-0',
userCalendars: generateCalendars(2, true),
});
await render(<ExtraEvents message={message} />, false);
// Alert is displayed
expect(await screen.findByText('All your calendars are disabled.')).toBeInTheDocument();
expect(
await screen.findByText('Create a calendar linked to an active email address.')
).toBeInTheDocument();
// test buttons
expect(screen.getByText(/Attending?/)).toBeInTheDocument();
expect(screen.getByText(/Yes/, { selector: 'button' })).toBeInTheDocument();
expect(screen.getByText(/Maybe/, { selector: 'button' })).toBeInTheDocument();
expect(screen.getByText(/No/, { selector: 'button' })).toBeInTheDocument();
});
it('should show widget when the attendee is a party crasher with disabled calendars, calendar limit reached, and organizer is external', async () => {
// dummySenderExternalEmailAddress sends an invitation to dummyRecipientExternalEmailAddress
// Then dummyRecipientExternalEmailAddress forwards the invite to dummyUserEmailAddress.
// => dummyUserEmailAddress is now a party crasher
const message = await getSetup({
attachments: [
{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics: partyCrasherExternalICS },
],
methodInMimeType: ICAL_METHOD.REQUEST,
userCalendarSettings: dummyCalendarUserSettings,
senderEmailAddress: dummyRecipientExternalEmailAddress,
defaultCalendarID: 'calendar-key-id-0',
userCalendars: generateCalendars(25, true),
});
await render(<ExtraEvents message={message} />, false);
// Alert is displayed
expect(await screen.findByText('All your calendars are disabled.')).toBeInTheDocument();
expect(
await screen.findByText('Enable an email address linked to one of your calendars.')
).toBeInTheDocument();
expect(
await screen.findByText(
'Or you can delete one of your calendars and create a new one linked to an active email address.'
)
).toBeInTheDocument();
// test buttons
expect(screen.getByText(/Attending?/)).toBeInTheDocument();
expect(screen.getByText(/Yes/, { selector: 'button' })).toBeInTheDocument();
expect(screen.getByText(/Maybe/, { selector: 'button' })).toBeInTheDocument();
expect(screen.getByText(/No/, { selector: 'button' })).toBeInTheDocument();
});
it('should not be possible to accept party crasher events when the mail is coming from SimpleLogin', async () => {
const message = await getSetup({
attachments: [
{ attachmentID: dummyAttachmentID, filename: dummyFileName, ics: partyCrasherExternalICS },
],
methodInMimeType: ICAL_METHOD.REQUEST,
userCalendarSettings: dummyCalendarUserSettings,
senderEmailAddress: dummyRecipientExternalEmailAddress,
isSimpleLogin: true,
});
await render(<ExtraEvents message={message} />, false);
// Alert is displayed
expect(
await screen.findByText('Your email address is not in the original participants list.')
).toBeInTheDocument();
// test buttons
expect(screen.queryByText(/Attending?/)).not.toBeInTheDocument();
expect(screen.queryByText(/Yes/, { selector: 'button' })).not.toBeInTheDocument();
expect(screen.queryByText(/Maybe/, { selector: 'button' })).not.toBeInTheDocument();
expect(screen.queryByText(/No/, { selector: 'button' })).not.toBeInTheDocument();
});
});
});
});
});
| 3,599
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.