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/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/ExtraEvents.tsx
import { useEffect, useState } from 'react'; import { useAddresses, useApi, useContactEmails, useEventManager, useGetAddressKeys, useGetCalendarEventRaw, useGetCalendarInfo, useGetCalendarUserSettings, useGetCalendars, useUser, useUserSettings, } from '@proton/components'; import { useGetCanonicalEmailsMap } from '@proton/components/hooks/useGetCanonicalEmailsMap'; import { WorkerDecryptionResult } from '@proton/crypto'; import { arrayToBinaryString, decodeUtf8 } from '@proton/crypto/lib/utils'; import { useLoading } from '@proton/hooks'; import useIsMounted from '@proton/hooks/useIsMounted'; import { getCanCreateCalendar, getDefaultCalendar, getIsCalendarDisabled, getOwnedPersonalCalendars, } from '@proton/shared/lib/calendar/calendar'; import { ICAL_MIME_TYPE } from '@proton/shared/lib/calendar/constants'; import { EVENT_INVITATION_ERROR_TYPE, EventInvitationError, } from '@proton/shared/lib/calendar/icsSurgery/EventInvitationError'; import { getIsVcalErrorComponent, getVcalendarHasNoErrorComponents } from '@proton/shared/lib/calendar/vcalHelper'; import { VcalErrorComponent, VcalVcalendarWithMaybeErrors, VisualCalendar, } from '@proton/shared/lib/interfaces/calendar'; import { Attachment } from '@proton/shared/lib/interfaces/mail/Message'; import { getAttachments, isBounced } from '@proton/shared/lib/mail/messages'; import isTruthy from '@proton/utils/isTruthy'; import unary from '@proton/utils/unary'; import { useContactsMap } from 'proton-mail/hooks/contact/useContacts'; import { formatDownload } from '../../../helpers/attachment/attachmentDownloader'; import { EventInvitation, filterAttachmentsForEvents, getSupportedEventInvitation, parseVcalendar, } from '../../../helpers/calendar/invite'; import { getOrCreatePersonalCalendarsAndSettings } from '../../../helpers/calendar/inviteApi'; import { isNetworkError } from '../../../helpers/errors'; import { getMessageHasData } from '../../../helpers/message/messages'; import { useGetAttachment } from '../../../hooks/attachments/useAttachment'; import { useGetMessageKeys } from '../../../hooks/message/useGetMessageKeys'; import { updateAttachment } from '../../../logic/attachments/attachmentsActions'; import { MessageErrors, MessageStateWithData } from '../../../logic/messages/messagesTypes'; import { errors as errorsAction } from '../../../logic/messages/read/messagesReadActions'; import { useAppDispatch } from '../../../logic/store'; import ExtraEvent from './calendar/ExtraEvent'; interface Props { message: MessageStateWithData; } const ExtraEvents = ({ message }: Props) => { const api = useApi(); const { call } = useEventManager(); const isMounted = useIsMounted(); const getMessageKeys = useGetMessageKeys(); const getAttachment = useGetAttachment(); const dispatch = useAppDispatch(); // const messageCache = useMessageCache(); const getCalendars = useGetCalendars(); const [contactEmails = [], loadingContactEmails] = useContactEmails(); const [addresses = [], loadingAddresses] = useAddresses(); const getAddressKeys = useGetAddressKeys(); const [user, loadingUser] = useUser(); const [userSettings, loadingUserSettings] = useUserSettings(); const getCalendarUserSettings = useGetCalendarUserSettings(); const getCalendarInfo = useGetCalendarInfo(); const contactsMap = useContactsMap(); const getCalendarEventRaw = useGetCalendarEventRaw(contactsMap); const getCanonicalEmailsMap = useGetCanonicalEmailsMap(); const [loadingWidget, withLoadingWidget] = useLoading(); const [loadedWidget, setLoadedWidget] = useState(''); const [invitations, setInvitations] = useState<(EventInvitation | EventInvitationError)[]>([]); const [calData, setCalData] = useState<{ calendars: VisualCalendar[]; defaultCalendar?: VisualCalendar; canCreateCalendar: boolean; maxUserCalendarsDisabled: boolean; }>({ calendars: [], canCreateCalendar: true, maxUserCalendarsDisabled: false }); const loadingConfigs = loadingContactEmails || loadingAddresses || loadingUserSettings || loadingUser; const messageHasDecryptionError = !!message.errors?.decryption?.length; const isBouncedEmail = isBounced(message.data); useEffect(() => { try { const attachments = getAttachments(message.data); const eventAttachments = filterAttachmentsForEvents(attachments); if ( !eventAttachments.length || messageHasDecryptionError || isBouncedEmail || loadingConfigs || !getMessageHasData(message) ) { // widget should not be displayed under these circumstances // clear up React states in case this component does not unmount when opening new emails setInvitations([]); setLoadedWidget(''); return; } if (loadedWidget === message.data.ID) { // avoid re-loading widget if it has been loaded already return; } const run = async () => { const getCalData = async () => { const isFreeUser = !user.hasPaidMail; const { calendars, calendarUserSettings } = await getOrCreatePersonalCalendarsAndSettings({ api, callEventManager: call, addresses, isFreeUser, getAddressKeys, getCalendars, getCalendarUserSettings, }); const defaultCalendar = getDefaultCalendar(calendars, calendarUserSettings.DefaultCalendarID); const ownedPersonalCalendars = getOwnedPersonalCalendars(calendars); const disabledCalendars = ownedPersonalCalendars.filter(unary(getIsCalendarDisabled)); const canCreateCalendar = getCanCreateCalendar({ calendars, ownedPersonalCalendars, disabledCalendars, isFreeUser, }); const maxUserCalendarsDisabled = !canCreateCalendar && ownedPersonalCalendars.length === disabledCalendars.length; return { calendars: ownedPersonalCalendars, defaultCalendar, canCreateCalendar, maxUserCalendarsDisabled, }; }; const getInvitations = async () => { // re-order attachments by MIME Type, as we prefer 'text/calendar' in case of duplicate uids const sortedEventAttachments = [...eventAttachments].sort(({ MIMEType: a }, { MIMEType: b }) => { if (a === ICAL_MIME_TYPE) { return -1; } if (b === ICAL_MIME_TYPE) { return 1; } return 0; }); const onUpdateAttachment = (ID: string, attachment: WorkerDecryptionResult<Uint8Array>) => { dispatch(updateAttachment({ ID, attachment })); }; const invitations = ( await Promise.all( sortedEventAttachments.map(async (attachment: Attachment) => { try { const messageKeys = await getMessageKeys(message.data); const download = await formatDownload( attachment, message.verification, messageKeys, onUpdateAttachment, api, getAttachment, message.data.Flags ); if (download.isError) { return new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.DECRYPTION_ERROR); } const icsBinaryString = arrayToBinaryString(download.data); const parsedVcalendar = parseVcalendar( decodeUtf8(icsBinaryString) ) as VcalVcalendarWithMaybeErrors; if (!parsedVcalendar) { return; } if (!getVcalendarHasNoErrorComponents(parsedVcalendar)) { const externalError = (parsedVcalendar.components || []).find( (component): component is VcalErrorComponent => getIsVcalErrorComponent(component) )!.error; return new EventInvitationError( EVENT_INVITATION_ERROR_TYPE.INVITATION_INVALID, { externalError } ); } const { PrimaryTimezone: primaryTimezone } = await getCalendarUserSettings(); const supportedEventInvitation = await getSupportedEventInvitation({ vcalComponent: parsedVcalendar, message: message.data, icsBinaryString, icsFileName: attachment.Name || '', primaryTimezone, }); return supportedEventInvitation; } catch (error: any) { if (error instanceof EventInvitationError) { return error; } return new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.INVITATION_INVALID, { externalError: error, }); } }) ) ).filter(isTruthy); const { uniqueInvitations } = invitations.reduce<{ uniqueInvitations: (EventInvitation | EventInvitationError)[]; uniqueUids: string[]; }>( (acc, invitation) => { const { uniqueInvitations, uniqueUids } = acc; const uid = invitation.originalUniqueIdentifier; if (!uid) { uniqueInvitations.push(invitation); return acc; } if (uniqueUids.includes(uid)) { return acc; } uniqueUids.push(uid); uniqueInvitations.push(invitation); return acc; }, { uniqueInvitations: [], uniqueUids: [] } ); return uniqueInvitations; }; const [calData, invitations] = await Promise.all([getCalData(), getInvitations()]); if (!isMounted()) { return; } setCalData(calData); setInvitations(invitations); }; void withLoadingWidget(run()); void setLoadedWidget(message.data.ID); } catch (error: any) { const errors: MessageErrors = {}; if (isNetworkError(error)) { errors.network = [error]; } else { errors.unknown = [error]; } dispatch(errorsAction({ ID: message.localID, errors })); } }, [message.data, message.errors, loadingConfigs, message.data.ID]); if (loadingConfigs || messageHasDecryptionError || !getMessageHasData(message) || loadingWidget) { return null; } return ( <> {invitations.map((invitation, index: number) => { return ( <ExtraEvent key={index} // eslint-disable-line react/no-array-index-key invitationOrError={invitation} message={message} calendars={calData.calendars} defaultCalendar={calData.defaultCalendar} canCreateCalendar={calData.canCreateCalendar} maxUserCalendarsDisabled={calData.maxUserCalendarsDisabled} contactEmails={contactEmails} ownAddresses={addresses} userSettings={userSettings} getAddressKeys={getAddressKeys} getCalendarInfo={getCalendarInfo} getCalendarEventRaw={getCalendarEventRaw} getCanonicalEmailsMap={getCanonicalEmailsMap} /> ); })} </> ); }; export default ExtraEvents;
3,600
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/ExtraImages.tsx
import { c } from 'ttag'; import { Button, Kbd } from '@proton/atoms'; import { Icon, Tooltip } from '@proton/components'; import LoadRemoteImageBanner from '@proton/components/containers/banner/LoadRemoteImageBanner'; import { shiftKey } from '@proton/shared/lib/helpers/browser'; import { MailSettings } from '@proton/shared/lib/interfaces'; import { hasShowEmbedded, hasShowRemote } from '@proton/shared/lib/mail/images'; import { hasToSkipProxy } from '../../../helpers/message/messageRemotes'; import { MessageImages } from '../../../logic/messages/messagesTypes'; interface Props { messageImages?: MessageImages; type: string; onLoadImages: () => void; mailSettings: MailSettings; } const ExtraImages = ({ messageImages, type, onLoadImages, mailSettings }: Props) => { const { Shortcuts } = mailSettings; const { showRemoteImages = true, showEmbeddedImages = true } = messageImages || {}; const couldLoadDirect = type === 'remote' && showRemoteImages === true && hasToSkipProxy(messageImages?.images); if (type === 'embedded' && hasShowEmbedded(mailSettings)) { return null; } if (type === 'embedded' && showEmbeddedImages !== false) { return null; } if (type === 'remote' && hasShowRemote(mailSettings) && !couldLoadDirect) { return null; } if (type === 'remote' && showRemoteImages !== false && !couldLoadDirect) { return null; } const remoteText = couldLoadDirect ? c('Action').t`Some images could not be loaded with tracker protection.` : c('Action').t`This message contains remote content.`; const embeddedText = c('Action').t`This message contains embedded images.`; const text = type === 'remote' ? remoteText : embeddedText; const actionText = type === 'embedded' ? c('Action').t`Load embedded images` : c('Action').t`Load`; const tooltipText = couldLoadDirect ? c('Action').t`Images will be loaded without a proxy` : type === 'remote' ? c('Title').t`Load remote content` : c('Title').t`Load embedded images`; const tooltip = Shortcuts ? ( <> {tooltipText} <br /> <Kbd shortcut={shiftKey} /> + <Kbd shortcut="C" /> </> ) : undefined; if (type === 'embedded') { return ( <Tooltip title={text}> <Button onClick={onLoadImages} data-testid="embedded-content:load" className="inline-flex flex-align-items-center w-full md:w-auto on-mobile-flex-justify-center mr-0 md:mr-0 mb-3 px-2" > <Icon name="image" className="flex-item-noshrink ml-1" /> <span className="ml-2">{actionText}</span> </Button> </Tooltip> ); } return ( <LoadRemoteImageBanner onClick={onLoadImages} actionText={actionText} text={text} tooltip={tooltip} couldLoadDirect={couldLoadDirect} /> ); }; export default ExtraImages;
3,601
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/ExtraPinKey.test.tsx
import { Matcher, fireEvent } from '@testing-library/react'; import { PublicKeyReference } from '@proton/crypto'; import { Address, MailSettings } from '@proton/shared/lib/interfaces'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { VERIFICATION_STATUS } from '@proton/shared/lib/mail/constants'; import { PROMPT_PIN } from '@proton/shared/lib/mail/mailSettings'; import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../helpers/test/crypto'; import { addApiMock, addToCache, clearAll, generateKeys, minimalCache, render, tick, } from '../../../helpers/test/helper'; import { message } from '../../../helpers/test/pinKeys'; import { MessageVerification } from '../../../logic/messages/messagesTypes'; import ExtraPinKey from './ExtraPinKey'; const { SIGNED_AND_VALID, SIGNED_AND_INVALID, NOT_SIGNED, NOT_VERIFIED } = VERIFICATION_STATUS; const setup = async ( message: Message, messageVerification: MessageVerification, isOwnAddress = false, isAutoPrompt = false ) => { minimalCache(); if (isOwnAddress) { addToCache('Addresses', [{ Email: 'sender@protonmail.com' } as Address]); } if (isAutoPrompt) { addToCache('MailSettings', { PromptPin: PROMPT_PIN.ENABLED } as MailSettings); } const component = await render(<ExtraPinKey message={message} messageVerification={messageVerification} />, false); return component; }; describe('Extra pin key banner not displayed', () => { beforeAll(async () => { await setupCryptoProxyForTesting(); }); afterAll(async () => { await releaseCryptoProxy(); }); afterEach(clearAll); it('should not render the banner when sender has a PM address', async () => { const senderKey = await generateKeys('sender', 'sender@protonmail.com'); const signingKey = await generateKeys('signing', 'sender@protonmail.com'); const messageVerification = { signingPublicKey: signingKey.publicKeys[0], senderPinnedKeys: [...senderKey.publicKeys] as PublicKeyReference[], verificationStatus: SIGNED_AND_VALID, } as MessageVerification; const { queryByTestId } = await setup(message, messageVerification, true); const banner = queryByTestId('extra-pin-key:banner'); expect(banner).toBeNull(); }); it.each` verificationStatus ${NOT_SIGNED} ${NOT_VERIFIED} ${SIGNED_AND_INVALID} `('should not render the banner when signing public key is already pinned', async ({ verificationStatus }) => { const senderKey = await generateKeys('sender', message.Sender.Address); const messageVerification = { senderPinnedKeys: [...senderKey.publicKeys] as PublicKeyReference[], attachedPublicKeys: [...senderKey.publicKeys] as PublicKeyReference[], verificationStatus, } as MessageVerification; const { queryByTestId } = await setup(message, messageVerification); const banner = queryByTestId('extra-pin-key:banner'); expect(banner).toBeNull(); }); }); describe('Extra pin key banner displayed', () => { beforeAll(async () => { await setupCryptoProxyForTesting(); }); afterAll(async () => { await releaseCryptoProxy(); }); afterEach(clearAll); const openTrustKeyModal = async (getByText: (text: Matcher) => HTMLElement) => { const trustKeyButton = getByText('Trust key'); fireEvent.click(trustKeyButton); await tick(); // Trust public key modal is open getByText('Trust public key?'); }; // AUTOPROMPT it.each` verificationStatus | shouldDisablePrompt ${NOT_VERIFIED} | ${true} ${NOT_VERIFIED} | ${false} ${SIGNED_AND_INVALID} | ${true} ${SIGNED_AND_INVALID} | ${false} `( 'should render the banner when prompt key pinning is AUTOPROMPT', async ({ verificationStatus, shouldDisablePrompt }) => { const signingKey = await generateKeys('signing', message.Sender.Address); const messageVerification = { signingPublicKey: signingKey.publicKeys[0], verificationStatus, } as MessageVerification; const { getByTestId, getByText } = await setup(message, messageVerification, false, true); getByTestId('extra-pin-key:banner'); // Expected text is displayed getByText("This sender's public key has not been trusted yet."); // Test disable prompt button if (shouldDisablePrompt) { const updateSpy = jest.fn(() => Promise.resolve({})); addApiMock('mail/v4/settings/promptpin', updateSpy, 'put'); const disableAutopromtButton = getByText('Never show'); fireEvent.click(disableAutopromtButton); await tick(); expect(updateSpy).toBeCalled(); } else { // Open trust public key modal and trust the key await openTrustKeyModal(getByText); } } ); // PIN_UNSEEN it('should render the banner when prompt key pinning is PIN_UNSEEN', async () => { const senderKey = await generateKeys('sender', message.Sender.Address); const signingKey = await generateKeys('signing', message.Sender.Address); const messageVerification = { signingPublicKey: signingKey.publicKeys[0], senderPinnedKeys: [...senderKey.publicKeys] as PublicKeyReference[], senderPinnableKeys: [...signingKey.publicKeys] as PublicKeyReference[], verificationStatus: NOT_VERIFIED, } as MessageVerification; const { getByTestId, getByText } = await setup(message, messageVerification); getByTestId('extra-pin-key:banner'); // Expected text is displayed getByText('This message is signed by a key that has not been trusted yet.'); await openTrustKeyModal(getByText); }); it('should not render the banner when prompt key pinning is PIN_UNSEEN but the signature is invalid', async () => { const senderKey = await generateKeys('sender', message.Sender.Address); const signingKey = await generateKeys('signing', message.Sender.Address); const messageVerification = { signingPublicKey: signingKey.publicKeys[0], senderPinnedKeys: [...senderKey.publicKeys] as PublicKeyReference[], verificationStatus: SIGNED_AND_INVALID, } as MessageVerification; const { queryByTestId } = await setup(message, messageVerification); expect(queryByTestId('extra-pin-key:banner')).toBeNull(); }); // PIN_ATTACHED_SIGNING it.each` verificationStatus ${NOT_VERIFIED} ${SIGNED_AND_INVALID} `('should render the banner when prompt key pinning is PIN_ATTACHED_SIGNING', async ({ verificationStatus }) => { const signingKey = await generateKeys('signing', message.Sender.Address); const messageVerification = { signingPublicKey: signingKey.publicKeys[0], attachedPublicKeys: [...signingKey.publicKeys] as PublicKeyReference[], verificationStatus, } as MessageVerification; const { getByTestId, getByText } = await setup(message, messageVerification); getByTestId('extra-pin-key:banner'); // Expected text is displayed getByText('This message is signed by the key attached, that has not been trusted yet.'); await openTrustKeyModal(getByText); }); // PIN_ATTACHED it.each` verificationStatus | hasSigningKey ${NOT_SIGNED} | ${false} ${NOT_SIGNED} | ${true} ${NOT_VERIFIED} | ${false} ${SIGNED_AND_INVALID} | ${false} `( 'should render the banner when prompt key pinning is PIN_ATTACHED', async ({ verificationStatus, hasSigningKey }) => { const signingKey = await generateKeys('signing', message.Sender.Address); const messageVerification = { signingPublicKey: hasSigningKey ? signingKey.publicKeys[0] : undefined, attachedPublicKeys: [...signingKey.publicKeys] as PublicKeyReference[], verificationStatus, } as MessageVerification; const { getByTestId, getByText } = await setup(message, messageVerification, false, true); getByTestId('extra-pin-key:banner'); // Expected text is displayed getByText('An unknown public key has been detected for this recipient.'); await openTrustKeyModal(getByText); } ); });
3,602
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/ExtraPinKey.tsx
import { useMemo } from 'react'; import { c } from 'ttag'; import { Button, Href } from '@proton/atoms'; import { Icon, InlineLinkButton, useAddresses, useApi, useEventManager, useModalState, useNotifications, } from '@proton/components'; import { PublicKeyReference } from '@proton/crypto'; import { useLoading } from '@proton/hooks'; import { updatePromptPin } from '@proton/shared/lib/api/mailSettings'; import { canonicalizeInternalEmail } from '@proton/shared/lib/helpers/email'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { Address, MailSettings } from '@proton/shared/lib/interfaces'; import { ContactWithBePinnedPublicKey } from '@proton/shared/lib/interfaces/contacts'; import { VERIFICATION_STATUS } from '@proton/shared/lib/mail/constants'; import { PROMPT_PIN } from '@proton/shared/lib/mail/mailSettings'; import { isInternal } from '@proton/shared/lib/mail/messages'; import useMailModel from 'proton-mail/hooks/useMailModel'; import { getContactEmail } from '../../../helpers/message/messageRecipients'; import { useContactsMap } from '../../../hooks/contact/useContacts'; import { MessageVerification, MessageWithOptionalBody } from '../../../logic/messages/messagesTypes'; import TrustPublicKeyModal from '../modals/TrustPublicKeyModal'; const { NOT_VERIFIED, SIGNED_AND_INVALID } = VERIFICATION_STATUS; enum PROMPT_KEY_PINNING_TYPE { AUTOPROMPT = 1, PIN_UNSEEN, PIN_ATTACHED_SIGNING, PIN_ATTACHED, } interface Params { messageVerification: MessageVerification; mailSettings: MailSettings; addresses: Address[]; senderAddress: string; } const getPromptKeyPinningType = ({ messageVerification, mailSettings, addresses, senderAddress, }: Params): PROMPT_KEY_PINNING_TYPE | undefined => { if (addresses.find(({ Email }) => canonicalizeInternalEmail(Email) === canonicalizeInternalEmail(senderAddress))) { // Do not pin keys for own addresses return undefined; } const { PromptPin } = mailSettings; const { senderPinnedKeys = [], senderPinnableKeys = [], attachedPublicKeys = [], signingPublicKey, verificationStatus, } = messageVerification; const senderHasPinnedKeys = !!senderPinnedKeys.length; const firstAttachedPublicKey = attachedPublicKeys.length ? attachedPublicKeys[0] : undefined; const isSignedByAttachedKey = !!signingPublicKey && attachedPublicKeys?.some((key) => signingPublicKey?.equals(key)); const isAttachedKeyPinned = firstAttachedPublicKey && senderPinnedKeys.some((key) => firstAttachedPublicKey.equals(key)); if (verificationStatus === SIGNED_AND_INVALID || verificationStatus === NOT_VERIFIED) { if (!signingPublicKey) { if (firstAttachedPublicKey) { return PROMPT_KEY_PINNING_TYPE.PIN_ATTACHED; } return; } const signingFingerprint = signingPublicKey.getFingerprint(); if (senderHasPinnedKeys) { if (senderPinnableKeys.find((key) => key.getFingerprint() === signingFingerprint)) { // TODO: Exclude case where signature is invalid due to message modification (cf. OpenPGP.js v5) return PROMPT_KEY_PINNING_TYPE.PIN_UNSEEN; } else { return; } } if (isSignedByAttachedKey) { return PROMPT_KEY_PINNING_TYPE.PIN_ATTACHED_SIGNING; } if (PromptPin) { return PROMPT_KEY_PINNING_TYPE.AUTOPROMPT; } } if (verificationStatus === VERIFICATION_STATUS.NOT_SIGNED) { if (!firstAttachedPublicKey || isAttachedKeyPinned) { return; } return PROMPT_KEY_PINNING_TYPE.PIN_ATTACHED; } }; const getBannerMessage = (promptKeyPinningType: PROMPT_KEY_PINNING_TYPE) => { if (promptKeyPinningType === PROMPT_KEY_PINNING_TYPE.PIN_UNSEEN) { return c('Info').t`This message is signed by a key that has not been trusted yet.`; } if (promptKeyPinningType === PROMPT_KEY_PINNING_TYPE.PIN_ATTACHED_SIGNING) { return c('Info').t`This message is signed by the key attached, that has not been trusted yet.`; } if (promptKeyPinningType === PROMPT_KEY_PINNING_TYPE.PIN_ATTACHED) { return c('Info').t`An unknown public key has been detected for this recipient.`; } if (promptKeyPinningType === PROMPT_KEY_PINNING_TYPE.AUTOPROMPT) { return c('Info').t`This sender's public key has not been trusted yet.`; } }; interface Props { message: MessageWithOptionalBody; messageVerification: MessageVerification; } const ExtraPinKey = ({ message, messageVerification }: Props) => { const api = useApi(); const mailSettings = useMailModel('MailSettings'); const [addresses] = useAddresses(); const [loadingDisablePromptPin, withLoadingDisablePromptPin] = useLoading(); const { createNotification } = useNotifications(); const { call } = useEventManager(); const contactsMap = useContactsMap(); const [trustPublicKeyModalProps, setTrustPublicKeyModalOpen, renderTrustPublicKeyModal] = useModalState(); const senderAddress = message.Sender.Address; const name = message.Sender.Name; const isSenderInternal = isInternal(message); const messageContactID = message?.Sender.ContactID; const contactID = useMemo<string | undefined>(() => { if (messageContactID) { return messageContactID; } if (!senderAddress) { return; } const preferredContact = getContactEmail(contactsMap, senderAddress); return preferredContact?.ContactID; }, [messageContactID, contactsMap, senderAddress]); const promptKeyPinningType = useMemo<PROMPT_KEY_PINNING_TYPE | undefined>(() => { if (!senderAddress) { return undefined; } return getPromptKeyPinningType({ messageVerification, mailSettings, addresses, senderAddress }); }, [messageVerification, mailSettings, addresses, senderAddress]); const isPinUnseen = promptKeyPinningType === PROMPT_KEY_PINNING_TYPE.PIN_UNSEEN; const firstAttachedPublicKey = messageVerification?.attachedPublicKeys?.length ? messageVerification.attachedPublicKeys[0] : undefined; const bePinnedPublicKey = messageVerification?.signingPublicKey || firstAttachedPublicKey; const loading = loadingDisablePromptPin || !senderAddress || (isPinUnseen && !contactID) || !bePinnedPublicKey; // Prevent to propose an already pinned key even if for a strange reason, // the suggested key is already pinned yet the verification still fails const signingPublicKeyAlreadyPinned = messageVerification?.senderPinnedKeys?.some( (pinKey) => bePinnedPublicKey?.equals(pinKey) ); const contact = useMemo<ContactWithBePinnedPublicKey>(() => { return { emailAddress: senderAddress || '', name, contactID, isInternal: isSenderInternal, bePinnedPublicKey: bePinnedPublicKey as PublicKeyReference, }; }, [senderAddress, name, contactID, isSenderInternal, bePinnedPublicKey]); if (promptKeyPinningType === undefined || signingPublicKeyAlreadyPinned) { return null; } const handleDisablePromptPin = async () => { await api(updatePromptPin(PROMPT_PIN.DISABLED)); await call(); createNotification({ text: c('Success').t`Address verification disabled` }); }; const handleTrustKey = () => { if (loading || !bePinnedPublicKey || !senderAddress) { return; } setTrustPublicKeyModalOpen(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 flex-justify-space-between on-mobile-flex-column" data-testid="extra-pin-key:banner" > <div className="flex flex-nowrap pr-4 mb-2 md:mb-0"> <Icon name="exclamation-circle-filled" className="mt-1 mr-2 ml-0.5 flex-item-noshrink color-danger" /> <div> <span className="pr-2 flex flex-item-fluid mt-1"> <span className="mr-1" data-testid="extra-pin-key:content"> {getBannerMessage(promptKeyPinningType)} </span> {promptKeyPinningType === PROMPT_KEY_PINNING_TYPE.AUTOPROMPT ? ( <InlineLinkButton disabled={loadingDisablePromptPin} onClick={() => withLoadingDisablePromptPin(handleDisablePromptPin())} > {c('Action').t`Never show`} </InlineLinkButton> ) : ( <Href href={getKnowledgeBaseUrl('/address-verification')}>{c('Link').t`Learn more`}</Href> )} </span> </div> </div> <span className="flex-align-items-start flex-item-noshrink w-full md:w-auto pt-0.5"> <Button size="small" color="weak" shape="outline" fullWidth className="rounded-sm" onClick={handleTrustKey} disabled={loading} data-testid="extra-pin-key:trust-button" > {c('Action').t`Trust key`} </Button> </span> {renderTrustPublicKeyModal && <TrustPublicKeyModal contact={contact} {...trustPublicKeyModalProps} />} </div> ); }; export default ExtraPinKey;
3,603
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/ExtraReadReceipt.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Icon, Tooltip, useApi, useEventManager, useNotifications } from '@proton/components'; import { useLoading } from '@proton/hooks'; import { readReceipt } from '@proton/shared/lib/api/messages'; import { isReadReceiptSent, requireReadReceipt } from '@proton/shared/lib/mail/messages'; import { MessageWithOptionalBody } from '../../../logic/messages/messagesTypes'; interface Props { message: MessageWithOptionalBody; } const ExtraReadReceipt = ({ message }: Props) => { const api = useApi(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const [loading, withLoading] = useLoading(); const { ID } = message; const receiptSent = isReadReceiptSent(message); if (!requireReadReceipt(message)) { return null; } const handleClick = async () => { await api(readReceipt(ID)); await call(); createNotification({ text: c('Success').t`Read receipt sent` }); }; if (receiptSent) { return ( <span className="mr-2 mb-3 color-success flex w-full md:w-auto flex-align-items-center on-mobile-flex-justify-center flex-items-align-center"> <Icon name="checkmark" className="flex-item-noshrink my-auto" /> <span className="ml-2" data-testid="message-view:sent-receipt">{c('Action').t`Read receipt sent`}</span> </span> ); } return ( <Tooltip title={c('Info').t`The sender has requested a read receipt.`}> <Button onClick={() => withLoading(handleClick())} disabled={loading} data-testid="message-view:send-receipt" 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="bell" className="flex-item-noshrink ml-1" /> <span className="ml-2">{c('Action').t`Send read receipt`}</span> </Button> </Tooltip> ); }; export default ExtraReadReceipt;
3,604
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/ExtraScheduledMessage.test.tsx
import { act, fireEvent } from '@testing-library/react'; import { addHours, addSeconds } from 'date-fns'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { addDays } from '@proton/shared/lib/date-fns-utc'; import { formatDateToHuman } from '../../../helpers/date'; import { addApiMock, clearAll } from '../../../helpers/test/helper'; import { render } from '../../../helpers/test/render'; import { MessageStateWithData } from '../../../logic/messages/messagesTypes'; import ExtraScheduledMessage from './ExtraScheduledMessage'; const getMessage = (sendingDate: Date) => { return { localID: '1', data: { ID: '1', Subject: 'Scheduled message subject', Time: sendingDate.getTime() / 1000, LabelIDs: [MAILBOX_LABEL_IDS.SENT, MAILBOX_LABEL_IDS.SCHEDULED], }, } as MessageStateWithData; }; describe('Scheduled messages banner', () => { afterEach(clearAll); it('should show scheduled banner for scheduled messages', async () => { const sendingDate = addDays(new Date(), 3); const message = getMessage(sendingDate); const { getByTestId, getByText } = await render(<ExtraScheduledMessage message={message} />); const { dateString, formattedTime } = formatDateToHuman(sendingDate); getByTestId('message:schedule-banner'); getByText(`This message will be sent on ${dateString} at ${formattedTime}`); getByText('Edit'); }); it('should have text will be sent tomorrow', async () => { const sendingDate = addDays(new Date(), 1); const message = getMessage(sendingDate); const { getByTestId, getByText } = await render(<ExtraScheduledMessage message={message} />); const { formattedTime } = formatDateToHuman(sendingDate); getByTestId('message:schedule-banner'); const scheduledBannerText = getByText(`This message will be sent tomorrow at ${formattedTime}`); expect(scheduledBannerText.innerHTML).toContain('tomorrow'); getByText('Edit'); }); it('should have text will be sent in the morning', async () => { const aDayInTheMorningDate = new Date(2020, 0, 1, 8, 0, 0); const dateSpy = jest.spyOn(Date, 'now').mockImplementation(() => aDayInTheMorningDate.setHours(8).valueOf()); const sendingDate = addHours(aDayInTheMorningDate, 3); const message = getMessage(sendingDate); const { getByTestId, getByText } = await render(<ExtraScheduledMessage message={message} />); const { formattedTime } = formatDateToHuman(sendingDate); getByTestId('message:schedule-banner'); const scheduledBannerText = getByText(`This message will be sent in the morning at ${formattedTime}`); expect(scheduledBannerText.innerHTML).toContain('in the morning'); getByText('Edit'); dateSpy.mockRestore(); }); it('should have text will be sent today', async () => { const dateSpy = jest.spyOn(Date, 'now').mockImplementation(() => new Date().setHours(12).valueOf()); const sendingDate = addHours(new Date(Date.now()), 3); const message = getMessage(sendingDate); const { getByTestId, getByText } = await render(<ExtraScheduledMessage message={message} />); const { formattedTime } = formatDateToHuman(sendingDate); getByTestId('message:schedule-banner'); const scheduledBannerText = getByText(`This message will be sent today at ${formattedTime}`); expect(scheduledBannerText.innerHTML).toContain('today'); getByText('Edit'); dateSpy.mockRestore(); }); it('should have text will be sent shortly', async () => { const sendingDate = addSeconds(new Date(), 29); const message = getMessage(sendingDate); const { getByTestId, getByText, queryByTestId } = await render(<ExtraScheduledMessage message={message} />); getByTestId('message:schedule-banner'); getByText(`This message will be sent shortly`); expect(queryByTestId(`Edit`)).toBeNull(); }); it('should be able to edit the message', async () => { const sendingDate = addDays(new Date(), 1); const message = getMessage(sendingDate); const unscheduleCall = jest.fn(); addApiMock(`mail/v4/messages/${message.data?.ID}/cancel_send`, unscheduleCall); const { getByTestId, getByText } = await render(<ExtraScheduledMessage message={message} />); const { formattedTime } = formatDateToHuman(sendingDate); getByTestId('message:schedule-banner'); getByText(`This message will be sent tomorrow at ${formattedTime}`); const editButton = getByText('Edit'); // Edit the scheduled message fireEvent.click(editButton); getByText('Edit and reschedule'); const editDraftButton = getByText('Edit draft'); await act(async () => { // Unschedule the message fireEvent.click(editDraftButton); }); // Unschedule route is called expect(unscheduleCall).toHaveBeenCalled(); }); });
3,605
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/ExtraScheduledMessage.tsx
import { useEffect, useState } from 'react'; import { useHistory, useLocation } from 'react-router-dom'; import { isToday, isTomorrow } from 'date-fns'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Icon, Prompt, useApi, useEventManager, useModalState, useNotifications } from '@proton/components'; import { cancelSend } from '@proton/shared/lib/api/messages'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { hasBit } from '@proton/shared/lib/helpers/bitset'; import { SHOW_MOVED } from '@proton/shared/lib/mail/mailSettings'; import { isScheduled } from '@proton/shared/lib/mail/messages'; import clsx from '@proton/utils/clsx'; import useMailModel from 'proton-mail/hooks/useMailModel'; import { LABEL_IDS_TO_HUMAN, PREVENT_CANCEL_SEND_INTERVAL } from '../../../constants'; import { useOnCompose } from '../../../containers/ComposeProvider'; import { formatDateToHuman } from '../../../helpers/date'; import { ComposeTypes } from '../../../hooks/composer/useCompose'; import { MessageStateWithData } from '../../../logic/messages/messagesTypes'; import { cancelScheduled } from '../../../logic/messages/scheduled/scheduledActions'; import { useAppDispatch } from '../../../logic/store'; import { isScheduledSendTodayMorning } from '../../composer/actions/scheduleSend/helpers'; interface Props { message: MessageStateWithData; } const ExtraScheduledMessage = ({ message }: Props) => { const api = useApi(); const { call } = useEventManager(); const dispatch = useAppDispatch(); const { createNotification } = useNotifications(); const location = useLocation(); const history = useHistory(); const mailSettings = useMailModel('MailSettings'); const [loading, setLoading] = useState(false); const [nowDate, setNowDate] = useState(() => Date.now()); const onCompose = useOnCompose(); const [editScheduleModalProps, setEditScheduleModalOpen] = useModalState(); const isScheduledMessage = isScheduled(message.data); const scheduleDate = isScheduledMessage ? new Date(message.data.Time * 1000) : new Date(); const beforeSendInterval = scheduleDate.getTime() - nowDate; // Prevent from cancelling a message that is about to be sent 30s before const isScheduleSentShortly = beforeSendInterval < PREVENT_CANCEL_SEND_INTERVAL; useEffect(() => { const handle = setInterval(() => setNowDate(Date.now()), 1000); return () => { clearInterval(handle); }; }, []); const handleUnscheduleMessage = async () => { setLoading(true); dispatch(cancelScheduled({ ID: message.localID, scheduledAt: message.data.Time })); await api(cancelSend(message.data.ID)); setEditScheduleModalOpen(false); setLoading(false); await call(); createNotification({ text: c('Message notification').t`Scheduling canceled. Message has been moved to Drafts.`, }); onCompose({ type: ComposeTypes.existingDraft, existingDraft: message, fromUndo: false }); if (location.pathname.includes(LABEL_IDS_TO_HUMAN[MAILBOX_LABEL_IDS.SCHEDULED])) { const redirectToLoation = hasBit(mailSettings.ShowMoved, SHOW_MOVED.DRAFTS) ? MAILBOX_LABEL_IDS.ALL_DRAFTS : MAILBOX_LABEL_IDS.DRAFTS; history.push(LABEL_IDS_TO_HUMAN[redirectToLoation]); } }; const getScheduleBannerMessage = () => { if (isScheduleSentShortly) { return c('Info').t`This message will be sent shortly`; } const { dateString, formattedTime } = formatDateToHuman(scheduleDate); if (isScheduledSendTodayMorning(scheduleDate)) { /* * ${formattedTime} is the date formatted in user's locale (e.g. 11:00 PM) * Full sentence for reference: "This message will be sent in the morning at 11:00 AM" */ return c('Info').t`This message will be sent in the morning at ${formattedTime}`; } if (isToday(scheduleDate)) { /* * ${formattedTime} is the date formatted in user's locale (e.g. 11:00 PM) * Full sentence for reference: "This message will be sent today at 12:30 PM" */ return c('Info').t`This message will be sent today at ${formattedTime}`; } if (isTomorrow(scheduleDate)) { /* * ${formattedTime} is the date formatted in user's locale (e.g. 11:00 PM) * Full sentence for reference: "This message will be sent tomorrow at 12:30 PM" */ return c('Info').t`This message will be sent tomorrow at ${formattedTime}`; } /* * translator: The variables here are the following. * ${dateString} can be "on Tuesday, May 11" for example * ${formattedTime} is the date formatted in user's locale (e.g. 11:00 PM) * Full sentence for reference: "This message will be sent on Tuesday, May 11 at 12:30 PM" */ return c('Info').t`This message will be sent on ${dateString} at ${formattedTime}`; }; return ( <div className="bg-info rounded border border-info pr-2 md:pr-1 pb-2 md:pb-1 pt-1 pl-2 mb-3 flex flex-nowrap" data-testid="message:schedule-banner" > <Icon name="paper-plane-horizontal-clock" className="mt-1 ml-0.5 flex-item-noshrink" /> <span className={clsx(['px-2 flex-item-fluid mt-1', isScheduleSentShortly && 'mb-1'])}> {getScheduleBannerMessage()} </span> {!isScheduleSentShortly ? ( <span className="flex-item-noshrink flex-align-items-start flex"> <Button size="small" color="info" shape="outline" fullWidth className="rounded-sm" onClick={() => setEditScheduleModalOpen(true)} data-testid="message:schedule-banner-edit-button" >{c('Action').t`Edit`}</Button> </span> ) : null} <Prompt title={c('Confirm modal title').t`Edit and reschedule`} buttons={[ <Button disabled={loading} color="norm" onClick={handleUnscheduleMessage} data-testid="message:modal-edit-draft-button" >{c('Action').t`Edit draft`}</Button>, <Button disabled={loading} onClick={editScheduleModalProps.onClose}>{c('Action') .t`Cancel`}</Button>, ]} {...editScheduleModalProps} > {c('Info') .t`This message will be moved to Drafts so you can edit it. You'll need to reschedule when it will be sent.`} </Prompt> </div> ); }; export default ExtraScheduledMessage;
3,606
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/ExtraSnoozedMessage.test.tsx
import { act, fireEvent } from '@testing-library/react'; import { addHours } from 'date-fns'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { addDays } from '@proton/shared/lib/date-fns-utc'; import { formatDateToHuman } from '../../../helpers/date'; import { clearAll } from '../../../helpers/test/helper'; import { render } from '../../../helpers/test/render'; import useSnooze from '../../../hooks/actions/useSnooze'; import { MessageStateWithData } from '../../../logic/messages/messagesTypes'; import ExtraSnoozedMessage from './ExtraSnoozedMessage'; const mockUseGetElementsFromIDs = jest.fn(); jest.mock('../../../hooks/mailbox/useElements', () => ({ useGetElementsFromIDs: () => mockUseGetElementsFromIDs, })); jest.mock('../../../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 getMessage = (sendingDate: Date) => { return { localID: '1', data: { ID: '1', ConversationID: 'conversation', Subject: 'Scheduled message subject', SnoozeTime: sendingDate.getTime() / 1000, LabelIDs: [MAILBOX_LABEL_IDS.SENT, MAILBOX_LABEL_IDS.SNOOZED], }, } as MessageStateWithData; }; describe('Scheduled messages banner', () => { const useSnoozeMock = useSnooze as jest.Mock; const useGetElementsFromIDsMock = jest.fn(); afterEach(clearAll); it('should have text will be sent shortly, the unsnooze button must be hidden', async () => { const sendingDate = new Date(); const message = getMessage(sendingDate); const { getByTestId, getByText, queryByText } = await render(<ExtraSnoozedMessage message={message} />); const { formattedTime } = formatDateToHuman(sendingDate); getByTestId('message:snooze-banner'); getByText(`Snoozed until today, ${formattedTime}`); expect(queryByText('Unsnooze')).toBeNull(); }); it('should have text will be sent today', async () => { const sendingDate = addHours(new Date(), 1); const message = getMessage(sendingDate); const { getByTestId, getByText } = await render(<ExtraSnoozedMessage message={message} />); const { formattedTime } = formatDateToHuman(sendingDate); getByTestId('message:snooze-banner'); const text = `Snoozed until today, ${formattedTime}`; getByText(text); getByText('Unsnooze'); }); it('should have text will be sent tomorrow', async () => { const sendingDate = addDays(new Date(), 1); const message = getMessage(sendingDate); const { getByTestId, getByText } = await render(<ExtraSnoozedMessage message={message} />); const { formattedTime } = formatDateToHuman(sendingDate); getByTestId('message:snooze-banner'); getByText(`Snoozed until tomorrow, ${formattedTime}`); getByText('Unsnooze'); }); it('should have text will be sent in the future', async () => { const sendingDate = addDays(new Date(), 100); const message = getMessage(sendingDate); const { getByTestId, getByText } = await render(<ExtraSnoozedMessage message={message} />); const { formattedTime, dateString } = formatDateToHuman(sendingDate); getByTestId('message:snooze-banner'); getByText(`Snoozed until ${dateString} at ${formattedTime}`); getByText('Unsnooze'); }); it('should call the unsnooze method if has element', async () => { const sendingDate = addDays(new Date(), 1); const message = getMessage(sendingDate); mockUseGetElementsFromIDs.mockReturnValue([{ ID: '1' }]); const unsnoozeCall = jest.fn(); useSnoozeMock.mockReturnValue({ unsnooze: unsnoozeCall, }); const { getByTestId, getByText } = await render(<ExtraSnoozedMessage message={message} />); const { formattedTime } = formatDateToHuman(sendingDate); getByTestId('message:snooze-banner'); getByText(`Snoozed until tomorrow, ${formattedTime}`); const editButton = getByText('Unsnooze'); // Edit the snooze message await act(async () => { fireEvent.click(editButton); }); // Unsnooze route is called expect(unsnoozeCall).toHaveBeenCalled(); }); it('should not call the unsnooze method if has element', async () => { const sendingDate = addDays(new Date(), 1); const message = getMessage(sendingDate); mockUseGetElementsFromIDs.mockReturnValue(undefined); useGetElementsFromIDsMock.mockReturnValue(undefined); const unsnoozeCall = jest.fn(); useSnoozeMock.mockReturnValue({ unsnooze: unsnoozeCall, }); const { getByTestId, getByText } = await render(<ExtraSnoozedMessage message={message} />); const { formattedTime } = formatDateToHuman(sendingDate); getByTestId('message:snooze-banner'); getByText(`Snoozed until tomorrow, ${formattedTime}`); const editButton = getByText('Unsnooze'); // Edit the snooze message await act(async () => { fireEvent.click(editButton); }); // Unsnooze route is called expect(unsnoozeCall).not.toHaveBeenCalled(); }); });
3,607
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/ExtraSnoozedMessage.tsx
import { useEffect, useMemo, useState } from 'react'; import { isToday, isTomorrow } from 'date-fns'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Icon } from '@proton/components'; import { isSnoozed } from '@proton/shared/lib/mail/messages'; import clsx from '@proton/utils/clsx'; import { PREVENT_CANCEL_SEND_INTERVAL } from '../../../constants'; import { formatDateToHuman } from '../../../helpers/date'; import useSnooze from '../../../hooks/actions/useSnooze'; import { useGetElementsFromIDs } from '../../../hooks/mailbox/useElements'; import { MessageStateWithData } from '../../../logic/messages/messagesTypes'; import { getSnoozeTimeFromElement } from '../../../logic/snoozehelpers'; interface Props { message: MessageStateWithData; } const ExtraSnoozedMessage = ({ message }: Props) => { const getElementsFromIDs = useGetElementsFromIDs(); const elements = useMemo(() => getElementsFromIDs([message.data.ConversationID]), [message]); const [nowDate, setNowDate] = useState(() => Date.now()); const { unsnooze } = useSnooze(); const isSnoozedMessage = isSnoozed(message.data); const snoozeTime = getSnoozeTimeFromElement(message.data); const snoozeDate = isSnoozedMessage && snoozeTime ? new Date(snoozeTime * 1000) : new Date(); useEffect(() => { const handle = setInterval(() => setNowDate(Date.now()), 1000); return () => { clearInterval(handle); }; }, []); const handleUnsnoozeMessage = async () => { if (!elements || !elements.length) { return; } unsnooze(elements); }; const getSnoozeBannerMessage = () => { const { dateString, formattedTime } = formatDateToHuman(snoozeDate); if (isToday(snoozeDate)) { /* * ${formattedTime} is the date formatted in user's locale (e.g. 11:00 PM) * Translator: "Snoozed until today, 8:00 AM" */ return c('Info').t`Snoozed until today, ${formattedTime}`; } if (isTomorrow(snoozeDate)) { /* * ${formattedTime} is the date formatted in user's locale (e.g. 11:00 PM) * Translator: "Snoozed until tomorrow, 8:00 AM" */ return c('Info').t`Snoozed until tomorrow, ${formattedTime}`; } /* * translator: The variables here are the following. * ${dateString} can be "on Tuesday, May 11" for example * ${formattedTime} is the date formatted in user's locale (e.g. 11:00 PM) * Full sentence for reference: "Snoozed until on Tuesday, May 11 at 8:00 AM" */ return c('Info').t`Snoozed until ${dateString} at ${formattedTime}`; }; // Prevent from cancelling a message that is about to be sent 30s before const beforeSendInterval = snoozeDate.getTime() - nowDate; const isUnsnoozeShortly = beforeSendInterval < PREVENT_CANCEL_SEND_INTERVAL; return ( <div className="rounded border pr-2 md:pr-1 pb-2 md:pb-1 pt-1 pl-2 mb-3 flex flex-nowrap" data-testid="message:snooze-banner" > <Icon name="clock" className="mt-1 ml-0.5 flex-item-noshrink color-warning" /> <span className={clsx(['px-2 flex-item-fluid mt-1'])}>{getSnoozeBannerMessage()}</span> {!isUnsnoozeShortly ? ( <span className="flex-item-noshrink flex-align-items-start flex"> <Button size="small" shape="outline" fullWidth className="rounded-sm" onClick={handleUnsnoozeMessage} data-testid="snooze-banner-edit-button" >{c('Action').t`Unsnooze`}</Button> </span> ) : null} </div> ); }; export default ExtraSnoozedMessage;
3,608
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/ExtraSpamScore.tsx
import { c } from 'ttag'; import { Button, Href } from '@proton/atoms'; import { Icon, Prompt, useApi, useEventManager, useModalState, useNotifications } from '@proton/components'; import { useLoading } from '@proton/hooks'; import { markAsHam } from '@proton/shared/lib/api/messages'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { getBlogURL, getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { isAutoFlaggedPhishing, isDMARCValidationFailure, isManualFlaggedHam, isSuspicious, } from '@proton/shared/lib/mail/messages'; import { MessageStateWithData } from '../../../logic/messages/messagesTypes'; interface Props { message: MessageStateWithData; } const ExtraSpamScore = ({ message }: Props) => { const [loading, withLoading] = useLoading(); const { LabelIDs = [] } = message.data || {}; const { call } = useEventManager(); const api = useApi(); const { createNotification } = useNotifications(); const [spamScoreModalProps, setSpamScoreModalOpen] = useModalState(); const isSuspiciousFlagged = isSuspicious(message.data); if (isDMARCValidationFailure(message.data)) { return ( <div className="bg-norm rounded px-2 py-1 mb-3 flex flex-nowrap" data-testid="spam-banner:failed-dmarc-validation" > <Icon name="exclamation-circle-filled" className="flex-item-noshrink mt-1 ml-0.5 color-danger" /> <span className="px-2 pb-1 mt-0.5 flex-item-fluid"> {c('Info') .t`This email has failed its domain's authentication requirements. It may be spoofed or improperly forwarded.`}{' '} <Href href={getKnowledgeBaseUrl('/email-has-failed-its-domains-authentication-requirements-warning')} > {c('Info').t`Learn more`} </Href> </span> </div> ); } if ( (isAutoFlaggedPhishing(message.data) || isSuspiciousFlagged) && (!isManualFlaggedHam(message.data) || LabelIDs.includes(MAILBOX_LABEL_IDS.SPAM)) ) { const markAsLegitimate = async () => { await api(markAsHam(message.data.ID)); await call(); createNotification({ text: c('Success').t`Message marked as legitimate` }); }; return ( <div className="bg-danger border border-danger rounded pr-2 md:pr-1 pb-2 md:pb-1 pt-1 pl-2 mb-3 flex flex-nowrap" data-testid="spam-banner:phishing-banner" > <Icon name="exclamation-circle-filled" className="flex-item-noshrink ml-0.5 mt-1" /> <span className="px-2 mt-0.5 flex-item-fluid"> {isSuspiciousFlagged ? ( <> {c('Info') .t`Our system flagged this message as a suspicious email. Please check that it is legitimate before clicking any links or attachments.`} </> ) : ( <> {c('Info') .t`Our system flagged this message as a phishing attempt. Please check that it is legitimate.`} <Href className="px-2" href={getBlogURL('/prevent-phishing-attacks')}> {c('Info').t`Learn more`} </Href> </> )} </span> <span className="flex-item-noshrink flex-align-items-start flex"> <Button size="small" color="danger" shape="outline" className="rounded-sm" fullWidth onClick={() => setSpamScoreModalOpen(true)} disabled={loading} data-testid="spam-banner:mark-legitimate" > {c('Action').t`Mark legitimate`} </Button> </span> <Prompt title={c('Title').t`Mark email as legitimate`} buttons={[ <Button color="norm" onClick={() => withLoading(markAsLegitimate())}>{c('Action') .t`Mark legitimate`}</Button>, <Button onClick={spamScoreModalProps.onClose}>{c('Action').t`Cancel`}</Button>, ]} {...spamScoreModalProps} > {c('Info') .t`We apologize. This might have been a mistake from our side. Can you please confirm that you want to mark this email as a legitimate one?`} </Prompt> </div> ); } return null; }; export default ExtraSpamScore;
3,609
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/ExtraUnsubscribe.test.tsx
import { fireEvent, screen } from '@testing-library/react'; import loudRejection from 'loud-rejection'; import { openNewTab } from '@proton/shared/lib/helpers/browser'; import { mergeMessages } from '../../../helpers/message/messages'; import { addAddressToCache, minimalCache } from '../../../helpers/test/cache'; import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../helpers/test/crypto'; import { addApiKeys, addApiMock, addKeysToAddressKeysCache, clearAll, generateKeys, render, setFeatureFlags, waitForEventManagerCall, waitForNotification, } from '../../../helpers/test/helper'; import * as useSimpleLoginExtension from '../../../hooks/simpleLogin/useSimpleLoginExtension'; import { MessageStateWithData } from '../../../logic/messages/messagesTypes'; import ExtraUnsubscribe from './ExtraUnsubscribe'; loudRejection(); jest.mock('@proton/shared/lib/helpers/browser', () => ({ isMac: jest.fn(() => false), openNewTab: jest.fn(), isMobile: jest.fn(), isFirefoxLessThan55: jest.fn(), getIsIframe: jest.fn(() => false), })); describe('Unsubscribe banner', () => { const messageID = 'messageID'; const toAddressID = 'toAddressID'; const toAddress = 'to@domain.com'; const defaultMessage = { localID: messageID, data: { ID: messageID, Subject: 'test', ParsedHeaders: { 'X-Original-To': toAddress }, Attachments: [] } as any, messageDocument: { initialized: true }, verification: {}, } as MessageStateWithData; beforeAll(async () => { await setupCryptoProxyForTesting(); }); afterAll(async () => { await releaseCryptoProxy(); }); afterEach(clearAll); it('should show the unsubscribe banner with one click method', async () => { const unsubscribeCall = jest.fn(); const markUnsubscribedCall = jest.fn(); minimalCache(); addAddressToCache({ Email: toAddress }); addApiMock(`mail/v4/messages/${messageID}/unsubscribe`, unsubscribeCall); addApiMock(`mail/v4/messages/mark/unsubscribed`, markUnsubscribedCall); const message = mergeMessages(defaultMessage, { data: { UnsubscribeMethods: { OneClick: 'OneClick' }, }, }) as MessageStateWithData; await render(<ExtraUnsubscribe message={message.data} />, false); const button = screen.getByTestId('unsubscribe-banner'); expect(button.textContent).toMatch(/Unsubscribe/); if (button) { fireEvent.click(button); } const submitButton = screen.getByTestId('unsubscribe-banner:submit'); if (submitButton) { fireEvent.click(submitButton); } await waitForEventManagerCall(); expect(unsubscribeCall).toHaveBeenCalled(); expect(markUnsubscribedCall).toHaveBeenCalled(); }); it('should show the unsubscribe banner with mailto method', async () => { const mailto = 'to@address.com'; const keys = await generateKeys('me', toAddress); const createCall = jest.fn(() => ({ Message: { ID: messageID, Attachments: [] } })); const sendCall = jest.fn(() => ({ Sent: {} })); const markUnsubscribedCall = jest.fn(); minimalCache(); addAddressToCache({ ID: toAddressID, Email: toAddress }); addApiKeys(false, mailto, []); addKeysToAddressKeysCache(toAddressID, keys); addApiMock(`mail/v4/messages`, createCall); addApiMock(`mail/v4/messages/messageID`, sendCall); addApiMock(`mail/v4/messages/mark/unsubscribed`, markUnsubscribedCall); const message = mergeMessages(defaultMessage, { data: { UnsubscribeMethods: { Mailto: { ToList: [mailto], Body: 'body', Subject: 'subject' } }, }, }) as MessageStateWithData; await render(<ExtraUnsubscribe message={message.data} />, false); const button = screen.getByTestId('unsubscribe-banner'); expect(button.textContent).toMatch(/Unsubscribe/); if (button) { fireEvent.click(button); } const submitButton = screen.getByTestId('unsubscribe-banner:submit'); if (submitButton) { fireEvent.click(submitButton); } await waitForNotification('Mail list unsubscribed'); await waitForEventManagerCall(); expect(sendCall).toHaveBeenCalled(); expect(markUnsubscribedCall).toHaveBeenCalled(); }); it('should show the unsubscribe banner with http client method', async () => { const markUnsubscribedCall = jest.fn(); const openNewTabMock = openNewTab as jest.Mock; minimalCache(); addAddressToCache({ ID: toAddressID, Email: toAddress }); addApiMock(`mail/v4/messages/mark/unsubscribed`, markUnsubscribedCall); const message = mergeMessages(defaultMessage, { data: { UnsubscribeMethods: { HttpClient: 'url' }, }, }) as MessageStateWithData; await render(<ExtraUnsubscribe message={message.data} />, false); const button = screen.getByTestId('unsubscribe-banner'); expect(button.textContent).toMatch(/Unsubscribe/); if (button) { fireEvent.click(button); } const submitButton = screen.getByTestId('unsubscribe-banner:submit'); if (submitButton) { fireEvent.click(submitButton); } await waitForEventManagerCall(); expect(openNewTabMock).toHaveBeenCalled(); expect(markUnsubscribedCall).toHaveBeenCalled(); }); it('should show an extra modal when the user has no SimpleLogin extension', async () => { setFeatureFlags('SLIntegration', true); jest.spyOn(useSimpleLoginExtension, 'useSimpleLoginExtension').mockReturnValue({ hasSimpleLogin: false, hasSLExtension: false, canUseExtension: true, hasAccountLinked: true, isFetchingAccountLinked: true, }); const unsubscribeCall = jest.fn(); const markUnsubscribedCall = jest.fn(); minimalCache(); addAddressToCache({ Email: toAddress }); addApiMock(`mail/v4/messages/${messageID}/unsubscribe`, unsubscribeCall); addApiMock(`mail/v4/messages/mark/unsubscribed`, markUnsubscribedCall); const message = mergeMessages(defaultMessage, { data: { UnsubscribeMethods: { OneClick: 'OneClick' }, }, }) as MessageStateWithData; await render(<ExtraUnsubscribe message={message.data} />, false); const button = screen.getByTestId('unsubscribe-banner'); expect(button.textContent).toMatch(/Unsubscribe/); if (button) { fireEvent.click(button); } // Submit first modal const submitButton = screen.getByTestId('unsubscribe-banner:submit'); if (submitButton) { fireEvent.click(submitButton); } // Second modal should be opened screen.getByText('hide-my-email aliases'); }); it('should not show an extra modal when the user has SimpleLogin extension', async () => { setFeatureFlags('SLIntegration', true); jest.spyOn(useSimpleLoginExtension, 'useSimpleLoginExtension').mockReturnValue({ hasSimpleLogin: true, hasSLExtension: true, canUseExtension: true, hasAccountLinked: true, isFetchingAccountLinked: true, }); const unsubscribeCall = jest.fn(); const markUnsubscribedCall = jest.fn(); minimalCache(); addAddressToCache({ Email: toAddress }); addApiMock(`mail/v4/messages/${messageID}/unsubscribe`, unsubscribeCall); addApiMock(`mail/v4/messages/mark/unsubscribed`, markUnsubscribedCall); const message = mergeMessages(defaultMessage, { data: { UnsubscribeMethods: { OneClick: 'OneClick' }, }, }) as MessageStateWithData; await render(<ExtraUnsubscribe message={message.data} />, false); const button = screen.getByTestId('unsubscribe-banner'); expect(button.textContent).toMatch(/Unsubscribe/); if (button) { fireEvent.click(button); } // Submit first modal const submitButton = screen.getByTestId('unsubscribe-banner:submit'); if (submitButton) { fireEvent.click(submitButton); } // Second modal should not be opened expect(screen.queryByText('hide-my-email aliases')).toBeNull(); }); it('should not show an extra modal when the user has no SimpleLogin extension but the message is from SimpleLogin', async () => { setFeatureFlags('SLIntegration', true); jest.spyOn(useSimpleLoginExtension, 'useSimpleLoginExtension').mockReturnValue({ hasSimpleLogin: false, hasSLExtension: false, canUseExtension: true, hasAccountLinked: true, isFetchingAccountLinked: true, }); const unsubscribeCall = jest.fn(); const markUnsubscribedCall = jest.fn(); minimalCache(); addAddressToCache({ Email: toAddress }); addApiMock(`mail/v4/messages/${messageID}/unsubscribe`, unsubscribeCall); addApiMock(`mail/v4/messages/mark/unsubscribed`, markUnsubscribedCall); const message = mergeMessages(defaultMessage, { data: { UnsubscribeMethods: { OneClick: 'OneClick' }, Sender: { Address: 'sender@simplelogin.co', Name: 'SimpleLoginAlias', IsSimpleLogin: 1 }, }, }) as MessageStateWithData; await render(<ExtraUnsubscribe message={message.data} />, false); const button = screen.getByTestId('unsubscribe-banner'); expect(button.textContent).toMatch(/Unsubscribe/); if (button) { fireEvent.click(button); } // Submit first modal const submitButton = screen.getByTestId('unsubscribe-banner:submit'); if (submitButton) { fireEvent.click(submitButton); } // Second modal should not be opened expect(screen.queryByText('hide-my-email aliases')).toBeNull(); }); it('should not show an extra modal when the message was coming from an official Proton address', async () => { const unsubscribeCall = jest.fn(); const markUnsubscribedCall = jest.fn(); minimalCache(); addAddressToCache({ Email: toAddress }); addApiMock(`mail/v4/messages/${messageID}/unsubscribe`, unsubscribeCall); addApiMock(`mail/v4/messages/mark/unsubscribed`, markUnsubscribedCall); const message = mergeMessages(defaultMessage, { data: { UnsubscribeMethods: { OneClick: 'OneClick' }, Sender: { Address: 'sender@simplelogin.co', Name: 'SimpleLoginAlias', IsProton: 1 }, }, }) as MessageStateWithData; await render(<ExtraUnsubscribe message={message.data} />, false); const button = screen.getByTestId('unsubscribe-banner'); expect(button.textContent).toMatch(/Unsubscribe/); if (button) { fireEvent.click(button); } // Submit first modal const submitButton = screen.getByTestId('unsubscribe-banner:submit'); if (submitButton) { fireEvent.click(submitButton); } // Second modal should not be opened expect(screen.queryByText('hide-my-email aliases')).toBeNull(); }); });
3,610
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/ExtraUnsubscribe.tsx
import { c } from 'ttag'; import { Button, ButtonLike, Href } from '@proton/atoms'; import { FeatureCode, Field, Icon, Label, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, PrimaryButton, Prompt, Row, Tooltip, generateUID, useAddresses, useApi, useEventManager, useFeature, useModalState, useNotifications, } from '@proton/components'; import { useLoading } from '@proton/hooks'; import { markAsUnsubscribed, oneClickUnsubscribe } from '@proton/shared/lib/api/messages'; import { TelemetrySimpleLoginEvents } from '@proton/shared/lib/api/telemetry'; import { MIME_TYPES } from '@proton/shared/lib/constants'; import { openNewTab } from '@proton/shared/lib/helpers/browser'; import { canonicalizeInternalEmail } from '@proton/shared/lib/helpers/email'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { AUTO_SAVE_CONTACTS } from '@proton/shared/lib/mail/mailSettings'; import { getOriginalTo, hasProtonSender, hasSimpleLoginSender, isUnsubscribed } from '@proton/shared/lib/mail/messages'; import isTruthy from '@proton/utils/isTruthy'; import { useOnCompose } from '../../../containers/ComposeProvider'; import { findSender } from '../../../helpers/message/messageRecipients'; import { useSendMessage } from '../../../hooks/composer/useSendMessage'; import { useSendVerifications } from '../../../hooks/composer/useSendVerifications'; import { useGetMessage } from '../../../hooks/message/useMessage'; import { useSaveDraft } from '../../../hooks/message/useSaveDraft'; import { useSimpleLoginExtension } from '../../../hooks/simpleLogin/useSimpleLoginExtension'; import { useSimpleLoginTelemetry } from '../../../hooks/simpleLogin/useSimpleLoginTelemetry'; import { MessageStateWithData, MessageWithOptionalBody, PartialMessageState, } from '../../../logic/messages/messagesTypes'; import SimpleLoginModal from '../../simpleLogin/SimpleLoginModal'; interface Props { message: MessageWithOptionalBody; } const ExtraUnsubscribe = ({ message }: Props) => { const { feature: simpleLoginIntegrationFeature, loading: loadingSimpleLoadingFeature } = useFeature( FeatureCode.SLIntegration ); const { handleSendTelemetryData } = useSimpleLoginTelemetry(); const { createNotification } = useNotifications(); const api = useApi(); const { call } = useEventManager(); const [addresses] = useAddresses(); const { extendedVerifications: sendVerification } = useSendVerifications(); const { hasSimpleLogin } = useSimpleLoginExtension(); const saveDraft = useSaveDraft(); const getMessage = useGetMessage(); const sendMessage = useSendMessage(); const [loading, withLoading] = useLoading(); const onCompose = useOnCompose(); const toAddress = getOriginalTo(message); const address = addresses.find( ({ Email }) => canonicalizeInternalEmail(Email) === canonicalizeInternalEmail(toAddress) ); const unsubscribeMethods = message.UnsubscribeMethods || {}; // If the user doesn't have the simple login extension, we want to show an extra modal to upsell the feature // However, if the received email is coming from Simple Login, the user is probably already using SL, so we don't want to display the extra modal // Finally, if the sender is an official Proton address, we don't want to show this modal const needsSimpleLoginPresentation = simpleLoginIntegrationFeature?.Value && !hasSimpleLogin && !hasSimpleLoginSender(message) && !hasProtonSender(message); const [unsubscribeModalProps, setUnsubscribeModalOpen] = useModalState(); const [unsubscribedModalProps, setUnsubscribedModalOpen, renderUnsubscribedModal] = useModalState(); const [simpleLoginModalProps, setSimpleLoginModalOpen, renderSimpleLoginModal] = useModalState(); if (!Object.keys(unsubscribeMethods).length || !address) { return null; } const messageID = message.ID; let modalContent; let submit: () => void; if (unsubscribeMethods.OneClick) { modalContent = ( <> {c('Info') .t`A request to unsubscribe from this mailing list will be sent to the sender of the newsletter and automatically processed.`} <br /> <Href href={getKnowledgeBaseUrl('/auto-unsubscribe')}>{c('Link').t`Learn more`}</Href> </> ); submit = async () => { await api(oneClickUnsubscribe(messageID)); }; } else if (unsubscribeMethods.HttpClient) { modalContent = ( <> {c('Info') .jt`To unsubscribe from this mailing list, you will be taken to the following URL where instructions will be provided by the sender of the newsletter:`} <br /> <Href href={getKnowledgeBaseUrl('/avoid-spam')}>{c('Link').t`Learn more`}</Href> <div className="text-bold rounded border p-4 bg-weak text-break my-4">{c('Info') .t`URL: ${unsubscribeMethods.HttpClient}`}</div> </> ); submit = () => { if (unsubscribeMethods.HttpClient) { openNewTab(unsubscribeMethods.HttpClient); } }; } else if (unsubscribeMethods.Mailto) { const { Subject = 'Unsubscribe', Body = 'Please, unsubscribe me', ToList = [] } = unsubscribeMethods.Mailto; // "address" by default, but will default to another address if this address cant send message const from = findSender(addresses, { AddressID: address.ID }, true); if (!from) { throw new Error('Unable to find from address'); } const { DisplayName: senderName, Email: senderAddress } = from; const sender = [senderName, senderName ? `<${senderAddress}>` : senderAddress].filter(isTruthy).join(' '); // senderName can be undefined const boldFrom = <strong key="email">{sender}</strong>; const toEmails = ToList.join(', '); modalContent = ( <> {c('Info') .jt`To unsubscribe from this mailing list, an email will be sent from ${boldFrom} with following details as defined by the sender of the newsletter:`} <br /> <Href href={getKnowledgeBaseUrl('/avoid-spam')}>{c('Link').t`Learn more`}</Href> <Row className="mt-4"> <Label className="cursor-default"> <span className="mr-2">{c('Info').t`Recipient: `}</span> </Label> <Field className="border bg-weak"> <div className="px-4 py-2 text-ellipsis" title={toEmails}> {toEmails} </div> </Field> </Row> <Row> <Label className="cursor-default"> <span className="mr-2">{c('Info').t`Subject: `}</span> </Label> <Field className="border bg-weak"> <div className="px-4 py-2 text-ellipsis" title={Subject}> {Subject} </div> </Field> </Row> <Row> <Label className="cursor-default"> <span className="mr-2">{c('Info').t`Body: `}</span> </Label> <Field className="border bg-weak"> <div className="px-4 py-2 text-ellipsis" title={Body}> {Body} </div> </Field> </Row> </> ); const inputMessage: PartialMessageState = { localID: generateUID('unsubscribe'), draftFlags: { autoSaveContacts: AUTO_SAVE_CONTACTS.DISABLED }, // Unsubscribe request should not save "to" address in contact list messageDocument: { plainText: Body }, data: { AddressID: from.ID, Subject, Sender: { Address: senderAddress, Name: senderName }, ToList: ToList.map((email: string) => ({ Address: email, Name: email, })), CCList: [], BCCList: [], MIMEType: MIME_TYPES.PLAINTEXT, Attachments: [], }, }; submit = async () => { const { cleanMessage, mapSendPrefs } = await sendVerification(inputMessage as MessageStateWithData, {}); await saveDraft(cleanMessage); const message = getMessage(cleanMessage.localID) as MessageStateWithData; cleanMessage.data = message.data; await sendMessage({ inputMessage: cleanMessage, mapSendPrefs, onCompose }); }; } const handleSubmit = async () => { unsubscribeModalProps.onClose(); if (needsSimpleLoginPresentation) { // We need to send a telemetry request when the user sees the SL unsubscribe modal handleSendTelemetryData(TelemetrySimpleLoginEvents.newsletter_unsubscribe); setUnsubscribedModalOpen(true); } await submit(); await api(markAsUnsubscribed([messageID])); await call(); createNotification({ text: c('Success').t`Mail list unsubscribed` }); }; const handleSimpleLoginModalOpen = () => { // We need to send a telemetry request when the user clicks on the hide-my-email button handleSendTelemetryData(TelemetrySimpleLoginEvents.simplelogin_modal_view, {}, true); unsubscribedModalProps.onClose(); setSimpleLoginModalOpen(true); }; if (loadingSimpleLoadingFeature) { return null; } /* * translator: * ${maskMyEmailButton} link to open the hide-my-email modal * Full sentence for reference: "Protect your email from being leaked to mailing lists or spammers with hide-my-email aliases." */ const maskMyEmailButton = ( <ButtonLike as="a" key="mask-my-email-button" className="ml-1" color="norm" shape="underline" onClick={handleSimpleLoginModalOpen} >{c('Action').t`hide-my-email aliases`}</ButtonLike> ); /* * translator: * ${maskMyEmailButton} link to open the hide-my-email modal * Full sentence for reference: "Protect your email from being leaked to mailing lists or spammers with hide-my-email." */ const unsubscribeSLtext = c('Info') .jt`Protect your email from being leaked to mailing lists or spammers with ${maskMyEmailButton}.`; 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"> <div className="flex-item-fluid flex flex-nowrap mb-2 md:mb-0"> <Icon name="envelope" className="mt-custom ml-0.5 flex-item-noshrink" style={{ marginTop: '0.375rem' }} /> <span className="px-1 flex flex-item-fluid flex-align-items-center">{c('Status') .t`This message is from a mailing list.`}</span> </div> <span className="flex-item-noshrink flex-align-items-start flex w-full md:w-auto pt-0.5"> <Tooltip title={c('Info').t`This message is from a mailing list.`}> <Button onClick={() => setUnsubscribeModalOpen(true)} size="small" color="weak" shape="outline" fullWidth className="rounded-sm" data-testid="unsubscribe-banner" disabled={loading || isUnsubscribed(message)} > {isUnsubscribed(message) ? c('Status').t`Unsubscribed` : loading ? c('Action').t`Unsubscribing` : c('Action').t`Unsubscribe`} </Button> </Tooltip> </span> <ModalTwo className="pm-modal--shorterLabels" {...unsubscribeModalProps}> <ModalTwoHeader title={c('Title').t`Unsubscribe`} /> <ModalTwoContent>{modalContent}</ModalTwoContent> <ModalTwoFooter> <Button onClick={unsubscribeModalProps.onClose}>{c('Action').t`Cancel`}</Button> <PrimaryButton onClick={() => withLoading(handleSubmit())} data-testid="unsubscribe-banner:submit" >{c('Action').t`Unsubscribe`}</PrimaryButton> </ModalTwoFooter> </ModalTwo> {renderUnsubscribedModal && ( <Prompt title={c('Title').t`Unsubscribe request sent`} buttons={[<Button onClick={unsubscribedModalProps.onClose}>{c('Action').t`Close`}</Button>]} {...unsubscribedModalProps} > <span>{unsubscribeSLtext}</span> </Prompt> )} {renderSimpleLoginModal && <SimpleLoginModal {...simpleLoginModalProps} />} </div> ); }; export default ExtraUnsubscribe;
3,611
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/calendar/CalendarWidget.scss
@import '~@proton/styles/scss/lib'; // Needed for placeholder-loading import @import '~@proton/styles/scss/specifics/placeholder-loading'; .calendar-widget { &-skeleton { &::before { @extend %item-loading-pseudo; @extend %placeholder-loading; } &--title { &::before { inline-size: 50%; } } &--date { &::before { inline-size: 60%; } } &--link { &::before { inline-size: 30%; } } &--details { &::before { inline-size: 45%; } } &--icon { &::before { block-size: 100%; inline-size: 100%; border-radius: 50%; } } } // Removing the margin of the last IconRow item .form--icon-labels:last-child { margin-block-end: 0; } }
3,612
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/calendar/EmailReminderWidget.test.tsx
import { BrowserRouter } from 'react-router-dom'; import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import { mocked } from 'jest-mock'; import { FeaturesProvider, useAddresses, useUserSettings } from '@proton/components'; import AuthenticationProvider from '@proton/components/containers/authentication/Provider'; import { CacheProvider } from '@proton/components/containers/cache'; import { DrawerProvider } from '@proton/components/hooks/drawer/useDrawer'; import useApi from '@proton/components/hooks/useApi'; import useGetCalendarEventRaw from '@proton/components/hooks/useGetCalendarEventRaw'; import useNotifications from '@proton/components/hooks/useNotifications'; import { CALENDAR_APP_NAME } from '@proton/shared/lib/constants'; import { addDays } from '@proton/shared/lib/date-fns-utc'; import { toUTCDate } from '@proton/shared/lib/date/timezone'; import createCache from '@proton/shared/lib/helpers/cache'; import { DRAWER_VISIBILITY, Nullable, UserSettings } from '@proton/shared/lib/interfaces'; import { VERIFICATION_STATUS } from '@proton/srp/lib/constants'; import { addressBuilder, calendarBuilder, calendarEventBuilder, messageBuilder, mockApiWithServer, mockNotifications, rest, server, veventBuilder, } from '@proton/testing'; import { refresh } from 'proton-mail/logic/contacts/contactsActions'; import { store } from 'proton-mail/logic/store'; import { ReduxProviderWrapper, authentication, tick } from '../../../../helpers/test/render'; import EmailReminderWidget from './EmailReminderWidget'; jest.mock('@proton/components/hooks/useNotifications'); jest.mock('@proton/components/hooks/useModals'); jest.mock('@proton/components/hooks/useApi'); jest.mock('@proton/components/hooks/useGetCalendarEventRaw'); jest.mock('@proton/components/hooks/useAddresses'); jest.mock('@proton/components/hooks/useUserSettings'); jest.mock('./EventReminderText', () => ({ __esModule: true, default: jest.fn(() => <span>EventReminderText</span>), })); jest.mock('@proton/components/components/calendarEventDateHeader/CalendarEventDateHeader', () => ({ __esModule: true, default: jest.fn(() => <span>DateHeader</span>), })); jest.mock('@proton/components/hooks/useConfig', () => () => ({ APP_NAME: 'proton-calendar', APP_VERSION: 'test' })); // Force narrow mode for "renders the widget and the necessary information" so that we can see the link // With the drawer we do not have a AppLink anymore, we will open Calendar in the drawer directly jest.mock('@proton/components/hooks/useActiveBreakpoint', () => () => { return { isNarrow: true, }; }); jest.mock('@proton/components/hooks/useUser', () => ({ __esModule: true, default: jest.fn(() => [ [ { ID: 'id', }, ], ]), useGetUser: jest.fn( () => () => Promise.resolve([ [ { ID: 'id', }, ], ]) ), })); jest.mock('@proton/components/hooks/useMailSettings', () => ({ useMailSettings: jest.fn(() => [{}, false]), })); const mockedUseApi = mocked(useApi); const mockedUseNotifications = mocked(useNotifications); const mockedUseGetCalendarEventRaw = mocked(useGetCalendarEventRaw); const mockedUseAddresses = mocked(useAddresses); const mockedUserSettings = mocked(useUserSettings); function renderComponent(overrides?: any) { window.history.pushState({}, 'Calendar', '/'); const Wrapper = ({ children }: any) => ( <AuthenticationProvider store={authentication}> <CacheProvider cache={createCache()}> <FeaturesProvider> <DrawerProvider> <ReduxProviderWrapper> <BrowserRouter>{children}</BrowserRouter> </ReduxProviderWrapper> </DrawerProvider> </FeaturesProvider> </CacheProvider> </AuthenticationProvider> ); return { ...render(<EmailReminderWidget message={messageBuilder({ overrides })} />, { wrapper: Wrapper }), skeleton: screen.queryByTestId('calendar-widget-widget-skeleton') as HTMLDivElement, }; } describe('EmailReminderWidget', () => { beforeAll(() => { // Initialize contactsMap store.dispatch(refresh({ contacts: [], contactGroups: [] })); server.listen(); }); afterAll(() => server.close()); beforeEach(() => { mockedUseApi.mockImplementation(() => mockApiWithServer); mockedUseNotifications.mockImplementation(() => mockNotifications); }); afterEach(() => { server.resetHandlers(); jest.clearAllMocks(); }); beforeEach(() => { mockedUseGetCalendarEventRaw.mockImplementation( () => () => Promise.resolve({ verificationStatus: VERIFICATION_STATUS.SIGNED_AND_VALID, hasDefaultNotifications: true, selfAddressData: { isOrganizer: false, isAttendee: false }, veventComponent: veventBuilder(), encryptionData: { encryptingAddressID: undefined, sharedSessionKey: undefined, calendarSessionKey: undefined, }, }) ); mockedUseAddresses.mockImplementation(() => [[addressBuilder({})], false, null]); mockedUserSettings.mockImplementation(() => [ { HideSidePanel: DRAWER_VISIBILITY.HIDE } as UserSettings, false, {} as Error, ]); server.use( rest.get(`/core/v4/features`, (req, res, ctx) => { return res.once(ctx.json({})); }) ); }); it('does not render anything when necessary headers are not present', () => { const { container } = renderComponent({ ParsedHeaders: {} }); expect(container).toBeEmptyDOMElement(); }); it('renders the widget and the necessary information', async () => { const { skeleton } = renderComponent(); expect(skeleton).toBeInTheDocument(); await waitFor(() => { expect(screen.getByText(/DateHeader/)).toBeInTheDocument(); }); await tick(); expect((screen.getByText(new RegExp(`Open in ${CALENDAR_APP_NAME}`)) as HTMLAnchorElement).href).toBe( `http://localhost/event?Action=VIEW&EventID=${encodeURIComponent( calendarEventBuilder().ID )}&CalendarID=${encodeURIComponent(calendarBuilder().ID)}&RecurrenceID=${encodeURIComponent( `${messageBuilder()?.ParsedHeaders['X-Pm-Calendar-Occurrence']}` )}` ); expect(screen.getByText(veventBuilder().summary!.value)).toBeInTheDocument(); expect(screen.getByText(veventBuilder().location!.value)).toBeInTheDocument(); expect(screen.getByText(/Organizer/)).toBeInTheDocument(); expect(screen.getByText(/EventReminderText/)).toBeInTheDocument(); fireEvent.click(screen.getByRole(/button/)); expect(screen.getByText(/visionary@proton.black/)).toBeInTheDocument(); expect(screen.getByText(/calendar@proton.black/)).toBeInTheDocument(); }); it('renders the widget when the event has been cancelled', async () => { server.use( rest.get(`/calendar/v1/:calendarId/events/:eventId`, (req, res, ctx) => { return res.once( ctx.json({ Event: calendarEventBuilder({ traits: 'canceled', }), }) ); }) ); const { skeleton } = renderComponent(); expect(skeleton).toBeInTheDocument(); await screen.findByText(/Event was canceled/); await tick(); expect(screen.queryByText(new RegExp(`Open in ${CALENDAR_APP_NAME}`))).toBeInTheDocument(); }); it('displays an error instead of the widget when there has been a breaking change', async () => { mockedUseGetCalendarEventRaw.mockImplementation( () => () => Promise.resolve({ verificationStatus: VERIFICATION_STATUS.SIGNED_AND_VALID, hasDefaultNotifications: true, selfAddressData: { isOrganizer: false, isAttendee: false }, veventComponent: veventBuilder({ overrides: { sequence: { value: 2 } } }), encryptionData: { encryptingAddressID: undefined, sharedSessionKey: undefined, calendarSessionKey: undefined, }, }) ); const { skeleton } = renderComponent(); expect(skeleton).toBeInTheDocument(); await screen.findByText(/Event was updated. This reminder is out-of-date./); expect(screen.queryByText(new RegExp(`Open in ${CALENDAR_APP_NAME}`))).not.toBeInTheDocument(); }); it('displays an error instead of the widget when the event does not exist anymore', async () => { server.use( rest.get(`/calendar/v1/:calendarId/events/:eventId`, (req, res, ctx) => { return res.once(ctx.status(404)); }) ); const { skeleton } = renderComponent(); expect(skeleton).toBeInTheDocument(); await screen.findByText(new RegExp('Event is no longer in your calendar')); expect(screen.queryByText(new RegExp(`Open in ${CALENDAR_APP_NAME}`))).not.toBeInTheDocument(); }); describe('decryption error', () => { beforeEach(() => { mockedUseGetCalendarEventRaw.mockImplementation( // eslint-disable-next-line prefer-promise-reject-errors () => () => Promise.reject({ message: 'DECRYPTION_FAILED' }) ); }); describe('needs user action', () => { async function displaysErrorWithoutButtonInsteadOfWidget() { const { skeleton } = renderComponent(); expect(skeleton).toBeInTheDocument(); await screen.findByText( /Event details are encrypted. Sign in again to restore Calendar and decrypt your data./ ); expect(screen.queryByText(new RegExp(`Open in ${CALENDAR_APP_NAME}`))).not.toBeInTheDocument(); expect(screen.queryByText(/Learn more/)).toBeInTheDocument(); expect(screen.queryByText(new RegExp(`Open ${CALENDAR_APP_NAME}`))).toBeInTheDocument(); } it('displays an error instead of the widget when the calendar needs a reset', async () => { server.use( rest.get(`/calendar/v1`, (req, res, ctx) => { return res.once( ctx.json({ Calendars: [calendarBuilder({ traits: 'resetNeeded' })], }) ); }) ); await displaysErrorWithoutButtonInsteadOfWidget(); }); it('displays an error instead of the widget when the calendar needs a passphrase update', async () => { const calendar = calendarBuilder({ traits: 'updatePassphrase' }); server.use( rest.get(`/calendar/v1`, (req, res, ctx) => { return res.once( ctx.json({ Calendars: [calendar], }) ); }), rest.get(`/calendar/v1/${calendar.ID}/keys/all`, (req, res, ctx) => { return res.once(ctx.json({})); }), rest.get(`/calendar/v1/${calendar.ID}/passphrases`, (req, res, ctx) => { return res.once(ctx.json({})); }), rest.get(`/calendar/v1/${calendar.ID}/members`, (req, res, ctx) => { return res.once(ctx.json({})); }) ); await displaysErrorWithoutButtonInsteadOfWidget(); }); }); describe('does not need user action', () => { it('displays an error instead of the widget when the event cannot be decrypted', async () => { const { skeleton } = renderComponent(); expect(skeleton).toBeInTheDocument(); await screen.findByText(new RegExp('Event details cannot be decrypted.')); expect(screen.queryByText(new RegExp(`Open in ${CALENDAR_APP_NAME}`))).not.toBeInTheDocument(); expect(screen.queryByText(new RegExp('Why not?'))).toBeInTheDocument(); }); }); }); async function errorAndNoWidget(skeleton: Nullable<HTMLDivElement>) { expect(skeleton).toBeInTheDocument(); await screen.findByText(/Event is no longer in your calendar/); expect(screen.queryByText(/DateHeader/)).not.toBeInTheDocument(); } it('displays an error and no widget if the `until` is expired', async () => { mockedUseGetCalendarEventRaw.mockImplementation( () => () => Promise.resolve({ hasDefaultNotifications: true, verificationStatus: VERIFICATION_STATUS.SIGNED_AND_VALID, selfAddressData: { isOrganizer: false, isAttendee: false }, veventComponent: { ...veventBuilder(), // override manually as overrides does not work for undefined properties in the builder rrule: { value: { freq: 'DAILY', until: { ...veventBuilder().dtstart.value, day: addDays(toUTCDate(veventBuilder().dtstart.value), -1).getDate(), }, }, }, }, encryptionData: { encryptingAddressID: undefined, sharedSessionKey: undefined, calendarSessionKey: undefined, }, }) ); const { skeleton } = renderComponent(); await errorAndNoWidget(skeleton); }); it('displays an error and no widget if the count is not matched', async () => { mockedUseGetCalendarEventRaw.mockImplementation( () => () => Promise.resolve({ hasDefaultNotifications: true, verificationStatus: VERIFICATION_STATUS.SIGNED_AND_VALID, selfAddressData: { isOrganizer: false, isAttendee: false }, veventComponent: { ...veventBuilder(), // override manually as overrides does not work for undefined properties in the builder rrule: { value: { freq: 'DAILY', count: 1, }, }, }, encryptionData: { encryptingAddressID: undefined, sharedSessionKey: undefined, calendarSessionKey: undefined, }, }) ); const { skeleton } = renderComponent({ ParsedHeaders: { ...messageBuilder().ParsedHeaders, 'X-Pm-Calendar-Occurrence': `${new Date(2050, 12, 12).getTime() / 1000}`, }, }); await errorAndNoWidget(skeleton); }); it('displays an error and no widget if the occurrence is in exdates (the occurrence has been removed from the chain)', async () => { server.use( rest.get(`/calendar/v1/events`, (req, res, ctx) => { return res.once( ctx.json({ Events: [calendarEventBuilder(), { Exdates: [123] }], }) ); }) ); const { skeleton } = renderComponent({ ParsedHeaders: { ...messageBuilder().ParsedHeaders, 'X-Pm-Calendar-Eventisrecurring': '1', 'X-Pm-Calendar-Occurrence': '123', 'X-Pm-Calendar-Calendarid': '321', }, }); await errorAndNoWidget(skeleton); }); it('displays an error and no widget if there are no events found with recurring header', async () => { server.use( rest.get(`/calendar/v1/events`, (req, res, ctx) => { return res.once( ctx.json({ Events: [], }) ); }) ); const { skeleton } = renderComponent({ ParsedHeaders: { ...messageBuilder().ParsedHeaders, 'X-Pm-Calendar-Eventisrecurring': '1', }, }); await errorAndNoWidget(skeleton); }); it('displays an error and no widget if there are no events found with the first event API call fails', async () => { server.use( rest.get(`/calendar/v1/:calendarId/events/:eventId`, () => { throw new Error('Anything can happen'); }) ); server.use( rest.get(`/calendar/v1/events`, (req, res, ctx) => { return res.once( ctx.json({ Events: [], }) ); }) ); const { skeleton } = renderComponent(); await errorAndNoWidget(skeleton); }); it('falls back to calling by uid in case the main api call fails', async () => { server.use( rest.get(`/calendar/v1/:calendarId/events/:eventId`, () => { throw new Error('Anything can happen'); }) ); server.use( rest.get(`/calendar/v1/events`, (req, res, ctx) => { return res.once( ctx.json({ Events: [calendarEventBuilder()], }) ); }) ); const { skeleton } = renderComponent(); expect(skeleton).toBeInTheDocument(); await screen.findByText(/DateHeader/); }); it('displays a generic error when both event API calls fail', async () => { server.use( rest.get(`/calendar/v1/:calendarId/events/:eventId`, () => { throw new Error('Anything can happen'); }) ); server.use( rest.get(`/calendar/v1/events`, () => { throw new Error('Anything can happen in the fallback'); }) ); const { skeleton } = renderComponent(); expect(skeleton).toBeInTheDocument(); await waitFor(() => expect(screen.queryByText(/DateHeader/)).not.toBeInTheDocument()); expect(mockedUseNotifications().createNotification).toHaveBeenCalledWith({ type: 'error', text: expect.stringContaining('Anything can happen in the fallback'), }); }); });
3,613
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/calendar/EmailReminderWidget.tsx
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { getUnixTime } from 'date-fns'; import { c } from 'ttag'; import { ButtonLike, Href } from '@proton/atoms'; import { AppLink, Banner, CalendarEventDateHeader, Icon, IconRow, useAddresses, useApi, useContactEmails, useGetAddressKeys, useGetCalendarEventRaw, useGetCalendars, useNotifications, } from '@proton/components'; import { BannerBackgroundColor } from '@proton/components/components/banner/Banner'; import CalendarSelectIcon from '@proton/components/components/calendarSelect/CalendarSelectIcon'; import { useLinkHandler } from '@proton/components/hooks/useLinkHandler'; import useIsMounted from '@proton/hooks/useIsMounted'; import { getEvent } from '@proton/shared/lib/api/calendars'; import { getPaginatedEventsByUID } from '@proton/shared/lib/calendar/api'; import { getCalendarWithReactivatedKeys, getDoesCalendarNeedUserAction, getVisualCalendars, } from '@proton/shared/lib/calendar/calendar'; import { getSelfAddressData } from '@proton/shared/lib/calendar/deserialize'; import { getDisplayTitle } from '@proton/shared/lib/calendar/helper'; import { getParticipant } from '@proton/shared/lib/calendar/mailIntegration/invite'; import { getOccurrencesBetween } from '@proton/shared/lib/calendar/recurrence/recurring'; import { restrictedCalendarSanitize } from '@proton/shared/lib/calendar/sanitize'; import urlify from '@proton/shared/lib/calendar/urlify'; import { getIsEventCancelled } from '@proton/shared/lib/calendar/veventHelper'; import { APPS, CALENDAR_APP_NAME, SECOND } from '@proton/shared/lib/constants'; import { toUTCDate } from '@proton/shared/lib/date/timezone'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { CalendarEvent, VcalVeventComponent, VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { getParsedHeadersFirstValue } from '@proton/shared/lib/mail/messages'; import { useContactsMap } from 'proton-mail/hooks/contact/useContacts'; import useMailModel from 'proton-mail/hooks/useMailModel'; import { getEventLocalStartEndDates } from '../../../../helpers/calendar/emailReminder'; import { getParticipantsList } from '../../../../helpers/calendar/invite'; import { MessageErrors } from '../../../../logic/messages/messagesTypes'; import EmailReminderWidgetSkeleton from './EmailReminderWidgetSkeleton'; import EventReminderBanner from './EventReminderBanner'; import ExtraEventParticipants from './ExtraEventParticipants'; import OpenInCalendarButton from './OpenInCalendarButton'; import useCalendarWidgetDrawerEvents from './useCalendarWidgetDrawerEvents'; import './CalendarWidget.scss'; const EVENT_NOT_FOUND_ERROR = 'EVENT_NOT_FOUND'; const DECRYPTION_ERROR = 'DECRYPTION_ERROR'; interface EmailReminderWidgetProps { message: Pick<Message, 'ID' | 'ParsedHeaders'>; errors?: MessageErrors; } const EmailReminderWidget = ({ message, errors }: EmailReminderWidgetProps) => { const mailSettings = useMailModel('MailSettings'); const eventReminderRef = useRef<HTMLDivElement>(null); const calendarIdHeader = getParsedHeadersFirstValue(message, 'X-Pm-Calendar-Calendarid'); const eventIdHeader = getParsedHeadersFirstValue(message, 'X-Pm-Calendar-Eventid'); const occurrenceHeader = getParsedHeadersFirstValue(message, 'X-Pm-Calendar-Occurrence'); const sequenceHeader = getParsedHeadersFirstValue(message, 'X-Pm-Calendar-Sequence'); const eventUIDHeader = getParsedHeadersFirstValue(message, 'X-Pm-Calendar-Eventuid'); const eventIsRecurringHeader = getParsedHeadersFirstValue(message, 'X-Pm-Calendar-Eventisrecurring'); const recurrenceIdHeader = getParsedHeadersFirstValue(message, 'X-Pm-Calendar-Recurrenceid'); const [vevent, setVevent] = useState<VcalVeventComponent>(); const [calendar, setCalendar] = useState<VisualCalendar>(); const [addresses] = useAddresses(); const [calendarEvent, setCalendarEvent] = useState<CalendarEvent>(); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState<React.ReactNode>(null); const [loadedWidget, setLoadedWidget] = useState<string>(); const [refreshCount, setRefreshCount] = useState<number>(0); const { createNotification } = useNotifications(); const api = useApi(); const contactsMap = useContactsMap(); const getCalendarEventRaw = useGetCalendarEventRaw(contactsMap); const contactEmails = useContactEmails()[0] || []; const getCalendars = useGetCalendars(); const getAddressKeys = useGetAddressKeys(); const isMounted = useIsMounted(); // setters don't need to be listed as dependencies in a callback const refresh = useCallback(() => { if (isMounted()) { setLoadedWidget(''); setRefreshCount((count) => count + 1); } }, []); const messageHasDecryptionError = !!errors?.decryption?.length; const { modal: linkModal } = useLinkHandler(eventReminderRef, mailSettings); useCalendarWidgetDrawerEvents({ messageID: message.ID, calendarEvent, refresh, }); useEffect(() => { void (async () => { if ( !calendarIdHeader || !eventIdHeader || !occurrenceHeader || !sequenceHeader || messageHasDecryptionError ) { // widget should not be displayed under these circumstances // clear up React states in case this component does not unmount when opening new emails setError(null); setLoadedWidget(''); return; } if (loadedWidget === message.ID) { return; } let calendarData; try { setError(null); setIsLoading(true); const occurrence = parseInt(`${occurrenceHeader}`, 10); const fetchEvent = async ( byUID = eventIsRecurringHeader === '1' ): Promise<{ Event: CalendarEvent }> => { // We need to fall back to UID search for // - recurring events, to detect deleted and modified occurrences // - when the calendar is changed, since the other route relies on the calendar id if (byUID) { const allEventsByUID = await getPaginatedEventsByUID({ api, uid: `${eventUIDHeader}`, recurrenceID: recurrenceIdHeader ? parseInt(recurrenceIdHeader, 10) : undefined, }); if (!allEventsByUID.length) { throw new Error(EVENT_NOT_FOUND_ERROR); } const sameCalendarEvents = allEventsByUID.filter( ({ CalendarID }) => CalendarID === calendarIdHeader ); const events = sameCalendarEvents.length ? sameCalendarEvents : allEventsByUID; if (events.find(({ Exdates }) => Exdates.includes(occurrence))) { throw new Error(EVENT_NOT_FOUND_ERROR); } const currentEvent = events.find(({ RecurrenceID }) => RecurrenceID === occurrence); if (currentEvent) { return { Event: currentEvent }; } const baseEvent = events.filter(({ RecurrenceID }) => !RecurrenceID)[0]; if (baseEvent) { return { Event: baseEvent }; } return { Event: events[0] }; } return api<{ Event: CalendarEvent }>({ ...getEvent(calendarIdHeader, eventIdHeader), silence: true, }).catch(() => { return fetchEvent(true); }); }; const [{ Event }, calendarsWithMembers = []] = await Promise.all([fetchEvent(), getCalendars()]); const calendars = getVisualCalendars(calendarsWithMembers); const calendar = calendars.find(({ ID }) => ID === Event.CalendarID); // We cannot be sure that setCalendar has finished when reaching the catch calendarData = calendar ? await getCalendarWithReactivatedKeys({ calendar, api, addresses, getAddressKeys }) : calendar; if (!isMounted()) { return; } setCalendar(calendarData); const { veventComponent } = await getCalendarEventRaw(Event).catch(() => { throw new Error(DECRYPTION_ERROR); }); if (!isMounted()) { return; } const { until, count } = veventComponent.rrule?.value || {}; const jsOccurrence = occurrence * SECOND; const isUntilExpired = until ? occurrence > getUnixTime(toUTCDate(until)) : false; const isCountExpired = count !== undefined ? !getOccurrencesBetween(veventComponent, jsOccurrence, jsOccurrence).length : false; if (isUntilExpired || isCountExpired) { throw new Error(EVENT_NOT_FOUND_ERROR); } setCalendarEvent(Event); setVevent(veventComponent); } catch (error: any) { if (!(error instanceof Error)) { createNotification({ type: 'error', text: 'Unknown error' }); } if (!isMounted()) { return; } if (calendarData && error.message === DECRYPTION_ERROR) { const shouldShowAction = getDoesCalendarNeedUserAction(calendarData); if (shouldShowAction) { const learnMoreLink = ( <Href href={getKnowledgeBaseUrl('/restoring-encrypted-calendar')} className="link align-baseline" key="learn-more" > {c('Action').t`Learn more`} </Href> ); setError( <Banner icon="key" action={ <ButtonLike as={AppLink} toApp={APPS.PROTONCALENDAR} to="/" color="norm" className="flex-item-noshrink" > <div className="flex flex-align-items-center"> <span className="mr-3">{c('Action').t`Open ${CALENDAR_APP_NAME}`}</span> <Icon name="arrow-out-square" /> </div> </ButtonLike> } > {c('Email reminder decryption error') .jt`Event details are encrypted. Sign in again to restore Calendar and decrypt your data. ${learnMoreLink}`} </Banner> ); return; } const whyNotLink = ( <Href href={getKnowledgeBaseUrl('/restoring-encrypted-calendar')} key="learn-more"> {c('Action').t`Why not?`} </Href> ); setError( <Banner icon="exclamation-circle" backgroundColor={BannerBackgroundColor.DANGER}> {c('Email reminder decryption error').jt`Event details cannot be decrypted. ${whyNotLink}`} </Banner> ); return; } if (error.message === EVENT_NOT_FOUND_ERROR) { setError( <Banner icon="exclamation-circle" backgroundColor={BannerBackgroundColor.DANGER}> {c('Email reminder error').t`Event is no longer in your calendar`} </Banner> ); return; } createNotification({ type: 'error', text: error.message }); } finally { if (isMounted()) { setIsLoading(false); setLoadedWidget(message.ID); } } })(); }, [calendarIdHeader, eventIdHeader, messageHasDecryptionError, message.ID, refreshCount]); const sanitizedAndUrlifiedLocation = useMemo(() => { const trimmedLocation = vevent?.location?.value?.trim(); if (!trimmedLocation) { return null; } return restrictedCalendarSanitize(urlify(trimmedLocation)); }, [vevent]); if (isLoading) { return <EmailReminderWidgetSkeleton />; } if (error && !messageHasDecryptionError) { return <>{error}</>; } if ( !calendarEvent || !vevent || !calendar || !calendarIdHeader || !eventIdHeader || !occurrenceHeader || !sequenceHeader || messageHasDecryptionError ) { return null; } const { summary, organizer, attendee, sequence } = vevent; const { FullDay } = calendarEvent; const { Color, Name } = calendar; const selfAddressData = getSelfAddressData({ organizer, attendees: attendee, addresses, }); const organizerParticipant = organizer ? getParticipant({ participant: organizer, contactEmails, ...selfAddressData }) : undefined; const participants = attendee ? attendee.map((participant) => getParticipant({ participant, contactEmails, ...selfAddressData })) : undefined; const participantsList = getParticipantsList(participants, organizerParticipant); const [startDate, endDate] = getEventLocalStartEndDates(calendarEvent, parseInt(occurrenceHeader, 10)); const isOutdated = (sequence?.value || 0) > parseInt(`${sequenceHeader}`, 10); const labelClassName = 'inline-flex pt-0.5'; return ( <div className="calendar-widget mb-3" ref={eventReminderRef}> <EventReminderBanner startDate={startDate} endDate={endDate} isAllDay={!!FullDay} isCanceled={getIsEventCancelled(calendarEvent)} isOutdated={isOutdated} /> {!isOutdated && ( <div className="rounded border bg-norm scroll-if-needed"> <div className="p-5"> <h2 className="h3 mb-1 text-bold">{getDisplayTitle(summary?.value)}</h2> <CalendarEventDateHeader className="text-lg mt-0 mb-3" startDate={startDate} endDate={endDate} isAllDay={!!FullDay} /> <OpenInCalendarButton linkString={c('Link to calendar event').t`Open in ${CALENDAR_APP_NAME}`} calendarID={calendarEvent?.CalendarID || calendarIdHeader} eventID={calendarEvent?.ID || eventIdHeader} recurrenceID={parseInt(occurrenceHeader, 10)} /> </div> <hr className="m-0" /> <div className="p-5"> <IconRow title={c('Label').t`Calendar`} icon={<CalendarSelectIcon color={Color} />} labelClassName={labelClassName} > <span className="text-break">{Name}</span> </IconRow> {!!sanitizedAndUrlifiedLocation && ( <IconRow title={c('Label').t`Location`} icon="map-pin" labelClassName={labelClassName}> <span dangerouslySetInnerHTML={{ __html: sanitizedAndUrlifiedLocation }} /> </IconRow> )} {!!participantsList.length && ( <IconRow title={c('Label').t`Participants`} icon="users" labelClassName={labelClassName}> <ExtraEventParticipants list={participantsList} /> </IconRow> )} </div> </div> )} {linkModal} </div> ); }; export default EmailReminderWidget;
3,614
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/calendar/EmailReminderWidgetSkeleton.tsx
import { IconRow } from '@proton/components'; export const EmailReminderWidgetSkeleton = () => ( <div data-testid="calendar-widget-widget-skeleton" className="mb-3"> <div className="bg-norm rounded border"> <div className="p-5"> <div className="h3 mb-1 calendar-widget-skeleton calendar-widget-skeleton--title" /> <p className="text-sm mt-0 mb-5 calendar-widget-skeleton calendar-widget-skeleton--date" /> <div className="calendar-widget-skeleton calendar-widget-skeleton--link" /> </div> <hr className="mt-3 mb-0" /> <div className="p-5"> <IconRow icon={ <div className="calendar-select-color calendar-widget-skeleton calendar-widget-skeleton--icon p-0" /> } labelClassName="inline-flex pt-1" > <div className="calendar-widget-skeleton calendar-widget-skeleton--details" /> </IconRow> </div> </div> </div> ); export default EmailReminderWidgetSkeleton;
3,615
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/calendar/EventReminderBanner.tsx
import { c } from 'ttag'; import { Banner } from '@proton/components'; import { BannerBackgroundColor } from '@proton/components/components/banner/Banner'; import EventReminderText from './EventReminderText'; interface Props { isAllDay: boolean; startDate: Date; endDate: Date; isOutdated?: boolean; isCanceled?: boolean; } const EventReminderBanner = ({ isAllDay, startDate, endDate, isOutdated, isCanceled }: Props) => { if (isCanceled) { return ( <Banner icon="exclamation-circle" backgroundColor={BannerBackgroundColor.WARNING}> {c('Email reminder out of date alert').t`Event was canceled`} </Banner> ); } if (isOutdated) { return ( <Banner icon="exclamation-circle" backgroundColor={BannerBackgroundColor.DANGER}> {c('Email reminder out of date alert').t`Event was updated. This reminder is out-of-date.`} </Banner> ); } return <EventReminderText startDate={startDate} endDate={endDate} isAllDay={isAllDay} />; }; export default EventReminderBanner;
3,616
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/calendar/EventReminderText.test.tsx
import { render, screen } from '@testing-library/react'; import EventReminderText, { EventReminderTextProps } from './EventReminderText'; function renderComponent(props?: Partial<EventReminderTextProps>) { const defaultProps = { startDate: new Date(1969, 11, 31, 8, 9, 10), endDate: new Date(1969, 11, 31, 8, 9, 10), isAllDay: false, }; return <EventReminderText {...defaultProps} {...props} />; } describe('EventReminderText', () => { const fakeNow = new Date(1969, 11, 31, 7, 58, 10); beforeEach(() => { jest.useFakeTimers().setSystemTime(fakeNow.getTime()); }); afterEach(() => { jest.clearAllTimers(); }); it('displays the time remaining until event', () => { const { rerender } = render(renderComponent()); expect(screen.getByText(/Event starts in 11 minutes/)).toBeInTheDocument(); rerender( renderComponent({ isAllDay: true, startDate: new Date(1970, 0, 1), endDate: new Date(1970, 0, 2), }) ); expect(screen.getByText(/Event is tomorrow/)).toBeInTheDocument(); rerender( renderComponent({ isAllDay: true, startDate: new Date(1970, 0, 1), endDate: new Date(1970, 0, 3), }) ); expect(screen.getByText(/Event starts tomorrow/)).toBeInTheDocument(); }); it('displays an alert for events starting now', () => { const { rerender } = render( renderComponent({ startDate: new Date(1969, 11, 31, 7, 58, 30), endDate: new Date(1969, 11, 31, 8, 9, 10), isAllDay: false, }) ); expect(screen.getByText(/Event starting now/)).toBeInTheDocument(); rerender( renderComponent({ startDate: new Date(1969, 11, 31, 7, 58, 0), endDate: new Date(1969, 11, 31, 8, 9, 10), isAllDay: false, }) ); expect(screen.getByText(/Event in progress/)).toBeInTheDocument(); }); it('displays an alert for events that already happened', () => { const { rerender } = render( renderComponent({ startDate: new Date(1969, 11, 31, 5, 9, 10), endDate: new Date(1969, 11, 31, 6, 8, 10), }) ); expect(screen.getByText(/Event already ended/)).toBeInTheDocument(); const endedEventCommonProps = { isAllDay: true, start: new Date(1969, 10, 11), }; rerender( renderComponent({ ...endedEventCommonProps, endDate: new Date(1969, 10, 12), }) ); expect(screen.getByText(/Event already ended/)).toBeInTheDocument(); }); it('displays an alert for ongoing events', () => { const { rerender } = render( renderComponent({ startDate: new Date(1969, 11, 31, 6, 58, 10), endDate: new Date(1969, 11, 31, 8, 58, 10), }) ); expect(screen.getByText(/Event in progress/)).toBeInTheDocument(); rerender( renderComponent({ isAllDay: true, startDate: new Date(1969, 11, 31), endDate: new Date(1970, 0, 1), }) ); expect(screen.getByText(/Event in progress/)).toBeInTheDocument(); }); it('does not display anything when out of range', () => { const { container, rerender } = render( renderComponent({ startDate: new Date(1969, 11, 31, 9, 9, 10), endDate: new Date(1969, 11, 31, 9, 9, 10), }) ); expect(container).toBeEmptyDOMElement(); rerender( renderComponent({ isAllDay: true, startDate: new Date(1970, 0, 2), endDate: new Date(1970, 0, 3), }) ); expect(container).toBeEmptyDOMElement(); }); });
3,617
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/calendar/EventReminderText.tsx
import { useEffect, useState } from 'react'; import { differenceInDays } from 'date-fns'; import { c, msgid } from 'ttag'; import { Banner } from '@proton/components'; import { BannerBackgroundColor } from '@proton/components/components/banner/Banner'; import { DAY, HOUR, MINUTE, SECOND } from '@proton/shared/lib/constants'; import { Nullable } from '@proton/shared/lib/interfaces'; export interface EventReminderTextProps { isAllDay: boolean; startDate: Date; endDate: Date; } const EventReminderText = ({ isAllDay, startDate, endDate }: EventReminderTextProps) => { const [now, setNow] = useState(new Date()); useEffect(() => { const interval = setInterval(() => { setNow(new Date()); }, 30 * SECOND); return () => { clearInterval(interval); }; }, [startDate]); const msUntilEvent = +startDate - +now; const hasStarted = msUntilEvent <= 0; const hasEnded = +endDate < +now; const getMessageInfo = (): Nullable<[BannerBackgroundColor, string]> => { if (hasEnded) { return [BannerBackgroundColor.WARNING, c('Calendar widget banner').t`Event already ended`]; } if (hasStarted) { return [BannerBackgroundColor.WARNING, c('Calendar widget banner').t`Event in progress`]; } if (!isAllDay && msUntilEvent < HOUR) { const minutesUntilEvent = Math.round(msUntilEvent / MINUTE); const text = minutesUntilEvent === 0 ? c('Email reminder banner').t`Event starting now` : c('Email reminder banner').ngettext( msgid`Event starts in ${minutesUntilEvent} minute`, `Event starts in ${minutesUntilEvent} minutes`, minutesUntilEvent ); return [BannerBackgroundColor.INFO, text]; } if (isAllDay && msUntilEvent < DAY) { const text = differenceInDays(endDate, startDate) === 1 ? c('Email reminder banner').t`Event is tomorrow` : c('Email reminder banner').t`Event starts tomorrow`; return [BannerBackgroundColor.INFO, text]; } return null; }; const messageInfo = getMessageInfo(); if (!messageInfo) { return null; } const [backgroundColor, text] = messageInfo; return ( <Banner backgroundColor={backgroundColor} icon="bell"> {text} </Banner> ); }; export default EventReminderText;
3,618
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/calendar/ExtraEvent.tsx
import { useCallback, useEffect, useState } from 'react'; import { c } from 'ttag'; import { Banner, InlineLinkButton, useApi } from '@proton/components'; import { BannerBackgroundColor } from '@proton/components/components/banner/Banner'; import { useLoading } from '@proton/hooks'; import useIsMounted from '@proton/hooks/useIsMounted'; import { EVENT_INVITATION_ERROR_TYPE, EventInvitationError, } from '@proton/shared/lib/calendar/icsSurgery/EventInvitationError'; import { Address, UserSettings } from '@proton/shared/lib/interfaces'; import { VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import { ContactEmail } from '@proton/shared/lib/interfaces/contacts'; import { GetAddressKeys } from '@proton/shared/lib/interfaces/hooks/GetAddressKeys'; import { GetCalendarEventRaw } from '@proton/shared/lib/interfaces/hooks/GetCalendarEventRaw'; import { GetCalendarInfo } from '@proton/shared/lib/interfaces/hooks/GetCalendarInfo'; import { GetCanonicalEmailsMap } from '@proton/shared/lib/interfaces/hooks/GetCanonicalEmailsMap'; import { getWeekStartsOn } from '@proton/shared/lib/settings/helper'; import { EventInvitation, InvitationModel, UPDATE_ACTION, getEventTimeStatus, getHasFullCalendarData, getHasInvitationIcs, getInitialInvitationModel, getInvitationHasEventID, getIsInvitationFromFuture, getIsInvitationOutdated, getIsPartyCrasher, getIsProtonInvite, getIsReinvite, } from '../../../../helpers/calendar/invite'; import { fetchEventInvitation, updateEventInvitation } from '../../../../helpers/calendar/inviteApi'; import { MessageStateWithData } from '../../../../logic/messages/messagesTypes'; import EmailReminderWidgetSkeleton from './EmailReminderWidgetSkeleton'; import ExtraEventButtons from './ExtraEventButtons'; import ExtraEventDetails from './ExtraEventDetails'; import ExtraEventHeader from './ExtraEventHeader'; import ExtraEventSummary from './ExtraEventSummary'; import ExtraEventTimeStatus from './ExtraEventTimeStatus'; import ExtraEventWarning from './ExtraEventWarning'; import useCalendarWidgetDrawerEvents from './useCalendarWidgetDrawerEvents'; import './CalendarWidget.scss'; const { DECRYPTION_ERROR, FETCHING_ERROR, UPDATING_ERROR, CANCELLATION_ERROR, EVENT_CREATION_ERROR, EVENT_UPDATE_ERROR, } = EVENT_INVITATION_ERROR_TYPE; interface Props { message: MessageStateWithData; invitationOrError: EventInvitation | EventInvitationError; canCreateCalendar: boolean; maxUserCalendarsDisabled: boolean; calendars: VisualCalendar[]; defaultCalendar?: VisualCalendar; contactEmails: ContactEmail[]; ownAddresses: Address[]; userSettings: UserSettings; getAddressKeys: GetAddressKeys; getCalendarInfo: GetCalendarInfo; getCalendarEventRaw: GetCalendarEventRaw; getCanonicalEmailsMap: GetCanonicalEmailsMap; } const ExtraEvent = ({ invitationOrError, message, calendars, defaultCalendar, canCreateCalendar, maxUserCalendarsDisabled, contactEmails, ownAddresses, userSettings, getAddressKeys, getCalendarInfo, getCalendarEventRaw, getCanonicalEmailsMap, }: Props) => { const [model, setModel] = useState<InvitationModel>(() => getInitialInvitationModel({ invitationOrError, message, contactEmails, ownAddresses, calendar: defaultCalendar, hasNoCalendars: calendars.length === 0, canCreateCalendar, maxUserCalendarsDisabled, }) ); const [loading, withLoading] = useLoading(true); const [retryCount, setRetryCount] = useState<number>(0); const isMounted = useIsMounted(); const api = useApi(); const { isOrganizerMode, invitationIcs, isPartyCrasher: isPartyCrasherIcs, pmData, invitationApi } = model; // setters don't need to be listed as dependencies in a callback const refresh = useCallback(() => { if (isMounted()) { setRetryCount((count) => count + 1); } }, []); const handleReloadWidget = () => { // set model to clean up error setModel( getInitialInvitationModel({ invitationOrError, message, contactEmails, ownAddresses, calendar: defaultCalendar, hasNoCalendars: calendars.length === 0, canCreateCalendar, maxUserCalendarsDisabled, }) ); refresh(); }; useCalendarWidgetDrawerEvents({ messageID: message.data.ID, calendarEvent: invitationApi?.calendarEvent, refresh, }); useEffect(() => { const run = async () => { if (!invitationIcs?.vevent) { return; } let invitationApi; let parentInvitationApi; let calendarData; let hasDecryptionError; let singleEditData; let reencryptionData; let reinviteEventID; let isPartyCrasher = isPartyCrasherIcs; const supportedInvitationIcs = invitationIcs; try { // check if an event with the same uid exists in the calendar already const { invitation, parentInvitation, calendarData: calData, calendarEvent, singleEditData: singleData, reencryptionData: reencryptData, hasDecryptionError: hasDecryptError, supportedRecurrenceId, } = await fetchEventInvitation({ veventComponent: invitationIcs.vevent, legacyUid: invitationIcs.legacyUid, api, getAddressKeys, getCalendarInfo, getCalendarEventRaw, calendars, defaultCalendar, message, contactEmails, ownAddresses, }); invitationApi = invitation; calendarData = calData; singleEditData = singleData; reencryptionData = reencryptData; hasDecryptionError = hasDecryptError; const isOutdated = getIsInvitationOutdated({ invitationIcs, invitationApi, isOrganizerMode }); const isFromFuture = getIsInvitationFromFuture({ invitationIcs, invitationApi, isOrganizerMode }); const isProtonInvite = getIsProtonInvite({ invitationIcs, calendarEvent, pmData }); const isReinvite = getIsReinvite({ invitationIcs, calendarEvent, isOrganizerMode, isOutdated }); if (isReinvite) { reinviteEventID = calendarEvent?.ID; // ignore existing partstat delete invitationApi?.attendee?.partstat; } if (parentInvitation) { parentInvitationApi = parentInvitation; } if (supportedRecurrenceId) { supportedInvitationIcs.vevent['recurrence-id'] = supportedRecurrenceId; } isPartyCrasher = await getIsPartyCrasher({ isOrganizerMode, invitationApi, calendarEvent, message, isPartyCrasherIcs, }); if (isMounted()) { setModel({ ...model, invitationIcs: supportedInvitationIcs, invitationApi, parentInvitationApi, isOutdated, isFromFuture, isProtonInvite, isReinvite, reinviteEventID, calendarData, singleEditData, reencryptionData, hasDecryptionError, isPartyCrasher, }); } } catch (error: any) { // if fetching fails, proceed as if there was no event in the database return; } if ( !invitationApi || !getInvitationHasEventID(invitationApi) || !getHasFullCalendarData(calendarData) || calendarData?.calendarNeedsUserAction || !isMounted() ) { // treat as a new invitation return; } // otherwise update the invitation if outdated try { const { action: updateAction, invitation: updatedInvitationApi } = await updateEventInvitation({ isOrganizerMode, invitationIcs: supportedInvitationIcs, invitationApi, api, getCanonicalEmailsMap, calendarData, singleEditData, pmData, message, contactEmails, ownAddresses, overwrite: !!hasDecryptionError, }); const newInvitationApi = updatedInvitationApi || invitationApi; const isOutdated = updateAction !== UPDATE_ACTION.NONE ? false : getIsInvitationOutdated({ invitationIcs: supportedInvitationIcs, invitationApi: newInvitationApi, isOrganizerMode, }); const isFromFuture = getIsInvitationFromFuture({ invitationIcs: supportedInvitationIcs, invitationApi: newInvitationApi, isOrganizerMode, }); const isProtonInvite = getIsProtonInvite({ invitationIcs: supportedInvitationIcs, calendarEvent: newInvitationApi.calendarEvent, pmData, }); const isReinvite = getIsReinvite({ invitationIcs: supportedInvitationIcs, calendarEvent: newInvitationApi.calendarEvent, isOrganizerMode, isOutdated, }); if (isMounted()) { setModel({ ...model, invitationIcs: supportedInvitationIcs, invitationApi: newInvitationApi, parentInvitationApi, calendarData, singleEditData, reencryptionData, timeStatus: getEventTimeStatus(newInvitationApi.vevent, Date.now()), isOutdated, isFromFuture, isProtonInvite, isReinvite, reinviteEventID, updateAction, hasDecryptionError, isPartyCrasher, }); } } catch (e: any) { if (isMounted()) { setModel({ ...model, invitationApi, parentInvitationApi, error: new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.UPDATING_ERROR), }); } } }; void withLoading(run()); }, [retryCount]); if (loading) { return <EmailReminderWidgetSkeleton />; } if (model.error && ![EVENT_CREATION_ERROR, EVENT_UPDATE_ERROR].includes(model.error.type)) { const { message } = model.error; const canTryAgain = [DECRYPTION_ERROR, FETCHING_ERROR, UPDATING_ERROR, CANCELLATION_ERROR].includes( model.error.type ); return ( <Banner backgroundColor={BannerBackgroundColor.DANGER} icon="exclamation-circle" action={ canTryAgain && ( <span className="flex-item-noshrink flex"> <InlineLinkButton onClick={handleReloadWidget}>{c('Action').t`Try again`}</InlineLinkButton> </span> ) } > {message} </Banner> ); } if (!getHasInvitationIcs(model)) { return null; } return ( <div className="calendar-widget mb-3"> <ExtraEventTimeStatus model={model} /> <div className="rounded border bg-norm scroll-if-needed"> <div className="p-5"> <ExtraEventSummary model={model} /> <ExtraEventHeader model={model} /> <ExtraEventWarning model={model} /> <ExtraEventButtons model={model} setModel={setModel} message={message} reloadWidget={handleReloadWidget} /> </div> <hr className="m-0" /> <ExtraEventDetails model={model} weekStartsOn={getWeekStartsOn(userSettings)} /> </div> </div> ); }; export default ExtraEvent;
3,619
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/calendar/ExtraEventAddParticipantButton.tsx
import { Dispatch, SetStateAction } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useDrawer, useNotifications } from '@proton/components'; import { useAddAttendees } from '@proton/components/containers/calendar/hooks'; import { useLoading } from '@proton/hooks'; import { reformatApiErrorMessage } from '@proton/shared/lib/calendar/api'; import { getAttendeeEmail, withPartstat } from '@proton/shared/lib/calendar/attendees'; import { ICAL_ATTENDEE_STATUS } from '@proton/shared/lib/calendar/constants'; import { getIsSuccessSyncApiResponse } from '@proton/shared/lib/calendar/helper'; import { AddAttendeeError } from '@proton/shared/lib/calendar/mailIntegration/AddAttendeeError'; import { APPS } from '@proton/shared/lib/constants'; import { postMessageToIframe } from '@proton/shared/lib/drawer/helpers'; import { DRAWER_EVENTS } from '@proton/shared/lib/drawer/interfaces'; import { omit } from '@proton/shared/lib/helpers/object'; import { RequireSome } from '@proton/shared/lib/interfaces'; import { SyncMultipleApiSuccessResponses } from '@proton/shared/lib/interfaces/calendar'; import { EncryptionPreferencesError } from '@proton/shared/lib/mail/encryptionPreferences'; import noop from '@proton/utils/noop'; import { InvitationModel, UPDATE_ACTION, getDisableButtons } from '../../../../helpers/calendar/invite'; import { useContactsMap } from '../../../../hooks/contact/useContacts'; interface Props { model: RequireSome<InvitationModel, 'invitationIcs' | 'invitationApi'>; setModel: Dispatch<SetStateAction<InvitationModel>>; } const ExtraEventAddParticipantButton = ({ model, setModel }: Props) => { const { createNotification } = useNotifications(); const [loading, withLoading] = useLoading(); const contactEmailsMap = useContactsMap(); const addAttendees = useAddAttendees(); const { appInView } = useDrawer(); const { calendarData, invitationIcs: { attendee: attendeeIcs }, invitationApi: { vevent: veventApi, calendarEvent, participants: participantsApi = [], organizer }, isOutdated, } = model; if (!attendeeIcs || getDisableButtons(model)) { // we do not want to display the button in the disabled-scenario cases return null; } const sendInvitation = !!isOutdated; const attendeeToSave = sendInvitation ? // reset the partstat as we will send a new invitation in this case withPartstat(attendeeIcs.vcalComponent, ICAL_ATTENDEE_STATUS.NEEDS_ACTION) : attendeeIcs.vcalComponent; const veventToSave = { ...veventApi, attendee: [...(veventApi.attendee || []), attendeeToSave], }; const handleSuccess = (response: SyncMultipleApiSuccessResponses) => { const invitationApiToSave = { vevent: veventToSave, calendarEvent: response.Response.Event, attendee: attendeeIcs, participants: [...participantsApi, attendeeIcs], organizer, }; createNotification({ type: 'success', text: sendInvitation ? c('Add participant to calendar event').t`Invitation sent and participant added` : c('Add participant to calendar event').t`Participant added`, }); setModel({ ...omit(model, ['error']), invitationApi: invitationApiToSave, hideLink: false, isPartyCrasher: false, updateAction: UPDATE_ACTION.NONE, }); }; const handleError = (message = '') => { createNotification({ type: 'error', text: message || c('Add participant to calendar event').t`Failed to add participant`, }); }; const handleAdd = async () => { if (calendarData?.isCalendarDisabled) { return noop(); } try { const response = await addAttendees({ eventComponent: veventToSave, calendarEvent, addedAttendees: [attendeeToSave], sendInvitation, contactEmailsMap, }); if (!getIsSuccessSyncApiResponse(response)) { return handleError(); } handleSuccess(response); // If the calendar app is opened in the drawer, // we want to call the calendar event manager to refresh the view if (appInView === APPS.PROTONCALENDAR) { postMessageToIframe( { type: DRAWER_EVENTS.CALL_CALENDAR_EVENT_MANAGER, payload: { calendarID: calendarEvent.CalendarID }, }, APPS.PROTONCALENDAR ); } } catch (e: any) { if (e instanceof EncryptionPreferencesError) { const email = getAttendeeEmail(attendeeToSave); const errorMessage = reformatApiErrorMessage(e.message); return handleError( c('Error sending calendar invitation').t`Cannot send invitation to ${email}. ${errorMessage}` ); } if (e instanceof AddAttendeeError) { return handleError(e.message); } handleError(); } }; const addParticipantText = c('Action').t`Add participant`; return ( <Button className="mb-2" color="weak" onClick={() => withLoading(handleAdd())} loading={loading} title={addParticipantText} > {addParticipantText} </Button> ); }; export default ExtraEventAddParticipantButton;
3,620
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/calendar/ExtraEventAlert.tsx
import { c } from 'ttag'; import { Alert, SettingsLink } from '@proton/components'; import { ICAL_METHOD } from '@proton/shared/lib/calendar/constants'; import { getCalendarsSettingsPath } from '@proton/shared/lib/calendar/settingsRoutes'; import { getIsEventCancelled } from '@proton/shared/lib/calendar/veventHelper'; import { APPS, BRAND_NAME } from '@proton/shared/lib/constants'; import { RequireSome } from '@proton/shared/lib/interfaces/utils'; import { InvitationModel } from '../../../../helpers/calendar/invite'; interface Props { model: RequireSome<InvitationModel, 'invitationIcs'>; } const ExtraEventAlert = ({ model }: Props) => { const { isOrganizerMode, isImport, hasMultipleVevents, isOutdated, isPartyCrasher, hasProtonUID, invitationIcs: { method, vevent: veventIcs, attendee: attendeeIcs }, invitationApi, calendarData, isAddressActive, canCreateCalendar, maxUserCalendarsDisabled, hasNoCalendars, } = model; const isCancel = method === ICAL_METHOD.CANCEL; const alertClassName = 'my-4 text-break'; /* Depending on the case, we want to display a different alert message in the ICS widget. * For party crashers, we have two scenarios: * 1- When we have a party crasher invitation from an internal organizer, the condition is blocking. * The party crasher alert message should be more important than other types of messages. * 2- However, since we can accept party crasher invitations from an external organizers, * the alert message will be less important than other messages (address is disabled, calendar limit reached, etc...) */ const isPartyCrasherBlocking = isPartyCrasher && hasProtonUID; const isPartyCrasherNonBlocking = isPartyCrasher && !hasProtonUID; if (isImport && hasMultipleVevents) { return null; } /** * organizer mode */ if (isOrganizerMode) { if (method !== ICAL_METHOD.REPLY || !attendeeIcs?.partstat || !invitationApi) { return null; } if (calendarData?.isCalendarDisabled) { const text = isOutdated || isPartyCrasher ? c('Link').t`Re-enable the address linked to this calendar to manage your invitation.` : c('Link').t`Re-enable the address linked to this calendar to update your invitation.`; return ( <Alert className={alertClassName} type="warning"> <span className="mr-2">{c('Info').t`This invitation is saved in a disabled calendar.`}</span> <span> <SettingsLink path="/identity-addresses" app={APPS.PROTONMAIL}> {text} </SettingsLink> </span> </Alert> ); } if (isPartyCrasher && !veventIcs['recurrence-id']) { const participantName = attendeeIcs.displayName; return ( <Alert className={alertClassName} type="warning"> {c('Calendar invite info').t`${participantName} is not in the participants list.`} </Alert> ); } return null; } /** * attendee mode * There are priorities on the message we want to display in attendee mode. * 1- The user is a party crasher of the invitation and that the invitation is internal * 2- Invitation is outdated * 3- For unanswered invitations * a. Invitation is cancelled * b. The user address is inactive, and it's not an import * c. There is no calendar data available * i. User has no calendars * ii. User calendars are all using disabled addresses, but has not reached the calendar number limit * iii. User calendars are all using disabled addresses, but has reached the calendar number limit * 4- The user is a party crasher of the invitation and the invitation is external */ if (isPartyCrasherBlocking) { // In case the user is a party crasher, we want to display a different message if organizer is internal or external. // If organizer is internal, we cannot accept the event for now. // But we can for external organizers. return ( <Alert className={alertClassName} type="warning"> {c('Calendar invite info') .t`You cannot respond to ${BRAND_NAME} invites if you're not on the participants list at the moment.`} </Alert> ); } // attendee can take no action for outdated invitations if (isOutdated) { return null; } // the invitation is unanswered if (!invitationApi) { if (isCancel) { return null; } if (!isAddressActive && !isImport) { return ( <Alert className={alertClassName} type="warning"> <span className="mr-2">{c('Info').t`You cannot reply from the invited address.`}</span> <span> <SettingsLink path="/identity-addresses" app={APPS.PROTONMAIL}> {c('Link').t`Enable your address to answer this invitation.`} </SettingsLink> </span> </Alert> ); } if (!calendarData) { // no default calendar was found, which means that either the user has no calendar, // all user calendars are disabled, or no calendar is active yet if (hasNoCalendars) { return null; } if (canCreateCalendar) { return ( <Alert className={alertClassName} type="warning"> <span className="mr-2">{c('Info').t`All your calendars are disabled.`}</span> <SettingsLink path={getCalendarsSettingsPath()} app={APPS.PROTONCALENDAR}> {c('Link').t`Create a calendar linked to an active email address.`} </SettingsLink> </Alert> ); } if (maxUserCalendarsDisabled) { return ( <Alert className={alertClassName} type="warning"> <span className="mr-2">{c('Info').t`All your calendars are disabled.`}</span> <span className="mr-2"> <SettingsLink path="/identity-addresses" app={APPS.PROTONMAIL}> {c('Link').t`Enable an email address linked to one of your calendars.`} </SettingsLink> </span> <span> <SettingsLink path={getCalendarsSettingsPath()} app={APPS.PROTONCALENDAR}> {c('Link') .t`Or you can delete one of your calendars and create a new one linked to an active email address.`} </SettingsLink> </span> </Alert> ); } } if (!isPartyCrasherNonBlocking) { return null; } } // for import we do not care about the state of the calendar where the event was saved if (isImport) { return null; } // the invitation has been answered if (invitationApi && getIsEventCancelled(invitationApi.calendarEvent)) { return null; } if (!isAddressActive) { if (isCancel) { return null; } return ( <Alert className={alertClassName} type="warning"> <span className="mr-2">{c('Info').t`You cannot reply from the invited address.`}</span> <span> <SettingsLink path="/identity-addresses" app={APPS.PROTONMAIL}> {c('Link').t`Enable your address again to modify your answer.`} </SettingsLink> </span> </Alert> ); } if (calendarData?.isCalendarDisabled) { const text = isCancel ? c('Link').t`Enable the email address linked to the disabled calendar to cancel the event.` : c('Link').t`Enable the email address linked to the disabled calendar to modify your answer.`; return ( <Alert className={alertClassName} type="warning"> <span className="mr-2">{c('Info').t`This invitation is saved in a disabled calendar.`}</span> <span> <SettingsLink path="/identity-addresses" app={APPS.PROTONMAIL}> {text} </SettingsLink> </span> </Alert> ); } if (isPartyCrasherNonBlocking) { return ( <Alert className={alertClassName} type="warning"> {c('Calendar invite info').t`Your email address is not in the original participants list.`} </Alert> ); } return null; }; export default ExtraEventAlert;
3,621
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/calendar/ExtraEventAttendeeButtons.tsx
import { Dispatch, SetStateAction, useCallback } from 'react'; import { c } from 'ttag'; import { CalendarInviteButtons, InlineLinkButton, Loader, useDrawer, useNotifications } from '@proton/components'; import Banner, { BannerBackgroundColor } from '@proton/components/components/banner/Banner'; import { useLoading } from '@proton/hooks'; import { getApiErrorMessage } from '@proton/shared/lib/api/helpers/apiErrorHelper'; import { reformatApiErrorMessage } from '@proton/shared/lib/calendar/api'; import { ICAL_ATTENDEE_STATUS, ICAL_METHOD } from '@proton/shared/lib/calendar/constants'; import { EVENT_INVITATION_ERROR_TYPE, EventInvitationError, getErrorMessage, } from '@proton/shared/lib/calendar/icsSurgery/EventInvitationError'; import { getAttendeePartstat, getAttendeeToken } from '@proton/shared/lib/calendar/vcalHelper'; import { APPS } from '@proton/shared/lib/constants'; import { postMessageToIframe } from '@proton/shared/lib/drawer/helpers'; import { DRAWER_EVENTS } from '@proton/shared/lib/drawer/interfaces'; import { ApiError } from '@proton/shared/lib/fetch/ApiError'; import { omit } from '@proton/shared/lib/helpers/object'; import { wait } from '@proton/shared/lib/helpers/promise'; import { Participant, SavedInviteData } from '@proton/shared/lib/interfaces/calendar'; import { RequireSome } from '@proton/shared/lib/interfaces/utils'; import { EncryptionPreferencesError } from '@proton/shared/lib/mail/encryptionPreferences'; import { RE_PREFIX, formatSubject } from '@proton/shared/lib/mail/messages'; import { InvitationModel, UPDATE_ACTION, getDisableButtons } from '../../../../helpers/calendar/invite'; import useInviteButtons from '../../../../hooks/useInviteButtons'; import { MessageState } from '../../../../logic/messages/messagesTypes'; const { EVENT_CREATION_ERROR, EVENT_UPDATE_ERROR } = EVENT_INVITATION_ERROR_TYPE; interface Props { model: RequireSome<InvitationModel, 'invitationIcs'>; setModel: Dispatch<SetStateAction<InvitationModel>>; message: MessageState; reloadWidget: () => void; } const ExtraEventAttendeeButtons = ({ model, setModel, message, reloadWidget }: Props) => { const { invitationIcs, invitationIcs: { method }, invitationApi, calendarData, pmData, singleEditData, reencryptionData, isProtonInvite, isReinvite, error, hasDecryptionError, reinviteEventID, } = model; const partstat = invitationApi?.attendee?.partstat || ICAL_ATTENDEE_STATUS.NEEDS_ACTION; const { attendee } = invitationApi || invitationIcs; const { organizer } = invitationApi || invitationIcs; const [loadingRetry, withLoadingRetry] = useLoading(); const { createNotification } = useNotifications(); const { appInView } = useDrawer(); const handleEmailSuccess = () => { createNotification({ type: 'success', text: c('Reply to calendar invitation').t`Answer sent`, }); }; const handleCreateEventSuccess = () => { createNotification({ type: 'success', text: c('Reply to calendar invitation').t`Calendar event created`, }); }; const handleUpdateEventSuccess = () => { createNotification({ type: 'success', text: c('Reply to calendar invitation').t`Calendar event updated`, }); }; const handleSuccess = useCallback( ({ savedEvent, savedVevent, savedVcalAttendee }: SavedInviteData) => { if (!attendee) { throw new Error('Missing attendee'); } const savedAttendee: Participant = { ...attendee, vcalComponent: savedVcalAttendee, partstat: getAttendeePartstat(savedVcalAttendee), token: getAttendeeToken(savedVcalAttendee), }; const invitationApiToSave = { ...invitationApi, vevent: savedVevent, calendarEvent: savedEvent, attendee: savedAttendee, organizer, }; const newModel = { ...omit(model, ['error', 'reinviteEventID', 'reencryptionData']), invitationApi: invitationApiToSave, hideSummary: true, hideLink: false, updateAction: UPDATE_ACTION.NONE, }; setModel(newModel); // If the calendar app is opened in the drawer, // we want to call the calendar event manager to refresh the view if (appInView === APPS.PROTONCALENDAR) { postMessageToIframe( { type: DRAWER_EVENTS.CALL_CALENDAR_EVENT_MANAGER, payload: { calendarID: savedEvent.CalendarID }, }, APPS.PROTONCALENDAR ); } }, [invitationApi, attendee, organizer, appInView] ); const handleUnexpectedError = () => { setModel({ ...model, error: new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.UNEXPECTED_ERROR), }); }; const handleCreateEventError = (partstat: ICAL_ATTENDEE_STATUS, isProtonInvite: boolean, error?: any) => { const errorMessage = error?.data?.Error || error?.message || 'Creating calendar event failed'; createNotification({ type: 'error', text: errorMessage, }); if (error instanceof EventInvitationError && error.type === EVENT_INVITATION_ERROR_TYPE.UNEXPECTED_ERROR) { handleUnexpectedError(); return; } setModel({ ...model, hideLink: true, error: new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.EVENT_CREATION_ERROR, { partstat, isProtonInvite, }), }); }; const handleUpdateEventError = ( partstat: ICAL_ATTENDEE_STATUS, timestamp: number, isProtonInvite: boolean, error?: any ) => { const errorMessage = error?.data?.Error || error?.message || 'Updating calendar event failed'; createNotification({ type: 'error', text: errorMessage, }); if (error instanceof EventInvitationError && error.type === EVENT_INVITATION_ERROR_TYPE.UNEXPECTED_ERROR) { handleUnexpectedError(); return; } setModel({ ...model, hideLink: true, error: new EventInvitationError(EVENT_INVITATION_ERROR_TYPE.EVENT_UPDATE_ERROR, { partstat, timestamp, isProtonInvite, }), }); }; const handleReencryptEventError = (error: Error) => { reloadWidget(); // A retry should fix this error, so we display to the user a custom message asking to retry createNotification({ type: 'error', text: c('Reply to calendar invitation').t`Re-encrypting invitation failed. Please try again.`, }); // we console.log the real error in case there's a systematic problem const errorMessage = error instanceof ApiError ? getApiErrorMessage(error) : error.message; console.error(errorMessage); }; const handleEmailError = (error: Error) => { if (error instanceof EncryptionPreferencesError) { const errorMessage = reformatApiErrorMessage(error.message); createNotification({ type: 'error', text: c('Reply to calendar invitation').t`Cannot send to organizer address: ${errorMessage}`, }); return; } createNotification({ type: 'error', text: c('Reply to calendar invitation').t`Answering invitation failed`, }); }; const buttonsDisabled = getDisableButtons(model); const actions = useInviteButtons({ veventIcs: invitationIcs.vevent, veventApi: invitationApi?.vevent, calendarEvent: invitationApi?.calendarEvent, attendee, organizer, subject: formatSubject(message.data?.Subject, RE_PREFIX), messageID: message.data?.ID, calendarData, pmData: isProtonInvite || (pmData && isReinvite) ? pmData : undefined, singleEditData, reencryptionData, onEmailSuccess: handleEmailSuccess, onCreateEventSuccess: handleCreateEventSuccess, onUpdateEventSuccess: handleUpdateEventSuccess, onEmailError: handleEmailError, onCreateEventError: handleCreateEventError, onUpdateEventError: handleUpdateEventError, onReencryptEventError: handleReencryptEventError, onSuccess: handleSuccess, onUnexpectedError: handleUnexpectedError, disabled: buttonsDisabled, overwrite: !!hasDecryptionError, reinviteEventID, }); if (error && [EVENT_CREATION_ERROR, EVENT_UPDATE_ERROR].includes(error.type)) { const { partstat, timestamp, isProtonInvite } = error; const { retryCreateEvent, retryUpdateEvent } = actions; const isUpdate = error.type === EVENT_UPDATE_ERROR; const message = getErrorMessage(error.type, { ...error }); const handleRetry = () => { if (!partstat) { return withLoadingRetry(wait(0)); } if (!isUpdate) { return retryCreateEvent({ partstat, isProtonInvite: !!isProtonInvite }); } if (timestamp !== undefined) { return retryUpdateEvent({ partstat, timestamp, isProtonInvite: !!isProtonInvite, calendarEvent: invitationApi?.calendarEvent, }); } return withLoadingRetry(wait(0)); }; if (loadingRetry) { return <Loader className="mx-auto flex my-4 " />; } return ( <Banner backgroundColor={BannerBackgroundColor.DANGER} icon="exclamation-circle" action={ <span className="flex-item-noshrink flex"> <InlineLinkButton onClick={handleRetry} className="text-underline color-inherit"> {c('Action').t`Try again`} </InlineLinkButton> </span> } > {message} </Banner> ); } if (method === ICAL_METHOD.REQUEST && partstat) { return ( <div className="mt-6 flex flex-align-items-center"> <div className="text-bold mr-4">{c('Calendar invite buttons label').t`Attending?`}</div> <CalendarInviteButtons actions={actions} partstat={partstat} disabled={buttonsDisabled} /> </div> ); } return null; }; export default ExtraEventAttendeeButtons;
3,622
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/calendar/ExtraEventButtons.tsx
import { Dispatch, SetStateAction } from 'react'; import { RequireSome } from '@proton/shared/lib/interfaces/utils'; import { InvitationModel, getDoNotDisplayButtons } from '../../../../helpers/calendar/invite'; import { getCalendarEventLink } from '../../../../helpers/calendar/inviteLink'; import { MessageState } from '../../../../logic/messages/messagesTypes'; import ExtraEventAlert from './ExtraEventAlert'; import ExtraEventAttendeeButtons from './ExtraEventAttendeeButtons'; import ExtraEventImportButton from './ExtraEventImportButton'; import ExtraEventOrganizerButtons from './ExtraEventOrganizerButtons'; interface Props { model: RequireSome<InvitationModel, 'invitationIcs'>; setModel: Dispatch<SetStateAction<InvitationModel>>; message: MessageState; reloadWidget: () => void; } const ExtraEventButtons = ({ model, setModel, message, reloadWidget }: Props) => { const { isImport, isOrganizerMode } = model; const inviteButtons = isOrganizerMode ? ( <ExtraEventOrganizerButtons model={model} setModel={setModel} /> ) : ( <ExtraEventAttendeeButtons model={model} setModel={setModel} message={message} reloadWidget={reloadWidget} /> ); const importButton = <ExtraEventImportButton model={model} setModel={setModel} />; const buttons = isImport ? importButton : inviteButtons; const displayButtons = getDoNotDisplayButtons(model) ? null : buttons; const link = getCalendarEventLink(model); return ( <> {link && <div className="mb-2">{link}</div>} <ExtraEventAlert model={model} /> {displayButtons} </> ); }; export default ExtraEventButtons;
3,623
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/calendar/ExtraEventDetails.tsx
import { useMemo, useRef } from 'react'; import { c } from 'ttag'; import { IconRow } from '@proton/components'; import CalendarSelectIcon from '@proton/components/components/calendarSelect/CalendarSelectIcon'; import { useLinkHandler } from '@proton/components/hooks/useLinkHandler'; import { ICAL_METHOD } from '@proton/shared/lib/calendar/constants'; import { getFrequencyString } from '@proton/shared/lib/calendar/recurrence/getFrequencyString'; import { restrictedCalendarSanitize } from '@proton/shared/lib/calendar/sanitize'; import urlify from '@proton/shared/lib/calendar/urlify'; import { WeekStartsOn } from '@proton/shared/lib/date-fns-utc/interface'; import { dateLocale } from '@proton/shared/lib/i18n'; import { RequireSome } from '@proton/shared/lib/interfaces/utils'; import useMailModel from 'proton-mail/hooks/useMailModel'; import { InvitationModel, getParticipantsList } from '../../../../helpers/calendar/invite'; import ExtraEventParticipants from './ExtraEventParticipants'; const { REFRESH, REPLY } = ICAL_METHOD; interface Props { model: RequireSome<InvitationModel, 'invitationIcs'>; weekStartsOn: WeekStartsOn; } const ExtraEventDetails = ({ model, weekStartsOn }: Props) => { const mailSettings = useMailModel('MailSettings'); const eventDetailsRef = useRef<HTMLDivElement>(null); const { isImport, hasMultipleVevents, calendarData, invitationIcs, invitationIcs: { method }, invitationApi, } = model; const displayApiDetails = [REFRESH, REPLY].includes(method); const { vevent, organizer, participants } = invitationApi && displayApiDetails ? invitationApi : invitationIcs; const { rrule, dtstart } = vevent; const { modal: linkModal } = useLinkHandler(eventDetailsRef, mailSettings); const trimmedLocation = vevent.location?.value?.trim(); const sanitizedAndUrlifiedLocation = useMemo( () => restrictedCalendarSanitize(urlify(trimmedLocation || '')), [trimmedLocation] ); const frequencyString = rrule ? getFrequencyString(rrule.value, dtstart, { weekStartsOn, locale: dateLocale, }) : undefined; const calendar = calendarData?.calendar; const participantsList = getParticipantsList(participants, organizer); if (isImport && hasMultipleVevents) { return null; } return ( <div className="p-5" ref={eventDetailsRef}> {!!frequencyString && ( <IconRow title={c('Label').t`Frequency`} icon="arrows-rotate" labelClassName="inline-flex pt-0.5"> {frequencyString} </IconRow> )} {!!calendar && ( <IconRow title={c('Label').t`Calendar`} icon={<CalendarSelectIcon color={calendar.Color} />} labelClassName="inline-flex pt-0.5" > <span className="text-break">{calendar.Name}</span> </IconRow> )} {!!trimmedLocation && ( <IconRow title={c('Label').t`Location`} icon="map-pin" labelClassName="inline-flex pt-0.5"> <span dangerouslySetInnerHTML={{ __html: sanitizedAndUrlifiedLocation }} /> </IconRow> )} {!!participantsList.length && ( <IconRow title={c('Label').t`Participants`} icon="users" labelClassName="inline-flex pt-0.5"> <ExtraEventParticipants list={participantsList} /> </IconRow> )} {linkModal} </div> ); }; export default ExtraEventDetails;
3,624
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/calendar/ExtraEventHeader.tsx
import { c } from 'ttag'; import CalendarEventDateHeader from '@proton/components/components/calendarEventDateHeader/CalendarEventDateHeader'; import { ICAL_ATTENDEE_ROLE, ICAL_METHOD } from '@proton/shared/lib/calendar/constants'; import { getDisplayTitle } from '@proton/shared/lib/calendar/helper'; import { getDtendProperty, propertyToLocalDate } from '@proton/shared/lib/calendar/vcalConverter'; import { getIsPropertyAllDay } from '@proton/shared/lib/calendar/vcalHelper'; import { RequireSome } from '@proton/shared/lib/interfaces'; import { InvitationModel } from '../../../../helpers/calendar/invite'; const { DECLINECOUNTER, REPLY, REFRESH } = ICAL_METHOD; interface Props { model: RequireSome<InvitationModel, 'invitationIcs'>; } const ExtraEventHeader = ({ model }: Props) => { const { invitationIcs, invitationIcs: { method, attendee: attendeeIcs }, invitationApi, isOutdated, isPartyCrasher, isImport, hasMultipleVevents, } = model; const displayApiDetails = [REFRESH, DECLINECOUNTER, REPLY].includes(method); const { vevent } = invitationApi && displayApiDetails ? invitationApi : invitationIcs; const { dtstart, summary } = vevent; const dtend = getDtendProperty(vevent); const isAllDay = getIsPropertyAllDay(dtstart); const startDate = propertyToLocalDate(dtstart); const endDate = propertyToLocalDate(dtend); const title = isImport && hasMultipleVevents ? invitationIcs?.fileName || '' : getDisplayTitle(summary?.value); const canShowOptionalHeader = method === ICAL_METHOD.REQUEST && !isOutdated && !isPartyCrasher && !isImport; const optionalHeader = canShowOptionalHeader && attendeeIcs?.role === ICAL_ATTENDEE_ROLE.OPTIONAL ? c('Calendar invite info').t`(Attendance optional)` : null; return ( <div className="mb-3"> <div className="h3 mb-1 text-bold">{title}</div> {!hasMultipleVevents && ( <> <CalendarEventDateHeader className="text-lg" startDate={startDate} endDate={endDate} isAllDay={isAllDay} data-testid="extra-event-date-header" /> {optionalHeader && <div className="text-sm color-weak">{optionalHeader}</div>} </> )} </div> ); }; export default ExtraEventHeader;
3,625
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/calendar/ExtraEventImportButton.tsx
import { Dispatch, SetStateAction, useCallback } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useDrawer, useNotifications } from '@proton/components'; import { useAddEvents } from '@proton/components/containers/calendar/hooks'; import { useLoading } from '@proton/hooks'; import { getVeventWithDefaultCalendarAlarms } from '@proton/shared/lib/calendar/mailIntegration/invite'; import { APPS, CALENDAR_APP_NAME } from '@proton/shared/lib/constants'; import { postMessageToIframe } from '@proton/shared/lib/drawer/helpers'; import { DRAWER_EVENTS } from '@proton/shared/lib/drawer/interfaces'; import { omit } from '@proton/shared/lib/helpers/object'; import { RequireSome } from '@proton/shared/lib/interfaces'; import { ImportedEvent } from '@proton/shared/lib/interfaces/calendar'; import noop from '@proton/utils/noop'; import { InvitationModel, UPDATE_ACTION, getDisableButtons } from '../../../../helpers/calendar/invite'; interface Props { model: RequireSome<InvitationModel, 'invitationIcs'>; setModel: Dispatch<SetStateAction<InvitationModel>>; } const ExtraEventImportButton = ({ model, setModel }: Props) => { const [loading, withLoading] = useLoading(); const addEvents = useAddEvents(); const { createNotification } = useNotifications(); const { appInView } = useDrawer(); const { calendarData, invitationIcs: { vevent }, } = model; const handleSuccess = useCallback(([{ response, component }]: ImportedEvent[]) => { const invitationApiToSave = { vevent: component, calendarEvent: response.Response.Event, }; createNotification({ type: 'success', text: c('Import ICS file from Mail').t`Calendar event created`, }); setModel({ ...omit(model, ['error']), invitationApi: invitationApiToSave, hideSummary: true, hideLink: false, updateAction: UPDATE_ACTION.NONE, }); }, []); const handleError = useCallback(() => { createNotification({ type: 'error', text: c('Import ICS file from Mail').t`Creating calendar event failed`, }); }, []); const handleAdd = async () => { const { calendar, isCalendarDisabled, calendarSettings } = calendarData || {}; if (!calendar || isCalendarDisabled || !calendarSettings) { return noop(); } try { const veventWithAlarms = getVeventWithDefaultCalendarAlarms(vevent, calendarSettings); const { importedEvents, importErrors } = await addEvents({ events: [{ eventComponent: veventWithAlarms, hasDefaultNotifications: true }], calendarID: calendar.ID, }); if (importedEvents.length) { handleSuccess(importedEvents); if (appInView === APPS.PROTONCALENDAR) { postMessageToIframe( { type: DRAWER_EVENTS.CALL_CALENDAR_EVENT_MANAGER, payload: { calendarID: calendar.ID }, }, APPS.PROTONCALENDAR ); } } if (importErrors.length) { handleError(); } } catch { handleError(); } }; const importText = c('Action').t`Add to ${CALENDAR_APP_NAME}`; return ( <Button className="mb-2" color="weak" onClick={() => withLoading(handleAdd())} disabled={getDisableButtons(model)} loading={loading} title={importText} > {importText} </Button> ); }; export default ExtraEventImportButton;
3,626
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/calendar/ExtraEventOrganizerButtons.tsx
import { Dispatch, SetStateAction } from 'react'; import { ICAL_METHOD } from '@proton/shared/lib/calendar/constants'; import { RequireSome } from '@proton/shared/lib/interfaces/utils'; import { InvitationModel, getHasInvitationApi } from '../../../../helpers/calendar/invite'; import ExtraEventAddParticipantButton from './ExtraEventAddParticipantButton'; interface Props { model: RequireSome<InvitationModel, 'invitationIcs'>; setModel: Dispatch<SetStateAction<InvitationModel>>; } const ExtraEventOrganizerButtons = ({ model, setModel }: Props) => { const { invitationIcs: { method }, isPartyCrasher, } = model; if (!getHasInvitationApi(model)) { return null; } if (method === ICAL_METHOD.REPLY && isPartyCrasher) { return <ExtraEventAddParticipantButton model={model} setModel={setModel} />; } return null; }; export default ExtraEventOrganizerButtons;
3,627
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/calendar/ExtraEventParticipant.tsx
import { c } from 'ttag'; import { buildMailTo } from '@proton/shared/lib/helpers/email'; import { Participant } from '@proton/shared/lib/interfaces/calendar'; import clsx from '@proton/utils/clsx'; interface Props { participant: Participant; isOrganizer?: boolean; } const ExtraEventParticipant = ({ participant, isOrganizer = false }: Props) => { const { displayEmail, displayName } = participant; const displayText = displayName !== displayEmail ? `${displayName} <${displayEmail}>` : displayEmail; return ( <div className={clsx(['text-ellipsis', isOrganizer && 'mb-1'])}> {isOrganizer && <span className="mr-1">{c('ICS widget label for event details').t`Organizer:`}</span>} <a href={buildMailTo(displayEmail)} title={displayText}> {displayText} </a> </div> ); }; export default ExtraEventParticipant;
3,628
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/calendar/ExtraEventParticipants.tsx
import { useState } from 'react'; import { c, msgid } from 'ttag'; import { UnderlineButton } from '@proton/components'; import { Participant } from '@proton/shared/lib/interfaces/calendar'; import ExtraEventParticipant from './ExtraEventParticipant'; interface Props { list: Participant[]; } const ExtraEventParticipants = ({ list }: Props) => { const [isShowingMore, setIsShowingMore] = useState(false); const [organizer, ...attendees] = list; const totalAttendees = attendees.length; const toggleShowMore = () => setIsShowingMore((prevState) => !prevState); if (totalAttendees <= 1) { return ( <> {list.map((participant, i) => { return ( <ExtraEventParticipant participant={participant} isOrganizer={i === 0} key={participant.emailAddress} /> ); })} </> ); } return ( <> <ExtraEventParticipant participant={organizer} isOrganizer /> {!isShowingMore && ( <div className="flex flex-align-items-center"> <span className="mr-2"> {c('ICS widget label for event details').ngettext( msgid`${totalAttendees} participant`, `${totalAttendees} participants`, totalAttendees )} </span> <UnderlineButton onClick={toggleShowMore}>{c('Action').t`Show`}</UnderlineButton> </div> )} {isShowingMore && attendees.map((participant) => { return <ExtraEventParticipant participant={participant} key={participant.emailAddress} />; })} {} {isShowingMore && ( <div> <UnderlineButton onClick={toggleShowMore}>{c('Action').t`Show less`}</UnderlineButton> </div> )} </> ); }; export default ExtraEventParticipants;
3,629
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/calendar/ExtraEventSummary.test.tsx
import { render, screen } from '@testing-library/react'; import { ICAL_ATTENDEE_STATUS, ICAL_EVENT_STATUS, ICAL_METHOD } from '@proton/shared/lib/calendar/constants'; import { Participant, VcalDateProperty, VcalVeventComponent } from '@proton/shared/lib/interfaces/calendar'; import { calendarEventBuilder, veventBuilder } from '@proton/testing'; import { EVENT_TIME_STATUS, InvitationModel, UPDATE_ACTION } from '../../../../helpers/calendar/invite'; import ExtraEventSummary from './ExtraEventSummary'; const dummyRecurrenceID: VcalDateProperty = { value: { year: 2020, month: 2, day: 2, }, parameters: { type: 'date', }, }; const getAttendee = (partstat = ICAL_ATTENDEE_STATUS.NEEDS_ACTION) => ({ vcalComponent: { value: 'test@pm.gg' }, name: 'test', emailAddress: 'test@pm.gg', displayName: 'test', displayEmail: 'test@pm.gg', partstat, }); function renderComponent({ vevent, method = ICAL_METHOD.REPLY, attendee, props, }: { vevent?: Partial<VcalVeventComponent>; attendee?: Participant; method?: ICAL_METHOD; props?: Partial<InvitationModel>; }) { const model = { isImport: false, isOrganizerMode: false, hasMultipleVevents: false, hasProtonUID: true, timeStatus: EVENT_TIME_STATUS.FUTURE, isAddressActive: true, isAddressDisabled: false, canCreateCalendar: true, maxUserCalendarsDisabled: false, hasNoCalendars: false, hideSummary: false, invitationIcs: { vevent: { component: 'vevent' as const, uid: { value: 'uid' }, dtstamp: { value: { year: 2020, month: 2, day: 2, hours: 2, minutes: 2, seconds: 2, isUTC: true, }, }, dtstart: { value: { year: 2020, month: 2, day: 2, hours: 2, minutes: 2, seconds: 2, isUTC: true, }, }, attendee: [{ value: 'test@pm.gg' }], ...vevent, }, method, attendee, }, ...props, }; return render(<ExtraEventSummary model={model} />); } describe('ExtraEventSummary', () => { it('displays nothing when importing', () => { const { container } = renderComponent({ props: { isImport: true }, attendee: getAttendee(), }); expect(container).toBeEmptyDOMElement(); }); it('displays nothing when hideSummary is set', () => { const { container } = renderComponent({ props: { hideSummary: true }, attendee: getAttendee(), }); expect(container).toBeEmptyDOMElement(); }); describe('Attendee mode', () => { describe('method: request', () => { describe('outdated event', () => { it('displays nothing when there is no event from api', () => { const { container } = renderComponent({ props: { isOutdated: true }, attendee: getAttendee(), method: ICAL_METHOD.REQUEST, }); expect(container).toBeEmptyDOMElement(); }); it('displays a cancellation message when the status is canceled', () => { renderComponent({ props: { isOutdated: true, invitationApi: { vevent: veventBuilder({ overrides: { status: { value: ICAL_EVENT_STATUS.CANCELLED } }, }), calendarEvent: calendarEventBuilder(), }, }, attendee: getAttendee(), method: ICAL_METHOD.REQUEST, }); expect( screen.getByText(/This invitation is out of date. The event has been canceled./) ).toBeInTheDocument(); }); it('displays an out of date message when the event is out of date', () => { renderComponent({ props: { isOutdated: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder(), }, }, attendee: getAttendee(), method: ICAL_METHOD.REQUEST, }); expect( screen.getByText(/This invitation is out of date. The event has been updated./) ).toBeInTheDocument(); }); }); describe('has been updated text', () => { it('displays the updated text for partstat keep update action', () => { renderComponent({ props: { updateAction: UPDATE_ACTION.KEEP_PARTSTAT, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder(), }, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED), method: ICAL_METHOD.REQUEST, }); expect(screen.getByText(/This event has been updated./)).toBeInTheDocument(); }); it('displays the updated text for partstat reset update action', () => { renderComponent({ props: { updateAction: UPDATE_ACTION.RESET_PARTSTAT, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder(), }, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED), method: ICAL_METHOD.REQUEST, }); expect(screen.getByText(/This event has been updated./)).toBeInTheDocument(); }); }); it('displays nothing when there is no event from api', () => { const { container } = renderComponent({ attendee: getAttendee(), method: ICAL_METHOD.REQUEST, }); expect(container).toBeEmptyDOMElement(); }); it('displays nothing when the partstat is "needs action"', () => { const { container } = renderComponent({ props: { invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder(), }, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.NEEDS_ACTION), method: ICAL_METHOD.REQUEST, }); expect(container).toBeEmptyDOMElement(); }); it('displays accepted message when the partstat is accepted', () => { renderComponent({ props: { invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder(), }, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED), method: ICAL_METHOD.REQUEST, }); expect(screen.getByText(/You already accepted this invitation./)).toBeInTheDocument(); }); it('displays declined message when the partstat is declined', () => { renderComponent({ props: { invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder(), }, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED), method: ICAL_METHOD.REQUEST, }); expect(screen.getByText(/You already declined this invitation./)).toBeInTheDocument(); }); it('displays tentatively accepted message when the partstat is tentatively accepted', () => { renderComponent({ props: { invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder(), }, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE), method: ICAL_METHOD.REQUEST, }); expect(screen.getByText(/You already tentatively accepted this invitation./)).toBeInTheDocument(); }); }); describe('method: cancel', () => { it('displays the canceled message when the method is cancel', () => { renderComponent({ attendee: getAttendee(), method: ICAL_METHOD.CANCEL, }); expect(screen.getByText(/This event has been canceled./)).toBeInTheDocument(); }); }); describe('method: add', () => { it('displays the out of date message when there is no vevent from api', () => { renderComponent({ attendee: getAttendee(), method: ICAL_METHOD.ADD, }); expect( screen.getByText(/This invitation is out of date. The event has been deleted./) ).toBeInTheDocument(); }); it('displays the deletion message when there is no vevent from api', () => { renderComponent({ attendee: getAttendee(), method: ICAL_METHOD.ADD, }); expect( screen.getByText(/This invitation is out of date. The event has been deleted./) ).toBeInTheDocument(); }); describe('outdated event', () => { it('displays the cancellation message when the outdated event has a canceled status', () => { renderComponent({ props: { invitationApi: { vevent: veventBuilder({ overrides: { status: { value: ICAL_EVENT_STATUS.CANCELLED } }, }), calendarEvent: calendarEventBuilder(), }, isOutdated: true, }, attendee: getAttendee(), method: ICAL_METHOD.ADD, }); expect( screen.getByText(/This invitation is out of date. The event has been canceled./) ).toBeInTheDocument(); }); it('displays the outdated message when the invitation is outdated', () => { renderComponent({ props: { invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder(), }, isOutdated: true, }, attendee: getAttendee(), method: ICAL_METHOD.ADD, }); expect( screen.getByText(/This invitation is out of date. The event has been updated./) ).toBeInTheDocument(); }); }); it('does not display the occurrence added message when the event is not outdated and is available from the API', () => { renderComponent({ props: { invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder(), }, }, attendee: getAttendee(), method: ICAL_METHOD.ADD, }); expect( screen.queryByText(/An occurrence has been added to the event \(no title\)/) ).not.toBeInTheDocument(); }); }); }); describe('Organizer mode', () => { it('displays nothing when there are no attendees', () => { const { container } = renderComponent({ props: { isOrganizerMode: true }, }); expect(container).toBeEmptyDOMElement(); }); describe('method: reply', () => { it('displays nothing when the attendee has no partstat', () => { const attendee = getAttendee(); // If somehow the attendee doesn't have a partstat // @ts-ignore delete attendee.partstat; const { container } = renderComponent({ props: { isOrganizerMode: true }, attendee, }); expect(container).toBeEmptyDOMElement(); }); describe('no event from api', () => { it('displays the no calendars message when there are no calendars', () => { renderComponent({ props: { isOrganizerMode: true, hasNoCalendars: true }, attendee: getAttendee(), }); expect( screen.getByText(/This response is out of date. You have no calendars./) ).toBeInTheDocument(); }); describe('decryption error', () => { describe('partstat: accepted', () => { it('displays the accepted message when the event was accepted', () => { renderComponent({ props: { isOrganizerMode: true, hasDecryptionError: true }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED), }); expect(screen.getByText(/test accepted your invitation./)).toBeInTheDocument(); }); it('displays the partycrasher accepted message when the event was accepted', () => { renderComponent({ props: { isOrganizerMode: true, hasDecryptionError: true, isPartyCrasher: true }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED), }); expect(screen.getByText(/test accepted an invitation to this event./)).toBeInTheDocument(); }); }); describe('partstat: declined', () => { it('displays the declined message when the event was declined', () => { renderComponent({ props: { isOrganizerMode: true, hasDecryptionError: true }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED), }); expect(screen.getByText(/test declined your invitation./)).toBeInTheDocument(); }); it('displays the partycrasher declined message when the event was declined', () => { renderComponent({ props: { isOrganizerMode: true, hasDecryptionError: true, isPartyCrasher: true }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED), }); expect(screen.getByText(/test declined an invitation to this event./)).toBeInTheDocument(); }); }); describe('partstat: tentative', () => { it('displays the tentative message when the event was accepted tentatively', () => { renderComponent({ props: { isOrganizerMode: true, hasDecryptionError: true }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE), }); expect(screen.getByText(/test tentatively accepted your invitation./)).toBeInTheDocument(); }); it('displays the partycrasher tentative message when the event was accepted tentatively', () => { renderComponent({ props: { isOrganizerMode: true, hasDecryptionError: true, isPartyCrasher: true }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE), }); expect( screen.getByText(/test tentatively accepted an invitation to this event./) ).toBeInTheDocument(); }); }); }); it('displays the does not exist message when the event does not exist', () => { renderComponent({ props: { isOrganizerMode: true }, attendee: getAttendee() }); expect( screen.getByText( /This response is out of date. The event does not exist in your calendar anymore./ ) ).toBeInTheDocument(); }); }); it('displays the future event message when the event is in the future', () => { renderComponent({ props: { isOrganizerMode: true, isFromFuture: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, }, attendee: getAttendee(), }); expect( screen.getByText( /This response doesn't match your invitation details. Please verify the invitation details in your calendar./ ) ).toBeInTheDocument(); }); describe('outdated event', () => { describe('partstat: accepted', () => { describe('single edit', () => { it('displays the accepted message when the event was accepted', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isOutdated: true, }, vevent: { 'recurrence-id': dummyRecurrenceID }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED), }); expect( screen.getByText( /test had previously accepted your invitation to one occurrence of the event./ ) ).toBeInTheDocument(); // has been updated text expect(screen.getByText(/This response is out of date./)).toBeInTheDocument(); }); it('displays the partycrasher accepted message when the event was accepted', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isOutdated: true, isPartyCrasher: true, }, vevent: { 'recurrence-id': dummyRecurrenceID }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED), }); expect( screen.getByText(/test had accepted an invitation to one occurrence of the event./) ).toBeInTheDocument(); }); }); it('displays the accepted message when the event was accepted', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isOutdated: true, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED), }); expect(screen.getByText(/test had previously accepted your invitation./)).toBeInTheDocument(); }); it('displays the partycrasher accepted message when the event was accepted', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isOutdated: true, isPartyCrasher: true, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED), }); expect(screen.getByText(/test had accepted an invitation to this event./)).toBeInTheDocument(); }); }); describe('partstat: declined', () => { describe('single edit', () => { it('displays the declined message when the event was declined', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isOutdated: true, }, vevent: { 'recurrence-id': dummyRecurrenceID }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED), }); expect( screen.getByText( /test had previously declined your invitation to one occurrence of the event./ ) ).toBeInTheDocument(); }); it('displays the partycrasher declined message when the event was declined', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isOutdated: true, isPartyCrasher: true, }, vevent: { 'recurrence-id': dummyRecurrenceID }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED), }); expect( screen.getByText(/test had declined an invitation to one occurrence of the event./) ).toBeInTheDocument(); }); }); it('displays the declined message when the event was declined', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isOutdated: true, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED), }); expect(screen.getByText(/test had previously declined your invitation./)).toBeInTheDocument(); }); it('displays the partycrasher declined message when the event was declined', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isOutdated: true, isPartyCrasher: true, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED), }); expect(screen.getByText(/test had declined an invitation to this event./)).toBeInTheDocument(); }); }); describe('partstat: tentative', () => { describe('single edit', () => { it('displays the tentative message when the event was accepted tentatively', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isOutdated: true, }, vevent: { 'recurrence-id': dummyRecurrenceID }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE), }); expect( screen.getByText( /test had previously tentatively accepted your invitation to one occurrence of the event./ ) ).toBeInTheDocument(); }); it('displays the partycrasher tentative message when the event was accepted tentatively', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isOutdated: true, isPartyCrasher: true, }, vevent: { 'recurrence-id': dummyRecurrenceID }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE), }); expect( screen.getByText( /test had tentatively accepted an invitation to one occurrence of the event./ ) ).toBeInTheDocument(); }); }); it('displays the tentative message when the event was accepted tentatively', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isOutdated: true, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE), }); expect( screen.getByText(/test had previously tentatively accepted your invitation./) ).toBeInTheDocument(); }); it('displays the partycrasher tentative message when the event was accepted tentatively', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isOutdated: true, isPartyCrasher: true, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE), }); expect( screen.getByText(/test had tentatively accepted an invitation to this event./) ).toBeInTheDocument(); }); }); }); describe('partstat: accepted', () => { describe('single edit', () => { it('displays the accepted message when the event was accepted', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, }, vevent: { 'recurrence-id': dummyRecurrenceID }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED), }); expect( screen.getByText(/test accepted your invitation to one occurrence of the event./) ).toBeInTheDocument(); }); it('displays the partycrasher accepted message when the event was accepted', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isPartyCrasher: true, }, vevent: { 'recurrence-id': dummyRecurrenceID }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED), }); expect( screen.getByText(/test accepted an invitation to one occurrence of the event./) ).toBeInTheDocument(); }); }); it('displays the accepted message when the event was accepted', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED), }); expect(screen.getByText(/test accepted your invitation./)).toBeInTheDocument(); }); it('displays the partycrasher accepted message when the event was accepted', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isPartyCrasher: true, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED), }); expect(screen.getByText(/test accepted an invitation to this event./)).toBeInTheDocument(); }); }); describe('partstat: declined', () => { describe('single edit', () => { it('displays the declined message when the event was declined', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, }, vevent: { 'recurrence-id': dummyRecurrenceID }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED), }); expect( screen.getByText(/test declined your invitation to one occurrence of the event./) ).toBeInTheDocument(); }); it('displays the partycrasher declined message when the event was declined', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isPartyCrasher: true, }, vevent: { 'recurrence-id': dummyRecurrenceID }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED), }); expect( screen.getByText(/test declined an invitation to one occurrence of the event./) ).toBeInTheDocument(); }); }); it('displays the declined message when the event was declined', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED), }); expect(screen.getByText(/test declined your invitation./)).toBeInTheDocument(); }); it('displays the partycrasher declined message when the event was declined', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isPartyCrasher: true, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED), }); expect(screen.getByText(/test declined an invitation to this event./)).toBeInTheDocument(); }); }); describe('partstat: tentative', () => { describe('single edit', () => { it('displays the tentatively accepted message when the event was tentatively accepted', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, }, vevent: { 'recurrence-id': dummyRecurrenceID }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE), }); expect( screen.getByText( /test tentatively accepted your invitation to one occurrence of the event./ ) ).toBeInTheDocument(); }); it('displays the partycrasher tentatively accepted message when the event was tentatively accepted', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isPartyCrasher: true, }, vevent: { 'recurrence-id': dummyRecurrenceID }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE), }); expect( screen.getByText(/test tentatively accepted an invitation to one occurrence of the event./) ).toBeInTheDocument(); }); }); it('displays the tentatively accepted message when the event was tentatively accepted', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE), }); expect(screen.getByText(/test tentatively accepted your invitation./)).toBeInTheDocument(); }); it('displays the partycrasher tentatively accepted message when the event was tentatively accepted', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isPartyCrasher: true, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE), }); expect( screen.getByText(/test tentatively accepted an invitation to this event./) ).toBeInTheDocument(); }); }); }); describe('method: counter', () => { describe('no event from api', () => { it('single edit: displays the no calendars message when there are no calendars', () => { renderComponent({ props: { isOrganizerMode: true, hasNoCalendars: true }, attendee: getAttendee(), vevent: { 'recurrence-id': dummyRecurrenceID }, method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test had proposed a new time for one occurrence of this event. This proposal is out of date. You have no calendars./ ) ).toBeInTheDocument(); }); it('displays the no calendars message when there are no calendars', () => { renderComponent({ props: { isOrganizerMode: true, hasNoCalendars: true }, attendee: getAttendee(), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test had proposed a new time for this event. This proposal is out of date. You have no calendars./ ) ).toBeInTheDocument(); }); describe('has decryption error', () => { describe('partstat: accepted', () => { describe('single edit', () => { it('displays the accepted message when the event was accepted', () => { renderComponent({ props: { hasDecryptionError: true, isOrganizerMode: true, }, vevent: { 'recurrence-id': dummyRecurrenceID }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test accepted your invitation and proposed a new time for one occurrence of this event./ ) ).toBeInTheDocument(); }); it('displays the partycrasher accepted message when the event was accepted', () => { renderComponent({ props: { hasDecryptionError: true, isOrganizerMode: true, isPartyCrasher: true, }, vevent: { 'recurrence-id': dummyRecurrenceID }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test accepted an invitation and proposed a new time for one occurrence of this event./ ) ).toBeInTheDocument(); }); }); it('displays the accepted message when the event was accepted', () => { renderComponent({ props: { hasDecryptionError: true, isOrganizerMode: true, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test accepted your invitation and proposed a new time for this event./ ) ).toBeInTheDocument(); }); it('displays the partycrasher accepted message when the event was accepted', () => { renderComponent({ props: { hasDecryptionError: true, isOrganizerMode: true, isPartyCrasher: true, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText(/test accepted an invitation and proposed a new time for this event./) ).toBeInTheDocument(); }); }); describe('partstat: declined', () => { describe('single edit', () => { it('displays the declined message when the event was declined', () => { renderComponent({ props: { hasDecryptionError: true, isOrganizerMode: true, }, vevent: { 'recurrence-id': dummyRecurrenceID }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test declined your invitation and proposed a new time for one occurrence of this event./ ) ).toBeInTheDocument(); }); it('displays the partycrasher declined message when the event was declined', () => { renderComponent({ props: { hasDecryptionError: true, isOrganizerMode: true, isPartyCrasher: true, }, vevent: { 'recurrence-id': dummyRecurrenceID }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test declined an invitation and proposed a new time for one occurrence of this event./ ) ).toBeInTheDocument(); }); }); it('displays the declined message when the event was declined', () => { renderComponent({ props: { hasDecryptionError: true, isOrganizerMode: true, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test declined your invitation and proposed a new time for this event./ ) ).toBeInTheDocument(); }); it('displays the partycrasher declined message when the event was declined', () => { renderComponent({ props: { hasDecryptionError: true, isOrganizerMode: true, isPartyCrasher: true, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText(/test declined an invitation and proposed a new time for this event./) ).toBeInTheDocument(); }); }); describe('partstat: tentative', () => { describe('single edit', () => { it('displays the tentative message when the event was accepted tentatively', () => { renderComponent({ props: { hasDecryptionError: true, isOrganizerMode: true, }, vevent: { 'recurrence-id': dummyRecurrenceID }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test tentatively accepted your invitation and proposed a new time for one occurrence of this event./ ) ).toBeInTheDocument(); }); it('displays the partycrasher tentative message when the event was accepted tentatively', () => { renderComponent({ props: { hasDecryptionError: true, isOrganizerMode: true, isPartyCrasher: true, }, vevent: { 'recurrence-id': dummyRecurrenceID }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test tentatively accepted an invitation and proposed a new time for one occurrence of this event./ ) ).toBeInTheDocument(); }); }); it('displays the tentative message when the event was accepted tentatively', () => { renderComponent({ props: { hasDecryptionError: true, isOrganizerMode: true, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test tentatively accepted your invitation and proposed a new time for this event./ ) ).toBeInTheDocument(); }); it('displays the partycrasher tentative message when the event was accepted tentatively', () => { renderComponent({ props: { hasDecryptionError: true, isOrganizerMode: true, isPartyCrasher: true, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test tentatively accepted an invitation and proposed a new time for this event./ ) ).toBeInTheDocument(); }); }); it('single edit: displays the out of date message when there are out of date', () => { renderComponent({ props: { isOrganizerMode: true, hasDecryptionError: true }, attendee: getAttendee(), vevent: { 'recurrence-id': dummyRecurrenceID }, method: ICAL_METHOD.COUNTER, }); expect( screen.getByText(/test proposed a new time for one occurrence of this event./) ).toBeInTheDocument(); }); it('displays the out of date message when there are out of date', () => { renderComponent({ props: { isOrganizerMode: true, hasDecryptionError: true }, attendee: getAttendee(), method: ICAL_METHOD.COUNTER, }); expect(screen.getByText(/test proposed a new time for this event./)).toBeInTheDocument(); }); }); it('single edit: displays the out of date message when there are out of date', () => { renderComponent({ props: { isOrganizerMode: true }, attendee: getAttendee(), vevent: { 'recurrence-id': dummyRecurrenceID }, method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test had proposed a new time for one occurrence of this event. This proposal is out of date. The event does not exist in your calendar anymore./ ) ).toBeInTheDocument(); }); it('displays the out of date message when there are out of date', () => { renderComponent({ props: { isOrganizerMode: true }, attendee: getAttendee(), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test had proposed a new time for this event. This proposal is out of date. The event does not exist in your calendar anymore./ ) ).toBeInTheDocument(); }); }); it('displays the future event message when the event is in the future', () => { const { container } = renderComponent({ props: { isOrganizerMode: true, isFromFuture: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, }, method: ICAL_METHOD.COUNTER, attendee: getAttendee(), }); expect(container.children[0].children.length).toBe(1); expect( screen.getByText( /This new time proposal doesn't match your invitation details. Please verify the invitation details in your calendar./ ) ).toBeInTheDocument(); }); describe('outdated event', () => { describe('partstat: accepted', () => { describe('single edit', () => { it('displays the accepted message when the event was accepted', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isOutdated: true, }, vevent: { 'recurrence-id': dummyRecurrenceID }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test had accepted your invitation and proposed a new time for one occurrence of this event. Answer and proposal are out of date./ ) ).toBeInTheDocument(); }); it('displays the partycrasher accepted message when the event was accepted', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isOutdated: true, isPartyCrasher: true, }, vevent: { 'recurrence-id': dummyRecurrenceID }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test had accepted an invitation and proposed a new time for one occurrence of this event. Answer and proposal are out of date./ ) ).toBeInTheDocument(); }); }); it('displays the accepted message when the event was accepted', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isOutdated: true, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test had accepted your invitation and proposed a new time for this event. Answer and proposal are out of date./ ) ).toBeInTheDocument(); }); it('displays the partycrasher accepted message when the event was accepted', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isOutdated: true, isPartyCrasher: true, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test had accepted an invitation and proposed a new time for this event. Answer and proposal are out of date./ ) ).toBeInTheDocument(); }); }); describe('partstat: declined', () => { describe('single edit', () => { it('displays the declined message when the event was declined', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isOutdated: true, }, vevent: { 'recurrence-id': dummyRecurrenceID }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test had declined your invitation and proposed a new time for one occurrence of this event. Answer and proposal are out of date./ ) ).toBeInTheDocument(); }); it('displays the partycrasher declined message when the event was declined', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isOutdated: true, isPartyCrasher: true, }, vevent: { 'recurrence-id': dummyRecurrenceID }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test had declined an invitation and proposed a new time for one occurrence of this event. Answer and proposal are out of date./ ) ).toBeInTheDocument(); }); }); it('displays the declined message when the event was declined', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isOutdated: true, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test had declined your invitation and proposed a new time for this event. Answer and proposal are out of date./ ) ).toBeInTheDocument(); }); it('displays the partycrasher declined message when the event was declined', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isOutdated: true, isPartyCrasher: true, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test had declined an invitation and proposed a new time for this event. Answer and proposal are out of date./ ) ).toBeInTheDocument(); }); }); describe('partstat: tentative', () => { describe('single edit', () => { it('displays the tentative message when the event was accepted tentatively', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isOutdated: true, }, vevent: { 'recurrence-id': dummyRecurrenceID }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test had tentatively accepted your invitation and proposed a new time for one occurrence of this event. Answer and proposal are out of date./ ) ).toBeInTheDocument(); }); it('displays the partycrasher tentative message when the event was accepted tentatively', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isOutdated: true, isPartyCrasher: true, }, vevent: { 'recurrence-id': dummyRecurrenceID }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test had tentatively accepted an invitation and proposed a new time for one occurrence of this event. Answer and proposal are out of date./ ) ).toBeInTheDocument(); }); }); it('displays the tentative message when the event was accepted tentatively', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isOutdated: true, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test had tentatively accepted your invitation and proposed a new time for this event. Answer and proposal are out of date./ ) ).toBeInTheDocument(); }); it('displays the partycrasher tentative message when the event was accepted tentatively', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isOutdated: true, isPartyCrasher: true, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test had tentatively accepted an invitation and proposed a new time for this event. Answer and proposal are out of date./ ) ).toBeInTheDocument(); }); }); describe('single edit', () => { it('displays the correct message when a counter was proposed', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isOutdated: true, }, vevent: { 'recurrence-id': dummyRecurrenceID }, attendee: getAttendee(), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test had proposed a new time for one occurrence of this event. This proposal is out of date./ ) ).toBeInTheDocument(); }); }); it('displays the correct message when a counter was proposed', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isOutdated: true, }, attendee: getAttendee(), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText(/test had proposed a new time for this event. This proposal is out of date./) ).toBeInTheDocument(); }); }); describe('partstat: accepted', () => { describe('single edit', () => { it('displays the accepted message when the event was accepted', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, }, vevent: { 'recurrence-id': dummyRecurrenceID }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test accepted your invitation and proposed a new time for one occurrence of this event./ ) ).toBeInTheDocument(); }); it('displays the partycrasher accepted message when the event was accepted', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isPartyCrasher: true, }, vevent: { 'recurrence-id': dummyRecurrenceID }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test accepted an invitation and proposed a new time for one occurrence of this event./ ) ).toBeInTheDocument(); }); }); it('displays the accepted message when the event was accepted', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText(/test accepted your invitation and proposed a new time for this event./) ).toBeInTheDocument(); }); it('displays the partycrasher accepted message when the event was accepted', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isPartyCrasher: true, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText(/test accepted an invitation and proposed a new time for this event./) ).toBeInTheDocument(); }); }); describe('partstat: declined', () => { describe('single edit', () => { it('displays the declined message when the event was declined', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, }, vevent: { 'recurrence-id': dummyRecurrenceID }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test declined your invitation and proposed a new time for one occurrence of this event./ ) ).toBeInTheDocument(); }); it('displays the partycrasher declined message when the event was declined', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isPartyCrasher: true, }, vevent: { 'recurrence-id': dummyRecurrenceID }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test declined an invitation and proposed a new time for one occurrence of this event./ ) ).toBeInTheDocument(); }); }); it('displays the declined message when the event was declined', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText(/test declined your invitation and proposed a new time for this event./) ).toBeInTheDocument(); }); it('displays the partycrasher declined message when the event was declined', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isPartyCrasher: true, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.DECLINED), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText(/test declined an invitation and proposed a new time for this event./) ).toBeInTheDocument(); }); }); describe('partstat: tentative', () => { describe('single edit', () => { it('displays the tentative message when the event was accepted tentatively', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, }, vevent: { 'recurrence-id': dummyRecurrenceID }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test tentatively accepted your invitation and proposed a new time for one occurrence of this event./ ) ).toBeInTheDocument(); }); it('displays the partycrasher tentative message when the event was accepted tentatively', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isPartyCrasher: true, }, vevent: { 'recurrence-id': dummyRecurrenceID }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test tentatively accepted an invitation and proposed a new time for one occurrence of this event./ ) ).toBeInTheDocument(); }); }); it('displays the tentative message when the event was accepted tentatively', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test tentatively accepted your invitation and proposed a new time for this event./ ) ).toBeInTheDocument(); }); it('displays the partycrasher tentative message when the event was accepted tentatively', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, isPartyCrasher: true, }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.TENTATIVE), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText( /test tentatively accepted an invitation and proposed a new time for this event./ ) ).toBeInTheDocument(); }); it('single edit: displays the out of date message when there are out of date', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, }, attendee: getAttendee(), vevent: { 'recurrence-id': dummyRecurrenceID }, method: ICAL_METHOD.COUNTER, }); expect( screen.getByText(/test proposed a new time for one occurrence of this event./) ).toBeInTheDocument(); }); it('displays the out of date message when there are out of date', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, }, attendee: getAttendee(), method: ICAL_METHOD.COUNTER, }); expect(screen.getByText(/test proposed a new time for this event./)).toBeInTheDocument(); }); }); describe('single edit', () => { it('displays the correct message when a counter was proposed', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, }, vevent: { 'recurrence-id': dummyRecurrenceID }, attendee: getAttendee(), method: ICAL_METHOD.COUNTER, }); expect( screen.getByText(/test proposed a new time for one occurrence of this event./) ).toBeInTheDocument(); }); }); it('displays the correct message when a counter was proposed', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, }, attendee: getAttendee(), method: ICAL_METHOD.COUNTER, }); expect(screen.getByText(/test proposed a new time for this event./)).toBeInTheDocument(); }); }); describe('method: refresh', () => { describe('no event from api', () => { it('displays the no calendars message when there are no calendars', () => { renderComponent({ props: { isOrganizerMode: true, hasNoCalendars: true }, attendee: getAttendee(), method: ICAL_METHOD.REFRESH, }); expect( screen.getByText( /test asked for the latest updates to an event which does not exist anymore. You have no calendars./ ) ).toBeInTheDocument(); }); describe('decryption error', () => { it('displays the accepted message when the event was accepted', () => { renderComponent({ props: { isOrganizerMode: true, hasDecryptionError: true }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED), method: ICAL_METHOD.REFRESH, }); expect(screen.getByText(/test asked for the latest event updates./)).toBeInTheDocument(); }); }); it('displays the accepted message when the event was accepted', () => { renderComponent({ props: { isOrganizerMode: true }, attendee: getAttendee(ICAL_ATTENDEE_STATUS.ACCEPTED), method: ICAL_METHOD.REFRESH, }); expect( screen.getByText( /test asked for the latest updates to an event which does not exist in your calendar anymore./ ) ).toBeInTheDocument(); }); }); it('displays the future message when the invite is from the future', () => { renderComponent({ props: { isFromFuture: true, isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, }, attendee: getAttendee(), method: ICAL_METHOD.REFRESH, }); expect( screen.getByText( /test 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('displays the refresh message when the invitation was found', () => { renderComponent({ props: { isOrganizerMode: true, invitationApi: { vevent: veventBuilder(), calendarEvent: calendarEventBuilder() }, }, attendee: getAttendee(), method: ICAL_METHOD.REFRESH, }); expect(screen.getByText(/test asked for the latest event updates./)).toBeInTheDocument(); }); }); }); });
3,630
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/calendar/ExtraEventSummary.tsx
import { RequireSome } from '@proton/shared/lib/interfaces/utils'; import { InvitationModel } from '../../../../helpers/calendar/invite'; import { getAttendeeSummaryText, getHasBeenUpdatedText, getOrganizerSummaryText, } from '../../../../helpers/calendar/summary'; export const getSummaryContent = (hasBeenUpdatedText?: string, summaryText?: string) => { if (!hasBeenUpdatedText && !summaryText) { return null; } const content = hasBeenUpdatedText && summaryText ? ( <> <span>{hasBeenUpdatedText}</span> <span>{summaryText}</span> </> ) : ( <span>{hasBeenUpdatedText || summaryText}</span> ); return ( <div data-testid="ics-widget-summary" className="my-2 rounded border bg-weak p-2 flex flex-column text-break"> {content} </div> ); }; export interface ExtraEventSummaryProps { model: RequireSome<InvitationModel, 'invitationIcs'>; } const ExtraEventSummary = ({ model }: ExtraEventSummaryProps) => { const { isImport, hideSummary, isOrganizerMode } = model; const summaryText = isOrganizerMode ? getOrganizerSummaryText(model) : getAttendeeSummaryText(model); const hasBeenUpdatedText = getHasBeenUpdatedText(model); if (isImport || hideSummary || !summaryText) { return null; } return getSummaryContent(hasBeenUpdatedText, summaryText); }; export default ExtraEventSummary;
3,631
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/calendar/ExtraEventTimeStatus.tsx
import { c } from 'ttag'; import { Banner } from '@proton/components'; import { BannerBackgroundColor } from '@proton/components/components/banner/Banner'; import { ICAL_METHOD } from '@proton/shared/lib/calendar/constants'; import { getIsVeventCancelled } from '@proton/shared/lib/calendar/vcalHelper'; import { RequireSome } from '@proton/shared/lib/interfaces'; import { EVENT_TIME_STATUS, InvitationModel } from '../../../../helpers/calendar/invite'; interface Props { model: RequireSome<InvitationModel, 'invitationIcs'>; } const ExtraEventTimeStatus = ({ model }: Props) => { const { timeStatus, hasMultipleVevents, invitationIcs, isOutdated, invitationApi } = model; if ( hasMultipleVevents || timeStatus === EVENT_TIME_STATUS.FUTURE || invitationIcs.method === ICAL_METHOD.CANCEL || (isOutdated && invitationApi && getIsVeventCancelled(invitationApi.vevent)) ) { return null; } const text = timeStatus === EVENT_TIME_STATUS.HAPPENING ? c('Calendar widget banner').t`Event in progress` : c('Calendar widget banner').t`Event already ended`; return <Banner backgroundColor={BannerBackgroundColor.WARNING}>{text}</Banner>; }; export default ExtraEventTimeStatus;
3,632
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/calendar/ExtraEventWarning.tsx
import { c } from 'ttag'; import { Alert } from '@proton/components'; import { ICAL_METHOD } from '@proton/shared/lib/calendar/constants'; import { CALENDAR_APP_NAME } from '@proton/shared/lib/constants'; import { RequireSome } from '@proton/shared/lib/interfaces/utils'; import { InvitationModel } from '../../../../helpers/calendar/invite'; interface Props { model: RequireSome<InvitationModel, 'invitationIcs'>; } const ExtraEventWarning = ({ model }: Props) => { const { isOrganizerMode, invitationIcs: { method, vevent: veventIcs }, invitationApi, hasDecryptionError, isOutdated, isFromFuture, } = model; const alertClassName = 'my-2 text-break'; if ((isOutdated || isFromFuture) && method !== ICAL_METHOD.REFRESH) { return null; } if (isOrganizerMode) { if (!invitationApi && !hasDecryptionError) { return null; } if (method === ICAL_METHOD.REFRESH) { return ( <Alert className={alertClassName} type="warning"> {c('Calendar invite info').t`Event refreshing is not supported for the moment`} </Alert> ); } if (method === ICAL_METHOD.COUNTER) { return ( <> {veventIcs['recurrence-id'] && ( <Alert className={alertClassName} type="warning"> {c('Calendar invite info') .t`This answer cannot be added to ${CALENDAR_APP_NAME} as we only support answers to all events of a series for the moment`} </Alert> )} <Alert className={alertClassName} type="warning"> {c('Calendar invite info').t`Event rescheduling is not supported for the moment`} </Alert> </> ); } if (method === ICAL_METHOD.REPLY && veventIcs['recurrence-id']) { return ( <Alert className={alertClassName} type="warning"> {c('Calendar invite info') .t`This answer cannot be added to ${CALENDAR_APP_NAME} as we only support answers to all events of a series for the moment`} </Alert> ); } } if (method === ICAL_METHOD.ADD && invitationApi) { return ( <Alert className={alertClassName} type="warning"> {c('Calendar invite info').t`Adding occurrences to an event is not supported for the moment`} </Alert> ); } return null; }; export default ExtraEventWarning;
3,633
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/calendar/OpenInCalendarButton.tsx
import { Button } from '@proton/atoms'; import { AppLink, useActiveBreakpoint, useAuthentication, useConfig, useDrawer } from '@proton/components'; import { getLinkToCalendarEvent } from '@proton/shared/lib/calendar/helper'; import { APPS } from '@proton/shared/lib/constants'; import { openCalendarEventInDrawer } from '@proton/shared/lib/drawer/calendar'; interface Props { linkString: string; calendarID: string; eventID: string; recurrenceID?: number; } const OpenInCalendarButton = ({ linkString, calendarID, eventID, recurrenceID }: Props) => { const { APP_NAME: currentApp } = useConfig(); const { setAppInView, iframeSrcMap, setIframeSrcMap, showDrawerSidebar } = useDrawer(); const { isNarrow } = useActiveBreakpoint(); const authentication = useAuthentication(); const localID = authentication.getLocalID(); const linkTo = getLinkToCalendarEvent({ calendarID, eventID, recurrenceID }); const appLink = ( <AppLink to={linkTo} toApp={APPS.PROTONCALENDAR}> {linkString} </AppLink> ); const handleDrawerAppOpening = () => { openCalendarEventInDrawer({ currentApp, setAppInView, iframeSrcMap, setIframeSrcMap, localID, calendarID, eventID, recurrenceID, }); }; // We use the default link to the Calendar app when mobile view OR the user is hiding the Drawer if (isNarrow || !showDrawerSidebar) { return appLink; } return ( <Button className="text-left" color="norm" shape="underline" onClick={handleDrawerAppOpening}> {linkString} </Button> ); }; export default OpenInCalendarButton;
3,634
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/calendar/useCalendarWidgetDrawerEvents.tsx
import { useEffect } from 'react'; import { APPS } from '@proton/shared/lib/constants'; import { getIsDrawerPostMessage, postMessageToIframe } from '@proton/shared/lib/drawer/helpers'; import { DRAWER_EVENTS } from '@proton/shared/lib/drawer/interfaces'; import { CalendarEvent } from '@proton/shared/lib/interfaces/calendar'; interface Props { messageID: string; calendarEvent?: CalendarEvent; refresh: () => void; } const useCalendarWidgetDrawerEvents = ({ messageID, calendarEvent, refresh }: Props) => { useEffect(() => { if (!calendarEvent) { return; } const { UID } = calendarEvent; // Tell potential calendar drawer app that the events in the widget are in view postMessageToIframe( { type: DRAWER_EVENTS.SET_WIDGET_EVENT, payload: { messageID: messageID, UID }, }, APPS.PROTONCALENDAR ); const handleSideCalendarEvents = (event: MessageEvent) => { if (!getIsDrawerPostMessage(event)) { return; } if (event.data.type === DRAWER_EVENTS.REQUEST_OPEN_EVENTS) { // The calendar app is requesting if there are open events in the widget postMessageToIframe( { type: DRAWER_EVENTS.SET_WIDGET_EVENT, payload: { messageID, UID }, }, APPS.PROTONCALENDAR ); } if (event.data.type === DRAWER_EVENTS.REFRESH_WIDGET) { const { UID, ModifyTime } = event.data.payload; const hasMatchingUID = calendarEvent ? calendarEvent.UID === UID : false; const shouldRefresh = calendarEvent ? calendarEvent.ModifyTime < ModifyTime : false; if (hasMatchingUID && shouldRefresh) { refresh(); } } }; window.addEventListener('message', handleSideCalendarEvents); return () => { window.addEventListener('message', handleSideCalendarEvents); // On unmount, tell potential calendar drawer app that the events in the widget are no longer in view postMessageToIframe( { type: DRAWER_EVENTS.UNSET_WIDGET_EVENT, payload: { messageID, UID }, }, APPS.PROTONCALENDAR ); }; }, [messageID, calendarEvent]); }; export default useCalendarWidgetDrawerEvents;
3,635
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/expiration/ExtraExpiration.tsx
import React from 'react'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { isFrozenExpiration } from '@proton/shared/lib/mail/messages'; import { getMessageHasData } from 'proton-mail/helpers/message/messages'; import { MessageState } from 'proton-mail/logic/messages/messagesTypes'; import ExtraExpirationSelfDestruction from './ExtraExpirationSelfDestruction'; import ExtraExpirationSentExpirationAutoDelete from './ExtraExpirationSentExpirationAutoDelete'; interface Props { message: MessageState; } const ExtraExpiration = ({ message }: Props) => { if (!getMessageHasData(message)) { return null; } // TODO: Remove when API has fixed expiresIn and freeze flag issue (MAILBE-1129) const isFrozen = isFrozenExpiration(message.data) || !!message.draftFlags?.expiresIn; const hasExpiration = !!(message.data?.ExpirationTime || message.draftFlags?.expiresIn); const hasSpamOrTrash = message.data?.LabelIDs?.includes(MAILBOX_LABEL_IDS.TRASH) || message.data?.LabelIDs?.includes(MAILBOX_LABEL_IDS.SPAM); return ( <> {hasExpiration && isFrozen ? <ExtraExpirationSentExpirationAutoDelete message={message} /> : null} {hasExpiration && !isFrozen && !hasSpamOrTrash ? ( <ExtraExpirationSelfDestruction message={message} /> ) : null} {hasExpiration && !isFrozen && hasSpamOrTrash ? ( <ExtraExpirationSentExpirationAutoDelete message={message} autoDelete /> ) : null} </> ); }; export default ExtraExpiration;
3,636
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/expiration/ExtraExpirationSelfDestruction.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { FeatureCode, Icon, Tooltip, useFeature, useNotifications, useUser } from '@proton/components'; import clsx from '@proton/utils/clsx'; import { canSetExpiration } from '../../../../helpers/expiration'; import useExpiration from '../../../../hooks/useExpiration'; import { expireMessages } from '../../../../logic/messages/expire/messagesExpireActions'; import { MessageState } from '../../../../logic/messages/messagesTypes'; import { useAppDispatch } from '../../../../logic/store'; interface Props { message: MessageState; } const ExtraExpirationSelfDestruction = ({ message }: Props) => { const { expirationMessage, expiresInLessThan24Hours } = useExpiration(message); const [user] = useUser(); const { createNotification } = useNotifications(); const { feature } = useFeature(FeatureCode.SetExpiration); const dispatch = useAppDispatch(); const canExpire = canSetExpiration(feature?.Value, user, message); const messageID = message.data?.ID || ''; const conversationID = message.data?.ConversationID; const handleClick = () => { if (user.isFree) { return; } void dispatch( expireMessages({ IDs: [messageID], conversationID, expirationTime: null, }) ); createNotification({ text: c('Success').t`Message expiration cancelled` }); }; return ( <div className={clsx( 'bg-norm rounded border flex flex-align-items-center py-2 px-2 mb-2 gap-4', expiresInLessThan24Hours && 'color-danger border-danger' )} data-testid="expiration-banner" > <Icon name="hourglass" className="flex-item-noshrink" /> <span className="flex flex-item-fluid flex-align-items-center">{expirationMessage}</span> {canExpire && ( <span className="flex-item-noshrink w-full md:w-auto"> <Tooltip title={c('Cancel expiration of the message').t`Cancel expiration`}> <Button onClick={handleClick} size="small" color={expiresInLessThan24Hours ? 'danger' : 'weak'} shape="underline" data-testid="unsubscribe-banner" > {c('Cancel expiration of the message').t`Cancel`} </Button> </Tooltip> </span> )} </div> ); }; export default ExtraExpirationSelfDestruction;
3,637
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/expiration/ExtraExpirationSentExpirationAutoDelete.tsx
import { Icon } from '@proton/components'; import clsx from '@proton/utils/clsx'; import useExpiration from '../../../../hooks/useExpiration'; import { MessageState } from '../../../../logic/messages/messagesTypes'; interface Props { message: MessageState; autoDelete?: boolean; } const ExtraExpirationSentExpirationAutoDelete = ({ message, autoDelete }: Props) => { const { expirationMessage, expiresInLessThan24Hours } = useExpiration(message, autoDelete); return ( <div className={clsx( 'bg-norm rounded border flex flex-align-items-center py-2 px-2 mb-2 gap-4', expiresInLessThan24Hours && 'color-danger border-danger' )} data-testid="expiration-banner" > <Icon name={autoDelete ? 'trash-clock' : 'hourglass'} className="flex-item-noshrink" /> <span className="flex flex-item-fluid flex-align-items-center">{expirationMessage}</span> </div> ); }; export default ExtraExpirationSentExpirationAutoDelete;
3,638
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/expiration/ExtraExpirationTime.test.tsx
import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { clearAll, render } from '../../../../helpers/test/helper'; import ExtraExpirationTime from './ExtraExpirationTime'; const getExpirationTime = (numberOfSeconds: number) => { return new Date().getTime() / 1000 + numberOfSeconds; }; describe('ExtraExpirationTime', () => { const seconds = 50; const setup = async (ExpirationTime: number) => { const result = await render( <ExtraExpirationTime message={{ localID: 'localID', data: { ExpirationTime } as Message }} /> ); const rerender = async (ExpirationTime: number) => { await result.rerender( <ExtraExpirationTime message={{ localID: 'localID', data: { ExpirationTime } as Message }} /> ); return result.queryByTestId('expiration-banner'); }; return { banner: result.queryByTestId('expiration-banner'), rerender }; }; afterEach(() => { jest.clearAllMocks(); clearAll(); }); it('should return no expiration if no expiration time', async () => { const { banner } = await setup(0); expect(banner).toBe(null); }); it('should return the expiration message if there is expiration time', async () => { const ExpirationTime = getExpirationTime(seconds); const { banner } = await setup(ExpirationTime); expect(banner).not.toBe(null); const value = Number(/\d+/.exec(banner?.textContent || '')?.[0]); expect(value).toBeLessThanOrEqual(seconds); }); it('should be able to react to new message', async () => { const ExpirationTime = getExpirationTime(seconds); const result = await setup(0); let { banner } = result; expect(banner).toBe(null); banner = await result.rerender(ExpirationTime); expect(banner).not.toBe(null); banner = await result.rerender(0); expect(banner).toBe(null); }); });
3,639
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/extras/expiration/ExtraExpirationTime.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { FeatureCode, Icon, Tooltip, useFeature, useNotifications, useUser } from '@proton/components'; import clsx from '@proton/utils/clsx'; import { canSetExpiration } from '../../../../helpers/expiration'; import useExpiration from '../../../../hooks/useExpiration'; import { expireMessages } from '../../../../logic/messages/expire/messagesExpireActions'; import { MessageState } from '../../../../logic/messages/messagesTypes'; import { useAppDispatch } from '../../../../logic/store'; interface Props { message: MessageState; } const ExtraExpirationTime = ({ message }: Props) => { const { expirationMessage, expiresInLessThan24Hours, expirationDate } = useExpiration(message); const [user] = useUser(); const { createNotification } = useNotifications(); const { feature } = useFeature(FeatureCode.SetExpiration); const dispatch = useAppDispatch(); const canExpire = canSetExpiration(feature?.Value, user, message); const messageID = message.data?.ID || ''; const conversationID = message.data?.ConversationID; if (!expirationDate) { return null; } const handleClick = () => { if (user.isFree) { return; } void dispatch( expireMessages({ IDs: [messageID], conversationID, expirationTime: null, }) ); createNotification({ text: c('Success').t`Message expiration cancelled` }); }; return ( <div className={clsx( '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', expiresInLessThan24Hours && 'color-danger border-danger' )} > <div className="flex-item-fluid flex flex-nowrap mb-2 md:mb-0" data-testid="expiration-banner"> <Icon name="hourglass" className="mt-1 ml-0.5 flex-item-noshrink" /> <span className={clsx(!canExpire && 'mt-1', 'px-2 flex flex-item-fluid flex-align-items-center')}> {expirationMessage} </span> </div> {canExpire ? ( <span className="flex-item-noshrink flex-align-items-start flex w-full md:w-auto pt-0.5"> <Tooltip title={c('Cancel expiration of the message').t`Cancel expiration`}> <Button onClick={handleClick} size="small" color="weak" shape="outline" fullWidth className="rounded-sm" data-testid="unsubscribe-banner" > {c('Cancel expiration of the message').t`Cancel`} </Button> </Tooltip> </span> ) : null} </div> ); }; export default ExtraExpirationTime;
3,640
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/header/HeaderCollapsed.tsx
import { MouseEvent } from 'react'; import { c } from 'ttag'; import { Label } from '@proton/shared/lib/interfaces/Label'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { getHasOnlyIcsAttachments, hasAttachments, isDraft, isExpiring, isScheduled, } from '@proton/shared/lib/mail/messages'; import clsx from '@proton/utils/clsx'; import noop from '@proton/utils/noop'; import { MessageState } from '../../../logic/messages/messagesTypes'; import { Breakpoints } from '../../../models/utils'; import ItemAttachmentIcon from '../../list/ItemAttachmentIcon'; import ItemDate from '../../list/ItemDate'; import ItemLabels from '../../list/ItemLabels'; import ItemLocation from '../../list/ItemLocation'; import ItemStar from '../../list/ItemStar'; import ItemUnread from '../../list/ItemUnread'; import ItemExpiration from '../../list/item-expiration/ItemExpiration'; import RecipientItem from '../recipients/RecipientItem'; interface Props { labelID: string; labels?: Label[]; message: MessageState; messageLoaded: boolean; isSentMessage: boolean; isUnreadMessage: boolean; onExpand: () => void; breakpoints: Breakpoints; conversationIndex?: number; } const HeaderCollapsed = ({ labelID, labels, message, messageLoaded, isSentMessage, isUnreadMessage, onExpand, breakpoints, conversationIndex = 0, }: Props) => { const handleClick = (event: MouseEvent) => { if ((event.target as HTMLElement).closest('.stop-propagation')) { event.stopPropagation(); return; } onExpand(); }; const isDraftMessage = isDraft(message.data) && !message.draftFlags?.sending; const isOutboxMessage = message.draftFlags?.sending; const isScheduledMessage = isScheduled(message.data); const isExpiringMessage = isExpiring(message.data); const hasOnlyIcsAttachments = getHasOnlyIcsAttachments(message.data?.AttachmentInfo); return ( <div className={clsx([ 'message-header message-header-collapsed px-5 flex flex-nowrap flex-align-items-center', isSentMessage ? 'is-outbound' : 'is-inbound', isUnreadMessage && 'is-unread', !messageLoaded && 'is-loading', !message.draftFlags?.sending && 'cursor-pointer', ])} onClick={handleClick} data-testid={`message-header-collapsed:${conversationIndex}`} > <div className="flex flex-item-fluid flex-nowrap flex-align-items-center mr-2"> <RecipientItem message={message} recipientOrGroup={{ recipient: message.data?.Sender }} isLoading={!messageLoaded} showDropdown={false} hideAddress={true} onContactDetails={noop} onContactEdit={noop} /> {messageLoaded && isDraftMessage && ( <span className="badge-label-success ml-2 flex-item-noshrink">{c('Info').t`Draft`}</span> )} {messageLoaded && isOutboxMessage && !isScheduledMessage && ( <span className="badge-label-primary ml-2 flex-item-noshrink">{c('Info').t`Sending`}</span> )} {messageLoaded && isExpiringMessage && ( <ItemExpiration className="badge-label-weak ml-2 py-0-5 TOCHECK flex-item-no-shrink" expirationTime={message.data?.ExpirationTime} element={message.data as Message} labelID={labelID} /> )} {messageLoaded && ( <div className="ml-2 flex-item-fluid flex flex-nowrap"> <ItemLabels className="hidden md:inline-flex" element={message.data} labels={labels} labelID={labelID} maxNumber={breakpoints.isTablet ? 1 : 5} isCollapsed={false} data-testid="message-header-collapsed:labels" /> </div> )} </div> <div className="flex flex-align-items-center flex-nowrap flex-item-noshrink"> {messageLoaded ? ( <> <span className="message-header-star mr-2 flex"> <ItemStar element={message.data} /> </span> <span className="flex"> <ItemLocation element={message.data} labelID={labelID} /> </span> {!!hasAttachments(message.data) && ( <span className="mr-2 flex"> <ItemAttachmentIcon icon={hasOnlyIcsAttachments ? 'calendar-grid' : undefined} element={message.data} className="m-auto" /> </span> )} <span className="text-sm"> <ItemDate element={message.data} labelID={labelID} useTooltip /> </span> {isUnreadMessage && <ItemUnread element={message.data} labelID={labelID} className="ml-2" />} </> ) : ( <span className="message-header-metas ml-2 flex" /> )} </div> </div> ); }; export default HeaderCollapsed;
3,641
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/header/HeaderDropdown.tsx
import { MutableRefObject, ReactNode, useEffect, useState } from 'react'; import { Button } from '@proton/atoms'; import { Dropdown, DropdownButton, DropdownProps, DropdownSizeUnit, Tooltip, generateUID, usePopperAnchor, } from '@proton/components'; import { DropdownButtonProps } from '@proton/components/components/dropdown/DropdownButton'; export interface DropdownRenderProps { onClose: () => void; onLock: (lock: boolean) => void; onOpenAdditional: (index: number) => void; } export interface DropdownRender { contentProps?: DropdownProps['contentProps']; render: (props: DropdownRenderProps) => ReactNode; } interface Props extends Omit<DropdownButtonProps<typeof Button>, 'title' | 'content'> { dropDownClassName?: string; content?: ReactNode; title?: ReactNode; className?: string; children: DropdownRender; autoClose?: boolean; dropdownSize?: DropdownProps['size']; loading?: boolean; /** * Used on mobile to open an additional dropdown from the dropdown * The handler onOpenAdditional is passed to use them */ additionalDropdowns?: DropdownRender[]; externalToggleRef?: MutableRefObject<() => void>; } const HeaderDropdown = ({ title, content, children, autoClose, dropdownSize, loading, className, dropDownClassName, externalToggleRef, additionalDropdowns, ...rest }: Props) => { const [uid] = useState(generateUID('dropdown')); const [lock, setLock] = useState(false); const [additionalOpen, setAdditionalOpen] = useState<number>(); const { anchorRef, isOpen, toggle, close } = usePopperAnchor<HTMLButtonElement>(); const handleAdditionalClose = () => { setAdditionalOpen(undefined); }; useEffect(() => { if (externalToggleRef) { externalToggleRef.current = toggle; } }, []); return ( <> <Tooltip title={title}> <DropdownButton as={Button} className={className} ref={anchorRef} isOpen={isOpen} onClick={toggle} disabled={loading} aria-expanded={isOpen} {...rest} > {content} </DropdownButton> </Tooltip> <Dropdown id={uid} className={dropDownClassName} originalPlacement="bottom" autoClose={autoClose} autoCloseOutside={!lock} isOpen={isOpen} size={dropdownSize} anchorRef={anchorRef} onClose={close} contentProps={children.contentProps} > {children.render({ onClose: close, onLock: setLock, onOpenAdditional: setAdditionalOpen })} </Dropdown> {additionalDropdowns?.map((additionalDropdown, index) => { return ( <Dropdown key={index} // eslint-disable-line react/no-array-index-key id={`${uid}-${index}`} className={dropDownClassName} originalPlacement="bottom" autoClose={false} autoCloseOutside={!lock} isOpen={additionalOpen === index} size={{ maxWidth: DropdownSizeUnit.Viewport, maxHeight: DropdownSizeUnit.Viewport }} anchorRef={anchorRef} onClose={handleAdditionalClose} contentProps={additionalDropdown.contentProps} data-testid={`message-view-more-dropdown:additional-${index}`} > {additionalDropdown.render({ onClose: handleAdditionalClose, onLock: setLock, onOpenAdditional: setAdditionalOpen, })} </Dropdown> ); })} </> ); }; export default HeaderDropdown;
3,642
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/header/HeaderExpanded.tsx
import { MouseEvent } from 'react'; import { c } from 'ttag'; import { Button, Kbd } from '@proton/atoms'; import { ButtonGroup, Icon, Tooltip, useAddresses, useContactModals, useToggle } from '@proton/components'; import { shiftKey } from '@proton/shared/lib/helpers/browser'; import { scrollIntoView } from '@proton/shared/lib/helpers/dom'; import { MailSettings } from '@proton/shared/lib/interfaces'; import { Label } from '@proton/shared/lib/interfaces/Label'; import { VERIFICATION_STATUS } from '@proton/shared/lib/mail/constants'; import { getHasOnlyIcsAttachments, getRecipients, isInternal, isScheduled } from '@proton/shared/lib/mail/messages'; import clsx from '@proton/utils/clsx'; import useMailModel from 'proton-mail/hooks/useMailModel'; import { MESSAGE_ACTIONS } from '../../../constants'; import { useOnCompose, useOnMailTo } from '../../../containers/ComposeProvider'; import { isSelfAddress } from '../../../helpers/addresses'; import { MessageViewIcons } from '../../../helpers/message/icon'; import { ComposeTypes } from '../../../hooks/composer/useCompose'; import { useRecipientLabel } from '../../../hooks/contact/useRecipientLabel'; import { MessageState } from '../../../logic/messages/messagesTypes'; import { Breakpoints } from '../../../models/utils'; import ItemAttachmentIcon from '../../list/ItemAttachmentIcon'; import ItemDate from '../../list/ItemDate'; import ItemLabels from '../../list/ItemLabels'; import ItemLocation from '../../list/ItemLocation'; import ItemStar from '../../list/ItemStar'; import ItemSpyTrackerIcon from '../../list/spy-tracker/ItemSpyTrackerIcon'; import MailRecipients from '../recipients/MailRecipients'; import RecipientItem from '../recipients/RecipientItem'; import RecipientType from '../recipients/RecipientType'; import HeaderExtra from './HeaderExtra'; import HeaderMoreDropdown from './HeaderMoreDropdown'; interface Props { labelID: string; labels?: Label[]; mailSettings: MailSettings; message: MessageState; messageViewIcons: MessageViewIcons; isSentMessage: boolean; messageLoaded: boolean; bodyLoaded: boolean; sourceMode: boolean; onResignContact: () => void; onLoadRemoteImages: () => void; onLoadEmbeddedImages: () => void; onToggle: () => void; onBack: () => void; onSourceMode: (sourceMode: boolean) => void; breakpoints: Breakpoints; labelDropdownToggleRef: React.MutableRefObject<() => void>; moveDropdownToggleRef: React.MutableRefObject<() => void>; filterDropdownToggleRef: React.MutableRefObject<() => void>; parentMessageRef: React.RefObject<HTMLElement>; conversationIndex?: number; } const HeaderExpanded = ({ labelID, labels, message, messageViewIcons, isSentMessage, messageLoaded, bodyLoaded, sourceMode, onResignContact, onLoadRemoteImages, onLoadEmbeddedImages, mailSettings, onToggle, onBack, onSourceMode, breakpoints, labelDropdownToggleRef, moveDropdownToggleRef, filterDropdownToggleRef, parentMessageRef, conversationIndex = 0, }: Props) => { const [addresses = []] = useAddresses(); const { state: showDetails, toggle: toggleDetails } = useToggle(); const isSendingMessage = message.draftFlags?.sending; const hasOnlyIcsAttachments = getHasOnlyIcsAttachments(message.data?.AttachmentInfo); const isScheduledMessage = isScheduled(message.data); const { Shortcuts } = useMailModel('MailSettings'); const onCompose = useOnCompose(); const onMailTo = useOnMailTo(); const { modals, onDetails: onContactDetails, onEdit: onContactEdit } = useContactModals({ onMailTo }); const { getRecipientsOrGroups } = useRecipientLabel(); const recipients = getRecipients(message.data); const recipientsOrGroup = getRecipientsOrGroups(recipients); // Show trackers icon when body is loaded so that we do not display it before cleaning trackers in links const canShowTrackersIcon = bodyLoaded; const handleClick = (event: MouseEvent) => { if ( (event.target as HTMLElement).closest('.stop-propagation') || window.getSelection()?.toString().length || document.querySelector('.dropdown') ) { event.stopPropagation(); return; } onToggle(); }; const handleAttachmentIconClick = (e: MouseEvent) => { e.stopPropagation(); scrollIntoView(parentMessageRef.current, { block: 'end' }); }; const handleCompose = (action: MESSAGE_ACTIONS) => async () => { onCompose({ type: ComposeTypes.newMessage, action, referenceMessage: message, }); }; const hasSigningPublicKey = isInternal(message.data) && !isSelfAddress(message.data?.Sender.Address, addresses) && message.verification?.signingPublicKey && message.verification?.verificationStatus !== VERIFICATION_STATUS.SIGNED_AND_VALID; const hasAttachedPublicKey = !isSelfAddress(message.data?.Sender?.Address, addresses) && message.verification?.attachedPublicKeys && message.verification?.verificationStatus !== VERIFICATION_STATUS.SIGNED_AND_VALID; const showPinPublicKey = hasSigningPublicKey || hasAttachedPublicKey; const { isNarrow } = breakpoints; const from = ( <RecipientItem message={message} recipientOrGroup={{ recipient: message.data?.Sender }} isLoading={!messageLoaded} signingPublicKey={showPinPublicKey ? message.verification?.signingPublicKey : undefined} attachedPublicKey={showPinPublicKey ? message.verification?.attachedPublicKeys?.[0] : undefined} isNarrow={isNarrow} globalIcon={messageViewIcons.globalIcon} onContactDetails={onContactDetails} onContactEdit={onContactEdit} customDataTestId="recipients:sender" /> ); const titleReply = Shortcuts ? ( <> {c('Title').t`Reply`} <br /> <Kbd shortcut="R" /> </> ) : ( c('Title').t`Reply` ); const titleReplyAll = Shortcuts ? ( <> {c('Title').t`Reply all`} <br /> <Kbd shortcut={shiftKey} /> + <Kbd shortcut="R" /> </> ) : ( c('Title').t`Reply all` ); const titleForward = Shortcuts ? ( <> {c('Title').t`Forward`} <br /> <Kbd shortcut={shiftKey} /> + <Kbd shortcut="F" /> </> ) : ( c('Title').t`Forward` ); return ( <div className={clsx([ 'message-header px-5 message-header-expanded', isSentMessage ? 'is-outbound' : 'is-inbound', !messageLoaded && 'is-loading', showDetails ? 'message-header-expanded--with-details' : 'message-header-expanded--without-details', ])} data-testid={`message-header-expanded:${conversationIndex}`} > {canShowTrackersIcon && <ItemSpyTrackerIcon message={message} />} {isNarrow && messageLoaded && ( <div className="flex flex-align-items-center flex-justify-space-between my-2" onClick={handleClick}> <span className="inline-flex"> <ItemLocation element={message.data} labelID={labelID} /> <ItemAttachmentIcon icon={hasOnlyIcsAttachments ? 'calendar-grid' : undefined} onClick={handleAttachmentIconClick} element={message.data} className="mr-2" /> </span> <ItemDate element={message.data} labelID={labelID} useTooltip className="color-weak text-sm" /> <span className="message-header-star mr-2 inline-flex"> <ItemStar element={message.data} /> </span> </div> )} <div className="flex flex-nowrap flex-align-items-center message-header-from-container" onClick={handleClick} > <span className="flex flex-item-fluid flex-nowrap mr-2"> <div className={clsx(['flex flex-nowrap', !messageLoaded && 'flex-item-fluid'])}> {isNarrow ? ( <span className="message-header-recipient-mobile">{from}</span> ) : ( <RecipientType label={c('Label Recipient').t`From`}>{from}</RecipientType> )} {messageLoaded && isSendingMessage && !isScheduledMessage && ( <span className="ml-2 flex-item-noshrink my-auto"> <span className="badge-label-primary">{c('Info').t`Sending`}</span> </span> )} </div> </span> {!isNarrow && ( <div className="message-header-metas-container flex flex-align-items-center flex-item-noshrink" data-testid="message:message-header-metas" > <span className="message-header-star mr-2 inline-flex"> <ItemStar element={message.data} /> </span> {messageLoaded && ( <> <span className="inline-flex"> <ItemLocation element={message.data} labelID={labelID} /> <ItemAttachmentIcon icon={hasOnlyIcsAttachments ? 'calendar-grid' : undefined} onClick={handleAttachmentIconClick} element={message.data} className="mr-2 mt-0.5" /> </span> <ItemDate element={message.data} labelID={labelID} useTooltip className="text-sm" /> </> )} {!messageLoaded && <span className="message-header-metas ml-2 inline-flex" />} </div> )} </div> <div className="flex flex-nowrap flex-align-items-center mb-2 on-mobile-flex-wrap message-header-ccbcc-container"> <MailRecipients message={message} recipientsOrGroup={recipientsOrGroup} mapStatusIcons={messageViewIcons.mapStatusIcon} isLoading={!messageLoaded} expanded={showDetails} toggleDetails={toggleDetails} onContactDetails={onContactDetails} onContactEdit={onContactEdit} /> </div> {showDetails && ( <div className="mb-2 flex flex-nowrap color-weak"> <span className="flex-align-self-center mr-2 text-ellipsis"> <ItemDate element={message.data} labelID={labelID} mode="full" useTooltip /> </span> </div> )} <HeaderExtra message={message} sourceMode={sourceMode} onResignContact={onResignContact} messageLoaded={messageLoaded} onLoadRemoteImages={onLoadRemoteImages} onLoadEmbeddedImages={onLoadEmbeddedImages} /> {messageLoaded && ( <> <div className="mb-3 flex-item-noshrink flex flex-align-items-center message-header-expanded-label-container"> <ItemLabels element={message.data} labelID={labelID} labels={labels} isCollapsed={false} className="pt-1 md:pt-0 ml-2" /> </div> </> )} <div className="pt-0 flex flex-justify-space-between"> <div className="flex"> <HeaderMoreDropdown labelID={labelID} message={message} messageLoaded={messageLoaded} sourceMode={sourceMode} onBack={onBack} onToggle={onToggle} onSourceMode={onSourceMode} breakpoints={breakpoints} parentMessageRef={parentMessageRef} mailSettings={mailSettings} messageViewIcons={messageViewIcons} onContactDetails={onContactDetails} onContactEdit={onContactEdit} labelDropdownToggleRef={labelDropdownToggleRef} moveDropdownToggleRef={moveDropdownToggleRef} filterDropdownToggleRef={filterDropdownToggleRef} /> </div> {!isScheduledMessage && ( <ButtonGroup className="mb-2"> <Tooltip title={titleReply}> <Button icon disabled={!messageLoaded || !bodyLoaded || isSendingMessage} onClick={handleCompose(MESSAGE_ACTIONS.REPLY)} data-testid="message-view:reply" > <Icon name="arrow-up-and-left-big" className="on-rtl-mirror" alt={c('Title').t`Reply`} /> </Button> </Tooltip> <Tooltip title={titleReplyAll}> <Button icon disabled={!messageLoaded || !bodyLoaded || isSendingMessage} onClick={handleCompose(MESSAGE_ACTIONS.REPLY_ALL)} data-testid="message-view:reply-all" > <Icon name="arrows-up-and-left-big" className="on-rtl-mirror" alt={c('Title').t`Reply all`} /> </Button> </Tooltip> <Tooltip title={titleForward}> <Button icon disabled={!messageLoaded || !bodyLoaded || isSendingMessage} onClick={handleCompose(MESSAGE_ACTIONS.FORWARD)} data-testid="message-view:forward" > <Icon name="arrow-up-and-right-big" className="on-rtl-mirror" alt={c('Title').t`Forward`} /> </Button> </Tooltip> </ButtonGroup> )} </div> {modals} </div> ); }; export default HeaderExpanded;
3,643
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/header/HeaderExtra.tsx
import { isReceived, isScheduled, isSnoozed } from '@proton/shared/lib/mail/messages'; import { getMessageHasData } from '../../../helpers/message/messages'; import useMailModel from '../../../hooks/useMailModel'; import { MessageState } from '../../../logic/messages/messagesTypes'; import useScheduleSendFeature from '../../composer/actions/scheduleSend/useScheduleSendFeature'; import ExtraAskResign from '../extras/ExtraAskResign'; import ExtraAutoReply from '../extras/ExtraAutoReply'; import ExtraBlockedSender from '../extras/ExtraBlockedSender'; import ExtraDarkStyle from '../extras/ExtraDarkStyle'; import ExtraDecryptedSubject from '../extras/ExtraDecryptedSubject'; import ExtraErrors from '../extras/ExtraErrors'; import ExtraEvents from '../extras/ExtraEvents'; import ExtraImages from '../extras/ExtraImages'; import ExtraPinKey from '../extras/ExtraPinKey'; import ExtraReadReceipt from '../extras/ExtraReadReceipt'; import ExtraScheduledMessage from '../extras/ExtraScheduledMessage'; import ExtraSnoozedMessage from '../extras/ExtraSnoozedMessage'; import ExtraSpamScore from '../extras/ExtraSpamScore'; import ExtraUnsubscribe from '../extras/ExtraUnsubscribe'; import EmailReminderWidget from '../extras/calendar/EmailReminderWidget'; import ExtraExpiration from '../extras/expiration/ExtraExpiration'; interface Props { message: MessageState; sourceMode: boolean; onResignContact: () => void; messageLoaded: boolean; onLoadRemoteImages: () => void; onLoadEmbeddedImages: () => void; } const HeaderExtra = ({ message, sourceMode, messageLoaded, onResignContact, onLoadRemoteImages, onLoadEmbeddedImages, }: Props) => { const mailSettings = useMailModel('MailSettings'); const received = isReceived(message.data); const { canScheduleSend } = useScheduleSendFeature(); const isScheduledMessage = isScheduled(message.data); const isSnoozeMessage = isSnoozed(message.data); const showCalendarWidget = messageLoaded && received; if (!getMessageHasData(message)) { return null; } return ( <section className="message-header-extra pt-2 hidden-empty"> <ExtraDecryptedSubject message={message} /> <ExtraSpamScore message={message} /> <ExtraErrors message={message} /> <ExtraAutoReply message={message.data} /> <ExtraUnsubscribe message={message.data} /> <ExtraBlockedSender message={message} /> {message.verification && <ExtraPinKey message={message.data} messageVerification={message.verification} />} <ExtraAskResign message={message.data} messageVerification={message.verification} onResignContact={onResignContact} /> {!sourceMode && ( <ExtraImages messageImages={message.messageImages} type="remote" onLoadImages={onLoadRemoteImages} mailSettings={mailSettings} /> )} {showCalendarWidget ? <EmailReminderWidget message={message.data} errors={message.errors} /> : null} {showCalendarWidget ? <ExtraEvents message={message} /> : null} {isScheduledMessage && canScheduleSend ? <ExtraScheduledMessage message={message} /> : null} {isSnoozeMessage ? <ExtraSnoozedMessage message={message} /> : null} <ExtraExpiration message={message} /> <span className="inline-flex flex-row w-full md:w-auto hidden-empty"> <ExtraReadReceipt message={message.data} /> {!sourceMode && ( <ExtraImages messageImages={message.messageImages} type="embedded" onLoadImages={onLoadEmbeddedImages} mailSettings={mailSettings} /> )} <ExtraDarkStyle message={message} /> </span> </section> ); }; export default HeaderExtra;
3,644
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/header/HeaderMoreDropdown.tsx
import { useRef } from 'react'; import { useLocation } from 'react-router-dom'; import { addDays } from 'date-fns'; import { c } from 'ttag'; import { Button, Kbd } from '@proton/atoms'; import { ButtonGroup, DropdownMenu, DropdownMenuButton, DropdownSizeUnit, FeatureCode, Icon, Tooltip, useApi, useEventManager, useFeature, useFolders, useModalState, useNotifications, useUser, } from '@proton/components'; import { ContactEditProps } from '@proton/components/containers/contacts/edit/ContactEditModal'; import { WorkerDecryptionResult } from '@proton/crypto'; import { useLoading } from '@proton/hooks'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import downloadFile from '@proton/shared/lib/helpers/downloadFile'; import { MailSettings } from '@proton/shared/lib/interfaces'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import useMailModel from 'proton-mail/hooks/useMailModel'; import { formatFileNameDate } from '../../../helpers/date'; import { isStarred as IsMessageStarred, getDate } from '../../../helpers/elements'; import { canSetExpiration, getExpirationTime } from '../../../helpers/expiration'; import { getCurrentFolderID, getFolderName } from '../../../helpers/labels'; import { isConversationMode } from '../../../helpers/mailSettings'; import { MessageViewIcons } from '../../../helpers/message/icon'; import { exportBlob } from '../../../helpers/message/messageExport'; import { MARK_AS_STATUS, useMarkAs } from '../../../hooks/actions/useMarkAs'; import { useMoveToFolder } from '../../../hooks/actions/useMoveToFolder'; import { useStar } from '../../../hooks/actions/useStar'; import { useGetAttachment } from '../../../hooks/attachments/useAttachment'; import { useGetMessageKeys } from '../../../hooks/message/useGetMessageKeys'; import { updateAttachment } from '../../../logic/attachments/attachmentsActions'; import { expireMessages } from '../../../logic/messages/expire/messagesExpireActions'; import { MessageState, MessageStateWithData, MessageWithOptionalBody } from '../../../logic/messages/messagesTypes'; import { useAppDispatch } from '../../../logic/store'; import { Element } from '../../../models/element'; import { Breakpoints } from '../../../models/utils'; import CustomFilterDropdown from '../../dropdown/CustomFilterDropdown'; import LabelDropdown, { labelDropdownContentProps } from '../../dropdown/LabelDropdown'; import MoveDropdown, { moveDropdownContentProps } from '../../dropdown/MoveDropdown'; import CustomExpirationModal from '../modals/CustomExpirationModal'; import MessageDetailsModal from '../modals/MessageDetailsModal'; import MessageHeadersModal from '../modals/MessageHeadersModal'; import MessagePermanentDeleteModal from '../modals/MessagePermanentDeleteModal'; import MessagePhishingModal from '../modals/MessagePhishingModal'; import MessagePrintModal from '../modals/MessagePrintModal'; import HeaderDropdown, { DropdownRender } from './HeaderDropdown'; const { INBOX, TRASH, SPAM, ARCHIVE } = MAILBOX_LABEL_IDS; interface Props { labelID: string; message: MessageState; messageLoaded: boolean; sourceMode: boolean; onBack: () => void; onToggle: () => void; onSourceMode: (sourceMode: boolean) => void; breakpoints: Breakpoints; parentMessageRef: React.RefObject<HTMLElement>; mailSettings: MailSettings; messageViewIcons: MessageViewIcons; onContactDetails: (contactID: string) => void; onContactEdit: (props: ContactEditProps) => void; labelDropdownToggleRef: React.MutableRefObject<() => void>; moveDropdownToggleRef: React.MutableRefObject<() => void>; filterDropdownToggleRef: React.MutableRefObject<() => void>; } const HeaderMoreDropdown = ({ labelID, message, messageLoaded, sourceMode, onBack, onToggle, onSourceMode, breakpoints, parentMessageRef, mailSettings, messageViewIcons, onContactDetails, onContactEdit, labelDropdownToggleRef, moveDropdownToggleRef, filterDropdownToggleRef, }: Props) => { const location = useLocation(); const api = useApi(); const getAttachment = useGetAttachment(); const { createNotification } = useNotifications(); const dispatch = useAppDispatch(); const [loading, withLoading] = useLoading(); const star = useStar(); const [user] = useUser(); const { feature } = useFeature(FeatureCode.SetExpiration); const { call } = useEventManager(); const closeDropdown = useRef<() => void>(); const { moveToFolder, moveScheduledModal, moveSnoozedModal, moveAllModal, moveToSpamModal } = useMoveToFolder(); const [folders = []] = useFolders(); const markAs = useMarkAs(); const getMessageKeys = useGetMessageKeys(); const { Shortcuts } = useMailModel('MailSettings'); const [CustomExpirationModalProps, openCustomExpirationModal, renderCustomExpirationModal] = useModalState(); const [messageDetailsModalProps, setMessageDetailsModalOpen] = useModalState(); const [messageHeaderModalProps, setMessageHeaderModalOpen] = useModalState(); const [messagePrintModalProps, setMessagePrintModalOpen, renderPrintModal] = useModalState(); const [messagePhishingModalProps, setMessagePhishingModalOpen] = useModalState(); const [messagePermanentDeleteModalProps, setMessagePermanentDeleteModalOpen] = useModalState(); const canExpire = canSetExpiration(feature?.Value, user, message); const isStarred = IsMessageStarred(message.data || ({} as Element)); const messageID = message.data?.ID || ''; const staringText = isStarred ? c('Action').t`Unstar` : c('Action').t`Star`; const willExpire = !!message.data?.ExpirationTime; const handleMove = (folderID: string, fromFolderID: string) => async () => { closeDropdown.current?.(); const folderName = getFolderName(folderID, folders); await moveToFolder([message.data || ({} as Element)], folderID, folderName, fromFolderID, false); }; const handleUnread = async () => { closeDropdown.current?.(); onToggle(); if (isConversationMode(labelID, mailSettings, location)) { parentMessageRef.current?.focus(); } else { onBack(); } markAs([message.data as Element], labelID, MARK_AS_STATUS.UNREAD); await call(); }; const onUpdateAttachment = (ID: string, attachment: WorkerDecryptionResult<Uint8Array>) => { dispatch(updateAttachment({ ID, attachment })); }; const handleExport = async () => { // Angular/src/app/message/directives/actionMessage.js const messageKeys = await getMessageKeys(message.data as Message); const { Subject = '' } = message.data || {}; const time = formatFileNameDate(getDate(message.data, labelID)); const blob = await exportBlob(message, messageKeys, getAttachment, onUpdateAttachment, api); const filename = `${Subject} ${time}.eml`; downloadFile(blob, filename); }; const handleStar = async () => { if (!loading) { void withLoading(star([message.data || ({} as Element)], !isStarred)); } }; const handleExpire = (days: number) => { const date = days ? addDays(new Date(), days) : undefined; const expirationTime = getExpirationTime(date); void dispatch( expireMessages({ IDs: [messageID], conversationID: message.data?.ConversationID, expirationTime, }) ); createNotification({ text: days ? c('Success').t`Self-destruction set` : c('Success').t`Self-destruction removed`, }); }; const handleCustomExpiration = (expirationDate: Date) => { const expirationTime = getExpirationTime(expirationDate); void dispatch( expireMessages({ IDs: [messageID], conversationID: message.data?.ConversationID, expirationTime, }) ); openCustomExpirationModal(false); createNotification({ text: c('Success').t`Self-destruction set` }); }; const messageLabelIDs = message.data?.LabelIDs || []; const selectedIDs = [messageID]; const isSpam = messageLabelIDs.includes(SPAM); const isInTrash = messageLabelIDs.includes(TRASH); const fromFolderID = getCurrentFolderID(messageLabelIDs, folders); const { isNarrow } = breakpoints; const additionalDropdowns: DropdownRender[] | undefined = isNarrow ? [ { contentProps: moveDropdownContentProps, render: ({ onClose, onLock }) => ( <MoveDropdown labelID={fromFolderID} selectedIDs={selectedIDs} onClose={onClose} onLock={onLock} breakpoints={breakpoints} /> ), }, { contentProps: labelDropdownContentProps, render: ({ onClose, onLock }) => ( <LabelDropdown labelID={labelID} selectedIDs={selectedIDs} onClose={onClose} onLock={onLock} breakpoints={breakpoints} /> ), }, { render: ({ onClose, onLock }) => ( <CustomFilterDropdown message={message.data as Message} onClose={onClose} onLock={onLock} /> ), }, ] : undefined; const titleMoveInboxNotSpam = Shortcuts ? ( <> {c('Title').t`Move to inbox (not spam)`} <br /> <Kbd shortcut="I" /> </> ) : ( c('Title').t`Move to inbox (not spam)` ); const titleUnread = Shortcuts ? ( <> {c('Title').t`Mark as unread`} <br /> <Kbd shortcut="U" /> </> ) : ( c('Title').t`Mark as unread` ); const titleMoveInbox = Shortcuts ? ( <> {c('Title').t`Move to inbox`} <br /> <Kbd shortcut="I" /> </> ) : ( c('Title').t`Move to inbox` ); const titleMoveTrash = Shortcuts ? ( <> {c('Title').t`Move to trash`} <br /> <Kbd shortcut="T" /> </> ) : ( c('Title').t`Move to trash` ); const titleMoveTo = Shortcuts ? ( <> {c('Title').t`Move to`} <br /> <Kbd shortcut="M" /> </> ) : ( c('Title').t`Move to` ); const titleLabelAs = Shortcuts ? ( <> {c('Title').t`Label as`} <br /> <Kbd shortcut="L" /> </> ) : ( c('Title').t`Label as` ); const titleFilterOn = Shortcuts ? ( <> {c('Title').t`Filter on...`} <br /> <Kbd shortcut="F" /> </> ) : ( c('Title').t`Filter on...` ); return ( <> <ButtonGroup className="mr-4 mb-2"> {isSpam ? ( <Tooltip title={titleMoveInboxNotSpam}> <Button icon disabled={!messageLoaded} onClick={handleMove(INBOX, SPAM)} data-testid="message-header-expanded:move-spam-to-inbox" > <Icon name="fire-slash" alt={c('Title').t`Move to inbox (not spam)`} /> </Button> </Tooltip> ) : ( <Tooltip title={titleUnread}> <Button icon disabled={!messageLoaded} onClick={handleUnread} data-testid="message-header-expanded:mark-as-unread" > <Icon name="envelope-dot" alt={c('Title').t`Mark as unread`} /> </Button> </Tooltip> )} {isInTrash ? ( <Tooltip title={titleMoveInbox}> <Button icon disabled={!messageLoaded} onClick={handleMove(INBOX, TRASH)} data-testid="message-header-expanded:move-trashed-to-inbox" > <Icon name="inbox" alt={c('Title').t`Move to inbox`} /> </Button> </Tooltip> ) : ( <Tooltip title={titleMoveTrash}> <Button icon disabled={!messageLoaded} onClick={handleMove(TRASH, fromFolderID)} data-testid="message-header-expanded:move-to-trash" > <Icon name="trash" alt={c('Title').t`Move to trash`} /> </Button> </Tooltip> )} {!isNarrow && [ <HeaderDropdown key="message-header-expanded:folder-dropdown" icon autoClose={false} dropdownSize={{ maxWidth: '22em', maxHeight: DropdownSizeUnit.Viewport }} content={<Icon name="folder-arrow-in" alt={c('Action').t`Move to`} />} className="messageMoveDropdownButton" dropDownClassName="move-dropdown" title={titleMoveTo} loading={!messageLoaded} externalToggleRef={moveDropdownToggleRef} data-testid="message-header-expanded:folder-dropdown" > {{ contentProps: moveDropdownContentProps, render: ({ onClose, onLock }) => ( <MoveDropdown labelID={fromFolderID} selectedIDs={selectedIDs} onClose={onClose} onLock={onLock} breakpoints={breakpoints} /> ), }} </HeaderDropdown>, <HeaderDropdown key="message-header-expanded:label-dropdown" icon autoClose={false} dropdownSize={{ maxWidth: '22em', maxHeight: DropdownSizeUnit.Viewport }} content={<Icon name="tag" alt={c('Action').t`Label as`} />} className="messageLabelDropdownButton" dropDownClassName="label-dropdown" title={titleLabelAs} loading={!messageLoaded} externalToggleRef={labelDropdownToggleRef} data-testid="message-header-expanded:label-dropdown" > {{ contentProps: labelDropdownContentProps, render: ({ onClose, onLock }) => ( <LabelDropdown labelID={labelID} selectedIDs={selectedIDs} onClose={onClose} onLock={onLock} breakpoints={breakpoints} /> ), }} </HeaderDropdown>, <HeaderDropdown key="message-header-expanded:filter-dropdown" icon autoClose={false} dropdownSize={{ maxWidth: DropdownSizeUnit.Viewport, maxHeight: DropdownSizeUnit.Viewport }} content={<Icon name="filter" alt={c('Action').t`Filter on...`} />} className="messageFilterDropdownButton" dropDownClassName="filter-dropdown" title={titleFilterOn} loading={!messageLoaded} externalToggleRef={filterDropdownToggleRef} data-testid="message-header-expanded:filter-dropdown" > {{ render: ({ onClose, onLock }) => ( <CustomFilterDropdown message={message.data as Message} onClose={onClose} onLock={onLock} /> ), }} </HeaderDropdown>, ]} <HeaderDropdown icon disabled={!messageLoaded} autoClose title={c('Title').t`More`} content={<Icon name="three-dots-horizontal" alt={c('Title').t`More options`} />} additionalDropdowns={additionalDropdowns} data-testid="message-header-expanded:more-dropdown" dropdownSize={{ maxWidth: DropdownSizeUnit.Viewport, maxHeight: DropdownSizeUnit.Viewport }} > {{ render: ({ onClose, onOpenAdditional }) => { closeDropdown.current = onClose; return ( <DropdownMenu> <DropdownMenuButton className="text-left flex flex-nowrap flex-align-items-center" onClick={handleStar} data-testid="message-view-more-dropdown:star" > <Icon name={isStarred ? 'star-slash' : 'star'} className="mr-2" /> <span className="flex-item-fluid my-auto">{staringText}</span> </DropdownMenuButton> <hr className="my-2" /> <DropdownMenuButton className="text-left flex flex-nowrap flex-align-items-center" onClick={handleMove(ARCHIVE, fromFolderID)} data-testid="message-view-more-dropdown:archive" > <Icon name="archive-box" className="mr-2" /> <span className="flex-item-fluid my-auto">{c('Action').t`Archive`}</span> </DropdownMenuButton> {isNarrow && ( <DropdownMenuButton className="text-left flex flex-nowrap flex-align-items-center" onClick={() => onOpenAdditional(0)} > <Icon name="folder-arrow-in" className="mr-2" /> <span className="flex-item-fluid my-auto">{c('Action').t`Move to...`}</span> </DropdownMenuButton> )} {isNarrow && ( <DropdownMenuButton className="text-left flex flex-nowrap flex-align-items-center" onClick={() => onOpenAdditional(1)} > <Icon name="tag" className="mr-2" /> <span className="flex-item-fluid my-auto">{c('Action') .t`Label as...`}</span> </DropdownMenuButton> )} {isNarrow && ( <DropdownMenuButton className="text-left flex flex-nowrap flex-align-items-center" onClick={() => onOpenAdditional(2)} > <Icon name="filter" className="mr-2" /> <span className="flex-item-fluid my-auto">{c('Action') .t`Filter on...`}</span> </DropdownMenuButton> )} {isSpam ? ( <DropdownMenuButton className="text-left flex flex-nowrap flex-align-items-center" onClick={handleUnread} data-testid="message-view-more-dropdown:unread" > <Icon name="eye-slash" className="mr-2" /> <span className="flex-item-fluid my-auto">{c('Action') .t`Mark as unread`}</span> </DropdownMenuButton> ) : ( <DropdownMenuButton className="text-left flex flex-nowrap flex-align-items-center" onClick={handleMove(SPAM, fromFolderID)} data-testid="message-view-more-dropdown:move-to-spam" > <Icon name="fire" className="mr-2" /> <span className="flex-item-fluid my-auto">{c('Action') .t`Move to spam`}</span> </DropdownMenuButton> )} {isInTrash ? ( <DropdownMenuButton className="text-left flex flex-nowrap flex-align-items-center" onClick={() => setMessagePermanentDeleteModalOpen(true)} data-testid="message-view-more-dropdown:delete" > <Icon name="cross-circle" className="mr-2" /> <span className="flex-item-fluid my-auto">{c('Action').t`Delete`}</span> </DropdownMenuButton> ) : null} {canExpire ? ( <> <hr className="my-2" /> {willExpire ? ( <DropdownMenuButton className="text-left flex flex-nowrap flex-align-items-center" onClick={() => handleExpire(0)} data-testid="message-view-more-dropdown:remove-expiration" > <Icon name="hourglass" className="mr-2" /> <span className="flex-item-fluid my-auto">{c('Action') .t`Remove self-destruction`}</span> </DropdownMenuButton> ) : ( <> <DropdownMenuButton className="text-left flex flex-nowrap flex-align-items-center" onClick={() => handleExpire(7)} data-testid="message-view-more-dropdown:expire-7-days" > <Icon name="hourglass" className="mr-2" /> <span className="flex-item-fluid my-auto">{c('Action') .t`Self-destruct in 7 days`}</span> </DropdownMenuButton> <DropdownMenuButton className="text-left flex flex-nowrap flex-align-items-center" onClick={() => openCustomExpirationModal(true)} data-testid="message-view-more-dropdown:expire-30-days" > <Icon name="hourglass" className="mr-2" /> <span className="flex-item-fluid my-auto">{c('Action') .t`Self-destruct on ...`}</span> </DropdownMenuButton> </> )} </> ) : null} <hr className="my-2" /> <DropdownMenuButton className="text-left flex flex-nowrap flex-align-items-center" onClick={handleExport} data-testid="message-view-more-dropdown:export" > <Icon name="arrow-up-from-square" className="mr-2" /> <span className="flex-item-fluid my-auto">{c('Action').t`Export`}</span> </DropdownMenuButton> <DropdownMenuButton className="text-left flex flex-nowrap flex-align-items-center" onClick={() => setMessagePrintModalOpen(true)} data-testid="message-view-more-dropdown:print" > <Icon name="printer" className="mr-2" /> <span className="flex-item-fluid my-auto">{c('Action').t`Print`}</span> </DropdownMenuButton> <hr className="my-2" /> <DropdownMenuButton className="text-left flex flex-nowrap flex-align-items-center" onClick={() => setMessageDetailsModalOpen(true)} data-testid="message-view-more-dropdown:view-message-details" > <Icon name="list-bullets" className="mr-2" /> <span className="flex-item-fluid my-auto">{c('Action') .t`View message details`}</span> </DropdownMenuButton> <DropdownMenuButton className="text-left flex flex-nowrap flex-align-items-center" onClick={() => setMessageHeaderModalOpen(true)} data-testid="message-view-more-dropdown:view-message-headers" > <Icon name="window-terminal" className="mr-2" /> <span className="flex-item-fluid my-auto">{c('Action').t`View headers`}</span> </DropdownMenuButton> {!sourceMode && ( <DropdownMenuButton className="text-left flex flex-nowrap flex-align-items-center" onClick={() => onSourceMode(true)} data-testid="message-view-more-dropdown:view-html" > <Icon name="code" className="mr-2" /> <span className="flex-item-fluid my-auto">{c('Action').t`View HTML`}</span> </DropdownMenuButton> )} {sourceMode && ( <DropdownMenuButton className="text-left flex flex-nowrap flex-align-items-center" onClick={() => onSourceMode(false)} data-testid="message-view-more-dropdown:view-rendered-html" > <Icon name="window-image" className="mr-2" /> <span className="flex-item-fluid my-auto">{c('Action') .t`View rendered HTML`}</span> </DropdownMenuButton> )} <hr className="my-2" /> <DropdownMenuButton className="text-left flex flex-nowrap flex-align-items-center color-danger" onClick={() => setMessagePhishingModalOpen(true)} data-testid="message-view-more-dropdown:report-phishing" > <Icon name="hook" className="mr-2 color-danger" /> <span className="flex-item-fluid my-auto color-danger">{c('Action') .t`Report phishing`}</span> </DropdownMenuButton> </DropdownMenu> ); }, }} </HeaderDropdown> </ButtonGroup> <MessageDetailsModal labelID={labelID} message={message} mailSettings={mailSettings} messageViewIcons={messageViewIcons} messageLoaded={messageLoaded} onContactDetails={onContactDetails} onContactEdit={onContactEdit} {...messageDetailsModalProps} /> <MessageHeadersModal message={message.data} {...messageHeaderModalProps} /> {renderPrintModal && ( <MessagePrintModal message={message as MessageStateWithData} labelID={labelID} {...messagePrintModalProps} /> )} <MessagePhishingModal message={message} onBack={onBack} {...messagePhishingModalProps} /> <MessagePermanentDeleteModal message={message.data as MessageWithOptionalBody} {...messagePermanentDeleteModalProps} /> {moveScheduledModal} {moveSnoozedModal} {moveAllModal} {moveToSpamModal} {renderCustomExpirationModal && ( <CustomExpirationModal onSubmit={handleCustomExpiration} {...CustomExpirationModalProps} /> )} </> ); }; export default HeaderMoreDropdown;
3,645
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/helpers/getIframeHtml.test.tsx
import { createDocument } from '../../../helpers/test/message'; import { MESSAGE_IFRAME_PRINT_CLASS, MESSAGE_IFRAME_PRINT_FOOTER_ID, MESSAGE_IFRAME_PRINT_HEADER_ID, } from '../constants'; import getIframeHtml from './getIframeHtml'; describe('getIframeHTML', () => { describe('rich text', () => { it('Should not contain print classes and elements', () => { const document = createDocument('hello buddy'); const htmlString = getIframeHtml({ emailContent: 'dude', messageDocument: document, isPlainText: false, isPrint: false, themeCSSVariables: '', }); expect(htmlString).not.toContain(MESSAGE_IFRAME_PRINT_CLASS); expect(htmlString).not.toContain(MESSAGE_IFRAME_PRINT_HEADER_ID); expect(htmlString).not.toContain(MESSAGE_IFRAME_PRINT_FOOTER_ID); }); it('Should contain print classes and elements', () => { const document = createDocument('hello buddy'); const htmlString = getIframeHtml({ emailContent: 'dude', messageDocument: document, isPlainText: false, isPrint: true, themeCSSVariables: '', }); expect(htmlString).toContain(MESSAGE_IFRAME_PRINT_CLASS); expect(htmlString).toContain(MESSAGE_IFRAME_PRINT_HEADER_ID); expect(htmlString).toContain(MESSAGE_IFRAME_PRINT_FOOTER_ID); }); }); describe('plain text', () => { it('Should not contain print classes and elements', () => { const document = createDocument('hello buddy'); const htmlString = getIframeHtml({ emailContent: 'dude', messageDocument: document, isPlainText: true, isPrint: false, themeCSSVariables: '', }); expect(htmlString).not.toContain(MESSAGE_IFRAME_PRINT_CLASS); expect(htmlString).not.toContain(MESSAGE_IFRAME_PRINT_HEADER_ID); expect(htmlString).not.toContain(MESSAGE_IFRAME_PRINT_FOOTER_ID); }); it('Should not contain print classes and elements', () => { const document = createDocument('hello buddy'); const htmlString = getIframeHtml({ emailContent: 'dude', messageDocument: document, isPlainText: true, isPrint: true, themeCSSVariables: '', }); expect(htmlString).toContain(MESSAGE_IFRAME_PRINT_CLASS); expect(htmlString).toContain(MESSAGE_IFRAME_PRINT_HEADER_ID); expect(htmlString).toContain(MESSAGE_IFRAME_PRINT_FOOTER_ID); }); }); });
3,646
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/helpers/getIframeHtml.ts
import svg from '@proton/styles/assets/img/icons/email-sprite-icons.svg'; import { locateHead } from '../../../helpers/message/messageHead'; import { MessageState } from '../../../logic/messages/messagesTypes'; import { MESSAGE_IFRAME_PRINT_CLASS, MESSAGE_IFRAME_PRINT_FOOTER_ID, MESSAGE_IFRAME_PRINT_HEADER_ID, MESSAGE_IFRAME_ROOT_ID, } from '../constants'; import cssStyles from '../MessageIframe.raw.scss'; type Options = { emailContent: string; messageDocument: Required<MessageState>['messageDocument']['document']; isPlainText: boolean; themeCSSVariables: string; isPrint: boolean; }; const getIframeHtml = ({ emailContent, messageDocument, isPlainText, themeCSSVariables, isPrint }: Options) => { const messageHead = locateHead(messageDocument) || ''; const bodyStyles = messageDocument?.querySelector('body')?.getAttribute('style'); const bodyClasses = messageDocument?.querySelector('body')?.getAttribute('class'); /** * About this line: * <div style="width: 100% !important;padding-bottom:10px;!important">${emailContent}</div> * Padding bottom is needed for the scrollbar */ // Plain text needs content needs to have no spaces in order to be correctly displayed if (isPlainText) { const emailHead = `<head><style>${themeCSSVariables}</style><style>${cssStyles}</style>${messageHead}</head>`; const emailBody = `<body><div id="${MESSAGE_IFRAME_ROOT_ID}" class="proton-plain-text ${ isPrint ? MESSAGE_IFRAME_PRINT_CLASS : '' }">${ isPrint ? `<div id="${MESSAGE_IFRAME_PRINT_HEADER_ID}"></div>` : '' }<div style="width: 100% !important;padding-bottom:10px;!important">${emailContent}</div>${ isPrint ? `<div id="${MESSAGE_IFRAME_PRINT_FOOTER_ID}"></div>` : '' }</div></body>`; return `<html>${emailHead}${emailBody}</html>`; } /** * Some infos about those `!important` values: * In order to compute correctly the height and avoid any kind of override * we had to put those inline style values with important on two divs. * * About this line: * <div style="width: 100% !important;padding-bottom:10px;!important">${emailContent}</div> * Padding bottom is needed for the scrollbar */ return ` <html> <head> <style>${themeCSSVariables}</style> <meta name="viewport" content="width=device-width"> <style>${cssStyles}</style> ${messageHead} </head> ${svg} <div id="${MESSAGE_IFRAME_ROOT_ID}" ${isPrint ? `class="${MESSAGE_IFRAME_PRINT_CLASS}"` : ''}> ${isPrint ? `<div id="${MESSAGE_IFRAME_PRINT_HEADER_ID}"></div>` : ''} <div ${ isPrint ? 'class="proton-print-content"' : '' } style="display: flex !important; width: 100% !important;"> <div style="width: 100% !important;padding-bottom:10px;!important"> ${bodyStyles || bodyClasses ? `<div class="${bodyClasses}" style="${bodyStyles}">` : ''} ${emailContent} ${bodyStyles || bodyClasses ? '</div>' : ''} </div> </div> ${isPrint ? `<div id="${MESSAGE_IFRAME_PRINT_FOOTER_ID}"></div>` : ''} </div> </body> </html> `; }; export default getIframeHtml;
3,647
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/helpers/getIframeSandboxAttributes.ts
import { isSafari } from '@proton/shared/lib/helpers/browser'; const getIframeSandboxAttributes = (isPrint: boolean) => { /** * "allow-same-origin" * Because iframe origin is set to protonmail.com we need * to be able to access it's origin * "allow-modals" * Allow to be able to print emails * "allow-scripts" * allows react portals to execute correctly in Safari * "allow-popups" * allows target="_blank" links to work * "allow-popups-to-escape-sandbox" * allows to open links in non sandboxed mode * for ex : if allow-scripts is not present opened links are allowed to execute scripts * * ATM we do not need to allow the following options * - allow-forms * - allow-pointer-lock * - allow-top-navigation */ const sandboxAttributes: string = [ 'allow-same-origin', 'allow-popups', 'allow-popups-to-escape-sandbox', ...(isPrint ? ['allow-modals'] : []), ...(isSafari() ? ['allow-scripts'] : []), ].join(' '); return sandboxAttributes; }; export default getIframeSandboxAttributes;
3,648
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/hooks/useIframeDispatchEvents.ts
import { RefObject, useCallback, useEffect } from 'react'; import { cloneEvent, isKeyboardEvent } from '@proton/shared/lib/helpers/events'; const IFRAME_EVENTS_LIST: Event['type'][] = ['focus', 'keydown', 'click']; const useIframeDispatchEvents = ( startListening: boolean, iframeRef: RefObject<HTMLIFrameElement>, onFocus?: () => void ) => { const bubbleEventCallback = useCallback((event: Event) => { if (['click', 'focus'].includes(event.type)) { document.dispatchEvent(new CustomEvent('dropdownclose')); onFocus?.(); } if (isKeyboardEvent(event)) { // In order to prevent focus we need to not bubble tab key if (event.key.toLowerCase() === 'tab') { return false; } const clonedEvent = cloneEvent(event); iframeRef.current?.dispatchEvent(clonedEvent); } }, []); useEffect(() => { const emailContentRoot = iframeRef.current?.contentWindow?.document.body; if (startListening === false || !emailContentRoot) { return; } IFRAME_EVENTS_LIST.forEach((eventName) => { emailContentRoot.addEventListener(eventName, bubbleEventCallback); }); return () => { IFRAME_EVENTS_LIST.forEach((eventName) => { emailContentRoot.removeEventListener(eventName, bubbleEventCallback); }); }; }, [startListening]); }; export default useIframeDispatchEvents;
3,649
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/hooks/useIframeShowBlockquote.ts
import { RefObject, useEffect, useState } from 'react'; import { MESSAGE_IFRAME_BLOCKQUOTE_ID, MESSAGE_IFRAME_TOGGLE_ID } from '../constants'; interface Props { iframeRef: RefObject<HTMLIFrameElement>; initStatus: 'start' | 'base_content' | 'done'; showBlockquoteProp: boolean; showBlockquoteToggle: boolean; blockquoteContent: string; onBlockquoteToggle?: () => void; } const useIframeShowBlockquote = ({ blockquoteContent, iframeRef, initStatus, showBlockquoteProp, showBlockquoteToggle, onBlockquoteToggle, }: Props) => { const [showBlockquote, setShowBlockquote] = useState(showBlockquoteProp); const iframeToggleDiv = iframeRef.current?.contentWindow?.document.getElementById(MESSAGE_IFRAME_TOGGLE_ID); const showToggle = initStatus !== 'start' && !!iframeToggleDiv && showBlockquoteToggle; useEffect(() => { const iframeBlockquoteDiv = iframeRef.current?.contentWindow?.document.getElementById(MESSAGE_IFRAME_BLOCKQUOTE_ID); if (!iframeBlockquoteDiv) { return; } if (showBlockquote) { iframeBlockquoteDiv.innerHTML = blockquoteContent; } else { iframeBlockquoteDiv.innerHTML = ''; } // If the user clicks the show blockquote button, we want to set the showBlockquotesProp state // But this useEffect can be triggered by the shortcut, where we don't want to trigger the OnBlockquoteToggle if (showBlockquote !== showBlockquoteProp) { onBlockquoteToggle?.(); } }, [showBlockquote]); useEffect(() => { // If the user triggers the showBlockquoteProp with a shortcut, we want to update showBlockquote if (showBlockquote !== showBlockquoteProp) { setShowBlockquote(showBlockquoteProp); } }, [showBlockquoteProp]); return { iframeToggleDiv, showToggle, showBlockquote, setShowBlockquote, }; }; export default useIframeShowBlockquote;
3,650
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/hooks/useInitIframeContent.ts
import { RefObject, useEffect, useRef, useState } from 'react'; import { useTheme } from '@proton/components'; import useIsMounted from '@proton/hooks/useIsMounted'; import { MessageState } from '../../../logic/messages/messagesTypes'; import { MESSAGE_IFRAME_BLOCKQUOTE_ID, MESSAGE_IFRAME_ROOT_ID, MESSAGE_IFRAME_TOGGLE_ID } from '../constants'; import getIframeHtml from '../helpers/getIframeHtml'; interface Props { messageID: string | undefined; content: string; message: MessageState; iframeRef: RefObject<HTMLIFrameElement>; isPlainText: boolean; onContentLoaded: (iframeRootElement: HTMLDivElement) => void; onReady?: (iframe: RefObject<HTMLIFrameElement>) => void; isPrint: boolean; } const useInitIframeContent = ({ messageID, iframeRef, message, content, onContentLoaded, isPlainText, onReady, isPrint, }: Props) => { const [initStatus, setInitStatus] = useState<'start' | 'done'>('start'); const hasBeenDone = useRef<boolean>(false); const iframeRootDivRef = useRef<HTMLDivElement>(); const prevContentRef = useRef<string>(content); const theme = useTheme(); const themeIndex = theme.information.theme; const themeCSSVariables = theme.information.style; const isMounted = useIsMounted(); const themeRef = useRef(themeIndex); useEffect(() => { if (initStatus === 'start') { let emailContent = content; if (!isPlainText) { emailContent += `<div id='${MESSAGE_IFRAME_TOGGLE_ID}'></div><div id='${MESSAGE_IFRAME_BLOCKQUOTE_ID}'></div>`; } const doc = iframeRef.current?.contentDocument; const iframeContent = getIframeHtml({ emailContent, messageDocument: message.messageDocument?.document, isPlainText, themeCSSVariables, isPrint, }); doc?.open(); doc?.write(iframeContent); doc?.close(); const iframeRootDivElement = doc?.getElementById(MESSAGE_IFRAME_ROOT_ID) as HTMLDivElement; iframeRootDivRef.current = iframeRootDivElement; setInitStatus('done'); return; } if (initStatus === 'done' && onContentLoaded && hasBeenDone.current === false) { const doc = iframeRef.current?.contentDocument; const iframeRootDivElement = doc?.getElementById(MESSAGE_IFRAME_ROOT_ID) as HTMLDivElement; onReady?.(iframeRef); hasBeenDone.current = true; if (isMounted()) { onContentLoaded(iframeRootDivElement); } } }, [initStatus]); // When theme is updated, need to compute again the styles so that plaintext messages use the correct bg color useEffect(() => { if (themeIndex !== themeRef.current) { setInitStatus('start'); themeRef.current = themeIndex; } }, [themeIndex]); /** * On content change, rerun the process to set content inside the iframe */ useEffect(() => { if (initStatus === 'done' && prevContentRef.current !== content) { setInitStatus('start'); prevContentRef.current = content; } }, [content, initStatus]); /** * On message change, rerun the process to set content too */ useEffect(() => { if (initStatus === 'done') { setInitStatus('start'); } }, [messageID]); return { initStatus, iframeRootDivRef }; }; export default useInitIframeContent;
3,651
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/hooks/useMessageDarkStyles.ts
import { RefObject, useEffect, useMemo } from 'react'; import { FeatureCode, useFeature, useTheme } from '@proton/components'; import { isNewsLetter, isPlainText } from '@proton/shared/lib/mail/messages'; import { canSupportDarkStyle } from '../../../helpers/message/messageContent'; import { MessageState } from '../../../logic/messages/messagesTypes'; import { applyDarkStyle } from '../../../logic/messages/read/messagesReadActions'; import { useAppDispatch } from '../../../logic/store'; const useMessageDarkStyles = ( message: MessageState, isIframeContentSet: boolean, iframeRef: RefObject<HTMLIFrameElement> ) => { const darkStylesFeature = useFeature(FeatureCode.DarkStylesInBody); const theme = useTheme(); const dispatch = useAppDispatch(); const needCompute = darkStylesFeature.feature?.Value && !message.messageDocument?.noDarkStyle && theme.information.dark && !isPlainText(message.data) && !isNewsLetter(message.data); // canSupportDarkStyle is costly, so we only call it when needed const { support, loading } = useMemo(() => { if (!needCompute) { return { support: false, loading: false }; } if (!isIframeContentSet) { return { support: true, loading: true }; } return { support: canSupportDarkStyle(iframeRef.current), loading: false }; }, [message.localID, needCompute, isIframeContentSet]); useEffect(() => { if (!loading && support) { dispatch(applyDarkStyle({ ID: message.localID, hasDarkStyle: true })); } }, [message.localID, support, loading]); if (darkStylesFeature.loading) { return { support: false, loading: true }; } return { support, loading }; }; export default useMessageDarkStyles;
3,652
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/hooks/useObserveIframeHeight.ts
import { RefObject, useCallback, useEffect, useRef } from 'react'; import useIsMounted from '@proton/hooks/useIsMounted'; import { MESSAGE_IFRAME_ROOT_ID } from '../constants'; const ALLOWED_PX_INTERVAL = 10; /** * Observe dom content changes and width changes in order to set content * * @param startObserving * @param iframeRef * @param imagesLoaded */ const useObserveIframeHeight = (startObserving: boolean, iframeRef: RefObject<HTMLIFrameElement>) => { const isMountedCallback = useIsMounted(); const prevHeightRef = useRef<number>(0); const setIframeHeight = useCallback(() => { if (!isMountedCallback() || !iframeRef || !iframeRef.current) { return; } const emailContentRoot = iframeRef.current?.contentWindow?.document.getElementById(MESSAGE_IFRAME_ROOT_ID); const prevHeight = prevHeightRef.current; const height = emailContentRoot?.scrollHeight; if (!emailContentRoot || height === undefined) { return; } const heightIsOutOfBoudaries = height && (height > prevHeight + ALLOWED_PX_INTERVAL || height < prevHeight - ALLOWED_PX_INTERVAL); if (heightIsOutOfBoudaries) { prevHeightRef.current = height; iframeRef.current.style.height = `${height}px`; } }, []); useEffect(() => { if (!startObserving) { return; } // We're ready set some height setIframeHeight(); const iframeRootDiv = iframeRef.current?.contentWindow?.document.getElementById( MESSAGE_IFRAME_ROOT_ID ) as HTMLDivElement; const resizeObserver = new ResizeObserver(() => { requestAnimationFrame(() => { setIframeHeight(); }); }); // Only checks iframe root div widths changes (window resize or inner resize when column mailbox layout is set) resizeObserver.observe(iframeRootDiv); return () => { resizeObserver.disconnect(); }; }, [startObserving]); }; export default useObserveIframeHeight;
3,653
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/modals/BlockSenderModal.tsx
import { useEffect, useState } from 'react'; import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms'; import { AppLink, Checkbox, Label, ModalProps, Prompt } from '@proton/components'; import { APPS } from '@proton/shared/lib/constants'; import { MailSettings, Recipient } from '@proton/shared/lib/interfaces'; import { BLOCK_SENDER_CONFIRMATION } from '@proton/shared/lib/mail/constants'; interface Props extends ModalProps { onConfirm: (blockSenderConfirmation: boolean) => void; senders: Recipient[]; mailSettings: MailSettings; onResolve: () => void; onReject: () => void; } const BlockSenderModal = ({ senders, onConfirm, mailSettings, onResolve, onReject, ...rest }: Props) => { const [blockSenderConfirmation, setBlockSenderConfirmation] = useState(false); const handleConfirm = () => { onConfirm(blockSenderConfirmation); onResolve(); }; const manageBlockedAddressesSettingsLink = ( <AppLink key={'manageMessageAddressLink'} to="mail/filters#spam" toApp={APPS.PROTONACCOUNT}>{c('Link') .t`Manage blocked email addresses`}</AppLink> ); const sendersEmails = senders.map((sender) => { return sender?.Address; }); const senderEmailAddress = sendersEmails.slice(0, 2).join(', '); const otherSendersCount = sendersEmails.length - 2; const blockSendersText = sendersEmails.length <= 2 ? // translator: The variable contains email addresses (up to two mail addresses) that will be blocked // Full sentence for reference "New emails from user1@domain.com, user2@domain.com won't be delivered and will be permanently deleted." c('Description') .t`New emails from ${senderEmailAddress} won't be delivered and will be permanently deleted.` : // translator: The variables are the following // ${senderEmailAddress}: contains email addresses (up to two mail addresses) that will be blocked // ${otherSendersCount}: since we display two addresses, the variable contains the number of address remaining which will be blocked // Full sentence for reference "New emails from user1@domain.com, user2@domain.com and X others won't be delivered and will be permanently deleted." c('Description').ngettext( msgid`New emails from ${senderEmailAddress} and ${otherSendersCount} other won't be delivered and will be permanently deleted.`, `New emails from ${senderEmailAddress} and ${otherSendersCount} others won't be delivered and will be permanently deleted.`, otherSendersCount ); // translator: The variable is a link to the settings page // Full sentence for reference "Manage blocked email addresses in settings." const manageInSettingsText = c('Description').jt`${manageBlockedAddressesSettingsLink} in settings.`; useEffect(() => { setBlockSenderConfirmation(mailSettings.BlockSenderConfirmation === BLOCK_SENDER_CONFIRMATION.DO_NOT_ASK); }, [mailSettings.BlockSenderConfirmation]); return ( <div onClick={(e) => e.stopPropagation()}> <Prompt title={c('Title').t`Block sender`} buttons={[ <Button key="submit" type="submit" color="warning" onClick={handleConfirm} data-testid="block-sender-modal-block:button" > {c('Action').t`Block`} </Button>, <Button key="reset" type="reset" onClick={onReject}> {c('Action').t`Cancel`} </Button>, ]} {...rest} > <div> <p className="text-break"> <span>{blockSendersText}</span> <span className="ml-1">{manageInSettingsText}</span> </p> <Label htmlFor="block-sender-confirmation" className="flex text-center"> <Checkbox id="block-sender-confirmation" checked={blockSenderConfirmation} onChange={() => { setBlockSenderConfirmation(!blockSenderConfirmation); }} data-testid="block-sender-modal-dont-show:checkbox" className="mr-1" /> {c('Label').t`Don't show this again`} </Label> </div> </Prompt> </div> ); }; export default BlockSenderModal;
3,654
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/modals/ContactResignModal.test.tsx
import { fireEvent, waitFor } from '@testing-library/react'; import { Address } from '@proton/shared/lib/interfaces'; import { ContactEmail } from '@proton/shared/lib/interfaces/contacts'; import { addApiMock } from '../../../helpers/test/api'; import { addToCache, minimalCache } from '../../../helpers/test/cache'; import { addKeysToUserKeysCache } from '../../../helpers/test/crypto'; import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../helpers/test/crypto'; import { contactID, receiver, sender, setupContactsForPinKeys } from '../../../helpers/test/pinKeys'; import { render, tick } from '../../../helpers/test/render'; import ContactResignModal from './ContactResignModal'; const contacts = [{ contactID: contactID }]; const title = 'Contact Resign Modal title'; const children = 'Contact Resign Modal children'; describe('Contact resign modal', () => { beforeAll(async () => { await setupCryptoProxyForTesting(); }); afterAll(async () => { await releaseCryptoProxy(); }); const setup = async (hasFingerprint: boolean) => { minimalCache(); addToCache('Addresses', [{ Email: receiver.Address } as Address]); const { receiverKeys, senderKeys } = await setupContactsForPinKeys(hasFingerprint); addApiMock('core/v4/keys/all', () => ({ Address: { Keys: [{ PublicKey: senderKeys.publicKeyArmored }] } })); addApiMock( 'contacts/v4/contacts/emails', () => ({ ContactEmails: [{ Email: sender.Address, ContactID: contactID } as ContactEmail] as ContactEmail[], }), 'get' ); const updateSpy = jest.fn(); addApiMock(`contacts/v4/contacts/${contactID}`, updateSpy, 'put'); addKeysToUserKeysCache(receiverKeys); const onResignSpy = jest.fn(); const container = await render( <ContactResignModal title={title} contacts={contacts} onResign={onResignSpy} open> {children} </ContactResignModal>, false ); return { container, senderKeys, updateSpy, onResignSpy }; }; it('should resign the contact and render email rows', async () => { const { container: { getByText, getByTestId }, senderKeys, updateSpy, onResignSpy, } = await setup(true); // Modal and content are displayed getByText(title); getByText(children); // Email rows are rendered (Email + fingerprints) await waitFor(() => getByText(`${sender.Address}:`)); const expectedFingerPrint = senderKeys.publicKeys[0].getFingerprint(); getByText(expectedFingerPrint); // Click on Re-sign button const resignButton = getByTestId('resign-contact'); fireEvent.click(resignButton); await tick(); // Contact update is called expect(updateSpy).toHaveBeenCalled(); // Optional on Resign action is called expect(onResignSpy).toHaveBeenCalled(); }); it('should resign the contact not render email rows', async () => { const { container: { getByText, queryByText, getByTestId }, updateSpy, onResignSpy, } = await setup(false); // Modal and content are displayed getByText(title); getByText(children); // Email rows are not rendered const emailRow = queryByText(`${sender.Address}:`); expect(emailRow).toBeNull(); // Click on Re-sign button const resignButton = getByTestId('resign-contact'); fireEvent.click(resignButton); await tick(); // Contact update is called expect(updateSpy).toHaveBeenCalled(); // Optional on Resign action is called expect(onResignSpy).toHaveBeenCalled(); }); });
3,655
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/modals/ContactResignModal.tsx
import { useEffect, useState } from 'react'; import * as React from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Form, Loader, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, PrimaryButton, useApi, useGetEncryptionPreferences, useGetUserKeys, useNotifications, } from '@proton/components'; import { useLoading } from '@proton/hooks'; import { getContact, updateContact } from '@proton/shared/lib/api/contacts'; import { processApiRequestsSafe } from '@proton/shared/lib/api/helpers/safeApiRequests'; import { resignCards } from '@proton/shared/lib/contacts/resign'; import { ContactCard, ContactEmail } from '@proton/shared/lib/interfaces/contacts'; import { LoadingMap } from '@proton/shared/lib/interfaces/utils'; import { splitKeys } from '@proton/shared/lib/keys/keys'; interface Props extends ModalProps { title: string; contacts: { contactID: string }[]; children: React.ReactNode; submit?: string; onResign?: () => void; onNotResign?: () => void; onError?: () => void; onResolve?: () => void; onReject?: () => void; } const ContactResignModal = ({ title, contacts, children, submit = c('Action').t`Re-sign`, onResign, onNotResign, onError, onResolve, onReject, onClose, ...rest }: Props) => { const getUserKeys = useGetUserKeys(); const { createNotification } = useNotifications(); const [contactFingerprintsByEmailMap, setContactFingerprintsByEmailMap] = useState<{ [key: string]: string[] | undefined; }>({}); const [contactCardsMap, setContactCardsMap] = useState<{ [key: string]: ContactCard[] | undefined }>({}); const [loadingMap, setLoadingMap] = useState<LoadingMap>( contacts.reduce<{ [key: string]: boolean }>((acc, { contactID }) => { acc[contactID] = true; return acc; }, {}) ); const [loadingResign, withLoadingResign] = useLoading(); const getEncryptionPreferences = useGetEncryptionPreferences(); const api = useApi(); useEffect(() => { const getContactFingerprintsByEmailMap = async (contactID: string) => { const { Contact: { Cards, ContactEmails }, } = await api(getContact(contactID)); const fingerprintsByEmail: { [key: string]: string[] | undefined } = {}; await Promise.all( ContactEmails.map(async ({ Email: email }: ContactEmail) => { const { pinnedKeys } = await getEncryptionPreferences({ email }); const fingerprints = pinnedKeys.map((key) => key.getFingerprint()); if (fingerprints.length) { fingerprintsByEmail[email] = fingerprints; } }) ); setContactFingerprintsByEmailMap((fingerprintsByEmailMap) => ({ ...fingerprintsByEmailMap, ...fingerprintsByEmail, })); setContactCardsMap((map) => ({ ...map, [contactID]: Cards })); setLoadingMap((map) => ({ ...map, [contactID]: false })); }; void Promise.all(contacts.map(({ contactID }) => getContactFingerprintsByEmailMap(contactID))); }, []); const handleSubmit = async () => { try { const { privateKeys } = splitKeys(await getUserKeys()); const resignedCardsMap: { [key: string]: ContactCard[] } = {}; await Promise.all( contacts.map(async ({ contactID }) => { const contactCards = contactCardsMap[contactID]; if (!contactCards || loadingMap[contactID]) { return; } const resignedCards = await resignCards({ contactCards, privateKeys: [privateKeys[0]], }); resignedCardsMap[contactID] = resignedCards; }) ); const requests = contacts.map( ({ contactID }) => () => api(updateContact(contactID, { Cards: resignedCardsMap[contactID] })) ); // the routes called in requests support 100 calls every 10 seconds await processApiRequestsSafe(requests, 100, 10 * 1000); onResign?.(); onResolve?.(); } catch (error: any) { createNotification({ text: error.message, type: 'error' }); onError?.(); } finally { onReject?.(); onClose?.(); } }; const handleClose = () => { onNotResign?.(); onReject?.(); onClose?.(); }; const renderEmailRow = (email: string) => { const fingerprints = contactFingerprintsByEmailMap[email]; if (!fingerprints) { return null; } return ( <li key={email}> <span className="flex max-w-full flex-nowrap on-mobile-flex-column"> <strong className="mr-1">{`${email}:`}</strong> <span className="flex-item-fluid"> {fingerprints.map((f: string, i: number) => ( <span className="text-ellipsis inline-block max-w-full" title={f} key={f}> {`${f}${i + 1 !== fingerprints.length ? ', ' : ''}`} </span> ))} </span> </span> </li> ); }; const loadingContacts = Object.values(loadingMap).some((loading) => loading === true); const emailsWithKeys = Object.values(contactFingerprintsByEmailMap); const content = emailsWithKeys.length ? ( <> <div> {c('Info') .t`Do you want to re-sign the contact details and in the process trust the keys with the following fingerprints?`} </div> {loadingContacts ? ( <Loader /> ) : ( <div> <ul>{Object.keys(contactFingerprintsByEmailMap).map(renderEmailRow)}</ul> </div> )} </> ) : ( <div>{c('Info').t`Do you want to re-sign the contact details?`}</div> ); return ( <ModalTwo size="large" as={Form} {...rest} onSubmit={() => withLoadingResign(handleSubmit())} onClose={handleClose} > <ModalTwoHeader title={title} /> <ModalTwoContent> {children} {content} </ModalTwoContent> <ModalTwoFooter> <Button onClick={onClose}>{c('Action').t`Cancel`}</Button> <PrimaryButton disabled={loadingContacts} loading={loadingResign} type="submit" data-testid="resign-contact" > {submit} </PrimaryButton> </ModalTwoFooter> </ModalTwo> ); }; export default ContactResignModal;
3,656
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/modals/CustomExpirationModal.tsx
import { useMemo, useRef, useState } from 'react'; import { addDays, endOfDay, endOfToday, isBefore, isToday, startOfToday } from 'date-fns'; import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms'; import { DateInput, InputFieldTwo, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, TimeInput, useUserSettings, } from '@proton/components'; import { getWeekStartsOn } from '@proton/shared/lib/settings/helper'; import { getMinExpirationTime } from 'proton-mail/helpers/expiration'; import { EXPIRATION_TIME_MAX_DAYS } from '../../../constants'; interface Props extends Omit<ModalProps, 'onSubmit'> { onSubmit: (expirationDate: Date) => void; } const CustomExpirationModal = ({ onSubmit, ...rest }: Props) => { const { onClose } = rest; const [userSettings] = useUserSettings(); const tomorrow = useRef<Date>(addDays(new Date(), 1)); const minDate = startOfToday(); const maxDate = endOfDay(addDays(minDate, EXPIRATION_TIME_MAX_DAYS)); const [date, setDate] = useState<Date>(tomorrow.current); const errorDate = useMemo(() => { if (date < minDate) { return c('Error').t`Choose a date in the future.`; } if (date > maxDate) { // translator : The variable is the number of days, written in digits return c('Error').ngettext( msgid`Choose a date within the next ${EXPIRATION_TIME_MAX_DAYS} day.`, `Choose a date within the next ${EXPIRATION_TIME_MAX_DAYS} days.`, EXPIRATION_TIME_MAX_DAYS ); } return undefined; }, [date]); const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => { event.preventDefault(); if (!date) { return; } onSubmit(date); }; const handleDate = (newDate?: Date, keepExistingTime?: boolean) => { if (!newDate) { return; } if (isBefore(newDate, startOfToday())) { return; } if (keepExistingTime) { const hours = date.getHours(); const minutes = date.getMinutes(); const seconds = date.getSeconds(); newDate.setHours(hours, minutes, seconds); } setDate(newDate); }; return ( <ModalTwo size="small" as="form" onReset={onClose} onSubmit={handleSubmit} data-testid="message-expiration-time:modal" {...rest} > <ModalTwoHeader title={c('Title').t`Self-destruct message`} /> <ModalTwoContent> <div className="mb-4">{c('Info').t`When do you want your message to self-destruct?`}</div> <div className="flex gap-2 flex-row flex-nowrap"> <InputFieldTwo as={DateInput} id="expiration-date" label={c('Label attach to date input to select a date').t`Date`} onChange={(newDate?: Date) => newDate && handleDate(newDate, true)} value={date} min={minDate} weekStartsOn={getWeekStartsOn({ WeekStart: userSettings.WeekStart })} max={maxDate} error={errorDate} preventValueReset data-testid="message:expiration-date-input" required /> <InputFieldTwo as={TimeInput} id="expiration-time" label={c('Label attach to time input to select hours').t`Time`} onChange={handleDate} value={date} min={getMinExpirationTime(date)} max={isToday(date) ? endOfToday() : undefined} data-testid="message:expiration-time-input" required /> </div> </ModalTwoContent> <ModalTwoFooter> <Button type="reset">{c('Action').t`Cancel`}</Button> <Button color="norm" type="submit">{c('Action').t`Self-destruct message`}</Button> </ModalTwoFooter> </ModalTwo> ); }; export default CustomExpirationModal;
3,657
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/modals/GroupModal.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Checkbox, FormModal, Label, generateUID } from '@proton/components'; import { ContactEmail } from '@proton/shared/lib/interfaces/contacts'; import { contactToInput } from '@proton/shared/lib/mail/recipient'; import { GroupWithContacts } from '../../../logic/contacts/contactsTypes'; import { RecipientGroup } from '../../../models/address'; import { MapStatusIcons, StatusIcon } from '../../../models/crypto'; import EncryptionStatusIcon from '../EncryptionStatusIcon'; interface Props { recipientGroup: RecipientGroup; group: GroupWithContacts | undefined; globalIcon?: StatusIcon; mapStatusIcons?: MapStatusIcons; onClose?: () => void; } const GroupModal = ({ recipientGroup, group, globalIcon, mapStatusIcons, onClose, ...rest }: Props) => { const [uid] = useState<string>(generateUID('header-group-modal')); const contacts = group?.contacts || []; const isChecked = (contact: ContactEmail) => !!recipientGroup.recipients?.find((recipient) => contact.Email === recipient.Address); const members = c('Info').t`Members`; const title = `${recipientGroup?.group?.Name} (${contacts.length} ${members})`; return ( <FormModal title={title} submit={c('Action').t`Close`} close={null} onSubmit={onClose} onClose={onClose} {...rest} > <ul className="unstyled"> {contacts.map((contact) => { const id = `${uid}-${contact.ID}`; const icon = globalIcon || (mapStatusIcons ? mapStatusIcons[contact.Email] : undefined); return ( <li key={contact.ID} className="mb-2"> <Checkbox id={id} checked={isChecked(contact)} disabled /> <span className="min-w-custom inline-flex align-middle" style={{'--min-w-custom': '1.4em'}}> {icon && <EncryptionStatusIcon {...icon} />} </span> <Label htmlFor={id} className="pt-0 pl-1"> {contactToInput(contact)} </Label> </li> ); })} </ul> </FormModal> ); }; export default GroupModal;
3,658
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/modals/MessageDetailsModal.tsx
import { c, msgid } from 'ttag'; import { Button, Href } from '@proton/atoms'; import { FeatureCode, Icon, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, useFeatures, useFolders, } from '@proton/components'; import { ContactEditProps } from '@proton/components/containers/contacts/edit/ContactEditModal'; import humanSize from '@proton/shared/lib/helpers/humanSize'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { MailSettings } from '@proton/shared/lib/interfaces'; import { getAttachments } from '@proton/shared/lib/mail/messages'; import { getSize } from '../../../helpers/elements'; import { getCurrentFolders } from '../../../helpers/labels'; import { MessageViewIcons } from '../../../helpers/message/icon'; import { getAttachmentCounts } from '../../../helpers/message/messages'; import { useMessageTrackers } from '../../../hooks/message/useMessageTrackers'; import { MessageState } from '../../../logic/messages/messagesTypes'; import { Element } from '../../../models/element'; import ItemAttachmentIcon from '../../list/ItemAttachmentIcon'; import ItemDate from '../../list/ItemDate'; import ItemLocation from '../../list/ItemLocation'; import SpyTrackerIcon from '../../list/spy-tracker/SpyTrackerIcon'; import EncryptionStatusIcon from '../EncryptionStatusIcon'; import RecipientItem from '../recipients/RecipientItem'; import RecipientsDetails from '../recipients/RecipientsDetails'; interface Props extends ModalProps { labelID: string; message: MessageState; messageViewIcons: MessageViewIcons; mailSettings: MailSettings; messageLoaded: boolean; onContactDetails: (contactID: string) => void; onContactEdit: (props: ContactEditProps) => void; } const MessageDetailsModal = ({ labelID, message, messageViewIcons, mailSettings, messageLoaded, onContactDetails, onContactEdit, ...rest }: Props) => { const { getFeature } = useFeatures([FeatureCode.NumAttachmentsWithoutEmbedded]); const { feature: numAttachmentsWithoutEmbeddedFeature } = getFeature(FeatureCode.NumAttachmentsWithoutEmbedded); const { onClose } = rest; const icon = messageViewIcons.globalIcon; const [customFolders = []] = useFolders(); const folders = getCurrentFolders(message.data, labelID, customFolders, mailSettings); const locationText = folders.map((folder) => folder.name).join(', '); const sizeText = humanSize(getSize(message.data || ({} as Element))); const { numberOfImageTrackers, numberOfUTMTrackers, needsMoreProtection, imageTrackerText, utmTrackerText, hasTrackers, } = useMessageTrackers(message); const displayTrackerIcon = hasTrackers && !needsMoreProtection; const { pureAttachmentsCount, embeddedAttachmentsCount } = getAttachmentCounts( getAttachments(message.data), message.messageImages ); const attachmentsTexts = []; if (pureAttachmentsCount) { attachmentsTexts.push( c('Info').ngettext( msgid`${pureAttachmentsCount} file attached`, `${pureAttachmentsCount} files attached`, pureAttachmentsCount ) ); } if (embeddedAttachmentsCount && !numAttachmentsWithoutEmbeddedFeature?.Value) { attachmentsTexts.push( c('Info').ngettext( msgid`${embeddedAttachmentsCount} embedded image`, `${embeddedAttachmentsCount} embedded images`, embeddedAttachmentsCount ) ); } const attachmentsText = attachmentsTexts.join(', '); const showAttachmentsDetails = numAttachmentsWithoutEmbeddedFeature?.Value ? pureAttachmentsCount > 0 : attachmentsText; const sender = message.data?.Sender; return ( <ModalTwo data-testid="message-details:modal" {...rest}> <ModalTwoHeader title={c('Title').t`Message details`} /> <ModalTwoContent> <div className="message-detailed-header-extra pt-2 mb-8" data-testid="message:message-expanded-header-extra" > {icon && ( <div className="mb-2 flex flex-nowrap flex-align-items-center"> <span className="mr-2 flex"> <EncryptionStatusIcon useTooltip={true} isDetailsModal {...icon} /> </span> <div className="pl-1 flex-item-fluid"> <div className="flex flex-column"> <span className="text-ellipsis w-full" title={icon.text}> {icon.messageEncryptionDetails ?? icon.text} </span> {icon.senderVerificationDetails && ( <div> <span className="w-full" title={c('Sender verification details').t`Sender verification`} > {icon.senderVerificationDetails.description} </span> {icon.senderVerificationDetails?.showKeyTransparencyLearnMore && ( <Href className="ml-1" href={getKnowledgeBaseUrl('/key-transparency')} >{c('Link').t`Learn more`}</Href> )} </div> )} </div> </div> </div> )} {displayTrackerIcon && ( <div className="mb-2 flex flex-nowrap flex-align-items-center"> <span className="mr-2 relative inline-flex item-spy-tracker-link flex-align-items-center"> <SpyTrackerIcon numberOfTrackers={numberOfImageTrackers + numberOfUTMTrackers} needsMoreProtection={needsMoreProtection} title={imageTrackerText} isStandaloneIcon className="m-auto" /> </span> <span className="pl-0.5 flex-item-fluid text-ellipsis" title={imageTrackerText}> {imageTrackerText}, {utmTrackerText} </span> </div> )} <div className="mb-2 flex flex-nowrap" data-testid="message-details:date"> <span className="mr-2 flex"> <Icon name="calendar-grid" className="m-auto" alt={c('Label').t`Date:`} /> </span> <span className="pl-1 flex-item-fluid text-ellipsis"> <ItemDate element={message.data} labelID={labelID} mode="full" /> </span> </div> <div className="mb-2 flex flex-nowrap"> <span className="mr-2 flex"> <span className="m-auto flex"> <ItemLocation element={message.data} labelID={labelID} shouldStack showTooltip={false} withDefaultMargin={false} ignoreIconFilter /> </span> </span> <span className="pl-1 flex-item-fluid text-ellipsis" title={locationText}> {locationText} </span> </div> <div className="mb-2 flex flex-nowrap" data-testid="message-details:size"> <span className="mr-2 flex"> <Icon name="filing-cabinet" className="m-auto" alt={c('Label').t`Size:`} /> </span> <span className="pl-1 flex-item-fluid text-ellipsis" title={sizeText}> {sizeText} </span> </div> {showAttachmentsDetails && ( <div className="mb-2 flex flex-nowrap"> <span className="mr-2 flex"> <span className="m-auto flex"> <ItemAttachmentIcon element={message.data} /> </span> </span> <span className="pl-1 flex-item-fluid text-ellipsis" title={attachmentsText}> {attachmentsText} </span> </div> )} </div> {sender && ( <div className="mb-4"> <div className="mb-2"> <strong>{c('Title').t`Sender`}</strong> </div> <RecipientItem recipientOrGroup={{ recipient: sender }} isLoading={!messageLoaded} onContactDetails={onContactDetails} onContactEdit={onContactEdit} /> </div> )} <div className="message-detail-modal-container"> <RecipientsDetails message={message} isLoading={!messageLoaded} isDetailsModal={true} onContactDetails={onContactDetails} onContactEdit={onContactEdit} /> </div> </ModalTwoContent> <ModalTwoFooter> <Button className="ml-auto" color="norm" onClick={onClose}>{c('Action').t`Close`}</Button> </ModalTwoFooter> </ModalTwo> ); }; export default MessageDetailsModal;
3,659
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/modals/MessageHeadersModal.scss
.message-headers-modal { --size: 46rem; // done with real tests on Mac/Linux }
3,660
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/modals/MessageHeadersModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Form, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader } from '@proton/components'; import downloadFile from '@proton/shared/lib/helpers/downloadFile'; import { MessageWithOptionalBody } from '../../../logic/messages/messagesTypes'; import './MessageHeadersModal.scss'; interface Props extends ModalProps { message?: MessageWithOptionalBody; } const MessageHeadersModal = ({ message, ...rest }: Props) => { const { onClose } = rest; const content = `${message?.Header}\n\r${message?.Body}`; const handleDownload = () => { const blob = new Blob([content], { type: 'text/plain;charset=utf-8' }); downloadFile(blob, 'pgp.txt'); }; return ( <ModalTwo className="message-headers-modal" size="large" as={Form} onSubmit={handleDownload} {...rest}> <ModalTwoHeader title={c('Info').t`Message headers`} /> <ModalTwoContent> <pre className="text-break">{content}</pre> </ModalTwoContent> <ModalTwoFooter> <Button onClick={onClose}>{c('Action').t`Cancel`}</Button> <Button color="norm" type="submit">{c('Action').t`Download`}</Button> </ModalTwoFooter> </ModalTwo> ); }; export default MessageHeadersModal;
3,661
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/modals/MessagePermanentDeleteModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { ErrorButton, ModalProps, Prompt, useApi, useEventManager, useNotifications } from '@proton/components'; import { deleteMessages } from '@proton/shared/lib/api/messages'; import { getDeleteTitle, getModalText, getNotificationText } from '../../../hooks/actions/usePermanentDelete'; import { MessageWithOptionalBody } from '../../../logic/messages/messagesTypes'; interface Props extends ModalProps { message: MessageWithOptionalBody; } const MessagePermanentDeleteModal = ({ message, ...rest }: Props) => { const api = useApi(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const { onClose } = rest; const handleDelete = async () => { onClose?.(); await api(deleteMessages([message.ID])); await call(); createNotification({ text: getNotificationText(false, false, 1) }); }; return ( <Prompt title={getDeleteTitle(false, false, 1)} buttons={[ <ErrorButton onClick={handleDelete}>{c('Action').t`Delete`}</ErrorButton>, <Button onClick={onClose}>{c('Action').t`Cancel`}</Button>, ]} {...rest} > {getModalText(false, false, 1)} </Prompt> ); }; export default MessagePermanentDeleteModal;
3,662
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/modals/MessagePhishingModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { ErrorButton, ModalProps, Prompt, useApi, useNotifications } from '@proton/components'; import { reportPhishing } from '@proton/shared/lib/api/reports'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { useMoveToFolder } from '../../../hooks/actions/useMoveToFolder'; import { MessageState } from '../../../logic/messages/messagesTypes'; import { Element } from '../../../models/element'; const { SPAM } = MAILBOX_LABEL_IDS; interface Props extends ModalProps { message: MessageState; onBack: () => void; } const MessagePhishingModal = ({ message, onBack, ...rest }: Props) => { const api = useApi(); const { moveToFolder } = useMoveToFolder(); const { createNotification } = useNotifications(); const { onClose } = rest; // Reference: Angular/src/app/bugReport/factories/bugReportModel.js const handleConfirmPhishing = async () => { onClose?.(); await api( reportPhishing({ MessageID: message.data?.ID, MIMEType: message.data?.MIMEType === 'text/plain' ? 'text/plain' : 'text/html', // Accept only 'text/plain' / 'text/html' Body: message.decryption?.decryptedBody, }) ); await moveToFolder([message.data || ({} as Element)], SPAM, '', '', false, true, false); createNotification({ text: c('Success').t`Phishing reported` }); onBack(); }; return ( <Prompt title={c('Info').t`Confirm phishing report`} buttons={[ <ErrorButton onClick={handleConfirmPhishing}>{c('Action').t`Confirm`}</ErrorButton>, <Button onClick={onClose}>{c('Action').t`Cancel`}</Button>, ]} {...rest} > {c('Info') .t`Reporting a message as a phishing attempt will send the message to us, so we can analyze it and improve our filters. This means that we will be able to see the contents of the message in full.`} </Prompt> ); }; export default MessagePhishingModal;
3,663
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/modals/MessagePrint.scss
@import '~@proton/styles/scss/lib'; .print-modal { // Special case otherwise print modal is not properly displayed --size: #{rem(1000)}; } .message-print-subject { font-size: #{rem(20)}; border-block-end: 1px solid var(--border-norm); } .message-print-header { border-block-end: 1px solid var(--border-weak); } .message-recipient-item-expanded { .message-recipient-item-expanded-content { padding-block-start: 0.5em; } } .is-printed-version { .item-icon, .container-to.container-to--item { display: none; } .item-date { font-size: 1em; } .color-weak { color: var(--text-norm); } }
3,664
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/modals/MessagePrintModal.tsx
import { RefObject, useEffect, useRef } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Form, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader } from '@proton/components'; import { MailboxContainerContextProvider } from '../../../containers/mailbox/MailboxContainerProvider'; import { MessageStateWithData } from '../../../logic/messages/messagesTypes'; import MessageBody from '../MessageBody'; import './MessagePrint.scss'; interface Props extends ModalProps { labelID: string; message: MessageStateWithData; } const MessagePrintModal = ({ labelID, message, ...rest }: Props) => { const iframeRef = useRef<HTMLIFrameElement | null>(); const { onClose } = rest; const handlePrint = () => { iframeRef.current?.contentWindow?.print(); }; useEffect(() => { document.body.classList.add('is-printed-version'); }, []); const handleClose = () => { document.body.classList.remove('is-printed-version'); onClose?.(); }; const handleIframeReady = (iframe: RefObject<HTMLIFrameElement>) => { iframeRef.current = iframe.current; }; return ( <ModalTwo className="print-modal" as={Form} onSubmit={handlePrint} {...rest} onClose={handleClose}> <ModalTwoHeader title={c('Info').t`Print email`} /> <ModalTwoContent> <MailboxContainerContextProvider containerRef={null} elementID={undefined} isResizing={false}> <MessageBody messageLoaded bodyLoaded sourceMode={false} message={message} labelID={labelID} originalMessageMode={false} forceBlockquote isPrint onIframeReady={handleIframeReady} /> </MailboxContainerContextProvider> </ModalTwoContent> <ModalTwoFooter> <Button onClick={handleClose}>{c('Action').t`Cancel`}</Button> <Button color="norm" type="submit">{c('Action').t`Print`}</Button> </ModalTwoFooter> </ModalTwo> ); }; export default MessagePrintModal;
3,665
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/modals/MoveScheduledModal.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 MoveScheduledModal = ({ isMessage, onResolve, onReject, onCloseCustomAction, ...rest }: Props) => { const text = isMessage ? c('Info').t`Scheduled send of this message will be canceled.` : c('Info').t`This conversation contains a scheduled message. Sending of this message will be canceled.`; const handleClose = () => { onCloseCustomAction?.(); onReject(); }; return ( <Prompt title={c('Title').t`Moving a scheduled message`} buttons={[ <Button color="norm" onClick={onResolve} data-testid="moveScheduledMessage">{c('Action') .t`OK`}</Button>, <Button onClick={handleClose}>{c('Action').t`Cancel`}</Button>, ]} {...rest} > {text} </Prompt> ); }; export default MoveScheduledModal;
3,666
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/modals/MoveToSpamModal.tsx
import { useMemo, useState } from 'react'; import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms'; import { Checkbox, Label, ModalProps, Prompt } from '@proton/components'; import { Element } from '../../../models/element'; export interface MoveToSpamModalResolveProps { unsubscribe: boolean; remember: boolean; } interface Props extends ModalProps { isMessage: boolean; elements: Element[]; onResolve: ({ unsubscribe, remember }: MoveToSpamModalResolveProps) => void; onReject: () => void; } const MoveToSpamModal = ({ isMessage, elements, onResolve, onReject, ...rest }: Props) => { const [remember, setRemember] = useState(false); const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => setRemember(e.target.checked); const text = useMemo(() => { const elementsCount = elements.length; if (isMessage) { return c('Info').ngettext( msgid`This message will be marked as spam. Would you also like to unsubscribe from future emails?`, `These messages will be marked as spam. Would you also like to unsubscribe from future emails?`, elementsCount ); } return c('Info').ngettext( msgid`This conversation will be marked as spam. Would you also like to unsubscribe from future emails?`, `These conversations will be marked as spam. Would you also like to unsubscribe from future emails?`, elementsCount ); }, [isMessage, elements]); return ( <Prompt title={c('Title').t`Move to spam`} buttons={[ <Button color="norm" onClick={() => onResolve({ unsubscribe: true, remember })}>{c('Action') .t`Move to spam and unsubscribe`}</Button>, <Button onClick={() => onResolve({ unsubscribe: false, remember })}>{c('Action') .t`Move to spam`}</Button>, <Button onClick={() => onReject()}>{c('Action').t`Cancel`}</Button>, ]} {...rest} > <p className="mb-8">{text}</p> <Label htmlFor="remember-me" className="inline-flex w-auto"> <Checkbox id="remember-me" checked={remember} onChange={handleChange} className="mr-2" /> {c('Label').t`Remember my choice`} </Label> </Prompt> ); }; export default MoveToSpamModal;
3,667
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/modals/SimplePublicKeyTable.tsx
import { useEffect, useState } from 'react'; import { format, isValid } from 'date-fns'; import { c } from 'ttag'; import { ContactKeyWarningIcon, Loader, Table, TableBody, TableRow, useActiveBreakpoint } from '@proton/components'; import { useLoading } from '@proton/hooks'; import { dateLocale } from '@proton/shared/lib/i18n'; import { ContactWithBePinnedPublicKey } from '@proton/shared/lib/interfaces/contacts'; import { getFormattedAlgorithmName } from '@proton/shared/lib/keys'; interface Props { contact: ContactWithBePinnedPublicKey; } const SimplePublicKeyTable = ({ contact }: Props) => { const [expirationDate, setExpirationDate] = useState<Date | typeof Infinity | null>(); const [loading, withLoading] = useLoading(); const { isNarrow, isTinyMobile } = useActiveBreakpoint(); const publicKey = contact.bePinnedPublicKey; const fingerprint = publicKey.getFingerprint(); const creationDate = new Date(publicKey.getCreationTime()); const algorithmType = getFormattedAlgorithmName(publicKey.getAlgorithmInfo()); useEffect(() => { const getExpirationTime = async () => { const time = await publicKey.getExpirationTime(); setExpirationDate(time); }; void withLoading(getExpirationTime()); }, []); const fingerprintCell = ( <div key={fingerprint} title={fingerprint} className="flex flex-nowrap"> <ContactKeyWarningIcon className="mr-2 flex-item-noshrink" publicKey={publicKey} emailAddress={contact.emailAddress} isInternal={contact.isInternal} /> <span className="flex-item-fluid text-ellipsis">{fingerprint}</span> </div> ); const creationCell = isNarrow ? null : isValid(creationDate) ? format(creationDate, 'PP', { locale: dateLocale }) : '-'; const expirationCell = isTinyMobile ? null : loading ? ( <Loader className="icon-18p m-auto flex" /> ) : isValid(expirationDate) ? ( format(expirationDate as Date, 'PP', { locale: dateLocale }) ) : ( '-' ); const algorithmCell = !isNarrow && algorithmType; const cells = [fingerprintCell, creationCell, expirationCell, algorithmCell]; return ( <Table className="simple-table"> <thead> <tr> <th scope="col" className="text-ellipsis">{c('Table header').t`Fingerprint`}</th> {!isNarrow && <th scope="col" className="text-ellipsis w-1/5">{c('Table header').t`Created`}</th>} {!isTinyMobile && ( <th scope="col" className="text-ellipsis w-1/6">{c('Table header').t`Expires`}</th> )} {!isNarrow && <th scope="col" className="text-ellipsis w-1/6">{c('Table header').t`Type`}</th>} </tr> </thead> <TableBody> <TableRow key={fingerprint} cells={cells} /> </TableBody> </Table> ); }; export default SimplePublicKeyTable;
3,668
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/modals/TrustPublicKeyModal.test.tsx
import { fireEvent } from '@testing-library/react'; import { act } from '@testing-library/react'; import { PublicKeyReference } from '@proton/crypto'; import { wait } from '@proton/shared/lib/helpers/promise'; import { ContactWithBePinnedPublicKey } from '@proton/shared/lib/interfaces/contacts'; import { addApiMock } from '../../../helpers/test/api'; import { GeneratedKey, addKeysToUserKeysCache, generateKeys } from '../../../helpers/test/crypto'; import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../helpers/test/crypto'; import { clearAll, waitForNotification } from '../../../helpers/test/helper'; import { receiver, sender, setupContactsForPinKeys } from '../../../helpers/test/pinKeys'; import { render, tick } from '../../../helpers/test/render'; import TrustPublicKeyModal from './TrustPublicKeyModal'; const senderAddress = 'sender@outside.com'; const getContact = (senderKey: PublicKeyReference, isContact = false) => { return { emailAddress: senderAddress, name: 'Sender', contactID: isContact ? 'contactID' : undefined, isInternal: false, bePinnedPublicKey: senderKey, } as ContactWithBePinnedPublicKey; }; describe('Trust public key modal', () => { beforeAll(async () => { await setupCryptoProxyForTesting(); }); afterAll(async () => { await releaseCryptoProxy(); }); afterEach(clearAll); const setup = async (senderKeys: GeneratedKey, isContact: boolean) => { const contact = getContact(senderKeys.publicKeys[0], isContact); const component = await render(<TrustPublicKeyModal contact={contact} open />); return component; }; it('should update contact when trusting key if contact already exists', async () => { // Create the contact const { senderKeys, receiverKeys, updateSpy } = await setupContactsForPinKeys(); addKeysToUserKeysCache(receiverKeys); const { getByText, getByTestId } = await setup(senderKeys, true); // Modal is displayed getByText('Trust public key?'); // Click on Trust key button const submitButton = getByTestId('trust-key-modal:submit'); // Without the wait the test is sometimes failing because the call is not done await act(async () => { fireEvent.click(submitButton); await wait(100); }); // Contact has been updated expect(updateSpy).toHaveBeenCalled(); }); it('should create a contact when trusting key if contact does not exists', async () => { const senderKeys = await generateKeys('sender', sender.Address); const receiverKeys = await generateKeys('me', receiver.Address); addKeysToUserKeysCache(receiverKeys); const createSpy = jest.fn(() => { return { Responses: [ { Response: { Code: 1000 }, }, ], }; }); addApiMock('contacts/v4/contacts', createSpy, 'post'); const { getByText, getByTestId } = await setup(senderKeys, false); // Modal is displayed getByText('Trust public key?'); // Click on Trust key button const submitButton = getByTestId('trust-key-modal:submit'); fireEvent.click(submitButton); await tick(); // Contact has been created expect(createSpy).toHaveBeenCalled(); }); it('should display a notification when key could not be trusted', async () => { const senderKeys = await generateKeys('sender', sender.Address); const receiverKeys = await generateKeys('me', receiver.Address); addKeysToUserKeysCache(receiverKeys); const createSpy = jest.fn(() => { return { Responses: [ { Response: { Code: 1002 }, // Wrong api code to trigger the error }, ], }; }); addApiMock('contacts/v4/contacts', createSpy, 'post'); const { getByText, getByTestId } = await setup(senderKeys, false); // Modal is displayed getByText('Trust public key?'); // Click on Trust key button const submitButton = getByTestId('trust-key-modal:submit'); fireEvent.click(submitButton); await tick(); // Contact has been created expect(createSpy).toHaveBeenCalled(); await waitForNotification('Public key could not be trusted'); }); });
3,669
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/modals/TrustPublicKeyModal.tsx
import { c } from 'ttag'; import { Button, Href } from '@proton/atoms'; import { Form, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, PrimaryButton, useApi, useEventManager, useGetUserKeys, useNotifications, } from '@proton/components'; import { PrivateKeyReference, PublicKeyReference } from '@proton/crypto'; import { useLoading } from '@proton/hooks'; import { addContacts, getContact, updateContact } from '@proton/shared/lib/api/contacts'; import { API_CODES, CONTACT_CARD_TYPE } from '@proton/shared/lib/constants'; import { pinKeyCreateContact, pinKeyUpdateContact } from '@proton/shared/lib/contacts/keyPinning'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { Api } from '@proton/shared/lib/interfaces'; import { ContactCard, ContactWithBePinnedPublicKey } from '@proton/shared/lib/interfaces/contacts'; import { splitKeys } from '@proton/shared/lib/keys/keys'; import SimplePublicKeyTable from './SimplePublicKeyTable'; interface ParamsUpdate { contact: Required<ContactWithBePinnedPublicKey>; api: Api; publicKeys: PublicKeyReference[]; privateKeys: PrivateKeyReference[]; } const updateContactPinnedKeys = async ({ contact, api, publicKeys, privateKeys }: ParamsUpdate) => { const { contactID, emailAddress, bePinnedPublicKey, isInternal } = contact; const { Contact: { Cards: contactCards }, } = await api<{ Contact: { Cards: ContactCard[] } }>(getContact(contactID)); const hasSignedCard = !!contactCards.find(({ Type }) => Type === CONTACT_CARD_TYPE.SIGNED); const hasEncryptedCard = !!contactCards.find(({ Type }) => [CONTACT_CARD_TYPE.ENCRYPTED, CONTACT_CARD_TYPE.ENCRYPTED_AND_SIGNED].includes(Type) ); if (hasEncryptedCard && !hasSignedCard) { throw new Error('Corrupted contact card data'); } // If no signed card is present, that means the contact was created by the server, // and we can simply create a new contact const updatedContactCards = hasSignedCard ? await pinKeyUpdateContact({ contactCards, emailAddress, isInternal, bePinnedPublicKey, publicKeys, privateKeys, }) : await pinKeyCreateContact({ emailAddress, isInternal, bePinnedPublicKey, privateKeys, }); await api(updateContact(contactID, { Cards: updatedContactCards })); }; interface ParamsCreate { contact: ContactWithBePinnedPublicKey; api: Api; privateKeys: PrivateKeyReference[]; } const createContactPinnedKeys = async ({ contact, api, privateKeys }: ParamsCreate) => { const { emailAddress, name, isInternal, bePinnedPublicKey } = contact; const contactCards = await pinKeyCreateContact({ emailAddress, name, isInternal, bePinnedPublicKey, privateKeys, }); return api<{ Code: number; Responses: { Response: { Code: number } }[] }>( addContacts({ Contacts: [{ Cards: contactCards }], Overwrite: 1, Labels: 0 }) ); }; interface Props extends ModalProps { contact: ContactWithBePinnedPublicKey; } const TrustPublicKeyModal = ({ contact, ...rest }: Props) => { const api = useApi(); const getUserKeys = useGetUserKeys(); const [loading, withLoading] = useLoading(false); const { createNotification } = useNotifications(); const { call } = useEventManager(); const { onClose } = rest; const isCreateContact = !contact.contactID; const handleUpdateContact = async () => { const { privateKeys: allPrivateKeys, publicKeys } = splitKeys(await getUserKeys()); const privateKeys = [allPrivateKeys[0]]; await updateContactPinnedKeys({ contact: contact as Required<ContactWithBePinnedPublicKey>, api, publicKeys, privateKeys, }); createNotification({ text: c('Success').t`Public key trusted`, type: 'success' }); void call(); // No await onClose?.(); }; const handleCreateContact = async () => { const { privateKeys: allPrivateKeys } = splitKeys(await getUserKeys()); const privateKeys = [allPrivateKeys[0]]; const { Responses: [ { Response: { Code }, }, ], } = await createContactPinnedKeys({ contact, api, privateKeys }); if (Code !== API_CODES.SINGLE_SUCCESS) { createNotification({ text: c('Error').t`Public key could not be trusted`, type: 'error' }); onClose?.(); return; } createNotification({ text: c('Success').t`Public key trusted`, type: 'success' }); void call(); // No await onClose?.(); }; const handleSubmit = isCreateContact ? handleCreateContact : handleUpdateContact; const alertMessage = isCreateContact ? c('Key pinning') .t`Clicking "Trust Key" will create a new contact and associate this public key with this sender. Emails from this address will be automatically cryptographically verified.` : c('Key pinning') .t`Clicking "Trust Key" will associate this public key with this sender and emails from this address will be automatically cryptographically verified.`; return ( <ModalTwo as={Form} onSubmit={() => withLoading(handleSubmit())} size="xlarge" {...rest}> <ModalTwoHeader title={c('Title').t`Trust public key?`} /> <ModalTwoContent> <div className="mb-4"> {alertMessage} <Href href={getKnowledgeBaseUrl('/address-verification')} className="ml-2">{c('Link') .t`Learn more`}</Href> </div> <div className="mb-4"> {c('Info').t`This public key will be automatically used for encrypting email sent to this address.`} <Href href={getKnowledgeBaseUrl('/how-to-use-pgp')} className="ml-2">{c('Link') .t`Learn more`}</Href> </div> <div> <SimplePublicKeyTable contact={contact} /> </div> </ModalTwoContent> <ModalTwoFooter> <Button onClick={onClose}>{c('Action').t`Cancel`}</Button> <PrimaryButton loading={loading} type="submit" data-testid="trust-key-modal:submit"> {c('Action').t`Trust key`} </PrimaryButton> </ModalTwoFooter> </ModalTwo> ); }; export default TrustPublicKeyModal;
3,670
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/recipients/MailRecipientItemSingle.tsx
import { MouseEvent, useMemo } from 'react'; import { useHistory } from 'react-router-dom'; import { c } from 'ttag'; import { DropdownMenuButton, Icon, useModalState, usePopperAnchor } from '@proton/components/components'; import { ContactEditProps } from '@proton/components/containers/contacts/edit/ContactEditModal'; import { PublicKeyReference } from '@proton/crypto'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { createContactPropertyUid } from '@proton/shared/lib/contacts/properties'; import { changeSearchParams } from '@proton/shared/lib/helpers/url'; import { Recipient } from '@proton/shared/lib/interfaces'; import { ContactWithBePinnedPublicKey } from '@proton/shared/lib/interfaces/contacts'; import { VIEW_LAYOUT } from '@proton/shared/lib/mail/mailSettings'; import useMailModel from 'proton-mail/hooks/useMailModel'; import { MESSAGE_ACTIONS } from '../../../constants'; import { useOnCompose } from '../../../containers/ComposeProvider'; import { getHumanLabelID } from '../../../helpers/labels'; import { getContactEmail } from '../../../helpers/message/messageRecipients'; import { ComposeTypes } from '../../../hooks/composer/useCompose'; import { useContactsMap } from '../../../hooks/contact/useContacts'; import { useRecipientLabel } from '../../../hooks/contact/useRecipientLabel'; import useBlockSender from '../../../hooks/useBlockSender'; import { MessageState } from '../../../logic/messages/messagesTypes'; import { MapStatusIcons, StatusIcon } from '../../../models/crypto'; import { Element } from '../../../models/element'; import TrustPublicKeyModal from '../modals/TrustPublicKeyModal'; import RecipientItemSingle from './RecipientItemSingle'; interface Props { message?: MessageState; recipient: Recipient; mapStatusIcons?: MapStatusIcons; globalIcon?: StatusIcon; signingPublicKey?: PublicKeyReference; attachedPublicKey?: PublicKeyReference; isNarrow?: boolean; showDropdown?: boolean; isOutside?: boolean; hideAddress?: boolean; isRecipient?: boolean; isExpanded?: boolean; onContactDetails: (contactID: string) => void; onContactEdit: (props: ContactEditProps) => void; customDataTestId?: string; } const MailRecipientItemSingle = ({ message, recipient, mapStatusIcons, globalIcon, signingPublicKey, attachedPublicKey, isNarrow, showDropdown, isOutside, hideAddress, isRecipient, isExpanded, onContactDetails, onContactEdit, customDataTestId, }: Props) => { const { anchorRef, isOpen, toggle, close } = usePopperAnchor<HTMLButtonElement>(); const history = useHistory(); const contactsMap = useContactsMap(); const { getRecipientLabel } = useRecipientLabel(); const mailSettings = useMailModel('MailSettings'); const onCompose = useOnCompose(); const [trustPublicKeyModalProps, setTrustPublicKeyModalOpen, renderTrustPublicKeyModal] = useModalState(); const { ContactID } = getContactEmail(contactsMap, recipient.Address) || {}; const label = getRecipientLabel(recipient, true); const showTrustPublicKey = !!signingPublicKey || !!attachedPublicKey; const { canShowBlockSender, handleClickBlockSender, blockSenderModal } = useBlockSender({ elements: [message?.data || ({} as Element)], onCloseDropdown: close, }); // We can display the block sender option in the dropdown if: // 1 - Block sender option can be displayed (FF and incoming are ready, item is not already blocked or self address) // 2 - The item is a sender and not a recipient const showBlockSenderOption = canShowBlockSender && !isRecipient; const contact = useMemo<ContactWithBePinnedPublicKey>(() => { return { emailAddress: recipient.Address || '', name: label, contactID: ContactID, isInternal: true, bePinnedPublicKey: signingPublicKey || (attachedPublicKey as PublicKeyReference), }; }, [recipient, label, ContactID, signingPublicKey, attachedPublicKey]); const handleCompose = (event: MouseEvent) => { event.stopPropagation(); onCompose({ type: ComposeTypes.newMessage, action: MESSAGE_ACTIONS.NEW, referenceMessage: { data: { ToList: [recipient] } }, }); close(); }; const handleClickContact = (event: MouseEvent) => { event.stopPropagation(); close(); if (ContactID) { onContactDetails(ContactID); return; } onContactEdit({ vCardContact: { fn: [ { field: 'fn', value: recipient.Name || recipient.Address || '', uid: createContactPropertyUid(), }, ], email: [{ field: 'email', value: recipient.Address || '', uid: createContactPropertyUid() }], }, }); }; const handleClickTrust = (event: MouseEvent) => { event.stopPropagation(); setTrustPublicKeyModalOpen(true); }; const handleClickSearch = (event: MouseEvent) => { event.stopPropagation(); if (recipient.Address) { const humanLabelID = getHumanLabelID(MAILBOX_LABEL_IDS.ALL_MAIL); let newPathname = `/${humanLabelID}`; if (mailSettings.ViewLayout === VIEW_LAYOUT.COLUMN) { const pathname = history.location.pathname.split('/'); pathname[1] = humanLabelID; newPathname = pathname.join('/'); } history.push( changeSearchParams(newPathname, history.location.hash, { keyword: recipient.Address, page: undefined, sort: undefined, }) ); } close(); }; const customDropdownActions = ( <> <hr className="my-2" /> <DropdownMenuButton className="text-left flex flex-nowrap flex-align-items-center" onClick={handleCompose} data-testid="recipient:new-message" > <Icon name="pen-square" className="mr-2" /> <span className="flex-item-fluid my-auto">{c('Action').t`New message`}</span> </DropdownMenuButton> {ContactID ? ( <DropdownMenuButton className="text-left flex flex-nowrap flex-align-items-center" onClick={handleClickContact} data-testid="recipient:view-contact-details" > <Icon name="user" className="mr-2" /> <span className="flex-item-fluid my-auto">{c('Action').t`View contact details`}</span> </DropdownMenuButton> ) : ( <DropdownMenuButton className="text-left flex flex-nowrap flex-align-items-center" onClick={handleClickContact} data-testid="recipient:create-new-contact" > <Icon name="user-plus" className="mr-2" /> <span className="flex-item-fluid my-auto">{c('Action').t`Create new contact`}</span> </DropdownMenuButton> )} <DropdownMenuButton className="text-left flex flex-nowrap flex-align-items-center" onClick={handleClickSearch} data-testid="recipient:search-messages" > <Icon name="envelope-magnifying-glass" className="mr-2" /> <span className="flex-item-fluid my-auto"> {isRecipient ? c('Action').t`Messages to this recipient` : c('Action').t`Messages from this sender`} </span> </DropdownMenuButton> {showBlockSenderOption && ( <DropdownMenuButton className="text-left flex flex-nowrap flex-align-items-center" onClick={handleClickBlockSender} data-testid="block-sender:button" > <Icon name="circle-slash" className="mr-2" /> <span className="flex-item-fluid my-auto">{c('Action').t`Block messages from this sender`}</span> </DropdownMenuButton> )} {showTrustPublicKey && ( <DropdownMenuButton className="text-left flex flex-nowrap flex-align-items-center" onClick={handleClickTrust} data-testid="recipient:show-trust-public-key" > <Icon name="user" className="mr-2" /> <span className="flex-item-fluid my-auto">{c('Action').t`Trust public key`}</span> </DropdownMenuButton> )} </> ); return ( <> <RecipientItemSingle message={message} recipient={recipient} mapStatusIcons={mapStatusIcons} globalIcon={globalIcon} isNarrow={isNarrow} showDropdown={showDropdown} actualLabel={label} customDropdownActions={customDropdownActions} anchorRef={anchorRef} toggle={toggle} close={close} isOpen={isOpen} isOutside={isOutside} hideAddress={hideAddress} isRecipient={isRecipient} isExpanded={isExpanded} customDataTestId={customDataTestId} /> {renderTrustPublicKeyModal && <TrustPublicKeyModal contact={contact} {...trustPublicKeyModalProps} />} {blockSenderModal} </> ); }; export default MailRecipientItemSingle;
3,671
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/recipients/MailRecipientList.tsx
import { ContactEditProps } from '@proton/components/containers/contacts/edit/ContactEditModal'; import { Recipient } from '@proton/shared/lib/interfaces'; import { useRecipientLabel } from '../../../hooks/contact/useRecipientLabel'; import { MapStatusIcons } from '../../../models/crypto'; import RecipientsList from './RecipientsList'; interface Props { list: Recipient[]; mapStatusIcons?: MapStatusIcons; isLoading: boolean; showDropdown?: boolean; isPrintModal?: boolean; onContactDetails: (contactID: string) => void; onContactEdit: (props: ContactEditProps) => void; } const MailRecipientList = ({ list, mapStatusIcons, isLoading, showDropdown, isPrintModal, onContactDetails, onContactEdit, }: Props) => { const { getRecipientsOrGroups } = useRecipientLabel(); /* Recipient "item" can be displayed in several ways * - As a contact group: If recipients are included in a contact group (recipient.Group is filled), we display the contact group, and not the recipient * - As a real recipient * - When contact has no group set * - In print modal, we want to display recipients, not contact group */ const recipientsOrGroup = getRecipientsOrGroups(list, isPrintModal); return ( <RecipientsList mapStatusIcons={mapStatusIcons} isLoading={isLoading} recipientsOrGroup={recipientsOrGroup} showDropdown={showDropdown} isPrintModal={isPrintModal} onContactDetails={onContactDetails} onContactEdit={onContactEdit} /> ); }; export default MailRecipientList;
3,672
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/recipients/MailRecipients.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Icon } from '@proton/components'; import { ContactEditProps } from '@proton/components/containers/contacts/edit/ContactEditModal'; import clsx from '@proton/utils/clsx'; import { MessageState } from '../../../logic/messages/messagesTypes'; import { RecipientOrGroup } from '../../../models/address'; import { MapStatusIcons } from '../../../models/crypto'; import RecipientSimple from './RecipientSimple'; import RecipientsDetails from './RecipientsDetails'; interface Props { message: MessageState; mapStatusIcons?: MapStatusIcons; isLoading: boolean; expanded: boolean; toggleDetails: () => void; recipientsOrGroup: RecipientOrGroup[]; isOutside?: boolean; onContactDetails: (contactID: string) => void; onContactEdit: (props: ContactEditProps) => void; } const MailRecipients = ({ message, mapStatusIcons, isLoading, expanded, toggleDetails, recipientsOrGroup, isOutside, onContactDetails, onContactEdit, }: Props) => { const titleAction = expanded ? c('Action').t`Hide details` : c('Action').t`Show details`; return ( <div id="message-recipients" className={clsx([ 'flex flex-nowrap flex-item-fluid message-recipient', expanded && 'message-recipient-expanded', ])} > {expanded ? ( <RecipientsDetails message={message} isLoading={isLoading} mapStatusIcons={mapStatusIcons} isOutside={isOutside} onContactDetails={onContactDetails} onContactEdit={onContactEdit} /> ) : ( <RecipientSimple isLoading={isLoading} recipientsOrGroup={recipientsOrGroup} isOutside={isOutside} onContactDetails={onContactDetails} onContactEdit={onContactEdit} /> )} {!isLoading && ( <div className="flex-item-noshrink flex ml-auto"> <Button onClick={toggleDetails} aria-expanded={expanded} shape="ghost" color="weak" data-testid="message-show-details" icon className="ml-auto mb-auto message-header-expand-button" title={titleAction} size="small" aria-controls="message-recipients" // hack to get proper styles AND proper vocalization > <Icon name="chevron-down" className={clsx(['navigation-icon--expand', expanded && 'rotateX-180'])} alt={titleAction} /> </Button> </div> )} </div> ); }; export default MailRecipients;
3,673
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/recipients/RecipientItem.tsx
import { useRef } from 'react'; import { c } from 'ttag'; import { ContactEditProps } from '@proton/components/containers/contacts/edit/ContactEditModal'; import { PublicKeyReference } from '@proton/crypto'; import { Recipient } from '@proton/shared/lib/interfaces'; import { MessageState } from '../../../logic/messages/messagesTypes'; import { RecipientOrGroup } from '../../../models/address'; import { MapStatusIcons, StatusIcon } from '../../../models/crypto'; import EORecipientSingle from '../../eo/message/recipients/EORecipientSingle'; import MailRecipientItemSingle from './MailRecipientItemSingle'; import RecipientItemGroup from './RecipientItemGroup'; import RecipientItemLayout from './RecipientItemLayout'; interface Props { message?: MessageState; recipientOrGroup: RecipientOrGroup; mapStatusIcons?: MapStatusIcons; globalIcon?: StatusIcon; isLoading: boolean; signingPublicKey?: PublicKeyReference; attachedPublicKey?: PublicKeyReference; isNarrow?: boolean; showDropdown?: boolean; isOutside?: boolean; hideAddress?: boolean; isRecipient?: boolean; isExpanded?: boolean; onContactDetails: (contactID: string) => void; onContactEdit: (props: ContactEditProps) => void; customDataTestId?: string; } const RecipientItem = ({ message, recipientOrGroup, mapStatusIcons, globalIcon, isLoading, signingPublicKey, attachedPublicKey, isNarrow, showDropdown, isOutside = false, hideAddress, isRecipient, isExpanded, onContactDetails, onContactEdit, customDataTestId, }: Props) => { const ref = useRef<HTMLButtonElement>(null); if (isLoading) { return ( <RecipientItemLayout dropdrownAnchorRef={ref} isLoading showDropdown={showDropdown} isOutside={isOutside} /> ); } if (recipientOrGroup.group) { return ( <RecipientItemGroup group={recipientOrGroup.group} mapStatusIcons={mapStatusIcons} globalIcon={globalIcon} showDropdown={showDropdown} customDataTestId={customDataTestId} /> ); } if (recipientOrGroup.recipient) { if (!isOutside) { return ( <MailRecipientItemSingle message={message} recipient={recipientOrGroup.recipient as Recipient} mapStatusIcons={mapStatusIcons} globalIcon={globalIcon} signingPublicKey={signingPublicKey} attachedPublicKey={attachedPublicKey} isNarrow={isNarrow} showDropdown={showDropdown} isOutside={isOutside} hideAddress={hideAddress} isRecipient={isRecipient} isExpanded={isExpanded} onContactDetails={onContactDetails} onContactEdit={onContactEdit} customDataTestId={customDataTestId} /> ); } return ( <EORecipientSingle recipient={recipientOrGroup.recipient as Recipient} isRecipient={isRecipient} isExpanded={isExpanded} /> ); } // Undisclosed Recipient return ( <RecipientItemLayout dropdrownAnchorRef={ref} label={c('Label').t`Undisclosed Recipients`} title={c('Label').t`Undisclosed Recipients`} showDropdown={showDropdown} isOutside={isOutside} /> ); }; export default RecipientItem;
3,674
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/recipients/RecipientItemGroup.tsx
import { MouseEvent, useState } from 'react'; import { c } from 'ttag'; import { Dropdown, DropdownMenu, DropdownMenuButton, DropdownSizeUnit, Icon, generateUID, useModals, useNotifications, usePopperAnchor, } from '@proton/components'; import RecipientDropdownItem from '@proton/components/containers/contacts/view/RecipientDropdownItem'; import { textToClipboard } from '@proton/shared/lib/helpers/browser'; import { MESSAGE_ACTIONS } from '../../../constants'; import { useOnCompose } from '../../../containers/ComposeProvider'; import { ComposeTypes } from '../../../hooks/composer/useCompose'; import { useGroupsWithContactsMap } from '../../../hooks/contact/useContacts'; import { useRecipientLabel } from '../../../hooks/contact/useRecipientLabel'; import { RecipientGroup } from '../../../models/address'; import { MapStatusIcons, StatusIcon } from '../../../models/crypto'; import GroupModal from '../modals/GroupModal'; import RecipientItemLayout from './RecipientItemLayout'; interface Props { group: RecipientGroup; mapStatusIcons?: MapStatusIcons; globalIcon?: StatusIcon; showDropdown?: boolean; isOutside?: boolean; customDataTestId?: string; } const RecipientItemGroup = ({ group, mapStatusIcons, globalIcon, showDropdown, isOutside, customDataTestId, }: Props) => { const { getGroupLabel, getRecipientLabel } = useRecipientLabel(); const { createModal } = useModals(); const { createNotification } = useNotifications(); const groupsWithContactsMap = useGroupsWithContactsMap(); const [uid] = useState(generateUID('dropdown-group')); const { anchorRef, isOpen, toggle, close } = usePopperAnchor<HTMLButtonElement>(); const onCompose = useOnCompose(); let addresses = group.recipients.map((recipient) => recipient.Address).join(', '); const labelText = getGroupLabel(group, true); const label = ( <div className="text-left flex flex-nowrap flex-align-items-center"> <Icon name="users" className="mr-1" /> <span>{labelText}</span> </div> ); const handleCompose = (event: MouseEvent) => { event.stopPropagation(); onCompose({ type: ComposeTypes.newMessage, action: MESSAGE_ACTIONS.NEW, referenceMessage: { data: { ToList: group.recipients } }, }); close(); }; const handleCopy = (event: MouseEvent<HTMLButtonElement>) => { event.stopPropagation(); textToClipboard(group.recipients.map((recipient) => recipient.Address).join(';'), event.currentTarget); createNotification({ text: c('Info').t`Copied to clipboard` }); close(); }; const handleRecipients = (event: MouseEvent) => { event.stopPropagation(); createModal( <GroupModal recipientGroup={group} group={groupsWithContactsMap[group.group?.ID || '']} mapStatusIcons={mapStatusIcons} globalIcon={globalIcon} /> ); }; return ( <RecipientItemLayout label={label} title={addresses} ariaLabelTitle={`${labelText} ${addresses}`} showDropdown={showDropdown} dropdrownAnchorRef={anchorRef} dropdownToggle={toggle} isDropdownOpen={isOpen} dropdownContent={ <Dropdown id={uid} size={{ maxWidth: DropdownSizeUnit.Viewport }} originalPlacement="bottom" isOpen={isOpen} anchorRef={anchorRef} onClose={close} > <DropdownMenu> {group.recipients.map((recipient) => { return ( <RecipientDropdownItem displaySenderImage={!!recipient?.DisplaySenderImage} recipient={recipient} label={getRecipientLabel(recipient)} closeDropdown={close} key={recipient.Address} bimiSelector={recipient?.BimiSelector || undefined} simple={isOutside} /> ); })} <hr className="my-2" /> <DropdownMenuButton className="text-left flex flex-nowrap flex-align-items-center" onClick={handleCompose} data-testid="recipient:new-message-to-group" > <Icon name="pen-square" className="mr-2" /> <span className="flex-item-fluid my-auto">{c('Action').t`New message`}</span> </DropdownMenuButton> <DropdownMenuButton className="text-left flex flex-nowrap flex-align-items-center" onClick={handleCopy} data-testid="recipient:copy-group-emails" > <Icon name="squares" className="mr-2" /> <span className="flex-item-fluid my-auto">{c('Action').t`Copy addresses`}</span> </DropdownMenuButton> <DropdownMenuButton className="text-left flex flex-nowrap flex-align-items-center" onClick={handleRecipients} data-testid="recipient:view-group-recipients" > <Icon name="user" className="mr-2" /> <span className="flex-item-fluid my-auto">{c('Action').t`View recipients`}</span> </DropdownMenuButton> </DropdownMenu> </Dropdown> } isOutside={isOutside} recipientOrGroup={{ group }} customDataTestId={customDataTestId} /> ); }; export default RecipientItemGroup;
3,675
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/recipients/RecipientItemLayout.tsx
import { MouseEvent, ReactNode, RefObject, useMemo, useRef } from 'react'; import { c } from 'ttag'; import { ProtonBadgeType, useHotkeys } from '@proton/components'; import { highlightNode } from '@proton/encrypted-search'; import { useCombinedRefs } from '@proton/hooks'; import { KeyboardKey } from '@proton/shared/lib/interfaces'; import clsx from '@proton/utils/clsx'; import { useEncryptedSearchContext } from '../../../containers/EncryptedSearchProvider'; import { RecipientOrGroup } from '../../../models/address'; interface Props { label?: ReactNode; itemActionIcon?: ReactNode; labelHasIcon?: boolean; /** * Show address except if recipient list collapsed or if recipient name = recipient email */ showAddress?: boolean; address?: ReactNode; title?: string; ariaLabelTitle?: string; icon?: ReactNode; isLoading?: boolean; isNarrow?: boolean; dropdownContent?: ReactNode; dropdrownAnchorRef: RefObject<HTMLButtonElement>; dropdownToggle?: () => void; isDropdownOpen?: boolean; /** * Dropdown is shown by default, but not in the print modal */ showDropdown?: boolean; isOutside?: boolean; /** * The recipient item is not the sender */ isRecipient?: boolean; recipientOrGroup?: RecipientOrGroup; customDataTestId?: string; } const RecipientItemLayout = ({ label, itemActionIcon, labelHasIcon = false, showAddress = true, address, title, ariaLabelTitle, icon, isLoading = false, isNarrow, dropdownContent, dropdrownAnchorRef, dropdownToggle, isDropdownOpen = false, showDropdown = true, isOutside = false, isRecipient = false, recipientOrGroup, customDataTestId, }: Props) => { // When displaying messages sent as Encrypted Outside, this component is used // almost in isolation, specifically without the usual mail app (and authenticated // routes) around it. This means that useEncryptedSearchContext will not return // the usual encrypted search context but its default value, where each function // is mocked. Since highlightMetadata and shouldHighlight are irrelevant in that // scenario, the mocked version is enough and prevents the component from crashing const { highlightMetadata, shouldHighlight } = useEncryptedSearchContext(); const highlightData = shouldHighlight(); const rootRef = useRef<HTMLSpanElement>(null); const highlightedLabel = useMemo( () => (!!label && highlightData ? highlightNode(label, highlightMetadata) : label), [label, highlightData] ); const highlightedAddress = useMemo( () => (!!address && highlightData ? highlightNode(address, highlightMetadata) : address), [address, highlightData] ); const combinedRef = useCombinedRefs(dropdrownAnchorRef, rootRef); // To have an ellipsis, we need to display the button as a span // We had to add hotkeys to make it accessible with keyboard useHotkeys(rootRef, [ [ 'Enter', (e) => { if (showDropdown) { e.stopPropagation(); dropdownToggle?.(); } }, ], [ KeyboardKey.Spacebar, (e) => { if (showDropdown) { e.stopPropagation(); dropdownToggle?.(); } }, ], ]); const handleClick = (event: MouseEvent) => { if (document.getSelection()?.isCollapsed && showDropdown) { event.stopPropagation(); dropdownToggle?.(); } }; // translator: Example: More details about "Jack <email>" const labelMessageRecipientButton = c('Action').t`More details about ${ariaLabelTitle}`; // had to use span instead of button, otherwise ellipsis can't work return ( <span className={clsx([ 'inline-flex flex-align-items-center flex-nowrap message-recipient-item max-w-full cursor-pointer', isLoading && 'flex-item-fluid', ])} role="button" tabIndex={0} onClick={handleClick} ref={combinedRef} aria-label={labelMessageRecipientButton} aria-expanded={isDropdownOpen} title={title} data-testid={customDataTestId ? customDataTestId : `recipient:details-dropdown-${title}`} > <span className={clsx(['flex flex-align-items-center flex-nowrap max-w-full', isLoading && 'flex-item-fluid'])} > <span className={clsx([ 'inline-flex flex-item-fluid flex-nowrap relative', !isOutside && showDropdown && 'message-recipient-item-label-address', ])} > <span className="inline-block text-ellipsis max-w-full"> {labelHasIcon && ( <span className="inline-block align-sub" data-testid="recipient:action-icon"> {itemActionIcon} </span> )} {icon} <span className={clsx([ 'message-recipient-item-label', isLoading && 'inline-block', isNarrow && 'text-strong', ])} data-testid="recipient-label" > {highlightedLabel} </span> {!isOutside && recipientOrGroup?.recipient && ( <ProtonBadgeType recipient={recipientOrGroup.recipient} /> )} {showAddress && ( <span className={clsx([ 'message-recipient-item-address ml-1', isLoading && 'inline-block', isRecipient ? 'color-weak' : 'color-primary', ])} data-testid="recipient-address" > {highlightedAddress} </span> )} </span> </span> </span> {showDropdown && dropdownContent} </span> ); }; export default RecipientItemLayout;
3,676
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/recipients/RecipientItemSingle.tsx
import { ReactNode, RefObject, useState } from 'react'; import { Dropdown, DropdownMenu, DropdownSizeUnit, generateUID } from '@proton/components'; import RecipientDropdownItem from '@proton/components/containers/contacts/view/RecipientDropdownItem'; import { Recipient } from '@proton/shared/lib/interfaces'; import { MessageState } from '../../../logic/messages/messagesTypes'; import { MapStatusIcons, StatusIcon } from '../../../models/crypto'; import ItemAction from '../../list/ItemAction'; import EncryptionStatusIcon from '../EncryptionStatusIcon'; import RecipientItemLayout from './RecipientItemLayout'; interface Props { message?: MessageState; recipient: Recipient; mapStatusIcons?: MapStatusIcons; globalIcon?: StatusIcon; isNarrow?: boolean; showDropdown?: boolean; actualLabel?: string; customDropdownActions?: ReactNode; anchorRef: RefObject<HTMLButtonElement>; isOpen: boolean; toggle: () => void; close: () => void; isOutside?: boolean; hideAddress?: boolean; isRecipient?: boolean; isExpanded?: boolean; customDataTestId?: string; } const RecipientItemSingle = ({ message, recipient, mapStatusIcons, globalIcon, isNarrow, showDropdown, actualLabel, customDropdownActions, anchorRef, isOpen, toggle, close, isOutside, hideAddress = false, isRecipient = false, isExpanded = false, customDataTestId, }: Props) => { const [uid] = useState(generateUID('dropdown-recipient')); const label = actualLabel || recipient.Name || recipient.Address; const icon = globalIcon || (mapStatusIcons ? mapStatusIcons[recipient.Address as string] : undefined); // We don't want to show the address: // - If recipient has no name (in that case name = address) // - In mail recipients on collapsed mode // - In the collapsed message header const showAddress = (isExpanded && label !== recipient.Address) || (!isRecipient && !hideAddress && label !== recipient.Address); // If the message is has been forwarded, replied or replied all we want to display an icon const isActionLabel = message?.data?.IsForwarded || message?.data?.IsReplied || message?.data?.IsRepliedAll; return ( <RecipientItemLayout label={label} itemActionIcon={<ItemAction element={message?.data} />} labelHasIcon={!!isActionLabel} showAddress={showAddress} address={`<${recipient.Address}>`} title={recipient.Address} ariaLabelTitle={`${label} <${recipient.Address}>`} icon={ icon && ( <span className="inline-flex flex-item-noshrink message-recipient-item-lock-icon mr-1"> <EncryptionStatusIcon {...icon} /> </span> ) } isNarrow={isNarrow} showDropdown={showDropdown} dropdrownAnchorRef={anchorRef} dropdownToggle={toggle} isDropdownOpen={isOpen} dropdownContent={ <Dropdown id={uid} size={{ maxWidth: DropdownSizeUnit.Viewport }} originalPlacement="bottom" isOpen={isOpen} anchorRef={anchorRef} onClose={close} > <DropdownMenu> <RecipientDropdownItem displaySenderImage={!!recipient?.DisplaySenderImage} recipient={recipient} label={label} closeDropdown={close} bimiSelector={recipient?.BimiSelector || undefined} simple={isOutside} /> {customDropdownActions} </DropdownMenu> </Dropdown> } isOutside={isOutside} isRecipient={isRecipient} recipientOrGroup={{ recipient }} customDataTestId={customDataTestId} /> ); }; export default RecipientItemSingle;
3,677
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/recipients/RecipientSimple.tsx
import { c } from 'ttag'; import { ContactEditProps } from '@proton/components/containers/contacts/edit/ContactEditModal'; import { RecipientOrGroup } from '../../../models/address'; import RecipientItem from './RecipientItem'; import RecipientType from './RecipientType'; interface Props { recipientsOrGroup: RecipientOrGroup[]; isLoading: boolean; isOutside?: boolean; onContactDetails: (contactID: string) => void; onContactEdit: (props: ContactEditProps) => void; } const RecipientSimple = ({ isLoading, recipientsOrGroup, isOutside, onContactDetails, onContactEdit }: Props) => { return ( <div className="flex flex-nowrap flex-align-items-center" data-testid="message-header:to"> <RecipientType label={c('Label Recipient').t`To`}> <span className="flex" data-testid="recipients:partial-recipients-list"> {recipientsOrGroup.length ? recipientsOrGroup.map((recipientOrGroup, index) => { return ( <span className="mr-2 flex" key={index}> <RecipientItem recipientOrGroup={recipientOrGroup} isLoading={isLoading} isOutside={isOutside} isRecipient={true} isExpanded={false} onContactDetails={onContactDetails} onContactEdit={onContactEdit} customDataTestId={`recipients:item-${ recipientOrGroup.group ? recipientOrGroup.group.group?.Name : recipientOrGroup.recipient?.Address }`} /> {index < recipientsOrGroup.length - 1 && ( <span className="message-recipient-item-separator mr-0.5">,</span> )} </span> ); }) : c('Label').t`Undisclosed Recipients`} </span> </RecipientType> </div> ); }; export default RecipientSimple;
3,678
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/recipients/RecipientType.tsx
import { ReactNode } from 'react'; interface Props { label: ReactNode; className?: string; children: ReactNode; } const RecipientType = ({ label, className = 'flex flex-align-items-start flex-nowrap message-recipient-item-expanded max-w-full', children, }: Props) => { return ( <span className={className} data-testid={`message-header-expanded:${label}`}> <span className="container-to pt-2 text-semibold">{label}</span> <span className="flex-align-self-center message-recipient-item-expanded-content">{children}</span> </span> ); }; export default RecipientType;
3,679
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/recipients/RecipientsDetails.tsx
import { c } from 'ttag'; import { ContactEditProps } from '@proton/components/containers/contacts/edit/ContactEditModal'; import { MessageState } from '../../../logic/messages/messagesTypes'; import { MapStatusIcons } from '../../../models/crypto'; import EORecipientsList from '../../eo/message/recipients/EORecipientsList'; import MailRecipientList from './MailRecipientList'; import RecipientItem from './RecipientItem'; import RecipientType from './RecipientType'; interface Props { message: MessageState; mapStatusIcons?: MapStatusIcons; isLoading: boolean; isDetailsModal?: boolean; isPrintModal?: boolean; showDropdown?: boolean; isOutside?: boolean; onContactDetails: (contactID: string) => void; onContactEdit: (props: ContactEditProps) => void; } const RecipientsDetails = ({ message, mapStatusIcons, isLoading, isDetailsModal = false, isPrintModal = false, showDropdown, isOutside, onContactDetails, onContactEdit, }: Props) => { const { ToList = [], CCList = [], BCCList = [] } = message?.data || {}; const undisclosedRecipients = ToList.length + CCList.length + BCCList.length === 0; const toRecipientsList = ( <> {!isOutside ? ( <MailRecipientList list={ToList} mapStatusIcons={mapStatusIcons} isLoading={isLoading} showDropdown={showDropdown} isPrintModal={isPrintModal} onContactDetails={onContactDetails} onContactEdit={onContactEdit} /> ) : ( <EORecipientsList list={ToList} isLoading={isLoading} showDropdown={showDropdown} /> )} </> ); const ccRecipientsList = ( <> {!isOutside ? ( <MailRecipientList list={CCList} mapStatusIcons={mapStatusIcons} isLoading={isLoading} showDropdown={showDropdown} isPrintModal={isPrintModal} onContactDetails={onContactDetails} onContactEdit={onContactEdit} /> ) : ( <EORecipientsList list={CCList} isLoading={isLoading} showDropdown={showDropdown} /> )} </> ); const bccRecipientsList = ( <> {!isOutside ? ( <MailRecipientList list={BCCList} mapStatusIcons={mapStatusIcons} isLoading={isLoading} showDropdown={showDropdown} isPrintModal={isPrintModal} onContactDetails={onContactDetails} onContactEdit={onContactEdit} /> ) : ( <EORecipientsList list={BCCList} isLoading={isLoading} showDropdown={showDropdown} /> )} </> ); const undisclosedRecipientsItem = ( <RecipientItem recipientOrGroup={{}} isLoading={isLoading} showDropdown={showDropdown} isOutside={isOutside} onContactDetails={onContactDetails} onContactEdit={onContactEdit} /> ); const outputRecipientsDetails = ( <> {!isDetailsModal ? ( <> {ToList.length > 0 && ( <RecipientType label={c('Label Recipient').t`To`}>{toRecipientsList}</RecipientType> )} {CCList.length > 0 && <RecipientType label={c('Label').t`CC`}>{ccRecipientsList}</RecipientType>} {BCCList.length > 0 && <RecipientType label={c('Label').t`BCC`}>{bccRecipientsList}</RecipientType>} {undisclosedRecipients && ( <RecipientType label={c('Label Recipient').t`To`}>{undisclosedRecipientsItem}</RecipientType> )} </> ) : ( <> {ToList.length > 0 && ( <div className="mb-4 max-w-full" data-testid="recipients:to-list"> <div className="mb-2"> <strong className="mb-2">{c('Title').t`Recipients`}</strong> </div> {toRecipientsList} </div> )} {CCList.length > 0 && ( <div className="mb-4 max-w-full" data-testid="recipients:cc-list"> <div className="mb-2"> <strong className="mb-2">{c('Title').t`CC`}</strong> </div> {ccRecipientsList} </div> )} {BCCList.length > 0 && ( <div className="mb-4 max-w-full" data-testid="recipients:bcc-list"> <div className="mb-2"> <strong className="mb-2">{c('Title').t`BCC`}</strong> </div> {bccRecipientsList} </div> )} {undisclosedRecipients && ( <div className="mb-4"> <div className="mb-2"> <strong className="mb-2">{c('Title').t`BCC`}</strong> </div> {undisclosedRecipientsItem} </div> )} </> )} </> ); return isPrintModal ? ( outputRecipientsDetails ) : ( <div className="flex flex-column flex-align-items-start flex-item-fluid">{outputRecipientsDetails}</div> ); }; export default RecipientsDetails;
3,680
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/recipients/RecipientsList.tsx
import { Fragment } from 'react'; import { ContactEditProps } from '@proton/components/containers/contacts/edit/ContactEditModal'; import { RecipientOrGroup } from '../../../models/address'; import { MapStatusIcons } from '../../../models/crypto'; import RecipientItem from './RecipientItem'; interface Props { recipientsOrGroup: RecipientOrGroup[]; mapStatusIcons?: MapStatusIcons; isLoading: boolean; showDropdown?: boolean; isOutside?: boolean; isPrintModal?: boolean; onContactDetails: (contactID: string) => void; onContactEdit: (props: ContactEditProps) => void; } const RecipientsList = ({ recipientsOrGroup, mapStatusIcons, isLoading, showDropdown, isOutside, isPrintModal, onContactDetails, onContactEdit, }: Props) => ( <Fragment> {recipientsOrGroup.map((recipientOrGroup, index) => ( <Fragment key={index} // eslint-disable-line react/no-array-index-key > <RecipientItem recipientOrGroup={recipientOrGroup} mapStatusIcons={mapStatusIcons} isLoading={isLoading} showDropdown={showDropdown} isOutside={isOutside} isRecipient={true} isExpanded={true} onContactDetails={onContactDetails} onContactEdit={onContactEdit} customDataTestId={`recipients:item-${ recipientOrGroup.group ? recipientOrGroup.group.group?.Name : recipientOrGroup.recipient?.Address }`} /> {isPrintModal && index < recipientsOrGroup.length - 1 && <span>, </span>} </Fragment> ))} </Fragment> ); export default RecipientsList;
3,681
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/recipients
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/recipients/tests/MailRecipientItemSingle.blockSender.test.tsx
import { act } from 'react-dom/test-utils'; import { fireEvent } from '@testing-library/react'; import { RenderResult, queryByTestId } from '@testing-library/react'; import { INCOMING_DEFAULTS_LOCATION, MIME_TYPES } from '@proton/shared/lib/constants'; import { IncomingDefault, MailSettings, Recipient } from '@proton/shared/lib/interfaces'; import { BLOCK_SENDER_CONFIRMATION } from '@proton/shared/lib/mail/constants'; import { addApiMock, addToCache, clearAll, getDropdown, minimalCache, render, setFeatureFlags, waitForNotification, } from '../../../../helpers/test/helper'; import { load } from '../../../../logic/incomingDefaults/incomingDefaultsActions'; import { MessageState } from '../../../../logic/messages/messagesTypes'; import { store } from '../../../../logic/store'; import MailRecipientItemSingle from '../MailRecipientItemSingle'; const meAddress = 'me@protonmail.com'; const me2Address = 'me2@protonmail.com'; const alreadyBlockedAddress = 'alreadyBlocked@protonmail.com'; const recipientAddress = 'recipient@protonmail.com'; const normalSenderAddress = 'normalSender@protonmail.com'; const spamSenderAddress = 'spamSender@protonmail.com'; const inboxSenderAddress = 'inboxSender@protonmail.com'; const spamSenderID = 'spamSender'; const modalsHandlers = { onContactDetails: jest.fn(), onContactEdit: jest.fn(), }; const getTestMessageToBlock = (sender: Recipient) => { return { localID: 'message', data: { ID: 'message', MIMEType: 'text/plain' as MIME_TYPES, Subject: '', Sender: sender, ToList: [] as Recipient[], ConversationID: 'conversationID', }, } as MessageState; }; const openDropdown = async (container: RenderResult, sender: Recipient) => { const { getByTestId } = container; const recipientItem = getByTestId(`recipient:details-dropdown-${sender.Address}`); fireEvent.click(recipientItem); const fromDropdown = await getDropdown(); return fromDropdown; }; const setup = async (sender: Recipient, isRecipient = false, hasBlockSenderConfimationChecked = false) => { minimalCache(); addToCache('MailSettings', { BlockSenderConfirmation: hasBlockSenderConfimationChecked ? BLOCK_SENDER_CONFIRMATION.DO_NOT_ASK : undefined, } as MailSettings); addToCache('Addresses', [ { Email: meAddress, }, { Email: me2Address, }, ]); setFeatureFlags('BlockSender', true); addApiMock('mail/v4/incomingdefaults', () => { return { IncomingDefaults: [ { ID: 'alreadyBlocked', Email: alreadyBlockedAddress, Location: INCOMING_DEFAULTS_LOCATION.BLOCKED, }, { ID: spamSenderID, Email: spamSenderAddress, Location: INCOMING_DEFAULTS_LOCATION.SPAM, }, { ID: 'inboxSender', Email: inboxSenderAddress, Location: INCOMING_DEFAULTS_LOCATION.INBOX, }, ] as IncomingDefault[], Total: 1, GlobalTotal: 3, }; }); const message = getTestMessageToBlock(sender); const container = await render( <MailRecipientItemSingle message={message} recipient={sender} isRecipient={isRecipient} {...modalsHandlers} />, false ); // Load manually incoming defaults await store.dispatch(load()); const dropdown = await openDropdown(container, sender); const blockSenderOption = queryByTestId(dropdown, 'block-sender:button'); return { container, dropdown, blockSenderOption }; }; describe('MailRecipientItemSingle block sender option in dropdown', () => { afterEach(clearAll); it('should not be possible to block sender if sender is the user', async () => { const sender = { Name: 'Me', Address: meAddress, } as Recipient; const { blockSenderOption } = await setup(sender); expect(blockSenderOption).toBeNull(); }); it('should not be possible to block sender if sender is a secondary address of the user', async () => { const sender = { Name: 'Me2', Address: me2Address, } as Recipient; const { blockSenderOption } = await setup(sender); expect(blockSenderOption).toBeNull(); }); it('should not be possible to block sender if sender is already blocked', async () => { const sender = { Name: 'already blocked', Address: alreadyBlockedAddress, } as Recipient; const { blockSenderOption } = await setup(sender); expect(blockSenderOption).toBeNull(); }); it('should not be possible to block sender if item is a recipient and not a sender', async () => { const sender = { Name: 'recipient', Address: recipientAddress, } as Recipient; const { blockSenderOption } = await setup(sender, true); expect(blockSenderOption).toBeNull(); }); it('should be possible to block sender', async () => { const sender = { Name: 'normal sender', Address: normalSenderAddress, } as Recipient; const { blockSenderOption } = await setup(sender); expect(blockSenderOption).not.toBeNull(); }); it('should be possible to block sender if already flagged as spam', async () => { const sender = { Name: 'spam sender', Address: spamSenderAddress, } as Recipient; const { blockSenderOption } = await setup(sender); expect(blockSenderOption).not.toBeNull(); }); it('should be possible to block sender if already flagged as inbox', async () => { const sender = { Name: 'inbox sender', Address: inboxSenderAddress, } as Recipient; const { blockSenderOption } = await setup(sender); expect(blockSenderOption).not.toBeNull(); }); }); describe('MailRecipientItemSingle blocking a sender', () => { afterEach(clearAll); const blockSender = async ( container: RenderResult, senderAddress: string, blockSenderOption: HTMLElement | null, selectDoNotAsk = false ) => { const { findByText, findByTestId } = container; if (blockSenderOption) { fireEvent.click(blockSenderOption); } // Modal is displayed await findByText('Block sender'); await findByText(`New emails from ${senderAddress} won't be delivered and will be permanently deleted.`); // Should check do not ask again if (selectDoNotAsk) { const checkbox = await findByTestId('block-sender-modal-dont-show:checkbox'); act(() => { fireEvent.click(checkbox); }); } // Block sender const blockButton = await findByTestId('block-sender-modal-block:button'); act(() => { fireEvent.click(blockButton); }); }; it('should block a sender', async () => { const createSpy = jest.fn(() => ({ IncomingDefault: { ID: 'normalSender', Email: normalSenderAddress, Location: INCOMING_DEFAULTS_LOCATION.BLOCKED, } as IncomingDefault, })); addApiMock('mail/v4/incomingdefaults?Overwrite=1', createSpy, 'post'); const sender = { Name: 'normal sender', Address: normalSenderAddress, } as Recipient; const { container, blockSenderOption } = await setup(sender); await blockSender(container, normalSenderAddress, blockSenderOption); expect(createSpy).toHaveBeenCalled(); await waitForNotification(`Sender ${normalSenderAddress} blocked`); }); it('should block a sender already in incoming defaults', async () => { const createSpy = jest.fn(() => ({ IncomingDefault: { Email: spamSenderAddress, Location: INCOMING_DEFAULTS_LOCATION.BLOCKED, } as IncomingDefault, })); addApiMock(`mail/v4/incomingdefaults?Overwrite=1`, createSpy, 'post'); const sender = { Name: 'spam sender', Address: spamSenderAddress, } as Recipient; const { container, blockSenderOption } = await setup(sender); await blockSender(container, spamSenderAddress, blockSenderOption); expect(createSpy).toHaveBeenCalled(); await waitForNotification(`Sender ${spamSenderAddress} blocked`); }); it('should block a sender and apply do not ask', async () => { const createSpy = jest.fn(() => ({ IncomingDefault: { ID: 'normalSender', Email: normalSenderAddress, Location: INCOMING_DEFAULTS_LOCATION.BLOCKED, } as IncomingDefault, })); addApiMock('mail/v4/incomingdefaults?Overwrite=1', createSpy, 'post'); const doNotAskSpy = jest.fn(() => ({ BlockSenderConfirmation: BLOCK_SENDER_CONFIRMATION.DO_NOT_ASK, })); addApiMock('mail/v4/settings/block-sender-confirmation', doNotAskSpy, 'put'); const sender = { Name: 'normal sender', Address: normalSenderAddress, } as Recipient; const { container, blockSenderOption } = await setup(sender); await blockSender(container, normalSenderAddress, blockSenderOption, true); expect(createSpy).toHaveBeenCalled(); expect(doNotAskSpy).toHaveBeenCalled(); await waitForNotification(`Sender ${normalSenderAddress} blocked`); }); it('should block a sender and not open the modal', async () => { const createSpy = jest.fn(() => ({ IncomingDefault: { ID: 'normalSender', Email: normalSenderAddress, Location: INCOMING_DEFAULTS_LOCATION.BLOCKED, } as IncomingDefault, })); addApiMock('mail/v4/incomingdefaults?Overwrite=1', createSpy, 'post'); const sender = { Name: 'normal sender', Address: normalSenderAddress, } as Recipient; const { blockSenderOption } = await setup(sender, false, true); // Click on block sender option, no modal should be displayed if (blockSenderOption) { fireEvent.click(blockSenderOption); } expect(createSpy).toHaveBeenCalled(); await waitForNotification(`Sender ${normalSenderAddress} blocked`); }); });
3,682
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/recipients
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/recipients/tests/MailRecipientItemSingle.test.tsx
import { Matcher, fireEvent } from '@testing-library/react'; import { Recipient } from '@proton/shared/lib/interfaces'; import { GeneratedKey, generateKeys } from '../../../../helpers/test/crypto'; import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../../helpers/test/crypto'; import { clearAll } from '../../../../helpers/test/helper'; import { render, tick } from '../../../../helpers/test/render'; import MailRecipientItemSingle from '../MailRecipientItemSingle'; const senderAddress = 'sender@outside.com'; const sender = { Name: 'sender', Address: senderAddress, } as Recipient; const modalsHandlers = { onContactDetails: jest.fn(), onContactEdit: jest.fn(), }; describe('MailRecipientItemSingle trust public key item in dropdown', () => { let senderKeys: GeneratedKey; beforeAll(async () => { await setupCryptoProxyForTesting(); senderKeys = await generateKeys('sender', senderAddress); }); afterAll(async () => { await releaseCryptoProxy(); }); afterEach(clearAll); const openDropdown = async ( getByTestId: (text: Matcher) => HTMLElement, getByText: (text: Matcher) => HTMLElement ) => { // Open the dropdown const recipientItem = getByTestId(`recipient:details-dropdown-${sender.Address}`); fireEvent.click(recipientItem); await tick(); // The dropdown must be open getByText('New message'); }; it('should not contain the trust key action in the dropdown', async () => { const { queryByText, getByTestId, getByText } = await render( <MailRecipientItemSingle recipient={sender} {...modalsHandlers} /> ); await openDropdown(getByTestId, getByText); // Trust public key dropdown item should not be found const dropdownItem = queryByText('Trust public key'); expect(dropdownItem).toBeNull(); }); it('should contain the trust key action in the dropdown if signing key', async () => { const { getByTestId, getByText } = await render( <MailRecipientItemSingle recipient={sender} signingPublicKey={senderKeys.publicKeys[0]} {...modalsHandlers} /> ); await openDropdown(getByTestId, getByText); // Trust public key dropdown item should be found getByText('Trust public key'); }); it('should contain the trust key action in the dropdown if attached key', async () => { const { getByTestId, getByText } = await render( <MailRecipientItemSingle recipient={sender} attachedPublicKey={senderKeys.publicKeys[0]} {...modalsHandlers} /> ); await openDropdown(getByTestId, getByText); // Trust public key dropdown item should be found getByText('Trust public key'); }); });
3,683
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/tests/Message.attachments.test.tsx
import { fireEvent, within } from '@testing-library/react'; import { MIME_TYPES } from '@proton/shared/lib/constants'; import humanSize from '@proton/shared/lib/helpers/humanSize'; import { Attachment, Message } from '@proton/shared/lib/interfaces/mail/Message'; import { VERIFICATION_STATUS } from '@proton/shared/lib/mail/constants'; import { assertIcon } from '../../../helpers/test/assertion'; import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../helpers/test/crypto'; import { GeneratedKey, addApiKeys, addApiMock, clearAll, createEmbeddedImage, createMessageImages, encryptMessage, generateKeys, tick, } from '../../../helpers/test/helper'; import { store } from '../../../logic/store'; import { addressID, body, initMessage, messageID, setup, subject } from './Message.test.helpers'; const cid = 'cid'; const attachment1 = { ID: 'id1', Name: 'attachment-name-unknown', Size: 100, Headers: { 'content-id': cid }, nameSplitStart: 'attachment-name-unkn', nameSplitEnd: 'own', }; const attachment2 = { ID: 'id2', Name: 'attachment-name-pdf.pdf', Size: 200, MIMEType: 'application/pdf', nameSplitStart: 'attachment-name-p', nameSplitEnd: 'df.pdf', }; const attachment3 = { ID: 'id3', Name: 'attachment-name-png.png', Size: 300, MIMEType: 'image/png', // Allow to skip actual download of the file content Preview: { data: [], filename: 'preview', signatures: [], verified: VERIFICATION_STATUS.NOT_SIGNED, }, nameSplitStart: 'attachment-name-p', nameSplitEnd: 'ng.png', }; describe('Message attachments', () => { const Attachments = [attachment1, attachment2, attachment3]; const NumAttachments = Attachments.length; const icons = ['md-unknown', 'md-pdf', 'md-image']; const totalSize = Attachments.map((attachment) => attachment.Size).reduce((acc, size) => acc + size, 0); const embeddedImage = createEmbeddedImage(attachment1); const messageImages = createMessageImages([embeddedImage]); afterEach(clearAll); it('should show attachments with their correct icon', async () => { initMessage({ data: { NumAttachments, Attachments } }); const { getAllByTestId } = await setup(); const items = getAllByTestId('attachment-item'); expect(items.length).toBe(NumAttachments); for (let i = 0; i < NumAttachments; i++) { const { getByText, getByTestId } = within(items[i]); getByText(Attachments[i].nameSplitStart); getByText(Attachments[i].nameSplitEnd); const attachmentSizeText = getByTestId('attachment-item:size').textContent; expect(attachmentSizeText).toEqual(humanSize(Attachments[i].Size)); assertIcon(items[i].querySelector('svg'), icons[i], undefined, 'mime'); } }); it('should show global size and counters', async () => { initMessage({ data: { NumAttachments, Attachments }, messageImages }); const { getByTestId } = await setup(); const header = getByTestId('attachment-list:header'); expect(header.textContent).toMatch(String(totalSize)); expect(header.textContent).toMatch(/2\s*files/); expect(header.textContent).toMatch(/1\s*embedded/); }); it('should open preview when clicking', async () => { window.URL.createObjectURL = jest.fn(); initMessage({ data: { NumAttachments, Attachments } }); const { getAllByTestId } = await setup(); const items = getAllByTestId('attachment-item'); const itemButton = items[2].querySelectorAll('button')[1]; fireEvent.click(itemButton); await tick(); const preview = document.querySelector('.file-preview'); expect(preview).toBeDefined(); expect(preview?.textContent).toMatch(new RegExp(attachment3.Name)); expect(preview?.textContent).toMatch(/3of3/); }); }); describe('NumAttachments from message initialization', () => { const toAddress = 'me@home.net'; const fromName = 'someone'; const fromAddress = 'someone@somewhere.net'; let toKeys: GeneratedKey; let fromKeys: GeneratedKey; beforeAll(async () => { await setupCryptoProxyForTesting(); toKeys = await generateKeys('me', toAddress); fromKeys = await generateKeys('someone', fromAddress); }); afterAll(async () => { await releaseCryptoProxy(); }); it('should have the correct NumAttachments', async () => { const receivedNumAttachment = 1; addApiKeys(false, fromAddress, []); const encryptedBody = await encryptMessage(body, fromKeys, toKeys); addApiMock(`mail/v4/messages/${messageID}`, () => ({ Message: { ID: messageID, AddressID: addressID, Subject: subject, Sender: { Name: fromName, Address: fromAddress }, Body: encryptedBody, MIMEType: MIME_TYPES.DEFAULT, Attachments: [attachment1] as Attachment[], NumAttachments: receivedNumAttachment, } as Message, })); const { open } = await setup({ conversationMode: true }); await open(); const messageFromCache = store.getState().messages[messageID]; expect(messageFromCache?.data?.NumAttachments).toEqual(receivedNumAttachment); }); it('should update NumAttachments', async () => { const receivedNumAttachment = 0; const expectedNumAttachments = 1; addApiKeys(false, fromAddress, []); const encryptedBody = await encryptMessage(body, fromKeys, toKeys); addApiMock(`mail/v4/messages/${messageID}`, () => ({ Message: { ID: messageID, AddressID: addressID, Subject: subject, Sender: { Name: fromName, Address: fromAddress }, Body: encryptedBody, MIMEType: MIME_TYPES.DEFAULT, Attachments: [attachment1] as Attachment[], NumAttachments: receivedNumAttachment, } as Message, })); const { open } = await setup({ conversationMode: true }); await open(); const messageFromCache = store.getState().messages[messageID]; expect(messageFromCache?.data?.NumAttachments).not.toEqual(receivedNumAttachment); expect(messageFromCache?.data?.NumAttachments).toEqual(expectedNumAttachments); }); });
3,684
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/tests/Message.banners.test.tsx
import { waitFor } from '@testing-library/react'; import { setBit } from '@proton/shared/lib/helpers/bitset'; import { MESSAGE_FLAGS } from '@proton/shared/lib/mail/constants'; import { addAddressToCache, minimalCache } from '../../../helpers/test/cache'; import { clearAll } from '../../../helpers/test/helper'; import { initMessage, setup } from './Message.test.helpers'; describe('Message banners', () => { afterEach(clearAll); it('should show expiration banner', async () => { const ExpirationTime = new Date().getTime() / 1000 + 1000; initMessage({ data: { ExpirationTime } }); const { getByTestId } = await setup(); const banner = await waitFor(() => getByTestId('expiration-banner')); expect(banner.textContent).toMatch(/This message will expire/); }); it('should show the decrypted subject banner', async () => { const decryptedSubject = 'decrypted-subject'; initMessage({ data: { Subject: '...' }, decryption: { decryptedSubject } }); const { getByTestId } = await setup(); const banner = getByTestId('encrypted-subject-banner'); expect(banner.textContent).toMatch(new RegExp(decryptedSubject)); }); it('should show the spam banner', async () => { initMessage({ data: { Flags: setBit( MESSAGE_FLAGS.FLAG_PHISHING_AUTO, setBit(MESSAGE_FLAGS.FLAG_SENT, setBit(0, MESSAGE_FLAGS.FLAG_RECEIVED)) ), }, }); const { getByTestId } = await setup(); const banner = getByTestId('spam-banner:phishing-banner'); expect(banner.textContent).toMatch(/phishing/); }); it('should show error banner for network error', async () => { initMessage({ errors: { network: [new Error('test')] } }); const { getByTestId } = await setup(); const banner = getByTestId('errors-banner'); expect(banner.textContent).toMatch(/error/); }); it('should show the unsubscribe banner with one click method', async () => { const toAddress = 'to@domain.com'; minimalCache(); addAddressToCache({ Email: toAddress }); initMessage({ data: { ParsedHeaders: { 'X-Original-To': toAddress }, UnsubscribeMethods: { OneClick: 'OneClick' }, }, }); const { getByTestId } = await setup({}, false); const banner = getByTestId('unsubscribe-banner'); expect(banner.textContent).toMatch(/Unsubscribe/); }); // it('AUTOPROMPT', async () => {}); // it('PIN_UNSEEN', async () => {}); // it('PIN_ATTACHED_SIGNING mode', async () => {}); // it('PIN_ATTACHED mode', async () => {}); });
3,685
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/tests/Message.content.test.tsx
import { fireEvent, screen } from '@testing-library/react'; import { MIME_TYPES } from '@proton/shared/lib/constants'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { addApiKeys } from '../../../helpers/test/crypto'; import { initialize } from '../../../logic/messages/read/messagesReadActions'; import { store } from '../../../logic/store'; import { MESSAGE_IFRAME_PRINT_CLASS, MESSAGE_IFRAME_PRINT_FOOTER_ID, MESSAGE_IFRAME_PRINT_HEADER_ID, } from '../constants'; import { getIframeRootDiv, setup } from './Message.test.helpers'; describe('Message content', () => { describe('plain text', () => { it('should not contain print classes and elements', async () => { const ID1 = 'ID1'; const sender1Email = 'sender1@email.com'; addApiKeys(false, sender1Email, []); const message1 = { localID: ID1, data: { ID: ID1, Body: 'something', MIMEType: MIME_TYPES.PLAINTEXT, Sender: { Name: '', Address: sender1Email }, } as Message, messageDocument: { initialized: true, plainText: 'Body1' }, }; store.dispatch(initialize(message1)); const { container } = await setup({ message: message1.data }); const iframe = await getIframeRootDiv(container); const wrapper = document.createElement('div'); wrapper.appendChild(iframe); expect(wrapper.querySelector('.proton-plain-text')).not.toBe(null); expect(wrapper.querySelector('.' + MESSAGE_IFRAME_PRINT_CLASS)).toBe(null); expect(wrapper.querySelector('#' + MESSAGE_IFRAME_PRINT_HEADER_ID)).toBe(null); expect(wrapper.querySelector('#' + MESSAGE_IFRAME_PRINT_FOOTER_ID)).toBe(null); }); // Issues displaying dropdown. it.skip('should contain print classes and elements', async () => { const ID1 = 'ID1'; const sender1Email = 'sender1@email.com'; addApiKeys(false, sender1Email, []); const message1 = { localID: ID1, data: { ID: ID1, Body: 'something', MIMEType: MIME_TYPES.PLAINTEXT, Sender: { Name: '', Address: sender1Email }, } as Message, messageDocument: { initialized: true, plainText: 'Body1' }, }; store.dispatch(initialize(message1)); await setup({ message: message1.data }); const moreDropdown = await screen.findByTestId('message-header-expanded:more-dropdown'); fireEvent.click(moreDropdown); const printButton = await screen.findByTestId('message-view-more-dropdown:print'); fireEvent.click(printButton); const printModal = await screen.findByTestId('modal:print-message'); const iframe = await getIframeRootDiv(printModal.querySelector('iframe') as HTMLIFrameElement); const wrapper = document.createElement('div'); wrapper.appendChild(iframe); expect(wrapper.querySelector('.proton-plain-text')).not.toBe(null); expect(wrapper.querySelector('.' + MESSAGE_IFRAME_PRINT_CLASS)).not.toBe(null); expect(wrapper.querySelector('#' + MESSAGE_IFRAME_PRINT_HEADER_ID)).not.toBe(null); expect(wrapper.querySelector('#' + MESSAGE_IFRAME_PRINT_FOOTER_ID)).not.toBe(null); }); }); });
3,686
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/tests/Message.dark.test.tsx
import { waitFor } from '@testing-library/react'; import { FeatureCode } from '@proton/components'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { addApiMock, clearAll, createDocument, minimalCache, setFeatureFlags } from '../../../helpers/test/helper'; import { MessageState } from '../../../logic/messages/messagesTypes'; import { getIframeRootDiv, initMessage, setup as messageSetup } from './Message.test.helpers'; jest.mock('@proton/components/containers/themes/ThemeProvider', () => { return { useTheme: () => ({ information: { dark: true } }), }; }); describe('Message dark styles', () => { afterEach(clearAll); const setup = async (content: string) => { addApiMock('metrics', () => ({})); setFeatureFlags(FeatureCode.DarkStylesInBody, true); const document = createDocument(content); const message: MessageState = { localID: 'messageID', data: { ID: 'messageID', } as Message, messageDocument: { document }, }; minimalCache(); initMessage(message); const { container } = await messageSetup({}, false); const iframe = await getIframeRootDiv(container); await waitFor(() => { const placeholders = container.querySelectorAll('.message-content-loading-placeholder'); if (placeholders.length > 0) { throw new Error('placeholders'); } }); return iframe.classList.contains('proton-dark-style'); }; it('should activate dark style when no contrast issue', async () => { const content = ` <div> <p>this is a test</p> <p>with no special style</p> </div> `; const hasDarkStyle = await setup(content); expect(hasDarkStyle).toBe(true); }); it('should not activate dark style when a contrast issue is found', async () => { const content = ` <div> <p>this is a test</p> <p style='color: #111'>with forced color</p> </div> `; const hasDarkStyle = await setup(content); expect(hasDarkStyle).toBe(false); }); it('should deal with transparent backgrounds', async () => { const content = ` <div> <p>this is a test</p> <p style='background: #0000'>with transparent background</p> </div> `; const hasDarkStyle = await setup(content); expect(hasDarkStyle).toBe(true); }); it('should deal with forced light', async () => { const content = ` <div> <p>this is a test</p> <p style='color: #fff; background: #000'>with forced light section</p> </div> `; const hasDarkStyle = await setup(content); expect(hasDarkStyle).toBe(true); }); });
3,687
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/tests/Message.encryption.test.tsx
import { findByText } from '@testing-library/react'; import { MIME_TYPES } from '@proton/shared/lib/constants'; import { Attachment, Message } from '@proton/shared/lib/interfaces/mail/Message'; import { parseInDiv } from '../../../helpers/dom'; import { constructMime } from '../../../helpers/send/sendMimeBuilder'; import { addApiContact } from '../../../helpers/test/contact'; import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../helpers/test/crypto'; import { GeneratedKey, addApiKeys, addApiMock, addKeysToAddressKeysCache, addKeysToUserKeysCache, api, assertIcon, clearAll, encryptMessage, generateKeys, } from '../../../helpers/test/helper'; import { MessageKeys } from '../../../logic/messages/messagesTypes'; import { X_PM_HEADERS } from '../../../models/crypto'; import { addressID, body, getIframeRootDiv, localID, messageID, setup, subject } from './Message.test.helpers'; jest.setTimeout(20000); describe('MessageView encryption', () => { const toAddress = 'me@home.net'; const fromName = 'someone'; const fromAddress = 'someone@somewhere.net'; const otherAddress = 'other@somewhere.net'; let toKeys: GeneratedKey; let fromKeys: GeneratedKey; let otherKeys: GeneratedKey; let publicPrivateKey: MessageKeys; beforeAll(async () => { await setupCryptoProxyForTesting(); toKeys = await generateKeys('me', toAddress); fromKeys = await generateKeys('someone', fromAddress); otherKeys = await generateKeys('other', otherAddress); publicPrivateKey = { type: 'publicPrivate', publicKeys: toKeys.publicKeys, privateKeys: toKeys.privateKeys, }; }); afterAll(async () => { await releaseCryptoProxy(); }); afterEach(clearAll); describe('Decrypt and render', () => { it('html', async () => { addKeysToAddressKeysCache(addressID, toKeys); addApiKeys(false, fromAddress, []); const encryptedBody = await encryptMessage(body, fromKeys, toKeys); addApiMock(`mail/v4/messages/${messageID}`, () => ({ Message: { ID: messageID, AddressID: addressID, Subject: subject, Sender: { Name: fromName, Address: fromAddress }, Body: encryptedBody, MIMEType: MIME_TYPES.DEFAULT, Attachments: [] as Attachment[], } as Message, })); const { open, container } = await setup({ conversationMode: true }); await open(); const iframeContent = await getIframeRootDiv(container); await findByText(iframeContent, body); }); it('plaintext', async () => { addKeysToAddressKeysCache(addressID, toKeys); addApiKeys(false, fromAddress, []); const encryptedBody = await encryptMessage(body, fromKeys, toKeys); addApiMock(`mail/v4/messages/${messageID}`, () => ({ Message: { ID: messageID, AddressID: addressID, Subject: subject, Sender: { Name: fromName, Address: fromAddress }, Body: encryptedBody, MIMEType: MIME_TYPES.PLAINTEXT, Attachments: [] as Attachment[], } as Message, })); const { open, container } = await setup(); await open(); const iframeContent = await getIframeRootDiv(container); await findByText(iframeContent, body); }); it('multipart/mixed html', async () => { const message = { ID: messageID, AddressID: addressID, Subject: subject, Sender: { Name: fromName, Address: fromAddress }, MIMEType: MIME_TYPES.MIME, Attachments: [] as Attachment[], } as Message; addKeysToAddressKeysCache(addressID, toKeys); addApiKeys(false, fromAddress, []); const mimeBody = await constructMime( { localID, data: message, messageDocument: { document: parseInDiv(body) } }, publicPrivateKey, jest.fn(), jest.fn(), api, false ); const encryptedBody = await encryptMessage(mimeBody, fromKeys, toKeys); addApiMock(`mail/v4/messages/${messageID}`, () => ({ Message: { ...message, Body: encryptedBody }, })); const { open, container } = await setup(); await open(); const iframeContent = await getIframeRootDiv(container); await findByText(iframeContent, body); }); it('multipart/mixed plaintext', async () => { const message = { ID: messageID, AddressID: addressID, Subject: subject, Sender: { Name: fromName, Address: fromAddress }, MIMEType: MIME_TYPES.MIME, Attachments: [] as Attachment[], } as Message; addKeysToAddressKeysCache(addressID, toKeys); addApiKeys(false, fromAddress, []); const mimeBody = await constructMime( { localID, data: { ...message, MIMEType: MIME_TYPES.PLAINTEXT }, messageDocument: { plainText: body } }, publicPrivateKey, jest.fn(), jest.fn(), api, false ); const encryptedBody = await encryptMessage(mimeBody, fromKeys, toKeys); addApiMock(`mail/v4/messages/${messageID}`, () => ({ Message: { ...message, Body: encryptedBody }, })); const { open, container } = await setup(); await open(); const iframeContent = await getIframeRootDiv(container); await findByText(iframeContent, body); }); }); describe('Signature verification', () => { it('verified sender internal', async () => { addKeysToAddressKeysCache(addressID, toKeys); addKeysToUserKeysCache(toKeys); addApiKeys(true, fromAddress, [fromKeys]); addApiContact({ contactID: 'contactID', email: fromAddress, pinKey: fromKeys }, toKeys); const encryptedBody = await encryptMessage(body, fromKeys, toKeys); addApiMock(`mail/v4/messages/${messageID}`, () => ({ Message: { ID: messageID, AddressID: addressID, Sender: { Name: fromName, Address: fromAddress, }, Subject: subject, Body: encryptedBody, MIMEType: MIME_TYPES.DEFAULT, Attachments: [] as Attachment[], ParsedHeaders: { 'X-Pm-Origin': X_PM_HEADERS.INTERNAL, 'X-Pm-Content-Encryption': X_PM_HEADERS.END_TO_END, } as any, Time: new Date().getTime(), } as Message, })); const { open, findByTestId } = await setup(); await open(); const icon = await findByTestId('encryption-icon'); assertIcon(icon, 'lock-check-filled', 'color-info'); }); it('verified sender external', async () => { addKeysToAddressKeysCache(addressID, toKeys); addKeysToUserKeysCache(toKeys); addApiKeys(false, fromAddress, [fromKeys]); addApiContact({ contactID: 'contactID', email: fromAddress, pinKey: fromKeys }, toKeys); const message = { ID: messageID, AddressID: addressID, Sender: { Address: fromAddress, }, Subject: subject, MIMEType: MIME_TYPES.DEFAULT, Attachments: [] as Attachment[], ParsedHeaders: { 'X-Pm-Origin': X_PM_HEADERS.EXTERNAL, 'X-Pm-Content-Encryption': X_PM_HEADERS.END_TO_END, } as any, Time: new Date().getTime(), } as Message; const mimeBody = await constructMime( { localID, data: message, messageDocument: { document: parseInDiv(body) } }, publicPrivateKey, jest.fn(), jest.fn(), api, false ); const encryptedBody = await encryptMessage(mimeBody, fromKeys, toKeys); addApiMock(`mail/v4/messages/${messageID}`, () => ({ Message: { ...message, Body: encryptedBody }, })); const { open, findByTestId } = await setup(); await open(); const icon = await findByTestId('encryption-icon'); assertIcon(icon, 'lock-check-filled', 'color-success'); }); it('signature verification error', async () => { addKeysToAddressKeysCache(addressID, toKeys); addKeysToUserKeysCache(toKeys); addApiKeys(true, fromAddress, []); addApiContact({ contactID: 'contactID', email: fromAddress, pinKey: otherKeys }, toKeys); const encryptedBody = await encryptMessage(body, fromKeys, toKeys); addApiMock(`mail/v4/messages/${messageID}`, () => ({ Message: { ID: messageID, AddressID: addressID, Sender: { Name: fromName, Address: fromAddress, }, Subject: subject, Body: encryptedBody, MIMEType: MIME_TYPES.DEFAULT, Attachments: [] as Attachment[], ParsedHeaders: { 'X-Pm-Origin': X_PM_HEADERS.INTERNAL, 'X-Pm-Content-Encryption': X_PM_HEADERS.END_TO_END, } as any, Time: new Date().getTime(), } as Message, })); const { open, findByTestId } = await setup(); await open(); const icon = await findByTestId('encryption-icon'); assertIcon(icon, 'lock-exclamation-filled', 'color-info'); }); }); });
3,688
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/tests/Message.images.test.tsx
import { findByTestId, fireEvent } from '@testing-library/react'; import { mockWindowLocation, resetWindowLocation } from '@proton/components/helpers/url.test.helpers'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { IMAGE_PROXY_FLAGS, SHOW_IMAGES } from '@proton/shared/lib/mail/mailSettings'; import { addApiMock, addToCache, assertIcon, clearAll, minimalCache } from '../../../helpers/test/helper'; import { createDocument } from '../../../helpers/test/message'; import { MessageState } from '../../../logic/messages/messagesTypes'; import MessageView from '../MessageView'; import { defaultProps, getIframeRootDiv, initMessage, setup } from './Message.test.helpers'; const imageURL = 'imageURL'; const blobURL = 'blobURL'; const content = `<div> <div> <table> <tbody> <tr> <td proton-background='${imageURL}' data-testid="image-background">Element</td> </tr> </tbody> </table> </div> <div> <video proton-poster='${imageURL}' data-testid="image-poster"> <source src="" type="video/mp4" /> </video> </div> <div> <picture> <source media="(min-width:650px)" proton-srcset='${imageURL}' data-testid="image-srcset"/> <img src='${imageURL}' data-testid="image-srcset2"/> </picture> </div> <div> <svg width="50" height="50"> <image proton-xlink:href='${imageURL}' data-testid="image-xlinkhref"/> </svg> </div> </div>`; jest.mock('../../../helpers/dom', () => ({ ...jest.requireActual('../../../helpers/dom'), preloadImage: jest.fn(() => Promise.resolve()), })); const windowHostname = 'https://mail.proton.pink'; describe('Message images', () => { beforeEach(() => { mockWindowLocation(windowHostname); }); afterEach(() => { resetWindowLocation(); }); afterEach(clearAll); it('should display all elements other than images', async () => { const document = createDocument(content); const message: MessageState = { localID: 'messageID', data: { ID: 'messageID', } as Message, messageDocument: { document }, messageImages: { hasEmbeddedImages: false, hasRemoteImages: true, showRemoteImages: false, showEmbeddedImages: true, trackersStatus: 'not-loaded', images: [], }, }; minimalCache(); addToCache('MailSettings', { HideRemoteImages: SHOW_IMAGES.HIDE }); initMessage(message); const { container, rerender, getByTestId } = await setup({}, false); const iframe = await getIframeRootDiv(container); // Check that all elements are displayed in their proton attributes before loading them const elementBackground = await findByTestId(iframe, 'image-background'); expect(elementBackground.getAttribute('proton-background')).toEqual(imageURL); const elementPoster = await findByTestId(iframe, 'image-poster'); expect(elementPoster.getAttribute('proton-poster')).toEqual(imageURL); const elementSrcset = await findByTestId(iframe, 'image-srcset'); expect(elementSrcset.getAttribute('proton-srcset')).toEqual(imageURL); const elementXlinkhref = await findByTestId(iframe, 'image-xlinkhref'); expect(elementXlinkhref.getAttribute('proton-xlink:href')).toEqual(imageURL); const loadButton = getByTestId('remote-content:load'); fireEvent.click(loadButton); // Rerender the message view to check that images have been loaded await rerender(<MessageView {...defaultProps} />); const iframeRerendered = await getIframeRootDiv(container); // Check that proton attribute has been removed after images loading const updatedElementBackground = await findByTestId(iframeRerendered, 'image-background'); expect(updatedElementBackground.getAttribute('background')).toEqual(imageURL); const updatedElementPoster = await findByTestId(iframeRerendered, 'image-poster'); expect(updatedElementPoster.getAttribute('poster')).toEqual(imageURL); // srcset attribute is not loaded so we should check proton-srcset const updatedElementSrcset = await findByTestId(iframeRerendered, 'image-srcset'); expect(updatedElementSrcset.getAttribute('proton-srcset')).toEqual(imageURL); const updatedElementXlinkhref = await findByTestId(iframeRerendered, 'image-xlinkhref'); expect(updatedElementXlinkhref.getAttribute('xlink:href')).toEqual(imageURL); }); it('should load correctly all elements other than images with proxy', async () => { const forgedURL = `${windowHostname}/api/core/v4/images?Url=imageURL&DryRun=0&UID=uid`; const document = createDocument(content); const message: MessageState = { localID: 'messageID', data: { ID: 'messageID', } as Message, messageDocument: { document }, messageImages: { hasEmbeddedImages: false, hasRemoteImages: true, showRemoteImages: false, showEmbeddedImages: true, trackersStatus: 'not-loaded', images: [], }, }; minimalCache(); addToCache('MailSettings', { HideRemoteImages: SHOW_IMAGES.HIDE, ImageProxy: IMAGE_PROXY_FLAGS.PROXY }); initMessage(message); const { container, rerender, getByTestId } = await setup({}, false); const iframe = await getIframeRootDiv(container); // Need to mock this function to mock the blob url window.URL.createObjectURL = jest.fn(() => blobURL); // Check that all elements are displayed in their proton attributes before loading them const elementBackground = await findByTestId(iframe, 'image-background'); expect(elementBackground.getAttribute('proton-background')).toEqual(imageURL); const elementPoster = await findByTestId(iframe, 'image-poster'); expect(elementPoster.getAttribute('proton-poster')).toEqual(imageURL); const elementSrcset = await findByTestId(iframe, 'image-srcset'); expect(elementSrcset.getAttribute('proton-srcset')).toEqual(imageURL); const elementXlinkhref = await findByTestId(iframe, 'image-xlinkhref'); expect(elementXlinkhref.getAttribute('proton-xlink:href')).toEqual(imageURL); const loadButton = getByTestId('remote-content:load'); fireEvent.click(loadButton); // Rerender the message view to check that images have been loaded await rerender(<MessageView {...defaultProps} />); const iframeRerendered = await getIframeRootDiv(container); // Check that proton attribute has been removed after images loading const updatedElementBackground = await findByTestId(iframeRerendered, 'image-background'); expect(updatedElementBackground.getAttribute('background')).toEqual(forgedURL); const updatedElementPoster = await findByTestId(iframeRerendered, 'image-poster'); expect(updatedElementPoster.getAttribute('poster')).toEqual(forgedURL); // srcset attribute is not loaded, so we need to check proton-srcset const updatedElementSrcset = await findByTestId(iframeRerendered, 'image-srcset'); expect(updatedElementSrcset.getAttribute('proton-srcset')).toEqual(imageURL); const updatedElementXlinkhref = await findByTestId(iframeRerendered, 'image-xlinkhref'); expect(updatedElementXlinkhref.getAttribute('xlink:href')).toEqual(forgedURL); }); it('should be able to load direct when proxy failed at loading', async () => { const imageURL = 'imageURL'; const content = `<div><img proton-src="${imageURL}" data-testid="image"/></div>`; const document = createDocument(content); const message: MessageState = { localID: 'messageID', data: { ID: 'messageID', } as Message, messageDocument: { document }, messageImages: { hasEmbeddedImages: false, hasRemoteImages: true, showRemoteImages: false, showEmbeddedImages: true, trackersStatus: 'not-loaded', images: [], }, }; addApiMock(`core/v4/images`, () => { const error = new Error(); (error as any).data = { Code: 2902, Error: 'TEST error message' }; return Promise.reject(error); }); minimalCache(); addToCache('MailSettings', { HideRemoteImages: SHOW_IMAGES.HIDE, ImageProxy: IMAGE_PROXY_FLAGS.PROXY }); initMessage(message); const { getByTestId, rerender, container } = await setup({}, false); const iframe = await getIframeRootDiv(container); const image = await findByTestId(iframe, 'image'); expect(image.getAttribute('proton-src')).toEqual(imageURL); let loadButton = getByTestId('remote-content:load'); fireEvent.click(loadButton); // Rerender the message view to check that images have been loaded through URL await rerender(<MessageView {...defaultProps} />); const iframeRerendered = await getIframeRootDiv(container); const placeholder = iframeRerendered.querySelector('.proton-image-placeholder') as HTMLImageElement; expect(placeholder).not.toBe(null); assertIcon(placeholder.querySelector('svg'), 'cross-circle'); loadButton = getByTestId('remote-content:load'); fireEvent.click(loadButton); // Rerender the message view to check that images have been loaded await rerender(<MessageView {...defaultProps} />); const loadedImage = iframeRerendered.querySelector('.proton-image-anchor img') as HTMLImageElement; expect(loadedImage).toBeDefined(); expect(loadedImage.getAttribute('src')).toEqual( `https://mail.proton.pink/api/core/v4/images?Url=${imageURL}&DryRun=0&UID=uid` ); }); });
3,689
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/tests/Message.modes.test.tsx
import { act } from '@testing-library/react'; import { addApiResolver, clearAll } from '../../../helpers/test/helper'; import { initMessage, messageID, setup } from './Message.test.helpers'; jest.setTimeout(20000); describe('Message display modes', () => { afterEach(clearAll); it('loading mode', async () => { addApiResolver(`mail/v4/messages/${messageID}`); const { ref, getByTestId } = await setup(); const messageView = getByTestId('message-view-0'); act(() => ref.current?.expand()); const placeholders = messageView.querySelectorAll('.message-content-loading-placeholder'); expect(placeholders.length).toBeGreaterThanOrEqual(3); }); it('encrypted mode', async () => { const encryptedBody = 'body-test'; initMessage({ data: { Body: encryptedBody }, errors: { decryption: [new Error('test')] } }); const { getByTestId } = await setup(); const errorsBanner = getByTestId('errors-banner'); expect(errorsBanner.textContent).toContain('Decryption error'); const messageView = getByTestId('message-view-0'); expect(messageView.textContent).toContain(encryptedBody); }); it('source mode on processing error', async () => { const decryptedBody = 'decrypted-test'; initMessage({ data: { Body: 'test' }, errors: { processing: [new Error('test')] }, decryption: { decryptedBody }, }); const { getByTestId } = await setup(); const errorsBanner = getByTestId('errors-banner'); expect(errorsBanner.textContent).toContain('processing error'); const messageView = getByTestId('message-view-0'); expect(messageView.textContent).toContain(decryptedBody); }); });
3,690
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/tests/Message.recipients.test.tsx
import { ContactEmail, ContactGroup } from '@proton/shared/lib/interfaces/contacts'; import { clearAll } from '../../../helpers/test/helper'; import { refresh } from '../../../logic/contacts/contactsActions'; import { store } from '../../../logic/store'; import { initMessage, setup } from './Message.test.helpers'; describe('Message recipients rendering', () => { afterEach(clearAll); it('show a recipient not associated with a contact', async () => { const Name = 'test-name'; const Address = 'address@test.com'; initMessage({ data: { ToList: [{ Name, Address }] } }); const { getByText, details } = await setup(); getByText(Name); await details(); getByText(Name); getByText(Address, { exact: false }); }); it('show a recipient matching a contact', async () => { const Name = 'test-name'; const Address = 'address@test.com'; const ContactEmail = { Email: Address, Name: 'test-contact', } as ContactEmail; store.dispatch(refresh({ contacts: [ContactEmail], contactGroups: [] })); initMessage({ data: { ToList: [{ Name, Address }] } }); const { getByText, details } = await setup(); getByText(ContactEmail.Name); await details(); getByText(ContactEmail.Name); getByText(Address, { exact: false }); }); it('show recipients in a contact group partial', async () => { const Name = 'test-name'; const Address = 'address@test.com'; const ContactGroup = { ID: 'test-group-id', Name: 'test-group-name', Path: 'test-group-path', } as ContactGroup; const Group = ContactGroup.Path; const contacts = [ { Email: '', LabelIDs: [ContactGroup.ID] }, { Email: '', LabelIDs: [ContactGroup.ID] }, { Email: '', LabelIDs: [ContactGroup.ID] }, ] as ContactEmail[]; const ToList = [ { Name, Address, Group }, { Name, Address, Group }, ]; store.dispatch(refresh({ contacts, contactGroups: [ContactGroup] })); initMessage({ data: { ToList } }); const { getByText } = await setup(); const expectation = `${ContactGroup.Name} (${ToList.length}/${contacts.length})`; getByText(expectation); }); it('show recipients in a contact group full', async () => { const Name = 'test-name'; const Address = 'address@test.com'; const ContactGroup = { ID: 'test-group-id', Name: 'test-group-name', Path: 'test-group-path', } as ContactGroup; const Group = ContactGroup.Path; const contacts = [ { Email: '', LabelIDs: [ContactGroup.ID] }, { Email: '', LabelIDs: [ContactGroup.ID] }, { Email: '', LabelIDs: [ContactGroup.ID] }, ] as ContactEmail[]; const ToList = [ { Name, Address, Group }, { Name, Address, Group }, { Name, Address, Group }, ]; store.dispatch(refresh({ contacts, contactGroups: [ContactGroup] })); initMessage({ data: { ToList } }); const { getByText } = await setup(); const expectation = `${ContactGroup.Name} (${contacts.length})`; getByText(expectation); }); });
3,691
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/tests/Message.state.test.tsx
import { findByText } from '@testing-library/react'; import { MIME_TYPES } from '@proton/shared/lib/constants'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { addApiKeys, addApiMock, clearAll } from '../../../helpers/test/helper'; import { initialize } from '../../../logic/messages/read/messagesReadActions'; import { store } from '../../../logic/store'; import { addressID, getIframeRootDiv, initMessage, messageID, setup } from './Message.test.helpers'; describe('message state', () => { afterEach(clearAll); it('should initialize message in cache if not existing', async () => { const senderEmail = 'sender@email.com'; addApiKeys(false, senderEmail, []); const Message = { ID: messageID, AddressID: addressID, Attachments: [], NumAttachments: 0, Sender: { Name: '', Address: senderEmail }, } as any as Message; addApiMock(`mail/v4/messages/${messageID}`, () => ({ Message })); await setup(); const messageFromCache = store.getState().messages[messageID]; expect(messageFromCache).toBeDefined(); expect(messageFromCache?.data).toEqual(Message); }); it('should returns message from the cache', async () => { const apiMock = jest.fn(); addApiMock(`mail/v4/messages/${messageID}`, apiMock); initMessage(); await setup(); expect(apiMock).not.toHaveBeenCalled(); }); it('should handle switching of message', async () => { const ID1 = 'ID1'; const ID2 = 'ID2'; const sender1Email = 'sender1@email.com'; const sender2Email = 'sender2@email.com'; addApiKeys(false, sender1Email, []); addApiKeys(false, sender2Email, []); const message1 = { localID: ID1, data: { ID: ID1, Body: 'something', MIMEType: MIME_TYPES.PLAINTEXT, Sender: { Name: '', Address: sender1Email }, } as Message, messageDocument: { initialized: true, plainText: 'Body1' }, }; const message2 = { localID: ID2, data: { ID: ID2, Body: 'something', MIMEType: MIME_TYPES.PLAINTEXT, Sender: { Name: '', Address: sender2Email }, } as Message, messageDocument: { initialized: true, plainText: 'Body2' }, }; store.dispatch(initialize(message1)); store.dispatch(initialize(message2)); const { container, rerender } = await setup({ message: message1.data }); const iframe = await getIframeRootDiv(container); await findByText(iframe, 'Body1'); await rerender({ message: message2.data }); const iframe2 = await getIframeRootDiv(container); await findByText(iframe2, 'Body2'); await rerender({ message: message1.data }); const iframe3 = await getIframeRootDiv(container); await findByText(iframe3, 'Body1'); await rerender({ message: message2.data }); const iframe4 = await getIframeRootDiv(container); await findByText(iframe4, 'Body2'); }); });
3,692
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/tests/Message.test.helpers.tsx
import { MutableRefObject } from 'react'; import { findByTestId, fireEvent, waitFor } from '@testing-library/react'; import { act } from '@testing-library/react'; import loudRejection from 'loud-rejection'; import { MailSettings } from '@proton/shared/lib/interfaces'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import noop from '@proton/utils/noop'; import * as messageDecrypt from '../../../helpers/message/messageDecrypt'; import { mergeMessages } from '../../../helpers/message/messages'; import { render } from '../../../helpers/test/render'; import { MessageState, PartialMessageState } from '../../../logic/messages/messagesTypes'; import { initialize } from '../../../logic/messages/read/messagesReadActions'; import { store } from '../../../logic/store'; import { Breakpoints } from '../../../models/utils'; import MessageView, { MessageViewRef } from '../MessageView'; import { MESSAGE_IFRAME_ROOT_ID } from '../constants'; loudRejection(); export const localID = 'localID'; export const labelID = 'labelID'; export const messageID = 'messageID'; export const addressID = 'AddressID'; export const subject = 'Test subject'; export const body = 'Test body'; export type MessageViewProps = Parameters<typeof MessageView>[0]; export const defaultProps: MessageViewProps = { labelID, conversationMode: false, loading: false, labels: [], message: { ID: messageID, AddressID: addressID } as Message, mailSettings: {} as MailSettings, onBack: jest.fn(), breakpoints: {} as Breakpoints, onFocus: noop, isComposerOpened: false, }; export const setup = async (specificProps: Partial<MessageViewProps> = {}, useMinimalCache = true) => { const props = { ...defaultProps, ...specificProps }; const ref = { current: null } as MutableRefObject<MessageViewRef | null>; const refCallback = (refValue: MessageViewRef) => { ref.current = refValue; }; const renderResult = await render(<MessageView ref={refCallback} {...props} />, useMinimalCache); const open = async () => { jest.spyOn(messageDecrypt, 'decryptMessage'); await act(async () => { ref.current?.expand(); // Wait for message initialization to be finished before continuing await waitFor(() => { const message = store.getState().messages[props.message.ID]; expect(message?.messageDocument?.initialized).toBe(true); }); }); }; const details = async () => { await act(async () => { const button = renderResult.getByTestId('message-show-details'); fireEvent.click(button); }); }; const rerender = async (specificProps: Partial<MessageViewProps> = {}) => { const props = { ...defaultProps, ...specificProps }; await renderResult.rerender(<MessageView ref={refCallback} {...props} />); }; return { ...renderResult, ref, open, details, rerender }; }; export const initMessage = (inputMessage: PartialMessageState = {}) => { const defaultMessage = { localID: messageID, data: { ID: messageID, AddressID: addressID, Subject: 'test', Sender: { Name: 'testName', Address: 'testAddress' }, }, messageDocument: { initialized: true }, verification: {}, } as MessageState; const message = mergeMessages(defaultMessage, inputMessage); store.dispatch(initialize(message)); }; export const getIframeRootDiv = async (element: HTMLElement) => { const iframe = (await findByTestId(element, 'content-iframe')) as HTMLIFrameElement; const iframeContent = iframe.contentDocument?.getElementById(MESSAGE_IFRAME_ROOT_ID) as HTMLElement; return iframeContent; };
3,693
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/message/tests/Message.trackers.test.tsx
import { fireEvent, screen } from '@testing-library/react'; import { MailSettings } from '@proton/shared/lib/interfaces'; import { Attachment, Message } from '@proton/shared/lib/interfaces/mail/Message'; import { IMAGE_PROXY_FLAGS, SHOW_IMAGES } from '@proton/shared/lib/mail/mailSettings'; import { addApiMock } from '@proton/testing/lib/api'; import noop from '@proton/utils/noop'; import { addToCache, minimalCache } from '../../../helpers/test/cache'; import { GeneratedKey, addKeysToAddressKeysCache, generateKeys, releaseCryptoProxy, setupCryptoProxyForTesting, } from '../../../helpers/test/crypto'; import { encryptMessage } from '../../../helpers/test/message'; import { render } from '../../../helpers/test/render'; import { MessageState } from '../../../logic/messages/messagesTypes'; import { initialize } from '../../../logic/messages/read/messagesReadActions'; import { store } from '../../../logic/store'; import { Breakpoints } from '../../../models/utils'; import MessageView from '../MessageView'; import { addressID, labelID, messageID } from './Message.test.helpers'; const trackerName = 'Tracker.com'; const trackerURL = 'https://tracker.com'; const tracker1URL = `${trackerURL}/1`; const tracker2URL = `${trackerURL}/2`; const content = `<div> <img src={${tracker1URL}} /> <img src={${tracker2URL}} /> </div>`; describe('message trackers', () => { const toAddress = 'me@home.net'; const fromAddress = 'someone@somewhere.net'; let toKeys: GeneratedKey; let fromKeys: GeneratedKey; beforeAll(async () => { await setupCryptoProxyForTesting(); toKeys = await generateKeys('me', toAddress); fromKeys = await generateKeys('someone', fromAddress); addKeysToAddressKeysCache(addressID, toKeys); addApiMock('core/v4/keys/all', () => ({ Address: { Keys: [] } })); }); afterAll(async () => { await releaseCryptoProxy(); }); it('should display the correct number of trackers before and after load', async () => { addApiMock(`core/v4/images`, () => { const map = new Map(); map.set('x-pm-tracker-provider', trackerName); return { headers: map }; }); minimalCache(); const mailSettings = { HideRemoteImages: SHOW_IMAGES.HIDE, ImageProxy: IMAGE_PROXY_FLAGS.PROXY }; addToCache('MailSettings', mailSettings); const encryptedBody = await encryptMessage(content, fromKeys, toKeys); const message = { ID: messageID, AddressID: addressID, Subject: 'test', Sender: { Name: 'testName', Address: 'testAddress' }, Attachments: [] as Attachment[], Body: encryptedBody, } as Message; addApiMock(`mail/v4/messages/${messageID}`, () => ({ Message: message, })); store.dispatch(initialize({ data: { ID: messageID, AddressID: addressID } as Message } as MessageState)); const props = { labelID, conversationMode: false, loading: false, labels: [], message: { ID: messageID, AddressID: addressID } as Message, mailSettings: mailSettings as MailSettings, onBack: jest.fn(), breakpoints: {} as Breakpoints, onFocus: noop, isComposerOpened: false, }; await render(<MessageView {...props} />, false); // Check number of trackers before load const trackersNumberBeforeLoad = screen.queryByTestId('privacy:icon-number-of-trackers'); expect(trackersNumberBeforeLoad?.innerHTML).toEqual('2'); const loadButton = screen.getByTestId('remote-content:load'); fireEvent.click(loadButton); // Check number of trackers after load const trackersNumberAfterLoad = screen.queryByTestId('privacy:icon-number-of-trackers'); expect(trackersNumberAfterLoad?.innerHTML).toEqual('2'); }); });
3,694
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/notifications/DecryptionErrorNotification.tsx
import { c } from 'ttag'; import { Href } from '@proton/atoms'; import { SettingsLink } from '@proton/components'; import { APPS } from '@proton/shared/lib/constants'; import { reActivateKeySettingsURL, restoringEncryptedMessagesURL } from '../../constants'; interface Props { keyFound?: boolean; } const DecryptionErrorNotification = ({ keyFound = false }: Props) => { const getNotificationText = () => { const learnMoreLink = ( <Href key="learn-more-link" href={restoringEncryptedMessagesURL} className="text-bold link align-baseline color-inherit" > {c('Action').t`Learn more`} </Href> ); if (keyFound) { const reActivateKeyLink = ( <SettingsLink key="re-activate-link" path={reActivateKeySettingsURL} className="text-bold link align-baseline color-inherit" app={APPS.PROTONMAIL} > { // translator: Link to settings, which is part of the string "If you remember your previous password, you can re-activate the previous key in order to access your messages." c('Error').t`re-activate the previous key` } </SettingsLink> ); // translator: The first variable contains a link to settings displayed as 're-activate the previous key' and the second variable contains a link to the support displayed as 'Learn more' return c('Error') .jt`Your emails cannot be decrypted due to a recent password reset. If you remember your previous password, you can ${reActivateKeyLink} in order to access your messages. ${learnMoreLink}`; } return c('Error').jt`Your emails cannot be decrypted. This may be due to a password reset. ${learnMoreLink}`; }; return <span>{getNotificationText()}</span>; }; export default DecryptionErrorNotification;
3,695
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/notifications/LoadingNotificationContent.tsx
import { useEffect } from 'react'; import { useLoading } from '@proton/hooks'; interface Props { loadingText: string; loadedText: string; promise: Promise<any>; } const LoadingNotificationContent = ({ loadingText, loadedText, promise }: Props) => { const [loading, withLoading] = useLoading(); useEffect(() => { void withLoading(promise); }, [promise]); if (loading) { return <>{loadingText}</>; } return <>{loadedText}</>; }; export default LoadingNotificationContent;
3,696
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/notifications/MoveAllNotificationButton.tsx
import { c } from 'ttag'; import { NotificationButton } from '@proton/components'; interface Props { onMoveAll: () => void; isMessage: boolean; isLabel: boolean; className?: string; disabled?: boolean; } const getText = (isMessage: boolean, isLabel: boolean) => { if (isMessage) { if (isLabel) { return c('Action').t`Move all messages from this label`; } else { return c('Action').t`Move all messages from this folder`; } } else { if (isLabel) { return c('Action').t`Move all conversations from this label`; } else { return c('Action').t`Move all conversations from this folder`; } } }; const MoveAllNotificationButton = ({ onMoveAll, isMessage, isLabel, disabled }: Props) => ( <NotificationButton onClick={onMoveAll} disabled={disabled} className="ml-custom" style={{ '--ml-custom': 'var(--space-3)' }} > {getText(isMessage, isLabel)} </NotificationButton> ); export default MoveAllNotificationButton;
3,697
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/notifications/SavingDraftNotification.tsx
import { Ref, forwardRef, useImperativeHandle, useState } from 'react'; import { c } from 'ttag'; import { InlineLinkButton } from '@proton/components'; enum SavingStep { saving, sent, } interface Props { onDiscard: () => void; } export interface SavingDraftNotificationAction { saved: () => void; } const SavingDraftNotification = ({ onDiscard }: Props, ref: Ref<SavingDraftNotificationAction | undefined>) => { const [step, setStep] = useState(SavingStep.saving); useImperativeHandle(ref, () => ({ saved: () => setStep(SavingStep.sent) })); if (step === SavingStep.sent) { return ( <> <span className="mr-4">{c('Info').t`Draft saved.`}</span> <InlineLinkButton onClick={onDiscard}>{c('Action').t`Discard`}</InlineLinkButton> </> ); } return <>{c('Info').t`Saving draft…`}</>; }; export default forwardRef(SavingDraftNotification);
3,698
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/notifications/SendingMessageNotification.tsx
import { useLayoutEffect, useRef, useState } from 'react'; import { isToday, isTomorrow } from 'date-fns'; import { c } from 'ttag'; import { CircleLoader } from '@proton/atoms'; import useIsMounted from '@proton/hooks/useIsMounted'; import createListeners from '@proton/shared/lib/helpers/listeners'; import { wait } from '@proton/shared/lib/helpers/promise'; import { formatDateToHuman } from '../../helpers/date'; import { isScheduledSendTodayMorning } from '../composer/actions/scheduleSend/helpers'; import UndoNotificationButton from './UndoNotificationButton'; export const createSendingMessageNotificationManager = () => { const listeners = createListeners(); return { ID: -1, setProperties: (promise: Promise<any>, onUndo?: () => Promise<void>) => { listeners.notify(promise, onUndo); }, ...listeners, }; }; export type SendingMessageNotificationManager = ReturnType<typeof createSendingMessageNotificationManager>; interface SendingMessageNotificationProps { manager: SendingMessageNotificationManager; scheduledAt?: number; } enum SendingStep { sending, sent, sentWithUndo, } const SendingMessageNotification = ({ manager, scheduledAt }: SendingMessageNotificationProps) => { const [state, setState] = useState(SendingStep.sending); const onUndoRef = useRef<() => Promise<void> | undefined>(); const isMounted = useIsMounted(); const getScheduledNotification = (scheduledAt: number, onUndo: (() => Promise<void> | undefined) | undefined) => { const scheduleDate = scheduledAt * 1000; const { dateString, formattedTime } = formatDateToHuman(scheduleDate); const getNotificationText = () => { if (isScheduledSendTodayMorning(scheduledAt)) { /* * ${formattedTime} is the date formatted in user's locale (e.g. 11:00 PM) * Full sentence for reference: "Message will be sent in the morning at 11:00 AM" */ return c('Info').t`Message will be sent in the morning at ${formattedTime}`; } if (isToday(scheduleDate)) { /* * ${formattedTime} is the date formatted in user's locale (e.g. 11:00 PM) * Full sentence for reference: "Message will be sent today at 12:30 PM" */ return c('Info').t`Message will be sent today at ${formattedTime}`; } if (isTomorrow(scheduleDate)) { /* * ${formattedTime} is the date formatted in user's locale (e.g. 11:00 PM) * Full sentence for reference: "Message will be sent tomorrow at 12:30 PM" */ return c('Info').t`Message will be sent tomorrow at ${formattedTime}`; } /* * translator: The variables here are the following. * ${dateString} can be "on Tuesday, May 11" for example * ${formattedTime} is the date formatted in user's locale (e.g. 11:00 PM) * Full sentence for reference: "Message will be sent on Tuesday, May 11 at 12:30 PM" */ return c('Info').t`Message will be sent on ${dateString} at ${formattedTime}`; }; const notification = getNotificationText(); return ( <> <span>{notification}</span> {onUndo && <UndoNotificationButton className="mr-4" onUndo={onUndo} />} </> ); }; useLayoutEffect(() => { return manager.subscribe(async (promise: Promise<any>, onUndo: () => Promise<void>) => { onUndoRef.current = onUndo; const { undoTimeout } = await promise; if (isMounted()) { setState(undoTimeout ? SendingStep.sentWithUndo : SendingStep.sent); } if (undoTimeout) { await wait(undoTimeout); if (isMounted()) { setState(SendingStep.sent); } } }); }, []); if (state === SendingStep.sent) { return <>{scheduledAt ? getScheduledNotification(scheduledAt, undefined) : c('Info').t`Message sent`}</>; } const onUndo = onUndoRef.current; if (state === SendingStep.sentWithUndo && onUndo) { if (scheduledAt) { return getScheduledNotification(scheduledAt, onUndo); } return ( <> <span>{c('Info').t`Message sent.`}</span> <UndoNotificationButton onUndo={onUndo} /> </> ); } return ( <> {scheduledAt ? c('Info').t`Scheduling message...` : c('Info').t`Sending message...`} <CircleLoader /> </> ); }; export default SendingMessageNotification;
3,699