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/composer
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/modals/ComposerInnerModals.tsx
import { c } from 'ttag'; import { Href } from '@proton/atoms'; import { Alert, ErrorButton } from '@proton/components'; import { Cancellable } from '@proton/components/hooks/useHandler'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { ATTACHMENT_DISPOSITION } from '@proton/shared/lib/mail/constants'; import { ComposerInnerModalStates } from '../../../hooks/composer/useComposerInnerModals'; import { MessageState } from '../../../logic/messages/messagesTypes'; import { MessageChange } from '../Composer'; import ComposerExpirationModal from './ComposerExpirationModal'; import ComposerInnerModal from './ComposerInnerModal'; import ComposerInsertImageModal from './ComposerInsertImageModal'; import ComposerPasswordModal from './ComposerPasswordModal'; import ComposerScheduleSendModal from './ComposerScheduleSendModal'; interface Props { innerModal: ComposerInnerModalStates; message: MessageState; handleChange: MessageChange; pendingFiles?: File[]; handleCloseInnerModal: () => void; handleScheduleSend: (scheduledAt: number) => void; handleCloseInsertImageModal: () => void; handleAddAttachmentsUpload: ((action: ATTACHMENT_DISPOSITION, files?: File[]) => Promise<void>) & Cancellable; handleDelete: () => void; handleSendAnyway: () => void; handleCancelSend: (error: string) => void; attachmentsFoundKeyword: string; } const ComposerInnerModals = ({ innerModal, message, handleChange, pendingFiles, handleCloseInnerModal, handleScheduleSend, handleCloseInsertImageModal, handleAddAttachmentsUpload, handleDelete, handleSendAnyway, handleCancelSend, attachmentsFoundKeyword, }: Props) => { return ( <> {innerModal === ComposerInnerModalStates.Password && ( <ComposerPasswordModal message={message} onClose={handleCloseInnerModal} onChange={handleChange} /> )} {innerModal === ComposerInnerModalStates.Expiration && ( <ComposerExpirationModal message={message} onClose={handleCloseInnerModal} onChange={handleChange} /> )} {innerModal === ComposerInnerModalStates.ScheduleSend && ( <ComposerScheduleSendModal onClose={handleCloseInnerModal} onSubmit={handleScheduleSend} message={message} /> )} {innerModal === ComposerInnerModalStates.InsertImage && pendingFiles && ( <ComposerInsertImageModal files={pendingFiles} onClose={handleCloseInsertImageModal} onSelect={handleAddAttachmentsUpload} /> )} {innerModal === ComposerInnerModalStates.DeleteDraft && ( <ComposerInnerModal title={c('Title').t`Delete draft`} onCancel={handleCloseInnerModal} onSubmit={handleDelete} submitActions={<ErrorButton type="submit">{c('Action').t`Delete`}</ErrorButton>} > <Alert className="mb-4" type="error">{c('Info') .t`Are you sure you want to permanently delete this draft?`}</Alert> </ComposerInnerModal> )} {innerModal === ComposerInnerModalStates.NoRecipients && ( <ComposerInnerModal title={c('Title').t`Recipient missing`} onCancel={() => handleCancelSend('recipient missing')} onSubmit={() => handleCancelSend('recipient missing')} displayCancel={false} submit={c('Action').t`Got it`} data-testid={'composer:modal:norecipients'} > <p className="text-left m-0">{c('Info').t`Please add at least one recipient.`}</p> </ComposerInnerModal> )} {innerModal === ComposerInnerModalStates.NoSubjects && ( <ComposerInnerModal title={c('Title').t`Subject missing`} onCancel={() => handleCancelSend('subject missing')} onSubmit={handleSendAnyway} submit={c('Action').t`Send anyway`} data-testid={'composer:modal:nosubject'} > <p className="text-left m-0">{c('Info') .t`You have not given your email any subject. Do you want to send the message anyway?`}</p> </ComposerInnerModal> )} {innerModal === ComposerInnerModalStates.NoAttachments && ( <ComposerInnerModal title={c('Title').t`No attachment found`} onCancel={() => handleCancelSend('attachments missing')} onSubmit={handleSendAnyway} submit={c('Action').t`Send anyway`} > <Alert> {c('Info') .t`You wrote “${attachmentsFoundKeyword}”, but no attachment has been added. Do you want to send your message anyway?`} <div> <Href href={getKnowledgeBaseUrl('/attachment-reminders')}>{c('Link').t`Learn more`}</Href> </div> </Alert> </ComposerInnerModal> )} </> ); }; export default ComposerInnerModals;
3,400
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/modals/ComposerInsertImageModal.tsx
import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms'; import { ATTACHMENT_DISPOSITION } from '@proton/shared/lib/mail/constants'; import ComposerInnerModal from './ComposerInnerModal'; interface Props { files: File[]; onSelect: (action: ATTACHMENT_DISPOSITION) => void; onClose: () => void; } const ComposerInsertImageModal = ({ files, onSelect, onClose }: Props) => { const actions = ( <> <Button color="norm" fullWidth onClick={() => onSelect(ATTACHMENT_DISPOSITION.ATTACHMENT)} data-testid="composer:insert-image-attachment" autoFocus > {c('Action').t`Attachment`} </Button> <Button color="norm" fullWidth onClick={() => onSelect(ATTACHMENT_DISPOSITION.INLINE)} data-testid="composer:insert-image-inline" >{c('Action').t`Inline`}</Button> </> ); return ( <ComposerInnerModal title={c('Info').ngettext(msgid`Insert image`, `Insert images`, files.length)} onCancel={onClose} submitActions={actions} > <p className="text-left">{c('Info') .t`You can add it as an attachment or display it inline in your mail body.`}</p> </ComposerInnerModal> ); }; export default ComposerInsertImageModal;
3,401
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/modals/ComposerPasswordModal.tsx
import { addDays, differenceInDays } from 'date-fns'; import { c, msgid } from 'ttag'; import { Href } from '@proton/atoms'; import { useNotifications } from '@proton/components'; import { MAIL_APP_NAME } from '@proton/shared/lib/constants'; import { setBit } from '@proton/shared/lib/helpers/bitset'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { MESSAGE_FLAGS } from '@proton/shared/lib/mail/constants'; import { DEFAULT_EO_EXPIRATION_DAYS } from '../../../constants'; import { useExternalExpiration } from '../../../hooks/composer/useExternalExpiration'; import { updateExpires } from '../../../logic/messages/draft/messagesDraftActions'; import { MessageState } from '../../../logic/messages/messagesTypes'; import { useAppDispatch } from '../../../logic/store'; import { MessageChange } from '../Composer'; import ComposerInnerModal from './ComposerInnerModal'; import PasswordInnerModalForm from './PasswordInnerModalForm'; const getNumberOfExpirationDays = (message?: MessageState) => { return message?.draftFlags?.expiresIn ? differenceInDays(message.draftFlags.expiresIn, new Date()) : 28; }; const getExpirationText = (message?: MessageState) => { const numberOfDays = getNumberOfExpirationDays(message); if (numberOfDays === 0) { return c('Info').t`Your message will expire today.`; } if (numberOfDays === 1) { return c('Info').t`Your message will expire tomorrow.`; } return c('Info').ngettext( msgid`Your message will expire in ${numberOfDays} day.`, `Your message will expire in ${numberOfDays} days.`, numberOfDays ); }; interface Props { message?: MessageState; onClose: () => void; onChange: MessageChange; } const ComposerPasswordModal = ({ message, onClose, onChange }: Props) => { const { password, setPassword, passwordHint, setPasswordHint, validator, onFormSubmit } = useExternalExpiration(message); const { createNotification } = useNotifications(); const dispatch = useAppDispatch(); const isEdition = message?.draftFlags?.expiresIn; const handleSubmit = () => { if (!onFormSubmit()) { return; } if (!isEdition) { const expirationDate = addDays(new Date(), DEFAULT_EO_EXPIRATION_DAYS); onChange( (message) => ({ data: { Flags: setBit(message.data?.Flags, MESSAGE_FLAGS.FLAG_INTERNAL), Password: password, PasswordHint: passwordHint, }, draftFlags: { expiresIn: expirationDate }, }), true ); dispatch(updateExpires({ ID: message?.localID || '', expiresIn: expirationDate })); } else { onChange( (message) => ({ data: { Flags: setBit(message.data?.Flags, MESSAGE_FLAGS.FLAG_INTERNAL), Password: password, PasswordHint: passwordHint, }, }), true ); } createNotification({ text: c('Notification').t`Password has been set successfully` }); onClose(); }; const handleCancel = () => { onClose(); }; // translator : The variable "MAIL_APP_NAME" is the text "Proton Mail". This string is the bold part of the larger string "Send an encrypted, password protected message to a ${boldText} email address." const boldText = <strong key="strong-text">{c('Info').t`non-${MAIL_APP_NAME}`}</strong>; // translator : The variable "boldText" is the text "non-Proton Mail" written in bold const encryptionText = c('Info').jt`Send an encrypted, password protected message to a ${boldText} email address.`; const expirationText = getExpirationText(message); return ( <ComposerInnerModal title={isEdition ? c('Info').t`Edit encryption` : c('Info').t`Encrypt message`} submit={c('Action').t`Set encryption`} onSubmit={handleSubmit} onCancel={handleCancel} > <p className="mt-0 mb-2 color-weak">{encryptionText}</p> <p className="mt-0 mb-4 color-weak"> {expirationText} <br /> <Href href={getKnowledgeBaseUrl('/password-protected-emails')}>{c('Info').t`Learn more`}</Href> </p> <PasswordInnerModalForm password={password} setPassword={setPassword} passwordHint={passwordHint} setPasswordHint={setPasswordHint} validator={validator} /> </ComposerInnerModal> ); }; export default ComposerPasswordModal;
3,402
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/modals/ComposerScheduleSendModal.tsx
import { useEffect, useState } from 'react'; import { addDays, endOfToday, getUnixTime, isToday } from 'date-fns'; import { c, msgid } from 'ttag'; import { Href } from '@proton/atoms/Href'; import { DateInputTwo, InputFieldTwo, TimeInput, generateUID, useUserSettings } from '@proton/components'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { getWeekStartsOn } from '@proton/shared/lib/settings/helper'; import { SCHEDULED_MAX_DATE_DAYS } from '../../../constants'; import { getMinScheduleTime } from '../../../helpers/schedule'; import useFutureTimeDate from '../../../hooks/message/useFutureTimeDate'; import { MessageState } from '../../../logic/messages/messagesTypes'; import { updateScheduled } from '../../../logic/messages/scheduled/scheduledActions'; import { useAppDispatch } from '../../../logic/store'; import ComposerInnerModal from './ComposerInnerModal'; interface Props { message: MessageState; onClose: () => void; onSubmit: (timestamp: number) => void; } const ComposerScheduleSendModal = ({ message, onClose, onSubmit }: Props) => { const dispatch = useAppDispatch(); const [userSettings] = useUserSettings(); const [uid] = useState(generateUID('schedule-send-modal')); const defaultDate = message && message.draftFlags?.scheduledAt ? new Date(message.draftFlags?.scheduledAt * 1000) : addDays(new Date(), 1); if (!message || (message && !message.draftFlags?.scheduledAt)) { defaultDate.setHours(8, 0, 0, 0); } // translator : The variable is the number of days, written in digits const maxDateErrorMessage = c('Error').ngettext( msgid`Choose a date within the next ${SCHEDULED_MAX_DATE_DAYS} day.`, `Choose a date within the next ${SCHEDULED_MAX_DATE_DAYS} days.`, SCHEDULED_MAX_DATE_DAYS ); const { date, time, disabled, handleChangeDate, handleChangeTime, formatDateInput, scheduleDateTime, minDate, maxDate, errorDate, errorTime, } = useFutureTimeDate({ defaultDate, maxDaysAllowed: SCHEDULED_MAX_DATE_DAYS, maxDateErrorMessage, }); useEffect(() => { dispatch(updateScheduled({ ID: message.localID, scheduledAt: getUnixTime(scheduleDateTime) })); }, [scheduleDateTime]); const handleSubmit = () => { onSubmit(getUnixTime(scheduleDateTime)); onClose(); }; const handleCancel = () => { onClose(); }; return ( <ComposerInnerModal title={c('Title').t`Schedule send`} disabled={disabled} submit={c('Action').t`Schedule message`} onSubmit={handleSubmit} onCancel={handleCancel} > <div className="mb-4 flex"> <span data-testid="composer:schedule-send:custom-modal:title">{c('Info') .t`When do you want your message to be sent?`}</span> <Href className="underline inline-block" href={getKnowledgeBaseUrl('/schedule-email-send')}>{c('Link') .t`Learn more`}</Href> </div> <div className="flex gap-2 flex-row flex-nowrap"> <InputFieldTwo as={DateInputTwo} id={`composer-schedule-date-${uid}`} label={c('Label').t`Date`} onChange={handleChangeDate} value={date} min={minDate} weekStartsOn={getWeekStartsOn({ WeekStart: userSettings.WeekStart })} max={maxDate} toFormatter={formatDateInput} preventValueReset error={errorDate} data-testid="composer:schedule-date-input" /> <InputFieldTwo as={TimeInput} id={`composer-schedule-time-${uid}`} label={c('Label').t`Time`} onChange={handleChangeTime} value={time} min={getMinScheduleTime(date)} max={isToday(date) ? endOfToday() : undefined} error={errorTime} data-testid="composer:schedule-time-input" /> </div> </ComposerInnerModal> ); }; export default ComposerScheduleSendModal;
3,403
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/modals/PasswordInnerModal.scss
@import '~@proton/styles/scss/lib'; .password-inner-modal-copy { &-container { margin-block-start: 1.8em; // Magic number only for this case, otherwise impossible to align block-size: rem($default-height-fields); } svg { margin-block: auto; } }
3,404
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/modals/PasswordInnerModalForm.tsx
import { ChangeEvent, useState } from 'react'; import { c } from 'ttag'; import { Copy, Info, InputFieldTwo, PasswordInputTwo, generateUID, useNotifications } from '@proton/components'; import { minLengthValidator, requiredValidator } from '@proton/shared/lib/helpers/formValidators'; import './PasswordInnerModal.scss'; const MIN_PASSWORD_LENGTH = 8; interface Props { password: string; setPassword: (password: string) => void; passwordHint: string; setPasswordHint: (hint: string) => void; validator: (validations: string[]) => string; } const PasswordInnerModalForm = ({ password, setPassword, passwordHint, setPasswordHint, validator }: Props) => { const [uid] = useState(generateUID('password-modal')); const { createNotification } = useNotifications(); const handleChange = (setter: (value: string) => void) => (event: ChangeEvent<HTMLInputElement>) => { setter(event.target.value); }; const passwordLabel = ( <div> <span className="mr-1">{c('Label').t`Password`}</span> <Info className="mb-1" title={c('Info').t`Don't forget to share the password with the recipient`} /> </div> ); const passwordInput = ( <InputFieldTwo id={`composer-password-${uid}`} label={passwordLabel} data-testid="encryption-modal:password-input" value={password} as={PasswordInputTwo} placeholder={c('Placeholder').t`Password`} defaultType="text" onChange={handleChange(setPassword)} error={validator([requiredValidator(password), minLengthValidator(password, MIN_PASSWORD_LENGTH)])} /> ); return ( <> <div className="flex flex-nowrap"> <span className="mr-2 w-full">{passwordInput}</span> <span className="flex-item-noshrink password-inner-modal-copy-container"> <Copy value={password} className=" password-inner-modal-copy" tooltipText={c('Action').t`Copy password to clipboard`} size="medium" onCopy={() => { createNotification({ text: c('Success').t`Password copied to clipboard` }); }} /> </span> </div> <InputFieldTwo id={`composer-password-hint-${uid}`} label={c('Label').t`Password hint`} hint={c('info').t`Optional`} data-testid="encryption-modal:password-hint" value={passwordHint} placeholder={c('Placeholder').t`Hint`} onChange={handleChange(setPasswordHint)} autoComplete="off" /> </> ); }; export default PasswordInnerModalForm;
3,405
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/modals/SendingFromDefaultAddressModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { ModalProps, PrimaryButton, Prompt } from '@proton/components'; interface Props extends ModalProps { email: string; onResolve: () => void; onReject: () => void; } const SendingFromDefaultAddressModal = ({ email, onResolve, onReject, ...rest }: Props) => { return ( <Prompt title={c('Title').t`Sending notice`} buttons={[ <PrimaryButton onClick={onResolve}>{c('Action').t`OK`}</PrimaryButton>, <Button onClick={onReject}>{c('Action').t`Cancel`}</Button>, ]} {...rest} > {c('Info') .t`Sending messages from @pm.me address is a paid feature. Your message will be sent from your default address ${email}`} </Prompt> ); }; export default SendingFromDefaultAddressModal;
3,406
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/modals/SendingOriginalMessageModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { ErrorButton, Prompt } from '@proton/components'; interface Props { onResolve: () => void; onReject: () => void; } const SendingOriginalMessageModal = ({ onResolve, onReject, ...rest }: Props) => { return ( <Prompt title={c('Title').t`Sending original message`} buttons={[ <ErrorButton onClick={onResolve} data-testid="send-original-message:confirm">{c('Action') .t`OK`}</ErrorButton>, <Button onClick={onReject}>{c('Action').t`Close`}</Button>, ]} {...rest} > {c('Info') .t`The original message you are trying to forward / reply to is in the process of being sent. If you continue, you will not be able to undo sending of the original message any longer.`} </Prompt> ); }; export default SendingOriginalMessageModal;
3,407
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/modals
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/modals/InnerModal/InnerModal.scss
@import '~@proton/styles/scss/lib'; $field-container: rem(260) !default; $modal-max-width: rem(700) !default; $modal-breakpoint-width: 52em !default; $breakpoint-low-height-modal: em(500, 16) !default; $modal-max-height: 80% !default; $modal-full-dimension: 98% !default; .inner-modal { position: relative; inline-size: $modal-max-width; max-block-size: $modal-max-height; max-inline-size: $modal-max-width; background: var(--background-norm); color: var(--text-norm); padding: 0; overflow: hidden; border-radius: var(--border-radius-lg); box-shadow: var(--shadow-lifted); animation: anime-inner-modal-in ease 0.15s 1 normal; animation-fill-mode: both; animation-delay: 0.1s; // stupid fix for Safari crazy display bug margin: auto; display: flex; flex-direction: column; cursor: default; &-header { padding-block: rem(30) rem(15); padding-inline: rem(30); flex: 0; flex-shrink: 0; } &-title { font-size: rem(22); line-height: 1.5; margin-block-end: 0; } &-content { display: flex; flex-direction: column; flex: 1 1 auto; overflow: hidden; position: relative; } &-content-inner { position: relative; overflow-x: hidden; overflow-y: auto; flex: 1 1 auto; padding-block: 0; padding-inline: rem(30); background: var(--background-norm) no-repeat; & > p:first-child { margin-block-start: 0; } & > p:last-child { margin-block-end: 0; } } &-footer { padding-block: rem(15) rem(30); padding-inline: rem(30); flex: 0; flex-shrink: 0; [class*='button'] { // only for Safari the ugly min-block-size: rem(34); } // single button on right [class*='button']:only-child { margin-inline-start: auto; } // for vertically displayed buttons &.flex-column { [class*='button'] + [class*='button'] { margin-block-start: 0.5em; } } } &-close { position: absolute; inset-block-start: 0; inset-inline-end: 0; display: flex; flex-wrap: wrap; overflow: hidden; font-size: 1.25em; z-index: 1; } /* overlay covers everything */ &-overlay { position: fixed; inset: 0; background: var(--backdrop-norm); z-index: $layer-modals; animation: anime-inner-modal-overlay-in ease 0.5s 1 normal; } &-overlay--out { animation: anime-inner-modal-overlay-out ease 0.5s 1 normal; animation-fill-mode: forwards; } &-container { position: fixed; inset: 0; display: flex; justify-content: center; flex-direction: column; z-index: $layer-modals; &.is-behind-backdrop { z-index: $layer-modals - 1; } /* for very large inputs in modals, like rich text editor */ .field-container--full { inline-size: calc(100% - var(--label-width, #{$label-width})); @include media('<=#{em(1360, 16)}') { inline-size: $field-container; } @include media('<=#{em(830, 16)}') { inline-size: calc(100% - var(--label-width, #{$label-width})); } @include media('<=small') { inline-size: 100%; } } } .inner-modal--auto { inline-size: auto; } } @keyframes anime-inner-modal-overlay-in { from { opacity: 0; } to { opacity: 1; } } @keyframes anime-inner-modal-overlay-out { from { opacity: 1; } to { opacity: 0; } } @keyframes anime-inner-modal-in { 0% { opacity: 0; transform: scale(0.8); } 100% { opacity: 1; transform: scale(1); } } @include media('height<=#{$breakpoint-low-height-modal}') { .inner-modal { max-block-size: $modal-full-dimension; } .inner-modal-footer { padding-block-end: rem(10); } .inner-modal-header { padding-block-start: rem(10); padding-block-end: rem(5); } } // small viewports @include media('<=#{$modal-breakpoint-width}') { .inner-modal { margin: 1%; min-inline-size: 0; inline-size: 98%; max-inline-size: 98%; max-block-size: 98%; align-self: center; } }
3,408
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/modals
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/modals/InnerModal/InnerModalCloseButton.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Icon } from '@proton/components'; interface InnerModalModalCloseButtonProps { onClose?: () => void; closeTextModal?: string; } const InnerModalModalCloseButton = ({ closeTextModal, onClose }: InnerModalModalCloseButtonProps) => { const closeText = closeTextModal || c('Action').t`Close`; return ( <Button icon shape="ghost" size="small" className="inner-modal-close" title={closeText} onClick={onClose}> <Icon className="inner-modal-close-icon" name="cross-big" alt={closeText} /> </Button> ); }; export default InnerModalModalCloseButton;
3,409
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/modals
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/modals/InnerModal/InnerModalContent.tsx
import { FormEvent, ReactNode } from 'react'; import clsx from '@proton/utils/clsx'; import noop from '@proton/utils/noop'; interface Props { children: ReactNode; className?: string; onSubmit?: (event: FormEvent<HTMLFormElement>) => void; onReset?: (event: FormEvent<HTMLFormElement>) => void; autoComplete?: string; noValidate?: boolean; } const InnerModalContent = ({ children, className = '', onSubmit = noop, onReset = noop, autoComplete = 'off', noValidate = false, ...rest }: Props) => { const handleSubmit = (event: FormEvent<HTMLFormElement>) => { event.preventDefault(); onSubmit(event); }; return ( <form onSubmit={handleSubmit} onReset={onReset} autoComplete={autoComplete} className={clsx(['inner-modal-content', className])} noValidate={noValidate} method="post" {...rest} > {children} </form> ); }; export default InnerModalContent;
3,410
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/modals
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/modals/InnerModal/InnerModalFooter.tsx
import { ComponentPropsWithoutRef, ReactNode } from 'react'; import clsx from '@proton/utils/clsx'; interface Props extends ComponentPropsWithoutRef<'footer'> { children?: ReactNode; isColumn?: boolean; } const InnerModalFooter = ({ children, isColumn, className = clsx([ 'flex flex-nowrap', isColumn ? 'flex-column' : 'flex-justify-space-between flex-align-items-center', ]), ...rest }: Props) => { return ( <footer className={clsx(['inner-modal-footer', className])} {...rest}> {children} </footer> ); }; export default InnerModalFooter;
3,411
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/modals
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/modals/InnerModal/InnerModalHeader.tsx
import { DetailedHTMLProps, HTMLAttributes, ReactNode } from 'react'; import clsx from '@proton/utils/clsx'; import InnerModalModalCloseButton from './InnerModalCloseButton'; import InnerModalTitle from './InnerModalTitle'; interface Props extends Omit<DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>, 'children'> { modalTitleID?: string; children?: ReactNode; onClose?: () => void; displayTitle?: boolean; hasClose?: boolean; closeTextModal?: string; noEllipsis?: boolean; } const InnerModalHeader = ({ children, modalTitleID = 'modalTitle', className, closeTextModal, hasClose = true, onClose, noEllipsis = false, ...rest }: Props) => { return ( <header className={clsx(['inner-modal-header', className])} {...rest}> {hasClose ? <InnerModalModalCloseButton closeTextModal={closeTextModal} onClose={onClose} /> : null} {typeof children === 'string' ? ( <InnerModalTitle id={modalTitleID} className={noEllipsis ? undefined : 'text-ellipsis'}> {children} </InnerModalTitle> ) : ( children )} </header> ); }; export default InnerModalHeader;
3,412
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/modals
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/modals/InnerModal/InnerModalScroll.tsx
import { ReactNode, Ref, forwardRef } from 'react'; import { ScrollShadows } from '@proton/atoms'; import clsx from '@proton/utils/clsx'; interface Props { children: ReactNode; className?: string; } const InnerModalScroll = forwardRef<HTMLDivElement, Props>( ({ children, className = '' }: Props, ref: Ref<HTMLDivElement>) => { return ( <div ref={ref} className={clsx(['inner-modal-content-inner', className])}> <ScrollShadows>{children}</ScrollShadows> </div> ); } ); InnerModalScroll.displayName = 'InnerModalScroll'; export default InnerModalScroll;
3,413
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/modals
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/modals/InnerModal/InnerModalTitle.tsx
import { DetailedHTMLProps, HTMLAttributes, ReactNode } from 'react'; import clsx from '@proton/utils/clsx'; interface Props extends DetailedHTMLProps<HTMLAttributes<HTMLHeadingElement>, HTMLHeadingElement> { id: string; children: ReactNode; } const InnerModalTitle = ({ children, className, ...rest }: Props) => { return ( <h1 className={clsx(['inner-modal-title outline-none', className])} data-focus-trap-fallback="0" tabIndex={-1} {...rest} > {children} </h1> ); }; export default InnerModalTitle;
3,414
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/quickReply/DeleteQuickReplyModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { Alert, ErrorButton, ModalProps, Prompt } from '@proton/components/components'; interface Props extends ModalProps { onDeleteDraft: () => void; } const DeleteQuickReplyModal = ({ onDeleteDraft, ...rest }: Props) => { const { onClose } = rest; const handleDelete = () => { onDeleteDraft(); onClose?.(); }; return ( <Prompt title={c('Title').t`Delete draft`} buttons={[ <ErrorButton onClick={handleDelete}>{c('Action').t`Delete`}</ErrorButton>, <Button onClick={onClose}>{c('Action').t`Cancel`}</Button>, ]} {...rest} > <Alert className="mb-4" type="error">{c('Info') .t`Are you sure you want to permanently delete this draft?`}</Alert> </Prompt> ); }; export default DeleteQuickReplyModal;
3,415
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/quickReply/NoAttachmentsModal.tsx
import { c } from 'ttag'; import { Button, Href } from '@proton/atoms'; import { Alert, ModalProps, PrimaryButton, Prompt } from '@proton/components/components'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; interface Props extends ModalProps { attachmentsFoundKeyword: string; onResolve: () => void; onReject: () => void; } const NoAttachmentsModal = ({ attachmentsFoundKeyword, onResolve, onReject, ...rest }: Props) => { return ( <Prompt title={c('Title').t`No attachment found`} buttons={[ <PrimaryButton onClick={onResolve}>{c('Action').t`Send anyway`}</PrimaryButton>, <Button onClick={onReject}>{c('Action').t`Cancel`}</Button>, ]} {...rest} > <Alert> {c('Info') .t`You wrote “${attachmentsFoundKeyword}”, but no attachment has been added. Do you want to send your message anyway?`} <div> <Href href={getKnowledgeBaseUrl('/attachment-reminders')}>{c('Link').t`Learn more`}</Href> </div> </Alert> </Prompt> ); }; export default NoAttachmentsModal;
3,416
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/quickReply/QuickReply.scss
@import '~@proton/styles/scss/lib'; @import '../../composer/composer'; .quick-reply { &-collapsed { &:hover { border-color: var(--field-hover); } } &-composer { // need to size it, because quick reply does not have dimensions like the composer container block-size: em(135); // plain text case textarea { margin-inline-start: 0.1em; // Focus styles are brought by container with field and textarea classes &:focus-visible { outline: 0; } } } &-wrapper { border-end-start-radius: var(--border-radius-md); border-end-end-radius: var(--border-radius-md); } &-container { padding-inline: 0; padding-block: 0 0.5em; overflow: hidden; // to avoid iframe eating the border-radius :-\ &-dark-style { &, &:hover { &#{&} { // specificity issue ^^ background-color: white; // fix crazy hover bug and needed for dark styles } } } } &-emoji-button { padding: em(9); // to override toolbar-button padding &::after { content: unset; // remove interactive-pseudo styling here } // Specific to dark styles because the emoji button is displayed on top of the Rooster editor (which is white) &-dark-style { &, &:hover, &:focus, &[aria-expanded='true'] { &#{&} { color: var(--text-invert); } } &:hover, &:focus { --interaction-default-hover: rgb(186 190 199 / 0.2); } } } } .is-focused { border-color: var(--field-focus); box-shadow: 0 0 0 #{$focus-ring-size} var(--focus-ring); }
3,417
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/quickReply/QuickReply.tsx
import { Dispatch, SetStateAction, Suspense, lazy, useCallback, useEffect, useRef, useState } from 'react'; import { useDispatch } from 'react-redux'; import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { Editor, EditorActions, Icon, Tooltip, useModalState } from '@proton/components/components'; import { defaultFontStyle } from '@proton/components/components/editor/helpers'; import { useToolbar } from '@proton/components/components/editor/hooks/useToolbar'; import { useModalTwo } from '@proton/components/components/modalTwo/useModalTwo'; import { ErrorBoundary, useTheme } from '@proton/components/containers'; import { useAddresses, useHandler, useUserSettings } from '@proton/components/hooks'; import { MIME_TYPES } from '@proton/shared/lib/constants'; import { DIRECTION } from '@proton/shared/lib/mail/mailSettings'; import clsx from '@proton/utils/clsx'; import useMailModel from 'proton-mail/hooks/useMailModel'; import { MESSAGE_ACTIONS } from '../../../constants'; import { getFromAddress } from '../../../helpers/addresses'; import { insertSignature } from '../../../helpers/message/messageSignature'; import { toText } from '../../../helpers/parserHtml'; import { EditorTypes, useComposerContent } from '../../../hooks/composer/useComposerContent'; import { useGetConversation } from '../../../hooks/conversation/useConversation'; import { useGetAllMessages } from '../../../hooks/message/useMessage'; import { removeQuickReplyFlag } from '../../../logic/messages/draft/messagesDraftActions'; import { MessageState } from '../../../logic/messages/messagesTypes'; import DeleteQuickReplyModal from './DeleteQuickReplyModal'; import NoAttachmentsModal from './NoAttachmentsModal'; import QuickReplyType from './QuickReplyType'; import './QuickReply.scss'; const ToolbarEmojiDropdown = lazy(() => import('@proton/components/components/editor/toolbar/ToolbarEmojiDropdown')); interface Props { newMessageID: string; referenceMessage?: MessageState; onCloseQuickReply: () => void; conversationID?: string; onFocus: () => void; hasFocus: boolean; setHasFocus: Dispatch<SetStateAction<boolean>>; } const QuickReply = ({ newMessageID, referenceMessage, onCloseQuickReply, conversationID, onFocus, hasFocus, setHasFocus, }: Props) => { const [addresses] = useAddresses(); const mailSettings = useMailModel('MailSettings'); const [userSettings] = useUserSettings(); const dispatch = useDispatch(); const quickReplyFrameRef = useRef<HTMLDivElement>(null); const getConversation = useGetConversation(); const getAllMessages = useGetAllMessages(); const onClose = useHandler(onCloseQuickReply); const theme = useTheme(); const [deleteDraftModalProps, setDeleteDraftModalOpen, renderDeleteDraftModal] = useModalState(); const [replyUpdated, setReplyUpdated] = useState(false); const [isEditorInitialized, setIsEditorInitialized] = useState(false); // Indicates that the composer is open but the edited message is not yet ready // Needed to prevent edition while data is not ready const [editorReady, setEditorReady] = useState(false); const editorRef = useRef<EditorActions>(); const handleEditorReady = useCallback((editorActions: EditorActions) => { setEditorReady(true); editorRef.current = editorActions; }, []); const [attachmentsFoundKeyword, setAttachmentsFoundKeyword] = useState(''); const [noAttachmentsModal, showAttachmentsModal] = useModalTwo(NoAttachmentsModal); const handleNoAttachments = async (keyword: string) => { setAttachmentsFoundKeyword(keyword); return showAttachmentsModal({ attachmentsFoundKeyword: attachmentsFoundKeyword, }); }; const { syncedMessage, modelMessage, metadata, rightToLeft, isPlainText, isSending, opening, handleChange, handleChangeContent, handleDeleteDraft, handleDelete, senderVerificationModal, handleExpandComposer, handleSendQuickReply, } = useComposerContent({ type: EditorTypes.quickReply, messageID: newMessageID, onClose, composerFrameRef: quickReplyFrameRef, referenceMessage, replyUpdated, setReplyUpdated, setDeleteDraftModalOpen, onNoAttachments: handleNoAttachments, editorRef, editorReady, }); // Editor (Rooster) needs a white bg on dark themes, but not plaintext const needsDarkStyle = modelMessage.data?.MIMEType === MIME_TYPES.DEFAULT && theme.information.dark; /** * Initialize Rooster (or textarea) content at (and only) startup * Set content and RTL behavior */ useEffect(() => { if (editorRef.current && syncedMessage.messageDocument?.initialized && mailSettings && !isEditorInitialized) { setIsEditorInitialized(true); const defaultAddress = getFromAddress(addresses, '', undefined); const fontStyle = defaultFontStyle(mailSettings); const signature = insertSignature( undefined, defaultAddress?.Signature, MESSAGE_ACTIONS.REPLY_ALL, mailSettings, userSettings, fontStyle ); if (signature) { if (isPlainText) { const plainSignature = toText(signature); handleChangeContent(plainSignature, true, true); } else { handleChangeContent(signature, true, true); } } if (rightToLeft === DIRECTION.RIGHT_TO_LEFT) { editorRef.current?.setTextDirection?.(DIRECTION.RIGHT_TO_LEFT); } setHasFocus(true); } }, [editorRef.current, syncedMessage.messageDocument, isPlainText]); // Prevent shortcuts from outside useEffect(() => { const quickReplyFrame = quickReplyFrameRef?.current; if (!quickReplyFrame) { return; } const handlePreventShortcuts = (e: KeyboardEvent) => { e.stopPropagation(); }; quickReplyFrame.addEventListener('keydown', handlePreventShortcuts); return () => { quickReplyFrame.removeEventListener('keydown', handlePreventShortcuts); }; }, []); // Manage quick reply close when expanding // The composer will remove the draftFlag when opened, and we need to close the message afterwards useEffect(() => { if (!syncedMessage.draftFlags?.isQuickReply && !isSending) { onClose(); } }, [syncedMessage.draftFlags]); // If creating a new QR on the same conversation, close other QR which are not modified const closeUnmodifiedQuickReplies = () => { if (conversationID) { const conversation = getConversation(conversationID); const allMessages = getAllMessages(); const conversationMessagesIDs = conversation?.Messages?.map((message) => message.ID) || []; // We also need to check that the quick reply draft is not being saved const quickReplyMessages = allMessages.filter((message) => message?.draftFlags?.isQuickReply && !message?.draftFlags?.isSaving) || []; const quickReplyMessagesFromSameConversation = quickReplyMessages.filter((message) => { const isFromSameConversation = conversationMessagesIDs.includes(message?.draftFlags?.ParentID || ''); const isCurrentMessage = message?.localID == newMessageID; const isAlreadySaved = message?.data?.ID; return isFromSameConversation && !isCurrentMessage && !isAlreadySaved; }); quickReplyMessagesFromSameConversation.forEach((message) => dispatch(removeQuickReplyFlag(message?.localID || '')) ); } }; // When opening a quick reply, check if the user has other opened. // If so and if they are not modified yet, we can close them since he might have opened them by mistake. useEffect(() => { closeUnmodifiedQuickReplies(); }, []); const canRenderEditor = !!modelMessage.data?.MIMEType; const { openEmojiPickerRef, toolbarConfig, setToolbarConfig, modalLink, modalImage, modalDefaultFont } = useToolbar( {} ); const handleBlurCallback = () => { setHasFocus(false); }; const handleFocusCallback = () => { onFocus(); setHasFocus(true); }; const handleCloseQuickReply = async () => { onClose(); await handleDelete(); }; return ( <div ref={quickReplyFrameRef}> <div className="flex flex-nowrap flex-align-items-center mx-4 mt-4 mb-2"> <QuickReplyType referenceMessage={referenceMessage} modelMessage={modelMessage} onChange={handleChange} editorRef={editorRef} /> <Tooltip title={c('Action').t`Open composer`}> <Button color="weak" shape="ghost" size="small" icon onClick={handleExpandComposer} disabled={isSending} className="mr-2 flex-item-noshrink" > <Icon name="arrows-from-center" alt={c('Action').t`Open composer`} /> </Button> </Tooltip> <Tooltip title={c('Action').t`Close & discard`}> <Button color="weak" shape="ghost" size="small" icon onClick={handleDeleteDraft} disabled={isSending} className="flex-item-noshrink" > <Icon name="cross-big" alt={c('Action').t`Close & discard`} /> </Button> </Tooltip> </div> <div className={clsx([ 'border border-weak quick-reply-container bg-norm relative field textarea rounded-lg flex flex-nowrap flex-column mx-4 mb-4', hasFocus && 'is-focused', needsDarkStyle && 'quick-reply-container-dark-style', ])} onBlur={handleBlurCallback} onFocus={handleFocusCallback} data-shortcut-target="quick-reply-container" > <div className="composer-body-container quick-reply-composer mb-2"> {canRenderEditor && ( <Editor onChange={handleChangeContent} onReady={handleEditorReady} metadata={metadata} disabled={isSending || opening} mailSettings={mailSettings} isPlainText={isPlainText} openEmojiPickerRef={openEmojiPickerRef} toolbarConfig={toolbarConfig} setToolbarConfig={setToolbarConfig} modalLink={modalLink} modalImage={modalImage} modalDefaultFont={modalDefaultFont} hasToolbar={false} onFocus={handleFocusCallback} hasDropzone={false} /> )} </div> <div className="quick-reply-buttons absolute bottom right mb-2 mr-2 flex"> {toolbarConfig && !metadata.isPlainText && ( <ErrorBoundary component={() => null}> <Suspense fallback={null}> <ToolbarEmojiDropdown className={clsx([ 'button button-for-icon quick-reply-emoji-button ml-1', needsDarkStyle && 'quick-reply-emoji-button-dark-style', ])} onInsert={toolbarConfig.emoji.insert} openRef={openEmojiPickerRef} /> </Suspense> </ErrorBoundary> )} <Tooltip title={c('loc_nightly_Action').t`Send quick reply`}> <Button color="norm" icon disabled={!replyUpdated} onClick={handleSendQuickReply} loading={isSending} className="ml-2" data-testid="quick-reply-send-button" > <Icon name="paper-plane-horizontal" alt={c('loc_nightly_Action').t`Send quick reply`} /> </Button> </Tooltip> </div> </div> {renderDeleteDraftModal && ( <DeleteQuickReplyModal onDeleteDraft={handleCloseQuickReply} {...deleteDraftModalProps} /> )} {noAttachmentsModal} {senderVerificationModal} </div> ); }; export default QuickReply;
3,418
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/quickReply/QuickReplyContainer.tsx
import { Dispatch, KeyboardEvent, SetStateAction, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { Icon } from '@proton/components/components'; import { useAddresses } from '@proton/components/hooks'; import { MESSAGE_ACTIONS } from '../../../constants'; import { getReplyRecipientListAsString } from '../../../helpers/message/messageRecipients'; import { useContactsMap } from '../../../hooks/contact/useContacts'; import { useMessage } from '../../../hooks/message/useMessage'; import { useDraft } from '../../../hooks/useDraft'; import QuickReply from './QuickReply'; import './QuickReply.scss'; interface Props { referenceMessageID: string; conversationID?: string; conversationIndex?: number; onOpenQuickReply?: (index?: number) => void; onFocus: () => void; hasFocus: boolean; setHasFocus: Dispatch<SetStateAction<boolean>>; } const QuickReplyContainer = ({ referenceMessageID, conversationID, conversationIndex, onOpenQuickReply, onFocus, hasFocus, setHasFocus, }: Props) => { const [addresses] = useAddresses(); const contactEmailsMap = useContactsMap(); const { createDraft } = useDraft(); const [newMessageID, setNewMessageID] = useState<string>(); const { message: referenceMessage } = useMessage(referenceMessageID); const isReferenceMessageInitialized = referenceMessage?.messageDocument?.initialized; const handleEdit = async () => { const newMessageID = await createDraft(MESSAGE_ACTIONS.REPLY, referenceMessage, true); setNewMessageID(newMessageID); onOpenQuickReply?.(conversationIndex); }; const handleCloseQuickReply = () => { setNewMessageID(undefined); }; const handleOpenFromKeydown = (e: KeyboardEvent) => { if (e.key === 'Enter') { void handleEdit(); } }; const recipientsAsString = referenceMessage ? getReplyRecipientListAsString(referenceMessage, MESSAGE_ACTIONS.REPLY, addresses, contactEmailsMap) : ''; /* * translator: The variable contains the recipients list of the quick reply * The list can contain the name of the contact of the address if the contact has no name * Full sentence for reference: "Quick reply to Michael Scott, dwight.schrutte@pm.me" */ const replyToString = isReferenceMessageInitialized ? c('loc_nightly_Info').t`Quick reply to ${recipientsAsString}` : c('loc_nightly_Info').t`Quick reply`; return ( <div className="quick-reply-wrapper bg-norm color-norm pt-3 pb-4"> {!newMessageID ? ( <div className="flex flex-nowrap flex-align-items-center border border-weak rounded-lg color-weak mx-4 px-2 py-1 cursor-pointer quick-reply-collapsed relative"> <Icon className="mr-2 flex-item-noshrink" name="arrow-up-and-left-big" aria-hidden="true" /> <button type="button" className="flex-item-fluid text-ellipsis text-left increase-click-surface" onClick={handleEdit} disabled={!isReferenceMessageInitialized} onKeyDown={handleOpenFromKeydown} tabIndex={0} data-testid="quick-reply-container-button" > {replyToString} </button> <Button className="flex-item-noshrink" aria-hidden="true" color="weak" shape="outline" size="small" icon disabled > <Icon name="paper-plane-horizontal" alt={c('loc_nightly_action').t`Send quick reply`} /> </Button> </div> ) : ( <QuickReply newMessageID={newMessageID} referenceMessage={referenceMessage} onCloseQuickReply={handleCloseQuickReply} conversationID={conversationID} onFocus={onFocus} hasFocus={hasFocus} setHasFocus={setHasFocus} /> )} </div> ); }; export default QuickReplyContainer;
3,419
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/quickReply/QuickReplyType.tsx
import React, { MutableRefObject, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { DropdownMenu, DropdownMenuButton, EditorActions, Icon, SimpleDropdown } from '@proton/components/components'; import { useAddresses } from '@proton/components/hooks'; import { MESSAGE_ACTIONS } from '../../../constants'; import { getRecipients, getReplyRecipientListAsString } from '../../../helpers/message/messageRecipients'; import { useContactsMap } from '../../../hooks/contact/useContacts'; import { MessageState } from '../../../logic/messages/messagesTypes'; import { MessageChange } from '../Composer'; const { REPLY, REPLY_ALL } = MESSAGE_ACTIONS; interface Props { referenceMessage?: MessageState; modelMessage: MessageState; onChange: MessageChange; editorRef: MutableRefObject<EditorActions | undefined>; } const QuickReplyType = ({ referenceMessage, modelMessage, onChange, editorRef }: Props) => { const [addresses] = useAddresses(); const contactEmailsMap = useContactsMap(); const [replyType, setReplyType] = useState<MESSAGE_ACTIONS>(modelMessage.draftFlags?.action || REPLY); const handleChangeReplyType = (newReplyType: MESSAGE_ACTIONS) => { if (replyType === newReplyType || !referenceMessage) { return; } const { ToList, CCList, BCCList } = getRecipients(referenceMessage, newReplyType, addresses); onChange({ data: { ToList, CCList, BCCList } }); setReplyType(newReplyType); editorRef?.current?.focus(); }; const recipientsAsString = referenceMessage ? getReplyRecipientListAsString(referenceMessage, replyType, addresses, contactEmailsMap) : ''; /* * translator: The variable contains the recipients list of the quick reply * The list can contain the name of the contact of the address if the contact has no name * Full sentence for reference: "Quick reply to Michael Scott, dwight.schrutte@pm.me" */ const replyToString = c('loc_nightly_Info').t`Quick reply to ${recipientsAsString}`; const iconName = replyType === REPLY ? 'arrow-up-and-left-big' : 'arrows-up-and-left-big'; return ( <> <SimpleDropdown as={Button} shape="ghost" type="button" hasCaret className="flex mr-2 p-2 color-weak" content={ <Icon className="flex-item-noshrink mr-custom" style={{ '--mr-custom': 'calc(var(--space-2) * -1)' }} name={iconName} /> } data-testid="quick-reply-type-dropdown" > <DropdownMenu> <DropdownMenuButton className="flex flex-align-items-center text-left" onClick={() => handleChangeReplyType(REPLY)} data-testid="quick-reply-type-dropdown-reply-button" > <Icon name="arrow-up-and-left-big" className="mr-2" /> {c('Action').t`Reply`} </DropdownMenuButton> <DropdownMenuButton className="flex flex-align-items-center text-left" onClick={() => handleChangeReplyType(REPLY_ALL)} data-testid="quick-reply-type-dropdown-reply-all-button" > <Icon name="arrows-up-and-left-big" className="mr-2" /> {c('Action').t`Reply all`} </DropdownMenuButton> </DropdownMenu> </SimpleDropdown> <div className="flex-item-fluid text-ellipsis" aria-level={2} role="heading" title={replyToString} data-testid="recipients-list-string" > {replyToString} </div> </> ); }; export default QuickReplyType;
3,420
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/quickReply
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/quickReply/tests/QuickReply.compose.test.tsx
import { GeneratedKey, clearAll, generateKeys, releaseCryptoProxy, removeLineBreaks, setFeatureFlags, setupCryptoProxyForTesting, } from '../../../../helpers/test/helper'; import { messageID } from '../../../message/tests/Message.test.helpers'; import { data, fromFields, recipients } from './QuickReply.test.data'; import { getStateMessageFromParentID, setupQuickReplyTests } from './QuickReply.test.helpers'; jest.setTimeout(20000); describe('Quick reply - Compose', () => { let meKeys: GeneratedKey; beforeAll(async () => { await setupCryptoProxyForTesting(); meKeys = await generateKeys('me', fromFields.meAddress); }); afterAll(async () => { await releaseCryptoProxy(); }); beforeEach(() => { setFeatureFlags('QuickReply', true); }); afterEach(() => { clearAll(); }); it('should open a plaintext quick reply and be able to modify it', async () => { // Setup test const { openQuickReply, updateQuickReplyContent, sendQuickReply, getPlainTextEditor, expectedDefaultPlainTextContent, createCall, sendCall, } = await setupQuickReplyTests({ meKeys, isPlainText: true }); await openQuickReply(); const plainTextEditor = await getPlainTextEditor(); /** * Initialisation check */ // Plaintext editor should contain only the signature by default in QR // Because we hide the reply expect(plainTextEditor?.value.trim()).toEqual(data.protonSignature); // However, the state should contain the whole message (message + sig + blockquotes content) const messageFromState = getStateMessageFromParentID(messageID); expect(removeLineBreaks(messageFromState?.messageDocument?.plainText || '')).toEqual( removeLineBreaks(expectedDefaultPlainTextContent) ); // Sender and Recipients are correct expect(messageFromState?.data?.Sender.Address).toEqual(fromFields.meAddress); expect(messageFromState?.data?.ToList).toEqual([recipients.fromRecipient]); // Auto-save has not been called yet expect(createCall).not.toHaveBeenCalled(); /** * Check after making a change in the editor * After passing the whole composer logic, we still don't have the reply added to the content */ const newContent = 'Adding content'; const contentChange = `${newContent} ${data.protonSignature}`; // Type something in the editor await updateQuickReplyContent(contentChange); // Content in the editor is the one expected expect(removeLineBreaks(plainTextEditor?.value || '')).toEqual(removeLineBreaks(contentChange)); // Content in the state is the one expected const messageFromStateAfterUpdate = getStateMessageFromParentID(messageID); const expectedUpdatedContent = `${newContent} ${expectedDefaultPlainTextContent}`; expect(removeLineBreaks(messageFromStateAfterUpdate?.messageDocument?.plainText || '')).toEqual( removeLineBreaks(expectedUpdatedContent) ); // Auto-save has been called expect(createCall).toHaveBeenCalled(); /** * Send the quick reply */ await sendQuickReply(); expect(sendCall).toHaveBeenCalled(); const sendRequest = (sendCall.mock.calls[0] as any[])[0]; expect(sendRequest.method).toBe('post'); }); it('should open an HTML quick reply and be able to modify it', async () => { const referenceMessageContent = 'Reference message content'; const { openQuickReply, updateQuickReplyContent, getRoosterEditor, sendQuickReply, createCall, sendCall } = await setupQuickReplyTests({ meKeys, referenceMessageBody: `<div>${referenceMessageContent}<br><div>`, }); await openQuickReply(); const roosterEditor = await getRoosterEditor(); const messageFromState = getStateMessageFromParentID(messageID); /** * Initialisation check */ // Editor should contain only the signature by default in QR // Because we hide the reply let protonSignature; let protonBlockquotes; if (roosterEditor) { protonSignature = roosterEditor.innerHTML.includes('Sent with'); protonBlockquotes = roosterEditor.innerHTML.includes(referenceMessageContent); } // Editor // Signature is found in the editor expect(protonSignature).toBeTruthy(); // Blockquotes are not present in the editor expect(protonBlockquotes).toBeFalsy(); // Redux state // Signature is found in the state const messageInnerHTML = messageFromState?.messageDocument?.document?.innerHTML || ''; expect(messageInnerHTML.includes('Sent with')).toBeTruthy(); // Blockquotes are present in the state expect(messageInnerHTML.includes(referenceMessageContent)).toBeTruthy(); // Auto-save has not been called yet expect(createCall).not.toHaveBeenCalled(); /** * Check after making a change in the editor * After passing the whole composer logic, we still don't have the reply added to the content */ const newContent = 'Adding content'; // Type something in the editor await updateQuickReplyContent(newContent); const messageFromStateAfterUpdate = getStateMessageFromParentID(messageID); let protonContentAfterUpdate; let protonSignatureAfterUpdate; let protonBlockquotesAfterUpdate; if (roosterEditor) { protonContentAfterUpdate = roosterEditor.innerHTML.includes(newContent); protonSignatureAfterUpdate = roosterEditor.innerHTML.includes('Sent with'); protonBlockquotesAfterUpdate = roosterEditor.innerHTML.includes(referenceMessageContent); } // Editor // New content is found in the editor expect(protonContentAfterUpdate).toBeTruthy(); // Signature is found in the editor expect(protonSignatureAfterUpdate).toBeTruthy(); // Blockquotes are not present in the editor expect(protonBlockquotesAfterUpdate).toBeFalsy(); // Redux state const messageInnerHTMLAfterUpdate = messageFromStateAfterUpdate?.messageDocument?.document?.innerHTML || ''; // New content is found in the state expect(messageInnerHTMLAfterUpdate.includes(newContent)).toBeTruthy(); // Signature is found in the state expect(messageInnerHTMLAfterUpdate.includes('Sent with')).toBeTruthy(); // Blockquotes are present in the state expect(messageInnerHTMLAfterUpdate.includes(referenceMessageContent)).toBeTruthy(); // Auto-save has been called expect(createCall).toHaveBeenCalled(); /** * Send the quick reply */ await sendQuickReply(); await expect(sendCall).toHaveBeenCalled(); const sendRequest = (sendCall.mock.calls[0] as any[])[0]; expect(sendRequest.method).toBe('post'); }); });
3,421
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/quickReply
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/quickReply/tests/QuickReply.replyType.test.tsx
import { MESSAGE_ACTIONS } from '../../../../constants'; import { GeneratedKey, clearAll, generateKeys, releaseCryptoProxy, setFeatureFlags, setupCryptoProxyForTesting, } from '../../../../helpers/test/helper'; import { messageID } from '../../../message/tests/Message.test.helpers'; import { data, fromFields, recipients } from './QuickReply.test.data'; import { getStateMessageFromParentID, setupQuickReplyTests } from './QuickReply.test.helpers'; jest.setTimeout(20000); describe('Quick reply - Reply type', function () { beforeEach(() => { setFeatureFlags('QuickReply', true); }); afterEach(() => { clearAll(); }); let meKeys: GeneratedKey; beforeAll(async () => { await setupCryptoProxyForTesting(); meKeys = await generateKeys('me', fromFields.meAddress); }); afterAll(async () => { await releaseCryptoProxy(); }); it('should be possible to switch the quick reply type when user received a message', async () => { // Setup test const { openQuickReply, updateReplyType, getRecipientList, createCall, updateCall } = await setupQuickReplyTests({ meKeys, isPlainText: true, }); await openQuickReply(); /** * Initialisation check */ const messageFromState = getStateMessageFromParentID(messageID); // List is the one expected on the UI const expectedList = `${data.quickReplyRecipientsStart} ${fromFields.fromName}`; const recipientList = await getRecipientList(); expect(recipientList).toEqual(expectedList); // List is the one expected in the state expect(messageFromState?.data?.ToList).toEqual([recipients.fromRecipient]); expect(messageFromState?.data?.CCList).toEqual([]); expect(messageFromState?.data?.BCCList).toEqual([]); // Auto-save has not been called yet expect(createCall).not.toHaveBeenCalled(); /** * Switch to reply all */ await updateReplyType(MESSAGE_ACTIONS.REPLY_ALL, true); const messageFromStateAfterUpdate1 = getStateMessageFromParentID(messageID); const expectedListAfterUpdate1 = `${data.quickReplyRecipientsStart} ${fromFields.fromName}, ${fromFields.toName}, ${fromFields.ccName}`; const recipientListAfterUpdate1 = await getRecipientList(); expect(recipientListAfterUpdate1).toEqual(expectedListAfterUpdate1); // List is the one expected in the state expect(messageFromStateAfterUpdate1?.data?.ToList).toEqual([recipients.fromRecipient]); expect(messageFromStateAfterUpdate1?.data?.CCList).toEqual([recipients.toRecipient, recipients.ccRecipient]); expect(messageFromStateAfterUpdate1?.data?.BCCList).toEqual([]); // Auto-save has been called expect(createCall).toHaveBeenCalled(); /** * Switch back to reply */ await updateReplyType(MESSAGE_ACTIONS.REPLY); const messageFromStateAfterUpdate2 = getStateMessageFromParentID(messageID); expect(recipientList).toEqual(expectedList); // List is the one expected in the state expect(messageFromStateAfterUpdate2?.data?.ToList).toEqual([recipients.fromRecipient]); expect(messageFromStateAfterUpdate2?.data?.CCList).toEqual([]); expect(messageFromStateAfterUpdate2?.data?.BCCList).toEqual([]); // Auto-save update has been called expect(updateCall).toHaveBeenCalled(); }); it('should be possible to switch the quick reply type when user sent a message', async () => { // Setup test const { openQuickReply, updateReplyType, getRecipientList, createCall, updateCall } = await setupQuickReplyTests({ meKeys, isPlainText: true, isSender: true, }); await openQuickReply(); /** * Initialisation check */ const messageFromState = getStateMessageFromParentID(messageID); // List is the one expected on the UI const expectedList = `${data.quickReplyRecipientsStart} ${fromFields.fromName}, ${fromFields.toName}`; const recipientList = await getRecipientList(); expect(recipientList).toEqual(expectedList); // List is the one expected in the state expect(messageFromState?.data?.ToList).toEqual([recipients.fromRecipient, recipients.toRecipient]); expect(messageFromState?.data?.CCList).toEqual([]); expect(messageFromState?.data?.BCCList).toEqual([]); // Auto-save has not been called yet expect(createCall).not.toHaveBeenCalled(); /** * Switch to reply all */ await updateReplyType(MESSAGE_ACTIONS.REPLY_ALL, true); const messageFromStateAfterUpdate1 = getStateMessageFromParentID(messageID); const expectedListAfterUpdate1 = `${data.quickReplyRecipientsStart} ${fromFields.fromName}, ${fromFields.toName}, ${fromFields.ccName}, ${fromFields.bccName}`; const recipientListAfterUpdate1 = await getRecipientList(); expect(recipientListAfterUpdate1).toEqual(expectedListAfterUpdate1); // List is the one expected in the state expect(messageFromStateAfterUpdate1?.data?.ToList).toEqual([recipients.fromRecipient, recipients.toRecipient]); expect(messageFromStateAfterUpdate1?.data?.CCList).toEqual([recipients.ccRecipient]); expect(messageFromStateAfterUpdate1?.data?.BCCList).toEqual([recipients.bccRecipient]); // Auto-save has been called expect(createCall).toHaveBeenCalled(); /** * Switch back to reply */ await updateReplyType(MESSAGE_ACTIONS.REPLY); const messageFromStateAfterUpdate2 = getStateMessageFromParentID(messageID); expect(recipientList).toEqual(expectedList); // List is the one expected in the state expect(messageFromStateAfterUpdate2?.data?.ToList).toEqual([recipients.fromRecipient, recipients.toRecipient]); expect(messageFromState?.data?.CCList).toEqual([]); expect(messageFromState?.data?.BCCList).toEqual([]); // Auto-save update has been called expect(updateCall).toHaveBeenCalled(); }); });
3,422
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/quickReply
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/quickReply/tests/QuickReply.test.data.ts
import { MIME_TYPES } from '@proton/shared/lib/constants'; import { Recipient } from '@proton/shared/lib/interfaces'; import { Attachment, Message } from '@proton/shared/lib/interfaces/mail/Message'; import { formatFullDate } from '../../../../helpers/date'; import { createDocument } from '../../../../helpers/test/message'; import { MessageDecryption } from '../../../../logic/messages/messagesTypes'; import { addressID, messageID, subject } from '../../../message/tests/Message.test.helpers'; export const fromFields = { fromAddress: 'from@protonmail.com', fromName: 'From', meAddress: 'me@protonmail.com', meName: 'Me', toAddress: 'to@protonmail.com', toName: 'To', ccAddress: 'cc@protonmail.com', ccName: 'CC', bccAddress: 'bcc@protonmail.com', bccName: 'BCC', }; export const recipients: Record<string, Recipient> = { fromRecipient: { Name: fromFields.fromName, Address: fromFields.fromAddress, }, meRecipient: { Name: fromFields.meName, Address: fromFields.meAddress }, toRecipient: { Name: fromFields.toName, Address: fromFields.toAddress }, ccRecipient: { Name: fromFields.ccName, Address: fromFields.ccAddress }, bccRecipient: { Name: fromFields.bccName, Address: fromFields.bccAddress }, }; export const data = { protonSignature: 'Sent with Proton Mail secure email.', defaultReferenceMessageBody: 'Reference Message Body', quickReplyRecipientsStart: 'Quick reply to', quickReplyMessageID: 'quick-reply-message-id', }; export const getMessage = (isSender: boolean, isPlainText: boolean, referenceMessageBody: string) => ({ localID: messageID, data: { ID: messageID, AddressID: addressID, Subject: subject, Sender: isSender ? recipients.meRecipient : recipients.fromRecipient, ReplyTos: isSender ? [recipients.meRecipient] : [recipients.fromRecipient], ToList: isSender ? [recipients.fromRecipient, recipients.toRecipient] : [recipients.meRecipient, recipients.toRecipient], CCList: [recipients.ccRecipient], BCCList: [recipients.bccRecipient], MIMEType: isPlainText ? MIME_TYPES.PLAINTEXT : MIME_TYPES.DEFAULT, Attachments: [] as Attachment[], Flags: isSender ? 2 : 1, Time: Date.now() / 1000, } as Message, decryption: { decryptedBody: isPlainText ? referenceMessageBody : createDocument(referenceMessageBody), } as MessageDecryption, messageDocument: { initialized: true, plainText: isPlainText ? referenceMessageBody : undefined, document: isPlainText ? undefined : createDocument(referenceMessageBody), }, }); export const getExpectedDefaultPlainTextContent = (referenceMessageBody: string) => { const date = formatFullDate(new Date()); return `Sent with Proton Mail secure email. On ${date}, ${fromFields.fromName} <${fromFields.fromAddress}> wrote: > ${referenceMessageBody}`; };
3,423
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/quickReply
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/quickReply/tests/QuickReply.test.helpers.tsx
import { act, findByTestId, fireEvent, waitFor } from '@testing-library/react'; import { ROOSTER_EDITOR_ID } from '@proton/components/components/editor/constants'; import { MIME_TYPES } from '@proton/shared/lib/constants'; import { wait } from '@proton/shared/lib/helpers/promise'; import { MailSettings } from '@proton/shared/lib/interfaces'; import { PM_SIGNATURE } from '@proton/shared/lib/mail/mailSettings'; import { MESSAGE_ACTIONS } from '../../../../constants'; import { addApiMock } from '../../../../helpers/test/api'; import { addToCache, minimalCache } from '../../../../helpers/test/cache'; import { addApiKeys, addKeysToAddressKeysCache } from '../../../../helpers/test/crypto'; import { getDropdown } from '../../../../helpers/test/helper'; import { initialize } from '../../../../logic/messages/read/messagesReadActions'; import { store } from '../../../../logic/store'; import { addressID, setup } from '../../../message/tests/Message.test.helpers'; import { data, fromFields, getExpectedDefaultPlainTextContent, getMessage } from './QuickReply.test.data'; export const getStateMessageFromParentID = (parentMessageID: string) => { const messagesFromCache = store.getState().messages; // search for message ID of message from parentID (The QR generated) const foundMessageID = Object.keys(messagesFromCache).find((id) => { return messagesFromCache[id]?.draftFlags?.ParentID === parentMessageID; }); return foundMessageID ? messagesFromCache[foundMessageID] : undefined; }; interface QuickReplyTestConfig { meKeys: any; referenceMessageBody?: string; isPlainText?: boolean; isSender?: boolean; } export const setupQuickReplyTests = async ({ meKeys, referenceMessageBody = data.defaultReferenceMessageBody, isPlainText, isSender, }: QuickReplyTestConfig) => { minimalCache(); addToCache('MailSettings', { PMSignature: PM_SIGNATURE.ENABLED, DraftMIMEType: MIME_TYPES.DEFAULT, } as MailSettings); // Need to have the Proton signature by default in the QR addToCache('Addresses', [ { ID: addressID, Email: fromFields.meAddress, Receive: 1, Status: 1, Send: 1, }, ]); addKeysToAddressKeysCache(addressID, meKeys); addApiKeys(false, fromFields.fromAddress, []); addApiKeys(false, fromFields.toAddress, []); // Reference message const message = getMessage(!!isSender, !!isPlainText, referenceMessageBody); store.dispatch(initialize(message)); const expectedDefaultPlainTextContent = getExpectedDefaultPlainTextContent(referenceMessageBody); const container = await setup({ conversationMode: true, message: message.data }, false); const createCall = jest.fn((message) => { return Promise.resolve({ Message: { ID: data.quickReplyMessageID, ...message.data.Message, }, }); }); const updateCall = jest.fn((message) => { return Promise.resolve(message.data); }); const sendCall = jest.fn((message) => { return Promise.resolve({ Sent: { ID: data.quickReplyMessageID, ...message.data } }); }); addApiMock(`mail/v4/messages`, createCall, 'post'); addApiMock(`mail/v4/messages/${data.quickReplyMessageID}`, updateCall, 'put'); addApiMock(`mail/v4/messages/${data.quickReplyMessageID}`, sendCall, 'post'); const getPlainTextEditor = async () => { return (await container.findByTestId('editor-textarea')) as HTMLTextAreaElement; }; const getRoosterEditor = async () => { const iframe = (await container.findByTestId('rooster-iframe')) as HTMLIFrameElement; return iframe.contentDocument?.getElementById(ROOSTER_EDITOR_ID); }; const getRecipientList = async () => { const recipientListContainer = await container.findByTestId('recipients-list-string'); return recipientListContainer.innerHTML; }; const waitForSpy = (spy: jest.Mock<Promise<unknown>, [message: any]>) => waitFor( () => { expect(spy).toHaveBeenCalled(); }, { timeout: 10000 } ); const updateReplyType = async (type: MESSAGE_ACTIONS, isTriggeringCreate = false) => { const quickReplyTypeDropdown = await container.findByTestId('quick-reply-type-dropdown'); // Open the dropdown fireEvent.click(quickReplyTypeDropdown); const dropdown = await getDropdown(); const quickReplyTypeReplyButton = await findByTestId(dropdown, 'quick-reply-type-dropdown-reply-button'); const quickReplyTypeReplyAllButton = await findByTestId(dropdown, 'quick-reply-type-dropdown-reply-all-button'); // Click on the button if (type === MESSAGE_ACTIONS.REPLY) { await act(async () => { fireEvent.click(quickReplyTypeReplyButton); await wait(3000); if (isTriggeringCreate) { await waitForSpy(createCall); } else { await waitForSpy(updateCall); } }); } else if (MESSAGE_ACTIONS.REPLY_ALL) { await act(async () => { fireEvent.click(quickReplyTypeReplyAllButton); await wait(3000); if (isTriggeringCreate) { await waitForSpy(createCall); } else { await waitForSpy(updateCall); } }); } }; const openQuickReply = async () => { await container.open(); const quickReplyContainerButton = await container.findByTestId('quick-reply-container-button'); // Open quick reply await act(async () => { fireEvent.click(quickReplyContainerButton); }); }; const updateQuickReplyContent = async (newContent: string) => { if (isPlainText) { const plainTextEditor = await getPlainTextEditor(); if (plainTextEditor) { await act(async () => { fireEvent.change(plainTextEditor, { target: { value: newContent } }); await wait(3000); await waitForSpy(createCall); }); } } else { const roosterEditor = (await getRoosterEditor()) as HTMLElement; await act(async () => { // fireEvent.input will trigger an update inside the editor, but we need to add our content in it // The first thing to do is add content in the editor by hand // Then triggering input event will trigger the onChange in the composer, which will update the state etc.... // I'm totally cheating but the goal is only to check that the editor will receive new content such as the state roosterEditor.innerHTML = `${newContent}${roosterEditor.innerHTML}`; fireEvent.input(roosterEditor); await wait(3000); await waitForSpy(createCall); }); } }; const sendQuickReply = async () => { const sendButton = await container.findByTestId('quick-reply-send-button'); await act(async () => { fireEvent.click(sendButton); await waitForSpy(sendCall); }); }; return { container, getPlainTextEditor, getRoosterEditor, createCall, updateCall, sendCall, openQuickReply, updateQuickReplyContent, sendQuickReply, expectedDefaultPlainTextContent, getRecipientList, updateReplyType, waitForSpy, }; };
3,424
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/tests/Composer.attachments.test.tsx
import { fireEvent, getByTitle, waitFor } from '@testing-library/react'; import { act } from '@testing-library/react'; import loudRejection from 'loud-rejection'; import { MIME_TYPES } from '@proton/shared/lib/constants'; import { Address, Key } from '@proton/shared/lib/interfaces'; import { arrayToBase64 } from '../../../helpers/base64'; import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../helpers/test/crypto'; import { GeneratedKey, addAddressToCache, addApiKeys, addApiMock, addApiResolver, addKeysToAddressKeysCache, clearAll, createAttachment, createDocument, decryptSessionKey, generateKeys, getDropdown, minimalCache, parseFormData, render, tick, waitForNoNotification, waitForNotification, } from '../../../helpers/test/helper'; import { store } from '../../../logic/store'; import Composer from '../Composer'; import { ID, prepareMessage, props, toAddress } from './Composer.test.helpers'; loudRejection(); jest.setTimeout(20000); describe('Composer attachments', () => { let address1Keys: GeneratedKey; let address2Keys: GeneratedKey; const address1 = { ID: 'AddressID1', Email: 'email1@home.net', Keys: [{ ID: 'KeyID1' } as Key] } as Address; const address2 = { ID: 'AddressID2', Email: 'email2@home.net', Keys: [{ ID: 'KeyID2' } as Key] } as Address; const fileName = 'file.png'; const fileType = 'image/png'; const file = new File([], fileName, { type: fileType }); const attachmentData = { ID: 'AttachmentID', Name: fileName, MIMEType: fileType }; let updateSpy: jest.Mock; let sendSpy: jest.Mock; const setup = async (MIMEType = MIME_TYPES.PLAINTEXT) => { const { attachment, sessionKey: generatedSessionKey } = await createAttachment( attachmentData, address1Keys.publicKeys ); const { resolve } = addApiResolver('mail/v4/attachments'); updateSpy = jest.fn(({ data: { Message, AttachmentKeyPackets } }: any) => { Message.Attachments.forEach((Attachment: any) => { if (AttachmentKeyPackets?.[Attachment.ID]) { Attachment.KeyPackets = AttachmentKeyPackets[Attachment.ID]; } }); return Promise.resolve({ Message }); }); addApiMock(`mail/v4/messages/${ID}`, updateSpy, 'put'); sendSpy = jest.fn(() => Promise.resolve({ Sent: {} })); addApiMock(`mail/v4/messages/${ID}`, sendSpy, 'post'); minimalCache(); const message = prepareMessage({ localID: ID, data: { AddressID: address1.ID, MIMEType, Sender: { Address: address1.ID, Name: address1.Email } }, messageDocument: { plainText: 'test', document: createDocument('hello') }, }); addApiKeys(false, toAddress, []); addAddressToCache(address1); addAddressToCache(address2); const composerID = Object.keys(store.getState().composers.composers)[0]; const result = await render(<Composer {...props} composerID={composerID} />, false); props.onClose.mockImplementation(result.unmount); const inputAttachment = result.getByTestId('composer-attachments-button') as HTMLInputElement; fireEvent.change(inputAttachment, { target: { files: [file] } }); await tick(); return { ...result, resolve, message, attachment, generatedSessionKey, updateSpy, sendSpy }; }; const saveNow = async (container: HTMLElement) => { fireEvent.keyDown(container, { key: 's', ctrlKey: true }); await tick(); }; const waitForAutoSave = async () => { act(() => { jest.advanceTimersByTime(3000); }); await tick(); }; const switchAddress = async (getByTestId: (id: string) => HTMLElement) => { const fromButton = getByTestId('composer:from') as HTMLButtonElement; fireEvent.click(fromButton); const fromDropdown = await getDropdown(); const email2Dropdown = getByTitle(fromDropdown, address2.Email); fireEvent.click(email2Dropdown); }; beforeAll(async () => { await setupCryptoProxyForTesting(); address1Keys = await generateKeys('1', address1.Email); address2Keys = await generateKeys('2', address2.Email); }); afterAll(async () => { clearAll(); await releaseCryptoProxy(); }); beforeEach(() => { clearAll(); jest.useFakeTimers(); addKeysToAddressKeysCache(address1.ID, address1Keys); addKeysToAddressKeysCache(address2.ID, address2Keys); }); afterEach(() => { jest.useRealTimers(); }); it('should not show embedded modal when plaintext mode', async () => { const { queryAllByText, findByText, resolve, container } = await setup(); const embeddedModalMatch = queryAllByText('Insert image'); expect(embeddedModalMatch.length).toBe(0); // Testing aria-label is simple as filename has an ellipse split in the middle const attachmentName = container.querySelector(`[aria-label="${fileName}"]`); expect(attachmentName).not.toBe(null); resolve({ Attachment: { ID: 'AttachmentID' } }); await tick(); await waitForAutoSave(); // file without an "s" mean only one await findByText('file attached'); }); it('should show embedded modal when html mode', async () => { const { queryAllByText, getByTestId, findByText, resolve, container } = await setup(MIME_TYPES.DEFAULT); const embeddedModalMatch = queryAllByText('Insert image'); expect(embeddedModalMatch.length).toBeGreaterThanOrEqual(1); const attachmentButton = getByTestId('composer:insert-image-attachment'); fireEvent.click(attachmentButton); await tick(); // Testing aria-label is simple as filename has an ellipse split in the middle const attachmentName = container.querySelector(`[aria-label="${fileName}"]`); expect(attachmentName).not.toBe(null); resolve({ Attachment: { ID: 'AttachmentID' } }); await tick(); await waitForAutoSave(); // file without an "s" mean only one await findByText('file attached'); }); it('should re-encrypt attachment key packets on sender address change', async () => { const { getByTestId, findByText, resolve, attachment, generatedSessionKey, container, updateSpy } = await setup(); resolve({ Attachment: attachment }); await tick(); await waitForAutoSave(); await switchAddress(getByTestId); await findByText('file attached'); await saveNow(container); expect(updateSpy).toHaveBeenCalled(); const requestData = (updateSpy.mock.calls[1] as any[])[0].data; const keyPackets = requestData.AttachmentKeyPackets[attachment.ID as string]; expect(keyPackets).toBeDefined(); const decryptedSessionKey = await decryptSessionKey(keyPackets, address2Keys.privateKeys); expect(generatedSessionKey).toEqual(decryptedSessionKey); }); it('should re-encrypt attachment key packets on sender address change and send', async () => { const { message, resolve, attachment, generatedSessionKey, updateSpy, sendSpy, ...renderResult } = await setup(); await switchAddress(renderResult.getByTestId); const sendButton = await renderResult.findByTestId('composer:send-button'); fireEvent.click(sendButton); await tick(); await waitForNotification('Sending message...'); resolve({ Attachment: attachment }); await tick(); await waitFor( () => { expect(updateSpy).toBeCalled(); }, { timeout: 20000 } ); await tick(); await waitFor( () => { expect(sendSpy).toBeCalled(); }, { timeout: 20000 } ); await waitForNotification('Message sent'); await waitForNoNotification(); const requestData = (updateSpy.mock.calls[1] as any[])[0].data; const keyPackets = requestData.AttachmentKeyPackets[attachment.ID as string]; expect(keyPackets).toBeDefined(); const sendRequest = (sendSpy.mock.calls[0] as any[])[0].data; const sendData = parseFormData(sendRequest); const attachmentKey = sendData.Packages['text/plain'].AttachmentKeys[attachment.ID as string].Key; // Attachment session key sent is the one we generated expect(attachmentKey).toBe(arrayToBase64(generatedSessionKey.data)); }); });
3,425
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/tests/Composer.autosave.test.tsx
import { fireEvent, getByTestId, waitFor } from '@testing-library/react'; import { act } from '@testing-library/react'; import { ROOSTER_EDITOR_ID } from '@proton/components/components/editor/constants'; import { MIME_TYPES } from '@proton/shared/lib/constants'; import noop from '@proton/utils/noop'; import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../helpers/test/crypto'; import { GeneratedKey, addApiKeys, addApiMock, addKeysToAddressKeysCache, clearAll, createDocument, generateKeys, } from '../../../helpers/test/helper'; import { store } from '../../../logic/store'; import { AddressID, ID, fromAddress, prepareMessage, renderComposer, toAddress } from './Composer.test.helpers'; jest.setTimeout(20000); /** * Those tests are slow, I'm sorry for that * But I found no way of making jest fake timers works (at least with the composer) */ describe('Composer autosave', () => { let fromKeys: GeneratedKey; beforeAll(async () => { await setupCryptoProxyForTesting(); fromKeys = await generateKeys('me', fromAddress); }); afterAll(async () => { clearAll(); await releaseCryptoProxy(); }); beforeEach(() => { clearAll(); jest.useFakeTimers(); addKeysToAddressKeysCache(AddressID, fromKeys); addApiKeys(false, toAddress, []); }); afterEach(() => { jest.useRealTimers(); }); const asyncSpy = (resolved = true) => { let resolve: (value: unknown) => void = noop; let reject: (value: unknown) => void = noop; const spy = jest.fn(() => { if (resolved) { return Promise.resolve({ Message: { ID } }); } return new Promise((res, rej) => { resolve = res; reject = rej; }); }); return { spy, resolve: (value: unknown) => resolve(value), reject: (value: unknown) => reject(value) }; }; const triggerRoosterInput = (container: HTMLElement) => { const iframe = getByTestId(container, 'rooster-iframe') as HTMLIFrameElement; const editor = iframe.contentDocument?.getElementById(ROOSTER_EDITOR_ID); if (editor) { fireEvent.input(editor, 'hello'); } }; const setup = async (resolved = true) => { prepareMessage({ data: { ID: undefined, MIMEType: MIME_TYPES.DEFAULT }, messageDocument: { document: createDocument('test') }, }); const composerID = Object.keys(store.getState().composers.composers)[0]; const renderResult = await renderComposer(composerID); triggerRoosterInput(renderResult.container); // Initial dummy Squire input const { spy: createSpy, resolve: createResolve } = asyncSpy(resolved); const { spy: updateSpy, resolve: updateResolve } = asyncSpy(resolved); const { spy: sendSpy, resolve: sendResolve } = asyncSpy(resolved); addApiMock(`mail/v4/messages`, createSpy, 'post'); addApiMock(`mail/v4/messages/undefined`, updateSpy, 'put'); // Should be /ID addApiMock(`mail/v4/messages/${ID}`, sendSpy, 'post'); // Should be /ID return { ...renderResult, createSpy, updateSpy, sendSpy, createResolve, updateResolve, sendResolve }; }; const waitForSpy = (spy: jest.Mock<Promise<unknown>, []>) => waitFor( () => { expect(spy).toHaveBeenCalled(); }, { timeout: 10000 } ); it('should wait 2s before saving a change', async () => { const { createSpy, container } = await setup(); await act(async () => { triggerRoosterInput(container); jest.advanceTimersByTime(1500); expect(createSpy).not.toHaveBeenCalled(); jest.advanceTimersByTime(1500); await waitForSpy(createSpy); }); }); it('should wait 2s after the last change before saving a change', async () => { const { createSpy, container } = await setup(); await act(async () => { triggerRoosterInput(container); jest.advanceTimersByTime(1500); triggerRoosterInput(container); jest.advanceTimersByTime(1500); expect(createSpy).not.toHaveBeenCalled(); jest.advanceTimersByTime(1500); await waitForSpy(createSpy); }); }); it('should wait 2s after previous save resolved before saving a change', async () => { const { createSpy, createResolve, updateSpy, container } = await setup(false); await act(async () => { triggerRoosterInput(container); jest.advanceTimersByTime(1500); expect(createSpy).not.toHaveBeenCalled(); jest.advanceTimersByTime(1500); await waitForSpy(createSpy); triggerRoosterInput(container); jest.advanceTimersByTime(1500); expect(updateSpy).not.toHaveBeenCalled(); jest.advanceTimersByTime(1500); expect(updateSpy).not.toHaveBeenCalled(); createResolve({ Message: { ID } }); jest.advanceTimersByTime(1500); expect(updateSpy).not.toHaveBeenCalled(); jest.advanceTimersByTime(1500); await waitForSpy(updateSpy); }); }); it('should wait previous save before sending', async () => { jest.useFakeTimers(); const { createSpy, createResolve, sendSpy, container, ...renderResult } = await setup(false); await act(async () => { triggerRoosterInput(container); jest.advanceTimersByTime(1500); const sendButton = await renderResult.findByTestId('composer:send-button'); fireEvent.click(sendButton); jest.advanceTimersByTime(1500); await waitForSpy(createSpy); expect(sendSpy).not.toHaveBeenCalled(); createResolve({ Message: { ID, Attachments: [] } }); await waitForSpy(sendSpy); }); }); });
3,426
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/tests/Composer.expiration.test.tsx
import { fireEvent } from '@testing-library/react'; import { act, getByTestId as getByTestIdDefault, getByText as getByTextDefault } from '@testing-library/react'; import { format } from 'date-fns'; import loudRejection from 'loud-rejection'; import { MIME_TYPES } from '@proton/shared/lib/constants'; import { addDays } from '@proton/shared/lib/date-fns-utc'; import { dateLocale } from '@proton/shared/lib/i18n'; import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../helpers/test/crypto'; import { addApiKeys, addKeysToAddressKeysCache, clearAll, generateKeys, getDropdown, render, } from '../../../helpers/test/helper'; import { store } from '../../../logic/store'; import Composer from '../Composer'; import { AddressID, ID, fromAddress, prepareMessage, props, toAddress } from './Composer.test.helpers'; loudRejection(); describe('Composer expiration', () => { beforeEach(() => { clearAll(); }); beforeAll(async () => { await setupCryptoProxyForTesting(); }); afterAll(async () => { clearAll(); await releaseCryptoProxy(); }); const setup = async () => { const state = store.getState(); const composerID = Object.keys(state.composers.composers)[0]; const fromKeys = await generateKeys('me', fromAddress); addKeysToAddressKeysCache(AddressID, fromKeys); addApiKeys(false, toAddress, []); const result = await render(<Composer {...props} composerID={composerID} />); return result; }; it('should open expiration modal with default values', async () => { const expirationDate = addDays(new Date(), 7); const datePlaceholder = format(expirationDate, 'PP', { locale: dateLocale }); prepareMessage({ localID: ID, data: { MIMEType: 'text/plain' as MIME_TYPES }, messageDocument: { plainText: '' }, }); const { getByTestId, getByText } = await setup(); const moreOptionsButton = getByTestId('composer:more-options-button'); fireEvent.click(moreOptionsButton); const dropdown = await getDropdown(); getByTextDefault(dropdown, 'Expiration time'); const expirationButton = getByTestIdDefault(dropdown, 'composer:expiration-button'); await act(async () => { fireEvent.click(expirationButton); }); getByText('Expiring message'); const dayInput = getByTestId('composer:expiration-days') as HTMLInputElement; const hoursInput = getByTestId('composer:expiration-hours') as HTMLInputElement; // Check if default expiration is in 7 days and at 9 o'clock expect(dayInput.value).toEqual(datePlaceholder); expect(hoursInput.value).toEqual('9:00 AM'); }); it('should display expiration banner and open expiration modal when clicking on edit', async () => { const expirationDate = addDays(new Date(), 7); const expirationTime = expirationDate.getTime() / 1000; const datePlaceholder = format(expirationDate, 'PP', { locale: dateLocale }); prepareMessage({ localID: ID, data: { MIMEType: 'text/plain' as MIME_TYPES, ExpirationTime: expirationTime }, messageDocument: { plainText: '' }, }); const { getByText, getByTestId } = await setup(); getByText(/This message will expire/); const editButton = getByTestId('message:expiration-banner-edit-button'); await act(async () => { fireEvent.click(editButton); }); getByText('Expiring message'); const dayInput = getByTestId('composer:expiration-days') as HTMLInputElement; const hoursInput = getByTestId('composer:expiration-hours') as HTMLInputElement; // Check if default expiration is in 7 days and at 9 o'clock expect(dayInput.value).toEqual(datePlaceholder); expect(hoursInput.value).toEqual('9:00 AM'); }); });
3,427
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/tests/Composer.hotkeys.test.tsx
import { fireEvent } from '@testing-library/react'; import { MIME_TYPES } from '@proton/shared/lib/constants'; import { SHORTCUTS } from '@proton/shared/lib/mail/mailSettings'; import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../helpers/test/crypto'; import { GeneratedKey, addApiKeys, addApiMock, addKeysToAddressKeysCache, addToCache, clearAll, clearCache, createDocument, generateKeys, minimalCache, waitForNotification, } from '../../../helpers/test/helper'; import { store } from '../../../logic/store'; import { AddressID, ID, fromAddress, prepareMessage, renderComposer, toAddress } from './Composer.test.helpers'; const orignalGetSelection = global.getSelection; beforeAll(() => { global.getSelection = jest.fn(); }); afterAll(() => { global.getSelection = orignalGetSelection; }); describe('Composer hotkeys', () => { let fromKeys: GeneratedKey; beforeAll(async () => { await setupCryptoProxyForTesting(); fromKeys = await generateKeys('me', fromAddress); }); afterAll(async () => { await releaseCryptoProxy(); }); afterEach(() => { clearCache(); }); beforeEach(clearAll); const setup = async (hasShortcutsEnabled = true) => { minimalCache(); if (hasShortcutsEnabled) { addToCache('MailSettings', { Shortcuts: SHORTCUTS.ENABLED }); } else { addToCache('MailSettings', { Shortcuts: SHORTCUTS.DISABLED }); } addKeysToAddressKeysCache(AddressID, fromKeys); prepareMessage({ messageDocument: { document: createDocument('test') }, data: { MIMEType: MIME_TYPES.DEFAULT }, }); addApiKeys(false, toAddress, []); const composerID = Object.keys(store.getState().composers.composers)[0]; const result = await renderComposer(composerID, false); const iframe = result.container.querySelector('iframe') as HTMLIFrameElement; return { ...result, iframe, esc: () => fireEvent.keyDown(iframe, { key: 'Escape' }), ctrlEnter: () => fireEvent.keyDown(iframe, { key: 'Enter', ctrlKey: true }), ctrlAltBackspace: () => fireEvent.keyDown(iframe, { key: 'Backspace', ctrlKey: true, altKey: true }), ctrlS: () => fireEvent.keyDown(iframe, { key: 'S', ctrlKey: true }), ctrlM: () => fireEvent.keyDown(iframe, { key: 'M', ctrlKey: true }), ctrlShftM: () => fireEvent.keyDown(iframe, { key: 'M', ctrlKey: true, shiftKey: true }), ctrlShftA: () => fireEvent.keyDown(iframe, { key: 'A', ctrlKey: true, shiftKey: true }), ctrlShftE: () => fireEvent.keyDown(iframe, { key: 'E', ctrlKey: true, shiftKey: true }), ctrlShftX: () => fireEvent.keyDown(iframe, { key: 'X', ctrlKey: true, shiftKey: true }), }; }; it('shortcut should not work when app shortcuts settings are disabled', async () => { const { container, esc } = await setup(false); esc(); const composer = container.querySelector('.composer-container'); expect(composer).not.toBe(null); }); it('should close composer on escape', async () => { const { container, esc } = await setup(); esc(); const composer = container.querySelector('.composer-container'); expect(composer).toBe(null); }); it('should send on meta + enter', async () => { const { ctrlEnter } = await setup(); const sendSpy = jest.fn(() => Promise.resolve({ Sent: {} })); addApiMock(`mail/v4/messages/${ID}`, sendSpy, 'post'); ctrlEnter(); await waitForNotification('Message sent'); expect(sendSpy).toHaveBeenCalled(); }); it('should delete on meta + alt + enter', async () => { const deleteSpy = jest.fn(() => Promise.resolve({})); addApiMock(`mail/v4/messages/delete`, deleteSpy, 'put'); const { ctrlAltBackspace } = await setup(); ctrlAltBackspace(); await waitForNotification('Draft discarded'); expect(deleteSpy).toHaveBeenCalled(); }); it('should save on meta + S', async () => { const saveSpy = jest.fn(() => Promise.resolve({})); addApiMock(`mail/v4/messages/${ID}`, saveSpy, 'put'); const { ctrlS } = await setup(); ctrlS(); await waitForNotification('Draft saved'); expect(saveSpy).toHaveBeenCalled(); }); it('should open attachment on meta + shift + A', async () => { const { getByTestId, ctrlShftA } = await setup(); const attachmentsButton = getByTestId('composer:attachment-button'); const attachmentSpy = jest.fn(); attachmentsButton.addEventListener('click', attachmentSpy); ctrlShftA(); expect(attachmentSpy).toHaveBeenCalled(); }); it('should open encryption modal on meta + shift + E', async () => { const { findByText, ctrlShftE } = await setup(); ctrlShftE(); await findByText('Encrypt message'); }); it('should open encryption modal on meta + shift + X', async () => { const { findByText, ctrlShftX } = await setup(); ctrlShftX(); await findByText('Expiring message'); }); });
3,428
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/tests/Composer.outsideEncryption.test.tsx
import { fireEvent, getByTestId as getByTestIdDefault } from '@testing-library/react'; import { act } from '@testing-library/react'; import { addHours } from 'date-fns'; import loudRejection from 'loud-rejection'; import { MIME_TYPES } from '@proton/shared/lib/constants'; import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../helpers/test/crypto'; import { addApiKeys, addApiMock, addKeysToAddressKeysCache, clearAll, generateKeys, getDropdown, render, setFeatureFlags, tick, } from '../../../helpers/test/helper'; import { store } from '../../../logic/store'; import Composer from '../Composer'; import { AddressID, ID, fromAddress, prepareMessage, props, toAddress } from './Composer.test.helpers'; loudRejection(); const password = 'password'; describe('Composer outside encryption', () => { beforeEach(() => { clearAll(); }); beforeAll(async () => { await setupCryptoProxyForTesting(); }); afterAll(async () => { clearAll(); await releaseCryptoProxy(); }); const setup = async () => { setFeatureFlags('EORedesign', true); addApiMock(`mail/v4/messages/${ID}`, () => ({ Message: {} }), 'put'); const fromKeys = await generateKeys('me', fromAddress); addKeysToAddressKeysCache(AddressID, fromKeys); addApiKeys(false, toAddress, []); const composerID = Object.keys(store.getState().composers.composers)[0]; const result = await render(<Composer {...props} composerID={composerID} />); return result; }; it('should set outside encryption and display the expiration banner', async () => { prepareMessage({ localID: ID, data: { MIMEType: 'text/plain' as MIME_TYPES }, messageDocument: { plainText: '' }, }); const { getByTestId, getByText, container } = await setup(); const expirationButton = getByTestId('composer:password-button'); fireEvent.click(expirationButton); await tick(); // modal is displayed and we can set a password getByText('Encrypt message'); const passwordInput = getByTestId('encryption-modal:password-input'); fireEvent.change(passwordInput, { target: { value: password } }); const setEncryptionButton = getByTestId('modal-footer:set-button'); fireEvent.click(setEncryptionButton); // The expiration banner is displayed getByText(/This message will expire/); // Trigger manual save to avoid unhandledPromiseRejection await act(async () => { fireEvent.keyDown(container, { key: 'S', ctrlKey: true }); }); }); it('should set outside encryption with a default expiration time', async () => { // Message will expire tomorrow prepareMessage({ localID: ID, data: { MIMEType: 'text/plain' as MIME_TYPES }, messageDocument: { plainText: '' }, draftFlags: { expiresIn: addHours(new Date(), 25), // expires in 25 hours }, }); const { getByTestId, getByText } = await setup(); const expirationButton = getByTestId('composer:password-button'); fireEvent.click(expirationButton); await tick(); // Modal and expiration date are displayed getByText('Edit encryption'); getByText('Your message will expire tomorrow.'); }); it('should be able to edit encryption', async () => { prepareMessage({ localID: ID, data: { MIMEType: 'text/plain' as MIME_TYPES }, messageDocument: { plainText: '' }, }); const { getByTestId, getByText, container } = await setup(); const expirationButton = getByTestId('composer:password-button'); fireEvent.click(expirationButton); await tick(); // modal is displayed and we can set a password getByText('Encrypt message'); const passwordInput = getByTestId('encryption-modal:password-input'); fireEvent.change(passwordInput, { target: { value: password } }); const setEncryptionButton = getByTestId('modal-footer:set-button'); fireEvent.click(setEncryptionButton); // Trigger manual save to avoid unhandledPromiseRejection await act(async () => { fireEvent.keyDown(container, { key: 'S', ctrlKey: true }); }); // Edit encryption // Open the encryption dropdown const encryptionDropdownButton = getByTestId('composer:encryption-options-button'); fireEvent.click(encryptionDropdownButton); const dropdown = await getDropdown(); // Click on edit button const editEncryptionButton = getByTestIdDefault(dropdown, 'composer:edit-outside-encryption'); await act(async () => { fireEvent.click(editEncryptionButton); }); const passwordInputAfterUpdate = getByTestId('encryption-modal:password-input') as HTMLInputElement; const passwordValue = passwordInputAfterUpdate.value; expect(passwordValue).toEqual(password); // Trigger manual save to avoid unhandledPromiseRejection await act(async () => { fireEvent.keyDown(container, { key: 'S', ctrlKey: true }); }); }); it('should be able to remove encryption', async () => { prepareMessage({ localID: ID, data: { MIMEType: 'text/plain' as MIME_TYPES }, messageDocument: { plainText: '' }, }); const { getByTestId, getByText, queryByText, container } = await setup(); const expirationButton = getByTestId('composer:password-button'); fireEvent.click(expirationButton); await tick(); // modal is displayed and we can set a password getByText('Encrypt message'); const passwordInput = getByTestId('encryption-modal:password-input'); fireEvent.change(passwordInput, { target: { value: password } }); const setEncryptionButton = getByTestId('modal-footer:set-button'); fireEvent.click(setEncryptionButton); // Edit encryption // Open the encryption dropdown const encryptionDropdownButton = getByTestId('composer:encryption-options-button'); fireEvent.click(encryptionDropdownButton); const dropdown = await getDropdown(); // Click on remove button const editEncryptionButton = getByTestIdDefault(dropdown, 'composer:remove-outside-encryption'); await act(async () => { fireEvent.click(editEncryptionButton); }); expect(queryByText(/This message will self-destruct on/)).toBe(null); // Trigger manual save to avoid unhandledPromiseRejection await act(async () => { fireEvent.keyDown(container, { key: 'S', ctrlKey: true }); }); }); });
3,429
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/tests/Composer.plaintext.test.tsx
import { fireEvent } from '@testing-library/react'; import { MIME_TYPES } from '@proton/shared/lib/constants'; import { clearAll, createDocument, waitForSpyCall } from '../../../helpers/test/helper'; import { render } from '../../../helpers/test/render'; import * as useSaveDraft from '../../../hooks/message/useSaveDraft'; import { store } from '../../../logic/store'; import Composer from '../Composer'; import { ID, prepareMessage, props } from './Composer.test.helpers'; jest.setTimeout(20000); // In this test, switching from plaintext to html will trigger autosave // But encryption and save requests are not the point of this test so it's easier and faster to mock that logic jest.mock('../../../hooks/message/useSaveDraft', () => { const saveSpy = jest.fn(() => Promise.resolve()); return { saveSpy, useCreateDraft: () => () => Promise.resolve(), useSaveDraft: () => saveSpy, useDeleteDraft: () => () => Promise.resolve(), }; }); const saveSpy = (useSaveDraft as any).saveSpy as jest.Mock; const mockSetContent = jest.fn(); jest.mock('@proton/components/components/editor/rooster/helpers/getRoosterEditorActions', () => { let content = ''; return function () { return { getContent: () => { return content; }, setContent: (nextContent: string) => { content = nextContent; mockSetContent(nextContent); }, focus: () => {}, }; }; }); describe('Composer switch plaintext <-> html', () => { beforeEach(clearAll); afterAll(clearAll); it('should switch from plaintext to html content without loosing content', async () => { const content = 'content'; prepareMessage({ localID: ID, data: { MIMEType: 'text/plain' as MIME_TYPES, ToList: [], }, messageDocument: { plainText: content, }, }); const composerID = Object.keys(store.getState().composers.composers)[0]; const { findByTestId } = await render(<Composer {...props} composerID={composerID} />); const moreOptionsButton = await findByTestId('composer:more-options-button'); fireEvent.click(moreOptionsButton); const toHtmlButton = await findByTestId('editor-to-html'); fireEvent.click(toHtmlButton); await findByTestId('rooster-iframe'); await waitForSpyCall(mockSetContent); expect(mockSetContent).toHaveBeenCalledWith( `<div style="font-family: Arial, sans-serif; font-size: 14px;">${content}</div>` ); // Wait for auto save await waitForSpyCall(saveSpy); }); it('should switch from html to plaintext content without loosing content', async () => { const content = ` <div>content line 1<br><div> <div>content line 2<br><div> `; prepareMessage({ localID: ID, data: { MIMEType: 'text/html' as MIME_TYPES, ToList: [], }, messageDocument: { document: createDocument(content), }, }); const composerID = Object.keys(store.getState().composers.composers)[0]; const { findByTestId } = await render(<Composer {...props} composerID={composerID} />); const moreOptionsButton = await findByTestId('composer:more-options-button'); fireEvent.click(moreOptionsButton); const toHtmlButton = await findByTestId('editor-to-plaintext'); fireEvent.click(toHtmlButton); const textarea = (await findByTestId('editor-textarea')) as HTMLTextAreaElement; expect(textarea.value).toBe('content line 1\ncontent line 2'); // Wait for auto save await waitForSpyCall(saveSpy); }); });
3,430
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/tests/Composer.reply.test.tsx
import { fireEvent } from '@testing-library/react'; import { act } from '@testing-library/react'; import loudRejection from 'loud-rejection'; import { MIME_TYPES } from '@proton/shared/lib/constants'; import { MailSettings } from '@proton/shared/lib/interfaces'; import { GeneratedKey, addApiKeys, addKeysToAddressKeysCache, generateKeys, releaseCryptoProxy, setupCryptoProxyForTesting, } from '../../../helpers/test/crypto'; import { addApiMock, addToCache, clearAll, createDocument, decryptMessage, decryptSessionKey, minimalCache, } from '../../../helpers/test/helper'; import { store } from '../../../logic/store'; import { ID, clickSend, prepareMessage, renderComposer, send } from './Composer.test.helpers'; loudRejection(); jest.setTimeout(20000); const bodyContent = 'body content'; const blockquoteContent = 'blockquoteContent'; const content = ` ${bodyContent} <blockquote class="protonmail_quote" type="cite"> ${blockquoteContent} </blockquote> `; describe('Composer reply and forward', () => { const AddressID = 'AddressID'; const fromAddress = 'me@home.net'; const toAddress = 'someone@somewhere.net'; let fromKeys: GeneratedKey; let toKeys: GeneratedKey; beforeAll(async () => { await setupCryptoProxyForTesting(); fromKeys = await generateKeys('me', fromAddress); toKeys = await generateKeys('someone', toAddress); }); afterAll(async () => { await releaseCryptoProxy(); }); beforeEach(() => { addKeysToAddressKeysCache(AddressID, fromKeys); }); afterEach(() => { clearAll(); jest.useRealTimers(); }); it('send content with blockquote collapsed', async () => { const { composerID } = prepareMessage({ messageDocument: { document: createDocument(content) }, data: { MIMEType: MIME_TYPES.DEFAULT }, }); minimalCache(); addToCache('MailSettings', { DraftMIMEType: MIME_TYPES.DEFAULT } as MailSettings); addApiKeys(true, toAddress, [toKeys]); // Will use update only on the wrong path, but it allows to have a "nice failure" const updateSpy = jest.fn(() => Promise.reject(new Error('Should not update here'))); addApiMock(`mail/v4/messages/${ID}`, updateSpy, 'put'); const sendRequest = await send(composerID, false); const packages = sendRequest.data.Packages; const pack = packages['text/html']; const address = pack.Addresses[toAddress]; const sessionKey = await decryptSessionKey(address.BodyKeyPacket, toKeys.privateKeys); const decryptResult = await decryptMessage(pack, toKeys.privateKeys, sessionKey); expect(decryptResult.data).toContain(bodyContent); expect(decryptResult.data).toContain(blockquoteContent); }); it('send content with blockquote expanded', async () => { prepareMessage({ messageDocument: { document: createDocument(content) }, data: { MIMEType: MIME_TYPES.DEFAULT }, }); minimalCache(); addToCache('MailSettings', { DraftMIMEType: MIME_TYPES.DEFAULT } as MailSettings); addApiKeys(true, toAddress, [toKeys]); const composerID = Object.keys(store.getState().composers.composers)[0]; const renderResult = await renderComposer(composerID, false); const iframe = (await renderResult.findByTestId('rooster-iframe')) as HTMLIFrameElement; const button = iframe.contentWindow?.document.getElementById('ellipsis') as HTMLButtonElement; await act(async () => { fireEvent.click(button); }); // Will use update only on the wrong path, but it allows to have a "nice failure" const updateSpy = jest.fn(() => Promise.reject(new Error('Should not update here'))); addApiMock(`mail/v4/messages/${ID}`, updateSpy, 'put'); const sendRequest = await clickSend(renderResult); const packages = sendRequest.data.Packages; const pack = packages['text/html']; const address = pack.Addresses[toAddress]; const sessionKey = await decryptSessionKey(address.BodyKeyPacket, toKeys.privateKeys); const decryptResult = await decryptMessage(pack, toKeys.privateKeys, sessionKey); expect(decryptResult.data).toContain(bodyContent); expect(decryptResult.data).toContain(blockquoteContent); }); });
3,431
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/tests/Composer.schedule.test.tsx
import { act, fireEvent, getByTestId as getByTestIdDefault, getByText as getByTextDefault, screen, waitFor, } from '@testing-library/react'; import { format, getUnixTime } from 'date-fns'; import { enUS } from 'date-fns/locale'; import loudRejection from 'loud-rejection'; import { MAILBOX_LABEL_IDS, MIME_TYPES } from '@proton/shared/lib/constants'; import { addDays, addMinutes } from '@proton/shared/lib/date-fns-utc'; import { Recipient } from '@proton/shared/lib/interfaces'; import { VIEW_MODE } from '@proton/shared/lib/mail/mailSettings'; import { getMinScheduleTime } from '../../../helpers/schedule'; import { addApiMock, setFeatureFlags } from '../../../helpers/test/api'; import { addToCache, minimalCache } from '../../../helpers/test/cache'; import { addApiKeys, clearAll, getDropdown } from '../../../helpers/test/helper'; import { render } from '../../../helpers/test/render'; import Composer from '../Composer'; import { ID, prepareMessage, props } from './Composer.test.helpers'; loudRejection(); const user = { Name: 'User', Address: 'user@protonmail.com' }; const setupTest = ({ hasPaidMail, scheduledTotalCount = 4, featureFlagActive = true, showSpotlight = false, }: { hasPaidMail: boolean; scheduledTotalCount?: number; featureFlagActive?: boolean; showSpotlight?: boolean; }) => { minimalCache(); addToCache('User', { Email: 'Email', DisplayName: 'DisplayName', Name: 'Name', hasPaidMail, UsedSpace: 10, MaxSpace: 100, }); addToCache('MailSettings', { ViewMode: VIEW_MODE.SINGLE }); addToCache('MessageCounts', [{ LabelID: MAILBOX_LABEL_IDS.SCHEDULED, Unread: 1, Total: scheduledTotalCount }]); setFeatureFlags('ScheduledSendFreemium', featureFlagActive); setFeatureFlags('SpotlightScheduledSend', showSpotlight); addApiKeys(false, user.Address, []); }; const setupMessage = (Subject = '', ToList: Recipient[] = [], scheduledAt?: number) => { return prepareMessage({ localID: ID, data: { MIMEType: 'text/plain' as MIME_TYPES, Subject, ToList }, messageDocument: { plainText: '' }, ...(scheduledAt ? { draftFlags: { scheduledAt } } : {}), }); }; describe('Composer scheduled messages', () => { beforeEach(() => { clearAll(); addApiMock('core/v4/features/SpotlightScheduledSend/value', jest.fn, 'put'); }); afterEach(() => { jest.useRealTimers(); }); afterAll(() => { clearAll(); }); it('Should see the schedule send when FF is active', async () => { const { composerID } = setupMessage('Subject', [user as Recipient]); setupTest({ hasPaidMail: false, featureFlagActive: true }); const { queryByTestId } = await render(<Composer {...props} composerID={composerID} />, false); expect(queryByTestId('composer:send-button')).toBeTruthy(); expect(queryByTestId('composer:scheduled-send:open-dropdown')).toBeTruthy(); }); it('Should not see the schedule send when FF is not active', async () => { const { composerID } = setupMessage('Subject', [user as Recipient]); setupTest({ hasPaidMail: false, featureFlagActive: false }); const { queryByTestId } = await render(<Composer {...props} composerID={composerID} />, false); expect(queryByTestId('composer:send-button')).toBeTruthy(); expect(queryByTestId('composer:scheduled-send:open-dropdown')).toBeNull(); }); describe('Dropdown', () => { it('Should contain default fields', async () => { // Sunday 1 2023 const fakeNow = new Date(2023, 0, 1, 10, 0, 0); jest.useFakeTimers().setSystemTime(fakeNow.getTime()); const { composerID } = setupMessage('Subject', [user as Recipient]); setupTest({ hasPaidMail: false, featureFlagActive: true }); await render(<Composer {...props} composerID={composerID} />, false); const dropdownButton = screen.getByTestId('composer:scheduled-send:open-dropdown'); fireEvent.click(dropdownButton); expect(screen.queryByTestId('composer:schedule-send:dropdown-title')).toBeTruthy(); expect(screen.queryByTestId('composer:schedule-send:tomorrow')).toBeTruthy(); expect(screen.queryByTestId('composer:schedule-send:next-monday')).toBeTruthy(); expect(screen.queryByTestId('composer:schedule-send:custom')).toBeTruthy(); // Scheduled At should not be there expect(screen.queryByTestId('composer:schedule-send-as-scheduled')).toBeNull(); expect(screen.queryByTestId('composer:schedule-send:tomorrow')).toHaveTextContent('January 2nd at 8:00 AM'); expect(screen.queryByTestId('composer:schedule-send:next-monday')).toHaveTextContent( 'January 2nd at 8:00 AM' ); }); it.each` expected | date ${'Tomorrow'} | ${new Date(2023, 0, 1, 7, 59, 0)} ${'Tomorrow'} | ${new Date(2023, 0, 1, 8, 0, 0)} ${'Tomorrow'} | ${new Date(2023, 0, 1, 10, 0, 0)} ${'In the morning'} | ${new Date(2023, 0, 1, 0, 0, 1)} ${'In the morning'} | ${new Date(2023, 0, 1, 2, 0, 0)} ${'In the morning'} | ${new Date(2023, 0, 1, 7, 30, 0)} `('Should display "$expected" on "$date"', async ({ expected, date }) => { jest.useFakeTimers().setSystemTime(date.getTime()); const { composerID } = setupMessage('Subject', [user as Recipient]); setupTest({ hasPaidMail: false, featureFlagActive: true }); await render(<Composer {...props} composerID={composerID} />, false); const dropdownButton = screen.getByTestId('composer:scheduled-send:open-dropdown'); fireEvent.click(dropdownButton); expect(screen.queryByTestId('composer:schedule-send:tomorrow')).toHaveTextContent(expected); }); it('Should contain "as scheduled" field when editing', async () => { // Sunday 1 2023 const fakeNow = new Date(2023, 0, 1, 10, 0, 0); jest.useFakeTimers().setSystemTime(fakeNow.getTime()); const { composerID } = setupMessage( 'Subject', [user as Recipient], getUnixTime(new Date(2023, 0, 5, 10, 0, 0)) ); setupTest({ hasPaidMail: false, featureFlagActive: true }); await render(<Composer {...props} composerID={composerID} />, false); const dropdownButton = screen.getByTestId('composer:scheduled-send:open-dropdown'); fireEvent.click(dropdownButton); const asScheduledButton = screen.getByTestId('composer:schedule-send-as-scheduled'); expect(asScheduledButton).toHaveTextContent('January 5th at 10:00 AM'); }); }); describe('Spotlight', () => { it('Should be displayed on composer opening', async () => { const { composerID } = setupMessage('Subject', [user as Recipient]); setupTest({ hasPaidMail: false, featureFlagActive: true, showSpotlight: true }); await render(<Composer {...props} composerID={composerID} />, false); let spotlightTitle = screen.queryByTestId('composer:schedule-send:spotlight-title'); expect(spotlightTitle).toBeTruthy(); }); it('Should be closed when dropdown is clicked', async () => { const { composerID } = setupMessage('Subject', [user as Recipient]); setupTest({ hasPaidMail: false, featureFlagActive: true, showSpotlight: true }); await render(<Composer {...props} composerID={composerID} />, false); let spotlightTitle = screen.queryByTestId('composer:schedule-send:spotlight-title'); expect(spotlightTitle).toBeTruthy(); const dropdownButton = screen.getByTestId('composer:scheduled-send:open-dropdown'); fireEvent.click(dropdownButton); await waitFor(() => { expect(screen.queryByTestId('composer:schedule-send:spotlight-title')).toBeNull(); }); }); }); describe('Upsell modal', () => { it('Should be displayed to free users', async () => { const { composerID } = setupMessage('Subject', [user as Recipient]); setupTest({ hasPaidMail: false, featureFlagActive: true, showSpotlight: false }); await render(<Composer {...props} composerID={composerID} />, false); const dropdownButton = screen.getByTestId('composer:scheduled-send:open-dropdown'); fireEvent.click(dropdownButton); const customDropdownButton = screen.getByTestId('composer:schedule-send:custom'); fireEvent.click(customDropdownButton); expect(screen.queryByTestId('composer:schedule-send:upsell-modal')).toBeTruthy(); }); it('Should be hidden for paid users', async () => { const { composerID } = setupMessage('Subject', [user as Recipient]); setupTest({ hasPaidMail: true, featureFlagActive: true, showSpotlight: false }); await render(<Composer {...props} composerID={composerID} />, false); const dropdownButton = screen.getByTestId('composer:scheduled-send:open-dropdown'); fireEvent.click(dropdownButton); const customDropdownButton = screen.getByTestId('composer:schedule-send:custom'); fireEvent.click(customDropdownButton); expect(screen.queryByTestId('composer:schedule-send:upsell-modal')).toBeNull(); }); }); it('should show a modal when the user reached scheduled messages limit', async () => { const { composerID } = setupMessage('Subject', [user as Recipient]); setupTest({ hasPaidMail: true, scheduledTotalCount: 100 }); const { getByTestId, getByText } = await render(<Composer {...props} composerID={composerID} />, false); const sendActions = getByTestId('composer:send-actions'); const dropdownButton = getByTestIdDefault(sendActions, 'composer:scheduled-send:open-dropdown'); fireEvent.click(dropdownButton); const dropdown = await getDropdown(); const scheduledSendButton = getByTestIdDefault(dropdown, 'composer:schedule-send:custom'); fireEvent.click(scheduledSendButton); getByText( 'Too many messages waiting to be sent. Please wait until another message has been sent to schedule this one.' ); }); it('should show a modal when trying to schedule a message without a recipient', async () => { const { composerID } = setupMessage(); setupTest({ hasPaidMail: true }); const { getByTestId } = await render(<Composer {...props} composerID={composerID} />, false); const sendActions = getByTestId('composer:send-actions'); const dropdownButton = getByTestIdDefault(sendActions, 'composer:scheduled-send:open-dropdown'); fireEvent.click(dropdownButton); const dropdown = await getDropdown(); const scheduledSendButton = getByTestIdDefault(dropdown, 'composer:schedule-send:custom'); fireEvent.click(scheduledSendButton); const modal = getByTestId('composer:modal:norecipients'); getByTextDefault(modal, 'Recipient missing'); }); it('Should show a modal when trying to schedule a message with a recipient and without subject', async () => { const { composerID } = setupMessage('', [user as Recipient]); setupTest({ hasPaidMail: true }); await render(<Composer {...props} composerID={composerID} />, false); const sendActions = screen.getByTestId('composer:send-actions'); const dropdownButton = getByTestIdDefault(sendActions, 'composer:scheduled-send:open-dropdown'); fireEvent.click(dropdownButton); const dropdown = await getDropdown(); const scheduledSendButton = getByTestIdDefault(dropdown, 'composer:schedule-send:custom'); fireEvent.click(scheduledSendButton); const modal = await screen.findByTestId('composer:modal:nosubject'); getByTextDefault(modal, 'Subject missing'); }); it('should open schedule send modal and change date', async () => { const { composerID } = setupMessage('Subject', [user as Recipient]); setupTest({ hasPaidMail: true }); const dateSpy = jest.spyOn(Date, 'now').mockImplementation(() => new Date().setHours(12).valueOf()); const { getByTestId } = await render(<Composer {...props} composerID={composerID} />, false); const sendActions = getByTestId('composer:send-actions'); const dropdownButton = getByTestIdDefault(sendActions, 'composer:scheduled-send:open-dropdown'); fireEvent.click(dropdownButton); const dropdown = await getDropdown(); const scheduledSendButton = getByTestIdDefault(dropdown, 'composer:schedule-send:custom'); await act(async () => { fireEvent.click(scheduledSendButton); }); getByTestId('composer:schedule-send:custom-modal:title'); const dateInput = getByTestId('composer:schedule-date-input') as HTMLInputElement; const timeInput = getByTestId('composer:schedule-time-input') as HTMLInputElement; // Check if default date is Tomorrow, 8:00 AM expect(dateInput.value).toEqual('Tomorrow'); expect(timeInput.value).toEqual('8:00 AM'); // format today date to change the input const todayDate = format(new Date(Date.now()), 'PP', { locale: enUS }); // set date input to today fireEvent.change(dateInput, { target: { value: todayDate } }); fireEvent.keyDown(dateInput, { key: 'Enter' }); // When choosing today with a time before the current time, the time should be set to the next available time const nextAvailableTime = getMinScheduleTime(new Date()) ?? new Date(); const nextAvailableTimeFormatted = format(nextAvailableTime, 'p', { locale: enUS }); expect(dateInput.value).toEqual('Today'); expect(timeInput.value).toEqual(nextAvailableTimeFormatted); const laterDate = format(addDays(new Date(Date.now()), 5), 'PP', { locale: enUS }); // set date input to 5 days later fireEvent.change(dateInput, { target: { value: laterDate } }); fireEvent.keyDown(dateInput, { key: 'Enter' }); expect(dateInput.value).toEqual(laterDate); expect(timeInput.value).toEqual(nextAvailableTimeFormatted); dateSpy.mockRestore(); }); it('should disable schedule send button display if date is not valid', async () => { const { composerID } = setupMessage('Subject', [user as Recipient]); setupTest({ hasPaidMail: true }); const dateSpy = jest.spyOn(Date, 'now').mockImplementation(() => new Date().setHours(12).valueOf()); const { getByTestId } = await render(<Composer {...props} composerID={composerID} />, false); const sendActions = getByTestId('composer:send-actions'); const dropdownButton = getByTestIdDefault(sendActions, 'composer:scheduled-send:open-dropdown'); fireEvent.click(dropdownButton); const dropdown = await getDropdown(); const scheduledSendButton = getByTestIdDefault(dropdown, 'composer:schedule-send:custom'); await act(async () => { fireEvent.click(scheduledSendButton); }); const dateInput = getByTestId('composer:schedule-date-input') as HTMLInputElement; const timeInput = getByTestId('composer:schedule-time-input') as HTMLInputElement; const button = getByTestId('modal-footer:set-button') as HTMLButtonElement; // set date input to the past const previousDate = format(addDays(new Date(), -5), 'PP', { locale: enUS }); fireEvent.change(dateInput, { target: { value: previousDate } }); fireEvent.keyDown(dateInput, { key: 'Enter' }); expect(dateInput.value).toEqual(previousDate); expect(timeInput.value).toEqual('8:00 AM'); expect(button.disabled).toBeTruthy(); // set date input too far in the future const laterDate = format(addDays(new Date(), 91), 'PP', { locale: enUS }); fireEvent.change(dateInput, { target: { value: laterDate } }); fireEvent.keyDown(dateInput, { key: 'Enter' }); expect(dateInput.value).toEqual(laterDate); expect(timeInput.value).toEqual('8:00 AM'); expect(button.disabled).toBeTruthy(); // set date input to today, and time in the past const todayDate = format(Date.now(), 'PP', { locale: enUS }); const todayTime = format(addMinutes(new Date(Date.now()), -5), 'p', { locale: enUS }); fireEvent.change(dateInput, { target: { value: todayDate } }); fireEvent.keyDown(dateInput, { key: 'Enter' }); fireEvent.change(timeInput, { target: { value: todayTime } }); fireEvent.keyDown(timeInput, { key: 'Enter' }); expect(dateInput.value).toEqual('Today'); expect(timeInput.value).toEqual(todayTime); expect(button.disabled).toBeTruthy(); dateSpy.mockRestore(); }); });
3,432
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/tests/Composer.sending.test.tsx
import { fireEvent, getByTestId } from '@testing-library/react'; import loudRejection from 'loud-rejection'; import { ROOSTER_EDITOR_ID } from '@proton/components/components/editor/constants'; import { WorkerDecryptionResult } from '@proton/crypto/lib'; import { MIME_TYPES } from '@proton/shared/lib/constants'; import { MailSettings } from '@proton/shared/lib/interfaces'; import { SIGN } from '@proton/shared/lib/mail/mailSettings'; import { arrayToBase64 } from '../../../helpers/base64'; import { addApiContact } from '../../../helpers/test/contact'; import { GeneratedKey, addApiKeys, addKeysToAddressKeysCache, addKeysToUserKeysCache, generateKeys, releaseCryptoProxy, setupCryptoProxyForTesting, } from '../../../helpers/test/crypto'; import { addApiMock, addToCache, clearAll, createAttachment, createDocument, createEmbeddedImage, createMessageImages, decryptMessage, decryptMessageMultipart, decryptSessionKey, minimalCache, readSessionKey, } from '../../../helpers/test/helper'; import { addAttachment } from '../../../logic/attachments/attachmentsActions'; import { store } from '../../../logic/store'; import { ID, clickSend, prepareMessage, renderComposer, send } from './Composer.test.helpers'; loudRejection(); jest.setTimeout(20000); describe('Composer sending', () => { const AddressID = 'AddressID'; const fromAddress = 'me@home.net'; const toAddress = 'someone@somewhere.net'; let fromKeys: GeneratedKey; let secondFromKeys: GeneratedKey; let toKeys: GeneratedKey; beforeAll(async () => { await setupCryptoProxyForTesting(); fromKeys = await generateKeys('me', fromAddress); secondFromKeys = await generateKeys('secondme', fromAddress); toKeys = await generateKeys('someone', toAddress); }); afterAll(async () => { clearAll(); await releaseCryptoProxy(); }); beforeEach(() => { clearAll(); addKeysToAddressKeysCache(AddressID, fromKeys); }); describe('send plaintext', () => { it('text/plain clear', async () => { const { composerID, message } = prepareMessage({ localID: ID, messageDocument: { plainText: 'test' }, data: { MIMEType: MIME_TYPES.PLAINTEXT }, }); addKeysToAddressKeysCache(message.data.AddressID, fromKeys); const sendRequest = await send(composerID); expect(sendRequest.data.ExpirationTime).toBeUndefined(); expect(sendRequest.data.ExpiresIn).toBeUndefined(); const packages = sendRequest.data.Packages; const pack = packages['text/plain']; expect(pack).toBeDefined(); const sessionKey = readSessionKey(pack.BodyKey); const decryptResult = await decryptMessage(pack, fromKeys.privateKeys, sessionKey); expect(decryptResult.data).toBe(message.messageDocument?.plainText); }); it('text/plain self', async () => { const { composerID, message } = prepareMessage({ messageDocument: { plainText: 'test' }, data: { MIMEType: MIME_TYPES.PLAINTEXT, ToList: [{ Name: '', Address: fromAddress }] }, }); minimalCache(); addToCache('Addresses', [ { ID: message.data.AddressID, Email: fromAddress, Receive: 1, HasKeys: true, Keys: [ { Primary: 1, PrivateKey: fromKeys.privateKeyArmored, PublicKey: fromKeys.publicKeyArmored, }, ], }, ]); const sendRequest = await send(composerID, false); expect(sendRequest.data.ExpirationTime).toBeUndefined(); expect(sendRequest.data.ExpiresIn).toBeUndefined(); const packages = sendRequest.data.Packages; const pack = packages['text/plain']; const address = pack.Addresses[fromAddress]; const sessionKey = await decryptSessionKey(address.BodyKeyPacket, fromKeys.privateKeys); expect(sessionKey).toBeDefined(); const decryptResult = await decryptMessage(pack, fromKeys.privateKeys, sessionKey); expect(decryptResult.data).toBe(message.messageDocument?.plainText); }); it('text/plain pgp internal', async () => { const { composerID, message } = prepareMessage({ messageDocument: { plainText: 'test' }, data: { MIMEType: MIME_TYPES.PLAINTEXT }, }); addApiKeys(true, toAddress, [toKeys]); const sendRequest = await send(composerID); expect(sendRequest.data.ExpirationTime).toBeUndefined(); expect(sendRequest.data.ExpiresIn).toBeUndefined(); const packages = sendRequest.data.Packages; const pack = packages['text/plain']; const address = pack.Addresses[toAddress]; const sessionKey = await decryptSessionKey(address.BodyKeyPacket, toKeys.privateKeys); expect(sessionKey).toBeDefined(); const decryptResult = await decryptMessage(pack, toKeys.privateKeys, sessionKey); expect(decryptResult.data).toBe(message.messageDocument?.plainText); }); it('multipart/mixed pgp external', async () => { const { composerID, message } = prepareMessage({ messageDocument: { plainText: 'test' }, data: { MIMEType: MIME_TYPES.PLAINTEXT }, }); addApiKeys(false, toAddress, [toKeys]); const sendRequest = await send(composerID); expect(sendRequest.data.ExpirationTime).toBeUndefined(); expect(sendRequest.data.ExpiresIn).toBeUndefined(); const packages = sendRequest.data.Packages; const pack = packages['multipart/mixed']; const address = pack.Addresses[toAddress]; const sessionKey = await decryptSessionKey(address.BodyKeyPacket, toKeys.privateKeys); expect(sessionKey).toBeDefined(); const decryptResult = await decryptMessageMultipart(pack, toKeys.privateKeys, sessionKey); expect(decryptResult.data).toBe(message.messageDocument?.plainText); expect(decryptResult.mimeType).toBe(message.data.MIMEType); }); it('downgrade to plaintext due to contact setting', async () => { const content = 'test'; const { composerID } = prepareMessage({ messageDocument: { document: createDocument(content) }, data: { MIMEType: MIME_TYPES.DEFAULT }, }); minimalCache(); addToCache('MailSettings', { DraftMIMEType: MIME_TYPES.DEFAULT } as MailSettings); addKeysToUserKeysCache(fromKeys); addApiContact({ contactID: 'ContactID', email: toAddress, mimeType: MIME_TYPES.PLAINTEXT }, fromKeys); const sendRequest = await send(composerID, false); expect(sendRequest.data.ExpirationTime).toBeUndefined(); expect(sendRequest.data.ExpiresIn).toBeUndefined(); const packages = sendRequest.data.Packages; const pack = packages['text/plain']; expect(pack).toBeDefined(); const sessionKey = readSessionKey(pack.BodyKey); const decryptResult = await decryptMessage(pack, fromKeys.privateKeys, sessionKey); expect(decryptResult.data).toBe(content); }); it.skip('downgrade to plaintext and sign', async () => { const content = 'test'; const { composerID } = prepareMessage({ messageDocument: { document: createDocument(content) }, data: { MIMEType: MIME_TYPES.DEFAULT }, }); minimalCache(); addToCache('MailSettings', { DraftMIMEType: MIME_TYPES.DEFAULT, Sign: SIGN.ENABLED } as MailSettings); addApiContact({ contactID: 'ContactID', email: toAddress, mimeType: MIME_TYPES.PLAINTEXT }, fromKeys); const sendRequest = await send(composerID, false); expect(sendRequest.data.ExpirationTime).toBeUndefined(); expect(sendRequest.data.ExpiresIn).toBeUndefined(); const packages = sendRequest.data.Packages; const pack = packages['text/plain']; expect(pack).toBeDefined(); const sessionKey = readSessionKey(pack.BodyKey); const decryptResult = await decryptMessage(pack, fromKeys.privateKeys, sessionKey); expect(decryptResult.data).toBe(content); }); }); describe('send html', () => { it('text/html clear', async () => { const content = 'test'; const { composerID } = prepareMessage({ messageDocument: { document: createDocument(content) }, data: { MIMEType: MIME_TYPES.DEFAULT }, }); minimalCache(); addToCache('MailSettings', { DraftMIMEType: MIME_TYPES.DEFAULT } as MailSettings); const sendRequest = await send(composerID, false); expect(sendRequest.data.ExpirationTime).toBeUndefined(); expect(sendRequest.data.ExpiresIn).toBeUndefined(); const packages = sendRequest.data.Packages; const pack = packages['text/html']; expect(pack).toBeDefined(); const sessionKey = readSessionKey(pack.BodyKey); const decryptResult = await decryptMessage(pack, fromKeys.privateKeys, sessionKey); expect(decryptResult.data).toBe(content); }); it('text/html pgp internal', async () => { const content = 'test'; const { composerID } = prepareMessage({ messageDocument: { document: createDocument(content) }, data: { MIMEType: MIME_TYPES.DEFAULT }, }); minimalCache(); addToCache('MailSettings', { DraftMIMEType: MIME_TYPES.DEFAULT } as MailSettings); addApiKeys(true, toAddress, [toKeys]); const sendRequest = await send(composerID, false); expect(sendRequest.data.ExpirationTime).toBeUndefined(); expect(sendRequest.data.ExpiresIn).toBeUndefined(); const packages = sendRequest.data.Packages; const pack = packages['text/html']; const address = pack.Addresses[toAddress]; const sessionKey = await decryptSessionKey(address.BodyKeyPacket, toKeys.privateKeys); expect(sessionKey).toBeDefined(); const decryptResult = await decryptMessage(pack, toKeys.privateKeys, sessionKey); expect(decryptResult.data).toBe(content); }); it('no downgrade even for default plaintext', async () => { const content = 'test'; const { composerID } = prepareMessage({ messageDocument: { document: createDocument(content) }, data: { MIMEType: MIME_TYPES.DEFAULT }, }); minimalCache(); addToCache('MailSettings', { DraftMIMEType: MIME_TYPES.PLAINTEXT } as MailSettings); addApiKeys(true, toAddress, [toKeys]); const sendRequest = await send(composerID, false); expect(sendRequest.data.ExpirationTime).toBeUndefined(); expect(sendRequest.data.ExpiresIn).toBeUndefined(); const packages = sendRequest.data.Packages; const pack = packages['text/html']; const address = pack.Addresses[toAddress]; const sessionKey = await decryptSessionKey(address.BodyKeyPacket, toKeys.privateKeys); expect(sessionKey).toBeDefined(); const decryptResult = await decryptMessage(pack, toKeys.privateKeys, sessionKey); expect(decryptResult.data).toBe(content); }); it('multipart/mixed pgp external', async () => { const content = 'test'; const document = window.document.createElement('div'); document.innerHTML = content; const { composerID, message } = prepareMessage({ messageDocument: { document }, data: { MIMEType: MIME_TYPES.DEFAULT }, }); minimalCache(); addToCache('MailSettings', { DraftMIMEType: MIME_TYPES.DEFAULT } as MailSettings); addApiKeys(false, toAddress, [toKeys]); const sendRequest = await send(composerID, false); expect(sendRequest.data.ExpirationTime).toBeUndefined(); expect(sendRequest.data.ExpiresIn).toBeUndefined(); const packages = sendRequest.data.Packages; const pack = packages['multipart/mixed']; const address = pack.Addresses[toAddress]; const sessionKey = await decryptSessionKey(address.BodyKeyPacket, toKeys.privateKeys); expect(sessionKey).toBeDefined(); const decryptResult = await decryptMessageMultipart(pack, toKeys.privateKeys, sessionKey); expect(decryptResult.data).toBe(content); expect(decryptResult.mimeType).toBe(message.data.MIMEType); }); }); describe('attachments', () => { it('text/html with attachment', async () => { const content = 'test'; const { attachment, sessionKey: generatedSessionKey } = await createAttachment( { ID: 'AttachmentID', Name: 'image.png', MIMEType: 'image/png', }, fromKeys.publicKeys ); const { composerID } = prepareMessage({ messageDocument: { document: createDocument(content) }, data: { MIMEType: MIME_TYPES.DEFAULT, Attachments: [attachment] }, }); minimalCache(); addToCache('MailSettings', { DraftMIMEType: MIME_TYPES.DEFAULT } as MailSettings); addApiKeys(true, toAddress, [toKeys]); const sendRequest = await send(composerID, false); expect(sendRequest.data.ExpirationTime).toBeUndefined(); expect(sendRequest.data.ExpiresIn).toBeUndefined(); const packages = sendRequest.data.Packages; const pack = packages['text/html']; const address = pack.Addresses[toAddress]; const AttachmentKeyPackets = address.AttachmentKeyPackets[attachment.ID as string]; const sessionKey = await decryptSessionKey(AttachmentKeyPackets, toKeys.privateKeys); expect(arrayToBase64(sessionKey.data)).toBe(arrayToBase64(generatedSessionKey.data)); }); it('multipart/mixed with attachment', async () => { const content = 'test'; const { attachment } = await createAttachment( { ID: 'AttachmentID', Name: 'image.png', MIMEType: 'image/png', data: new Uint8Array(), }, fromKeys.publicKeys ); const { message, composerID } = prepareMessage({ messageDocument: { document: createDocument(content) }, data: { MIMEType: MIME_TYPES.DEFAULT, Attachments: [attachment], }, }); addApiKeys(false, toAddress, [toKeys]); store.dispatch( addAttachment({ ID: attachment.ID as string, attachment: { data: attachment.data } as WorkerDecryptionResult<Uint8Array>, }) ); const sendRequest = await send(composerID); expect(sendRequest.data.ExpirationTime).toBeUndefined(); expect(sendRequest.data.ExpiresIn).toBeUndefined(); const packages = sendRequest.data.Packages; const pack = packages['multipart/mixed']; const address = pack.Addresses[toAddress]; const sessionKey = await decryptSessionKey(address.BodyKeyPacket, toKeys.privateKeys); expect(sessionKey).toBeDefined(); const decryptResult = await decryptMessageMultipart(pack, toKeys.privateKeys, sessionKey); expect(decryptResult.data).toBe(content); expect(decryptResult.mimeType).toBe(message.data.MIMEType); expect(decryptResult.attachments.length).toBe(1); expect(decryptResult.attachments[0].fileName).toBe(attachment.Name); expect(decryptResult.attachments[0].contentType).toBe(attachment.MIMEType); }); it('embedded image', async () => { const cid = 'cid'; const imageUrl = 'https://localhost/some-generated-id'; const { attachment } = await createAttachment( { ID: 'AttachmentID', Name: 'embedded.png', MIMEType: 'image/png', Headers: { 'content-id': cid }, }, fromKeys.publicKeys ); const image = createEmbeddedImage(attachment); const messageImages = createMessageImages([image]); const content = `<img src="${imageUrl}" data-embedded-img="cid:${cid}">`; const document = window.document.createElement('div'); document.innerHTML = content; const { composerID } = prepareMessage({ messageDocument: { document }, messageImages, data: { MIMEType: MIME_TYPES.DEFAULT, Attachments: [attachment] }, }); minimalCache(); addToCache('MailSettings', { DraftMIMEType: MIME_TYPES.DEFAULT } as MailSettings); addApiKeys(true, toAddress, [toKeys]); const sendRequest = await send(composerID, false); expect(sendRequest.data.ExpirationTime).toBeUndefined(); expect(sendRequest.data.ExpiresIn).toBeUndefined(); const packages = sendRequest.data.Packages; const pack = packages['text/html']; const address = pack.Addresses[toAddress]; const sessionKey = await decryptSessionKey(address.BodyKeyPacket, toKeys.privateKeys); expect(sessionKey).toBeDefined(); const decryptResult = await decryptMessage(pack, toKeys.privateKeys, sessionKey); expect(decryptResult.data).toBe(`<img src="cid:${cid}">`); }); }); it('should not encrypt message with multiple keys', async () => { const { message, composerID } = prepareMessage({ messageDocument: { plainText: 'test' }, data: { MIMEType: MIME_TYPES.PLAINTEXT }, }); addKeysToAddressKeysCache(message.data.AddressID, secondFromKeys); addApiKeys(true, toAddress, [toKeys]); const sendRequest = await send(composerID); expect(sendRequest.data.ExpirationTime).toBeUndefined(); expect(sendRequest.data.ExpiresIn).toBeUndefined(); const packages = sendRequest.data.Packages; const pack = packages['text/plain']; const address = pack.Addresses[toAddress]; const sessionKey = await decryptSessionKey(address.BodyKeyPacket, toKeys.privateKeys); const decryptResult = await decryptMessage(pack, toKeys.privateKeys, sessionKey); // Having 2 signatures here would meen we used both private keys to encrypt // It's not "wrong", it works with OpenPGP and API accept it // But other clients (Android, iOS, Bridge) don't support it so it's critical to use only one key expect(decryptResult.signatures.length).toBe(1); }); it('should ensure rooster content before sending', async () => { const triggerEditorInput = (container: HTMLElement, content: string) => { const iframe = getByTestId(container, 'rooster-iframe') as HTMLIFrameElement; const editor = iframe.contentDocument?.getElementById(ROOSTER_EDITOR_ID); if (editor) { editor.innerHTML = content; fireEvent.input(editor); } }; const content = 'test'; const editorContent = 'editor-test'; const { composerID } = prepareMessage({ messageDocument: { document: createDocument(content) }, data: { MIMEType: MIME_TYPES.DEFAULT }, }); minimalCache(); addToCache('MailSettings', { DraftMIMEType: MIME_TYPES.DEFAULT } as MailSettings); addApiKeys(false, toAddress, []); const renderResult = await renderComposer(composerID, false); triggerEditorInput(renderResult.container, editorContent); addApiMock(`mail/v4/messages/${ID}`, ({ data: { Message } }) => ({ Message }), 'put'); const sendRequest = await clickSend(renderResult); const packages = sendRequest.data.Packages; const pack = packages['text/html']; const sessionKey = readSessionKey(pack.BodyKey); const decryptResult = await decryptMessage(pack, fromKeys.privateKeys, sessionKey); expect(decryptResult.data).toBe(editorContent); }); });
3,433
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/tests/Composer.test.helpers.tsx
import { act } from 'react-dom/test-utils'; import { RenderResult, fireEvent } from '@testing-library/react'; import { pick } from '@proton/shared/lib/helpers/object'; import { wait } from '@proton/shared/lib/helpers/promise'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { mergeMessages } from '../../../helpers/message/messages'; import { addApiKeys, addApiMock, apiKeys, parseFormData, render, tick, waitForNoNotification, waitForNotification, } from '../../../helpers/test/helper'; import { EditorTypes } from '../../../hooks/composer/useComposerContent'; import { composerActions } from '../../../logic/composers/composersSlice'; import { MessageStateWithData, PartialMessageState } from '../../../logic/messages/messagesTypes'; import { initialize } from '../../../logic/messages/read/messagesReadActions'; import { store } from '../../../logic/store'; import { Breakpoints } from '../../../models/utils'; import Composer from '../Composer'; // Fake timers fails for the complexe send action // These more manual trick is used to skip undo timing jest.mock('@proton/shared/lib/helpers/promise', () => { return { wait: jest.fn(() => { return Promise.resolve(); }), }; }); export const ID = 'ID'; export const AddressID = 'AddressID'; export const fromAddress = 'me@home.net'; export const toAddress = 'someone@somewhere.net'; export const props = { composerID: 'ComposerID', messageID: ID, composerFrameRef: { current: document.body as HTMLDivElement }, breakpoints: {} as Breakpoints, onFocus: jest.fn(), onClose: jest.fn(), onCompose: jest.fn(), toggleMinimized: jest.fn(), toggleMaximized: jest.fn(), onSubject: jest.fn(), isFocused: true, minimizeButtonRef: { current: null }, }; export const prepareMessage = (messageProp: PartialMessageState) => { const baseMessage = { localID: 'localID', data: { ID, AddressID, Subject: 'Subject', Sender: { Name: '', Address: fromAddress }, ToList: [{ Name: '', Address: toAddress }], CCList: [], BCCList: [], Attachments: [], } as Partial<Message>, messageDocument: { initialized: true, }, } as MessageStateWithData; const message = mergeMessages(baseMessage, messageProp) as MessageStateWithData; store.dispatch(initialize(message)); store.dispatch( composerActions.addComposer({ messageID: message.localID, type: EditorTypes.composer, senderEmailAddress: message.data?.Sender?.Address || '', recipients: message.data ? pick(message.data, ['ToList', 'CCList', 'BCCList']) : { BCCList: [], CCList: [], ToList: [] }, status: 'idle', }) ); const composerID = Object.keys(store.getState().composers.composers)[0]; return { message, composerID }; }; export const renderComposer = async (composerID: string, useMinimalCache = true) => { const renderResult = await render(<Composer {...props} composerID={composerID} />, useMinimalCache); // onClose will most likely unmount the component, it has to continue working props.onClose.mockImplementation(renderResult.unmount); return renderResult; }; export const clickSend = async (renderResult: RenderResult) => { const sendSpy = jest.fn(() => Promise.resolve({ Sent: {} })); addApiMock(`mail/v4/messages/${ID}`, sendSpy, 'post'); addApiMock(`mail/v4/messages/${ID}`, () => {}, 'get'); addApiMock(`mail/v4/messages/${ID}`, ({ data: { Message } }) => ({ Message }), 'put'); const sendButton = await renderResult.findByTestId('composer:send-button'); fireEvent.click(sendButton); await waitForNotification('Message sent'); const sendRequest = (sendSpy.mock.calls[0] as any[])[0]; expect(sendRequest.method).toBe('post'); await waitForNoNotification(); sendRequest.data = parseFormData(sendRequest.data); return sendRequest; }; export const send = async (composerID: string, useMinimalCache = true) => { try { if (!apiKeys.has(toAddress)) { addApiKeys(false, toAddress, []); } const renderResult = await renderComposer(composerID, useMinimalCache); return await clickSend(renderResult); } catch (error: any) { console.log('Error in sending helper', error); throw error; } }; export const saveNow = async (container: HTMLElement) => { fireEvent.keyDown(container, { key: 's', ctrlKey: true }); await tick(); // Mandatory to wait on every consequence of the change before starting another test // Definitely not proud of this, any better suggestion is welcomed await act(async () => { await wait(3000); }); };
3,434
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/composer/tests/Composer.verifySender.test.tsx
import { getByText as getByTextDefault } from '@testing-library/react'; import loudRejection from 'loud-rejection'; import { MIME_TYPES } from '@proton/shared/lib/constants'; import { Address, Recipient } from '@proton/shared/lib/interfaces'; import { addToCache, minimalCache } from '../../../helpers/test/cache'; import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../helpers/test/crypto'; import { GeneratedKey, addApiKeys, addApiMock, addKeysToAddressKeysCache, clearAll, generateKeys, render, } from '../../../helpers/test/helper'; import { messageID } from '../../message/tests/Message.test.helpers'; import Composer from '../Composer'; import { ID, prepareMessage, props, saveNow, toAddress } from './Composer.test.helpers'; loudRejection(); const name1 = 'Address 1'; const name2 = 'Address 2'; const address1 = 'address1@protonmail.com'; const address2 = 'address2@protonmail.com'; const addressID1 = 'AddressID1'; const addressID2 = 'AddressID2'; const addresses: Address[] = [ { DisplayName: name1, Email: address1, ID: addressID1, Send: 1, Receive: 1, Status: 1, Order: 1, } as Address, { DisplayName: name2, Email: address2, ID: addressID2, Send: 0, Receive: 0, Status: 0, Order: 2, } as Address, ]; const user = { Email: address1, DisplayName: name1, Name: name1, hasPaidMail: true, UsedSpace: 10, MaxSpace: 100, }; describe('Composer verify sender', () => { let fromKeys: GeneratedKey; beforeAll(async () => { await setupCryptoProxyForTesting(); fromKeys = await generateKeys('me', address1); }); afterAll(async () => { clearAll(); await releaseCryptoProxy(); }); beforeEach(() => { clearAll(); addKeysToAddressKeysCache(addressID1, fromKeys); }); const setup = (sender: Recipient) => { minimalCache(); addToCache('Addresses', addresses); addToCache('User', user); addApiKeys(false, toAddress, []); addApiKeys(false, sender.Address, []); const { composerID } = prepareMessage({ localID: ID, data: { ID: messageID, MIMEType: MIME_TYPES.PLAINTEXT, Sender: sender, Flags: 12, }, draftFlags: { isSentDraft: false, openDraftFromUndo: false }, messageDocument: { plainText: '' }, }); return composerID; }; it('should display the sender address if the address is valid', async () => { const sender = { Name: name1, Address: address1 } as Recipient; const composerID = setup(sender); const { findByTestId } = await render(<Composer {...props} composerID={composerID} />, false); const fromField = await findByTestId('composer:from'); getByTextDefault(fromField, address1); }); it('should display a modal and switch to default address when address is disabled', async () => { addApiMock(`mail/v4/messages/${messageID}`, () => ({})); const sender = { Name: name2, Address: address2 } as Recipient; const composerID = setup(sender); const { findByTestId, getByText, container } = await render( <Composer {...props} composerID={composerID} />, false ); await saveNow(container); // Sender is invalid, so we should see a modal getByText('Sender changed'); // Then, the from field must have been replaced by the default address const fromField = await findByTestId('composer:from'); getByTextDefault(fromField, address1); }); it("should display a modal and switch to default address when address does not exist in user's addresses", async () => { addApiMock(`mail/v4/messages/${messageID}`, () => ({})); const sender = { Name: 'Address 3', Address: 'address3@protonmail.com' } as Recipient; const composerID = setup(sender); const { findByTestId, container, getByText } = await render( <Composer {...props} composerID={composerID} />, false ); await saveNow(container); // Sender is invalid, so we should see a modal getByText('Sender changed'); // Then, the from field must have been replaced by the default address const fromField = await findByTestId('composer:from'); getByTextDefault(fromField, address1); }); });
3,435
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/conversation/ConversationErrorBanner.tsx
import { forwardRef } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Icon } from '@proton/components'; import { hasError } from '../../helpers/errors'; import { ConversationErrors } from '../../logic/conversations/conversationsTypes'; const getTranslations = (key: keyof ConversationErrors) => { switch (key) { case 'network': return c('Error').t`Network error: Please check your connection and try again.`; default: return c('Error').t`Unknown error.`; } }; interface Props { errors: ConversationErrors | undefined; onRetry: () => void; } const ConversationErrorBanner = ({ errors = {}, onRetry }: Props, ref: React.Ref<HTMLDivElement>) => { if (!hasError(errors)) { return null; } const errorType = (Object.keys(errors) as (keyof ConversationErrors)[]).filter((type) => errors?.[type]?.length)[0]; return ( <div ref={ref} tabIndex={-1} className="bg-danger rounded p-2 m-4 flex flex-nowrap flex-align-items-center" data-shortcut-target="trash-warning" > <Icon name="exclamation-circle" className="mr-4" /> <span className="px-2 flex-item-fluid">{getTranslations(errorType)}</span> <span className="flex-item-noshrink flex"> <Button size="small" onClick={onRetry} data-testid="conversation-view:error-banner-button"> {c('Action').t`Try again`} </Button> </span> </div> ); }; export default forwardRef(ConversationErrorBanner);
3,436
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/conversation/ConversationHeader.tsx
import { useMemo } from 'react'; import clsx from '@proton/utils/clsx'; import { useEncryptedSearchContext } from '../../containers/EncryptedSearchProvider'; import { isConversation as testIsConversation } from '../../helpers/elements'; import { Element } from '../../models/element'; import NumMessages from './NumMessages'; interface Props { className?: string; loading: boolean; element?: Element; } const ConversationHeader = ({ className, loading, element }: Props) => { const { highlightMetadata, shouldHighlight } = useEncryptedSearchContext(); const highlightSubject = shouldHighlight(); const isConversation = testIsConversation(element); const subjectElement = useMemo( () => !!element?.Subject && highlightSubject ? ( highlightMetadata(element.Subject, true).resultJSX ) : ( <span>{element?.Subject}</span> ), [element, highlightSubject] ); return ( <header className={clsx([ 'max-w-full message-conversation-summary upper-layer pt-5 pb-2 px-2 mx-4 flex-item-noshrink', loading && 'message-conversation-summary-is-loading', className, ])} data-shortcut-target="message-conversation-summary" data-testid="conversation-header" > <div className="flex flex-nowrap"> <h1 className={clsx([ 'message-conversation-summary-header my-0 h3 text-bold text-ellipsis-two-lines lh-rg flex-item-fluid', ])} title={element?.Subject} data-testid="conversation-header:subject" > {!loading ? ( <> {isConversation && <NumMessages className="mr-1" conversation={element} />} {subjectElement} </> ) : ( <>&nbsp;</> )} </h1> </div> </header> ); }; export default ConversationHeader;
3,437
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/conversation/ConversationView.test.tsx
import { fireEvent, waitFor } from '@testing-library/react'; import { act } from '@testing-library/react'; import { wait } from '@proton/shared/lib/helpers/promise'; import { MailSettings } from '@proton/shared/lib/interfaces'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import range from '@proton/utils/range'; import { addApiKeys, addApiMock, assertFocus, clearAll, mockConsole, render, tick } from '../../helpers/test/helper'; import { initialize as initializeConversation, updateConversation, } from '../../logic/conversations/conversationsActions'; import { ConversationState } from '../../logic/conversations/conversationsTypes'; import * as messageDraftActions from '../../logic/messages/draft/messagesDraftActions'; import { initialize as initializeMessage } from '../../logic/messages/read/messagesReadActions'; import { store } from '../../logic/store'; import { Conversation } from '../../models/conversation'; import { Breakpoints } from '../../models/utils'; import ConversationView from './ConversationView'; jest.setTimeout(20000); describe('ConversationView', () => { const props = { hidden: false, labelID: 'labelID', conversationID: 'conversationID', mailSettings: {} as MailSettings, onBack: jest.fn(), onCompose: jest.fn(), breakpoints: {} as Breakpoints, onMessageReady: jest.fn(), columnLayout: true, isComposerOpened: false, containerRef: { current: null }, elementIDs: ['conversationID'], loadingElements: false, conversationMode: true, }; const conversation = { ID: props.conversationID, Subject: 'conversation subject', } as Conversation; const message = { ID: 'messageID', Subject: 'message subject', Sender: {}, Attachments: [] as any, } as Message; const conversationState = { Conversation: conversation, Messages: [message], loadRetry: 0, errors: {}, } as ConversationState; const setup = async () => { const result = await render(<ConversationView {...props} />); const rerender = (newProps: Partial<typeof props> = {}) => result.rerender(<ConversationView {...props} {...newProps} />); const messageElements = result.container.querySelectorAll<HTMLElement>( '[data-shortcut-target="message-container"]' ); const message = messageElements[0]; return { ...result, rerender, messageElements, left: () => fireEvent.keyDown(message, { key: 'ArrowLeft' }), down: () => fireEvent.keyDown(messageElements[0], { key: 'ArrowDown' }), ctrlDown: () => fireEvent.keyDown(messageElements[0], { key: 'ArrowDown', ctrlKey: true }), up: () => fireEvent.keyDown(messageElements[0], { key: 'ArrowUp' }), ctrlUp: () => fireEvent.keyDown(messageElements[0], { key: 'ArrowUp', ctrlKey: true }), enter: () => fireEvent.keyDown(messageElements[0], { key: 'Enter' }), }; }; beforeEach(clearAll); afterEach(() => { jest.useRealTimers(); }); describe('Store / State management', () => { it('should return store value', async () => { store.dispatch(initializeConversation(conversationState)); store.dispatch(initializeMessage({ localID: message.ID, data: message })); const { getByText } = await setup(); getByText(conversation.Subject as string); }); it('should update value if store is updated', async () => { store.dispatch(initializeConversation(conversationState)); store.dispatch(initializeMessage({ localID: message.ID, data: message })); const { getByText, rerender } = await setup(); getByText(conversation.Subject as string); const newSubject = 'other subject'; store.dispatch( updateConversation({ ID: conversation.ID, updates: { Conversation: { Subject: newSubject, ID: conversation.ID } }, }) ); await rerender(); getByText(newSubject); }); it('should launch api request when needed', async () => { const response = { Conversation: conversation, Messages: [message] }; addApiMock(`mail/v4/conversations/${conversation.ID}`, () => response); const { getByText } = await setup(); getByText(conversation.Subject as string); }); it('should change conversation when id change', async () => { const conversation2 = { ID: 'conversationID2', Subject: 'other conversation subject' } as Conversation; const conversationState2 = { Conversation: conversation2, Messages: [message], loadRetry: 0, errors: {}, } as ConversationState; store.dispatch(initializeConversation(conversationState)); store.dispatch(initializeConversation(conversationState2)); const { getByText, rerender } = await setup(); getByText(conversation.Subject as string); await rerender({ conversationID: conversation2.ID }); getByText(conversation2.Subject as string); }); it('should reorder by date when old conversation draft is sent', async () => { const conversationID = 'conversationID'; const makeMessage = (title: string, time: number): Message => ({ ID: title, Subject: title, Time: time, Sender: { Name: title, Address: `${title.replaceAll(' ', '')}@test.fr` }, Attachments: [] as any, Flags: {}, ConversationID: conversationID, } as Message); const conversationState = { Conversation: { ID: conversationID, Subject: 'a subject' }, Messages: [ makeMessage('test-message 1', new Date('2020-01-01').getTime()), makeMessage('test-message 2', new Date('2020-01-02').getTime()), makeMessage('test-message 3', new Date('2020-01-03').getTime()), ], loadRetry: 0, errors: {}, }; store.dispatch(initializeConversation(conversationState as ConversationState)); conversationState.Messages.forEach((message) => { store.dispatch(initializeMessage({ localID: message.ID, data: message })); }); const { getAllByText } = await setup(); const elements = getAllByText('test-message', { exact: false }); expect(elements[0].textContent).toContain('test-message 1'); expect(elements[1].textContent).toContain('test-message 2'); expect(elements[2].textContent).toContain('test-message 3'); // Consider message 2 is a draft and user sends it later store.dispatch(messageDraftActions.sent(makeMessage('test-message 2', new Date('2020-01-04').getTime()))); // Wait for react to reflect store update await wait(50); // List order should change after draft is sent because of the date change const elementsReordered = getAllByText('test-message ', { exact: false }); expect(elementsReordered[0].textContent).toContain('test-message 1'); expect(elementsReordered[1].textContent).toContain('test-message 3'); expect(elementsReordered[2].textContent).toContain('test-message 2'); }); }); describe('Auto reload', () => { const waitForSpyCalls = (spy: jest.Mock, count: number) => waitFor( () => { expect(spy).toBeCalledTimes(count); }, { timeout: 20000 } ); it('should reload a conversation if first request failed', async () => { jest.useFakeTimers(); mockConsole(); const response = { Conversation: conversation, Messages: [message] }; const getSpy = jest.fn(() => { if (getSpy.mock.calls.length === 1) { const error = new Error(); error.name = 'NetworkError'; throw error; } return response; }); addApiMock(`mail/v4/conversations/${conversation.ID}`, getSpy); const { getByTestId, getByText, rerender } = await setup(); const header = getByTestId('conversation-header') as HTMLHeadingElement; expect(header.getAttribute('class')).toContain('is-loading'); jest.advanceTimersByTime(5000); await waitForSpyCalls(getSpy, 2); await rerender(); expect(header.getAttribute('class')).not.toContain('is-loading'); getByText(conversation.Subject as string); expect(getSpy).toHaveBeenCalledTimes(2); jest.runAllTimers(); }); it('should show error banner after 4 attemps', async () => { jest.useFakeTimers(); mockConsole(); const getSpy = jest.fn(() => { const error = new Error(); error.name = 'NetworkError'; throw error; }); addApiMock(`mail/v4/conversations/${conversation.ID}`, getSpy); const { getByText } = await setup(); await act(async () => { jest.advanceTimersByTime(5000); await waitForSpyCalls(getSpy, 2); jest.advanceTimersByTime(5000); await waitForSpyCalls(getSpy, 3); jest.advanceTimersByTime(5000); await waitForSpyCalls(getSpy, 4); }); getByText('Network error', { exact: false }); getByText('Try again'); expect(getSpy).toHaveBeenCalledTimes(4); jest.runAllTimers(); }); it('should retry when using the Try again button', async () => { const conversationState = { Conversation: { ID: conversation.ID }, Messages: [], loadRetry: 4, errors: { network: [new Error()] }, } as ConversationState; store.dispatch(initializeConversation(conversationState)); const response = { Conversation: conversation, Messages: [message] }; addApiMock(`mail/v4/conversations/${conversation.ID}`, () => response); const { getByText, rerender } = await setup(); const tryAgain = getByText('Try again'); fireEvent.click(tryAgain); await rerender(); getByText(conversation.Subject as string); }); }); describe('Hotkeys', () => { it('should focus item container on left', async () => { store.dispatch(initializeConversation(conversationState)); const TestComponent = (props: any) => { return ( <> <div data-shortcut-target="item-container" tabIndex={-1}> item container test </div> <ConversationView {...props} /> </> ); }; const { container } = await render(<TestComponent {...props} />); const itemContainer = container.querySelector('[data-shortcut-target="item-container"]'); const firstMessage = container.querySelector('[data-shortcut-target="message-container"]') as HTMLElement; fireEvent.keyDown(firstMessage, { key: 'ArrowLeft' }); assertFocus(itemContainer); }); it('should navigate through messages with up and down', async () => { const messages = range(0, 10).map( (i) => ({ ID: `messageID${i}`, Subject: `message subject ${i}`, } as Message) ); const conversationState = { Conversation: conversation, Messages: messages, loadRetry: 0, errors: {}, } as ConversationState; store.dispatch(initializeConversation(conversationState)); const { messageElements, down, ctrlDown, up, ctrlUp } = await setup(); const isFocused = (element: HTMLElement) => element.dataset.hasfocus === 'true'; down(); expect(isFocused(messageElements[0])).toBe(true); down(); expect(isFocused(messageElements[1])).toBe(true); down(); expect(isFocused(messageElements[2])).toBe(true); up(); expect(isFocused(messageElements[1])).toBe(true); up(); expect(isFocused(messageElements[0])).toBe(true); ctrlDown(); expect(isFocused(messageElements[9])).toBe(true); ctrlUp(); expect(isFocused(messageElements[0])).toBe(true); }); it('should open a message on enter', async () => { const senderEmail = 'sender@email.com'; addApiKeys(false, senderEmail, []); store.dispatch(initializeConversation(conversationState)); const messageMock = jest.fn(() => ({ Message: { ID: message.ID, Attachments: [], Sender: { Name: '', Address: senderEmail } }, })); addApiMock(`mail/v4/messages/${message.ID}`, messageMock); const { down, enter } = await setup(); down(); enter(); await tick(); expect(messageMock).toHaveBeenCalled(); }); }); });
3,438
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/conversation/ConversationView.tsx
import { RefObject, memo, useEffect, useRef } from 'react'; import { useDispatch } from 'react-redux'; import { Scroll } from '@proton/atoms'; import { useLabels, useToggle } from '@proton/components'; import { isEditing } from '@proton/shared/lib/busy'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { MailSettings } from '@proton/shared/lib/interfaces'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { isDraft } from '@proton/shared/lib/mail/messages'; import clsx from '@proton/utils/clsx'; import { useEncryptedSearchContext } from '../../containers/EncryptedSearchProvider'; import { hasLabel } from '../../helpers/elements'; import { findMessageToExpand } from '../../helpers/message/messageExpandable'; import { MARK_AS_STATUS, useMarkAs } from '../../hooks/actions/useMarkAs'; import { useConversation } from '../../hooks/conversation/useConversation'; import { useConversationFocus } from '../../hooks/conversation/useConversationFocus'; import { useConversationHotkeys } from '../../hooks/conversation/useConversationHotkeys'; import { useGetMessage } from '../../hooks/message/useMessage'; import { usePlaceholders } from '../../hooks/usePlaceholders'; import useShouldMoveOut from '../../hooks/useShouldMoveOut'; import { removeAllQuickReplyFlags } from '../../logic/messages/draft/messagesDraftActions'; import { isElementReminded } from '../../logic/snoozehelpers'; import { Breakpoints } from '../../models/utils'; import MessageView, { MessageViewRef } from '../message/MessageView'; import ConversationErrorBanner from './ConversationErrorBanner'; import ConversationHeader from './ConversationHeader'; import TrashWarning from './TrashWarning'; import UnreadMessages from './UnreadMessages'; const { TRASH, ALL_MAIL } = MAILBOX_LABEL_IDS; interface Props { hidden: boolean; labelID: string; conversationID: string; messageID?: string; mailSettings: MailSettings; onBack: () => void; breakpoints: Breakpoints; onMessageReady: () => void; columnLayout: boolean; isComposerOpened: boolean; containerRef: RefObject<HTMLElement>; loadingElements: boolean; elementIDs: string[]; conversationMode: boolean; } const DEFAULT_FILTER_VALUE = true; const ConversationView = ({ hidden, labelID, conversationID: inputConversationID, messageID, mailSettings, onBack, breakpoints, onMessageReady, columnLayout, isComposerOpened, containerRef, loadingElements, elementIDs, conversationMode, }: Props) => { const dispatch = useDispatch(); const getMessage = useGetMessage(); const { isSearchResult } = useEncryptedSearchContext(); const [labels = []] = useLabels(); const { conversationID, conversation: conversationState, loadingConversation, loadingMessages, handleRetry, } = useConversation(inputConversationID, messageID); const { state: filter, toggle: toggleFilter, set: setFilter } = useToggle(DEFAULT_FILTER_VALUE); useShouldMoveOut({ elementIDs, elementID: conversationMode ? conversationID : messageID, loadingElements, onBack, }); const messageViewsRefs = useRef({} as { [messageID: string]: MessageViewRef | undefined }); const wrapperRef = useRef<HTMLDivElement>(null); const { Conversation: conversation, Messages: inputMessages = [] } = conversationState || {}; const messages = usePlaceholders(inputMessages, loadingMessages, conversation?.NumMessages || 1) as Message[]; const inTrash = labelID === TRASH; const inAllMail = labelID === ALL_MAIL; const filteredMessages = messages.filter( (message) => inAllMail || inTrash === hasLabel(message, TRASH) || isSearchResult(message.ID) ); const messagesToShow = !loadingMessages && filter ? filteredMessages : messages; const messagesWithoutQuickReplies = messagesToShow .filter((message) => { const messageFromState = getMessage(message.ID); return !messageFromState?.draftFlags?.isQuickReply; }) .sort((a, b) => a.Time - b.Time); const showTrashWarning = !loadingMessages && filteredMessages.length !== messages.length; const messageInUrl = conversationState?.Messages?.find((message) => message.ID === messageID); const loading = loadingConversation || loadingMessages; const showConversationError = !loading && conversationState?.Conversation?.Subject === undefined; const showMessagesError = !loading && !showConversationError && !conversationState?.Messages; const markAs = useMarkAs(); const { focusIndex, handleFocus, handleScrollToMessage, handleBlur, getFocusedId } = useConversationFocus(messagesWithoutQuickReplies); const expandMessage = (messageID: string | undefined, scrollTo = false) => { messageViewsRefs.current[messageID || '']?.expand(); const index = messagesToShow.findIndex((message) => message.ID === messageID); // isEditing is used to prevent the focus to be set on the message when the user is editing, otherwise it triggers shortcuts if (index !== undefined && !isEditing()) { handleFocus(index, { scrollTo }); } }; const { elementRef } = useConversationHotkeys( { messages: messagesWithoutQuickReplies, focusIndex }, { handleFocus, getFocusedId, expandMessage } ); // Open the first message of a conversation if none selected in URL useEffect(() => { if (!loadingMessages && !messageID) { expandMessage(findMessageToExpand(labelID, messagesWithoutQuickReplies)?.ID); } }, [conversationID, messageID, loadingMessages]); // Open the message in URL useEffect(() => { if (!loadingMessages && messageID && !isDraft(messageInUrl)) { expandMessage(messageID, true); } }, [conversationID, messageID, loadingMessages, messageInUrl]); useEffect(() => { setFilter(DEFAULT_FILTER_VALUE); }, [inputConversationID]); useEffect(() => { // When the user is switching conversation we need to remove potential quick replies draft flags dispatch(removeAllQuickReplyFlags()); }, [conversationID]); // Mark conversation as read when opened and reminded (snooze feature) useEffect(() => { const isReminded = isElementReminded(conversation); if (isReminded && conversation) { markAs([conversation], labelID, MARK_AS_STATUS.READ); } }, [conversation]); const handleOpenQuickReply = (messageIndex?: number) => { handleScrollToMessage(messageIndex, 'end'); }; const handleClickUnread = (messageID: string) => { expandMessage(messageID); }; const trashWarningRef = useRef<HTMLDivElement>(null); const onlyTrashInConversation = !loadingMessages && !filteredMessages.length; useEffect(() => { if (onlyTrashInConversation) { // unblock J/K shortcuts setTimeout(onMessageReady); if (!columnLayout) { trashWarningRef.current?.parentElement?.focus(); } } }, [onlyTrashInConversation, conversationID, columnLayout]); return showConversationError ? ( <ConversationErrorBanner errors={conversationState?.errors} onRetry={handleRetry} /> ) : ( <Scroll className={clsx([hidden && 'hidden'])} customContainerRef={containerRef}> <ConversationHeader className={clsx([hidden && 'hidden'])} loading={loadingConversation} element={conversation} /> <div ref={wrapperRef} className="flex-item-fluid px-4 w-full"> <div className="outline-none" ref={elementRef} tabIndex={-1}> {showMessagesError ? ( <ConversationErrorBanner errors={conversationState?.errors} onRetry={handleRetry} /> ) : null} {showTrashWarning && ( <TrashWarning ref={trashWarningRef} inTrash={inTrash} filter={filter} onToggle={toggleFilter} /> )} {messagesWithoutQuickReplies.map((message, index) => ( <MessageView key={message.ID} ref={(ref) => { messageViewsRefs.current[message.ID] = ref || undefined; }} labelID={labelID} conversationMode loading={loadingMessages} message={message} labels={labels} mailSettings={mailSettings} conversationIndex={index} conversationID={conversationID} onBack={onBack} breakpoints={breakpoints} onFocus={handleFocus} onBlur={handleBlur} hasFocus={index === focusIndex} onMessageReady={onMessageReady} columnLayout={columnLayout} isComposerOpened={isComposerOpened} containerRef={containerRef} wrapperRef={wrapperRef} onOpenQuickReply={handleOpenQuickReply} /> ))} </div> </div> <UnreadMessages conversationID={conversationID} messages={conversationState?.Messages} onClick={handleClickUnread} /> </Scroll> ); }; export default memo(ConversationView);
3,439
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/conversation/NumMessages.scss
@import '~@proton/styles/scss/lib'; .number-elements { block-size: 1.5em; border: 1px solid; .message-conversation-summary-header & { font-size: em(16, 20); // we want 16 in an element with 20 } }
3,440
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/conversation/NumMessages.tsx
import { c, msgid } from 'ttag'; import { Conversation } from '../../models/conversation'; import './NumMessages.scss'; interface Props { conversation: Conversation | undefined; className?: string; } const NumMessages = ({ conversation, className }: Props) => { // ContextNumMessages should not be used const { NumMessages = 0 } = conversation || {}; if (NumMessages <= 1) { return null; } return ( <> <span className={className} aria-hidden="true"> [{NumMessages}] </span> <span className="sr-only"> {c('Info').ngettext( msgid`${NumMessages} message in conversation`, `${NumMessages} messages in conversation`, NumMessages )} </span> </> ); }; export default NumMessages;
3,441
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/conversation/TrashWarning.tsx
import { forwardRef } from 'react'; import * as React from 'react'; import { c } from 'ttag'; import { Icon, InlineLinkButton, useHotkeys } from '@proton/components'; interface Props { inTrash: boolean; filter: boolean; onToggle: () => void; } const TrashWarning = ({ inTrash, filter, onToggle }: Props, ref: React.Ref<HTMLDivElement>) => { useHotkeys(ref as React.RefObject<HTMLDivElement>, [ [ 'Enter', (e) => { e.stopPropagation(); onToggle(); }, ], [ 'ArrowDown', (e) => { e.stopPropagation(); const messages = document.querySelectorAll('[data-shortcut-target="message-container"]'); if (messages.length) { const firstMessage = messages[0] as HTMLElement; firstMessage.focus(); } }, ], ]); return ( <div ref={ref} tabIndex={0} className="border rounded m-2 mb-4 p-4 flex flex-nowrap flex-align-items-center flex-justify-space-between trashed-messages outline-none" data-shortcut-target="trash-warning" > <div className="flex flex-nowrap flex-align-items-center"> <Icon name="trash" className="mr-4 flex-item-noshrink" /> <span> {inTrash ? c('Info').t`This conversation contains non-trashed messages.` : c('Info').t`This conversation contains trashed messages.`} </span> </div> <InlineLinkButton onClick={onToggle} className="ml-2 text-underline" data-testid="conversation-view:toggle-trash-messages-button" > {inTrash ? filter ? c('Action').t`Show messages` : c('Action').t`Hide messages` : filter ? c('Action').t`Show messages` : c('Action').t`Hide messages`} </InlineLinkButton> </div> ); }; export default forwardRef(TrashWarning);
3,442
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/conversation/UnreadMessages.tsx
import { useEffect, useState } from 'react'; import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms'; import { Icon } from '@proton/components'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { isUnread } from '../../helpers/elements'; interface Props { conversationID: string; messages?: Message[]; onClick: (messageID: string) => void; } const UnreadMessages = ({ conversationID, messages, onClick }: Props) => { const [count, setCount] = useState(0); const [initials, setInitials] = useState(messages); const newUnreads = () => { if (initials === undefined || messages === undefined) { return []; } const initialsIDs = initials.map((message) => message.ID); return messages .filter((message) => !initialsIDs.includes(message.ID)) .filter((message) => isUnread(message, undefined)); }; // Reset initials if conversation changed useEffect(() => { setInitials(messages); }, [conversationID]); // Reset initials if messages are loaded useEffect(() => { if (initials === undefined && Array.isArray(messages)) { setInitials(messages); } }, [messages]); // Update unreads count useEffect(() => setCount(newUnreads().length)); // No deps not to miss unread change status on newUnreads if (count === 0) { return null; } const handleClick = () => onClick(newUnreads()[0].ID); const text = c('Info').ngettext(msgid`${count} unread message`, `${count} unread messages`, count); return ( <span className="absolute absolute-center-x bottom pb-4" aria-live="assertive" aria-atomic="true"> <Button pill color="norm" className="flex flex-nowrap flex-align-items-center conversation-unread-messages" onClick={handleClick} data-testid="conversation-view:view-new-unread-message" > <span>{text}</span> <Icon name="arrow-down" className="ml-2" /> </Button> </span> ); }; export default UnreadMessages;
3,443
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/drawer/MailQuickSettings.tsx
import { useMemo } from 'react'; import { c } from 'ttag'; import { Icon, IconName, Info, Option, SelectTwo, Tooltip, useModalState } from '@proton/components/components'; import { DefaultQuickSettings, QuickSettingsButton, QuickSettingsButtonSection, QuickSettingsMain, QuickSettingsSection, QuickSettingsSectionRow, } from '@proton/components/components/drawer/views/quickSettings'; import DrawerAllSettingsView from '@proton/components/components/drawer/views/quickSettings/DrawerAllSettingsView'; import { KeyTransparencyDetailsModal } from '@proton/components/components/keyTransparency'; import { MailShortcutsModal, useKeyTransparencyContext } from '@proton/components/containers'; import ShortcutsToggle from '@proton/components/containers/general/ShortcutsToggle'; import { useApi, useEventManager, useNotifications, useUserSettings } from '@proton/components/hooks'; import useKeyTransparencyNotification from '@proton/components/hooks/useKeyTransparencyNotification'; import { useLoading } from '@proton/hooks'; import { updateComposerMode, updateViewLayout } from '@proton/shared/lib/api/mailSettings'; import { updateDensity } from '@proton/shared/lib/api/settings'; import { DENSITY, MAIL_APP_NAME } from '@proton/shared/lib/constants'; import { KEY_TRANSPARENCY_REMINDER_UPDATE, QuickSettingsReminders } from '@proton/shared/lib/drawer/interfaces'; import { isFirefox } from '@proton/shared/lib/helpers/browser'; import { KeyTransparencyActivation } from '@proton/shared/lib/interfaces'; import { COMPOSER_MODE, VIEW_LAYOUT } from '@proton/shared/lib/mail/mailSettings'; import isTruthy from '@proton/utils/isTruthy'; import OnboardingChecklistModal from 'proton-mail/components/header/OnboardingChecklistModal'; import { useGetStartedChecklist } from 'proton-mail/containers/onboardingChecklist/provider/GetStartedChecklistProvider'; import useMailModel from 'proton-mail/hooks/useMailModel'; import { useEncryptedSearchContext } from '../../containers/EncryptedSearchProvider'; import ClearBrowserDataModal from '../header/ClearBrowserDataModal'; import MailDefaultHandlerModal from '../header/MailDefaultHandlerModal'; interface QuickSettingsSelectOption { value: any; text: string; icon?: IconName; } const MailQuickSettings = () => { const api = useApi(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const [{ Density, Checklists }] = useUserSettings(); const { ComposerMode, ViewLayout } = useMailModel('MailSettings'); const { esStatus } = useEncryptedSearchContext(); const { dbExists, esEnabled } = esStatus; const keyTransparencyNotification = useKeyTransparencyNotification(); const { ktActivation } = useKeyTransparencyContext(); const showKT = ktActivation === KeyTransparencyActivation.SHOW_UI; const hasFreeOnboardingChecklist = Checklists?.includes('get-started'); const { isChecklistFinished } = useGetStartedChecklist(); const [loadingViewLayout, withLoadingViewLayout] = useLoading(); const [loadingDensity, withLoadingDensity] = useLoading(); const [loadingComposerSize, withLoadingComposerSize] = useLoading(); const [clearBrowserDataProps, setClearBrowserDataModalOpen] = useModalState(); const [mailDefaultHandlerProps, setDefaultHandlerModalOpen] = useModalState(); const [mailShortcutsProps, setMailShortcutsModalOpen] = useModalState(); const [keyTransparencyDetailsModalProps, setKeyTransparencyDetailsModalOpen] = useModalState(); const [onboardingChecklistProps, setOnboardingChecklistProps] = useModalState(); const viewLayoutOptions: QuickSettingsSelectOption[] = [ { icon: 'column-two', value: VIEW_LAYOUT.COLUMN, text: c('Layout mode').t`Column`, }, { icon: 'column-one', value: VIEW_LAYOUT.ROW, text: c('Layout mode').t`Row`, }, ]; const defaultViewLayoutOption = viewLayoutOptions.find((option) => option.value === ViewLayout) || viewLayoutOptions[0]; const densityOptions: QuickSettingsSelectOption[] = [ { icon: 'density-low', value: DENSITY.COMFORTABLE, text: c('Density mode').t`Comfortable`, }, { icon: 'density-high', value: DENSITY.COMPACT, text: c('Density mode').t`Compact`, }, ]; const defaultDensityOption = densityOptions.find((option) => option.value === Density) || densityOptions[0]; const composerSizeOptions: QuickSettingsSelectOption[] = [ { icon: 'window-small', value: COMPOSER_MODE.POPUP, text: c('Composer size').t`Normal`, }, { icon: 'window-maximised', value: COMPOSER_MODE.MAXIMIZED, text: c('Composer size').t`Maximized`, }, ]; const defaultComposerModeOption = composerSizeOptions.find((option) => option.value === ComposerMode) || composerSizeOptions[0]; const handleChangeViewLayout = async (layout: number) => { await api(updateViewLayout(layout)); await call(); createNotification({ text: c('Success').t`Preference saved` }); }; const handleChangeDensity = async (density: number) => { await api(updateDensity(density)); await call(); createNotification({ text: c('Success').t`Preference saved` }); }; const handleChangeComposerMode = async (mode: number) => { await api(updateComposerMode(mode)); await call(); createNotification({ text: c('Success').t`Preference saved` }); }; const handleShowKeyTransparencyModal = () => { // Update local storage value document.dispatchEvent( new CustomEvent(KEY_TRANSPARENCY_REMINDER_UPDATE, { detail: { value: true, }, }) ); setKeyTransparencyDetailsModalOpen(true); }; const mailReminders: QuickSettingsReminders[] = useMemo(() => { const ktReminder: QuickSettingsReminders | undefined = showKT ? { color: keyTransparencyNotification, icon: keyTransparencyNotification ? 'exclamation-circle-filled' : undefined, text: c('loc_nightly: Key transparency details').t`Key verification`, callback: handleShowKeyTransparencyModal, testID: 'key-verification', } : undefined; return [ktReminder].filter(isTruthy); }, [showKT, keyTransparencyNotification]); return ( <QuickSettingsMain> <DrawerAllSettingsView /> <QuickSettingsSection> <QuickSettingsSectionRow // translator: As in Mailbox layout label={c('Label').t`Layout`} action={ <SelectTwo unstyled originalPlacement="bottom-end" value={defaultViewLayoutOption.value} onValue={(value: number) => withLoadingViewLayout(handleChangeViewLayout(value))} renderSelected={(selected) => { const value = viewLayoutOptions.find((option) => option.value === selected); return <>{value?.text}</>; }} disabled={loadingViewLayout} loading={loadingViewLayout} data-testid="mail-quick-settings:mailbox-layout-select" > {viewLayoutOptions.map((option) => { return ( <Option key={option.value} value={option.value} title={option.text} className="flex flex-align-items-center flex-nowrap gap-2 flex-item-noshrink" > <> {option.icon && <Icon name={option.icon} className="flex-item-noshrink" />} <span className="text-nowrap">{option.text}</span> </> </Option> ); })} </SelectTwo> } /> <QuickSettingsSectionRow // translator: As in Mailbox layout label={c('Label').t`Density`} action={ <SelectTwo unstyled originalPlacement="bottom-end" value={defaultDensityOption.value} onValue={(value: number) => withLoadingDensity(handleChangeDensity(value))} renderSelected={(selected) => { const value = densityOptions.find((option) => option.value === selected); return <>{value?.text}</>; }} disabled={loadingDensity} loading={loadingDensity} data-testid="mail-quick-settings:mailbox-density-select" > {densityOptions.map((option) => { return ( <Option key={option.value} value={option.value} title={option.text} className="flex flex-align-items-center flex-nowrap gap-2 flex-item-noshrink" > <> {option.icon && <Icon name={option.icon} className="flex-item-noshrink" />} <span className="flex-item-noshrink">{option.text}</span> </> </Option> ); })} </SelectTwo> } /> <QuickSettingsSectionRow // translator: As in Composer size label={c('Label').t`Composer`} action={ <SelectTwo unstyled originalPlacement="bottom-end" value={defaultComposerModeOption.value} onValue={(value: number) => withLoadingComposerSize(handleChangeComposerMode(value))} renderSelected={(selected) => { const value = composerSizeOptions.find((option) => option.value === selected); return <>{value?.text}</>; }} disabled={loadingComposerSize} loading={loadingComposerSize} data-testid="mail-quick-settings:composer-size-select" > {composerSizeOptions.map((option) => { return ( <Option key={option.value} value={option.value} title={option.text} className="flex flex-align-items-center flex-nowrap gap-2 flex-item-noshrink" > <> {option.icon && <Icon name={option.icon} className="flex-item-noshrink" />} <span className="text-nowrap flex-item-noshrink">{option.text}</span> </> </Option> ); })} </SelectTwo> } /> </QuickSettingsSection> <QuickSettingsSection> <QuickSettingsSectionRow label={c('Label').t`Keyboard shortcuts`} labelInfo={ <Info title={c('Info').t`Open shortcut cheat sheet`} onClick={() => setMailShortcutsModalOpen(true)} data-testid="mail-quick-settings:keyboard-shortcuts-info" /> } action={ <ShortcutsToggle id="toggle-shortcuts" data-testid="mail-quick-settings:keyboard-shortcuts-toggle" /> } /> </QuickSettingsSection> <DefaultQuickSettings inAppReminders={mailReminders} /> <QuickSettingsButtonSection> {hasFreeOnboardingChecklist && ( <QuickSettingsButton onClick={() => setOnboardingChecklistProps(true)} data-testid="mail-quick-settings:started-checklist-button" > {isChecklistFinished ? c('Get started checklist instructions').t`Open checklist` : c('Get started checklist instructions').t`Open checklist and get free storage`} </QuickSettingsButton> )} {isFirefox() && ( <QuickSettingsButton onClick={() => setDefaultHandlerModalOpen(true)} data-testid="mail-quick-settings:default-mail-app-button" > {c('Action').t`Set ${MAIL_APP_NAME} as default email application`} </QuickSettingsButton> )} {(dbExists || esEnabled) && ( <> <Tooltip title={c('Info') .t`Clears browser data related to message content search including downloaded messages`} > <QuickSettingsButton onClick={() => setClearBrowserDataModalOpen(true)} data-testid="mail-quick-settings:clear-cache-button" > {c('Action').t`Clear browser data`} </QuickSettingsButton> </Tooltip> </> )} </QuickSettingsButtonSection> <MailDefaultHandlerModal {...mailDefaultHandlerProps} /> <ClearBrowserDataModal {...clearBrowserDataProps} /> <MailShortcutsModal {...mailShortcutsProps} /> <KeyTransparencyDetailsModal {...keyTransparencyDetailsModalProps} /> <OnboardingChecklistModal {...onboardingChecklistProps} /> </QuickSettingsMain> ); }; export default MailQuickSettings;
3,444
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/dropdown/CustomFilterDropdown.tsx
import * as React from 'react'; import { useEffect, useMemo, useState } from 'react'; import { c } from 'ttag'; import { Checkbox, FiltersUpsellModal, PrimaryButton, useFilters, useModalState, useUser } from '@proton/components'; import { OPERATORS } from '@proton/components/containers/filters/constants'; import { ConditionComparator, ConditionType, Filter } from '@proton/components/containers/filters/interfaces'; import FilterModal from '@proton/components/containers/filters/modal/FilterModal'; import newFilter, { computeTree } from '@proton/components/containers/filters/utils'; import { hasReachedFiltersLimit } from '@proton/shared/lib/helpers/filters'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import identity from '@proton/utils/identity'; type FiltersState = { [key in ConditionType]: boolean; }; type FilterType = { label: string; value: ConditionType; conditionLabel: string; }; interface Props { message: Message; onClose: () => void; onLock: (lock: boolean) => void; } const CustomFilterDropdown = ({ message, onClose, onLock }: Props) => { const [containFocus, setContainFocus] = useState(true); const [filterModalProps, setFilterModalOpen, renderFilterModal] = useModalState(); const [upsellModalProps, handleUpsellModalDisplay, renderUpsellModal] = useModalState(); useEffect(() => onLock(!containFocus), [containFocus]); const [filtersState, setFiltersState] = useState<FiltersState>({ [ConditionType.SELECT]: false, [ConditionType.SUBJECT]: false, [ConditionType.SENDER]: false, [ConditionType.RECIPIENT]: false, [ConditionType.ATTACHMENTS]: false, }); const [user] = useUser(); const [filters = []] = useFilters() as [Filter[], boolean, Error]; const FILTER_TYPES: FilterType[] = [ { value: ConditionType.SUBJECT, label: c('CustomFilter').t`Subject`, conditionLabel: c('Filter modal type').t`If the subject`, }, { value: ConditionType.SENDER, label: c('CustomFilter').t`Sender`, conditionLabel: c('Filter modal type').t`If the sender`, }, { value: ConditionType.RECIPIENT, label: c('CustomFilter').t`Recipient`, conditionLabel: c('Filter modal type').t`If the recipient`, }, { value: ConditionType.ATTACHMENTS, label: c('CustomFilter').t`Attachment`, conditionLabel: c('Filter modal type').t`If the attachments`, }, ]; const toggleFilterType = (filterType: ConditionType) => { setFiltersState({ ...filtersState, [filterType]: !filtersState[filterType], }); }; const formatConditions = (conditions: ConditionType[]) => { return conditions.map((condition) => { const filterType = FILTER_TYPES.find((f) => f.value === condition) as FilterType; let value; switch (condition) { case ConditionType.SUBJECT: value = message.Subject; break; case ConditionType.SENDER: value = message.Sender ? message.Sender.Address : ''; break; case ConditionType.RECIPIENT: value = message.ToList && message.ToList.length ? message.ToList[0].Address : ''; break; case ConditionType.ATTACHMENTS: default: value = ''; break; } return { value, Values: [value], Type: { label: filterType?.conditionLabel, value: filterType?.value, }, Comparator: { label: 'contains', value: ConditionComparator.CONTAINS }, }; }); }; const filter = useMemo(() => { const filter = newFilter(); const conditions = []; let filterType: ConditionType; for (filterType in filtersState) { if (filtersState[filterType]) { conditions.push(filterType); } } filter.Simple = { Operator: { label: OPERATORS[0].label, value: OPERATORS[0].value, }, Conditions: formatConditions(conditions), Actions: { FileInto: [], Vacation: '', Mark: { Read: false, Starred: false }, }, }; return filter; }, [filtersState]); const handleNext = () => { // Set focus state to lock the dropdown // We need this otherwise modal that is rendered in the dropdown will be closed if dropdown disappear from the DOM setContainFocus(false); if (hasReachedFiltersLimit(user, filters)) { handleUpsellModalDisplay(true); } else { setFilterModalOpen(true); } }; const buttonDisabled = !Object.values(filtersState).some(identity); const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); handleNext(); }; return ( <> <form onSubmit={handleSubmit}> <div className="m-4"> <span className="text-bold" tabIndex={-2}> {c('CustomFilter').t`Filter on`} </span> </div> <ul className="unstyled my-4"> {FILTER_TYPES.map((filterType: FilterType) => ( <li key={filterType.value} className="dropdown-item w-full flex flex-nowrap flex-align-items-center py-2 px-4" > <Checkbox className="flex-item-noshrink mr-2" id={filterType.value} data-testid={`custom-filter-checkbox:${filterType.value}`} checked={filtersState[filterType.value]} onChange={() => toggleFilterType(filterType.value)} /> <label htmlFor={filterType.value} title={filterType.label} className="flex-item-fluid text-ellipsis" > {filterType.label} </label> </li> ))} </ul> <div className="m-4"> <PrimaryButton className="w-full" disabled={buttonDisabled} data-prevent-arrow-navigation type="submit" data-testid="filter-dropdown:next-button" > {c('CustomFilter').t`Next`} </PrimaryButton> </div> </form> {renderFilterModal && ( <FilterModal filter={{ ...filter, Tree: computeTree(filter), }} onCloseCustomAction={() => setContainFocus(true)} {...filterModalProps} /> )} {renderUpsellModal && ( <FiltersUpsellModal modalProps={upsellModalProps} onCloseCustomAction={() => { setContainFocus(true); onClose(); }} /> )} </> ); }; export default CustomFilterDropdown;
3,445
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/dropdown/LabelDropdown.scss
@import '~@proton/styles/scss/lib'; .label-dropdown { &-list { @include media('>small') { max-block-size: 13.5em; } } }
3,446
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/dropdown/LabelDropdown.tsx
import { ChangeEvent, useEffect, useMemo, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Checkbox, Icon, LabelsUpsellModal, Mark, PrimaryButton, SearchInput, Tooltip, generateUID, useLabels, useModalState, useUser, } from '@proton/components'; import EditLabelModal from '@proton/components/containers/labels/modals/EditLabelModal'; import { useLoading } from '@proton/hooks'; import { getRandomAccentColor } from '@proton/shared/lib/colors'; import { LABEL_TYPE, MAILBOX_IDENTIFIERS, MAIL_UPSELL_PATHS } from '@proton/shared/lib/constants'; import { hasReachedLabelLimit } from '@proton/shared/lib/helpers/folder'; import isDeepEqual from '@proton/shared/lib/helpers/isDeepEqual'; import { normalize } from '@proton/shared/lib/helpers/string'; import { Label } from '@proton/shared/lib/interfaces/Label'; import clsx from '@proton/utils/clsx'; import { getLabelIDs } from '../../helpers/elements'; import { getStandardFolders } from '../../helpers/labels'; import { useApplyLabels } from '../../hooks/actions/useApplyLabels'; import { useCreateFilters } from '../../hooks/actions/useCreateFilters'; import { useMoveToFolder } from '../../hooks/actions/useMoveToFolder'; import { useGetElementsFromIDs } from '../../hooks/mailbox/useElements'; import { Element } from '../../models/element'; import { Breakpoints } from '../../models/utils'; import './LabelDropdown.scss'; export const labelDropdownContentProps = { className: 'flex flex-column flex-nowrap flex-align-items-stretch' }; enum LabelState { On = 'On', Off = 'Off', Indeterminate = 'Indeterminate', } const { On, Off, Indeterminate } = LabelState; type SelectionState = { [labelID: string]: LabelState }; const getInitialState = (labels: Label[] = [], elements: Element[] = []) => { const result: SelectionState = {}; const elementsLabels = elements.map((element) => getLabelIDs( element, // Undefined and not labelID here. Because applying a label to a conversation apply to all messages // Not only those from the current labelID. undefined ) ); labels.forEach(({ ID = '' }) => { const counts = elementsLabels.reduce<{ [state: string]: number }>( (acc, elementLabels) => { if (elementLabels[ID] === undefined) { acc[Off] += 1; } else if (elementLabels[ID]) { acc[On] += 1; } else { acc[Indeterminate] += 1; } return acc; }, { [On]: 0, [Off]: 0, [Indeterminate]: 0 } ); result[ID] = counts[Off] === elements.length ? Off : counts[On] === elements.length ? On : Indeterminate; }); return result; }; const getIsApplyDisabled = ( initialState: SelectionState, selectedLabelIDs: SelectionState, checkedIDs: string[], always: boolean, alsoArchive: boolean ) => { // If same labels, no changes have been made in the label dropdown const areSameLabels = isDeepEqual(initialState, selectedLabelIDs); // If some labels are checked // If there are no changes in the dropdown AND always label OR also archive are checked => We should be able to apply, so we return false // Else, no changes are detected AND we have no action to do => Apply should be disabled if (checkedIDs.length > 0) { return areSameLabels && !(always || alsoArchive); } // If no labels are checked // If no changes in the dropdown AND also archive is checked => We should be able to apply, so we return false // Else, no changes are detected and no action to do => Apply should be disabled return areSameLabels && !alsoArchive; }; interface Props { selectedIDs: string[]; labelID: string; onClose: () => void; onLock: (lock: boolean) => void; breakpoints: Breakpoints; } const LabelDropdown = ({ selectedIDs, labelID, onClose, onLock, breakpoints }: Props) => { const [uid] = useState(generateUID('label-dropdown')); const [labels = []] = useLabels(); const [user] = useUser(); const [loading, withLoading] = useLoading(); const [search, updateSearch] = useState(''); const [containFocus, setContainFocus] = useState(true); const [lastChecked, setLastChecked] = useState(''); // Store ID of the last label ID checked const [alsoArchive, updateAlsoArchive] = useState(false); const [always, setAlways] = useState(false); const getElementsFromIDs = useGetElementsFromIDs(); const applyLabels = useApplyLabels(); const { moveToFolder, moveScheduledModal, moveSnoozedModal, moveAllModal, moveToSpamModal } = useMoveToFolder(setContainFocus); const { getSendersToFilter } = useCreateFilters(); /* * translator: Text displayed in a button to suggest the creation of a new label in the label dropdown * This button is shown when the user search for a label which doesn't exist * ${search} is a string containing the search the user made in the label dropdown * Full sentence for reference: 'Create label "Dunder Mifflin"' */ const createLabelButtonText = c('Title').t`Create label "${search}"`; const [editLabelProps, setEditLabelModalOpen, renderLabelModal] = useModalState(); const [upsellModalProps, handleUpsellModalDisplay, renderUpsellModal] = useModalState(); const initialState = useMemo( () => getInitialState(labels, getElementsFromIDs(selectedIDs)), [selectedIDs, labels, labelID] ); const [selectedLabelIDs, setSelectedLabelIDs] = useState<SelectionState>(initialState); // IDs currently checked in the modal // We will use this string[] to always label sender's emails on all checked ids in the modal const checkedIDs = useMemo(() => { return Object.keys(selectedLabelIDs).reduce<string[]>((acc, LabelID) => { if (selectedLabelIDs[LabelID] === LabelState.On) { acc.push(LabelID); } return acc; }, []); }, [selectedLabelIDs]); const changes = useMemo(() => { const elements = getElementsFromIDs(selectedIDs); const initialState = getInitialState(labels, elements); return Object.keys(selectedLabelIDs).reduce((acc, LabelID) => { if (selectedLabelIDs[LabelID] === LabelState.On && initialState[LabelID] !== LabelState.On) { acc[LabelID] = true; } if (selectedLabelIDs[LabelID] === LabelState.Off && initialState[LabelID] !== LabelState.Off) { acc[LabelID] = false; } return acc; }, {} as { [labelID: string]: boolean }); }, [selectedIDs, initialState, selectedLabelIDs]); // Always checkbox should be disabled when we don't find senders OR there are no labels checked (so no filter based on labels to create) const alwaysCheckboxDisabled = useMemo(() => { return !getSendersToFilter(getElementsFromIDs(selectedIDs)).length || checkedIDs.length < 1; }, [getSendersToFilter, selectedIDs, changes]); useEffect(() => { if (alwaysCheckboxDisabled && always) { setAlways(false); } }, [alwaysCheckboxDisabled, always]); useEffect(() => onLock(!containFocus), [containFocus]); if (!selectedIDs || !selectedIDs.length) { return null; } const newLabel: Pick<Label, 'Name' | 'Color' | 'Type'> = { Name: search, Color: getRandomAccentColor(), Type: LABEL_TYPE.MESSAGE_LABEL, }; // The dropdown is several times in the view, native html ids has to be different each time const searchInputID = `${uid}-search`; const archiveCheckID = `${uid}-archive`; const alwaysCheckID = `${uid}-always`; const labelCheckID = (ID: string) => `${uid}-${ID}`; const applyDisabled = getIsApplyDisabled(initialState, selectedLabelIDs, checkedIDs, always, alsoArchive); const autoFocusSearch = !breakpoints.isNarrow; const normSearch = normalize(search, true); const list = labels.filter(({ Name = '' }) => { if (!search) { return true; } const normName = normalize(Name, true); return normName.includes(normSearch); }); const actualApplyLabels = async (changes: { [p: string]: boolean }) => { const elements = getElementsFromIDs(selectedIDs); const promises = []; promises.push(applyLabels(elements, changes, always, false, checkedIDs)); if (alsoArchive) { const folderName = getStandardFolders()[MAILBOX_IDENTIFIERS.archive].name; promises.push(moveToFolder(elements, MAILBOX_IDENTIFIERS.archive, folderName, labelID, false)); } await Promise.all(promises); onClose(); }; const handleApply = async () => { await actualApplyLabels(changes); }; const applyCheck = (labelIDs: string[], selected: boolean) => { const update = labelIDs.reduce((acc, ID) => { acc[ID] = selected ? LabelState.On : LabelState.Off; return acc; }, {} as SelectionState); setSelectedLabelIDs({ ...selectedLabelIDs, ...update }); }; const handleCheck = (labelID: string) => ({ target, nativeEvent }: ChangeEvent<HTMLInputElement>) => { const { shiftKey } = nativeEvent as any; const labelIDs = [labelID]; if (lastChecked && shiftKey) { const start = list.findIndex(({ ID }) => ID === labelID); const end = list.findIndex(({ ID }) => ID === lastChecked); labelIDs.push(...list.slice(Math.min(start, end), Math.max(start, end) + 1).map(({ ID = '' }) => ID)); } setLastChecked(labelID); applyCheck(labelIDs, target.checked); }; const handleAddNewLabel = (label?: Partial<Label>) => { applyCheck([label?.ID || ''], true); }; const handleCreate = () => { // Set focus state to lock the dropdown // We need this otherwise modal that is rendered in the dropdown will be closed if dropdown disappear from the DOM setContainFocus(false); if (hasReachedLabelLimit(user, labels)) { handleUpsellModalDisplay(true); } else { setEditLabelModalOpen(true); } }; const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); await withLoading(handleApply()); }; const handleApplyDirectly = async (labelID: string) => { const updatedChanges = { ...changes, [labelID]: selectedLabelIDs[labelID] !== LabelState.On, }; await actualApplyLabels(updatedChanges); }; return ( <form className="flex flex-column flex-nowrap flex-justify-start flex-align-items-stretch flex-item-fluid-auto" onSubmit={handleSubmit} > <div className="flex flex-item-noshrink flex-justify-space-between flex-align-items-center m-4 mb-0"> <span className="text-bold" tabIndex={-2}> {c('Label').t`Label as`} </span> <Tooltip title={c('Title').t`Create label`}> <Button icon color="norm" size="small" onClick={handleCreate} className="flex flex-align-items-center" data-testid="label-dropdown:add-label" data-prevent-arrow-navigation > <Icon name="tag" /> + </Button> </Tooltip> </div> <div className="flex-item-noshrink m-4 mb-0"> <SearchInput value={search} onChange={updateSearch} id={searchInputID} placeholder={c('Placeholder').t`Filter labels`} autoFocus={autoFocusSearch} data-test-selector="label-dropdown:search-label" data-prevent-arrow-navigation data-testid="label-dropdown:search-input" /> </div> <div className="label-dropdown-list overflow-auto mt-4 flex-item-fluid-auto" data-testid="label-dropdown-list" > <ul className="unstyled my-0"> {list.map(({ ID = '', Name = '', Color = '' }) => ( <li key={ID} className="dropdown-item dropdown-item-button relative cursor-pointer w-full flex flex-nowrap flex-align-items-center py-2 px-4" > <Checkbox className="flex-item-noshrink mr-2" id={labelCheckID(ID)} checked={selectedLabelIDs[ID] === LabelState.On} indeterminate={selectedLabelIDs[ID] === LabelState.Indeterminate} onChange={handleCheck(ID)} data-testid={`label-dropdown:label-checkbox-${Name}`} /> <label htmlFor={labelCheckID(ID)} title={Name} className="flex flex-nowrap flex-align-items-center flex-item-fluid" data-testid={`label-dropdown:label-${Name}`} onClick={() => handleApplyDirectly(ID)} > <Icon name="circle-filled" size={16} color={Color} className="flex-item-noshrink relative mx-2" /> <span className="text-ellipsis"> <Mark value={search}>{Name}</Mark> </span> </label> </li> ))} {list.length === 0 && !search && ( <li key="empty" className="dropdown-item w-full py-2 px-4"> {c('Info').t`No label found`} </li> )} {list.length === 0 && search && ( <span className="flex w-full"> <Button key="create-new-label" className="w-full mx-8 text-ellipsis" data-testid="label-dropdown:create-label-option" title={createLabelButtonText} onClick={handleCreate} > {createLabelButtonText} </Button> </span> )} </ul> </div> <hr className="m-0 flex-item-noshrink" /> <div className={clsx(['px-4 mt-4 flex-item-noshrink', alwaysCheckboxDisabled && 'color-disabled'])}> <Checkbox id={alwaysCheckID} checked={always} disabled={alwaysCheckboxDisabled} onChange={({ target }) => setAlways(target.checked)} data-testid="label-dropdown:always-move" data-prevent-arrow-navigation > {c('Label').t`Always label sender's emails`} </Checkbox> </div> <div className="px-4 mt-4 flex-item-noshrink"> <Checkbox id={archiveCheckID} checked={alsoArchive} onChange={({ target }) => updateAlsoArchive(target.checked)} data-testid="label-dropdown:also-archive" data-prevent-arrow-navigation > {c('Label').t`Also archive`} </Checkbox> </div> <div className="m-4 flex-item-noshrink"> <PrimaryButton className="w-full" loading={loading} disabled={applyDisabled} data-testid="label-dropdown:apply" data-prevent-arrow-navigation type="submit" > {c('Action').t`Apply`} </PrimaryButton> </div> {moveScheduledModal} {moveSnoozedModal} {moveAllModal} {moveToSpamModal} {renderLabelModal && ( <EditLabelModal label={newLabel} onAdd={(label) => handleAddNewLabel(label)} onCloseCustomAction={() => setContainFocus(true)} {...editLabelProps} /> )} {renderUpsellModal && ( <LabelsUpsellModal modalProps={upsellModalProps} feature={MAIL_UPSELL_PATHS.UNLIMITED_LABELS} onCloseCustomAction={() => { setContainFocus(true); onClose(); }} /> )} </form> ); }; export default LabelDropdown;
3,447
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/dropdown/MoveDropdown.scss
@import '~@proton/styles/scss/lib'; .move-dropdown { [data-level='1'] { padding-inline-start: 1em; } [data-level='2'] { padding-inline-start: 2em; } &-list { @include media('>small') { max-block-size: 15.5em; } } }
3,448
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/dropdown/MoveDropdown.tsx
import { useEffect, useMemo, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Checkbox, FolderIcon, Icon, IconName, LabelsUpsellModal, Mark, PrimaryButton, Radio, SearchInput, Tooltip, generateUID, useFolders, useModalState, useUser, } from '@proton/components'; import EditLabelModal from '@proton/components/containers/labels/modals/EditLabelModal'; import { useLoading } from '@proton/hooks'; import { ACCENT_COLORS } from '@proton/shared/lib/colors'; import { LABEL_TYPE, MAILBOX_LABEL_IDS, MAIL_UPSELL_PATHS } from '@proton/shared/lib/constants'; import { buildTreeview, hasReachedFolderLimit } from '@proton/shared/lib/helpers/folder'; import { normalize } from '@proton/shared/lib/helpers/string'; import { Label } from '@proton/shared/lib/interfaces'; import { Folder, FolderWithSubFolders } from '@proton/shared/lib/interfaces/Folder'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import clsx from '@proton/utils/clsx'; import isTruthy from '@proton/utils/isTruthy'; import randomIntFromInterval from '@proton/utils/randomIntFromInterval'; import { isMessage as testIsMessage } from '../../helpers/elements'; import { getMessagesAuthorizedToMove } from '../../helpers/message/messages'; import { useCreateFilters } from '../../hooks/actions/useCreateFilters'; import { useMoveToFolder } from '../../hooks/actions/useMoveToFolder'; import { useGetElementsFromIDs } from '../../hooks/mailbox/useElements'; import { Breakpoints } from '../../models/utils'; import './MoveDropdown.scss'; export const moveDropdownContentProps = { className: 'flex flex-column flex-nowrap flex-align-items-stretch' }; type FolderItem = Folder & { icon: IconName; level: number }; const { INBOX, TRASH, SPAM, ARCHIVE } = MAILBOX_LABEL_IDS; const folderReducer = (acc: FolderItem[], folder: FolderWithSubFolders, level = 0): FolderItem[] => { acc.push({ ...folder, Name: folder.Name, icon: folder.subfolders?.length ? 'folders' : 'folder', level, }); if (Array.isArray(folder.subfolders)) { folder.subfolders.forEach((folder: FolderWithSubFolders) => folderReducer(acc, folder, level + 1)); } return acc; }; interface Props { selectedIDs: string[]; labelID: string; onClose: () => void; onLock: (lock: boolean) => void; breakpoints: Breakpoints; } const MoveDropdown = ({ selectedIDs, labelID, onClose, onLock, breakpoints }: Props) => { const [uid] = useState(generateUID('move-dropdown')); const [folders = []] = useFolders(); const [user] = useUser(); const [loading, withLoading] = useLoading(); const [search, updateSearch] = useState(''); const [selectedFolder, setSelectedFolder] = useState<Folder | undefined>(); const [always, setAlways] = useState(false); const [containFocus, setContainFocus] = useState(true); const normSearch = normalize(search, true); const getElementsFromIDs = useGetElementsFromIDs(); const { moveToFolder, moveScheduledModal, moveSnoozedModal, moveAllModal, moveToSpamModal } = useMoveToFolder(setContainFocus); const { getSendersToFilter } = useCreateFilters(); const [editLabelProps, setEditLabelModalOpen, renderLabelModal] = useModalState(); const [upsellModalProps, handleUpsellModalDisplay, renderUpsellModal] = useModalState(); useEffect(() => onLock(!containFocus), [containFocus]); const treeview = buildTreeview(folders); const elements = getElementsFromIDs(selectedIDs); const isMessage = testIsMessage(elements[0]); const canMoveToInbox = isMessage ? !!getMessagesAuthorizedToMove(elements as Message[], INBOX).length : true; const canMoveToSpam = isMessage ? !!getMessagesAuthorizedToMove(elements as Message[], SPAM).length : true; /* * translator: Text displayed in a button to suggest the creation of a new folder in the move dropdown * This button is shown when the user search for a folder which doesn't exist * ${search} is a string containing the search the user made in the folder dropdown * Full sentence for reference: 'Create folder "Dunder Mifflin"' */ const createFolderButtonText = c('Title').t`Create folder "${search}"`; const alwaysCheckboxDisabled = useMemo(() => { return !getSendersToFilter(elements).length || !selectedFolder; }, [getSendersToFilter, elements]); const list = treeview .reduce<FolderItem[]>((acc, folder) => folderReducer(acc, folder), []) .concat([ canMoveToInbox && { ID: INBOX, Name: c('Mailbox').t`Inbox`, icon: 'inbox', }, { ID: ARCHIVE, Name: c('Mailbox').t`Archive`, icon: 'archive-box' }, canMoveToSpam && { ID: SPAM, Name: c('Mailbox').t`Spam`, icon: 'fire', }, { ID: TRASH, Name: c('Mailbox').t`Trash`, icon: 'trash' }, ] as FolderItem[]) .filter(isTruthy) .filter(({ Name = '' }: { Name: string }) => { if (!search) { return true; } const normName = normalize(Name, true); return normName.includes(normSearch); }); const actualMoveFolder = async (selectedFolderID: string, selectedFolderName: string) => { // If the destination folder is SPAM, we don't want to create a filter even if always is checked // Senders will be moved to spam anyway, but since we don't want to create filters in the "Spam case", // We only need to ignore the value in that scenario const canApplyAlways = selectedFolderID !== SPAM; await moveToFolder(elements, selectedFolderID, selectedFolderName, labelID, canApplyAlways ? always : false); onClose(); }; const handleMove = async () => { await actualMoveFolder(selectedFolder?.ID || '', selectedFolder?.Name || ''); }; const handleApplyDirectly = async (selectedFolderID: string, selectedFolderName: string) => { await actualMoveFolder(selectedFolderID, selectedFolderName); }; const handleCreate = () => { // Set focus state to lock the dropdown // We need this otherwise modal that is rendered in the dropdown will be closed if dropdown disappear from the DOM setContainFocus(false); if (hasReachedFolderLimit(user, folders)) { handleUpsellModalDisplay(true); } else { setEditLabelModalOpen(true); } }; const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); await withLoading(handleMove()); }; // The dropdown is several times in the view, native html ids has to be different each time const searchInputID = `${uid}-search`; const alwaysCheckID = `${uid}-always`; const folderButtonID = (ID: string) => `${uid}-${ID}`; const autoFocusSearch = !breakpoints.isNarrow; const applyDisabled = selectedFolder?.ID === undefined; const newFolder: Pick<Label, 'Name' | 'Color' | 'Type'> = { Name: search, Color: ACCENT_COLORS[randomIntFromInterval(0, ACCENT_COLORS.length - 1)], Type: LABEL_TYPE.MESSAGE_FOLDER, }; return ( <form className="flex flex-column flex-nowrap flex-justify-start flex-align-items-stretch flex-item-fluid-auto" onSubmit={handleSubmit} > <div className="flex flex-item-noshrink flex-justify-space-between flex-align-items-center m-4 mb-0"> <span className="text-bold" tabIndex={-2}> {c('Label').t`Move to`} </span> <Tooltip title={c('Title').t`Create folder`}> <Button icon color="norm" size="small" onClick={handleCreate} className="flex flex-align-items-center" data-testid="folder-dropdown:add-folder" data-prevent-arrow-navigation > <Icon name="folder" /> + </Button> </Tooltip> </div> <div className="flex-item-noshrink m-4 mb-0"> <SearchInput value={search} onChange={updateSearch} id={searchInputID} placeholder={c('Placeholder').t`Filter folders`} autoFocus={autoFocusSearch} data-testid="folder-dropdown:search-folder" data-prevent-arrow-navigation /> </div> <div className="move-dropdown-list overflow-auto mt-4 flex-item-fluid-auto" data-testid="move-dropdown-list" > <ul className="unstyled my-0"> {list.map((folder: FolderItem) => { return ( <li key={folder.ID} className="dropdown-item dropdown-item-button relative cursor-pointer w-full flex flex-nowrap flex-align-items-center py-2 px-4" > <Radio className="flex-item-noshrink mr-2" id={folderButtonID(folder.ID)} name={uid} checked={selectedFolder?.ID === folder.ID} onChange={() => setSelectedFolder(folder)} data-testid={`label-dropdown:folder-radio-${folder.Name}`} /> <label htmlFor={folderButtonID(folder.ID)} data-level={folder.level} className="flex flex-nowrap flex-align-items-center flex-item-fluid" data-testid={`folder-dropdown:folder-${folder.Name}`} onClick={() => handleApplyDirectly(folder.ID, folder.Name)} > <FolderIcon folder={folder} name={folder.icon} className="flex-item-noshrink mr-2" /> <span className="text-ellipsis" title={folder.Name}> <Mark value={search}>{folder.Name}</Mark> </span> </label> </li> ); })} {list.length === 0 && !search && ( <li key="empty" className="dropdown-item w-full py-2 px-4"> {c('Info').t`No folder found`} </li> )} {list.length === 0 && search && ( <span className="flex w-full"> <Button key="create-new-folder" className="w-full mx-8 text-ellipsis" data-testid="folder-dropdown:create-folder-option" title={createFolderButtonText} onClick={handleCreate} > {createFolderButtonText} </Button> </span> )} </ul> </div> <hr className="m-0 flex-item-noshrink" /> <div className={clsx(['mx-4 mt-4 flex-item-noshrink', alwaysCheckboxDisabled && 'color-disabled'])}> <Checkbox id={alwaysCheckID} checked={always} disabled={alwaysCheckboxDisabled} onChange={({ target }) => setAlways(target.checked)} data-testid="move-dropdown:always-move" data-prevent-arrow-navigation > {c('Label').t`Always move sender's emails`} </Checkbox> </div> <div className="m-4 flex-item-noshrink"> <PrimaryButton className="w-full" loading={loading} disabled={applyDisabled} data-testid="move-dropdown:apply" data-prevent-arrow-navigation type="submit" > {c('Action').t`Apply`} </PrimaryButton> </div> {moveScheduledModal} {moveSnoozedModal} {moveAllModal} {moveToSpamModal} {renderLabelModal && ( <EditLabelModal label={newFolder} type="folder" onCloseCustomAction={() => setContainFocus(true)} {...editLabelProps} /> )} {renderUpsellModal && ( <LabelsUpsellModal modalProps={upsellModalProps} feature={MAIL_UPSELL_PATHS.UNLIMITED_FOLDERS} onCloseCustomAction={() => { setContainFocus(true); onClose(); }} /> )} </form> ); }; export default MoveDropdown;
3,449
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/dropdown
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/dropdown/tests/CustomFilterDropdown.test.tsx
import { fireEvent } from '@testing-library/react'; import { act } from '@testing-library/react'; import { ConditionType } from '@proton/components/containers/filters/interfaces'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { render, tick } from '../../../helpers/test/render'; import CustomFilterDropdown from '../CustomFilterDropdown'; const subject = 'Message subject'; const sender = 'sender@pm.me'; const me = 'me@pm.me'; const message = { Subject: subject, Sender: { Address: sender }, ToList: [{ Address: me }], } as Message; const props = { message: message, onClose: jest.fn(), onLock: jest.fn(), }; describe('CustomFilterDropdown', () => { it('should create a filter based on all options', async () => { const { getByTestId } = await render(<CustomFilterDropdown {...props} />); const subjectCheckbox = getByTestId(`custom-filter-checkbox:${ConditionType.SUBJECT}`) as HTMLInputElement; const recipientCheckbox = getByTestId(`custom-filter-checkbox:${ConditionType.RECIPIENT}`) as HTMLInputElement; const senderCheckbox = getByTestId(`custom-filter-checkbox:${ConditionType.SENDER}`) as HTMLInputElement; const attachmentCheckbox = getByTestId( `custom-filter-checkbox:${ConditionType.ATTACHMENTS}` ) as HTMLInputElement; // By default all options are not checked expect(subjectCheckbox.checked).toBeFalsy(); expect(recipientCheckbox.checked).toBeFalsy(); expect(senderCheckbox.checked).toBeFalsy(); expect(attachmentCheckbox.checked).toBeFalsy(); // Then we want to check them all (need to do it separately otherwise it fails) await act(async () => { fireEvent.click(subjectCheckbox); await tick(); }); expect(subjectCheckbox.checked).toBeTruthy(); await act(async () => { fireEvent.click(recipientCheckbox); await tick(); }); expect(recipientCheckbox.checked).toBeTruthy(); await act(async () => { fireEvent.click(senderCheckbox); await tick(); }); expect(senderCheckbox.checked).toBeTruthy(); await act(async () => { fireEvent.click(attachmentCheckbox); await tick(); }); expect(attachmentCheckbox.checked).toBeTruthy(); // Open the filter modal const applyButton = getByTestId('filter-dropdown:next-button'); fireEvent.click(applyButton); /* TODO enable this part of the test when Sieve will be part of the monorepo For now, we are forced to mock the library which is causing issue when we want to check prefilled condition from the modal // Add a name to the filter so that we can pass to next step const filterNameInput = screen.getByTestId('filter-modal:name-input'); await act(async () => { fireEvent.change(filterNameInput, {target: {value: newFilterName}}); // input has a debounce, so we need to wait for the onChange await wait(300); }); const modalNextButton = screen.getByTestId('filter-modal:next-button'); fireEvent.click(modalNextButton); // Check that conditions const conditions = screen.queryAllByTestId(/filter-modal:condition-/) expect(conditions.length).toEqual(4) // Check that option 1 is Subject with the expected value // Check that option 2 is Recipient with the expected value // Check that option 2 is Sender with the expected value // Check that option 2 is Attachments with the expected value */ }); });
3,450
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/dropdown
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/dropdown/tests/LabelDropdown.test.tsx
import { fireEvent } from '@testing-library/react'; import { act, getByTestId as getByTestIdDefault, screen } from '@testing-library/react'; import { ACCENT_COLORS } from '@proton/shared/lib/colors'; import { LABEL_TYPE, MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { wait } from '@proton/shared/lib/helpers/promise'; import { Label } from '@proton/shared/lib/interfaces'; import { addApiMock } from '../../../helpers/test/api'; import { addToCache, minimalCache } from '../../../helpers/test/cache'; 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 { messageID } from '../../message/tests/Message.test.helpers'; import LabelDropdown from '../LabelDropdown'; const label1Name = 'Label1'; const label1ID = 'label-1-id'; const label2Name = 'Label2'; const label2ID = 'label-2-id'; const search = 'This label does not exists'; const props = { selectedIDs: [messageID], labelID: MAILBOX_LABEL_IDS.INBOX, onClose: jest.fn(), onLock: jest.fn(), breakpoints: {} as Breakpoints, }; const getMessage = (labelIDs: string[] = []) => { return { localID: messageID, data: { Sender: { Address: 'sender@sender.pm.me' }, ConversationID: 'conversationID', LabelIDs: [MAILBOX_LABEL_IDS.INBOX, ...labelIDs], }, } as MessageState; }; describe('LabelDropdown', () => { const setup = async (labelIDs: string[] = []) => { minimalCache(); addToCache('Labels', [ { ID: label1ID, Name: label1Name, Color: ACCENT_COLORS[0], Type: LABEL_TYPE.MESSAGE_LABEL, Path: label1Name, } as Label, { ID: label2ID, Name: label2Name, Color: ACCENT_COLORS[1], Type: LABEL_TYPE.MESSAGE_LABEL, Path: label2Name, } as Label, ]); const message = getMessage(labelIDs); store.dispatch(initialize(message)); const result = await render(<LabelDropdown {...props} />, false); return result; }; it("should display user's labels in the dropdown", async () => { const { findAllByTestId, getByText } = await setup(); const labels = (await findAllByTestId(/label-dropdown:label-checkbox-/)) as HTMLInputElement[]; expect(labels.length).toBe(2); // Checkboxes are present and unchecked expect(labels[0].checked).toBe(false); expect(labels[1].checked).toBe(false); getByText(label1Name); getByText(label2Name); }); it('should label a message', async () => { const apiMock = jest.fn(() => ({ UndoToken: 1000 })); addApiMock(`mail/v4/messages/label`, apiMock); const { getByTestId } = await setup(); const checkbox1 = getByTestId(`label-dropdown:label-checkbox-${label1Name}`) as HTMLInputElement; // Check the first label expect(checkbox1.checked).toBe(false); await act(async () => { fireEvent.click(checkbox1); }); expect(checkbox1.checked).toBe(true); // Apply the label const applyButton = getByTestId('label-dropdown:apply'); await act(async () => { fireEvent.click(applyButton); }); // label call has been made expect(apiMock).toHaveBeenCalled(); }); it('should unlabel a message', async () => { const apiMock = jest.fn(() => ({ UndoToken: 1000 })); addApiMock(`mail/v4/messages/unlabel`, apiMock); const { getByTestId } = await setup([label1ID]); const checkbox1 = getByTestId(`label-dropdown:label-checkbox-${label1Name}`) as HTMLInputElement; // Check the first label expect(checkbox1.checked).toBeTruthy(); await act(async () => { fireEvent.click(checkbox1); }); expect(checkbox1.checked).toBeFalsy(); // Apply the unlabel const applyButton = getByTestId('label-dropdown:apply'); await act(async () => { fireEvent.click(applyButton); }); // label call has been made expect(apiMock).toHaveBeenCalled(); }); it('should add the "also archive" option', async () => { const apiMock = jest.fn(() => ({ UndoToken: 1000 })); addApiMock(`mail/v4/messages/label`, apiMock); const { getByTestId } = await setup(); const checkbox1 = getByTestId(`label-dropdown:label-checkbox-${label1Name}`) as HTMLInputElement; // Check the first label expect(checkbox1.checked).toBe(false); await act(async () => { fireEvent.click(checkbox1); }); expect(checkbox1.checked).toBe(true); // Check the also archive option const alsoArchiveCheckbox = getByTestId('label-dropdown:also-archive') as HTMLInputElement; await act(async () => { fireEvent.click(alsoArchiveCheckbox); }); // Apply the label const applyButton = getByTestId('label-dropdown:apply'); await act(async () => { fireEvent.click(applyButton); }); // label calls have been made // Call 1 => Apply label // Call 2 => Apply archive expect(apiMock).toHaveBeenCalledTimes(2); expect((apiMock.mock.calls[0] as any[])[0]?.data?.LabelID).toEqual(label1ID); expect((apiMock.mock.calls[1] as any[])[0]?.data?.LabelID).toEqual(MAILBOX_LABEL_IDS.ARCHIVE); }); it('should add the "always label sender\'s email" option', async () => { const labelApiMock = jest.fn(() => ({ UndoToken: 1000 })); addApiMock(`mail/v4/messages/label`, labelApiMock); const filterApiMock = jest.fn(() => ({ Filter: {} })); addApiMock('mail/v4/filters', filterApiMock); const { getByTestId } = await setup(); const checkbox1 = getByTestId(`label-dropdown:label-checkbox-${label1Name}`) as HTMLInputElement; // Check the first label expect(checkbox1.checked).toBe(false); await act(async () => { fireEvent.click(checkbox1); }); expect(checkbox1.checked).toBe(true); // Check the "always label sender's email" checkbox const alwaysLabelCheckbox = getByTestId('label-dropdown:always-move') as HTMLInputElement; await act(async () => { fireEvent.click(alwaysLabelCheckbox); }); // Apply the label const applyButton = getByTestId('label-dropdown:apply'); await act(async () => { fireEvent.click(applyButton); }); expect(labelApiMock).toHaveBeenCalled(); expect(filterApiMock).toHaveBeenCalled(); }); it('should create a label from the button', async () => { const { getByTestId, queryAllByTestId } = await setup(); // Search for a label which does not exist const searchInput = getByTestId('label-dropdown:search-input'); await act(async () => { fireEvent.change(searchInput, { target: { value: search } }); // input has a debounce, so we need to wait for the onChange await wait(300); }); // No more option are displayed const labels = queryAllByTestId(/label-dropdown:label-checkbox-/) as HTMLInputElement[]; expect(labels.length).toBe(0); // Click on the create label button const createLabelButton = getByTestId('label-dropdown:add-label'); fireEvent.click(createLabelButton); // Get the modal content const createLabelModal = screen.getByRole('dialog', { hidden: true }); const labelModalNameInput = getByTestIdDefault(createLabelModal, 'label/folder-modal:name') as HTMLInputElement; // Input is filled with the previous search content expect(labelModalNameInput.value).toEqual(search); }); it('should create a label from the option', async () => { const { getByTestId, queryAllByTestId } = await setup(); // Search for a label which does not exist const searchInput = getByTestId('label-dropdown:search-input'); await act(async () => { fireEvent.change(searchInput, { target: { value: search } }); // input has a debounce, so we need to wait for the onChange await wait(300); }); // No more option are displayed const labels = queryAllByTestId(/label-dropdown:label-checkbox-/) as HTMLInputElement[]; expect(labels.length).toBe(0); // Click on the create label option const createLabelOption = getByTestId('label-dropdown:create-label-option'); fireEvent.click(createLabelOption); // Get the modal content const createLabelModal = screen.getByRole('dialog', { hidden: true }); const labelModalNameInput = getByTestIdDefault(createLabelModal, 'label/folder-modal:name') as HTMLInputElement; // Input is filled with the previous search content expect(labelModalNameInput.value).toEqual(search); }); });
3,451
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/dropdown
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/dropdown/tests/MoveDropdownd.test.tsx
import { act, fireEvent, getByTestId as getByTestIdDefault, screen } from '@testing-library/react'; import { ACCENT_COLORS } from '@proton/shared/lib/colors'; import { LABEL_TYPE, MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { wait } from '@proton/shared/lib/helpers/promise'; import { Label } from '@proton/shared/lib/interfaces'; import { addApiMock } from '../../../helpers/test/api'; import { addToCache, minimalCache } from '../../../helpers/test/cache'; 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 { messageID } from '../../message/tests/Message.test.helpers'; import MoveDropdown from '../MoveDropdown'; const folder1Name = 'Folder1'; const folder1ID = 'folder-1-id'; const folder2Name = 'Folder2'; const folder2ID = 'folder-2-id'; const search = 'This label does not exists'; const props = { selectedIDs: [messageID], labelID: MAILBOX_LABEL_IDS.INBOX, onClose: jest.fn(), onLock: jest.fn(), breakpoints: {} as Breakpoints, }; const getMessage = (labelIDs: string[] = []) => { return { localID: messageID, data: { Sender: { Address: 'sender@sender.pm.me' }, ConversationID: 'conversationID', LabelIDs: [MAILBOX_LABEL_IDS.INBOX, ...labelIDs], }, } as MessageState; }; describe('MoveDropdown', () => { const setup = async (labelIDs: string[] = []) => { minimalCache(); addToCache('Labels', [ { ID: folder1ID, Name: folder1Name, Color: ACCENT_COLORS[0], Type: LABEL_TYPE.MESSAGE_FOLDER, Path: folder1Name, } as Label, { ID: folder2ID, Name: folder2Name, Color: ACCENT_COLORS[1], Type: LABEL_TYPE.MESSAGE_FOLDER, Path: folder2Name, } as Label, ]); const message = getMessage(labelIDs); store.dispatch(initialize(message)); const result = await render(<MoveDropdown {...props} />, false); return result; }; it("should display user's folders in the dropdowm", async () => { const { findAllByTestId, getAllByText } = await setup(); const folders = (await findAllByTestId(/label-dropdown:folder-radio-/)) as HTMLInputElement[]; // Should contain default folders (Inbox, Archive, Spam, Trash) + custom folders expect(folders.length).toBe(6); expect(folders[0].checked).toBe(false); expect(folders[1].checked).toBe(false); getAllByText(folder1Name); getAllByText(folder2Name); }); it('should move to a folder', async () => { const apiMock = jest.fn(() => ({ UndoToken: 1000 })); addApiMock(`mail/v4/messages/label`, apiMock); const { getByTestId } = await setup(); const radio1 = getByTestId(`label-dropdown:folder-radio-${folder1Name}`) as HTMLInputElement; // Check the first radio expect(radio1.checked).toBe(false); await act(async () => { fireEvent.click(radio1); }); expect(radio1.checked).toBe(true); // Apply the label const applyButton = getByTestId('move-dropdown:apply'); await act(async () => { fireEvent.click(applyButton); }); // label call has been made expect(apiMock).toHaveBeenCalled(); }); it('should create a folder from the button', async () => { const { getByTestId, queryAllByTestId } = await setup(); // Search for a label which does not exist const searchInput = getByTestId('folder-dropdown:search-folder'); await act(async () => { fireEvent.change(searchInput, { target: { value: search } }); // input has a debounce, so we need to wait for the onChange await wait(300); }); // No more option are displayed const labels = queryAllByTestId(/label-dropdown:folder-radio-/) as HTMLInputElement[]; expect(labels.length).toBe(0); // Click on the create label button const createLabelButton = getByTestId('folder-dropdown:add-folder'); fireEvent.click(createLabelButton); // Get the modal content const createLabelModal = screen.getByRole('dialog', { hidden: true }); const labelModalNameInput = getByTestIdDefault(createLabelModal, 'label/folder-modal:name') as HTMLInputElement; // Input is filled with the previous search content expect(labelModalNameInput.value).toEqual(search); }); it('should create a folder from the option', async () => { const { getByTestId, queryAllByTestId } = await setup(); // Search for a label which does not exist const searchInput = getByTestId('folder-dropdown:search-folder'); await act(async () => { fireEvent.change(searchInput, { target: { value: search } }); // input has a debounce, so we need to wait for the onChange await wait(300); }); // No more option are displayed const labels = queryAllByTestId(/label-dropdown:folder-radio-/) as HTMLInputElement[]; expect(labels.length).toBe(0); // Click on the create label option const createLabelOption = getByTestId('folder-dropdown:create-folder-option'); fireEvent.click(createLabelOption); // Get the modal content const createLabelModal = screen.getByRole('dialog', { hidden: true }); const labelModalNameInput = getByTestIdDefault(createLabelModal, 'label/folder-modal:name') as HTMLInputElement; // Input is filled with the previous search content expect(labelModalNameInput.value).toEqual(search); }); });
3,452
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/EORedirect.test.tsx
import { EOGetHistory, EORender } from '../../helpers/test/eo/EORender'; import { EOClearAll } from '../../helpers/test/eo/helpers'; import { MessageState } from '../../logic/messages/messagesTypes'; import EORedirect from './EORedirect'; describe('Encrypted Outside Redirection', () => { afterEach(EOClearAll); const getProps = (id?: string) => { return { id: id ? id : undefined, isStoreInitialized: true, messageState: {} as MessageState, setSessionStorage: jest.fn(), }; }; it('should redirect to Unlock page from /message if no id', async () => { const props = getProps(); await EORender(<EORedirect {...props} />, '/eo/message/:id'); // Redirects to /eo const history = EOGetHistory(); expect(history.location.pathname).toBe(`/eo`); }); it('should redirect to Unlock page from /reply if no id', async () => { const props = getProps(); await EORender(<EORedirect {...props} />, '/eo/reply/:id'); // Redirects to /eo const history = EOGetHistory(); expect(history.location.pathname).toBe(`/eo`); }); it('should redirect to Unlock page from /message if invalid id', async () => { const props = getProps('invalidID'); await EORender(<EORedirect {...props} />, '/eo/message/:id'); // Redirects to /eo const history = EOGetHistory(); expect(history.location.pathname).toBe(`/eo`); }); it('should redirect to Unlock page from /reply if invalid id', async () => { const props = getProps('invalidID'); await EORender(<EORedirect {...props} />, '/eo/reply/:id'); // Redirects to /eo const history = EOGetHistory(); expect(history.location.pathname).toBe(`/eo`); }); });
3,453
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/EORedirect.tsx
import { ReactNode, useEffect } from 'react'; import { Redirect } from 'react-router-dom'; import { Loader, useApi } from '@proton/components'; import { EO_REDIRECT_PATH, LOAD_RETRY_COUNT } from '../../constants'; import { useInitializeEOMessage } from '../../hooks/eo/useInitializeEOMessage'; import { useGetEODecryptedToken, useGetEOPassword } from '../../hooks/eo/useLoadEOMessage'; import { loadEOMessage } from '../../logic/eo/eoActions'; import { MessageState } from '../../logic/messages/messagesTypes'; import { useAppDispatch } from '../../logic/store'; interface Props { id?: string; isStoreInitialized: boolean; messageState: MessageState; setSessionStorage: (key: string, data: any) => void; children?: ReactNode; } const EORedirect = ({ id, isStoreInitialized, messageState, children, setSessionStorage }: Props) => { const dispatch = useAppDispatch(); const api = useApi(); const getPassword = useGetEOPassword(); const getDecryptedToken = useGetEODecryptedToken(); const initialize = useInitializeEOMessage(); const password = getPassword(); const decryptedToken = getDecryptedToken(); const shouldRedirectToUnlock = (!password || !decryptedToken) && isStoreInitialized; useEffect(() => { if (isStoreInitialized && messageState && messageState?.messageDocument?.initialized === undefined) { if ((messageState.loadRetry || 0) > LOAD_RETRY_COUNT) { return; } void initialize(); } }, [isStoreInitialized, messageState?.messageDocument?.initialized, messageState]); useEffect(() => { const loadMessage = async (id: string) => { await dispatch(loadEOMessage({ api, token: decryptedToken, id, password, set: setSessionStorage })); }; if (id && decryptedToken && password && isStoreInitialized && messageState === undefined) { void loadMessage(id); } }, [decryptedToken, password, id, messageState, isStoreInitialized]); if (!id) { return <Redirect to={EO_REDIRECT_PATH} />; } if (shouldRedirectToUnlock) { return <Redirect to={`${EO_REDIRECT_PATH}/${id}`} />; } if (!isStoreInitialized || !messageState || !messageState?.messageDocument?.initialized) { return <Loader />; } return <>{children}</>; }; export default EORedirect;
3,454
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message/EOExpirationTime.test.tsx
import { add, addHours, addMinutes, addSeconds, getUnixTime } from 'date-fns'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { clearAll, render, tick } from '../../../helpers/test/helper'; import EOExpirationTime from './EOExpirationTime'; describe('EOExpirationTime', () => { const date = new Date(2023, 0, 1, 10, 0, 1); const seconds = 50; beforeAll(() => { jest.useFakeTimers(); }); beforeEach(() => { jest.clearAllTimers(); jest.setSystemTime(date); }); afterAll(() => { jest.useRealTimers(); }); afterEach(() => { jest.clearAllMocks(); clearAll(); }); const setup = async (ExpirationTime: number) => { const result = await render( <EOExpirationTime message={{ localID: 'localID', data: { ExpirationTime } as Message }} /> ); const rerender = async (ExpirationTime: number) => { await result.rerender( <EOExpirationTime message={{ localID: 'localID', data: { ExpirationTime } as Message }} /> ); return result.queryByTestId('expiration-banner'); }; return { banner: result.queryByTestId('expiration-banner'), rerender }; }; it('should display expiration banner as button and expected content', async () => { // Set expiration time to two days const daysInSeconds = getUnixTime( add(date, { hours: 23, minutes: 59, seconds: 59, }) ); const result = await setup(daysInSeconds); let { banner } = result; // The message will expire in 1 day 23h 59min 59s, so we display "Expires in less than 24 hours" expect(banner?.textContent).toBe('Expires in less than 24 hours'); // The message will expire in 0 day 3h 59min 59s, so we display "Expires in less than 4 hours" const hoursInSeconds1 = getUnixTime(addHours(date, 4)); banner = await result.rerender(hoursInSeconds1); await tick(); expect(banner?.textContent).toBe('Expires in less than 4 hours'); // The message will expire in 0 day 1h 59min 59s, so we display "Expires in less than 2 hour" const hoursInSeconds2 = getUnixTime(addHours(date, 2)); banner = await result.rerender(hoursInSeconds2); await tick(); expect(banner?.textContent).toBe('Expires in less than 2 hours'); // The message will expire in 0 day 0h 1min 59s, so we display "Expires in 2 minutes" const minutesInSeconds = getUnixTime(addMinutes(date, 2)); banner = await result.rerender(minutesInSeconds); await tick(); expect(banner?.textContent).toBe('Expires in 2 minutes'); // The message will expire in 0 day 0h 0min Xs, so we display "Expires in less than X seconds" banner = await result.rerender(getUnixTime(addSeconds(date, seconds))); const value = Number(/\d+/.exec(banner?.textContent || '')?.[0]); await tick(); expect(value).toBeLessThanOrEqual(seconds); }); });
3,455
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message/EOExpirationTime.tsx
import { differenceInHours, differenceInMinutes, endOfHour, endOfMinute, formatDistanceToNow, startOfHour, startOfMinute, } from 'date-fns'; import { c, msgid } from 'ttag'; import { Button, ButtonLike, Href } from '@proton/atoms'; import { Icon, Prompt, Tooltip, useModalState } from '@proton/components'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { getMessageExpirationDate } from '../../../helpers/message/messageExpirationTime'; import useExpiration from '../../../hooks/useExpiration'; import { MessageState } from '../../../logic/messages/messagesTypes'; interface Props { message: MessageState; } const getButtonText = (expirationDate: Date, messageExpiresSoon: boolean) => { if (messageExpiresSoon) { const hoursDiff = differenceInHours(endOfHour(expirationDate), startOfHour(new Date())); if (hoursDiff === 0) { const minutesDiff = differenceInMinutes(endOfMinute(expirationDate), startOfMinute(new Date())); // translator: When message expires in less than one hour we display "Expires in 10 minutes" return c('Info').ngettext( msgid`Expires in ${minutesDiff} minute`, `Expires in ${minutesDiff} minutes`, minutesDiff ); } // translator: When message expires in more than one hour we display "Expires in less than X hours" return c('Info').ngettext( msgid`Expires in less than ${hoursDiff} hour`, `Expires in less than ${hoursDiff} hours`, hoursDiff ); } const formattedDate = formatDistanceToNow(expirationDate); return c('Info').t`Expires in ${formattedDate}`; }; const EOExpirationTime = ({ message }: Props) => { const [expirationModalProps, setExpirationModalOpen] = useModalState(); const { onClose } = expirationModalProps; const { expirationMessage, expiresInLessThan24Hours } = useExpiration(message); const expirationDate = getMessageExpirationDate(message); if (!expirationDate) { return null; } const buttonMessage = getButtonText(expirationDate, expiresInLessThan24Hours); return ( <> <Tooltip title={expirationMessage}> <ButtonLike as="span" color={expiresInLessThan24Hours ? 'danger' : undefined} data-testid="expiration-banner" className="inline-flex flex-align-items-center w-full md:w-auto on-mobile-flex-justify-center mb-3 px-2" onClick={() => setExpirationModalOpen(true)} > <Icon name="hourglass" className="flex-item-noshrink ml-1" /> <span className="ml-2">{buttonMessage}</span> </ButtonLike> </Tooltip> <Prompt title={c('Title').t`Message will expire`} buttons={[<Button autoFocus type="submit" onClick={onClose}>{c('Action').t`Got it`}</Button>]} {...expirationModalProps} > <div className="mr-2">{expirationMessage}</div> <Href href={getKnowledgeBaseUrl('/expiration')}>{c('Link').t`Learn more`}</Href> </Prompt> </> ); }; export default EOExpirationTime;
3,456
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message/EOHeaderExpanded.tsx
import { MouseEvent } from 'react'; import { c } from 'ttag'; import { Icon, useToggle } from '@proton/components'; import { scrollIntoView } from '@proton/shared/lib/helpers/dom'; import { EO_DEFAULT_MAILSETTINGS } from '@proton/shared/lib/mail/eo/constants'; import { getRecipients } from '@proton/shared/lib/mail/messages'; import clsx from '@proton/utils/clsx'; import noop from '@proton/utils/noop'; import { recipientsToRecipientOrGroup } from '../../../helpers/message/messageRecipients'; import { MessageState } from '../../../logic/messages/messagesTypes'; import { Breakpoints } from '../../../models/utils'; import ItemAttachmentIcon from '../../list/ItemAttachmentIcon'; import ItemDate from '../../list/ItemDate'; import ExtraImages from '../../message/extras/ExtraImages'; import MailRecipients from '../../message/recipients/MailRecipients'; import RecipientItem from '../../message/recipients/RecipientItem'; import RecipientType from '../../message/recipients/RecipientType'; import EOExpirationTime from './EOExpirationTime'; interface Props { labelID: string; message: MessageState; messageLoaded: boolean; onLoadRemoteImages: () => void; onLoadEmbeddedImages: () => void; breakpoints: Breakpoints; parentMessageRef: React.RefObject<HTMLElement>; } const EOHeaderExpanded = ({ labelID, message, messageLoaded, onLoadRemoteImages, onLoadEmbeddedImages, breakpoints, parentMessageRef, }: Props) => { const { state: showDetails, toggle: toggleDetails } = useToggle(); const { isNarrow } = breakpoints; const recipients = getRecipients(message.data); const recipientsOrGroup = recipientsToRecipientOrGroup(recipients); const handleAttachmentIconClick = (e: MouseEvent) => { e.stopPropagation(); scrollIntoView(parentMessageRef.current, { block: 'end' }); }; return ( <div className={clsx([ 'message-header eo-message-header px-7 sm:px-0 message-header-expanded is-outbound border-bottom', showDetails && 'message-header--showDetails', !messageLoaded && 'is-loading', ])} data-testid={`message-header-expanded:${message.data?.Subject}`} > <div className="flex flex-nowrap flex-align-items-center mx-0 mb-3 sm:mx-8"> <span className="flex flex-item-fluid flex-nowrap mr-2"> <div className={clsx(['flex flex-nowrap', !messageLoaded && 'flex-item-fluid'])}> <RecipientType label={c('Label Recipient').t`From`} className={clsx([ 'flex flex-align-items-start flex-nowrap', !messageLoaded && 'flex-item-fluid', ])} > <RecipientItem recipientOrGroup={{ recipient: message.data?.Sender }} isLoading={!messageLoaded} isOutside onContactDetails={noop} onContactEdit={noop} /> </RecipientType> </div> </span> <div className="message-header-metas-container flex flex-align-items-center flex-item-noshrink" data-testid="message:message-header-metas" > {messageLoaded && ( <> <span> <ItemAttachmentIcon onClick={handleAttachmentIconClick} element={message.data} className="ml-2" /> </span> {!isNarrow && ( <ItemDate className="ml-2" element={message.data} labelID={labelID} useTooltip /> )} </> )} {!messageLoaded && <span className="message-header-metas ml-2 inline-flex" />} </div> </div> <div className="flex flex-nowrap flex-align-items-center on-mobile-flex-wrap mx-0 sm:mx-8 mt-0 mb-4"> <MailRecipients message={message} recipientsOrGroup={recipientsOrGroup} isLoading={!messageLoaded} isOutside expanded={showDetails} toggleDetails={toggleDetails} onContactDetails={noop} onContactEdit={noop} /> </div> {showDetails && ( <div className="my-2 mx-8 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> )} {!showDetails && isNarrow && ( <div className="flex flex-justify-space-between flex-align-items-center border-top mx-0 sm:mx-8 pt-2 mb-2"> {messageLoaded ? ( <> <div className="flex flex-nowrap flex-align-items-center"> <Icon name="calendar-grid" className="mx-2" /> <ItemDate element={message.data} labelID={labelID} useTooltip /> </div> </> ) : ( <span className="message-header-metas inline-flex" /> )} </div> )} <section className="message-header-extra border-top mx-0 sm:mx-8 pt-2"> <div className="mt-2 flex flex-row message-banners-container"> {messageLoaded && <EOExpirationTime message={message} />} <ExtraImages messageImages={message.messageImages} type="remote" onLoadImages={onLoadRemoteImages} mailSettings={EO_DEFAULT_MAILSETTINGS} /> <ExtraImages messageImages={message.messageImages} type="embedded" onLoadImages={onLoadEmbeddedImages} mailSettings={EO_DEFAULT_MAILSETTINGS} /> </div> </section> </div> ); }; export default EOHeaderExpanded;
3,457
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message/EOMessage.scss
@import '~@proton/styles/scss/lib/index'; .eo-message-header { &#{&} { border-radius: 0; @include media('>small') { .message-banners-container { > * { margin-block-end: 0.85em; margin-inline-end: 0.85em; } } } .message-recipient-item-expanded-content { padding-block-start: 0.5em; } .message-recipient-expanded .message-recipient-item-expanded-content { padding-block-start: 0.2em; } } }
3,458
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message/EOMessageBody.tsx
import { useMemo, useRef } from 'react'; import { EO_DEFAULT_MAILSETTINGS } from '@proton/shared/lib/mail/eo/constants'; import { isPlainText } from '@proton/shared/lib/mail/messages'; import clsx from '@proton/utils/clsx'; import { MailboxContainerContextProvider } from '../../../containers/mailbox/MailboxContainerProvider'; import { locateBlockquote } from '../../../helpers/message/messageBlockquote'; import { MessageState } from '../../../logic/messages/messagesTypes'; import MessageBodyIframe from '../../message/MessageBodyIframe'; interface Props { message: MessageState; messageLoaded: boolean; bodyLoaded: boolean; sourceMode: boolean; originalMessageMode: boolean; onBlockquoteToggle?: () => void; } const EOMessageBody = ({ message, messageLoaded, bodyLoaded, sourceMode: inputSourceMode, originalMessageMode, onBlockquoteToggle, }: Props) => { const bodyRef = useRef<HTMLDivElement>(null); const iframeRef = useRef<HTMLIFrameElement>(null); const plain = isPlainText(message.data); const [content, blockquote] = useMemo( () => plain ? [message.messageDocument?.plainText as string, ''] : locateBlockquote(message.messageDocument?.document), [message.messageDocument?.document?.innerHTML, message.messageDocument?.plainText, plain] ); const encryptedMode = messageLoaded && !!message.errors?.decryption?.length; const sourceMode = !encryptedMode && inputSourceMode; const decryptingMode = !encryptedMode && !sourceMode && !bodyLoaded && messageLoaded; const loadingMode = !messageLoaded; const contentMode = !encryptedMode && !sourceMode && bodyLoaded; const isBlockquote = blockquote !== ''; return ( <div ref={bodyRef} className={clsx([ 'message-content scroll-horizontal-if-needed relative bodyDecrypted bg-norm color-norm px-7 py-1', plain && 'plain', ])} data-testid="message-content:body" > {encryptedMode && <pre>{message.data?.Body}</pre>} {sourceMode && <pre>{message.decryption?.decryptedBody}</pre>} {(loadingMode || decryptingMode) && ( <> <div className="message-content-loading-placeholder mb-1 max-w-custom" style={{ '--max-w-custom': '8em' }} /> <div className="message-content-loading-placeholder mb-1 max-w-custom" style={{ '--max-w-custom': '50em' }} /> <div className="message-content-loading-placeholder mb-1 max-w-custom" style={{ '--max-w-custom': '40em' }} /> <div className="message-content-loading-placeholder mb-1 max-w-custom" style={{ '--max-w-custom': '50em' }} /> <div className="message-content-loading-placeholder mb-1 max-w-custom" style={{ '--max-w-custom': '15em' }} /> <div className="message-content-loading-placeholder max-w-custom" style={{ '--max-w-custom': '8em' }} /> </> )} {contentMode && ( <MailboxContainerContextProvider containerRef={null} elementID={undefined} isResizing={false}> <MessageBodyIframe iframeRef={iframeRef} content={content} blockquoteContent={blockquote} showBlockquote={originalMessageMode} showBlockquoteToggle={isBlockquote} onBlockquoteToggle={onBlockquoteToggle} onContentLoaded={() => {}} isPlainText={plain} message={message} labelID="" isOutside mailSettings={EO_DEFAULT_MAILSETTINGS} /> </MailboxContainerContextProvider> )} </div> ); }; export default EOMessageBody;
3,459
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message/EOMessageHeader.tsx
import { useHistory } from 'react-router'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Icon, Loader, Tooltip } from '@proton/components'; import clsx from '@proton/utils/clsx'; import { EO_MAX_REPLIES_NUMBER, EO_REPLY_REDIRECT_PATH } from '../../../constants'; import { MessageState } from '../../../logic/messages/messagesTypes'; interface Props { message: MessageState; messageLoaded: boolean; id: string; numberOfReplies: number; } const EOMessageHeader = ({ message, messageLoaded, id, numberOfReplies }: Props) => { const history = useHistory(); const subject = message.data?.Subject; const canReply = numberOfReplies < EO_MAX_REPLIES_NUMBER; if (!messageLoaded) { return <Loader />; } const handleReply = () => { history.push(`${EO_REPLY_REDIRECT_PATH}/${id}`); }; const replyButton = ( <Button onClick={handleReply} color="norm" className="ml-auto flex flex-align-items-center" disabled={!canReply} data-testid="eoreply:button" > <Icon name="arrow-up-and-left-big" className="on-rtl-mirror mr-2" alt={c('Title').t`Reply`} /> <span>{c('Action').t`Reply securely`}</span> </Button> ); return ( <div className={clsx([ 'flex flex-align-items-center border-bottom px-7 py-5', !canReply && 'flex-justify-space-between', ])} > <h1 className="text-ellipsis m-0 mb-2 eo-layout-title" title={subject} data-testid="eo:subject"> {subject} </h1> {canReply ? ( replyButton ) : ( <Tooltip title={c('Info').t`You have reached the maximum number of 5 replies.`}> <span>{replyButton}</span> </Tooltip> )} </div> ); }; export default EOMessageHeader;
3,460
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message/ViewEOMessage.tsx
import { useRef, useState } from 'react'; import { useRouteMatch } from 'react-router-dom'; import { useActiveBreakpoint } from '@proton/components'; import { EO_DEFAULT_MAILSETTINGS } from '@proton/shared/lib/mail/eo/constants'; import { EOUrlParams } from '../../../helpers/eo/eoUrl'; import { useLoadEOEmbeddedImages, useLoadEORemoteImages } from '../../../hooks/eo/useLoadEOImages'; import { useLoadEOMessage } from '../../../hooks/eo/useLoadEOMessage'; import MessageFooter from '../../message/MessageFooter'; import EORedirect from '../EORedirect'; import EOHeaderExpanded from './EOHeaderExpanded'; import EOMessageBody from './EOMessageBody'; import EOMessageHeader from './EOMessageHeader'; import './EOMessage.scss'; interface Props { setSessionStorage: (key: string, data: any) => void; } const ViewEOMessage = ({ setSessionStorage }: Props) => { const breakpoints = useActiveBreakpoint(); const elementRef = useRef<HTMLDivElement>(null); const [originalMessageMode, setOriginalMessageMode] = useState(false); const match = useRouteMatch<EOUrlParams>(); const { id } = match.params; const loadRemoteImages = useLoadEORemoteImages(EO_DEFAULT_MAILSETTINGS); const loadEmbeddedImages = useLoadEOEmbeddedImages(id || ''); const { isStoreInitialized, messageState, message, outsideKey } = useLoadEOMessage({ id, setSessionStorage }); const messageLoaded = !!messageState; const bodyLoaded = !!messageState?.messageDocument?.initialized; const toggleOriginalMessage = () => setOriginalMessageMode(!originalMessageMode); return ( <EORedirect id={id} isStoreInitialized={isStoreInitialized} messageState={messageState} setSessionStorage={setSessionStorage} > {id && messageState && ( <main className="ui-standard sm:shadow-lifted shadow-color-primary relative no-scroll w-full max-w-custom mx-auto eo-layout" style={{ '--max-w-custom': '52rem' }}> <div ref={elementRef}> <EOMessageHeader message={messageState} messageLoaded={messageLoaded} id={id} numberOfReplies={message.Replies.length} /> <EOHeaderExpanded labelID="test" message={messageState} messageLoaded={messageLoaded} onLoadRemoteImages={loadRemoteImages} onLoadEmbeddedImages={loadEmbeddedImages} breakpoints={breakpoints} parentMessageRef={elementRef} /> <EOMessageBody message={messageState} messageLoaded={messageLoaded} bodyLoaded={bodyLoaded} sourceMode={false} onBlockquoteToggle={toggleOriginalMessage} originalMessageMode={originalMessageMode} /> <MessageFooter message={messageState} outsideKey={outsideKey} /> </div> </main> )} </EORedirect> ); }; export default ViewEOMessage;
3,461
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message/recipients/EORecipientSingle.tsx
import { usePopperAnchor } from '@proton/components'; import { Recipient } from '@proton/shared/lib/interfaces'; import RecipientItemSingle from '../../../message/recipients/RecipientItemSingle'; interface Props { recipient: Recipient; isRecipient?: boolean; isExpanded?: boolean; } const EORecipientSingle = ({ recipient, isRecipient, isExpanded }: Props) => { const { anchorRef, isOpen, toggle, close } = usePopperAnchor<HTMLButtonElement>(); return ( <RecipientItemSingle recipient={recipient} anchorRef={anchorRef} isOpen={isOpen} toggle={toggle} close={close} isOutside isRecipient={isRecipient} isExpanded={isExpanded} /> ); }; export default EORecipientSingle;
3,462
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message/recipients/EORecipientsList.tsx
import { Recipient } from '@proton/shared/lib/interfaces'; import noop from '@proton/utils/noop'; import { recipientsToRecipientOrGroup } from '../../../../helpers/message/messageRecipients'; import RecipientsList from '../../../message/recipients/RecipientsList'; interface Props { list: Recipient[]; isLoading: boolean; showDropdown?: boolean; } const EORecipientsList = ({ list, isLoading, showDropdown }: Props) => { const recipientsOrGroup = recipientsToRecipientOrGroup(list); return ( <RecipientsList isLoading={isLoading} recipientsOrGroup={recipientsOrGroup} showDropdown={showDropdown} isOutside onContactDetails={noop} onContactEdit={noop} /> ); }; export default EORecipientsList;
3,463
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message/tests/ViewEOMessage.attachments.test.tsx
import { fireEvent, waitFor, within } from '@testing-library/react'; import humanSize from '@proton/shared/lib/helpers/humanSize'; import { VERIFICATION_STATUS } from '@proton/shared/lib/mail/constants'; import { assertIcon } from '../../../../helpers/test/assertion'; import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../../helpers/test/crypto'; import { EOClearAll } from '../../../../helpers/test/eo/helpers'; import { tick } from '../../../../helpers/test/render'; import { setup } from './ViewEOMessage.test.helpers'; describe('Encrypted Outside message attachments', () => { 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', Headers: { 'content-id': 'cid-embedded', 'content-disposition': 'inline' }, }; 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); beforeAll(async () => { await setupCryptoProxyForTesting(); }); afterAll(async () => { await releaseCryptoProxy(); }); afterEach(EOClearAll); it('should show EO attachments with their correct icon', async () => { const { getAllByTestId } = await setup({ attachments: Attachments, numAttachments: NumAttachments }); const items = await waitFor(() => 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 () => { const body = '<div><img src="cid:cid-embedded"/></div>'; const { getByTestId } = await setup({ attachments: Attachments, numAttachments: NumAttachments, body: body }); const header = await waitFor(() => 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(); const { getAllByTestId } = await setup({ attachments: Attachments, numAttachments: NumAttachments }); const items = await waitFor(() => 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/); }); });
3,464
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message/tests/ViewEOMessage.banners.test.tsx
import { screen, waitFor } from '@testing-library/react'; import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../../helpers/test/crypto'; import { EOClearAll } from '../../../../helpers/test/eo/helpers'; import { setup } from './ViewEOMessage.test.helpers'; describe('Encrypted Outside message banners', () => { beforeAll(async () => { await setupCryptoProxyForTesting(); }); afterAll(async () => { await releaseCryptoProxy(); }); afterEach(EOClearAll); it('should show EO expiration banner', async () => { const ExpirationTime = new Date().getTime() / 1000 + 1000; await setup({ expirationTime: ExpirationTime }); const banner = await waitFor(() => screen.findByTestId('expiration-banner')); expect(banner.textContent).toMatch(/Expires in/); }); });
3,465
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message/tests/ViewEOMessage.encryption.test.tsx
import { findByText, waitFor } from '@testing-library/react'; import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../../helpers/test/crypto'; import { EOBody, EOClearAll, EOSubject } from '../../../../helpers/test/eo/helpers'; import { getIframeRootDiv } from '../../../message/tests/Message.test.helpers'; import { setup } from './ViewEOMessage.test.helpers'; describe('Encrypted Outside message view encryption', () => { beforeAll(async () => { await setupCryptoProxyForTesting(); }); afterAll(async () => { await releaseCryptoProxy(); }); afterEach(EOClearAll); it('should decrypt and render a EO message', async () => { const { getByText, container } = await setup(); await waitFor(() => getByText(EOSubject)); const iframeContent = await getIframeRootDiv(container); await findByText(iframeContent, EOBody); }); });
3,466
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message/tests/ViewEOMessage.images.test.tsx
import { findByRole, findByText, fireEvent, screen, waitFor } from '@testing-library/react'; import { VERIFICATION_STATUS } from '@proton/shared/lib/mail/constants'; import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../../helpers/test/crypto'; import { EOBody, EOClearAll, EOSubject } from '../../../../helpers/test/eo/helpers'; import { getIframeRootDiv } from '../../../message/tests/Message.test.helpers'; import { setup } from './ViewEOMessage.test.helpers'; const blobURL = 'blobURL'; const embeddedCID = 'cid-embedded'; const embeddedAttachment = { ID: 'id3', Name: 'attachment-name-png.png', Size: 300, MIMEType: 'image/png', // Allow to skip actual download of the file content Preview: { data: new Uint8Array([1, 2]), filename: 'preview', signatures: [], verified: VERIFICATION_STATUS.NOT_SIGNED, }, KeyPackets: [], nameSplitStart: 'attachment-name-p', nameSplitEnd: 'ng.png', Headers: { 'content-id': embeddedCID, 'content-disposition': 'inline' }, }; describe('Encrypted Outside message images', () => { beforeAll(async () => { // mockWindowLocation(windowHostname); await setupCryptoProxyForTesting(); }); afterAll(async () => { await releaseCryptoProxy(); }); afterEach(() => { EOClearAll(); // resetWindowLocation(); }); it('should load remote images', async () => { const imageURL = 'imageURL'; const body = `<div>${EOBody}<img src="${imageURL}"/></div>`; const { container } = await setup({ body }); // wait for the message to be fully loaded await waitFor(() => screen.getByText(EOSubject)); const iframe = await getIframeRootDiv(container); // Content is displayed await findByText(iframe, EOBody); // Check for image placeholder const placeholder = iframe.querySelector('.proton-image-placeholder') as HTMLImageElement; expect(placeholder).not.toBe(null); // Click on load banner screen.getByText('This message contains remote content.'); let loadButton = screen.getByTestId('remote-content:load'); fireEvent.click(loadButton); // Check that image has been loaded const image = await findByRole(iframe, 'img'); expect(image.getAttribute('src')).toEqual(imageURL); }); it('should load embedded images', async () => { const body = `<div>${EOBody}<img src="cid:${embeddedCID}"/></div>`; // Need to mock this function to mock the blob url window.URL.createObjectURL = jest.fn(() => blobURL); const { container } = await setup({ body, attachments: [embeddedAttachment] }); // wait for the message to be fully loaded await waitFor(() => screen.getByText(EOSubject)); const iframe = await getIframeRootDiv(container); // Content is displayed await findByText(iframe, EOBody); // Check for image placeholder const placeholder = iframe.querySelector('.proton-image-placeholder') as HTMLImageElement; expect(placeholder).not.toBe(null); // Click on load banner const loadButton = screen.getByText('Load embedded images'); fireEvent.click(loadButton); // Check that image has been loaded const image = await findByRole(iframe, 'img'); expect(image.getAttribute('src')).toEqual(blobURL); }); });
3,467
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message/tests/ViewEOMessage.reply.test.tsx
import { screen, waitFor } from '@testing-library/react'; import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../../helpers/test/crypto'; import { EOClearAll, reply } from '../../../../helpers/test/eo/helpers'; import { EOMessageReply } from '../../../../logic/eo/eoType'; import { setup } from './ViewEOMessage.test.helpers'; describe('Encrypted Outside message reply', () => { beforeAll(async () => { await setupCryptoProxyForTesting(); }); afterAll(async () => { await releaseCryptoProxy(); }); afterEach(EOClearAll); it('should not be able to click on reply button if max replies has been reached', async () => { await setup({ replies: [reply, reply, reply, reply, reply] as EOMessageReply[] }); const replyButton = await waitFor(() => screen.findByTestId('eoreply:button')); expect(replyButton).toHaveAttribute('disabled'); }); it('should be able to click on reply button if max replies has not been reached', async () => { await setup({ replies: [reply, reply, reply, reply] as EOMessageReply[] }); const replyButton = await waitFor(() => screen.findByTestId('eoreply:button')); expect(replyButton).not.toHaveAttribute('disabled'); }); });
3,468
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/message/tests/ViewEOMessage.test.helpers.tsx
import { EORender } from '../../../../helpers/test/eo/EORender'; import { EOInitStore, EOOriginalMessageOptions } from '../../../../helpers/test/eo/helpers'; import ViewEOMessage from '../ViewEOMessage'; export const setup = async (options?: EOOriginalMessageOptions) => { await EOInitStore('message', options); const renderResult = await EORender(<ViewEOMessage setSessionStorage={jest.fn()} />, '/eo/message/:id'); return renderResult; };
3,469
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/reply/EOComposer.tsx
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { EditorMetadata, useHandler } from '@proton/components'; import { PublicKeyReference } from '@proton/crypto'; import { EO_DEFAULT_MAILSETTINGS, eoDefaultUserSettings } from '@proton/shared/lib/mail/eo/constants'; import { DIRECTION } from '@proton/shared/lib/mail/mailSettings'; import { isPlainText as testIsPlainText } from '@proton/shared/lib/mail/messages'; import noop from '@proton/utils/noop'; import { MESSAGE_ACTIONS } from '../../../constants'; import { setContent } from '../../../helpers/message/messageContent'; import { createNewDraft } from '../../../helpers/message/messageDraft'; import { mergeMessages } from '../../../helpers/message/messages'; import { useEOAttachments } from '../../../hooks/eo/useEOAttachments'; import { MessageState, OutsideKey } from '../../../logic/messages/messagesTypes'; import { MessageChange } from '../../composer/Composer'; import ComposerContent from '../../composer/ComposerContent'; import { ExternalEditorActions } from '../../composer/editor/EditorWrapper'; import ComposerInsertImageModal from '../../composer/modals/ComposerInsertImageModal'; import EOReplyFooter from './EOReplyFooter'; import EOReplyHeader from './EOReplyHeader'; interface Props { referenceMessage: MessageState; id: string; publicKey?: PublicKeyReference[]; outsideKey?: OutsideKey; numberOfReplies: number; } const EOComposer = ({ referenceMessage, id, publicKey, outsideKey, numberOfReplies }: Props) => { // Indicates that the composer is in its initial opening // Needed to be able to force focus only at first time const [opening, setOpening] = useState(true); // Indicates that the composer is open but the edited message is not yet ready // Needed to prevent edition while data is not ready const [editorReady, setEditorReady] = useState(false); const [modelMessage, setModelMessage] = useState<MessageState>( createNewDraft( MESSAGE_ACTIONS.REPLY, referenceMessage, EO_DEFAULT_MAILSETTINGS, eoDefaultUserSettings, [], // eslint-disable-next-line @typescript-eslint/no-unused-vars (ID) => { return undefined; }, true ) as MessageState ); // Get a ref on the editor to trigger insertion of embedded images const editorActionsRef = useRef<ExternalEditorActions>(); // Manage focus from the container yet keeping logic in each component const contentFocusRef = useRef<() => void>(noop); const lock = opening; const [blockquoteExpanded, setBlockquoteExpanded] = useState(true); const isPlainText = testIsPlainText(modelMessage.data); const rightToLeft = modelMessage.data?.RightToLeft ? DIRECTION.RIGHT_TO_LEFT : DIRECTION.LEFT_TO_RIGHT; const metadata: EditorMetadata = useMemo( () => ({ supportPlainText: false, isPlainText, supportRightToLeft: true, rightToLeft, supportImages: true, supportDefaultFontSelector: false, blockquoteExpanded, setBlockquoteExpanded, }), [isPlainText, rightToLeft, blockquoteExpanded, setBlockquoteExpanded] ); useEffect(() => { if (editorReady) { setOpening(false); } }, [editorReady]); // Manage focus at opening useEffect(() => { if (!opening) { contentFocusRef.current(); } }, [opening]); const handleChange: MessageChange = useHandler((update) => { setModelMessage((modelMessage) => { const messageChanges = update instanceof Function ? update(modelMessage) : update; return mergeMessages(modelMessage, messageChanges); }); }); const handleChangeContent = useHandler((content: string, refreshEditor: boolean = false) => { setModelMessage((modelMessage) => { setContent(modelMessage, content); const newModelMessage = { ...modelMessage }; if (refreshEditor) { editorActionsRef.current?.setContent(newModelMessage); } return newModelMessage; }); }); const { imagesToInsert, setImagesToInsert, handleAddAttachments, handleRemoveAttachment, handleUploadImage } = useEOAttachments({ message: modelMessage, onChange: handleChange, editorActionsRef, publicKey, }); const handleEditorReady = useCallback((editorActions) => { setEditorReady(true); editorActionsRef.current = editorActions; }, []); const handleCloseInsertImageModal = () => { setImagesToInsert([]); }; return ( <> {imagesToInsert.length > 0 && ( <ComposerInsertImageModal files={imagesToInsert} onClose={handleCloseInsertImageModal} onSelect={handleUploadImage} /> )} <EOReplyHeader message={referenceMessage} /> <div className="composer-body-container eo-composer flex flex-column flex-nowrap flex-item-fluid-auto max-w-full"> <ComposerContent message={modelMessage} disabled={lock} onEditorReady={handleEditorReady} onChange={handleChange} onChangeContent={handleChangeContent} onAddAttachments={handleAddAttachments} onRemoveAttachment={handleRemoveAttachment} outsideKey={outsideKey} mailSettings={EO_DEFAULT_MAILSETTINGS} editorMetadata={metadata} /> </div> <EOReplyFooter id={id} onAddAttachments={handleAddAttachments} message={modelMessage} publicKeys={publicKey} outsideKey={outsideKey} numberOfReplies={numberOfReplies} /> </> ); }; export default EOComposer;
3,470
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/reply/EOReply.tsx
import { useRouteMatch } from 'react-router-dom'; import { EOUrlParams } from '../../../helpers/eo/eoUrl'; import { useLoadEOMessage } from '../../../hooks/eo/useLoadEOMessage'; import EORedirect from '../EORedirect'; import EOComposer from './EOComposer'; import './EOreply.scss'; interface Props { setSessionStorage: (key: string, data: any) => void; } const EOReply = ({ setSessionStorage }: Props) => { const match = useRouteMatch<EOUrlParams>(); const { id } = match.params; const { message, isStoreInitialized, messageState, outsideKey } = useLoadEOMessage({ id, setSessionStorage }); return ( <EORedirect id={id} isStoreInitialized={isStoreInitialized} messageState={messageState} setSessionStorage={setSessionStorage} > {id && messageState && ( <main className="ui-standard sm:shadow-lifted shadow-color-primary relative no-scroll w-full max-w-custom mx-auto eo-layout" style={{ '--max-w-custom': '52rem' }}> <EOComposer referenceMessage={messageState} id={id} publicKey={message.PublicKey} outsideKey={outsideKey} numberOfReplies={message.Replies.length} /> </main> )} </EORedirect> ); }; export default EOReply;
3,471
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/reply/EOReplyFooter.tsx
import { useState } from 'react'; import { useHistory } from 'react-router'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Tooltip } from '@proton/components'; import { PublicKeyReference } from '@proton/crypto'; import { EO_REPLY_NUM_ATTACHMENTS_LIMIT } from '@proton/shared/lib/mail/eo/constants'; import { EO_MAX_REPLIES_NUMBER, EO_MESSAGE_REDIRECT_PATH } from '../../../constants'; import { useSendEO } from '../../../hooks/eo/useSendEO'; import { MessageKeys, MessageState } from '../../../logic/messages/messagesTypes'; import AttachmentsButton from '../../attachment/AttachmentsButton'; interface Props { id: string; onAddAttachments: (files: File[]) => void; message: MessageState; publicKeys?: PublicKeyReference[]; outsideKey?: MessageKeys; numberOfReplies: number; } const EOReplyFooter = ({ id, onAddAttachments, message, publicKeys, outsideKey, numberOfReplies }: Props) => { const history = useHistory(); const [isSending, setIsSending] = useState(false); const isUnderLimit = numberOfReplies < EO_MAX_REPLIES_NUMBER; const canSend = !isSending && isUnderLimit; const { send } = useSendEO({ message, publicKeys, outsideKey, }); const handleSend = async () => { setIsSending(true); try { await send(); } catch { setIsSending(false); } }; const handleCancel = () => { history.push(`${EO_MESSAGE_REDIRECT_PATH}/${id}`); }; const sendButton = ( <Button className="ml-4" size="large" color="norm" type="button" onClick={handleSend} disabled={!canSend} data-testid="send-eo" > {c('Action').t`Send`} </Button> ); const canAddAttachment = (message.data?.Attachments.length || 0) < 10; const attachmentButton = ( <AttachmentsButton onAddAttachments={onAddAttachments} data-testid="eo-composer:attachment-button" disabled={!canAddAttachment} /> ); return ( <div className="flex flex-justify-space-between border-top p-4 mx-3"> <Button size="large" color="weak" type="button" onClick={handleCancel}> {c('Action').t`Cancel`} </Button> <div className="flex"> {canAddAttachment ? ( attachmentButton ) : ( /* * translator: EO_REPLY_NUM_ATTACHMENTS_LIMIT is the number of attachments maximum that we can have in an encrypted outside message * Currently it's 10 written in digits */ <Tooltip title={c('Info').t`Maximum number of attachments (${EO_REPLY_NUM_ATTACHMENTS_LIMIT}) exceeded.`} > <span className="flex">{attachmentButton}</span> </Tooltip> )} {isUnderLimit ? ( sendButton ) : ( <Tooltip title={c('Info').t`You have reached the maximum number of 5 replies.`}> <span>{sendButton}</span> </Tooltip> )} </div> </div> ); }; export default EOReplyFooter;
3,472
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/reply/EOReplyHeader.tsx
import { c } from 'ttag'; import clsx from '@proton/utils/clsx'; import noop from '@proton/utils/noop'; import { MessageState } from '../../../logic/messages/messagesTypes'; import RecipientItem from '../../message/recipients/RecipientItem'; import RecipientType from '../../message/recipients/RecipientType'; interface Props { message: MessageState; } const EOReplyHeader = ({ message }: Props) => { const subject = message.data?.Subject; return ( <> <div className="flex flex-align-items-center px-7 py-5"> <h1 className="eo-layout-title text-ellipsis m-0 mb-2" title={subject}> {subject} </h1> </div> <div className="message-header eo-message-header message-header-expanded is-outbound border-top border-bottom px-7 py-4"> <RecipientType label={c('Label').t`From:`} className={clsx(['flex flex-align-items-start flex-nowrap mb-3'])} > <RecipientItem recipientOrGroup={{ recipient: message.data?.EORecipient }} isLoading={false} isOutside onContactDetails={noop} onContactEdit={noop} /> </RecipientType> <RecipientType label={c('Label').t`To:`} className={clsx(['flex flex-align-items-start flex-nowrap message-recipient-expanded'])} > <RecipientItem recipientOrGroup={{ recipient: message.data?.Sender }} isLoading={false} isOutside onContactDetails={noop} onContactEdit={noop} /> </RecipientType> </div> </> ); }; export default EOReplyHeader;
3,473
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/reply/EOreply.scss
@import '~@proton/styles/scss/lib/index'; @import '../../composer/composer'; .eo { &-message-header { border-radius: 0; padding-block-end: 1em; .message-recipient-expanded .message-recipient-item-expanded-content { padding-block-start: 0.2em; } } &-composer { // need to size it, because EO does not have dimensions like the composer container block-size: em(300); @include media('<=xsmall') { margin-inline: 0; } .composer-content { margin-block-end: 0; } .editor { border: 0; padding-inline: 0.5em; @include media('<=xsmall') { padding-inline: 0; } } .composer-attachments-list { margin-inline: 0.75em; } &-attachments-list { padding-inline: 1em; padding-block-end: 0.5em; border-block-start: 0; .composer-attachment-list-wrapper, .message-attachmentList { padding-inline: 0; } } } }
3,474
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/reply
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/reply/tests/EOReply.attachments.test.tsx
import { act, fireEvent, waitFor } from '@testing-library/react'; import { wait } from '@proton/shared/lib/helpers/promise'; import { EO_REPLY_NUM_ATTACHMENTS_LIMIT } from '@proton/shared/lib/mail/eo/constants'; import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../../helpers/test/crypto'; import { EOClearAll, EOSubject } from '../../../../helpers/test/eo/helpers'; import { waitForNotification } from '../../../../helpers/test/helper'; import { tick } from '../../../../helpers/test/render'; import { setup } from './EOReply.test.helpers'; describe('EO Reply attachments', () => { beforeAll(async () => { await setupCryptoProxyForTesting(); }); afterAll(async () => { await releaseCryptoProxy(); }); afterEach(EOClearAll); const fileName = 'file.txt'; const fileType = 'text/plain'; const fileContent = 'File content'; const blob = new Blob([fileContent], { type: fileType }); const file = new File([blob], fileName, { type: fileType }); it('should add attachments to a EO message and be able to preview them', async () => { const { getByText, getByTestId } = await setup(); await waitFor(() => getByText(EOSubject)); const inputAttachment = getByTestId('composer-attachments-button') as HTMLInputElement; await act(async () => { fireEvent.change(inputAttachment, { target: { files: [file] } }); await wait(100); }); const toggleList = await waitFor(() => getByTestId('attachment-list:toggle')); fireEvent.click(toggleList); await tick(); const item = getByTestId('attachment-item').querySelectorAll('button')[1]; fireEvent.click(item); await tick(); const preview = document.querySelector('.file-preview'); expect(preview).toBeDefined(); expect(preview?.textContent).toMatch(new RegExp(fileName)); getByText(fileContent); }); it('should not be possible to add 10+ attachments', async () => { const { getByText, getByTestId } = await setup(); await waitFor(() => getByText(EOSubject)); // Add 11 files const inputAttachment = getByTestId('composer-attachments-button') as HTMLInputElement; await act(async () => { fireEvent.change(inputAttachment, { target: { files: [file, file, file, file, file, file, file, file, file, file, file] }, }); await wait(100); }); await waitForNotification(`Maximum number of attachments (${EO_REPLY_NUM_ATTACHMENTS_LIMIT}) exceeded`); }); });
3,475
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/reply
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/reply/tests/EOReply.reply.test.tsx
import { waitFor } from '@testing-library/react'; import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../../helpers/test/crypto'; import { EOClearAll, reply } from '../../../../helpers/test/eo/helpers'; import { setup } from './EOReply.test.helpers'; describe('EO Reply if max replies has been reached', function () { beforeAll(async () => { await setupCryptoProxyForTesting(); }); afterAll(async () => { await releaseCryptoProxy(); }); afterEach(EOClearAll); it('should have the sending button disabled if max replies has been reached', async () => { const { getByTestId } = await setup({ replies: [reply, reply, reply, reply, reply] }); const sendButton = await waitFor(() => getByTestId('send-eo')); expect(sendButton).toHaveAttribute('disabled'); }); it('should have the sending button enabled if max replies has not been reached', async () => { const { getByTestId } = await setup({ replies: [reply, reply, reply] }); const sendButton = await waitFor(() => getByTestId('send-eo')); expect(sendButton).not.toHaveAttribute('disabled'); }); });
3,476
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/reply
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/reply/tests/EOReply.sending.test.tsx
import { CryptoProxy } from '@proton/crypto'; import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../../helpers/test/crypto'; import { EOGetHistory } from '../../../../helpers/test/eo/EORender'; import { EOClearAll, EOPassword, validID } from '../../../../helpers/test/eo/helpers'; import { send } from './EOReply.test.helpers'; jest.setTimeout(20000); describe('EO Reply send', () => { beforeAll(async () => { await setupCryptoProxyForTesting(); }); afterAll(async () => { await releaseCryptoProxy(); }); afterEach(EOClearAll); it('should send a text/html reply', async () => { const expectedBlockquote = ` <blockquote class="protonmail_quote" type="cite"> Test EO body </blockquote>`; const sendRequest = await send(); const { data: decryptedReplyBody } = await CryptoProxy.decryptMessage({ armoredMessage: sendRequest.data.ReplyBody, passwords: [EOPassword], }); // Format the reply to remove all \n and spaces to check if they are equal const formattedReplyBody = decryptedReplyBody.replaceAll(/[ \n]/g, ''); const formattedExpectedBody = expectedBlockquote.replaceAll(/[ \n]/g, ''); expect(formattedReplyBody).toContain(formattedExpectedBody); const history = EOGetHistory(); expect(history.location.pathname).toBe(`/eo/message/${validID}`); }); });
3,477
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/reply
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/reply/tests/EOReply.test.helpers.tsx
import { RenderResult, fireEvent } from '@testing-library/react'; import { EORender } from '../../../../helpers/test/eo/EORender'; import { EOInitStore, EOOriginalMessageOptions } from '../../../../helpers/test/eo/helpers'; import { addApiMock, waitForNoNotification, waitForNotification } from '../../../../helpers/test/helper'; import EOReply from '../EOReply'; export const setup = async (options?: EOOriginalMessageOptions) => { await EOInitStore('reply', options); const renderResult = await EORender(<EOReply setSessionStorage={jest.fn()} />, '/eo/reply/:id'); return renderResult; }; export const clickSend = async (renderResult: RenderResult) => { const sendSpy = jest.fn(() => Promise.resolve({ Reply: {} })); addApiMock(`mail/v4/eo/reply`, sendSpy, 'post'); const sendButton = await renderResult.findByTestId('send-eo'); fireEvent.click(sendButton); await waitForNotification('Message sent'); const sendRequest = (sendSpy.mock.calls[0] as any[])[0]; expect(sendRequest.method).toBe('post'); await waitForNoNotification(); return sendRequest; }; export const send = async () => { try { const renderResult = await setup(); // Write a test "T" in the message body fireEvent.keyDown(renderResult.container, { key: 'T' }); return await clickSend(renderResult); } catch (error: any) { console.log('Error in sending helper', error); throw error; } };
3,478
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/unlock/EOUnlock.test.tsx
import { act, fireEvent } from '@testing-library/react'; import { wait } from '@proton/shared/lib/helpers/promise'; import { addApiMock } from '../../../helpers/test/api'; import { releaseCryptoProxy, setupCryptoProxyForTesting } from '../../../helpers/test/crypto'; import { EOGetHistory, EORender, EOResetHistory } from '../../../helpers/test/eo/EORender'; import { EOClearAll, EODecryptedToken, EOInvalidPassword, EOPassword, getEOEncryptedMessage, mockConsole, validID, } from '../../../helpers/test/eo/helpers'; import { waitForNotification } from '../../../helpers/test/helper'; import { init } from '../../../logic/eo/eoActions'; import { store } from '../../../logic/eo/eoStore'; import { EOMessage } from '../../../logic/eo/eoType'; import EOUnlock from './EOUnlock'; const props = { setSessionStorage: jest.fn(), }; describe('Encrypted Outside Unlock', () => { beforeAll(async () => { await setupCryptoProxyForTesting(); }); afterAll(async () => { await releaseCryptoProxy(); }); beforeEach(async () => { await store.dispatch(init({ get: jest.fn() })); }); afterEach(EOClearAll); it('should display an error if the EO id is not present', async () => { const { getByText } = await EORender(<EOUnlock {...props} />); getByText('Error'); getByText('Sorry, this message does not exist or has already expired.'); }); it('should display an error if the EO id is invalid', async () => { addApiMock('mail/v4/eo/token/invalidID', () => ({})); EOResetHistory(['/eo/invalidID']); const { getByText } = await EORender(<EOUnlock {...props} />, '/eo/:id'); getByText('Error'); getByText('Sorry, this message does not exist or has already expired.'); }); it('should see the form if the EO id is valid and an error if password is invalid', async () => { mockConsole(); EOResetHistory([`/eo/${validID}`]); // Get token from id mock addApiMock(`mail/v4/eo/token/${validID}`, () => ({ Token: 'token' })); const { getByText, getByTestId } = await EORender(<EOUnlock {...props} />, '/eo/:id'); // Unlock form is displayed getByText('Unlock message'); const unlockInput = getByTestId('unlock:input'); // Type the password fireEvent.change(unlockInput, { target: { value: EOInvalidPassword } }); fireEvent.keyDown(unlockInput, { key: 'Enter' }); await waitForNotification('Wrong mailbox password'); }); it('should see the form if the EO id is valid and redirect if password is valid', async () => { mockConsole('log'); const token = await getEOEncryptedMessage(EODecryptedToken, EOPassword); EOResetHistory([`/eo/${validID}`]); // Get token from id mock addApiMock(`mail/v4/eo/token/${validID}`, () => ({ Token: token })); // Get EO message from decryptedToken and password addApiMock('mail/v4/eo/message', () => ({ Message: {} as EOMessage, PublicKey: '', })); const { getByText, getByTestId } = await EORender(<EOUnlock {...props} />, '/eo/:id'); // Unlock form is displayed getByText('Unlock message'); const unlockInput = getByTestId('unlock:input'); // Type the password fireEvent.change(unlockInput, { target: { value: EOPassword } }); fireEvent.keyDown(unlockInput, { key: 'Enter' }); // Wait for redirection await act(async () => { await wait(2000); }); // Redirects to /eo/message/validID const history = EOGetHistory(); expect(history.location.pathname).toBe(`/eo/message/${validID}`); }); });
3,479
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/unlock/EOUnlock.tsx
import { useEffect, useState } from 'react'; import { useRouteMatch } from 'react-router'; import { c } from 'ttag'; import { Href } from '@proton/atoms'; import { Loader } from '@proton/components'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { EOUrlParams } from '../../../helpers/eo/eoUrl'; import { useLoadEOMessage } from '../../../hooks/eo/useLoadEOMessage'; import { useLoadEOToken } from '../../../hooks/eo/useLoadEOToken'; import MessageDecryptForm from './MessageDecryptForm'; interface Props { setSessionStorage: (key: string, data: any) => void; } const EOUnlock = ({ setSessionStorage }: Props) => { const match = useRouteMatch<EOUrlParams>(); const { id } = match.params; const { encryptedToken, isStoreInitialized } = useLoadEOMessage({ id, setSessionStorage }); const { handleTryUnlock } = useLoadEOToken({ id, encryptedToken, setSessionStorage }); const [isError, setIsError] = useState(true); useEffect(() => { if (encryptedToken && encryptedToken !== '') { setIsError(false); } }, [encryptedToken]); if (!isStoreInitialized) { return <Loader />; } return ( <main className="ui-standard sm:shadow-lifted shadow-color-primary relative no-scroll w-full max-w-custom mx-auto eo-layout" style={{ '--max-w-custom': '30rem' }}> <div className="eo-layout-header"> {isError && <h1 className="eo-layout-title mt-4" data-testid="eo:error">{c('Title').t`Error`}</h1>} </div> <div className="eo-layout-main-content"> {isError ? ( c('Info').t`Sorry, this message does not exist or has already expired.` ) : ( <MessageDecryptForm onSubmit={handleTryUnlock} /> )} </div> <div className="flex p-4 ml-auto mb-8"> <Href className="mx-auto" href={getKnowledgeBaseUrl('/open-password-protected-emails')}>{c('Action') .t`Need help?`}</Href> </div> </main> ); }; export default EOUnlock;
3,480
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/eo/unlock/MessageDecryptForm.tsx
import { KeyboardEvent, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { InputFieldTwo, PasswordInputTwo } from '@proton/components'; import { MAIL_APP_NAME } from '@proton/shared/lib/constants'; interface Props { onSubmit: (password: string) => void; } const MessageDecryptForm = ({ onSubmit }: Props) => { const [password, setPassword] = useState<string>(''); const handleSubmit = () => { onSubmit(password); }; return ( <form onSubmit={(e) => e.preventDefault()} className="px-7 sm:px-0"> <h1 className="eo-layout-title mb-0 mt-2 md:mt-0">{c('Info').t`Unlock message`}</h1> <div className="mt-1 color-weak mb-8">{MAIL_APP_NAME}</div> <InputFieldTwo autoFocus id="password" label={c('Label').t`Password`} bigger value={password} onValue={setPassword} onKeyDown={(event: KeyboardEvent<HTMLInputElement>) => { if (event.key === 'Enter') { handleSubmit(); } }} as={PasswordInputTwo} rootClassName="mt-2" data-testid="unlock:input" /> <Button size="large" color="norm" type="button" data-testid="unlock:submit" fullWidth onClick={handleSubmit} >{c('Action').t`Read message`}</Button> </form> ); }; export default MessageDecryptForm;
3,481
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/ClearBrowserDataModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { ModalProps, Prompt } from '@proton/components'; import { useEncryptedSearchContext } from '../../containers/EncryptedSearchProvider'; const ClearBrowserDataModal = (rest: ModalProps) => { const { onClose } = rest; const { esDelete } = useEncryptedSearchContext(); const handleClear = () => { void esDelete(); onClose?.(); }; return ( <Prompt title={c('Info').t`Disable message content search`} buttons={[ <Button color="norm" onClick={handleClear}>{c('Info').t`Clear data`}</Button>, <Button onClick={onClose}>{c('Action').t`Cancel`}</Button>, ]} {...rest} > {c('Info') .t`Clearing browser data also deactivates message content search on this device. All messages will need to be downloaded again to search within them.`} </Prompt> ); }; export default ClearBrowserDataModal;
3,482
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/MailDefaultHandlerModal.tsx
import { c } from 'ttag'; import { Button, Href } from '@proton/atoms'; import { ModalProps, Prompt } from '@proton/components'; import { MAIL_APP_NAME } from '@proton/shared/lib/constants'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { registerMailToProtocolHandler } from '../../helpers/url'; const MailDefaultHandlerModal = (props: ModalProps) => { const { onClose } = props; const handleAskForPermission = () => { registerMailToProtocolHandler(); onClose?.(); }; return ( <Prompt title={c('Info').t`Default email application`} buttons={[ <Button color="norm" onClick={handleAskForPermission}>{c('Action').t`Set as default`}</Button>, <Button onClick={onClose}>{c('Action').t`Cancel`}</Button>, ]} {...props} > <span>{c('Info') .t`Set ${MAIL_APP_NAME} as your default email application for this browser. ${MAIL_APP_NAME} will open automatically when you click an email link.`}</span> <Href className="ml-2" href={getKnowledgeBaseUrl('/set-default-email-handler')} title="Default mail handler" > {c('Info').t`Learn more`} </Href> </Prompt> ); }; export default MailDefaultHandlerModal;
3,483
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/MailHeader.test.tsx
import { fireEvent } from '@testing-library/react'; import { screen } from '@testing-library/react'; import loudRejection from 'loud-rejection'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { addApiMock, addToCache, clearAll, getDropdown, getHistory, minimalCache, render, tick, } from '../../helpers/test/helper'; import { Breakpoints } from '../../models/utils'; import MailHeader from './MailHeader'; loudRejection(); const getProps = () => ({ labelID: 'labelID', elementID: undefined, selectedIDs: [], location: getHistory().location, history: getHistory(), breakpoints: {} as Breakpoints, onSearch: jest.fn(), expanded: true, onToggleExpand: jest.fn(), onOpenShortcutsModal: jest.fn(), }); const user = { Email: 'Email', DisplayName: 'DisplayName', Name: 'Name', isFree: true, UsedSpace: 10, MaxSpace: 100, }; describe('MailHeader', () => { let props: ReturnType<typeof getProps>; const setup = async () => { minimalCache(); addToCache('User', user); addApiMock('payments/v4/plans', () => ({})); addApiMock('contacts/v4/contacts', () => ({ Contacts: [] })); addApiMock('payments/v4/subscription/latest', () => ({})); addApiMock('core/v4/experiments', () => ({})); props = getProps(); const result = await render(<MailHeader {...props} />, false); const search = result.getByTitle('Search'); const openSearch = async () => { fireEvent.click(search); await tick(); const overlay = document.querySelector('div[role="dialog"].overlay') as HTMLDivElement; const submitButton = overlay.querySelector('button[type="submit"]') as HTMLButtonElement; const submit = () => fireEvent.click(submitButton); return { overlay, submitButton, submit }; }; return { ...result, openSearch }; }; // Not found better to test // It's hard to override sso mode constant const assertAppLink = (element: HTMLElement, href: string) => { const link = element.closest('a'); expect(link?.getAttribute('href')).toBe(href); }; afterEach(clearAll); describe('Core features', () => { it('should open user dropdown', async () => { const { getByText: getByTextHeader } = await setup(); const userButton = getByTextHeader(user.DisplayName); fireEvent.click(userButton); const dropdown = await getDropdown(); const { textContent } = dropdown; expect(textContent).toContain('Proton shop'); expect(textContent).toContain('Sign out'); }); it('should show upgrade button', async () => { const { getByTestId } = await setup(); const upgradeLabel = getByTestId('cta:upgrade-plan'); assertAppLink(upgradeLabel, '/mail/upgrade?ref=upsell_mail-button-1'); }); }); describe('Search features', () => { it('should search with keyword', async () => { const searchTerm = 'test'; const { getByTestId, openSearch, rerender } = await setup(); const { submit } = await openSearch(); const keywordInput = document.getElementById('search-keyword') as HTMLInputElement; fireEvent.change(keywordInput, { target: { value: searchTerm } }); submit(); const history = getHistory(); expect(history.length).toBe(2); expect(history.location.pathname).toBe('/all-mail'); expect(history.location.hash).toBe(`#keyword=${searchTerm}`); await rerender(<MailHeader {...props} />); const searchKeyword = getByTestId('search-keyword') as HTMLInputElement; expect(searchKeyword.value).toBe(searchTerm); }); it('should search with keyword and location', async () => { const searchTerm = 'test'; const { openSearch } = await setup(); const { submit } = await openSearch(); const keywordInput = document.getElementById('search-keyword') as HTMLInputElement; fireEvent.change(keywordInput, { target: { value: searchTerm } }); const draftButton = screen.getByTestId(`location-${MAILBOX_LABEL_IDS.DRAFTS}`); fireEvent.click(draftButton); submit(); const history = getHistory(); expect(history.length).toBe(2); expect(history.location.pathname).toBe('/drafts'); expect(history.location.hash).toBe(`#keyword=${searchTerm}`); }); }); });
3,484
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/MailHeader.tsx
import { ReactNode, memo, useCallback } from 'react'; import { useLocation } from 'react-router-dom'; import { FloatingButton, Icon, PrivateHeader, RebrandingFeedbackModal, TopNavbarListItemFeedbackButton, UserDropdown, useFolders, useHasRebrandingFeedback, useLabels, useModalState, } from '@proton/components'; import { APPS } from '@proton/shared/lib/constants'; import useMailModel from 'proton-mail/hooks/useMailModel'; import { MESSAGE_ACTIONS } from '../../constants'; import { useOnCompose } from '../../containers/ComposeProvider'; import { getLabelName } from '../../helpers/labels'; import { isColumnMode } from '../../helpers/mailSettings'; import { ComposeTypes } from '../../hooks/composer/useCompose'; import { layoutActions } from '../../logic/layout/layoutSlice'; import { selectLayoutIsExpanded } from '../../logic/layout/layoutSliceSelectors'; import { useAppDispatch, useAppSelector } from '../../logic/store'; import { Breakpoints } from '../../models/utils'; import MailSearch from './search/MailSearch'; interface Props { labelID: string; elementID: string | undefined; selectedIDs: string[]; breakpoints: Breakpoints; toolbar?: ReactNode | undefined; settingsButton?: ReactNode; } const MailHeader = ({ labelID, elementID, selectedIDs = [], breakpoints, toolbar, settingsButton }: Props) => { const location = useLocation(); const [labels = []] = useLabels(); const [folders = []] = useFolders(); const mailSettings = useMailModel('MailSettings'); const hasRebrandingFeedback = useHasRebrandingFeedback(); const dispatch = useAppDispatch(); const expanded = useAppSelector(selectLayoutIsExpanded); const onToggleExpand = useCallback(() => dispatch(layoutActions.toggleSidebarExpand()), []); const onCompose = useOnCompose(); const [feedbackModalProps, setFeedbackModalOpen] = useModalState(); const hideMenuButton = breakpoints.isNarrow && !!elementID; const hideUpsellButton = (breakpoints.isNarrow || breakpoints.isTablet) && (!!elementID || selectedIDs.length !== 0); const labelName = getLabelName(labelID, labels, folders); const isColumn = isColumnMode(mailSettings); /** Search is displayed everytime except when we are on message view with row mode */ const displaySearch = !(!isColumn && elementID); return ( <> <PrivateHeader userDropdown={<UserDropdown app={APPS.PROTONMAIL} />} hideMenuButton={hideMenuButton} hideUpsellButton={hideUpsellButton} title={labelName} feedbackButton={ hasRebrandingFeedback ? ( <TopNavbarListItemFeedbackButton onClick={() => setFeedbackModalOpen(true)} /> ) : null } actionArea={ breakpoints.isNarrow || breakpoints.isTablet || (breakpoints.isSmallDesktop && elementID) ? ( <div className="flex flex-nowrap flex-justify-space-between"> {toolbar} {!elementID && ( <MailSearch breakpoints={breakpoints} labelID={labelID} location={location} columnMode={isColumn} /> )} </div> ) : displaySearch ? ( <MailSearch breakpoints={breakpoints} labelID={labelID} location={location} columnMode={isColumn} /> ) : ( <>{toolbar}</> ) } expanded={expanded} onToggleExpand={onToggleExpand} isNarrow={breakpoints.isNarrow} settingsButton={settingsButton} floatingButton={ <FloatingButton onClick={() => onCompose({ type: ComposeTypes.newMessage, action: MESSAGE_ACTIONS.NEW })} > <Icon size={24} name="pen" className="m-auto" /> </FloatingButton> } /> <RebrandingFeedbackModal {...feedbackModalProps} /> </> ); }; export default memo(MailHeader);
3,485
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/OnboardingChecklistModal.tsx
import { ModalProps, ModalTwo, ModalTwoContent, ModalTwoHeader } from '@proton/components'; import UsersOnboardingChecklist from '../checklist/UsersOnboardingChecklist'; const OnboardingChecklistModal = (rest: ModalProps) => { return ( <ModalTwo {...rest}> <ModalTwoHeader /> <ModalTwoContent> <UsersOnboardingChecklist hideDismissButton /> </ModalTwoContent> </ModalTwo> ); }; export default OnboardingChecklistModal;
3,486
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/SpotlightEmailForwarding.tsx
import React, { useRef } from 'react'; import { c } from 'ttag'; import { SettingsLink, Spotlight, useSpotlightShow } from '@proton/components/components'; import { FeatureCode, useFlag } from '@proton/components/containers'; import { useActiveBreakpoint, useSpotlightOnFeature, useUser, useWelcomeFlags } from '@proton/components/hooks'; import { APPS } from '@proton/shared/lib/constants'; import { hasPaidMail } from '@proton/shared/lib/user/helpers'; interface Props { children: React.ReactNode; } /** * Spotlight to introduce email forwarding to existing users * @see MAILWEB-4476 */ const SpotlightEmailForwarding = ({ children }: Props) => { const ref = useRef<HTMLDivElement>(null); const [user] = useUser(); const isPayingForMail = hasPaidMail(user); const isEmailForwardingEnabled = useFlag('EmailForwarding'); const [{ isWelcomeFlow }] = useWelcomeFlags(); const { isNarrow } = useActiveBreakpoint(); const releaseUTCDate = Date.UTC(2023, 10, 1, 12); // 1st November 2023 at 12:00 UTC const { show: showSpotlight, onDisplayed, onClose, } = useSpotlightOnFeature( FeatureCode.EmailForwardingSpotlight, !isWelcomeFlow && !isNarrow && isEmailForwardingEnabled && isPayingForMail, { alpha: 0, beta: releaseUTCDate, default: releaseUTCDate, } ); const show = useSpotlightShow(showSpotlight); // Wrap the children in a div to avoid conflicts with tooltip return ( <Spotlight originalPlacement="bottom" show={show} onDisplayed={onDisplayed} onClose={onClose} anchorRef={ref} type="new" style={{ maxWidth: '25rem' }} content={ <> <p className="m-0">{c('Spotlight').t`You can now automatically forward your emails to anyone!`}</p> <SettingsLink path="/auto-reply" app={APPS.PROTONMAIL}>{c('Link') .t`Set up email forwarding`}</SettingsLink> </> } > <div ref={ref}>{children}</div> </Spotlight> ); }; export default SpotlightEmailForwarding;
3,487
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/search/AdvancedSearch.tsx
import { FormEvent, useMemo, useRef, useState } from 'react'; import { useHistory } from 'react-router-dom'; import { add, fromUnixTime, getUnixTime, isAfter, isBefore, isEqual, sub } from 'date-fns'; import { History } from 'history'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { DateInput, Label, Option, PrimaryButton, SelectTwo, useAddresses, useUser } from '@proton/components'; import { ESIndexingState, contentIndexingProgress } from '@proton/encrypted-search'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { validateEmailAddress } from '@proton/shared/lib/helpers/email'; import isDeepEqual from '@proton/shared/lib/helpers/isDeepEqual'; import { omit } from '@proton/shared/lib/helpers/object'; import { changeSearchParams, getSearchParams } from '@proton/shared/lib/helpers/url'; import { Recipient } from '@proton/shared/lib/interfaces/Address'; import clsx from '@proton/utils/clsx'; import useMailModel from 'proton-mail/hooks/useMailModel'; import { useEncryptedSearchContext } from '../../../containers/EncryptedSearchProvider'; import { getHumanLabelID } from '../../../helpers/labels'; import { extractSearchParameters, keywordToString } from '../../../helpers/mailboxUrl'; import AddressesInput from '../../composer/addresses/AddressesInput'; import EncryptedSearchField from './AdvancedSearchFields/EncryptedSearchField'; import LocationField from './AdvancedSearchFields/LocationField'; import SearchField from './AdvancedSearchFields/SearchField'; interface SearchModel { keyword: string; labelID: string; from: Recipient[]; to: Recipient[]; address?: string; begin?: Date; end?: Date; wildcard?: number; filter?: string; } const UNDEFINED = undefined; const AUTO_WILDCARD = undefined; const ALL_ADDRESSES = 'all'; const { ALL_MAIL, ALMOST_ALL_MAIL } = MAILBOX_LABEL_IDS; const DEFAULT_MODEL_WITHOUT_LABEL_ID: Omit<SearchModel, 'labelID'> = { keyword: '', from: [], to: [], address: ALL_ADDRESSES, wildcard: AUTO_WILDCARD, filter: UNDEFINED, begin: undefined, end: undefined, }; const getRecipients = (value = '') => value .split(',') .filter(validateEmailAddress) .map((Address) => ({ Address, Name: '' })); const formatRecipients = (recipients: Recipient[] = []) => recipients.map(({ Address }) => Address).join(','); const initializeModel = (history: History, selectedLabelID: string, searchInputValue: string) => { const { keyword, address, wildcard, from, to, begin, end } = extractSearchParameters(history.location); const { filter } = getSearchParams(history.location.search); return { ...(keyword && { labelID: selectedLabelID }), keyword: searchInputValue ? keyword || '' : '', address: address || ALL_ADDRESSES, wildcard, from: getRecipients(from), to: getRecipients(to), begin: begin ? fromUnixTime(begin) : UNDEFINED, end: end ? sub(fromUnixTime(end), { days: 1 }) : UNDEFINED, filter, }; }; // Get right keyword value depending on the current situation const getKeyword = ({ keyword, reset, isNarrow }: { keyword: string; reset?: boolean; isNarrow: boolean }) => { if (reset) { return UNDEFINED; } const value = isNarrow ? keyword : keywordToString(keyword); if (value) { return value; } return UNDEFINED; }; interface Props { isNarrow: boolean; showEncryptedSearch: boolean; onClose: () => void; esIndexingProgressState: ESIndexingState; showMore: boolean; toggleShowMore: () => void; searchInputValue: string; labelID: string; } const AdvancedSearch = ({ isNarrow, showEncryptedSearch, onClose, esIndexingProgressState, showMore, searchInputValue, toggleShowMore, labelID, }: Props) => { const searchInputRef = useRef<HTMLInputElement>(null); const history = useHistory(); const [addresses] = useAddresses(); const { AlmostAllMail } = useMailModel('MailSettings'); const DEFAULT_MODEL: SearchModel = { ...DEFAULT_MODEL_WITHOUT_LABEL_ID, labelID: AlmostAllMail ? ALMOST_ALL_MAIL : ALL_MAIL, }; const [model, updateModel] = useState<SearchModel>({ ...DEFAULT_MODEL, ...initializeModel(history, labelID, searchInputValue), }); const [user] = useUser(); const { esStatus } = useEncryptedSearchContext(); const { isDBLimited, lastContentTime, esEnabled } = esStatus; const senderListAnchorRef = useRef<HTMLDivElement>(null); const toListAnchorRef = useRef<HTMLDivElement>(null); const handleSubmit = (event: FormEvent, reset?: boolean) => { event.preventDefault(); // necessary to not run a basic submission event.stopPropagation(); // necessary to not submit normal search from header const { keyword, begin, end, wildcard, from, to, address, filter } = reset ? DEFAULT_MODEL : model; history.push( changeSearchParams(`/${getHumanLabelID(model.labelID)}`, history.location.hash, { keyword: getKeyword({ keyword, reset, isNarrow }), from: from.length ? formatRecipients(from) : UNDEFINED, to: to.length ? formatRecipients(to) : UNDEFINED, address: address === ALL_ADDRESSES ? UNDEFINED : address, begin: begin ? String(getUnixTime(begin)) : UNDEFINED, end: end ? String(getUnixTime(add(end, { days: 1 }))) : UNDEFINED, wildcard: wildcard ? String(wildcard) : UNDEFINED, filter, sort: UNDEFINED, // Make sure to reset sort parameter when performing an advanced search page: UNDEFINED, // Reset page parameter when performing an advanced search so that search results are shown from the first page }) ); onClose(); }; const handleStartDateChange = async (begin: Date | undefined) => { if (esEnabled && isDBLimited && begin) { const wasIndexingDone = await contentIndexingProgress.isIndexingDone(user.ID); // In an encrypted search context, it's not possible to search for data that predates the timestamp of the most recently indexed content if (wasIndexingDone && isBefore(begin, lastContentTime)) { return; } } if (!model.end || isBefore(begin || -Infinity, model.end)) { updateModel({ ...model, begin }); } }; const handleEndDateChange = (end: Date | undefined) => { if (!model.begin || isEqual(model.begin, end || Infinity) || isAfter(end || Infinity, model.begin)) { updateModel({ ...model, end }); } }; const handleClear = () => { updateModel((currentModel) => ({ ...currentModel, keyword: '' })); searchInputRef.current?.focus(); }; const handleReset = (event: FormEvent) => { event.preventDefault(); // necessary to block native reset behaviour updateModel(DEFAULT_MODEL); searchInputRef.current?.focus(); }; const canReset = useMemo(() => { return !isDeepEqual(omit(model, ['labelID']), omit(DEFAULT_MODEL, ['labelID'])); }, [model]); return ( <form name="advanced-search" onSubmit={handleSubmit} onReset={handleReset}> <div className="flex border-bottom px-1 pt-1 pb-2"> <SearchField unstyled value={model.keyword} onChange={({ target }) => updateModel({ ...model, keyword: target.value })} onSubmit={handleSubmit} showSearchIcon={false} ref={searchInputRef} suffix={ model.keyword ? ( <Button shape="ghost" color="weak" size="small" type="button" data-testid="advanced-search:clear" onClick={handleClear} > {c('Action').t`Clear`} </Button> ) : null } esEnabled={esEnabled} /> </div> <div className="pt-4 px-5 pb-0"> {showEncryptedSearch && <EncryptedSearchField esIndexingProgressState={esIndexingProgressState} />} <div> <LocationField value={model.labelID} onChange={(nextLabelId) => updateModel({ ...model, labelID: nextLabelId })} /> </div> <hr className="my-4" /> {showMore && ( <> <div className="mt-4"> <Button className="mb-2 w-full md:w-auto" onClick={toggleShowMore} data-testid="advanced-search:show-less" title={c('Action').t`Show fewer search options`} > {c('Action').t`Fewer search options`} </Button> </div> <div className="mb-2 flex flex-justify-space-between on-mobile-flex-column"> <div className={clsx(['flex-item-fluid', isNarrow ? 'pr-0' : 'pr-4'])}> <Label className="advanced-search-label text-semibold" htmlFor="begin-date">{c('Label') .t`From`}</Label> <DateInput placeholder={c('Placeholder').t`Start date`} id="begin-date" data-testid="advanced-search:start-date" value={model.begin} onChange={handleStartDateChange} /> </div> <div className="flex-item-fluid"> <Label className="advanced-search-label text-semibold" htmlFor="end-date">{c('Label') .t`To`}</Label> <DateInput placeholder={c('Placeholder').t`End date`} id="end-date" data-testid="advanced-search:end-date" value={model.end} onChange={handleEndDateChange} /> </div> </div> <div className="mb-2" ref={senderListAnchorRef}> <Label title={c('Label').t`Sender`} className="advanced-search-label text-semibold" htmlFor="from" >{c('Label').t`Sender`}</Label> <AddressesInput id="from" dataTestId="advanced-search:sender" recipients={model.from} onChange={(from) => updateModel({ ...model, from })} placeholder={c('Placeholder').t`Name or email address`} anchorRef={senderListAnchorRef} /> </div> <div className="mb-2" ref={toListAnchorRef}> <Label title={c('Label').t`Recipient`} className="advanced-search-label text-semibold" htmlFor="to" >{c('Label').t`Recipient`}</Label> <AddressesInput id="to" dataTestId="advanced-search:recipient" recipients={model.to} onChange={(to) => updateModel({ ...model, to })} placeholder={c('Placeholder').t`Name or email address`} anchorRef={toListAnchorRef} /> </div> <div className="mb-2"> <Label title={c('Label').t`Address`} className="advanced-search-label text-semibold" htmlFor="address" >{c('Label').t`Address`}</Label> <SelectTwo id="address" data-testid="advanced-search:address" value={model.address} onChange={({ value }) => updateModel({ ...model, address: value })} > {[{ ID: ALL_ADDRESSES, Email: c('Option').t`All` }, ...addresses].map( ({ ID, Email }) => ( <Option key={ID} value={ID} title={Email} /> ) )} </SelectTwo> </div> </> )} </div> <div className="my-4 mx-5 flex flex-align-items-center flex-justify-space-between"> {showMore ? null : ( <Button data-testid="advanced-search:show-more" className="mb-2 w-full md:w-auto" onClick={toggleShowMore} title={c('Action').t`Show more search options`} > {c('Action').t`More search options`} </Button> )} <div className="ml-auto w-full md:w-auto"> {canReset ? ( <Button data-testid="advanced-search:reset" className="mb-2 w-full md:w-auto mr-4" type="reset" title={c('Action').t`Reset search form`} >{c('Action').t`Reset`}</Button> ) : null} <PrimaryButton data-testid="advanced-search:submit" type="submit" className="mb-2 w-full md:w-auto" >{c('Action').t`Search`}</PrimaryButton> </div> </div> </form> ); }; export default AdvancedSearch;
3,488
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/search/MailSearch.tsx
import { useEffect, useState } from 'react'; import { Location } from 'history'; import { FeatureCode, TopNavbarListItemSearchButton, generateUID, useAddresses, useFolders, useLabels, usePopperAnchor, useProgressiveRollout, useToggle, useUser, } from '@proton/components'; import { ADVANCED_SEARCH_OVERLAY_CLOSE_EVENT } from '../../../constants'; import { useEncryptedSearchContext } from '../../../containers/EncryptedSearchProvider'; import { isEncryptedSearchAvailable } from '../../../helpers/encryptedSearch/esUtils'; import { extractSearchParameters } from '../../../helpers/mailboxUrl'; import { useClickMailContent } from '../../../hooks/useClickMailContent'; import { Breakpoints } from '../../../models/utils'; import AdvancedSearch from './AdvancedSearch'; import MailSearchInput from './MailSearchInput'; import MailSearchSpotlight from './MailSearchSpotlight'; import SearchOverlay from './SearchOverlay'; import './Search.scss'; interface Props { breakpoints: Breakpoints; labelID: string; location: Location; columnMode: boolean; } const MailSearch = ({ breakpoints, labelID, location, columnMode }: Props) => { const [uid] = useState(generateUID('advanced-search-overlay')); const isESUserInterfaceAvailable = useProgressiveRollout(FeatureCode.ESUserInterface); const { anchorRef, isOpen, open, close } = usePopperAnchor<HTMLInputElement>(); const searchParams = extractSearchParameters(location); const [searchInputValue, setSearchInputValue] = useState(searchParams.keyword || ''); const [user] = useUser(); const [, loadingLabels] = useLabels(); const [, loadingFolders] = useFolders(); const [, loadingAddresses] = useAddresses(); const { esStatus, cacheIndexedDB, closeDropdown, esIndexingProgressState } = useEncryptedSearchContext(); const { dropdownOpened } = esStatus; const showEncryptedSearch = isEncryptedSearchAvailable(user, isESUserInterfaceAvailable); // Show more from inside AdvancedSearch to persist the state when the overlay is closed const { state: showMore, toggle: toggleShowMore } = useToggle(false); const loading = loadingLabels || loadingFolders || loadingAddresses; useEffect(() => { if (!isOpen) { closeDropdown(); } }, [isOpen]); useEffect(() => { if (dropdownOpened) { open(); } }, [dropdownOpened]); useEffect(() => { setSearchInputValue(searchParams?.keyword || ''); }, [location]); useClickMailContent(() => { close(); }); const handleOpen = () => { if (isOpen) { return; } if (!loading) { anchorRef.current?.blur(); void cacheIndexedDB(); open(); } }; // Listen to close events from composer or iframes useEffect(() => { document.addEventListener('dropdownclose', close); document.addEventListener(ADVANCED_SEARCH_OVERLAY_CLOSE_EVENT, close); return () => { document.removeEventListener('dropdownclose', close); document.removeEventListener(ADVANCED_SEARCH_OVERLAY_CLOSE_EVENT, close); }; }, [close]); return ( <> <MailSearchSpotlight canShow={showEncryptedSearch && !isOpen}> {breakpoints.isNarrow || breakpoints.isTablet ? ( <div className="topnav-listItem flex flex-item-noshrink pl-1"> <TopNavbarListItemSearchButton onClick={handleOpen} /> </div> ) : ( <MailSearchInput loading={loading} ref={anchorRef} value={searchInputValue} onChange={setSearchInputValue} onOpen={handleOpen} adaptWidth={columnMode} /> )} </MailSearchSpotlight> <SearchOverlay id={uid} isOpen={isOpen} anchorRef={anchorRef} onClose={close}> <AdvancedSearch isNarrow={breakpoints.isNarrow || breakpoints.isTablet} showEncryptedSearch={showEncryptedSearch} onClose={close} esIndexingProgressState={esIndexingProgressState} showMore={showMore} toggleShowMore={toggleShowMore} searchInputValue={searchInputValue} labelID={labelID} /> </SearchOverlay> </> ); }; export default MailSearch;
3,489
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/search/MailSearchInput.tsx
import { Ref, forwardRef, useRef } from 'react'; import { c } from 'ttag'; import { Button, Input } from '@proton/atoms'; import { Icon } from '@proton/components'; import clsx from '@proton/utils/clsx'; interface Props { onOpen: () => void; value: string; onChange: (newValue: string) => void; loading: boolean; adaptWidth: boolean; } const MailSearchInput = ({ value, onOpen, onChange, loading, adaptWidth }: Props, ref: Ref<HTMLInputElement>) => { const inputRef = useRef<HTMLInputElement>(null); const handleClear = () => { onChange(''); onOpen(); }; const handleFocus = () => { // Blur the input to avoid the focus to be triggered after search submission inputRef.current?.blur(); onOpen(); }; return ( <div className={clsx('searchbox flex pl-1', adaptWidth && 'searchbox--adaptWidth')} role="search"> <div ref={ref} className="w-full m-auto"> <Input ref={inputRef} inputClassName="cursor-text" disabled={loading} value={value} placeholder={c('Placeholder').t`Search messages`} onFocus={handleFocus} data-testid="search-keyword" readOnly prefix={ <Button type="submit" icon shape="ghost" color="weak" size="small" className="rounded-sm no-pointer-events" title={c('Action').t`Search`} onClick={onOpen} data-shorcut-target="searchbox-button" > <Icon name="magnifier" alt={c('Action').t`Search`} /> </Button> } suffix={ value.length ? ( <Button type="button" shape="ghost" color="weak" size="small" className="rounded-sm" title={c('Action').t`Clear search`} onClick={handleClear} data-testid="clear-button" > {c('Action').t`Clear`} </Button> ) : null } /> </div> </div> ); }; export default forwardRef(MailSearchInput);
3,490
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/search/MailSearchSpotlight.tsx
import { c } from 'ttag'; import { Href } from '@proton/atoms'; import { Spotlight, useSpotlightShow } from '@proton/components/components'; import { FeatureCode } from '@proton/components/containers'; import { useSpotlightOnFeature, useWelcomeFlags } from '@proton/components/hooks'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; interface Props { children: React.ReactElement; canShow: boolean; } const MailSearchSpotlight = ({ children, canShow }: Props) => { const [welcomeFlags] = useWelcomeFlags(); const { show: showSpotlight, onDisplayed } = useSpotlightOnFeature( FeatureCode.SpotlightEncryptedSearch, !welcomeFlags.isWelcomeFlow && canShow ); const shouldShowSpotlight = useSpotlightShow(showSpotlight); return ( <Spotlight originalPlacement="bottom" show={shouldShowSpotlight} onDisplayed={onDisplayed} content={ <> <div className="text-bold text-lg m-auto">{c('Spotlight') .t`Search just got smarter and faster`}</div> {c('Spotlight').t`Try it today.`} <br /> <Href href={getKnowledgeBaseUrl('/search-message-content')} title="Message Content Search"> {c('Info').t`Learn more`} </Href> </> } > {children} </Spotlight> ); }; export default MailSearchSpotlight;
3,491
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/search/Search.scss
@use 'sass:math'; @import '~@proton/styles/scss/lib'; // #{em(940, 16)} was `medium` but the value differs between default config and mail config. // The default value of 910 was loaded instead of 940. To check. .overlay { --min-width: 0; --max-width: 100vw; --max-height: 100vh; position: fixed; z-index: $layer-modals; transform-origin: top center; color: var(--text-norm); animation: anime-dropdown-in 0.15s easing(ease-out-cubic) both; @keyframes anime-dropdown-in { from { opacity: 0; } to { opacity: 1; } } &.is-dropdown-out { animation-name: anime-dropdown-out; @keyframes anime-dropdown-out { from { opacity: 1; } to { opacity: 0; } } } @include media('<=#{em(940, 16)}') { inset: 0; display: flex; padding-block: 15%; padding-inline: 25%; overflow: hidden; flex-flow: column nowrap; justify-content: center; align-items: center; background-color: var(--backdrop-norm); } @include media('<=#{em(940, 16)}') { padding: 5%; } @include media('>#{em(940, 16)}') { inset-block-start: calc(var(--top) * 1px - 1px); /* stylelint-disable */ inset-inline-start: calc(var(--left) * 1px - 1px); /* stylelint-enable */ margin-inline: -1em -0.5em; margin-block-start: -0.5em; border-radius: calc(var(--border-radius) * 1px); box-shadow: var(--shadow-lifted); border: 1px solid var(--border-norm); background: var(--background-norm); } /* Backdrop button, meant to override 'autoClose' option on mobile */ &-backdrop { @include media('<=#{em(940, 16)}') { position: absolute; inset: 0; z-index: 0; display: block; inline-size: 100%; block-size: 100%; margin: 0; padding: 0; border: none; outline: none; background: none; } @include media('>#{em(940, 16)}') { display: none; } } /* Scrollable insides of the dropdown */ &-content { block-size: calc( var(--height) * 1px ); // The min size can't be greater than the remaining space when the dropdown is positioned min-inline-size: min(var(--min-width, 1.5em), var(--max-width-bounds)); min-block-size: min(var(--min-height, 1em), var(--max-height-bounds)); overflow: auto; border-radius: var(--border-radius-md); background-color: var(--background-norm); background-image: radial-gradient(farthest-side at 50% 0, var(--backdrop-norm), transparent), radial-gradient(farthest-side at 50% 100%, var(--backdrop-norm), transparent); background-position: 50% 0, 0 100%; background-size: calc(100% - #{rem(20)}) rem(3); background-repeat: no-repeat; @include media('<=#{em(940, 16)}') { position: relative; z-index: 1; inline-size: 100%; box-shadow: var(--shadow-lifted); transition: transform 0.1s ease-out; } @include media('>#{em(940, 16)}') { inline-size: calc(var(--width) * 1px + 2em); // 2em for paddings max-inline-size: var(--max-width, unset); max-block-size: var(--max-height, unset); } &::before, &::after { content: ''; position: relative; z-index: 1; display: block; block-size: rem(3); flex: 0 0 rem(3); background: var(--background-norm); } } }
3,492
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/search/SearchOverlay.tsx
import { AnimationEvent, CSSProperties, HTMLAttributes, MouseEvent as ReactMouseEvent, ReactNode, RefObject, useLayoutEffect, useRef, } from 'react'; import { c } from 'ttag'; import { HotkeyTuple, getCustomSizingClasses, useDropdownArrowNavigation, useFocusTrap, useHotkeys, useIsClosing, } from '@proton/components'; import { Portal } from '@proton/components/components/portal'; import clsx from '@proton/utils/clsx'; import noop from '@proton/utils/noop'; interface ContentProps extends HTMLAttributes<HTMLDivElement> { ref?: RefObject<HTMLDivElement>; } interface Props extends HTMLAttributes<HTMLDivElement> { anchorRef: RefObject<HTMLElement>; children: ReactNode; className?: string; style?: CSSProperties; onClose?: (event?: ReactMouseEvent<HTMLDivElement> | Event) => void; onClosed?: () => void; onContextMenu?: (event: ReactMouseEvent<HTMLDivElement, MouseEvent>) => void; disableFocusTrap?: boolean; isOpen?: boolean; sameAnchorWidth?: boolean; offset?: number; autoClose?: boolean; contentProps?: ContentProps; disableDefaultArrowNavigation?: boolean; updatePositionOnDOMChange?: boolean; } const SearchOverlay = ({ anchorRef, children, className, style, onClose = noop, onClosed, onContextMenu = noop, isOpen = false, disableFocusTrap = false, sameAnchorWidth = false, contentProps, disableDefaultArrowNavigation = false, ...rest }: Props) => { const boundingRect = anchorRef.current?.getBoundingClientRect(); const rootRef = useRef<HTMLDivElement>(null); const contentRef = useRef<HTMLDivElement>(null); const anchorRectRef = useRef<DOMRect | undefined>(); const focusTrapProps = useFocusTrap({ rootRef, active: isOpen && !disableFocusTrap, enableInitialFocus: false }); const { shortcutHandlers: arrowNavigationShortcutHandlers } = useDropdownArrowNavigation({ rootRef, }); const defaultShortcutHandlers: HotkeyTuple = [ 'Escape', (e) => { e.stopPropagation(); onClose?.(); }, ]; const hotkeyTuples = disableDefaultArrowNavigation ? [defaultShortcutHandlers] : [...arrowNavigationShortcutHandlers, defaultShortcutHandlers]; useHotkeys(rootRef, hotkeyTuples, { dependencies: [isOpen, !disableDefaultArrowNavigation], }); useLayoutEffect(() => { if (!isOpen) { return; } if (sameAnchorWidth) { anchorRectRef.current = anchorRef.current?.getBoundingClientRect(); } }, [isOpen]); const [isClosing, isClosed, setIsClosed] = useIsClosing(isOpen); const popperClassName = clsx(['overlay', isClosing && `is-dropdown-out`, className, 'no-outline']); if (isClosed && !isOpen) { return null; } const varPosition = { '--top': boundingRect?.top, '--left': boundingRect?.left, }; const varSize = { '--width': boundingRect?.width, }; const handleAnimationEnd = ({ animationName }: AnimationEvent) => { if (animationName.includes('anime-dropdown-out') && isClosing) { setIsClosed(); onClosed?.(); } }; const rootStyle = { ...style, ...varPosition, ...varSize, }; const contentStyle = { '--h-custom': 'auto' }; return ( <Portal> <div ref={rootRef} style={rootStyle} role="dialog" className={popperClassName} onAnimationEnd={handleAnimationEnd} onContextMenu={onContextMenu} data-testid="overlay-button" {...rest} {...focusTrapProps} > {/* Backdrop button, meant to override 'autoClose' option on mobile */} <div role="button" tabIndex={0} data-ignore-close="true" className="overlay-backdrop" title={c('Action').t`Close`} onClick={() => onClose()} > <span className="sr-only">{c('Action').t`Close`}</span> </div> <div ref={contentRef} style={contentStyle} {...contentProps} className={clsx(['overlay-content', getCustomSizingClasses(contentStyle), contentProps?.className])} > {children} </div> </div> </Portal> ); }; export default SearchOverlay;
3,493
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/search
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/search/AdvancedSearchFields/EnableEncryptedSearchModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { Href } from '@proton/atoms/Href'; import { ModalProps, Prompt } from '@proton/components/components'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { useEncryptedSearchContext } from '../../../../containers/EncryptedSearchProvider'; interface Props extends ModalProps { openSearchAfterEnabling?: boolean; } const EnableEncryptedSearchModal = ({ openSearchAfterEnabling, ...rest }: Props) => { const { enableEncryptedSearch, enableContentSearch, openDropdown } = useEncryptedSearchContext(); const handleEnableES = async () => { if (openSearchAfterEnabling) { openDropdown(); } void enableEncryptedSearch().then((success) => (success ? enableContentSearch() : undefined)); rest.onClose?.(); }; return ( <Prompt title={c('Title').t`Enable message content search`} buttons={[ <Button color="norm" onClick={handleEnableES} data-testid="encrypted-search:enable">{c('Action') .t`Enable`}</Button>, <Button onClick={rest.onClose}>{c('Action').t`Cancel`}</Button>, ]} {...rest} > {c('Action') .t`To search your emails securely, we need to download a copy of your messages to your browser. The initial download may take a moment.`} <br /> <Href href={getKnowledgeBaseUrl('/search-message-content')}>{c('Info').t`Learn more`}</Href> </Prompt> ); }; export default EnableEncryptedSearchModal;
3,494
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/search
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/search/AdvancedSearchFields/EncryptedSearchField.tsx
import { ReactNode } from 'react'; import { add } from 'date-fns'; import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms'; import { Info, Label, Progress, Toggle, Tooltip, useModalState } from '@proton/components'; import { ESIndexingState } from '@proton/encrypted-search'; import clsx from '@proton/utils/clsx'; import { useEncryptedSearchContext } from '../../../../containers/EncryptedSearchProvider'; import { formatSimpleDate } from '../../../../helpers/date'; import EnableEncryptedSearchModal from '../AdvancedSearchFields/EnableEncryptedSearchModal'; interface Props { esIndexingProgressState: ESIndexingState; } const EncryptedSearchField = ({ esIndexingProgressState }: Props) => { const { enableContentSearch, esStatus, progressRecorderRef, pauseContentIndexing, toggleEncryptedSearch } = useEncryptedSearchContext(); const { isEnablingContentSearch, esEnabled, isDBLimited, isRefreshing, isEnablingEncryptedSearch, isContentIndexingPaused, contentIndexingDone, lastContentTime, } = esStatus; const { esProgress, totalIndexingItems, estimatedMinutes, currentProgressValue } = esIndexingProgressState; const [enableESModalProps, setEnableESModalOpen, renderEnableESModal] = useModalState(); // Switches const showProgress = isEnablingContentSearch || isContentIndexingPaused || (contentIndexingDone && isRefreshing); const showSubTitleSection = contentIndexingDone && !isRefreshing && isDBLimited && !isEnablingEncryptedSearch; let isEstimating = estimatedMinutes === 0 && (totalIndexingItems === 0 || esProgress !== totalIndexingItems); const showToggle = isEnablingContentSearch || isContentIndexingPaused || contentIndexingDone; // ES progress const progressFromBuildEvent = isRefreshing ? 0 : Math.ceil((progressRecorderRef.current[0] / progressRecorderRef.current[1]) * 100); const progressValue = isEstimating ? progressFromBuildEvent : currentProgressValue; // Header const esTitle = <span className="mr-2">{c('Action').t`Search message content`}</span>; // Remove one day from limit because the last day in IndexedDB might not be complete const oldestDate = formatSimpleDate(add(new Date(lastContentTime), { days: 1 })); const subTitleSection = ( // translator: the variable is a date, which is already localised <span className="color-weak mr-2">{c('Info').jt`For messages newer than ${oldestDate}`}</span> ); let esToggleTooltip = c('Info').t`Activation in progress`; if (contentIndexingDone && !isEnablingContentSearch) { esToggleTooltip = esEnabled ? c('Info') .t`Turn off to only search by date, name, email address, or subject line. To disable search message content and delete downloaded messages, go to settings.` : c('Info').t`Turn on to search the content of your messages`; } const esActivationTooltip = c('Info').t`The local database is being prepared`; const esActivationLoading = isEnablingEncryptedSearch; const esActivationButton = ( <Button onClick={() => setEnableESModalOpen(true)} loading={esActivationLoading} data-testid="encrypted-search:activate" > {esActivationLoading ? c('Action').t`Downloading` : c('Action').t`Enable`} </Button> ); const esCTA = showToggle ? ( <Tooltip title={esToggleTooltip}> <span> <Toggle id="es-toggle" className="ml-auto flex-item-noshrink" checked={contentIndexingDone && esEnabled && !isEnablingContentSearch} onChange={toggleEncryptedSearch} disabled={showProgress} /> </span> </Tooltip> ) : esActivationLoading ? ( <Tooltip title={esActivationTooltip}> <span>{esActivationButton}</span> </Tooltip> ) : ( esActivationButton ); const info = ( <Info questionMark title={c('Info').t`Search option that lets you securely search for keywords in the body of email messages.`} /> ); const esHeader = showToggle ? ( <Label htmlFor="es-toggle" className="text-bold p-0 pr-4 flex flex-item-fluid flex-align-items-center w-full"> {esTitle} {info} </Label> ) : ( <div className="text-bold p-0 pr-4 flex flex-item-fluid flex-align-items-center"> {esTitle} {info} </div> ); // Progress indicator const totalProgress = progressRecorderRef.current[1]; const currentProgress = Math.min(esProgress, totalProgress); isEstimating ||= currentProgress === 0; let progressStatus: ReactNode = ''; if (isContentIndexingPaused) { progressStatus = c('Info').t`Downloading paused`; } else if (isEstimating) { progressStatus = c('Info').t`Estimating time remaining...`; } else if (isRefreshing) { progressStatus = c('Info').t`Updating message content search...`; } else { // translator: currentProgress is a number representing the current message being fetched, totalProgress is the total number of message in the mailbox progressStatus = ( <> <span>{c('Info').t`Message download status:`}</span> <span className="ml-2"> {c('Info').ngettext( msgid`${currentProgress} out of ${totalProgress}`, `${currentProgress} out of ${totalProgress}`, totalProgress )} </span> </> ); } const etaMessage = estimatedMinutes <= 1 ? c('Info').t`Estimated time remaining: Less than a minute` : // translator: the variable is a positive integer (written in digits) always strictly bigger than 1 c('Info').ngettext( msgid`Estimated time remaining: ${estimatedMinutes} minute`, `Estimated time remaining: ${estimatedMinutes} minutes`, estimatedMinutes ); const progressBar = ( <Progress value={progressValue || 0} aria-describedby="timeRemaining" className={clsx(['my-4 flex-item-fluid', isContentIndexingPaused ? 'progress-bar--disabled' : undefined])} /> ); const disablePauseResumeButton = contentIndexingDone && !isEnablingContentSearch; const showPauseResumeButton = showProgress && (!contentIndexingDone || isEnablingContentSearch) && !isRefreshing; const pauseResumeButton = isContentIndexingPaused ? ( <Button shape="solid" color="norm" className="ml-4" onClick={() => enableContentSearch()} disabled={disablePauseResumeButton} > {c('Action').t`Resume`} </Button> ) : ( <Button className="ml-4" onClick={pauseContentIndexing} disabled={disablePauseResumeButton}> {c('Action').t`Pause`} </Button> ); return ( <div className="pt-0"> <div className="flex flex-column"> <div className="flex flex-nowrap flex-align-items-center mb-4"> {esHeader} {esCTA} </div> </div> {showSubTitleSection && <div className="mb-4">{subTitleSection}</div>} {showProgress && ( <div className="mt-2 mb-4 flex flex-column"> <span className="color-weak relative advanced-search-progress-status" aria-live="polite" aria-atomic="true" > {progressStatus} </span> <div className="flex flex-justify-space-between"> {progressBar} {showPauseResumeButton && pauseResumeButton} </div> <span id="timeRemaining" aria-live="polite" aria-atomic="true" className={clsx([ 'color-weak relative advanced-search-time-remaining', isEstimating || isContentIndexingPaused ? 'visibility-hidden' : undefined, ])} > {etaMessage} </span> </div> )} {renderEnableESModal && <EnableEncryptedSearchModal {...enableESModalProps} />} </div> ); }; export default EncryptedSearchField;
3,495
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/search
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/search/AdvancedSearchFields/LocationField.test.tsx
import { render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { ALMOST_ALL_MAIL } from '@proton/shared/lib/mail/mailSettings'; import { mockUseFolders, mockUseMailSettings } from '@proton/testing/index'; import LocationField from './LocationField'; import { mockUseLocationFieldOptions } from './LocationField.test.utils'; describe('LocationField', () => { beforeEach(() => { mockUseMailSettings(); mockUseLocationFieldOptions(); mockUseFolders(); }); it('should correctly render main locations buttons', () => { render(<LocationField value={MAILBOX_LABEL_IDS.ALL_MAIL} onChange={jest.fn()} />); expect(screen.getByText('Search in')); const allMailButton = screen.getByRole('button', { name: 'Search in All mail' }); expect(allMailButton).toBeInTheDocument(); expect(allMailButton).toHaveClass('button-solid-norm'); expect(screen.getByRole('button', { name: 'Search in Inbox' })); expect(screen.getByRole('button', { name: 'Search in Drafts' })); expect(screen.getByRole('button', { name: 'Search in Sent' })); expect(screen.getByRole('button', { name: 'Other' })); }); describe('when user click on another location', () => { it('should correctly change location', async () => { const onChange = jest.fn(); render(<LocationField value={MAILBOX_LABEL_IDS.INBOX} onChange={onChange} />); const draftsButton = screen.getByRole('button', { name: 'Search in Drafts' }); await userEvent.click(draftsButton); await waitFor(() => { expect(onChange).toHaveBeenCalledTimes(1); }); expect(onChange).toHaveBeenCalledWith(MAILBOX_LABEL_IDS.DRAFTS); }); }); describe('when user click on Other button', () => { it('should correctly change location', async () => { const onChange = jest.fn(); render(<LocationField value={MAILBOX_LABEL_IDS.INBOX} onChange={onChange} />); const otherButton = screen.getByRole('button', { name: 'Other' }); await userEvent.click(otherButton); await waitFor(() => { expect(screen.getByText('Labels')).toBeInTheDocument(); }); const customLabelButton = screen.getByRole('button', { name: 'Highlighted' }); await userEvent.click(customLabelButton); await waitFor(() => { expect(onChange).toHaveBeenCalledTimes(1); }); expect(onChange).toHaveBeenCalledWith('36'); }); }); describe('when custom option is set', () => { it('should correctly change location', async () => { const onChange = jest.fn(); render(<LocationField value={'36'} onChange={onChange} />); expect(screen.getByText('Highlighted')).toBeInTheDocument(); const customLabelButton = screen.getByRole('button', { name: 'Remove' }); expect(customLabelButton).toBeInTheDocument(); expect(customLabelButton).toHaveClass('button-solid-norm'); await userEvent.click(customLabelButton); await waitFor(() => { expect(onChange).toHaveBeenCalledTimes(1); }); expect(onChange).toHaveBeenCalledWith(MAILBOX_LABEL_IDS.ALL_MAIL); }); describe('when Almost All Mail is set', () => { it('should correctly change location', async () => { mockUseMailSettings([{ AlmostAllMail: ALMOST_ALL_MAIL.ENABLED }]); const onChange = jest.fn(); render(<LocationField value={'36'} onChange={onChange} />); expect(screen.getByText('Highlighted')).toBeInTheDocument(); const customLabelButton = screen.getByRole('button', { name: 'Remove' }); expect(customLabelButton).toBeInTheDocument(); expect(customLabelButton).toHaveClass('button-solid-norm'); await userEvent.click(customLabelButton); await waitFor(() => { expect(onChange).toHaveBeenCalledTimes(1); }); expect(onChange).toHaveBeenCalledWith(MAILBOX_LABEL_IDS.ALMOST_ALL_MAIL); }); }); }); });
3,496
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/search
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/search/AdvancedSearchFields/LocationField.test.utils.tsx
import * as useLocationFieldOptionsModule from './useLocationFieldOptions'; const defaultFolders: useLocationFieldOptionsModule.ItemDefaultFolder[] = [ { value: '5', text: 'All mail', url: '/all-mail', icon: 'envelopes', }, { value: '0', text: 'Inbox', url: '/inbox', icon: 'inbox', }, { value: '8', text: 'Drafts', url: '/drafts', icon: 'file-lines', }, { value: '12', text: 'Scheduled', url: '/scheduled', icon: 'clock', }, { value: '7', text: 'Sent', url: '/sent', icon: 'paper-plane-horizontal', }, ]; const folders: useLocationFieldOptionsModule.ItemCustomFolder[] = [ { text: 'news', value: '31dixxUc6tNkpKrI-abC_IQcnG4_K2brHumXkQb_Ib4-FEl5Q3n27dbhIkfBTnYrNonJ8DsySBbUM0RtQdhYhA==', className: '', folderEntity: { ID: '31dixxUc6tNkpKrI-abC_IQcnG4_K2brHumXkQb_Ib4-FEl5Q3n27dbhIkfBTnYrNonJ8DsySBbUM0RtQdhYhA==', Name: 'news', Path: 'news', Type: 3, Color: '#54473f', Order: 1, Notify: 1, Expanded: 0, subfolders: [], }, }, ]; const labels: useLocationFieldOptionsModule.ItemLabel[] = [ { color: 'white', text: 'Highlighted', value: '36', url: '/highlighted' }, ]; const all: useLocationFieldOptionsModule.Item[] = [...defaultFolders, ...folders, ...labels]; const grouped: useLocationFieldOptionsModule.ItemsGroup = [ { id: 'DEFAULT_FOLDERS', title: 'Default folders', items: defaultFolders, }, { id: 'CUSTOM_FOLDERS', title: 'Custom folders', items: folders, }, { id: 'LABELS', title: 'Labels', items: labels, }, ]; export const mockUseLocationFieldOptions = ( value?: Partial<ReturnType<typeof useLocationFieldOptionsModule.useLocationFieldOptions>> ) => { const mockedUseLocationFieldOptions = jest.spyOn(useLocationFieldOptionsModule, 'useLocationFieldOptions'); mockedUseLocationFieldOptions.mockReturnValue({ all, grouped, findItemByValue: (value: string) => all.find((item) => item.value === value), isDefaultFolder: ( item: useLocationFieldOptionsModule.Item ): item is useLocationFieldOptionsModule.ItemDefaultFolder => 'url' in item && 'icon' in item, isCustomFolder: ( item: useLocationFieldOptionsModule.Item ): item is useLocationFieldOptionsModule.ItemCustomFolder => 'folderEntity' in item, isLabel: (item: useLocationFieldOptionsModule.Item): item is useLocationFieldOptionsModule.ItemLabel => 'color' in item, ...value, }); return mockedUseLocationFieldOptions; };
3,497
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/search
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/search/AdvancedSearchFields/LocationField.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Icon } from '@proton/components'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import useMailModel from 'proton-mail/hooks/useMailModel'; import LocationFieldDropdown from './LocationFieldDropdown'; import { useLocationFieldOptions } from './useLocationFieldOptions'; interface Props { value: string; onChange: (nextValue: string) => void; } const { INBOX, ALL_MAIL, ALMOST_ALL_MAIL, SENT, DRAFTS, ALL_SENT, ALL_DRAFTS } = MAILBOX_LABEL_IDS; const LOCATION_FIELD_MAIN_OPTIONS: string[] = [ALL_MAIL, ALMOST_ALL_MAIL, INBOX, DRAFTS, SENT, ALL_SENT, ALL_DRAFTS]; const LocationField = ({ value, onChange }: Props) => { const { AlmostAllMail } = useMailModel('MailSettings'); const { all: options, findItemByValue } = useLocationFieldOptions(); const mainOptions = options.filter(({ value }) => LOCATION_FIELD_MAIN_OPTIONS.includes(value)); const isCustomValue = value !== undefined && LOCATION_FIELD_MAIN_OPTIONS.every((optionValue) => optionValue !== value); const customValueText = isCustomValue ? findItemByValue(value)?.text : undefined; const showCustomValue = isCustomValue === true && customValueText !== undefined; return ( <> <span className="block text-semibold mb-2">{c('Label').t`Search in`}</span> <div className="flex flex-wrap flex-align-items-start mb-2 gap-2"> {mainOptions.map((option) => ( <Button key={option.value} data-testid={`location-${option.value}`} onClick={() => { onChange(option.value); }} color={value === option.value ? 'norm' : 'weak'} shape="solid" size="small" title={ // translator: The full sentence is "Search in All mail/Inbox/Drafts/etc." (only for blind users) c('Action').t`Search in ${option.text}` } > {option.text} </Button> ))} <LocationFieldDropdown onChange={onChange} value={value} /> {showCustomValue ? ( <Button className="flex flex-nowrap flex-align-items-center" onClick={() => onChange(AlmostAllMail ? ALMOST_ALL_MAIL : ALL_MAIL)} color="norm" shape="solid" size="small" title={c('Action').t`Remove`} > <span className="text-ellipsis">{customValueText}</span> <Icon name="cross-small" className="ml-2 flex-item-noshrink" /> </Button> ) : null} </div> </> ); }; export default LocationField;
3,498
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/search
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/header/search/AdvancedSearchFields/LocationFieldDropdown.tsx
import { useEffect, useRef, useState } from 'react'; import { c } from 'ttag'; import { Dropdown, DropdownButton, DropdownMenu, DropdownMenuButton, FolderIcon, Icon, Mark, SearchInput, generateUID, usePopperAnchor, } from '@proton/components'; import clsx from '@proton/utils/clsx'; import { ItemsGroup, useLocationFieldOptions } from './useLocationFieldOptions'; interface Props { value: string; onChange: (selectedOptionValue: string) => void; } const LocationFieldDropdown = ({ value, onChange }: Props) => { const { grouped: optionGroups, isLabel, isCustomFolder, isDefaultFolder } = useLocationFieldOptions(); const [search, setSearch] = useState(''); const [options, setOptions] = useState(optionGroups); const { current: uid } = useRef(generateUID('advanced-search-location-dropdown')); const { current: searchInputID } = useRef(generateUID('dropdown')); const { anchorRef, isOpen, toggle, close } = usePopperAnchor<HTMLButtonElement>(); useEffect(() => { const lowerCaseSearch = search.toLowerCase(); const nextOptions = optionGroups.map((optionGroup) => { return { ...optionGroup, items: optionGroup.items.filter((item) => item.text.toLowerCase().includes(lowerCaseSearch)), }; }); setOptions(nextOptions as ItemsGroup); }, [search]); return ( <> <DropdownButton color="weak" hasCaret onClick={toggle} size="small" shape="solid" ref={anchorRef}> {c('Property type').t`Other`} </DropdownButton> <Dropdown anchorRef={anchorRef} autoClose onClosed={() => setSearch('')} id={uid} isOpen={isOpen} onClose={close} originalPlacement="bottom-start" contentProps={{ className: 'flex flex-column flex-nowrap', }} > <div className="p-4 flex-item-noshrink"> <SearchInput value={search} onChange={setSearch} onClick={(e) => { // Prevent dropdown closing e.stopPropagation(); }} id={searchInputID} placeholder={c('Placeholder').t`Filter folders`} autoFocus data-prevent-arrow-navigation /> </div> <div className="scroll-if-needed"> <DropdownMenu> {options.map((group) => group.items.length ? ( <div key={group.id}> <span className="button text-bold pl-4">{group.title}</span> {group.items.map((item) => ( <DropdownMenuButton className="text-left text-ellipsis" isSelected={item.value === value} key={item.value} onClick={() => onChange(item.value)} > <div className={clsx([ 'flex flex-nowrap flex-align-items-center', isCustomFolder(item) && item.className, ])} > {isLabel(item) && ( <Icon name="circle-filled" color={item.color} className="flex-item-noshrink mr-2" /> )} {isDefaultFolder(item) && ( <Icon name={item.icon} className="flex-item-noshrink mr-2" /> )} {isCustomFolder(item) && ( <FolderIcon folder={item.folderEntity} className="flex-item-noshrink mr-2" /> )} <span className="text-ellipsis"> <Mark value={search}>{item.text}</Mark> </span> </div> </DropdownMenuButton> ))} </div> ) : null )} </DropdownMenu> </div> </Dropdown> </> ); }; export default LocationFieldDropdown;
3,499