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/packages/activation
|
petrpan-code/ProtonMail/WebClients/packages/activation/__mocks__/styleMock.js
|
// __mocks__/styleMock.js
module.exports = {};
| 4,800
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation
|
petrpan-code/ProtonMail/WebClients/packages/activation/__mocks__/tabbable.js
|
const lib = jest.requireActual('tabbable');
const tabbable = {
...lib,
tabbable: (node, options) => lib.tabbable(node, { ...options, displayCheck: 'none' }),
focusable: (node, options) => lib.focusable(node, { ...options, displayCheck: 'none' }),
isFocusable: (node, options) => lib.isFocusable(node, { ...options, displayCheck: 'none' }),
isTabbable: (node, options) => lib.isTabbable(node, { ...options, displayCheck: 'none' }),
};
module.exports = tabbable;
| 4,801
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/constants.ts
|
import { c } from 'ttag';
import { CreateNotificationOptions } from '@proton/components';
import { EMAIL_PLACEHOLDER, USERNAME_PLACEHOLDER } from '@proton/shared/lib/constants';
import {
EASY_SWITCH_SOURCE,
ImportProvider,
MailImportGmailCategories,
OAUTH_PROVIDER,
TIME_PERIOD,
} from './interface';
export const G_OAUTH_REDIRECT_PATH = '/oauth/callback';
export const G_OAUTH_SCOPE_DEFAULT = ['email', 'openid'];
export const G_OAUTH_SCOPE_MAIL_READONLY = ['https://www.googleapis.com/auth/gmail.readonly'];
export const G_OAUTH_SCOPE_CONTACTS = ['https://www.googleapis.com/auth/contacts.readonly'];
export const G_OAUTH_SCOPE_CALENDAR = ['https://www.googleapis.com/auth/calendar.readonly'];
// export const G_OAUTH_SCOPE_DRIVE = [];
export const O_OAUTH_REDIRECT_PATH = '/oauth/callback';
export const O_OAUTH_SCOPE_DEFAULT = ['email', 'openid', 'User.Read', 'offline_access'];
export const O_OAUTH_SCOPE_MAIL = ['Mail.read'];
export const O_OAUTH_SCOPE_CONTACTS = ['Contacts.read'];
export const O_OAUTH_SCOPE_CALENDAR = ['Calendars.read'];
export const IA_PATHNAME_REGEX = /\/easy-switch/;
/* Mail specific */
export const GMAIL_CATEGORIES = Object.values(MailImportGmailCategories);
export const getTimeUnitLabels = () => ({
[TIME_PERIOD.BIG_BANG]: c('Label').t`Import all messages`,
[TIME_PERIOD.LAST_YEAR]: c('Label').t`Last 12 months only`,
[TIME_PERIOD.LAST_3_MONTHS]: c('Label').t`Last 3 months only`,
[TIME_PERIOD.LAST_MONTH]: c('Label').t`Last month only`,
});
export const MAX_FOLDERS_DEPTH = 3;
export const MAX_FOLDER_LIMIT = 20000;
export const IMAPS = {
[OAUTH_PROVIDER.GOOGLE]: 'imap.gmail.com',
[ImportProvider.YAHOO]: 'export.imap.mail.yahoo.com',
[ImportProvider.OUTLOOK]: 'outlook.office365.com',
[OAUTH_PROVIDER.OUTLOOK]: 'outlook.office365.com',
};
export const PORTS = {
[OAUTH_PROVIDER.GOOGLE]: '993',
[ImportProvider.YAHOO]: '993',
[ImportProvider.OUTLOOK]: '993',
[OAUTH_PROVIDER.OUTLOOK]: '993',
};
export const EASY_SWITCH_EMAIL_PLACEHOLDER = {
[ImportProvider.YAHOO]: `${USERNAME_PLACEHOLDER}@yahoo.com`,
[ImportProvider.OUTLOOK]: `${USERNAME_PLACEHOLDER}@outlook.com`,
[ImportProvider.GOOGLE]: `${USERNAME_PLACEHOLDER}@google.com`,
[ImportProvider.DEFAULT]: EMAIL_PLACEHOLDER,
};
/* Calendar specific */
export const CALENDAR_TO_BE_CREATED_PREFIX = '###TO_BE_CREATED###';
/* Sync specific */
export const SYNC_SOURCE = EASY_SWITCH_SOURCE.EASY_SWITCH_SETTINGS;
export const SYNC_G_OAUTH_SCOPES = [...G_OAUTH_SCOPE_DEFAULT, G_OAUTH_SCOPE_MAIL_READONLY];
export const SYNC_SUCCESS_NOTIFICATION: CreateNotificationOptions = {
type: 'success',
text: c('account').t`Forwarding will start soon. New emails will appear in your inbox.`,
};
| 4,802
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/interface.ts
|
import { Label } from '@proton/shared/lib/interfaces/Label';
import { ApiImporterError, ApiImporterState, ApiReportRollbackState } from './api/api.interface';
export enum ImportProvider {
GOOGLE = 'google',
YAHOO = 'yahoo',
OUTLOOK = 'outlook',
DEFAULT = 'default',
}
export enum OAUTH_PROVIDER {
GOOGLE = 1,
OUTLOOK = 2,
}
export interface OAuthProps {
Code: string;
Provider: OAUTH_PROVIDER;
RedirectUri: string;
}
export enum ImportType {
MAIL = 'Mail',
CALENDAR = 'Calendar',
CONTACTS = 'Contacts',
// DRIVE = 'Drive',
}
export interface CreateImportPayload {
TokenID?: string;
Source?: string;
[ImportType.MAIL]?: {
Account: string;
ImapHost?: string;
ImapPort?: number;
Sasl: AuthenticationMethod;
Code?: string;
AllowSelfSigned?: number;
RedirectUri?: string; // for reconnection
};
[ImportType.CALENDAR]?: {};
[ImportType.CONTACTS]?: {};
}
export interface LaunchImportPayload {
ImporterID: string;
[ImportType.MAIL]?: MailImporterPayload;
[ImportType.CALENDAR]?: CalendarImporterPayload;
[ImportType.CONTACTS]?: ContactsImporterPayload;
// [ImportType.DRIVE]?: DriveImporterPayload;
}
/* Token */
export interface ImportToken {
ID: string;
Account: string;
Provider: OAUTH_PROVIDER;
Products: ImportType[];
}
/* Mail Specific */
export enum AuthenticationMethod {
PLAIN = 'PLAIN',
OAUTH = 'XOAUTH2',
}
export interface MailImportMapping {
Source: string;
Destinations: {
FolderPath?: string;
Labels?: Pick<Label, 'Name' | 'Color'>[];
Category?: string;
};
checked?: boolean;
}
export interface MailImporterPayload {
AddressID: string;
/** User app password */
Code?: string;
/** Label used on */
ImportLabel?: Pick<Label, 'Name' | 'Color' | 'Type'>;
/** Unix timestamp. Received emails import starts after this date. */
StartTime?: Date | number;
/** Unix timestamp. Received emails import stops after this date. */
EndTime?: number;
Mapping: MailImportMapping[];
/** Bitmap of custom settings */
CustomFields?: number;
}
export enum MailImportDestinationFolder {
INBOX = 'Inbox',
ALL_DRAFTS = 'All Drafts',
ALL_SENT = 'All Sent',
TRASH = 'Trash',
SPAM = 'Spam',
ALL_MAIL = 'All Mail',
ALMOST_ALL_MAIL = 'Almost All Mail',
STARRED = 'Starred',
ARCHIVE = 'Archive',
SENT = 'Sent',
DRAFTS = 'Drafts',
}
export enum TIME_PERIOD {
BIG_BANG = 'big_bang',
LAST_YEAR = 'last_year',
LAST_3_MONTHS = 'last_3_months',
LAST_MONTH = 'last_month',
}
export enum IMPORT_ERROR {
UNEXPECTED_ERROR = 2000,
IMAP_CONNECTION_ERROR = 2900,
AUTHENTICATION_ERROR = 2901,
ALREADY_EXISTS = 2500,
OAUTH_INSUFFICIENT_SCOPES = 2027,
BANDWIDTH_LIMIT = 2902,
TEMP_PROVIDER_ERROR = 2902,
RATE_LIMIT_EXCEEDED = 429,
ACCOUNT_DOES_NOT_EXIST = 2011,
TOO_LARGE = 2024,
}
//TODO complete this once backend is more stable
export enum SYNC_ERROR {
MISSING_PRODUCT = 2000,
WRONG_PRODUCT = 2001,
AUTH_ERROR = 2501,
}
interface ImportedFolder {
SourceFolder: string;
DestinationFolder?: MailImportDestinationFolder;
Processed: number;
Total: number;
}
export enum MailImportGmailCategories {
FORUMS = 'Forums',
PROMOTIONS = 'Promotions',
SOCIAL = 'Social',
UPDATES = 'Updates',
}
export enum MailImportPayloadError {
MAX_FOLDERS_LIMIT_REACHED = 'Max folders limit reached',
FOLDER_NAMES_TOO_LONG = 'Folder names too long', //OK
LABEL_NAMES_TOO_LONG = 'Label names too long', //ok
UNAVAILABLE_NAMES = 'Unavailable names', //ok
RESERVED_NAMES = 'Reserved names', //ok
EMPTY = 'EMPTY', //ok
MERGE_WARNING = 'MERGE_WARNING',
}
export enum CustomFieldsBitmap {
Mapping = 1,
Label = 2,
Period = 4,
}
/* Calendar Specific */
export interface CalendarImportMapping {
Source: string;
Destination: string;
Description: string;
}
export enum IsCustomCalendarMapping {
TRUE = 1,
FALSE = 0,
}
export interface CalendarImporterPayload {
Mapping: CalendarImportMapping[];
CustomCalendarMapping: IsCustomCalendarMapping;
}
export interface ImportedCalendar {
ID: string;
Source: string;
Description: string;
}
/* Contacts Specific */
export interface ContactsImporterPayload {}
/* Drive Specific */
export interface DriveImporterPayload {}
/* Imports and Reports from Server */
interface ImporterActiveProps {
CreateTime: number;
State: ApiImporterState;
ErrorCode?: ApiImporterError;
Mapping: ImportedFolder[];
Processed?: number;
Total?: number;
}
export interface Importer {
ID: string;
TokenID: string;
Account: string;
Provider: number;
Product: ImportType[];
Active?: {
[ImportType.MAIL]?: ImporterActiveProps;
[ImportType.CALENDAR]?: ImporterActiveProps;
[ImportType.CONTACTS]?: ImporterActiveProps;
};
ImapHost: string;
ImapPort: string;
Sasl: AuthenticationMethod;
AllowSelfSigned: boolean;
Email: string; // Soon to be deprecated
}
enum ImportReportStatus {
UNSENT = 0,
SENT = 1,
}
interface ImportSummary {
State: ApiImporterState;
TotalSize: number;
RollbackState?: ApiReportRollbackState;
}
export interface ImportReportAggregated {
ID: string;
Account: string;
Provider: number;
State: ImportReportStatus;
TokenID: string;
CreateTime: number;
EndTime: number;
Summary: {
Mail?: ImportSummary & {
NumMessages: number;
};
Calendar?: ImportSummary & {
NumEvents: number;
};
Contacts?: ImportSummary & {
NumContacts: number;
};
};
}
export interface ImportReport {
ID: string;
Account: string;
Provider: number;
TokenID: string;
CreateTime: number;
EndTime: number;
NumItems: number;
State: ApiImporterState;
TotalSize: number;
Product: ImportType;
RollbackState?: ApiReportRollbackState;
}
export enum EASY_SWITCH_SOURCE {
EASY_SWITCH_SETTINGS = 'easy-switch-settings',
CONTACTS_WIDGET_SETTINGS = 'contacts-widget-settings',
IMPORT_CALENDAR_SETTINGS = 'import-calendar-settings',
RECONNECT_IMPORT = 'reconnect-import',
}
export interface EasySwitchFeatureFlag {
GoogleMail: boolean;
GoogleMailSync: boolean;
GoogleCalendar: boolean;
GoogleContacts: boolean;
GoogleDrive: boolean;
OutlookMail: boolean;
OutlookCalendar: boolean;
OutlookContacts: boolean;
OtherMail: boolean;
OtherCalendar: boolean;
OtherContacts: boolean;
OtherDrive: boolean;
}
| 4,803
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/api/api.interface.ts
|
import {
AuthenticationMethod,
CalendarImporterPayload,
ContactsImporterPayload,
ImportType,
MailImportDestinationFolder,
MailImportGmailCategories,
MailImporterPayload,
} from '@proton/activation/src/interface';
import { EVENT_ACTIONS } from '@proton/shared/lib/constants';
import { ApiResponse } from '@proton/shared/lib/interfaces';
/**
* API EVENTS
*/
interface ApiEventType {
ID: string;
Action: EVENT_ACTIONS;
}
export interface ApiEvent {
More?: 0 | 1;
EventID?: string;
Refresh?: number;
Imports?: ApiImportEvent[];
ImportReports?: ApiImportReportEvent[];
ImporterSyncs?: ApiSyncEvent[];
}
export interface ApiImportReportEvent extends ApiEventType {
ImportReport?: ApiReport;
}
export interface ApiImportEvent extends ApiEventType {
Importer?: ApiImporter;
}
export interface ApiSyncEvent extends ApiEventType {
ImporterSync?: ApiSync;
}
/**
* API CALLS RESPONSES
*/
export interface ApiMailImporterFolder {
Source: string;
/** The hierarchy delimiter in the Source field */
Separator: string;
Size: number;
/**
* TODO
* Flags seem to deliver inconsistent results between
* IMAP and OAuth calls. We will not rely on it ATM
* */
Flags: string[];
Total?: number;
DestinationCategory?: MailImportGmailCategories;
DestinationFolder?: MailImportDestinationFolder;
}
export enum ApiReportRollbackState {
CANNOT_ROLLBACK = 0,
CAN_ROLLBACK = 1,
ROLLING_BACK = 2,
ROLLED_BACK = 3,
}
export enum ApiImporterState {
QUEUED = 0,
RUNNING = 1,
DONE = 2,
FAILED = 3,
PAUSED = 4,
CANCELED = 5,
DELAYED = 6,
}
/**
* Payload changes depending of the import type (Contacts, Mail, Calendar)
* This is just the list of the common fields
* Please look at API docs to find more infos
*/
export interface ApiReportSummary {
State: ApiImporterState;
TotalSize: number;
RollbackState?: ApiReportRollbackState;
NumMessages?: number;
NumContacts?: number;
NumGroups?: number;
NumEvents?: number;
}
export enum ApiImportProvider {
IMAP = 0,
GOOGLE = 1,
OUTLOOK = 2,
}
export enum ApiReportState {
UNSENT = 0,
SENT = 1,
}
export interface ApiReport {
ID: string;
CreateTime: number;
EndTime: number;
Provider: ApiImportProvider;
/** Email */
Account: string;
State: ApiReportState;
Summary: Partial<Record<ImportType, ApiReportSummary>>;
TotalSize: number;
}
export enum ApiImporterError {
ERROR_CODE_IMAP_CONNECTION = 1,
ERROR_CODE_QUOTA_LIMIT = 2,
}
export interface ApiImporterFolder {
SourceFolder: string;
DestinationFolder?: MailImportDestinationFolder;
Processed: number;
Total: number;
Source?: string;
}
export interface ApiImporterActive {
CreateTime: number;
State: ApiImporterState;
ErrorCode?: ApiImporterError;
Mapping?: ApiImporterFolder[];
Processed?: number;
Total?: number;
AttemptTime?: number;
NumContacts?: number;
FilterStartDate?: string;
FilterEndDate?: string;
}
export interface ApiImporter {
ID: string;
/** Only on IMAP flow */
TokenID?: string;
Account: string;
Provider: ApiImportProvider;
Product: ImportType[];
Active?: Partial<Record<ImportType, ApiImporterActive>>;
ModifyTime: number;
/** Only on IMAP flow */
ImapHost?: string;
/** Only on IMAP flow */
ImapPort?: string;
/** Only on IMAP flow */
Sasl?: AuthenticationMethod;
/** Only on IMAP flow */
AllowSelfSigned?: boolean;
/** @deprecated replaced by account */
Email: string;
}
/**
* GET importer/v1/reports
*/
export interface ApiImportReportListResponse extends ApiResponse {
Reports: ApiReport[];
}
/**
* GET importer/v1/importers
*/
export interface ApiImportListResponse extends ApiResponse {
Importers: ApiImporter[];
}
/**
* GET importer/v1/importers/{enc_importerID}
*/
export interface ApiImportResponse extends ApiResponse {
Importer: ApiImporter;
}
/**
* POST importer/v1/mail/importers/authinfo
*/
export interface ApiImporterAuthInfoResponse extends ApiResponse {
Authentication: {
Sasl: string;
OAuthUrl: string;
OAuthParams: string[];
ImapHost: string;
ImapPort: number;
ImporterID: string;
};
}
/**
* POST importer/v1/importers
*/
export interface ApiCreateImporterResponse extends ApiResponse {
ImporterID: string;
}
/**
* GET importer/v1/mail/importers/${importerID}
*/
export interface ApiImporterImportResponse extends ApiResponse {
Folders: ApiMailImporterFolder[];
}
/**
* POST importer/v1/importers/start
*/
export interface ApiStartImportParams {
ImporterID: string;
[ImportType.MAIL]?: MailImporterPayload;
[ImportType.CALENDAR]?: CalendarImporterPayload;
[ImportType.CONTACTS]?: ContactsImporterPayload;
}
export interface ApiStartImportResponse extends ApiResponse {}
/**
* importer/v1/sync
*/
export enum ApiSyncState {
OFFLINE = 0,
ACTIVE = 1,
EXPIRED = 2,
}
export interface ApiSync {
Account: string;
ID: string;
ImporterID: string;
Product: ImportType;
State: ApiSyncState;
CreateTime: number;
LastImportTime: number;
LastRenewTime: number;
}
export interface APIImportSyncListResponse extends ApiResponse {
Syncs: ApiSync[];
}
| 4,804
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/api/api.ts
|
import { CreateImportPayload, ImportType, LaunchImportPayload, OAuthProps } from '../interface';
export const createToken = (
data: OAuthProps & {
Products: ImportType[];
Source: string;
}
) => ({
url: 'importer/v1/tokens',
method: 'post',
data,
});
export const createSync = (importerID: string) => ({
url: 'importer/v1/sync',
method: 'POST',
data: { ImporterID: importerID, Product: 'Mail' },
});
export const getSyncList = () => ({
url: 'importer/v1/sync',
method: 'get',
});
export const resumeSync = (syncId: string) => ({
url: `importer/v1/sync/${syncId}/resume`,
method: 'put',
});
export const deleteSync = (syncId: String) => ({
url: `importer/v1/sync/${syncId}`,
method: 'DELETE',
});
export const createImport = (data: CreateImportPayload) => ({
url: 'importer/v1/importers',
method: 'post',
data,
});
export const getImport = (importerID: string) => ({
url: `importer/v1/importers/${importerID}`,
method: 'get',
});
export const updateImport = (importerID: string, data: CreateImportPayload) => ({
url: `importer/v1/importers/${importerID}`,
method: 'put',
data,
});
export const startImportTask = (data: LaunchImportPayload) => ({
url: 'importer/v1/importers/start',
method: 'post',
data,
});
export const getImportsList = () => ({
url: 'importer/v1/importers',
method: 'get',
});
export const getImportReportsList = () => ({
url: 'importer/v1/reports',
method: 'get',
});
export const getMailImportData = (
importerID: string,
params?: {
Code: string;
}
) => ({
url: `importer/v1/mail/importers/${importerID}`,
method: 'get',
params,
});
export const getAuthenticationMethod = (params: { Email: string }) => ({
url: 'importer/v1/mail/importers/authinfo',
method: 'get',
params,
});
export const getCalendarImportData = (importerID: string) => ({
url: `importer/v1/calendar/importers/${importerID}`,
method: 'get',
});
export const getContactsImportData = (importerID: string) => ({
url: `importer/v1/contacts/importers/${importerID}`,
method: 'get',
});
export const deleteImportReport = (reportID: string, importType: ImportType) => {
const method = 'delete';
switch (importType) {
case ImportType.MAIL:
return { url: `importer/v1/mail/importers/reports/${reportID}`, method };
case ImportType.CALENDAR:
return { url: `importer/v1/calendar/importers/reports/${reportID}`, method };
case ImportType.CONTACTS:
return { url: `importer/v1/contacts/importers/reports/${reportID}`, method };
}
};
export const cancelImport = (data: { ImporterID: string; Products: ImportType[] }) => ({
url: 'importer/v1/importers/cancel',
method: 'put',
data,
});
export const resumeImport = (data: { ImporterID: string; Products: ImportType[] }) => ({
url: 'importer/v1/importers/resume',
method: 'put',
data,
});
export const rollbackImport = (reportID: string, Products: ImportType[]) => ({
url: `importer/v1/reports/${reportID}/undo`,
method: 'POST',
data: { Products },
});
| 4,805
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/api/index.ts
|
export * from './api';
| 4,806
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/MainModal.scss
|
@import '~@proton/styles/scss/lib';
.modal.easy-switch-modal {
max-inline-size: rem(580);
inline-size: 100%;
}
.import-buttons {
display: grid;
grid-gap: #{rem(20)};
grid-template-columns: repeat(auto-fit, minmax(#{rem(160)}, 1fr));
}
| 4,807
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/MainModal.tsx
|
import { ImportType } from '@proton/activation/src/interface';
import { selectDraftModal } from '@proton/activation/src/logic/draft/draft.selector';
import {
readImapInstructions,
resetImapDraft,
selectImapProduct,
} from '@proton/activation/src/logic/draft/imapDraft/imapDraft.actions';
import { useEasySwitchDispatch, useEasySwitchSelector } from '@proton/activation/src/logic/store';
import ContactImportModal from '@proton/components/containers/contacts/import/ContactImportModal';
import CalendarModal from './Imap/CalendarModal/CalendarModal';
import ImapMailModal from './Imap/ImapMailModal/ImapMailModal';
import ImapProductsModal from './Imap/ImapProductsModal/ImapProductsModal';
import InstructionsModal from './Imap/InstructionsModal/InstructionsModal';
import OAuthModal from './OAuth/OAuthModal';
import './MainModal.scss';
const MainModal = () => {
const dispatch = useEasySwitchDispatch();
const modal = useEasySwitchSelector(selectDraftModal);
if (modal === 'select-product') {
return (
<ImapProductsModal
onClick={(selectedProduct: ImportType) => {
dispatch(selectImapProduct({ product: selectedProduct }));
}}
onClose={() => dispatch(resetImapDraft())}
/>
);
}
if (modal === 'read-instructions') {
return (
<InstructionsModal
onClose={() => dispatch(resetImapDraft())}
onSubmit={() => {
dispatch(readImapInstructions());
}}
/>
);
}
if (modal === 'import-Mail') {
return <ImapMailModal />;
}
if (modal === 'import-Calendar') {
return <CalendarModal onClose={() => dispatch(resetImapDraft())} />;
}
if (modal === 'import-Contacts') {
return <ContactImportModal open onClose={() => dispatch(resetImapDraft())} />;
}
if (modal === 'oauth') {
return <OAuthModal />;
}
return null;
};
export default MainModal;
| 4,808
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/ConfirmLeaveModal/ConfirmLeaveModal.test.tsx
|
import { fireEvent, screen } from '@testing-library/dom';
import { easySwitchRender } from '@proton/activation/src/tests/render';
import ConfirmLeaveModal from './ConfirmLeaveModal';
describe('Test confirm leave modal', () => {
it('Should trigger close events', () => {
const handleClose = jest.fn();
const handleContinue = jest.fn();
easySwitchRender(<ConfirmLeaveModal handleClose={handleClose} handleContinue={handleContinue} />);
const cancel = screen.getByTestId('ConfirmLeaveModal:discard');
fireEvent.click(cancel);
expect(handleClose).toBeCalledTimes(1);
});
it('Should trigger continue events', () => {
const handleClose = jest.fn();
const handleContinue = jest.fn();
easySwitchRender(<ConfirmLeaveModal handleClose={handleClose} handleContinue={handleContinue} />);
const submit = screen.getByTestId('ConfirmLeaveModal:continue');
fireEvent.click(submit);
expect(handleContinue).toBeCalledTimes(1);
});
});
| 4,809
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/ConfirmLeaveModal/ConfirmLeaveModal.tsx
|
import { c } from 'ttag';
import { Button } from '@proton/atoms/Button';
import { Prompt } from '@proton/components/components';
interface Props {
handleClose: () => void;
handleContinue: () => void;
}
const ConfirmLeaveModal = ({ handleClose, handleContinue }: Props) => {
return (
<Prompt
open
onClose={handleContinue}
title={c('Confirm modal title').t`Quit import?`}
buttons={[
<Button color="danger" onClick={handleClose} data-testid="ConfirmLeaveModal:discard">{c('Action')
.t`Discard`}</Button>,
<Button onClick={handleContinue} data-testid="ConfirmLeaveModal:continue">{c('Action')
.t`Continue import`}</Button>,
]}
>
<p className="m-0">{c('Info').t`Are you sure you want to discard your import?`}</p>
</Prompt>
);
};
export default ConfirmLeaveModal;
| 4,810
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal/CustomizeMailImportModal.interface.ts
|
import { MailImportFolder } from '@proton/activation/src/helpers/MailImportFoldersParser/MailImportFoldersParser';
import { MailImportDestinationFolder, MailImportPayloadError, TIME_PERIOD } from '@proton/activation/src/interface';
import { Address, Label } from '@proton/shared/lib/interfaces';
export interface MailImportFields {
mapping: MailImportFolder[];
importLabel: Pick<Label, 'Color' | 'Name' | 'Type'>;
importPeriod: TIME_PERIOD;
importAddress: Address;
importCategoriesDestination: MailImportDestinationFolder;
}
export const SYSTEM_FOLDERS = Object.values(MailImportDestinationFolder) as string[];
export const FOLDER_ICONS = {
[MailImportDestinationFolder.INBOX]: 'inbox',
[MailImportDestinationFolder.ALL_DRAFTS]: 'file-lines',
[MailImportDestinationFolder.ALL_SENT]: 'paper-plane-horizontal',
[MailImportDestinationFolder.TRASH]: 'trash',
[MailImportDestinationFolder.SPAM]: 'fire',
[MailImportDestinationFolder.ARCHIVE]: 'archive-box',
[MailImportDestinationFolder.SENT]: 'paper-plane-horizontal',
[MailImportDestinationFolder.DRAFTS]: 'file-lines',
[MailImportDestinationFolder.STARRED]: 'star',
[MailImportDestinationFolder.ALL_MAIL]: 'envelopes',
[MailImportDestinationFolder.ALMOST_ALL_MAIL]: 'envelopes',
} as const;
export interface FolderMapItem extends MailImportFolder {
disabled: boolean;
errors: MailImportPayloadError[];
isLabel: boolean;
}
| 4,811
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal/CustomizeMailImportModal.test.tsx
|
import { fireEvent, screen, waitFor } from '@testing-library/dom';
import { ApiMailImporterFolder } from '@proton/activation/src/api/api.interface';
import MailImportFoldersParser from '@proton/activation/src/helpers/MailImportFoldersParser/MailImportFoldersParser';
import { MailImportDestinationFolder, TIME_PERIOD } from '@proton/activation/src/interface';
import { easySwitchRender } from '@proton/activation/src/tests/render';
import { ModalStateProps } from '@proton/components';
import { ADDRESS_STATUS, ADDRESS_TYPE } from '@proton/shared/lib/constants';
import { Address } from '@proton/shared/lib/interfaces';
import CustomizeMailImportModal from './CustomizeMailImportModal';
import { MailImportFields } from './CustomizeMailImportModal.interface';
const address: Address = {
DisplayName: 'Testing',
DomainID: 'proton.ch',
Email: 'testing@proton.ch',
HasKeys: 1,
ID: 'ID',
Keys: [],
SignedKeyList: null,
Order: 1,
Priority: 1,
Receive: 1,
Send: 1,
Signature: 'Testing signature',
Status: ADDRESS_STATUS.STATUS_ENABLED,
Type: ADDRESS_TYPE.TYPE_ORIGINAL,
ProtonMX: false,
ConfirmationState: 1,
CatchAll: false,
};
const isLabelMapping = false;
const simpleProviderFolders: ApiMailImporterFolder[] = [
{
Source: 'New Name',
Separator: '/',
Size: 10,
Flags: [],
},
];
const simpleFields: MailImportFields = {
mapping: new MailImportFoldersParser(simpleProviderFolders, isLabelMapping).folders,
importLabel: { Color: '#fff', Name: 'label', Type: 1 },
importPeriod: TIME_PERIOD.LAST_MONTH,
importAddress: address,
importCategoriesDestination: MailImportDestinationFolder.INBOX,
};
const providerFolderWithError: ApiMailImporterFolder[] = [
{
Source: 'Scheduled',
Separator: '/',
Size: 10,
Flags: [],
},
];
const getModalProps = (): ModalStateProps => {
const key = new Date();
return {
key: key.getTime().toString(),
open: true,
onClose: () => {},
onExit: () => {},
};
};
describe('Customize modal tests', () => {
it('Should display the customize folder modal and close it with save button', () => {
easySwitchRender(
<CustomizeMailImportModal
foldersOpened={false}
fields={simpleFields}
importedEmail="test@proton.ch"
isLabelMapping={false}
onSubmit={() => {}}
displayCategories={false}
modalProps={getModalProps()}
/>
);
const saveButton = screen.getByTestId('CustomizeModal:modalSave');
fireEvent.click(saveButton);
});
it('Should display the customize folder modal and close it with cancel button', () => {
easySwitchRender(
<CustomizeMailImportModal
foldersOpened={false}
fields={simpleFields}
importedEmail="test@proton.ch"
isLabelMapping={false}
onSubmit={() => {}}
displayCategories={false}
modalProps={getModalProps()}
/>
);
const cancelButton = screen.getByTestId('CustomizeModal:modalCancel');
fireEvent.click(cancelButton);
});
it('Should display the customize folder modal', () => {
easySwitchRender(
<CustomizeMailImportModal
foldersOpened={false}
fields={simpleFields}
importedEmail="test@proton.ch"
isLabelMapping={false}
onSubmit={() => {}}
displayCategories={false}
modalProps={getModalProps()}
/>
);
screen.getByTestId('CustomizeModal:folderHeader');
// Display folders
const showFolderButton = screen.getByTestId('CustomizeModal:toggleFolders');
fireEvent.click(showFolderButton);
screen.getByTestId('CustomizeModal:destinationItem');
// Toggle folder checkbox
const checkboxes = screen.getAllByTestId('CustomizeModal:checkbox');
fireEvent.click(checkboxes[0]);
fireEvent.click(checkboxes[0]);
// Close folders
fireEvent.click(showFolderButton);
expect(screen.queryByTestId('CustomizeModal:destinationItem')).toBeNull();
// Open and close the edit label modal
const editLabelButton = screen.getByTestId('CustomizeModal:editLabel');
fireEvent.click(editLabelButton);
screen.getByTestId('label-modal');
const editLabelCloseButton = screen.getByTestId('label-modal:cancel');
fireEvent.click(editLabelCloseButton);
// Change default time period
const select = screen.getByText('Last month only');
fireEvent.click(select);
fireEvent.click(screen.getByText('Last 3 months only'));
// Close modal and expect confirmation modal and close it
const cancelButton = screen.getByTestId('CustomizeModal:modalCancel');
fireEvent.click(cancelButton);
screen.getByTestId('CancelModal:container');
const closeModal = screen.getByTestId('CancelModal:cancel');
fireEvent.click(closeModal);
// Click again the cancel button but cancel the changes this time
fireEvent.click(cancelButton);
const quitModal = screen.getByTestId('CancelModal:quit');
fireEvent.click(quitModal);
});
it('Should display the customize label modal', async () => {
const onSubmit = jest.fn();
easySwitchRender(
<CustomizeMailImportModal
foldersOpened={false}
fields={simpleFields}
importedEmail="test@proton.ch"
isLabelMapping={true}
displayCategories={true}
onSubmit={onSubmit}
modalProps={getModalProps()}
/>
);
screen.getByTestId('CustomizeModal:labelHeader');
const showFolderButton = screen.getByTestId('CustomizeModal:toggleFolders');
fireEvent.click(showFolderButton);
screen.getByTestId('CustomizeModal:destinationItem');
fireEvent.click(showFolderButton);
expect(screen.queryByTestId('CustomizeModal:destinationItem')).toBeNull();
// Expect to see gmail categories
screen.getByTestId('CustomizeModal:gmailCategories');
// Change the Gmail category
const select = screen.getByText('Move to Inbox');
fireEvent.click(select);
fireEvent.click(screen.getByText('Move to Archive'));
// Submit the change and verify the new payload
const modalSave = screen.getByTestId('CustomizeModal:modalSave');
fireEvent.click(modalSave);
expect(onSubmit).toHaveBeenCalledTimes(1);
expect(onSubmit).toHaveBeenCalledWith({
...simpleFields,
importCategoriesDestination: MailImportDestinationFolder.ARCHIVE,
});
});
it('Should display an error if folder is reserved and save buttons should be disabled', () => {
const fields: MailImportFields = {
mapping: new MailImportFoldersParser(providerFolderWithError, isLabelMapping).folders,
importLabel: { Color: '#fff', Name: 'label', Type: 1 },
importPeriod: TIME_PERIOD.LAST_MONTH,
importAddress: address,
importCategoriesDestination: MailImportDestinationFolder.ALL_DRAFTS,
};
const onSubmit = jest.fn();
easySwitchRender(
<CustomizeMailImportModal
foldersOpened={true}
fields={fields}
importedEmail="test@proton.ch"
isLabelMapping={false}
displayCategories={false}
onSubmit={onSubmit}
modalProps={getModalProps()}
/>
);
const input = screen.getByDisplayValue('Scheduled');
const rowSave = screen.getAllByTestId('CustomizeModal:rowSave');
const modalSave = screen.getByTestId('CustomizeModal:modalSave');
expect(input).toBeInvalid();
expect(modalSave).toBeDisabled();
rowSave.every((item) => expect(item).toBeDisabled());
fireEvent.click(modalSave);
rowSave.forEach((item) => fireEvent.click(item));
expect(onSubmit).toHaveBeenCalledTimes(0);
});
it('Should remove error if error is fixed and save buttons should be enabled', async () => {
const fields: MailImportFields = {
mapping: new MailImportFoldersParser(providerFolderWithError, isLabelMapping).folders,
importLabel: { Color: '#fff', Name: 'label', Type: 1 },
importPeriod: TIME_PERIOD.LAST_MONTH,
importAddress: address,
importCategoriesDestination: MailImportDestinationFolder.ALL_DRAFTS,
};
const onSubmit = jest.fn();
easySwitchRender(
<CustomizeMailImportModal
foldersOpened={true}
fields={fields}
importedEmail="test@proton.ch"
isLabelMapping={false}
displayCategories={false}
onSubmit={onSubmit}
modalProps={getModalProps()}
/>
);
const input = screen.getByDisplayValue('Scheduled');
const rowSave = screen.getAllByTestId('CustomizeModal:rowSave');
const modalSave = screen.getByTestId('CustomizeModal:modalSave');
expect(modalSave).toBeDisabled();
expect(input).toBeInvalid();
rowSave.every((item) => expect(item).toBeDisabled());
fireEvent.click(modalSave);
rowSave.forEach((item) => {
fireEvent.click(item);
});
expect(onSubmit).toHaveBeenCalledTimes(0);
// Fix the error by changing input and click the buttons again
fireEvent.change(input, { target: { value: 'New Name' } });
await waitFor(() => expect(input).toBeValid());
rowSave.every((item) => expect(item).toBeEnabled());
rowSave.forEach((item) => {
fireEvent.click(item);
});
expect(modalSave).toBeEnabled();
fireEvent.click(modalSave);
expect(onSubmit).toHaveBeenCalledTimes(1);
// Update initial mapping to have the new folder name
const newMapping = fields.mapping;
newMapping[0].protonPath = ['New Name'];
expect(onSubmit).toHaveBeenCalledWith({ ...fields, mapping: newMapping });
});
it('Should update the payload when the selected period changes', () => {
const onSubmit = jest.fn();
easySwitchRender(
<CustomizeMailImportModal
foldersOpened={false}
fields={simpleFields}
importedEmail="test@proton.ch"
isLabelMapping={false}
displayCategories={false}
onSubmit={onSubmit}
modalProps={getModalProps()}
/>
);
const select = screen.getByText('Last month only');
const rowSave = screen.queryAllByTestId('CustomizeModal:rowSave');
const modalSave = screen.getByTestId('CustomizeModal:modalSave');
expect(rowSave.length).toBe(0);
fireEvent.click(select);
fireEvent.click(screen.getByText('Last 3 months only'));
fireEvent.click(modalSave);
expect(onSubmit).toHaveBeenCalledTimes(1);
expect(onSubmit).toHaveBeenCalledWith({ ...simpleFields, importPeriod: TIME_PERIOD.LAST_3_MONTHS });
});
it('Should display warning when cancelling changes in modal', () => {
const onSubmit = jest.fn();
easySwitchRender(
<CustomizeMailImportModal
foldersOpened={false}
fields={simpleFields}
importedEmail="test@proton.ch"
isLabelMapping={false}
displayCategories={false}
onSubmit={onSubmit}
modalProps={getModalProps()}
/>
);
const select = screen.getByText('Last month only');
const rowSave = screen.queryAllByTestId('CustomizeModal:rowSave');
const modalCancel = screen.getByTestId('CustomizeModal:modalCancel');
expect(rowSave.length).toBe(0);
fireEvent.click(select);
fireEvent.click(screen.getByText('Last 3 months only'));
fireEvent.click(modalCancel);
screen.getByTestId('CancelModal:container');
});
it('Should indent folders in source and destination', () => {
const providerFolders = [
'Parent',
'Parent/Children',
'Parent/Children/SubChildren',
'Parent/Children/SubChildren/FinalChildren',
].map(
(source) =>
({
Source: source,
Separator: '/',
}) as ApiMailImporterFolder
);
const nestedFields: MailImportFields = {
mapping: new MailImportFoldersParser(providerFolders, isLabelMapping).folders,
importLabel: { Color: '#fff', Name: 'label', Type: 1 },
importPeriod: TIME_PERIOD.LAST_MONTH,
importAddress: address,
importCategoriesDestination: MailImportDestinationFolder.ALL_DRAFTS,
};
const onSubmit = jest.fn();
easySwitchRender(
<CustomizeMailImportModal
foldersOpened={true}
fields={nestedFields}
importedEmail="test@proton.ch"
isLabelMapping={false}
displayCategories={false}
onSubmit={onSubmit}
modalProps={getModalProps()}
/>
);
const sourceItems = screen.getAllByTestId('CustomizeModal:sourceItem');
sourceItems.every((item, index) => {
expect(item).toHaveStyle(`--ml-custom: ${index + 1}em`);
});
const destinationItem = screen.getAllByTestId('CustomizeModal:destinationItem');
destinationItem.forEach((item, index) => {
if (index < 3) {
expect(item).toHaveStyle(`--ml-custom: ${index + 1}em`);
} else {
expect(item).toHaveStyle('--ml-custom: 3em');
}
});
});
it('Should display destinationFolder name instead of source in proton import column', () => {
const providerFolders = [
{
Source: 'INBOX',
Separator: '/',
DestinationFolder: 'Inbox',
} as ApiMailImporterFolder,
{
Source: '[Gmail]/Sent Mail',
Separator: '/',
DestinationFolder: 'Sent',
} as ApiMailImporterFolder,
{
Source: '[Gmail]/Drafts',
Separator: '/',
DestinationFolder: 'Drafts',
} as ApiMailImporterFolder,
];
const nestedFields: MailImportFields = {
mapping: new MailImportFoldersParser(providerFolders, isLabelMapping).folders,
importLabel: { Color: '#fff', Name: 'label', Type: 1 },
importPeriod: TIME_PERIOD.LAST_MONTH,
importAddress: address,
importCategoriesDestination: MailImportDestinationFolder.ALL_DRAFTS,
};
const onSubmit = jest.fn();
easySwitchRender(
<CustomizeMailImportModal
foldersOpened={true}
fields={nestedFields}
importedEmail="test@proton.ch"
isLabelMapping={true}
displayCategories={false}
onSubmit={onSubmit}
modalProps={getModalProps()}
/>
);
expect(screen.getAllByTestId('CustomizeModal:FolderRow:providerName').map((node) => node.textContent)).toEqual([
'INBOX',
'[Gmail]/Sent Mail',
'[Gmail]/Drafts',
]);
expect(screen.getAllByTestId('CustomizeModal:FolderRow:protonName').map((node) => node.textContent)).toEqual([
'Inbox',
'Sent',
'Drafts',
]);
});
});
| 4,812
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal/CustomizeMailImportModal.tsx
|
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import {
Form,
ModalStateProps,
ModalTwo,
ModalTwoFooter,
ModalTwoHeader,
useModalState,
useToggle,
} from '@proton/components';
import ModalContent from '@proton/components/components/modalTwo/ModalContent';
import { MailImportFields } from './CustomizeMailImportModal.interface';
import Addresses from './CustomizeMailImportModalAddresses';
import CustomizeMailImportModalConfirmLeaveModal from './CustomizeMailImportModalConfirmLeaveModal';
import ImportMappingToggle from './CustomizeMailImportModalCustomizeFoldersToggle';
import GmailCategories from './CustomizeMailImportModalGmailCategories';
import Header from './CustomizeMailImportModalHeader';
import ImportLabelField from './CustomizeMailImportModalLabel';
import ImportPeriodField from './CustomizeMailImportModalPeriod';
import ManageFolders from './ManageFolders/ManageFolders';
import useCustomizeMailImportModal from './useCustomizeMailImportModal';
interface Props {
fields: MailImportFields;
foldersOpened: boolean;
importedEmail: string;
isLabelMapping: boolean;
modalProps: ModalStateProps;
displayCategories: boolean;
onSubmit: (nextFields: MailImportFields) => void;
}
const CustomizeMailImportModal = ({
foldersOpened = false,
fields,
importedEmail,
isLabelMapping,
modalProps,
onSubmit,
displayCategories,
}: Props) => {
const [confirmLeaveModalProps, openConfirmLeaveModal, renderConfirmLeaveModal] = useModalState();
const {
customFields,
handleCancel,
handleChangeField,
handleSaveErroredInput,
handleSubmit,
selectedFoldersCount,
submitDisabled,
totalFoldersCount,
} = useCustomizeMailImportModal({
fields,
isLabelMapping,
onClose: modalProps.onClose,
onSubmit,
openConfirmModal: () => openConfirmLeaveModal(true),
});
const { state: displayFolders, toggle: toggleFolders } = useToggle(foldersOpened);
return (
<>
<ModalTwo {...modalProps} size="xlarge" onClose={handleCancel} as={Form} onSubmit={handleSubmit}>
<ModalTwoHeader title={c('Title').t`Customize your mail import`} />
<ModalContent>
<Header isLabelMapping={isLabelMapping} />
<ImportLabelField
label={customFields.importLabel}
onEditLabel={(nextLabel) => {
handleChangeField('importLabel', nextLabel);
}}
/>
<Addresses
selectedAddressID={customFields.importAddress.ID}
onChange={(nextAddress) => handleChangeField('importAddress', nextAddress)}
/>
<ImportPeriodField
selectedPeriod={customFields.importPeriod}
onChange={(nextPeriod) => handleChangeField('importPeriod', nextPeriod)}
/>
<ImportMappingToggle
isLabelMapping={isLabelMapping}
organizeFolderVisible={displayFolders}
selectedFoldersCount={selectedFoldersCount}
toggleFolderVisibility={toggleFolders}
totalFoldersCount={totalFoldersCount}
/>
<GmailCategories
handleChange={(nextCategoryDestination) =>
handleChangeField('importCategoriesDestination', nextCategoryDestination)
}
hasCategories={displayCategories}
selectedCategoriesDest={customFields.importCategoriesDestination}
/>
{displayFolders && (
<ManageFolders
toEmail={customFields.importAddress.Email}
fromEmail={importedEmail}
isLabelMapping={isLabelMapping}
mapping={customFields.mapping}
onChange={(nextMapping) => handleChangeField('mapping', nextMapping)}
onErroredInputSaved={handleSaveErroredInput}
/>
)}
</ModalContent>
<ModalTwoFooter>
<Button shape="outline" onClick={handleCancel} data-testid="CustomizeModal:modalCancel">
{c('Action').t`Cancel`}
</Button>
<Button color="norm" disabled={submitDisabled} type="submit" data-testid="CustomizeModal:modalSave">
{c('Action').t`Save`}
</Button>
</ModalTwoFooter>
</ModalTwo>
{renderConfirmLeaveModal && (
<CustomizeMailImportModalConfirmLeaveModal
onContinue={() => {
openConfirmLeaveModal(false);
}}
onStop={() => {
openConfirmLeaveModal(false);
modalProps.onClose();
}}
{...confirmLeaveModalProps}
/>
)}
</>
);
};
export default CustomizeMailImportModal;
| 4,813
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal/CustomizeMailImportModalAddresses.test.tsx
|
import { fireEvent, screen, waitFor } from '@testing-library/dom';
import useAvailableAddresses from '@proton/activation/src/hooks/useAvailableAddresses';
import { generateMockAddressArray } from '@proton/activation/src/tests/data/addresses';
import { easySwitchRender } from '@proton/activation/src/tests/render';
import CustomizeMailImportModalAddresses from './CustomizeMailImportModalAddresses';
jest.mock('@proton/activation/src/hooks/useAvailableAddresses');
const mockUseAvailableAddresses = useAvailableAddresses as jest.MockedFunction<any>;
const addresses = generateMockAddressArray(3, true);
describe('CustomizeMailImportModalAddresses', () => {
it('Should render simple field when one available address', async () => {
mockUseAvailableAddresses.mockReturnValue({
availableAddresses: addresses,
loading: false,
defaultAddress: addresses[0],
});
const onSubmit = jest.fn();
easySwitchRender(<CustomizeMailImportModalAddresses selectedAddressID={addresses[0].ID} onChange={onSubmit} />);
const select = screen.getByTestId('CustomizeModal:addressSelect');
fireEvent.click(select);
await waitFor(() => screen.getAllByTestId('CustomizeModal:addressRow'));
const options = screen.getAllByTestId('CustomizeModal:addressRow');
expect(options).toHaveLength(options.length);
fireEvent.click(options[1]);
expect(onSubmit).toHaveBeenCalledTimes(1);
expect(onSubmit).toHaveBeenCalledWith({ ...addresses[1] });
});
});
| 4,814
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal/CustomizeMailImportModalAddresses.tsx
|
import { c } from 'ttag';
import useAvailableAddresses from '@proton/activation/src/hooks/useAvailableAddresses';
import { Field, Label, Option, Row, SelectTwo } from '@proton/components/components';
import { Address } from '@proton/shared/lib/interfaces';
interface Props {
selectedAddressID: string;
onChange: (address: Address) => void;
}
const CustomizeMailImportModalAddresses = ({ selectedAddressID, onChange }: Props) => {
const { availableAddresses } = useAvailableAddresses();
return (
<>
{availableAddresses.length > 1 && (
<div className="mb-4 border-bottom flex-align-items-center">
<Row>
<Label className="flex flex-align-items-center">{c('Label').t`Import to email address`}</Label>
<Field>
<SelectTwo
className="flex-item-fluid"
value={selectedAddressID}
onChange={({ value: addressID }) => {
const nextAddress = availableAddresses.find((address) => address.ID === addressID);
if (nextAddress) {
onChange(nextAddress);
} else {
throw new Error('Address should be defined');
}
}}
data-testid="CustomizeModal:addressSelect"
>
{availableAddresses.map((address) => (
<Option
key={address.ID}
value={address.ID}
title={address.Email}
data-testid="CustomizeModal:addressRow"
>
{address.Email}
</Option>
))}
</SelectTwo>
</Field>
</Row>
</div>
)}
</>
);
};
export default CustomizeMailImportModalAddresses;
| 4,815
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal/CustomizeMailImportModalConfirmLeaveModal.tsx
|
import { c } from 'ttag';
import { Button } from '@proton/atoms/Button';
import { ModalStateProps, Prompt } from '@proton/components/components';
interface Props extends ModalStateProps {
onContinue: () => void;
onStop: () => void;
}
const CustomizeMailImportModalConfirmLeaveModal = ({ onContinue, onStop, ...rest }: Props) => (
<Prompt
{...rest}
title={c('Confirm modal title').t`Quit import customization?`}
buttons={[
<Button color="danger" onClick={onStop} data-testid="CancelModal:quit">{c('Action').t`Quit`}</Button>,
<Button color="weak" onClick={() => rest.onClose()} data-testid="CancelModal:cancel">{c('Action')
.t`Stay`}</Button>,
]}
onClose={onContinue}
data-testid="CancelModal:container"
>
<p className="m-0">{c('Warning').t`You will lose any customization you made so far.`}</p>
</Prompt>
);
export default CustomizeMailImportModalConfirmLeaveModal;
| 4,816
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal/CustomizeMailImportModalCustomizeFoldersToggle.tsx
|
import { EasyTrans } from '@proton/activation/src/helpers/easyTrans';
import { Button } from '@proton/atoms/Button';
import { Icon, Label, Row } from '@proton/components/components';
interface Props {
isLabelMapping: boolean;
organizeFolderVisible: boolean;
selectedFoldersCount: number;
toggleFolderVisibility: () => void;
totalFoldersCount: number;
}
const CustomizeMailImportModalCustomizeFoldersToggle = ({
isLabelMapping,
organizeFolderVisible,
selectedFoldersCount,
toggleFolderVisibility,
totalFoldersCount,
}: Props) => {
const t = EasyTrans.get(isLabelMapping);
const toggleActionCopy = organizeFolderVisible ? t.hide() : t.show();
return (
<div className="mb-4 border-bottom flex-align-items-center">
<Row>
<Label>{t.manage()}</Label>
<div className="flex flex-align-items-center">
<Icon name={isLabelMapping ? 'tags' : 'folders'} className="mr-2" />
{selectedFoldersCount === totalFoldersCount ? (
<span>{t.totalCount(totalFoldersCount)}</span>
) : (
<span>{t.partialCount(selectedFoldersCount)}</span>
)}
<Button
shape="outline"
className="ml-8"
onClick={toggleFolderVisibility}
data-testid="CustomizeModal:toggleFolders"
>
{toggleActionCopy}
</Button>
</div>
</Row>
</div>
);
};
export default CustomizeMailImportModalCustomizeFoldersToggle;
| 4,817
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal/CustomizeMailImportModalGmailCategories.tsx
|
import { c } from 'ttag';
import { MailImportDestinationFolder } from '@proton/activation/src/interface';
import { Field, Icon, Label, Option, Row, SelectTwo, Tooltip } from '@proton/components/components';
interface Props {
hasCategories: boolean;
selectedCategoriesDest: MailImportDestinationFolder;
handleChange: (val: MailImportDestinationFolder) => void;
}
const CustomizeMailImportModalGmailCategories = ({ hasCategories, selectedCategoriesDest, handleChange }: Props) => {
const categoriesDestOptions = [
{ value: MailImportDestinationFolder.INBOX, title: c('Label').t`Move to Inbox` },
{ value: MailImportDestinationFolder.ARCHIVE, title: c('Label').t`Move to Archive` },
];
return (
<>
{hasCategories && (
<div className="mb-4 flex-align-items-center" data-testid="CustomizeModal:gmailCategories">
<Row>
<Label className="flex flex-align-items-center">
{c('Label').t`Manage categories`}
<Tooltip
title={c('Tooltip')
.t`Gmail automatically categorizes some emails like Social or Promotions. You can select where to import these emails to.`}
>
<Icon name="info-circle" className="ml-2" />
</Tooltip>
</Label>
<Field>
<SelectTwo<MailImportDestinationFolder>
value={selectedCategoriesDest}
onChange={({ value }) => {
handleChange(value);
}}
>
{categoriesDestOptions.map((option) => (
<Option
key={option.value}
value={option.value}
title={option.title}
selected={selectedCategoriesDest === option.value}
/>
))}
</SelectTwo>
</Field>
</Row>
</div>
)}
</>
);
};
export default CustomizeMailImportModalGmailCategories;
| 4,818
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal/CustomizeMailImportModalHeader.tsx
|
import { EasyTrans } from '@proton/activation/src/helpers/easyTrans';
interface Props {
isLabelMapping: boolean;
}
const CustomizeMailImportModalHeader = ({ isLabelMapping }: Props) => {
return (
<div className="mb-4" data-testid={`CustomizeModal:${isLabelMapping ? 'labelHeader' : 'folderHeader'}`}>
{EasyTrans.get(isLabelMapping).infoHeader()}
</div>
);
};
export default CustomizeMailImportModalHeader;
| 4,819
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal/CustomizeMailImportModalLabel.tsx
|
import { c } from 'ttag';
import { Button } from '@proton/atoms/Button';
import { Field, Icon, Label, LabelStack, Row, Tooltip, useModalState } from '@proton/components/components';
import EditLabelModal, { LabelModel } from '@proton/components/containers/labels/modals/EditLabelModal';
interface Props {
label: Pick<LabelModel, 'Name' | 'Color' | 'Type'>;
onEditLabel: (label: Pick<LabelModel, 'Name' | 'Color' | 'Type'>) => void;
}
const CustomizeMailImportModalLabel = ({ label, onEditLabel }: Props) => {
const [editLabelModalProps, openEditLabelModal, renderEditLabelModal] = useModalState();
return (
<div className="mb-4 border-bottom flex-align-items-center">
<Row>
<Label className="flex flex-align-items-center">
{c('Label').t`Label messages as`}
<Tooltip title={c('Tooltip').t`Each imported email will have this label`}>
<Icon name="info-circle" className="ml-2" />
</Tooltip>
</Label>
<Field className="w-auto flex flex-align-items-center flex-nowrap">
{label.Name && (
<LabelStack
labels={[
{
name: label.Name,
color: label.Color,
title: label.Name,
},
]}
className="max-w-full"
/>
)}
<Button
shape="outline"
className="flex-item-noshrink ml-4"
onClick={() => openEditLabelModal(true)}
data-testid="CustomizeModal:editLabel"
>
{c('Action').t`Edit label`}
</Button>
</Field>
{renderEditLabelModal && (
<EditLabelModal
{...editLabelModalProps}
label={label}
type="label"
onCheckAvailable={({ Color, Name, Type }) => {
onEditLabel({ Color, Name, Type });
}}
mode="checkAvailable"
/>
)}
</Row>
</div>
);
};
export default CustomizeMailImportModalLabel;
| 4,820
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal/CustomizeMailImportModalPeriod.tsx
|
import { c } from 'ttag';
import { getTimeUnitLabels } from '@proton/activation/src/constants';
import { TIME_PERIOD } from '@proton/activation/src/interface';
import { Field, Icon, Label, Option, Row, SelectTwo, Tooltip } from '@proton/components/components';
interface Props {
selectedPeriod: TIME_PERIOD;
onChange: (timePeriod: TIME_PERIOD) => void;
}
const CustomizeMailImportModalPeriod = ({ selectedPeriod, onChange }: Props) => {
const timeUnitLabels = getTimeUnitLabels();
const periodOptions = Object.values(TIME_PERIOD).map((item) => ({ value: item, text: timeUnitLabels[item] }));
return (
<div className="mb-4 border-bottom flex-align-items-center">
<Row>
<Label className="flex flex-align-items-center">
{c('Label').t`Import interval`}
<Tooltip title={c('Tooltip').t`The import will start with the most recent messages.`}>
<Icon name="info-circle" className="ml-2" />
</Tooltip>
</Label>
<Field>
<SelectTwo
value={selectedPeriod}
onChange={({ value }) => {
onChange(value);
}}
>
{periodOptions.map((period) => (
<Option key={period.value} value={period.value} title={period.text}>
{period.text}
</Option>
))}
</SelectTwo>
</Field>
</Row>
</div>
);
};
export default CustomizeMailImportModalPeriod;
| 4,821
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal/useCustomizeMailImportModal.ts
|
import { FormEvent, useMemo, useState } from 'react';
import { getMailMappingErrors } from '@proton/activation/src/helpers/getMailMappingErrors';
import { useFolders, useLabels } from '@proton/components';
import isDeepEqual from '@proton/shared/lib/helpers/isDeepEqual';
import { FolderMapItem, MailImportFields } from './CustomizeMailImportModal.interface';
interface Props {
fields: MailImportFields;
isLabelMapping: boolean;
onClose: () => void;
onSubmit: (nextFields: MailImportFields) => void;
openConfirmModal: () => void;
}
const useCustomizeMailImportModal = ({ fields, onClose, onSubmit, openConfirmModal, isLabelMapping }: Props) => {
const [labels = []] = useLabels();
const [folders = []] = useFolders();
const [customFields, setCustomFields] = useState<MailImportFields>({
importAddress: fields.importAddress,
mapping: fields.mapping,
importLabel: fields.importLabel,
importPeriod: fields.importPeriod,
importCategoriesDestination: fields.importCategoriesDestination,
});
const [savedErroredIds, setSavedErroredIds] = useState<FolderMapItem['id'][]>([]);
// [Errors] 1. Lets parse errors once when we open the modal
const initialErrors = useMemo(
() => getMailMappingErrors(customFields.mapping, isLabelMapping, labels, folders),
[]
);
// [Errors] 2. Lets keep track of saved errored inputs and checked/unchecked folders
// to determine if errors are able to be submitted
const mappingInfos = useMemo(() => {
const checkedIds = customFields.mapping.filter((item) => item.checked).map((item) => item.id);
return {
hasErrors:
initialErrors.erroredIds.filter((id) => checkedIds.includes(id) && !savedErroredIds.includes(id))
.length > 0,
totalFoldersCount: customFields.mapping.filter((folder) => !folder.category).length,
selectedFoldersCount: customFields.mapping.filter((folder) => folder.checked && !folder.category).length,
};
}, [customFields.mapping, savedErroredIds]);
const submitDisabled = mappingInfos.selectedFoldersCount === 0 || mappingInfos.hasErrors;
const hasChanged = () => {
const changed = Object.keys(customFields).every((key) => {
// @ts-expect-error ts and key fields
const initialValue = fields[key];
// @ts-expect-error ts and key fields
const customValue = customFields[key];
return isDeepEqual(initialValue, customValue);
});
return changed ? false : true;
};
const handleCancel = () => {
if (hasChanged()) {
openConfirmModal();
} else {
onClose();
}
};
function handleChangeField<K extends keyof MailImportFields>(key: K, value: MailImportFields[K]) {
const nextCustomFields = { ...customFields };
nextCustomFields[key] = value;
setCustomFields(nextCustomFields);
}
const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
e.stopPropagation();
if (submitDisabled) {
return;
}
if (hasChanged()) {
onSubmit(customFields);
} else {
onClose();
}
};
const handleSaveErroredInput = (fieldId: FolderMapItem['id']) => {
setSavedErroredIds([...savedErroredIds, fieldId]);
};
return {
customFields,
handleCancel,
handleChangeField,
handleSubmit,
handleSaveErroredInput,
selectedFoldersCount: mappingInfos.selectedFoldersCount,
submitDisabled,
totalFoldersCount: mappingInfos.totalFoldersCount,
};
};
export default useCustomizeMailImportModal;
| 4,822
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal/ManageFolders/ManageFolders.tsx
|
import { c } from 'ttag';
import { MailImportFields } from '../CustomizeMailImportModal.interface';
import ManageFoldersHeader from './ManageFoldersHeader';
import ManageFoldersRow from './ManageFoldersRow/ManageFoldersRow';
import useManageFolders from './useManageFolders';
interface Props {
fromEmail: string;
isLabelMapping: boolean;
mapping: MailImportFields['mapping'];
onChange: (nextMapping: MailImportFields['mapping']) => void;
onErroredInputSaved: (fieldId: MailImportFields['mapping'][number]['id']) => void;
toEmail: MailImportFields['importAddress']['Email'];
}
const ManageFolders = ({ toEmail, mapping, isLabelMapping, fromEmail, onChange, onErroredInputSaved }: Props) => {
const { handleToggleCheckbox, items, handleRenameItem } = useManageFolders({
isLabelMapping,
mapping,
onChange,
});
return (
<>
<ManageFoldersHeader fromLabel={c('Label').t`From: ${fromEmail}`} toLabel={c('Label').t`To: ${toEmail}`} />
<div className="flex mb-4">
<div className="flex-item-fluid pt-2">
<ul className="unstyled m-0">
{items.map((item, index) => {
// We don't display folder with categories since they are merged
// We need them to keep the folder mapping intact so we return null instead of filtering the array
if (item.category) {
return null;
}
return (
<ManageFoldersRow
key={item.id}
index={index}
folderItem={item}
onRename={handleRenameItem}
onErrorSaved={() => onErroredInputSaved(item.id)}
onToggleCheck={handleToggleCheckbox}
/>
);
})}
</ul>
</div>
</div>
</>
);
};
export default ManageFolders;
| 4,823
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal/ManageFolders/ManageFoldersHeader.tsx
|
import { c } from 'ttag';
interface Props {
fromLabel: string;
toLabel: string;
}
const ManageFoldersHeader = ({ fromLabel, toLabel }: Props) => {
return (
<>
<div className="mb-4 mt-8">{c('Info').t`Please select the folders you would like to import:`}</div>
<div className="flex pt-4">
<div className="flex-item-fluid text-ellipsis pr-2" title={fromLabel}>
<strong>{fromLabel}</strong>
</div>
<div className="flex-item-fluid text-ellipsis pl-2" title={toLabel}>
<strong>{toLabel}</strong>
</div>
</div>
</>
);
};
export default ManageFoldersHeader;
| 4,824
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal/ManageFolders/useManageFolders.helpers.test.ts
|
import { ApiMailImporterFolder } from '@proton/activation/src/api/api.interface';
import MailImportFoldersParser from '@proton/activation/src/helpers/MailImportFoldersParser/MailImportFoldersParser';
import { folderWithChildren, getRenamedFolders } from '@proton/activation/src/tests/data/folders';
import { Label } from '@proton/shared/lib/interfaces';
import { Folder } from '@proton/shared/lib/interfaces/Folder';
import { formatItems, renameChildFolders } from './useManageFolders.helpers';
describe('renameChildFolders', () => {
it('Should rename all child in proton path', () => {
const folders = [...folderWithChildren];
const newFolders = [...folders];
const newFolder = { ...newFolders[0] };
const newName = 'newName';
newFolder.protonPath = [...newFolder.protonPath];
newFolder.protonPath[newFolder.protonPath.length - 1] = newName;
newFolders[0] = newFolder;
const renameFolders = renameChildFolders(newFolder, newFolders, newName);
expect(renameFolders).toStrictEqual(getRenamedFolders(newName));
});
});
describe('formatItems', () => {
it('should compare labels and not folders with mapping when isLabelMapping is false', () => {
const apiFolders = ['flavien', 'guillaume'].map(
(folder) => ({ Source: folder, Separator: '/' } as ApiMailImporterFolder)
);
const isLabelMapping = false;
const mapping = new MailImportFoldersParser(apiFolders, isLabelMapping).folders;
const result = formatItems({
labels: [
{
Name: 'flavien',
Path: 'flavien',
} as Label,
],
folders: [
{
Name: 'guillaume',
Path: 'guillaume',
} as Folder,
],
isLabelMapping,
mapping,
});
expect(result.find((item) => item.id === 'flavien')?.errors).toContain('Unavailable names');
expect(result.find((item) => item.id === 'guillaume')?.errors).toEqual([]);
});
it('should compare folders and not labels with mapping when isLabelMapping is true', () => {
const apiFolders = ['flavien', 'guillaume'].map(
(folder) => ({ Source: folder, Separator: '/' } as ApiMailImporterFolder)
);
const isLabelMapping = true;
const mapping = new MailImportFoldersParser(apiFolders, isLabelMapping).folders;
const result = formatItems({
folders: [
{
Name: 'flavien',
Path: 'flavien',
} as Folder,
],
labels: [
{
Name: 'guillaume',
Path: 'guillaume',
} as Label,
],
isLabelMapping,
mapping,
});
expect(result.find((item) => item.id === 'flavien')?.errors).toContain('Unavailable names');
expect(result.find((item) => item.id === 'guillaume')?.errors).toEqual([]);
});
});
| 4,825
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal/ManageFolders/useManageFolders.helpers.ts
|
import { MailImportFolder } from '@proton/activation/src/helpers/MailImportFoldersParser/MailImportFoldersParser';
import { getMailMappingError } from '@proton/activation/src/helpers/getMailMappingErrors';
import { omit } from '@proton/shared/lib/helpers/object';
import { Label } from '@proton/shared/lib/interfaces';
import { Folder } from '@proton/shared/lib/interfaces/Folder';
import { FolderMapItem, MailImportFields } from '../CustomizeMailImportModal.interface';
interface FormatItemsProps {
mapping: MailImportFields['mapping'];
isLabelMapping: boolean;
folders: Folder[];
labels: Label[];
}
const isItemDisabled = (item: MailImportFolder, collection: MailImportFolder[]) => {
const isRootFolder = item.providerPath.length === 1;
const isParentItemChecked = collection.find((val) => val.id === item.folderParentID)?.checked;
return !(item.checked || isRootFolder || isParentItemChecked);
};
export const formatItems = ({ isLabelMapping, mapping, labels, folders }: FormatItemsProps) => {
return mapping
.map<FolderMapItem>((item, _, collection) => {
return {
...item,
disabled: isItemDisabled(item, collection),
errors: [],
isLabel: isLabelMapping,
};
})
.map((item, _, collection) => {
const errors = getMailMappingError(item, labels, folders, collection, isLabelMapping);
return { ...item, errors };
});
};
/**
* Rename all child folders with new name when a parent is updated
* @param newFolder the current folder that is renamed
* @param newFolders the list of all folders in the current mapping
* @param newName the new name of the folder
* @returns an updated mapping where all childIDs of the updated folder are renamed
*/
export const renameChildFolders = (newFolder: FolderMapItem, newFolders: FolderMapItem[], newName: string) => {
const foldersCopy = [...newFolders];
if (newFolder.folderChildIDS && newFolder.folderChildIDS.length) {
newFolder.folderChildIDS.forEach((childId) => {
const childFolderIndex = foldersCopy.findIndex((val) => val.id === childId);
const childFolder = { ...foldersCopy[childFolderIndex] };
if (!childFolder) {
return;
}
const providerPathIndex = childFolder.providerPath.findIndex((item) => item === newFolder.id);
if (providerPathIndex === -1) {
return;
}
childFolder.protonPath = [...childFolder.protonPath];
childFolder.protonPath[providerPathIndex] = newName;
foldersCopy[childFolderIndex] = childFolder;
});
}
return foldersCopy;
};
export const formatMapping = (nextItems: FolderMapItem[]): MailImportFields['mapping'] =>
nextItems.map((item) => omit(item, ['disabled', 'errors', 'isLabel']));
| 4,826
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal/ManageFolders/useManageFolders.ts
|
import { useFolders, useLabels } from '@proton/components/hooks';
import { FolderMapItem, MailImportFields } from '../CustomizeMailImportModal.interface';
import { formatItems, formatMapping, renameChildFolders } from './useManageFolders.helpers';
interface Props {
mapping: MailImportFields['mapping'];
onChange: (nextMapping: MailImportFields['mapping']) => void;
isLabelMapping: boolean;
}
const useManageFolders = ({ mapping, isLabelMapping, onChange }: Props) => {
const [folders = []] = useFolders();
const [labels = []] = useLabels();
const items: FolderMapItem[] = formatItems({ mapping, isLabelMapping, folders, labels });
const handleToggleCheckbox = (index: number, checked: boolean) => {
const newFolders = [...items];
newFolders[index].checked = checked;
const updatedFolder = newFolders[index];
const final = newFolders.map((val) => {
if (updatedFolder.folderChildIDS.includes(val.id)) {
val.checked = checked;
val.disabled = !checked;
}
return val;
});
onChange(formatMapping(final));
};
const handleRenameItem = (index: number, newName: string) => {
const newFolders = [...items];
const newFolder = { ...newFolders[index] };
newFolder.protonPath = [...newFolder.protonPath];
newFolder.protonPath[newFolder.protonPath.length - 1] = newName;
newFolders[index] = newFolder;
const updatedFolders = renameChildFolders(newFolder, newFolders, newName);
onChange(formatMapping(updatedFolders));
};
return {
items,
handleRenameItem,
handleToggleCheckbox,
};
};
export default useManageFolders;
| 4,827
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal/ManageFolders
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal/ManageFolders/ManageFoldersRow/ManageFoldersRow.tsx
|
import { ChangeEvent, useEffect, useRef, useState } from 'react';
import { c } from 'ttag';
import { MailImportPayloadError } from '@proton/activation/src/interface';
import { Checkbox, Icon, InlineLinkButton, LabelStack } from '@proton/components';
import clsx from '@proton/utils/clsx';
import debounce from '@proton/utils/debounce';
import { FOLDER_ICONS, FolderMapItem } from '../../CustomizeMailImportModal.interface';
import ManageFoldersRowFolderErrors from './ManageFoldersRowFolderErrors';
import ManageFolderRowInput from './ManageFoldersRowInput';
import ManageFoldersRowLabelErrors from './ManageFoldersRowLabelErrors';
const DIMMED_OPACITY_CLASSNAMES = 'opacity-30';
interface WrapperProps {
checked: boolean;
editMode: boolean;
disabled: boolean;
checkboxId: string;
children: React.ReactNode;
}
const Wrapper = ({ checked, editMode, disabled, checkboxId, children }: WrapperProps) => {
const classNames = clsx([
'flex flex-nowrap flex-align-items-center py-4',
!checked && DIMMED_OPACITY_CLASSNAMES,
(disabled || editMode) && 'cursor-default',
]);
return editMode ? (
<div className={classNames}>{children}</div>
) : (
<label htmlFor={checkboxId} className={classNames}>
{children}
</label>
);
};
interface Props {
index: number;
folderItem: FolderMapItem;
onRename: (index: number, Name: string) => void;
onToggleCheck: (index: number, checked: boolean) => void;
onErrorSaved: () => void;
}
const debouncedRenameCallback = debounce((callback) => callback(), 150);
const indentStyle = (level: number) => {
return { '--ml-custom': `${level}em` };
};
const ManageFoldersRow = ({ index, folderItem, onRename, onToggleCheck, onErrorSaved }: Props) => {
const { disabled, checked, errors, systemFolder, protonPath, providerPath, isLabel } = folderItem;
const hasError = errors.length > 0 && checked;
const inputRef = useRef<HTMLInputElement>(null);
const folderProtonName = systemFolder ? systemFolder : protonPath[protonPath.length - 1];
const folderProviderName = providerPath[providerPath.length - 1];
const [inputValue, setInputValue] = useState(folderProtonName);
const [editMode, setEditMode] = useState(hasError);
const handleSave = () => {
setEditMode(false);
onErrorSaved();
};
const handleChange = ({ target }: ChangeEvent<HTMLInputElement>) => {
const { value } = target;
setInputValue(value);
debouncedRenameCallback(() => onRename(index, value));
};
useEffect(() => {
if (editMode && inputRef && inputRef.current) {
inputRef.current.focus();
}
}, [editMode]);
return (
<li className="border-bottom">
<Wrapper checked={checked} editMode={editMode} disabled={disabled} checkboxId={folderItem.id}>
<div className="flex w-1/2 flex-nowrap flex-align-items-center flex-item-noshrink pr-2">
<div
className="flex-item-noshrink ml-custom"
style={indentStyle(providerPath.length)}
data-testid="CustomizeModal:sourceItem"
>
<Checkbox
onChange={({ target: { checked } }: ChangeEvent<HTMLInputElement>) => {
onToggleCheck(index, checked);
}}
id={folderItem.id}
checked={checked}
disabled={disabled}
data-testid="CustomizeModal:checkbox"
/>
</div>
<div
data-testid="CustomizeModal:FolderRow:providerName"
className="ml-2 flex-item-fluid-auto text-ellipsis"
title={folderProviderName}
>
{folderProviderName}
</div>
</div>
<div className="flex w-1/2 pl-2">
<div
className={clsx(['flex flex-nowrap flex-align-items-center ml-custom'])}
style={indentStyle(protonPath.length)}
data-testid="CustomizeModal:destinationItem"
>
{((isLabel && systemFolder) || !isLabel) && (
<Icon
name={systemFolder ? FOLDER_ICONS[systemFolder] : 'folder'}
className={clsx([
'flex-item-noshrink mr-2',
hasError && 'color-danger',
errors.includes(MailImportPayloadError.MERGE_WARNING) && 'color-warning',
])}
/>
)}
</div>
<div
data-testid="CustomizeModal:FolderRow:protonName"
className={clsx([
'flex flex-nowrap flex-item-fluid flex-align-items-center',
hasError && 'color-danger',
errors.includes(MailImportPayloadError.MERGE_WARNING) && 'color-warning',
])}
>
{editMode && !disabled && checked ? (
<ManageFolderRowInput
disabled={!checked}
errors={errors}
handleChange={handleChange}
handleSave={handleSave}
hasError={hasError}
inputRef={inputRef}
inputValue={inputValue}
isLabelMapping={isLabel}
/>
) : (
<>
{isLabel && !systemFolder ? (
<div
className={clsx([
'flex-item-fluid-auto text-ellipsis flex flex-align-items-center',
(hasError || errors.includes(MailImportPayloadError.MERGE_WARNING)) &&
'text-bold',
])}
title={folderProtonName}
>
<LabelStack
labels={[
{
name: folderProtonName,
color: folderItem.color,
title: folderProtonName,
},
]}
className="max-w-full flex-item-fluid"
/>
<ManageFoldersRowLabelErrors checked={checked} errors={errors} />
</div>
) : (
<div
className={clsx([
'text-ellipsis flex flex-align-items-center',
(hasError || errors.includes(MailImportPayloadError.MERGE_WARNING)) &&
'text-bold',
])}
title={folderProtonName}
>
<div className="flex-item-fluid text-ellipsis" title={folderProtonName}>
{folderProtonName}
</div>
<ManageFoldersRowFolderErrors
checked={checked}
errors={errors}
isSystemFolderChild={folderItem.isSystemFolderChild}
/>
</div>
)}
</>
)}
</div>
{checked && ((editMode && !disabled) || hasError) && (
<InlineLinkButton
onClick={handleSave}
className={clsx(['ml-2 p-2', hasError && DIMMED_OPACITY_CLASSNAMES])}
aria-disabled={hasError}
disabled={hasError || !checked}
data-testid="CustomizeModal:rowSave"
>
{c('Action').t`Save`}
</InlineLinkButton>
)}
</div>
</Wrapper>
</li>
);
};
export default ManageFoldersRow;
| 4,828
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal/ManageFolders
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal/ManageFolders/ManageFoldersRow/ManageFoldersRowFolderErrors.tsx
|
import { c } from 'ttag';
import { EasyTrans } from '@proton/activation/src/helpers/easyTrans';
import { MailImportPayloadError } from '@proton/activation/src/interface';
import { Icon, Tooltip } from '@proton/components';
import { BRAND_NAME, MAIL_APP_NAME } from '@proton/shared/lib/constants';
interface Props {
isSystemFolderChild: boolean;
checked: boolean;
errors: MailImportPayloadError[];
}
const ManageFoldersRowFolderErrors = ({ isSystemFolderChild, checked, errors }: Props) => {
const trans = EasyTrans.get(false);
const tooLong = errors.includes(MailImportPayloadError.FOLDER_NAMES_TOO_LONG);
const alreadyUsed = errors.includes(MailImportPayloadError.UNAVAILABLE_NAMES);
const mergeWarning = errors.includes(MailImportPayloadError.MERGE_WARNING);
return checked ? (
<div className="flex-item-noshrink inline-flex flex-align-self-center flex-item-noshrink ml-2">
{tooLong && (
<Tooltip title={trans.errorNameTooLong()} type="error">
<Icon tabIndex={-1} name="info-circle" className="color-danger" />
</Tooltip>
)}
{alreadyUsed && !tooLong && (
<Tooltip title={trans.errorNameAlreadyExists()} type="error">
<Icon tabIndex={-1} name="info-circle" className="color-danger" />
</Tooltip>
)}
{mergeWarning && (
<Tooltip
title={c('Warning')
.t`${BRAND_NAME} will merge all folders with the same name. To avoid this, change the names before import.`}
type="warning"
>
<Icon tabIndex={-1} name="info-circle" className="color-warning" />
</Tooltip>
)}
{isSystemFolderChild && !mergeWarning && (
<Tooltip title={c('Tooltip').t`System subfolders will show up as separate folders in ${MAIL_APP_NAME}`}>
<Icon tabIndex={-1} name="info-circle" />
</Tooltip>
)}
</div>
) : null;
};
export default ManageFoldersRowFolderErrors;
| 4,829
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal/ManageFolders
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal/ManageFolders/ManageFoldersRow/ManageFoldersRowInput.test.tsx
|
import { fireEvent, screen } from '@testing-library/dom';
import { MailImportPayloadError } from '@proton/activation/src/interface';
import { easySwitchRender } from '@proton/activation/src/tests/render';
import ManageFolderRowInput from './ManageFoldersRowInput';
describe('ManageFoldersRowInput', () => {
it('Should not display error', () => {
easySwitchRender(
<ManageFolderRowInput
disabled={false}
errors={[]}
handleChange={jest.fn}
handleSave={jest.fn}
hasError={false}
inputValue={''}
inputRef={null}
isLabelMapping={false}
/>
);
});
it('Should display too long error', async () => {
easySwitchRender(
<ManageFolderRowInput
disabled={false}
errors={[MailImportPayloadError.FOLDER_NAMES_TOO_LONG]}
handleChange={jest.fn}
handleSave={jest.fn}
hasError={true}
inputValue={'Testing'}
inputRef={null}
isLabelMapping={false}
/>
);
await screen.findByText('The folder name is too long. Please choose a different name.');
});
it('Should display too unavailable name error', async () => {
easySwitchRender(
<ManageFolderRowInput
disabled={false}
errors={[MailImportPayloadError.UNAVAILABLE_NAMES]}
handleChange={jest.fn}
handleSave={jest.fn}
hasError={true}
inputValue={'Testing'}
inputRef={null}
isLabelMapping={false}
/>
);
await screen.findByText('This folder name is not available. Please choose a different name.');
});
it('Should display too non empty name error', async () => {
easySwitchRender(
<ManageFolderRowInput
disabled={false}
errors={[MailImportPayloadError.EMPTY]}
handleChange={jest.fn}
handleSave={jest.fn}
hasError={true}
inputValue={'Testing'}
inputRef={null}
isLabelMapping={false}
/>
);
await screen.findByText('Folder name cannot be empty.');
});
it('Should display too reserved name error', async () => {
easySwitchRender(
<ManageFolderRowInput
disabled={false}
errors={[MailImportPayloadError.RESERVED_NAMES]}
handleChange={jest.fn}
handleSave={jest.fn}
hasError={true}
inputValue={'Testing'}
inputRef={null}
isLabelMapping={false}
/>
);
await screen.findByText('The folder name is invalid. Please choose a different name.');
});
it('Should run save method when enter is pressed', async () => {
const handleSave = jest.fn();
easySwitchRender(
<ManageFolderRowInput
disabled={false}
errors={[]}
handleChange={jest.fn}
handleSave={handleSave}
hasError={false}
inputValue={'Testing'}
inputRef={null}
isLabelMapping={false}
/>
);
const input = await screen.getByDisplayValue('Testing');
fireEvent.keyDown(input, { key: 'Enter', code: 'Enter', charCode: 13 });
expect(handleSave).toBeCalledTimes(1);
});
it('Should not run save method when enter is pressed and component has error', async () => {
const handleSave = jest.fn();
easySwitchRender(
<ManageFolderRowInput
disabled={false}
errors={[MailImportPayloadError.EMPTY]}
handleChange={jest.fn}
handleSave={handleSave}
hasError={true}
inputValue={'Testing'}
inputRef={null}
isLabelMapping={false}
/>
);
const input = await screen.getByDisplayValue('Testing');
fireEvent.keyDown(input, { key: 'Enter', code: 'Enter', charCode: 13 });
expect(handleSave).toBeCalledTimes(0);
});
});
| 4,830
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal/ManageFolders
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal/ManageFolders/ManageFoldersRow/ManageFoldersRowInput.tsx
|
import { KeyboardEvent, Ref } from 'react';
import { EasyTrans } from '@proton/activation/src/helpers/easyTrans';
import { MailImportPayloadError } from '@proton/activation/src/interface';
import { InputFieldTwo } from '@proton/components/components';
interface Props {
disabled: boolean;
errors: MailImportPayloadError[];
handleChange: (val: any) => void;
handleSave: () => void;
hasError: boolean;
inputRef: Ref<any>;
inputValue: string;
isLabelMapping: boolean;
}
const ManageFolderRowInput = ({
disabled,
errors,
handleChange,
handleSave,
hasError,
inputRef,
inputValue,
isLabelMapping,
}: Props) => {
const trans = EasyTrans.get(isLabelMapping);
let error;
const tooLongErrors = [MailImportPayloadError.FOLDER_NAMES_TOO_LONG, MailImportPayloadError.LABEL_NAMES_TOO_LONG];
if (tooLongErrors.some((error) => errors.includes(error))) {
error = trans.errorNameTooLong();
}
if (errors.includes(MailImportPayloadError.UNAVAILABLE_NAMES)) {
error = trans.errorNameAlreadyExists();
}
if (errors.includes(MailImportPayloadError.EMPTY)) {
error = trans.errorEmptyValue();
}
if (errors.includes(MailImportPayloadError.RESERVED_NAMES)) {
error = trans.errorReservedName();
}
return (
<InputFieldTwo
autoFocus
disabled={disabled}
required
ref={inputRef}
value={inputValue}
onChange={handleChange}
onKeyDown={(e: KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter') {
e.preventDefault();
if (hasError) {
return;
}
handleSave();
}
}}
dense
error={error}
className="h-auto"
/>
);
};
export default ManageFolderRowInput;
| 4,831
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal/ManageFolders
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/CustomizeMailImportModal/ManageFolders/ManageFoldersRow/ManageFoldersRowLabelErrors.tsx
|
import { EasyTrans } from '@proton/activation/src/helpers/easyTrans';
import { MailImportPayloadError } from '@proton/activation/src/interface';
import { Icon, Tooltip } from '@proton/components';
interface Props {
checked: boolean;
errors: MailImportPayloadError[];
}
const ManageFoldersRowLabelErrors = ({ checked, errors }: Props) => {
const trans = EasyTrans.get(true);
const tooLong = errors.includes(MailImportPayloadError.LABEL_NAMES_TOO_LONG);
const alreadyUsed = errors.includes(MailImportPayloadError.UNAVAILABLE_NAMES);
return checked ? (
<div className="flex-item-noshrink inline-flex flex-align-self-center flex-item-noshrink ml-4">
{tooLong && (
<Tooltip title={trans.errorNameTooLong()} type="error">
<Icon tabIndex={-1} name="info-circle" className="color-danger" />
</Tooltip>
)}
{alreadyUsed && !tooLong && (
<Tooltip title={trans.errorNameAlreadyExists()} type="error">
<Icon tabIndex={-1} name="info-circle" className="color-danger" />
</Tooltip>
)}
</div>
) : null;
};
export default ManageFoldersRowLabelErrors;
| 4,832
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/CalendarModal/CalendarModal.tsx
|
import { ImportModal } from '@proton/components/containers/calendar/importModal';
import { useCalendarUserSettings, useCalendars } from '@proton/components/hooks';
import {
DEFAULT_CALENDAR_USER_SETTINGS as DEFAULT_SETTINGS,
getPreferredActiveWritableCalendar,
getVisualCalendars,
sortCalendars,
} from '@proton/shared/lib/calendar/calendar';
interface Props {
onClose: () => void;
}
const CalendarModal = ({ onClose }: Props) => {
const [calendars = [], loading] = useCalendars();
const visualCalendars = sortCalendars(getVisualCalendars(calendars));
const [settings = DEFAULT_SETTINGS, loadingSettings] = useCalendarUserSettings();
const defaultCalendar = getPreferredActiveWritableCalendar(visualCalendars, settings.DefaultCalendarID);
if (loading || loadingSettings) {
return null;
}
return (
<ImportModal
key={'calendar-import-modal'}
isOpen
onClose={onClose}
initialCalendar={defaultCalendar!}
calendars={visualCalendars}
/>
);
};
export default CalendarModal;
| 4,833
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/ImapMailModal.test.tsx
|
import { fireEvent, screen, waitFor } from '@testing-library/react';
import { rest } from 'msw';
import { setupServer } from 'msw/node';
import { easySwitchRender } from '@proton/activation/src/tests/render';
import ImapMailModal from './ImapMailModal';
const server = setupServer();
beforeAll(() => {
server.listen();
});
afterEach(() => server.resetHandlers());
afterAll(() => {
server.close();
});
describe('IMAP Start Step', () => {
it('Should render an empty form and fill server when email filled', async () => {
easySwitchRender(<ImapMailModal />);
const emailInput = screen.getByTestId('StepForm:emailInput');
const passwordInput = screen.getByTestId('StepForm:passwordInput');
const serverInput = screen.getByTestId('StepForm:serverInput');
const portInput = screen.getByTestId('StepForm:portInput');
const submitButton = screen.getByTestId('StepForm:submitButton');
fireEvent.change(emailInput, { target: { value: 'testing@proton.ch' } });
server.use(
rest.get('/importer/v1/mail/importers/authinfo', (req, res, ctx) => {
return res(
ctx.set('date', '01/01/2022'),
ctx.json({
Authentication: {
ImapHost: 'imap.proton.ch',
ImapPort: 993,
},
})
);
})
);
await waitFor(() => expect(serverInput).toHaveValue('imap.proton.ch'));
expect(portInput).toHaveValue('993');
expect(submitButton).toBeDisabled();
fireEvent.change(passwordInput, { target: { value: 'password' } });
await waitFor(() => expect(submitButton).toBeEnabled());
// Change server and port if there is an issue
fireEvent.change(serverInput, { target: { value: 'imap.proton.me' } });
expect(serverInput).toHaveValue('imap.proton.me');
fireEvent.change(portInput, { target: { value: '995' } });
expect(portInput).toHaveValue('995');
});
});
| 4,834
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/ImapMailModal.tsx
|
import { useEffect } from 'react';
import {
displayConfirmLeaveModal,
initImapMailImport,
resetImapDraft,
} from '@proton/activation/src/logic/draft/imapDraft/imapDraft.actions';
import {
selectImapDraftMailConfirmModalDisplay,
selectImapDraftMailImportStep,
} from '@proton/activation/src/logic/draft/imapDraft/imapDraft.selector';
import { useEasySwitchDispatch, useEasySwitchSelector } from '@proton/activation/src/logic/store';
import ConfirmLeaveModal from '../../ConfirmLeaveModal/ConfirmLeaveModal';
import StepForm from './StepForm/StepForm';
import StepImporting from './StepImporting/StepImporting';
import StepPrepare from './StepPrepareImap/StepPrepareImap';
const ImapMailModal = () => {
const confirmLeave = useEasySwitchSelector(selectImapDraftMailConfirmModalDisplay);
const dispatch = useEasySwitchDispatch();
const step = useEasySwitchSelector(selectImapDraftMailImportStep);
useEffect(() => {
if (step === undefined) {
dispatch(initImapMailImport());
}
}, []);
const handleClose = () => {
dispatch(resetImapDraft());
};
const handleContinue = () => {
dispatch(displayConfirmLeaveModal(false));
};
return (
<>
{confirmLeave && <ConfirmLeaveModal handleClose={handleClose} handleContinue={handleContinue} />}
{step && ['form', 'reconnect-form'].includes(step) && <StepForm />}
{step === 'prepare-import' && <StepPrepare />}
{step === 'importing' && <StepImporting />}
</>
);
};
export default ImapMailModal;
| 4,835
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/ProviderWrapper.tsx
|
import { c } from 'ttag';
import { CircleLoader } from '@proton/atoms/CircleLoader';
import { TextLoader } from '@proton/components';
interface Props {
isConnectingToProvider: boolean;
children: React.ReactNode | React.ReactNode[];
}
const ProviderWrapper = ({ children, isConnectingToProvider }: Props) => {
if (isConnectingToProvider) {
return (
<div className="p-4 text-center w-full">
<CircleLoader size="large" />
<TextLoader>{c('Loading info').t`Connecting to your email provider`}</TextLoader>
</div>
);
}
return <>{children}</>;
};
export default ProviderWrapper;
| 4,836
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/StepForm/StepForm.tsx
|
import { c } from 'ttag';
import { EASY_SWITCH_EMAIL_PLACEHOLDER } from '@proton/activation/src/constants';
import { IMPORT_ERROR, ImportProvider } from '@proton/activation/src/interface';
import {
selectImapDraftMailImportApiErrorCode,
selectImapDraftMailImportStep,
selectImapDraftProvider,
} from '@proton/activation/src/logic/draft/imapDraft/imapDraft.selector';
import { useEasySwitchSelector } from '@proton/activation/src/logic/store';
import { Button, Input } from '@proton/atoms';
import {
Field,
Form,
Label,
ModalTwo,
ModalTwoContent,
ModalTwoFooter,
ModalTwoHeader,
PasswordInputTwo,
PrimaryButton,
Row,
} from '@proton/components/components';
import ProviderWrapper from '../ProviderWrapper';
import StepFormError from './StepFormError';
import useStepForm from './hooks/useStepForm';
function StepForm() {
const isReconnectStep = useEasySwitchSelector(selectImapDraftMailImportStep) === 'reconnect-form';
const importProvider = useEasySwitchSelector(selectImapDraftProvider);
const apiErrorCode = useEasySwitchSelector(selectImapDraftMailImportApiErrorCode);
const {
blurred,
hasErrors,
errors,
formValues,
setBlurred,
setFormValues,
handleCancel,
handleSubmit,
isConnectingToProvider,
} = useStepForm();
return (
<ModalTwo onClose={handleCancel} size="xlarge" open as={Form} onSubmit={handleSubmit}>
<ModalTwoHeader
title={isReconnectStep ? c('Title').t`Reconnect your account` : c('Title').t`Start a new import`}
/>
<ModalTwoContent>
<ProviderWrapper isConnectingToProvider={isConnectingToProvider}>
<StepFormError isReconnect={isReconnectStep} errorCode={apiErrorCode} />
<div className="mb-8">
{c('Info').t`Enter the credentials of the email account you want to import from.`}
<br />
{c('Info').t`Your login information will not be saved after the import is completed.`}
</div>
<Row>
<Label htmlFor="emailAddress">{c('Label').t`Email`}</Label>
<Field>
<Input
id="emailAddress"
value={formValues.emailAddress}
onChange={({ target }) => {
setFormValues({ ...formValues, emailAddress: target.value });
}}
onBlur={() => setBlurred({ ...blurred, emailAddress: true })}
autoFocus
required
disabled={isReconnectStep}
error={errors?.emailAddress}
placeholder={importProvider ? EASY_SWITCH_EMAIL_PLACEHOLDER[importProvider] : undefined}
data-testid="StepForm:emailInput"
/>
{errors?.emailAddress && <div className="text-sm color-danger">{errors?.emailAddress}</div>}
</Field>
</Row>
<Row>
<Label htmlFor="password">
{importProvider === ImportProvider.YAHOO
? c('Label').t`App password`
: c('Label').t`Password`}
</Label>
<Field>
<PasswordInputTwo
id="password"
value={formValues.password}
onChange={({ target }) => {
setFormValues({ ...formValues, password: target.value });
}}
onBlur={() => setBlurred({ ...blurred, password: true })}
required
error={errors?.password}
data-testid="StepForm:passwordInput"
/>
{errors?.password && <div className="text-sm color-danger">{errors?.password}</div>}
</Field>
</Row>
<Row>
<Label htmlFor="imap">{c('Label').t`Mail Server (IMAP)`}</Label>
<Field>
<Input
id="imap"
placeholder="imap.domain.com"
value={formValues.imap}
onChange={({ target }) => {
setFormValues({ ...formValues, imap: target.value });
}}
onBlur={() => setBlurred({ ...blurred, imap: true })}
required
error={errors?.imap}
data-testid="StepForm:serverInput"
/>
{errors?.imap && <div className="text-sm color-danger">{errors?.imap}</div>}
</Field>
</Row>
<Row>
<Label htmlFor="port">{c('Label').t`Port`}</Label>
<Field>
<Input
id="port"
placeholder="993"
value={formValues.port}
onChange={({ target }) => setFormValues({ ...formValues, port: target.value })}
onBlur={() => setBlurred({ ...blurred, port: true })}
required
error={errors?.port}
data-testid="StepForm:portInput"
/>
{errors?.port && <div className="text-sm color-danger">{errors?.port}</div>}
</Field>
</Row>
{apiErrorCode === IMPORT_ERROR.IMAP_CONNECTION_ERROR && (
<>
<p className="text-bold mb-3">{c('Warning').t`Skip verification?`}</p>
{/* translator: users with self hosted certificate can skip server validation if we're not able to verify the certificate ourselves */}
<p className="my-2">{c('Warning')
.t`We couldn't verify the mail server. If you trust it, you can skip this verification.`}</p>
</>
)}
</ProviderWrapper>
</ModalTwoContent>
<ModalTwoFooter>
<Button shape="outline" onClick={handleCancel} data-testid="StepForm:cancelButton">
{c('Action').t`Cancel`}
</Button>
<PrimaryButton
type="submit"
disabled={hasErrors}
loading={isConnectingToProvider}
data-testid="StepForm:submitButton"
>
{(() => {
if (isReconnectStep) {
return c('Action').t`Reconnect`;
}
if (apiErrorCode === IMPORT_ERROR.IMAP_CONNECTION_ERROR) {
return c('Action').t`Skip verification`;
}
return c('Action').t`Next`;
})()}
</PrimaryButton>
</ModalTwoFooter>
</ModalTwo>
);
}
export default StepForm;
| 4,837
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/StepForm/StepFormError.tsx
|
import { IMPORT_ERROR, ImportProvider } from '@proton/activation/src/interface';
import { selectImapDraftProvider } from '@proton/activation/src/logic/draft/imapDraft/imapDraft.selector';
import { useEasySwitchSelector } from '@proton/activation/src/logic/store';
import StepFormErrorDefault from './StepFormErrorDefault';
import StepFormErrorYahoo from './StepFormErrorYahoo';
interface Props {
isReconnect: boolean;
errorCode?: IMPORT_ERROR;
}
const StepFormError = ({ isReconnect, errorCode }: Props) => {
const provider = useEasySwitchSelector(selectImapDraftProvider);
if (provider === ImportProvider.YAHOO) {
return <StepFormErrorYahoo isReconnect={isReconnect} errorCode={errorCode} />;
}
return <StepFormErrorDefault isReconnect={isReconnect} errorCode={errorCode} />;
};
export default StepFormError;
| 4,838
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/StepForm/StepFormErrorDefault.tsx
|
import { c } from 'ttag';
import { IMPORT_ERROR } from '@proton/activation/src/interface';
import { Href } from '@proton/atoms';
import { Alert } from '@proton/components/components';
import { BRAND_NAME } from '@proton/shared/lib/constants';
import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url';
interface Props {
isReconnect: boolean;
errorCode?: IMPORT_ERROR;
}
const { RATE_LIMIT_EXCEEDED, ACCOUNT_DOES_NOT_EXIST, IMAP_CONNECTION_ERROR, AUTHENTICATION_ERROR } = IMPORT_ERROR;
const StepFormErrorDefault = ({ isReconnect, errorCode }: Props) => {
if (!isReconnect && !errorCode) {
return null;
}
const learnMoreUrl =
errorCode !== RATE_LIMIT_EXCEEDED ? getKnowledgeBaseUrl('/troubleshooting-easy-switch/') : undefined;
return (
<Alert className="mb-4" type="error">
{isReconnect === true && (
<>
<div className="mb-4">
{c('Import error').t`${BRAND_NAME} can't connect to your account. Please make sure that:`}
</div>
<ul className="m-0 pb-4">
<li>{c('Import error').t`IMAP access is enabled in your external account.`}</li>
<li>{c('Import error').t`Your password is correct.`}</li>
</ul>
<div className="mb-4">{c('Import error').t`Use your app password if:`}</div>
<ul className="m-0 pb-4">
<li>{c('Import error').t`2-step verification is enabled in your external account.`}</li>
<li>{c('Import error').t`Your email account requires one to export your data.`}</li>
</ul>
</>
)}
{[IMAP_CONNECTION_ERROR, ACCOUNT_DOES_NOT_EXIST].some((error) => error === errorCode) && (
<>{c('Import error')
.t`${BRAND_NAME} can't connect to your external account. Please make sure that the mail server address and port number are correct.`}</>
)}
{errorCode === AUTHENTICATION_ERROR && (
<>
<div className="mb-4">
{c('Import error')
.t`${BRAND_NAME} can't connect to your external account. Please make sure that:`}
</div>
<ul className="m-0 pb-4">
<li>{c('Import error').t`IMAP access is enabled in your external account.`}</li>
<li>{c('Import error').t`Your email address and password are correct.`}</li>
</ul>
<div className="mb-4">
{c('Import error').t`Use your app password instead of your regular password if:`}
</div>
<ul className="m-0 pb-4">
<li>{c('Import error').t`2-step verification is enabled in your external email account.`}</li>
<li>{c('Import error').t`Your email account requires an app password to export your data.`}</li>
</ul>
</>
)}
{errorCode === RATE_LIMIT_EXCEEDED &&
c('Import error').t`Too many recent requests. Please try again in a few moments.`}
{learnMoreUrl && (
<div>
<Href href={learnMoreUrl}>{c('Link').t`Learn more`}</Href>
</div>
)}
</Alert>
);
};
export default StepFormErrorDefault;
| 4,839
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/StepForm/StepFormErrorYahoo.tsx
|
import { c } from 'ttag';
import { IMPORT_ERROR } from '@proton/activation/src/interface';
import { Href } from '@proton/atoms/Href';
import { Alert } from '@proton/components/components';
import { BRAND_NAME } from '@proton/shared/lib/constants';
import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url';
interface Props {
isReconnect: boolean;
errorCode?: IMPORT_ERROR;
}
const { RATE_LIMIT_EXCEEDED, ACCOUNT_DOES_NOT_EXIST, IMAP_CONNECTION_ERROR, AUTHENTICATION_ERROR } = IMPORT_ERROR;
const StepFormErrorYahoo = ({ isReconnect, errorCode }: Props) => {
if (!isReconnect && !errorCode) {
return null;
}
const boldNot = <strong key="boldNot">{c('Import error emphasis').t`not`}</strong>;
const learnMoreUrl =
errorCode !== RATE_LIMIT_EXCEEDED ? getKnowledgeBaseUrl('/troubleshooting-easy-switch/') : undefined;
return (
<Alert className="mb-4" type="error">
{isReconnect === true && (
<>
<div className="mb-4">
{c('Import error').t`${BRAND_NAME} can't connect to your Yahoo account. Please make sure that:`}
</div>
<ul className="m-0 pb-4">
<li>{c('Import error').t`IMAP access is enabled in your Yahoo account.`}</li>
<li>{
// // translator: the variable here is a HTML tag, here is the complete sentence: "your app password is correct. Do not use your regular password"
c('Import error').jt`Your app password is correct. Do ${boldNot} use your regular password.`
}</li>
</ul>
</>
)}
{[IMAP_CONNECTION_ERROR, ACCOUNT_DOES_NOT_EXIST].some((error) => error === errorCode) && (
<>{c('Import error')
.t`${BRAND_NAME} can't connect to your Yahoo account. Please make sure that the mail server address and port number are correct.`}</>
)}
{errorCode === AUTHENTICATION_ERROR && (
<>
<div className="mb-4" data-testid="StepForm:yahooAuthError">
{c('Import error')
.t`${BRAND_NAME} can't connect to your external account. Please make sure that:`}
</div>
<ul className="m-0 pb-4">
<li>{c('Import error')
.jt`Your email address and app password are correct. Do ${boldNot} use your regular password.`}</li>
<li>{c('Import error').t`IMAP access is enabled in your Yahoo account.`}</li>
</ul>
</>
)}
{errorCode === RATE_LIMIT_EXCEEDED &&
c('Import error').t`Too many recent requests. Please try again in a few moments.`}
{learnMoreUrl && (
<div>
<Href href={learnMoreUrl}>{c('Link').t`Learn more`}</Href>
</div>
)}
</Alert>
);
};
export default StepFormErrorYahoo;
| 4,840
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/StepForm
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/StepForm/hooks/useAuthInfoByEmail.ts
|
import { useEffect } from 'react';
import { getAuthenticationMethod } from '@proton/activation/src/api';
import { ApiImporterAuthInfoResponse } from '@proton/activation/src/api/api.interface';
import { useDebounceInput } from '@proton/components/components';
import { useApi } from '@proton/components/hooks';
import { validateEmailAddress } from '@proton/shared/lib/helpers/email';
/**
* Fetches auth method for a given email address
*/
const useAuthInfoByEmail = (email: string, onInfosLoaded: (result: ApiImporterAuthInfoResponse) => void) => {
const debouncedEmail = useDebounceInput(email, 150);
const api = useApi();
useEffect(() => {
if (!email || !validateEmailAddress(debouncedEmail)) {
return;
}
const abortController = new AbortController();
void api<ApiImporterAuthInfoResponse>({
...getAuthenticationMethod({ Email: email }),
signal: abortController.signal,
}).then((result) => {
onInfosLoaded(result);
});
return () => {
abortController.abort();
};
}, [debouncedEmail]);
};
export default useAuthInfoByEmail;
| 4,841
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/StepForm
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/StepForm/hooks/useStepForm.helpers.test.ts
|
import { IMPORT_ERROR, ImportProvider } from '@proton/activation/src/interface';
import { getDefaultImap, getDefaultPort, validateStepForm } from './useStepForm.helpers';
import { StepFormBlur, StepFormState } from './useStepForm.interface';
describe('useStepForm', () => {
it('Should validate step form without any issue', () => {
const formValue: StepFormState = {
emailAddress: 'testing@proton.ch',
password: 'password',
imap: 'imap.proton.me',
port: '933',
};
const blurred: StepFormBlur = {
emailAddress: false,
password: false,
imap: false,
port: false,
};
const setErrors = jest.fn();
const setHasErrors = jest.fn();
validateStepForm(formValue, blurred, setErrors, setHasErrors);
expect(setErrors).toHaveBeenCalledTimes(1);
expect(setErrors).toHaveBeenCalledWith(undefined);
expect(setHasErrors).toHaveBeenCalledTimes(1);
expect(setHasErrors).toHaveBeenCalledWith(false);
});
it('Should have all possible errors', () => {
const formValue: StepFormState = {
emailAddress: '',
password: '',
imap: '',
port: '',
};
const blurred: StepFormBlur = {
emailAddress: true,
password: true,
imap: true,
port: true,
};
const setErrors = jest.fn();
const setHasErrors = jest.fn();
validateStepForm(formValue, blurred, setErrors, setHasErrors);
expect(setErrors).toHaveBeenCalledTimes(1);
expect(setErrors).toHaveBeenCalledWith({
emailAddress: 'Email address is required',
password: 'Password is required',
imap: 'IMAP server is required',
port: 'Port is required',
});
expect(setHasErrors).toHaveBeenCalledTimes(1);
expect(setHasErrors).toHaveBeenCalledWith(true);
});
it('Should test API code errors', () => {
const formValue: StepFormState = {
emailAddress: 'testing@proton.ch',
password: 'password',
imap: 'imap.proton.me',
port: '933',
};
const blurred: StepFormBlur = {
emailAddress: false,
password: false,
imap: false,
port: false,
};
const setErrors = jest.fn();
const setHasErrors = jest.fn();
validateStepForm(
formValue,
blurred,
setErrors,
setHasErrors,
IMPORT_ERROR.AUTHENTICATION_ERROR,
'api error message'
);
expect(setErrors).toHaveBeenCalledTimes(1);
expect(setErrors).toHaveBeenCalledWith({
emailAddress: 'api error message',
password: 'api error message',
});
validateStepForm(
formValue,
blurred,
setErrors,
setHasErrors,
IMPORT_ERROR.IMAP_CONNECTION_ERROR,
'api error message'
);
expect(setErrors).toHaveBeenCalledTimes(2);
expect(setErrors).toHaveBeenCalledWith({
imap: 'api error message',
port: 'api error message',
});
validateStepForm(
formValue,
blurred,
setErrors,
setHasErrors,
IMPORT_ERROR.ACCOUNT_DOES_NOT_EXIST,
'api error message'
);
expect(setErrors).toHaveBeenCalledTimes(3);
expect(setErrors).toHaveBeenCalledWith({
imap: 'api error message',
port: 'api error message',
});
});
it('Should return default imap and port', () => {
const defaultImap = getDefaultImap();
const defaultPort = getDefaultPort();
expect(defaultImap).toStrictEqual('');
expect(defaultPort).toStrictEqual('');
const googleImap = getDefaultImap(ImportProvider.GOOGLE);
const googlePort = getDefaultPort(ImportProvider.GOOGLE);
expect(googleImap).toStrictEqual('imap.gmail.com');
expect(googlePort).toStrictEqual('993');
const yahooImap = getDefaultImap(ImportProvider.YAHOO);
const yahooPort = getDefaultPort(ImportProvider.YAHOO);
expect(yahooImap).toStrictEqual('export.imap.mail.yahoo.com');
expect(yahooPort).toStrictEqual('993');
const outlookImap = getDefaultImap(ImportProvider.OUTLOOK);
const outlookPort = getDefaultPort(ImportProvider.OUTLOOK);
expect(outlookImap).toStrictEqual('outlook.office365.com');
expect(outlookPort).toStrictEqual('993');
});
});
| 4,842
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/StepForm
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/StepForm/hooks/useStepForm.helpers.ts
|
import { c } from 'ttag';
import { IMPORT_ERROR, ImportProvider } from '@proton/activation/src/interface';
import { StepFormBlur, StepFormErrors, StepFormState } from './useStepForm.interface';
const IMAPS = {
[ImportProvider.GOOGLE]: 'imap.gmail.com',
[ImportProvider.YAHOO]: 'export.imap.mail.yahoo.com',
[ImportProvider.OUTLOOK]: 'outlook.office365.com',
[ImportProvider.DEFAULT]: '',
};
const PORTS = {
[ImportProvider.GOOGLE]: '993',
[ImportProvider.YAHOO]: '993',
[ImportProvider.OUTLOOK]: '993',
[ImportProvider.DEFAULT]: '',
};
export const getDefaultImap = (provider?: ImportProvider): string =>
provider ? IMAPS[provider] : IMAPS[ImportProvider.DEFAULT];
export const getDefaultPort = (provider?: ImportProvider): string =>
provider ? PORTS[provider] : PORTS[ImportProvider.DEFAULT];
export const validateStepForm = (
formValues: StepFormState,
blurred: StepFormBlur,
setErrors: (nextErrors: StepFormErrors | undefined) => void,
setHasErrors: (hasErrors: boolean) => void,
apiErrorCode?: number,
apiErrorMessage?: string
) => {
const nextErrors: StepFormErrors = {};
// Check if there are any errors in form
if (Object.keys(formValues).some((key) => !formValues[key as keyof StepFormState])) {
setHasErrors(true);
} else {
setHasErrors(false);
}
// Check if we set some error messages
if (blurred.emailAddress && !formValues.emailAddress) {
nextErrors.emailAddress = c('Error').t`Email address is required`;
}
if (blurred.password && !formValues.password) {
nextErrors.password = c('Error').t`Password is required`;
}
if (blurred.imap && !formValues.imap) {
nextErrors.imap = c('Error').t`IMAP server is required`;
}
if (blurred.port && !formValues.port) {
nextErrors.port = c('Error').t`Port is required`;
}
// Override with api errors
if (apiErrorCode === IMPORT_ERROR.AUTHENTICATION_ERROR) {
nextErrors.emailAddress = apiErrorMessage;
nextErrors.password = apiErrorMessage;
}
if (IMPORT_ERROR.ACCOUNT_DOES_NOT_EXIST === apiErrorCode || IMPORT_ERROR.IMAP_CONNECTION_ERROR === apiErrorCode) {
nextErrors.imap = apiErrorMessage;
nextErrors.port = apiErrorMessage;
}
setErrors(Object.keys(nextErrors).length ? nextErrors : undefined);
};
| 4,843
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/StepForm
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/StepForm/hooks/useStepForm.interface.ts
|
export type StepFormState = {
emailAddress: string;
password: string;
imap: string;
port: string;
};
export type StepFormErrors = Partial<Record<keyof StepFormState, string>>;
export type StepFormBlur = Partial<Record<keyof StepFormState, boolean>>;
| 4,844
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/StepForm
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/StepForm/hooks/useStepForm.ts
|
import { useEffect, useState } from 'react';
import { updateImport } from '@proton/activation/src/api';
import { AuthenticationMethod, IMPORT_ERROR, ImportType } from '@proton/activation/src/interface';
import { selectImapDraftProduct } from '@proton/activation/src/logic/draft/draft.selector';
import {
displayConfirmLeaveModal,
resetImapDraft,
resumeImapImport,
submitImapMailCredentials,
} from '@proton/activation/src/logic/draft/imapDraft/imapDraft.actions';
import {
selectImapDraftMailImport,
selectImapDraftMailImportApiError,
selectImapDraftProvider,
} from '@proton/activation/src/logic/draft/imapDraft/imapDraft.selector';
import { useEasySwitchDispatch, useEasySwitchSelector } from '@proton/activation/src/logic/store';
import { useApi } from '@proton/components/index';
import throttle from '@proton/utils/throttle';
import useAuthInfoByEmail from './useAuthInfoByEmail';
import { getDefaultImap, getDefaultPort, validateStepForm } from './useStepForm.helpers';
import { StepFormBlur, StepFormErrors, StepFormState } from './useStepForm.interface';
const throttleValidateForm = throttle(validateStepForm, 150);
const useStepForm = () => {
const api = useApi();
const dispatch = useEasySwitchDispatch();
const product = useEasySwitchSelector(selectImapDraftProduct);
const mailImport = useEasySwitchSelector(selectImapDraftMailImport);
const apiError = useEasySwitchSelector(selectImapDraftMailImportApiError);
const importProvider = useEasySwitchSelector(selectImapDraftProvider);
const [formValues, setFormValues] = useState<StepFormState>({
emailAddress: mailImport?.email || '',
password: mailImport?.password || '',
imap: mailImport?.domain || getDefaultImap(importProvider),
port: mailImport?.port || getDefaultPort(importProvider),
});
/** Tells if form has at least one error */
const [hasErrors, setHasErrors] = useState<boolean>(false);
/** Contains the errors messages for each field input */
const [errors, setErrors] = useState<StepFormErrors>();
/** True if field input has triggered a blur event */
const [blurred, setBlurred] = useState<StepFormBlur>({
emailAddress: false,
imap: false,
password: false,
port: false,
});
const handleSubmit = async () => {
if (hasErrors) {
return;
}
const { emailAddress, imap, port, password } = formValues;
const allowSelfSigned = apiError?.code === IMPORT_ERROR.IMAP_CONNECTION_ERROR;
if (mailImport?.step === 'reconnect-form') {
if (!mailImport.apiImporterID || !product) {
throw new Error('Missing importerID or product');
}
await api(
updateImport(mailImport.apiImporterID, {
[ImportType.MAIL]: {
Account: emailAddress,
ImapHost: imap,
ImapPort: parseInt(port, 10),
Code: password,
Sasl: AuthenticationMethod.PLAIN,
AllowSelfSigned: allowSelfSigned ? 1 : 0,
},
})
);
return dispatch(
resumeImapImport({
importID: mailImport.apiImporterID,
product,
})
);
} else {
return dispatch(
submitImapMailCredentials({
email: emailAddress,
password: password,
domain: imap,
port,
allowSelfSigned,
})
);
}
};
const handleCancel = () => {
const shouldDisplayConfirmModal = mailImport?.step !== 'reconnect-form' && formValues.emailAddress;
if (shouldDisplayConfirmModal) {
dispatch(displayConfirmLeaveModal(true));
} else {
dispatch(resetImapDraft());
}
};
useAuthInfoByEmail(formValues.emailAddress, (result) => {
if (result.Authentication) {
setFormValues((formValues) => ({
...formValues,
imap: formValues.imap ? formValues.imap : result.Authentication.ImapHost || '',
port: formValues.port ? formValues.port : `${result.Authentication.ImapPort}` || '',
}));
}
});
useEffect(() => {
throttleValidateForm(formValues, blurred, setErrors, setHasErrors, apiError?.code, apiError?.message);
}, [formValues, blurred, apiError?.code]);
return {
isConnectingToProvider: !!mailImport?.loading,
formValues,
setFormValues,
hasErrors,
errors,
blurred,
setBlurred,
handleSubmit,
handleCancel,
};
};
export default useStepForm;
| 4,845
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/StepImporting/StepImporting.test.tsx
|
import { fireEvent, screen } from '@testing-library/dom';
import { easySwitchRender } from '@proton/activation/src/tests/render';
import StepImporting from './StepImporting';
describe('Step importing basic rendering testing', () => {
it('Should correctly render the step importing', () => {
easySwitchRender(<StepImporting />);
const closeButton = screen.getByTestId('StepImport:closeButton');
fireEvent.click(closeButton);
});
it('Should redirect user when not in easy switch', () => {
easySwitchRender(<StepImporting />);
const redirectButton = screen.getByTestId('StepImport:redirectButton');
fireEvent.click(redirectButton);
});
});
| 4,846
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/StepImporting/StepImporting.tsx
|
import { useLocation } from 'react-router-dom';
import { c } from 'ttag';
import { IA_PATHNAME_REGEX } from '@proton/activation/src/constants';
import { resetImapDraft } from '@proton/activation/src/logic/draft/imapDraft/imapDraft.actions';
import { selectImapDraftMailImport } from '@proton/activation/src/logic/draft/imapDraft/imapDraft.selector';
import { useEasySwitchDispatch, useEasySwitchSelector } from '@proton/activation/src/logic/store';
import { Button } from '@proton/atoms/Button';
import {
ModalTwo,
ModalTwoContent,
ModalTwoFooter,
ModalTwoHeader,
PrimaryButton,
useSettingsLink,
} from '@proton/components/components';
import StepImportingContent from './StepImportingContent';
const StepImporting = () => {
const dispatch = useEasySwitchDispatch();
const location = useLocation();
const isCurrentLocationImportPage = IA_PATHNAME_REGEX.test(location.pathname);
const mailImport = useEasySwitchSelector(selectImapDraftMailImport);
const settingsLink = useSettingsLink();
const handleClose = () => {
dispatch(resetImapDraft());
};
return (
<ModalTwo onClose={handleClose} size="xlarge" open>
<ModalTwoHeader />
<ModalTwoContent>
<StepImportingContent
importedEmailAddress={mailImport?.email || ''}
isCurrentLocationImportPage={isCurrentLocationImportPage}
onClose={() => {
dispatch(resetImapDraft());
}}
toEmail={mailImport?.fields?.importAddress.Email || ''}
/>
</ModalTwoContent>
<ModalTwoFooter className="flex-justify-end">
{!isCurrentLocationImportPage ? (
<PrimaryButton
onClick={() => {
dispatch(resetImapDraft());
settingsLink(`/easy-switch`);
}}
data-testid="StepImport:redirectButton"
>
{c('Action').t`Check import progress`}
</PrimaryButton>
) : null}
<Button shape="outline" onClick={handleClose} data-testid="StepImport:closeButton">
{c('Action').t`Close`}
</Button>
</ModalTwoFooter>
</ModalTwo>
);
};
export default StepImporting;
| 4,847
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/StepImporting/StepImportingContent.tsx
|
import { c } from 'ttag';
import { SettingsLink } from '@proton/components/components';
import importStartedSvg from '@proton/styles/assets/img/onboarding/import-assistant.svg';
interface Props {
importedEmailAddress: string;
isCurrentLocationImportPage: boolean;
onClose: () => void;
toEmail: string;
}
const StepImportingContent = ({ importedEmailAddress, toEmail, onClose, isCurrentLocationImportPage }: Props) => {
const importProgressLink = (
<SettingsLink key="link" path="/easy-switch" onClick={() => onClose()}>{c('Info').t`here`}</SettingsLink>
);
return (
<div className="text-center mb-8">
<img src={importStartedSvg} alt="" className="max-w-4/5" />
<h3>{c('Info').t`Import in progress`}</h3>
<div className="mb-4">{c('Info').t`Importing your data from ${importedEmailAddress} to ${toEmail}.`}</div>
<div>{c('Info').t`We'll notify you when the import is done.`}</div>
<div className="mb-4">{c('Info').t`Large imports can take several days.`}</div>
{!isCurrentLocationImportPage && (
<div className="mb-4">{c('Info').jt`You can check the progress ${importProgressLink}.`}</div>
)}
<div>{c('Info').t`Close this screen to exit.`}</div>
</div>
);
};
export default StepImportingContent;
| 4,848
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/StepPrepareImap/StepPrepareImap.helpers.test.ts
|
import { differenceInMonths, fromUnixTime } from 'date-fns';
import { ApiMailImporterFolder } from '@proton/activation/src/api/api.interface';
import MailImportFoldersParser from '@proton/activation/src/helpers/MailImportFoldersParser/MailImportFoldersParser';
import { MailImportDestinationFolder, MailImportMapping, TIME_PERIOD } from '@proton/activation/src/interface';
import { standardFolderResponse } from '@proton/activation/src/tests/data/gmail.formattedResponse';
import { gmailImapResponse } from '@proton/activation/src/tests/data/gmail.imap.formattedResponse';
import gmailImapModalLabels from '@proton/activation/src/tests/data/gmail.imap.providerFolders';
import labels from '@proton/activation/src/tests/data/gmail.providerFolders';
import { ADDRESS_STATUS, ADDRESS_TYPE } from '@proton/shared/lib/constants';
import { Address } from '@proton/shared/lib/interfaces';
import { formatPrepareStepPayload } from './StepPrepareImap.helpers';
import { StepPrepareData } from './useStepPrepareImap';
// used in MailFoldersMapping.getRandomLabelColor.
jest.mock('@proton/utils/randomIntFromInterval', () => () => 0);
const address: Address = {
DisplayName: 'Testing',
DomainID: 'proton.ch',
Email: 'testing@proton.ch',
HasKeys: 1,
ID: 'ID',
Keys: [],
SignedKeyList: null,
Order: 1,
Priority: 1,
Receive: 1,
Send: 1,
Signature: 'Testing signature',
Status: ADDRESS_STATUS.STATUS_ENABLED,
Type: ADDRESS_TYPE.TYPE_ORIGINAL,
ProtonMX: true,
ConfirmationState: 1,
CatchAll: false,
};
const providerLabels = labels.map((label) => {
return { ...label, Size: 1 } as ApiMailImporterFolder;
});
const correctData = {
email: 'string',
importerID: 'importerID',
password: 'password',
};
const updatedFields = {
updatedLabel: true,
updatedPeriod: true,
updatedMapping: true,
};
const isLabelMapping = true;
function getBaseFields(labels?: ApiMailImporterFolder[]) {
return {
mapping: new MailImportFoldersParser(labels ?? providerLabels, isLabelMapping).folders,
importLabel: { Color: '#fff', Name: 'label', Type: 1 },
importPeriod: TIME_PERIOD.BIG_BANG,
importAddress: address,
importCategoriesDestination: MailImportDestinationFolder.INBOX,
};
}
describe('Step prepare helpers tests', () => {
describe('formatPrepareStepPayload', () => {
it('Should return a standard payload (All time)', () => {
const fields: StepPrepareData['fields'] = getBaseFields();
const res = formatPrepareStepPayload({ isLabelMapping, data: correctData, fields, updatedFields });
expect(res).toEqual(standardFolderResponse);
});
it('Should return a standard payload (last year)', () => {
const fieldsOneYear: StepPrepareData['fields'] = {
...getBaseFields(),
importPeriod: TIME_PERIOD.LAST_YEAR,
};
const res = formatPrepareStepPayload({
isLabelMapping,
data: correctData,
fields: fieldsOneYear,
updatedFields,
});
const { StartTime } = res.Mail;
let diff = -1;
if (StartTime instanceof Date) {
diff = differenceInMonths(new Date(), StartTime);
} else {
const start = fromUnixTime(StartTime!);
diff = differenceInMonths(new Date(), start);
}
expect(diff).toBe(12);
});
it('Should return a standard payload (3 last months)', () => {
const fieldsThreeMonts: StepPrepareData['fields'] = {
...getBaseFields(),
importPeriod: TIME_PERIOD.LAST_3_MONTHS,
};
const res = formatPrepareStepPayload({
isLabelMapping,
data: correctData,
fields: fieldsThreeMonts,
updatedFields,
});
const { StartTime } = res.Mail;
let diff = -1;
if (StartTime instanceof Date) {
diff = differenceInMonths(new Date(), StartTime);
} else {
const start = fromUnixTime(StartTime!);
diff = differenceInMonths(new Date(), start);
}
expect(diff).toBe(3);
});
it('Should return a standard payload (last month)', () => {
const fieldsOneMonth: StepPrepareData['fields'] = {
...getBaseFields(),
importPeriod: TIME_PERIOD.LAST_MONTH,
};
const res = formatPrepareStepPayload({
isLabelMapping,
data: correctData,
fields: fieldsOneMonth,
updatedFields,
});
const { StartTime } = res.Mail;
let diff = -1;
if (StartTime instanceof Date) {
diff = differenceInMonths(new Date(), StartTime);
} else {
const start = fromUnixTime(StartTime!);
diff = differenceInMonths(new Date(), start);
}
expect(diff).toBe(1);
});
it('Should throw an error if importer ID is undefined ', () => {
const fields: StepPrepareData['fields'] = getBaseFields();
const faultyData = {
email: 'string',
providerFolders: providerLabels,
importerID: undefined,
password: 'password',
};
expect(() =>
formatPrepareStepPayload({ isLabelMapping, data: faultyData, fields, updatedFields })
).toThrowError('Importer ID should be defined');
});
it('Should not submit unchecked folders', () => {
const fields: StepPrepareData['fields'] = {
...getBaseFields(),
mapping: new MailImportFoldersParser(providerLabels, isLabelMapping).folders.map((folder) => ({
...folder,
checked: false,
})),
};
expect(
formatPrepareStepPayload({ isLabelMapping, data: correctData, fields, updatedFields }).Mail.Mapping
.length
).toBe(0);
});
it('Should send correctly formatted folders depth into payload', () => {
const isLabelMapping = false;
const fields: StepPrepareData['fields'] = {
...getBaseFields(),
mapping: new MailImportFoldersParser(
['dude 1', 'dude 1/dude 2', 'dude 1/dude 2/dude 3', 'dude 1/dude 2/dude 3/dude 4'].map(
(path) =>
({
Source: path,
Separator: '/',
}) as ApiMailImporterFolder
),
isLabelMapping
).folders,
};
expect(
formatPrepareStepPayload({ isLabelMapping, data: correctData, fields, updatedFields }).Mail.Mapping.map(
(item) => item.Destinations.FolderPath
)
).toEqual(['dude 1', 'dude 1/dude 2', 'dude 1/dude 2/dude 3', 'dude 1/dude 2/dude 3\\/dude 4']);
});
it('Should return correct payload when using Gmail account on IMAP modal', () => {
const gmailImapLabels = gmailImapModalLabels.map((label) => {
return { ...label, Size: 1 } as ApiMailImporterFolder;
});
const fields: StepPrepareData['fields'] = getBaseFields(gmailImapLabels);
const res = formatPrepareStepPayload({
isLabelMapping,
data: correctData,
fields,
updatedFields,
});
expect(res).toEqual(gmailImapResponse);
});
describe('Should add `folderPath` and `label` on specific conditions', () => {
const labels = getBaseFields(
['Inbox', 'dude 1', 'dude 1/dude 2'].map(
(path) =>
({
Source: path,
Separator: '/',
...(path === 'Inbox' ? { DestinationFolder: 'Inbox' } : {}),
}) as ApiMailImporterFolder
)
);
const res = formatPrepareStepPayload({
isLabelMapping,
data: correctData,
fields: labels,
updatedFields,
});
it('should contain folderPath if destination folder', () => {
const destinationFolder = res.Mail.Mapping.find(
(label) => label.Source === 'Inbox'
) as MailImportMapping;
expect(destinationFolder.Source).toEqual('Inbox');
expect('Labels' in destinationFolder.Destinations).toBe(false);
expect('FolderPath' in destinationFolder.Destinations).toBe(true);
expect(destinationFolder.Destinations.FolderPath).toBe('Inbox');
});
it('should contain Label if label', () => {
const parentFolder = res.Mail.Mapping.find((label) => label.Source === 'dude 1') as MailImportMapping;
expect(parentFolder.Source).toEqual('dude 1');
expect('Labels' in parentFolder.Destinations).toBe(true);
expect('FolderPath' in parentFolder.Destinations).toBe(false);
expect(parentFolder.Destinations.Labels?.[0].Name).toBe('dude 1');
});
});
});
});
| 4,849
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/StepPrepareImap/StepPrepareImap.helpers.tsx
|
import { getUnixTime, subMonths, subYears } from 'date-fns';
import { ApiStartImportParams } from '@proton/activation/src/api/api.interface';
import { GMAIL_CATEGORIES, MAX_FOLDERS_DEPTH } from '@proton/activation/src/constants';
import {
CustomFieldsBitmap,
ImportType,
MailImportGmailCategories,
MailImportMapping,
TIME_PERIOD,
} from '@proton/activation/src/interface';
import { RequireSome } from '@proton/shared/lib/interfaces';
import { StepPrepareData } from './useStepPrepareImap';
const generateCustomFieldBitmap = ({
updatedMapping,
updatedLabel,
updatedPeriod,
}: Record<'updatedMapping' | 'updatedLabel' | 'updatedPeriod', boolean>) => {
let CustomFields = 0;
if (updatedMapping) {
CustomFields += CustomFieldsBitmap.Mapping;
}
if (updatedLabel) {
CustomFields += CustomFieldsBitmap.Label;
}
if (updatedPeriod) {
CustomFields += CustomFieldsBitmap.Period;
}
return CustomFields;
};
const getStartTimeFromTimePeriod = (importPeriod: TIME_PERIOD): number | undefined => {
const now = new Date();
let result: Date | undefined;
switch (importPeriod) {
case TIME_PERIOD.BIG_BANG:
result = undefined;
break;
case TIME_PERIOD.LAST_YEAR:
result = subYears(now, 1);
break;
case TIME_PERIOD.LAST_3_MONTHS:
result = subMonths(now, 3);
break;
case TIME_PERIOD.LAST_MONTH:
result = subMonths(now, 1);
break;
default:
throw new Error('importPeriod should be specified');
}
return result ? getUnixTime(result) : undefined;
};
interface FormatProps {
isLabelMapping: boolean;
data: { email: string; importerID?: string; password?: string };
fields: StepPrepareData['fields'];
/** Fields used to generate a BITMAP for API */
updatedFields: Record<'updatedMapping' | 'updatedLabel' | 'updatedPeriod', boolean>;
}
export const formatPrepareStepPayload = ({
isLabelMapping,
data,
fields,
updatedFields,
}: FormatProps): RequireSome<ApiStartImportParams, ImportType.MAIL> => {
if (!data.importerID) {
throw new Error('Importer ID should be defined');
}
const mapping = fields.mapping
.filter((field) => field.checked)
.map((folder) => {
const Destinations: MailImportMapping['Destinations'] = (() => {
let result = '';
if (folder.category) {
result = fields.importCategoriesDestination;
} else if (folder.systemFolder) {
result = folder.systemFolder;
} else if (folder.protonPath.length < MAX_FOLDERS_DEPTH || folder.separator !== '/') {
result = folder.protonPath.join(folder.separator);
}
// Here separator is '/'
else {
const itemsWithoutLast = folder.protonPath.slice(0, -1);
const escapedLastItem = (folder.protonPath.slice(-1).pop() || '').split('/').join('\\/');
result = [...itemsWithoutLast, escapedLastItem].join('/');
}
return { FolderPath: result };
})();
if (isLabelMapping && !folder.category && !folder.systemFolder) {
Destinations.Labels = [
{
Name: folder.protonPath.join('-'),
Color: folder.color,
},
];
// We delete the FolderPath if we're in folder mapping to avoid creating folders
delete Destinations.FolderPath;
}
if (GMAIL_CATEGORIES.includes(folder.id as MailImportGmailCategories)) {
Destinations.Category = folder.category;
}
return {
Source: folder.id,
Destinations,
checked: true,
};
});
return {
ImporterID: data.importerID,
[ImportType.MAIL]: {
AddressID: fields.importAddress.ID,
StartTime: getStartTimeFromTimePeriod(fields.importPeriod),
Mapping: mapping,
Code: data.password,
CustomFields: generateCustomFieldBitmap(updatedFields),
ImportLabel: fields.importLabel,
},
};
};
| 4,850
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/StepPrepareImap/StepPrepareImap.test.tsx
|
import { fireEvent, screen } from '@testing-library/dom';
import useAvailableAddresses from '@proton/activation/src/hooks/useAvailableAddresses';
import { MailImportState } from '@proton/activation/src/logic/draft/imapDraft/imapDraft.interface';
import { generateMockAddressArray } from '@proton/activation/src/tests/data/addresses';
import { easySwitchRender } from '@proton/activation/src/tests/render';
import StepPrepare from './StepPrepareImap';
const data: MailImportState = {
step: 'prepare-import',
loading: false,
domain: 'imap.proton.ch',
email: 'testing@proton.ch',
password: 'password',
port: '993',
};
jest.mock('react-redux', () => ({
...jest.requireActual('react-redux'),
useSelector: jest.fn().mockReturnValue({ mailImport: data }),
}));
const addresses = generateMockAddressArray(3, true);
jest.mock('@proton/activation/src/hooks/useAvailableAddresses');
const mockUseAvailableAddresses = useAvailableAddresses as jest.MockedFunction<any>;
describe('Step prepare basic rendering testing', () => {
it('Should correctly render the step prepare', () => {
mockUseAvailableAddresses.mockReturnValue({
availableAddresses: addresses,
loading: false,
defaultAddress: addresses[0],
});
easySwitchRender(<StepPrepare />);
const customizeButton = screen.getByTestId('StepPrepare:customizeButton');
fireEvent.click(customizeButton);
screen.getByTestId('CustomizeModal:modalCancel');
});
});
| 4,851
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/StepPrepareImap/StepPrepareImap.tsx
|
import { c } from 'ttag';
import { MailImportPayloadError } from '@proton/activation/src/interface';
import { Button } from '@proton/atoms/Button';
import {
Form,
ModalTwo,
ModalTwoContent,
ModalTwoFooter,
ModalTwoHeader,
PrimaryButton,
useModalState,
} from '@proton/components/components';
import { useUser } from '@proton/components/hooks';
import CustomizeMailImportModal from '../../../CustomizeMailImportModal/CustomizeMailImportModal';
import ProviderWrapper from '../ProviderWrapper';
import StepPrepareContent from './StepPrepareImapContent';
import StepPrepareCustomButton from './StepPrepareImapCustomButton';
import StepPrepareError from './StepPrepareImapError';
import StepPrepareHeader from './StepPrepareImapHeader';
import useStepPrepare from './useStepPrepareImap';
const { MAX_FOLDERS_LIMIT_REACHED, FOLDER_NAMES_TOO_LONG, UNAVAILABLE_NAMES, RESERVED_NAMES, LABEL_NAMES_TOO_LONG } =
MailImportPayloadError;
const StepPrepare = () => {
const [user] = useUser();
const [displayCustomizeModalProps, handleDisplayCustomizeModal, renderCustomizeModal] = useModalState();
const {
email,
fields,
isLabelMapping,
selectedFolders,
errors,
hasErrors,
hasUpdatedField,
handleReset,
handleSubmit,
handleCancel,
handleSubmitCustomizeModal,
isConnectingToProvider,
importSize,
hasCategories,
} = useStepPrepare({ user, handleCloseCustomizeModal: () => handleDisplayCustomizeModal(false) });
const { importLabel, importPeriod, importAddress } = fields;
return (
<ModalTwo onClose={handleCancel} size="xlarge" open as={Form} onSubmit={handleSubmit}>
<ModalTwoHeader title={c('Title').t`Start import process`} />
<ModalTwoContent>
<ProviderWrapper isConnectingToProvider={isConnectingToProvider}>
<StepPrepareError
isLabelMapping={isLabelMapping}
errors={errors}
// TODO: Check why user.MaxSpace * 2
showSizeWarning={importSize + user.UsedSpace >= user.MaxSpace * 2}
/>
<StepPrepareHeader fromEmail={email} toEmail={importAddress?.Email || ''} />
<div className="pb-4 mb-4 border-bottom">
<StepPrepareContent
isLabelMapping={isLabelMapping}
selectedPeriod={importPeriod}
importLabel={importLabel}
showMaxFoldersError={errors.includes(MAX_FOLDERS_LIMIT_REACHED)}
providerFoldersCount={Object.keys(fields.mapping).length}
selectedFoldersCount={selectedFolders.length}
/>
<StepPrepareCustomButton
hasError={errors.some((error) =>
[
FOLDER_NAMES_TOO_LONG,
LABEL_NAMES_TOO_LONG,
UNAVAILABLE_NAMES,
RESERVED_NAMES,
].includes(error)
)}
handleClickCustomize={() => handleDisplayCustomizeModal(true)}
handleReset={handleReset}
isCustom={hasUpdatedField}
isLabelMapping={isLabelMapping}
/>
{renderCustomizeModal && (
<CustomizeMailImportModal
displayCategories={hasCategories}
fields={fields}
foldersOpened={hasErrors}
importedEmail={email}
isLabelMapping={isLabelMapping}
modalProps={displayCustomizeModalProps}
onSubmit={handleSubmitCustomizeModal}
/>
)}
</div>
</ProviderWrapper>
</ModalTwoContent>
<ModalTwoFooter>
<Button shape="outline" onClick={handleCancel}>
{c('Action').t`Cancel`}
</Button>
<PrimaryButton type="submit" disabled={hasErrors} loading={isConnectingToProvider}>{c('Action')
.t`Start import`}</PrimaryButton>
</ModalTwoFooter>
</ModalTwo>
);
};
export default StepPrepare;
| 4,852
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/StepPrepareImap/StepPrepareImapContent.tsx
|
import React from 'react';
import { c } from 'ttag';
import { getTimeUnitLabels } from '@proton/activation/src/constants';
import { EasyTrans } from '@proton/activation/src/helpers/easyTrans';
import { TIME_PERIOD } from '@proton/activation/src/interface';
import { Icon, LabelStack, Tooltip } from '@proton/components/components';
import { Label } from '@proton/shared/lib/interfaces';
interface Props {
selectedPeriod: TIME_PERIOD;
importLabel?: Pick<Label, 'Name' | 'Color' | 'Type'>;
isLabelMapping: boolean;
showMaxFoldersError: boolean;
providerFoldersCount: number;
selectedFoldersCount: number;
}
const StepPrepareContent = ({
selectedPeriod,
importLabel,
isLabelMapping,
showMaxFoldersError,
providerFoldersCount,
selectedFoldersCount,
}: Props) => {
const timeUnitLabels = getTimeUnitLabels();
const trans = EasyTrans.get(isLabelMapping);
const providerFoldersNum = providerFoldersCount;
const providerFoldersNumLocalized = providerFoldersNum.toLocaleString();
const selectedFoldersCountLocalized = selectedFoldersCount.toLocaleString();
return (
<>
<div className="mb-4 flex flex-align-items-center">
<Icon className="mr-2" name="inbox" />
{c('Info').t`Import mailbox`}
</div>
<div className="mb-4 ml-4 flex flex-align-items-center">
<Icon className="mr-2" name="clock" />
{c('Label').t`Import interval`}
{`: `}
<strong className="ml-2">{timeUnitLabels[selectedPeriod]}</strong>
</div>
<div className="mb-4 ml-4 flex flex-align-items-center flex-nowrap">
<Icon className="flex-item-noshrink mr-2" name="tag" />
<span className="flex-item-noshrink">{c('Info').t`Label all imported messages as`}</span>
{importLabel && (
<span className="ml-2">
<LabelStack
labels={[
{
name: importLabel.Name,
color: importLabel.Color,
title: importLabel.Name,
},
]}
className="max-w-full"
/>
</span>
)}
</div>
<div className="mb-4 ml-4 flex flex-align-items-center">
<Icon className="mr-2" name={isLabelMapping ? 'tags' : 'folders'} />
{trans.foundCount(providerFoldersNumLocalized, providerFoldersNum)}
{showMaxFoldersError && (
<Tooltip title={trans.errorMaxItems()} originalPlacement="right">
<Icon className="ml-2 color-danger" name="exclamation-circle-filled" size={18} />
</Tooltip>
)}
</div>
{selectedFoldersCount !== providerFoldersNum && (
<div className="mb-4 ml-8 flex flex-align-items-center">
<strong>
<Icon className="mr-2" name={isLabelMapping ? 'tags' : 'folders'} />
{trans.selectedCount(selectedFoldersCountLocalized, selectedFoldersCount)}
</strong>
</div>
)}
</>
);
};
export default StepPrepareContent;
| 4,853
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/StepPrepareImap/StepPrepareImapCustomButton.tsx
|
import React from 'react';
import { c } from 'ttag';
import { EasyTrans } from '@proton/activation/src/helpers/easyTrans';
import { Button } from '@proton/atoms/Button';
import { Icon, InlineLinkButton, Tooltip } from '@proton/components/components';
interface Props {
isLabelMapping: boolean;
handleClickCustomize: () => void;
handleReset: () => void;
hasError: boolean;
isCustom: boolean;
}
const StepPrepareCustomButton = ({ isLabelMapping, handleClickCustomize, handleReset, hasError, isCustom }: Props) => {
return (
<div className="mt-2 flex flex-align-items-center">
<Button shape="outline" onClick={handleClickCustomize} data-testid="StepPrepare:customizeButton">
{c('Action').t`Customize import`}
</Button>
{hasError && (
<Tooltip title={EasyTrans.get(isLabelMapping).editName()} originalPlacement="right">
<Icon name="exclamation-circle-filled" size={20} className="ml-2 color-danger" />
</Tooltip>
)}
{isCustom && (
<InlineLinkButton className="ml-4" onClick={handleReset}>
{c('Action').t`Reset to default`}
</InlineLinkButton>
)}
</div>
);
};
export default StepPrepareCustomButton;
| 4,854
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/StepPrepareImap/StepPrepareImapError.tsx
|
import { c } from 'ttag';
import { EasyTrans } from '@proton/activation/src/helpers/easyTrans';
import { MailImportPayloadError } from '@proton/activation/src/interface';
import { Alert } from '@proton/components/components';
import { BRAND_NAME } from '@proton/shared/lib/constants';
interface Props {
isLabelMapping: boolean;
errors: MailImportPayloadError[];
showSizeWarning: boolean;
}
const { FOLDER_NAMES_TOO_LONG, LABEL_NAMES_TOO_LONG, MAX_FOLDERS_LIMIT_REACHED, RESERVED_NAMES, UNAVAILABLE_NAMES } =
MailImportPayloadError;
const StepPrepareError = ({ isLabelMapping, errors, showSizeWarning }: Props) => {
const trans = EasyTrans.get(isLabelMapping);
return (
<>
{showSizeWarning && (
<Alert className="my-4" type="warning">
<div className="mb-4">
{c('Warning')
.t`This import may exceed the storage capacity currently available in your ${BRAND_NAME} account. Please consider customizing your import.`}
</div>
</Alert>
)}
{errors.includes(MAX_FOLDERS_LIMIT_REACHED) && (
<Alert className="my-4" type="error">
{c('Error')
.t`There are too many folders in your external account. Please customize the import to delete some folders.`}
</Alert>
)}
{(errors.includes(FOLDER_NAMES_TOO_LONG) || errors.includes(LABEL_NAMES_TOO_LONG)) && (
<Alert className="my-4" type="error">
{trans.errorItemsLimit()}
</Alert>
)}
{errors.includes(UNAVAILABLE_NAMES) && (
<Alert className="my-4" type="error">
{trans.errorUnavailableName()}
</Alert>
)}
{errors.includes(RESERVED_NAMES) && (
<Alert className="my-4" type="error">
{trans.errorReservedName()}
</Alert>
)}
</>
);
};
export default StepPrepareError;
| 4,855
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/StepPrepareImap/StepPrepareImapHeader.tsx
|
import { c } from 'ttag';
import { BRAND_NAME } from '@proton/shared/lib/constants';
interface Props {
fromEmail: string;
toEmail: string;
}
const StepPrepareHeader = ({ fromEmail, toEmail }: Props) => {
const from = <strong key="importedEmailAddress">{fromEmail}</strong>;
const to = <strong key="PMEmailAddress">{toEmail}</strong>;
return (
<>
<div>
{c('Warning')
.t`${BRAND_NAME} will transfer as much data as possible, starting with your most recent messages.`}
</div>
<div className="flex pb-4 mb-4 border-bottom">
<div className="flex-item-fluid text-ellipsis mr-2">{c('Label').jt`From: ${from}`}</div>
<div className="flex-item-fluid text-ellipsis ml-2 text-right">{c('Label').jt`To: ${to}`}</div>
</div>
</>
);
};
export default StepPrepareHeader;
| 4,856
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/StepPrepareImap/useStepPrepareImap.helpers.ts
|
import { format } from 'date-fns';
import { LabelModel } from '@proton/components/containers/labels/modals/EditLabelModal';
import { getRandomAccentColor } from '@proton/shared/lib/colors';
import { LABEL_TYPE } from '@proton/shared/lib/constants';
/**
* Returns the label under which every mails will be imported
*/
const getDefaultLabel = (email: string): LabelModel => ({
Name: `${email.split('@')[1]} ${format(new Date(), 'dd-MM-yyyy HH:mm')}`,
Color: getRandomAccentColor(),
Type: LABEL_TYPE.MESSAGE_LABEL,
});
export default getDefaultLabel;
| 4,857
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapMailModal/StepPrepareImap/useStepPrepareImap.ts
|
import { useMemo, useState } from 'react';
import cloneDeep from 'lodash/cloneDeep';
import { GMAIL_CATEGORIES, IMAPS } from '@proton/activation/src/constants';
import { MailImportFolder } from '@proton/activation/src/helpers/MailImportFoldersParser/MailImportFoldersParser';
import { getDefaultTimePeriod } from '@proton/activation/src/helpers/getDefaultTimePeriod';
import { getMailMappingErrors } from '@proton/activation/src/helpers/getMailMappingErrors';
import useAvailableAddresses from '@proton/activation/src/hooks/useAvailableAddresses';
import { MailImportDestinationFolder, OAUTH_PROVIDER, TIME_PERIOD } from '@proton/activation/src/interface';
import {
displayConfirmLeaveModal,
saveImapMailFields,
startImapMailImport,
} from '@proton/activation/src/logic/draft/imapDraft/imapDraft.actions';
import { selectImapDraftMailImport } from '@proton/activation/src/logic/draft/imapDraft/imapDraft.selector';
import { useEasySwitchDispatch, useEasySwitchSelector } from '@proton/activation/src/logic/store';
import { useFolders, useLabels } from '@proton/components';
import isDeepEqual from '@proton/shared/lib/helpers/isDeepEqual';
import { Address, Label, UserModel } from '@proton/shared/lib/interfaces';
import { MailImportFields } from '../../../CustomizeMailImportModal/CustomizeMailImportModal.interface';
import { formatPrepareStepPayload } from './StepPrepareImap.helpers';
import getDefaultLabel from './useStepPrepareImap.helpers';
type ImportLabel = Pick<Label, 'Color' | 'Name' | 'Type'>;
type Fields = {
mapping: {
value: MailImportFolder[];
initialValue: MailImportFolder[];
isUpdated: boolean;
};
importLabel: {
value: ImportLabel;
initialValue: ImportLabel;
isUpdated: boolean;
};
importPeriod: {
value: TIME_PERIOD;
initialValue: TIME_PERIOD;
isUpdated: boolean;
};
importAddress: {
value: Address;
initialValue: Address;
isUpdated: boolean;
};
importCategoriesDestination: {
value: MailImportDestinationFolder;
initialValue: MailImportDestinationFolder;
isUpdated: boolean;
};
};
export type StepPrepareData = ReturnType<typeof useStepPrepare>;
interface Props {
user: UserModel;
handleCloseCustomizeModal: () => void;
}
const useStepPrepare = ({ user, handleCloseCustomizeModal }: Props) => {
const dispatch = useEasySwitchDispatch();
const { defaultAddress } = useAvailableAddresses();
const [labels = []] = useLabels();
const [folders = []] = useFolders();
const data = useEasySwitchSelector(selectImapDraftMailImport);
if (!data) {
throw new Error('Data should be defined');
}
const {
domain,
email = '',
foldersMapping = [],
loading: connectingToProvider,
apiImporterID: importerID,
password,
} = data;
const isLabelMapping = domain === IMAPS[OAUTH_PROVIDER.GOOGLE];
const hasCategories = useMemo(() => foldersMapping.some((item) => item.category), []);
const [customFields, setCustomFields] = useState<Fields>(() => {
const defaultImportPeriod = getDefaultTimePeriod(user);
const defaultLabel = getDefaultLabel(email);
const defaultImportCategoriesDestination = (() => {
const firstMappingItemWithCategory = foldersMapping.find(
(item) => item.category && GMAIL_CATEGORIES.includes(item.category)
);
return firstMappingItemWithCategory?.systemFolder || MailImportDestinationFolder.INBOX;
})();
const fields: Fields = {
mapping: {
value: foldersMapping,
initialValue: foldersMapping,
isUpdated: false,
},
importLabel: {
value: defaultLabel,
initialValue: defaultLabel,
isUpdated: false,
},
importPeriod: {
value: defaultImportPeriod,
initialValue: defaultImportPeriod,
isUpdated: false,
},
importAddress: {
value: defaultAddress,
initialValue: defaultAddress,
isUpdated: false,
},
importCategoriesDestination: {
value: defaultImportCategoriesDestination,
initialValue: defaultImportCategoriesDestination,
isUpdated: false,
},
};
return fields;
});
const mailMappingErrors = getMailMappingErrors(customFields.mapping.value, isLabelMapping, labels, folders);
const hasErrors = mailMappingErrors.errors.length > 0;
const selectedFolders = customFields.mapping.value.filter((folder) => folder.checked);
const importSize = selectedFolders.reduce((acc, folder) => {
acc += folder.size;
return acc;
}, 0);
const fields: MailImportFields = {
mapping: customFields.mapping.value,
importLabel: customFields.importLabel.value,
importPeriod: customFields.importPeriod.value,
importAddress: customFields.importAddress.value,
importCategoriesDestination: customFields.importCategoriesDestination.value,
};
const handleUpdateField = <K extends keyof Fields>(fieldKey: K, value: Fields[K]['value']) => {
setCustomFields({
...customFields,
[fieldKey]: {
...customFields[fieldKey],
value,
isUpdated: isDeepEqual(customFields[fieldKey].initialValue, value),
},
});
};
const handleUpdateFields = (updatedFields: { [K in keyof Fields]: Fields[K]['value'] }) => {
const nextFields = cloneDeep(customFields);
for (let k in updatedFields) {
const key = k as keyof Fields;
nextFields[key].value = updatedFields[key];
nextFields[key].isUpdated = isDeepEqual(nextFields[key].initialValue, updatedFields[key]);
}
setCustomFields(nextFields);
};
const handleSubmitCustomizeModal = (updatedFields: MailImportFields) => {
handleUpdateFields(updatedFields);
handleCloseCustomizeModal();
};
const handleReset = () => {
const nextFields = cloneDeep(customFields);
for (let k in nextFields) {
const key = k as keyof Fields;
nextFields[key].value = nextFields[key].initialValue;
nextFields[key].isUpdated = false;
}
setCustomFields(nextFields);
};
const handleCancel = () => {
dispatch(displayConfirmLeaveModal(true));
};
const handleSubmit = () => {
if (hasErrors) {
return;
}
dispatch(saveImapMailFields(fields));
const payload = formatPrepareStepPayload({
isLabelMapping,
data: {
email,
importerID,
password,
},
fields: {
mapping: customFields.mapping.value,
importAddress: customFields.importAddress.value,
importLabel: customFields.importLabel.value,
importPeriod: customFields.importPeriod.value,
importCategoriesDestination: customFields.importCategoriesDestination.value,
},
updatedFields: {
updatedLabel: customFields.importLabel.isUpdated,
updatedPeriod: customFields.importPeriod.isUpdated,
updatedMapping: customFields.mapping.isUpdated,
},
});
if (connectingToProvider) {
return;
}
void dispatch(startImapMailImport(payload));
};
return {
email,
errors: mailMappingErrors.errors,
fields,
handleCancel,
handleReset,
handleSubmit,
handleSubmitCustomizeModal,
handleUpdateField,
hasErrors,
hasUpdatedField: Object.values(customFields).some(({ isUpdated }) => isUpdated),
isLabelMapping,
isConnectingToProvider: !!connectingToProvider,
importSize,
selectedFolders,
hasCategories,
};
};
export default useStepPrepare;
| 4,858
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapProductsModal/ImapProductsModal.tsx
|
import React from 'react';
import { c } from 'ttag';
import { EasySwitchFeatureFlag, ImportType } from '@proton/activation/src/interface';
import {
FeatureCode,
Loader,
ModalTwo,
ModalTwoContent,
ModalTwoHeader,
useCalendars,
useFeature,
} from '@proton/components';
import {
getProbablyActiveCalendars,
getVisualCalendars,
getWritableCalendars,
} from '@proton/shared/lib/calendar/calendar';
import { CALENDAR_APP_NAME } from '@proton/shared/lib/constants';
import ImapProductsModalButtons from './ImapProductsModalButtons';
interface Props {
onClick: (importType: ImportType) => void;
onClose: () => void;
}
const ImapProductsModal = ({ onClick, onClose }: Props) => {
const { feature, loading: FFLoading } = useFeature<EasySwitchFeatureFlag>(FeatureCode.EasySwitch);
const [calendars = [], calendarLoading] = useCalendars();
const activeWritableCalendars = getWritableCalendars(getProbablyActiveCalendars(getVisualCalendars(calendars)));
const loading = FFLoading || calendarLoading;
return (
<ModalTwo
key="easy-switch-imap-modal"
className="easy-switch-modal"
size="large"
open
onClose={onClose}
data-testid="MailModal:ProductModal"
>
<ModalTwoHeader title={c('Title').t`What would you like to import?`} />
<ModalTwoContent className="mb-8">
{loading ? (
<Loader />
) : (
<div>
<div className="mb-8">{c('Info').t`You can import one data type at a time.`}</div>
<div className="import-buttons">
<ImapProductsModalButtons
importType={ImportType.MAIL}
onClick={() => onClick(ImportType.MAIL)}
disabled={!feature?.Value?.OtherMail}
disabledTooltipTitle={c('Info').t`Temporarily unavailable. Please check back later.`}
/>
<ImapProductsModalButtons
importType={ImportType.CALENDAR}
onClick={() => onClick(ImportType.CALENDAR)}
disabled={!feature?.Value?.OtherCalendar || activeWritableCalendars.length === 0}
disabledTooltipTitle={
feature?.Value?.OtherCalendar
? c('Info')
.t`To import events, first create a calendar in ${CALENDAR_APP_NAME}. This is where the events will appear after the import.`
: c('Info').t`Temporarily unavailable. Please check back later.`
}
/>
<ImapProductsModalButtons
importType={ImportType.CONTACTS}
onClick={() => onClick(ImportType.CONTACTS)}
disabled={!feature?.Value?.OtherContacts}
disabledTooltipTitle={c('Info').t`Temporarily unavailable. Please check back later.`}
/>
</div>
</div>
)}
</ModalTwoContent>
</ModalTwo>
);
};
export default ImapProductsModal;
| 4,859
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/ImapProductsModal/ImapProductsModalButtons.tsx
|
import { c } from 'ttag';
import { ImportType } from '@proton/activation/src/interface';
import { Button } from '@proton/atoms/Button';
import { Tooltip } from '@proton/components/components';
import calendarIllustration from '@proton/styles/assets/img/import/importTypes/calendar.svg';
import contactsIllustration from '@proton/styles/assets/img/import/importTypes/contacts.svg';
import mailIllustration from '@proton/styles/assets/img/import/importTypes/mail.svg';
interface ImportTypeButtonProps {
importType: ImportType;
onClick: () => void;
disabled: boolean;
}
const ImportTypeButton = ({ importType, onClick, disabled }: ImportTypeButtonProps) => {
const typeMap = {
[ImportType.MAIL]: {
title: c('Action').t`Import emails`,
text: c('Label').t`Emails`,
illustration: mailIllustration,
},
[ImportType.CALENDAR]: {
title: c('Action').t`Import calendars`,
text: c('Label').t`Calendars`,
illustration: calendarIllustration,
},
[ImportType.CONTACTS]: {
title: c('Action').t`Import contacts`,
text: c('Label').t`Contacts`,
illustration: contactsIllustration,
},
};
return (
<Button
aria-label={typeMap[importType].title}
className="flex flex-align-center flex-justify-center pt-5 pb-4 px-7"
color="weak"
disabled={disabled}
onClick={onClick}
shape="outline"
title={typeMap[importType].title}
type="button"
data-testid="MailModal:ProductButton"
>
<span className="flex flex-nowrap flex-column px-4">
<img
src={typeMap[importType].illustration}
alt=""
className="w-custom mb-4"
style={{ '--w-custom': '5em' }}
/>
<span>{typeMap[importType].text}</span>
</span>
</Button>
);
};
interface Props {
importType: ImportType;
onClick: () => void;
disabled: boolean;
disabledTooltipTitle: string;
}
const ImapProductsModalButtons = ({ importType, onClick, disabled, disabledTooltipTitle }: Props) => {
const button = <ImportTypeButton importType={importType} onClick={onClick} disabled={disabled} />;
return disabled ? (
<Tooltip title={disabledTooltipTitle}>
<span>{button}</span>
</Tooltip>
) : (
button
);
};
export default ImapProductsModalButtons;
| 4,860
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/InstructionsModal/InstructionsModal.tsx
|
import React from 'react';
import { c } from 'ttag';
import { ImportProvider, ImportType } from '@proton/activation/src/interface';
import {
selectImapDraftProduct,
selectImapDraftProvider,
} from '@proton/activation/src/logic/draft/imapDraft/imapDraft.selector';
import { useEasySwitchSelector } from '@proton/activation/src/logic/store';
import { Button } from '@proton/atoms/Button';
import { ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader } from '@proton/components';
import DefaultCalendarInstructions from './Instructions/default/DefaultCalendarInstructions';
import DefaultContactsInstructions from './Instructions/default/DefaultContactsInstructions';
import DefaultMailInstructions from './Instructions/default/DefaultMailInstructions';
import YahooCalendarInstructions from './Instructions/yahoo/YahooCalendarInstructions';
import YahooContactsInstructions from './Instructions/yahoo/YahooContactsInstructions';
import YahooMailInstructions from './Instructions/yahoo/YahooMailInstructions';
interface Props {
onSubmit: () => void;
onClose: () => void;
}
const { DEFAULT, YAHOO } = ImportProvider;
const InstructionsModal = ({ onSubmit, onClose }: Props) => {
const product = useEasySwitchSelector(selectImapDraftProduct);
const provider = useEasySwitchSelector(selectImapDraftProvider);
const titleRenderer = () => {
if (product === ImportType.MAIL) {
if (provider === YAHOO) {
return c('Modal title').t`How to import emails from Yahoo`;
}
if (provider === DEFAULT) {
return c('Modal title').t`How to import emails from another service`;
}
}
if (product === ImportType.CALENDAR) {
if (provider === YAHOO) {
return c('Modal title').t`How to import calendars from Yahoo`;
}
if (provider === DEFAULT) {
return c('Modal title').t`How to import calendars from another service`;
}
}
if (product === ImportType.CONTACTS) {
if (provider === YAHOO) {
return c('Modal title').t`How to import contacts from Yahoo`;
}
if (provider === DEFAULT) {
return c('Modal title').t`How to import contacts from another service`;
}
}
};
const instructionsRenderer = () => {
if (product === ImportType.MAIL) {
if (provider === YAHOO) {
return <YahooMailInstructions />;
}
if (provider === DEFAULT) {
return <DefaultMailInstructions />;
}
}
if (product === ImportType.CALENDAR) {
if (provider === YAHOO) {
return <YahooCalendarInstructions />;
}
if (provider === DEFAULT) {
return <DefaultCalendarInstructions />;
}
}
if (product === ImportType.CONTACTS) {
if (provider === YAHOO) {
return <YahooContactsInstructions />;
}
if (provider === DEFAULT) {
return <DefaultContactsInstructions />;
}
}
return null;
};
return (
<ModalTwo key="easy-switch-instruction-modal" className="easy-switch-modal" open onClose={onClose}>
<ModalTwoHeader title={titleRenderer()} />
<ModalTwoContent>{instructionsRenderer()}</ModalTwoContent>
<ModalTwoFooter>
<Button color="weak" onClick={onClose} data-testid="Instruction:close">{c('Action').t`Close`}</Button>
<Button color="norm" onClick={onSubmit} data-testid="Instruction:continue">{c('Action')
.t`Continue`}</Button>
</ModalTwoFooter>
</ModalTwo>
);
};
export default InstructionsModal;
| 4,861
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/InstructionsModal/Instructions
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/InstructionsModal/Instructions/default/DefaultCalendarInstructions.tsx
|
import { c } from 'ttag';
import { Href } from '@proton/atoms';
import { IMPORT_CALENDAR_FAQ_URL } from '@proton/shared/lib/calendar/constants';
import { BRAND_NAME } from '@proton/shared/lib/constants';
import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url';
const DefaultCalendarInstructions = () => {
// translator: full sentence: "To import a calendar to Proton, you need the ICS file. Download this before you start the import process."
const knowledgeBaseLink = (
<Href href={getKnowledgeBaseUrl(IMPORT_CALENDAR_FAQ_URL)} key="knowledgeBaseLink">
{c('Import instructions link').t`ICS file`}
</Href>
);
// translator: full sentence: "To import a calendar to Proton, you need the ICS file. Download this before you start the import process."
const defaultCalendarMessage = c('Import instructions')
.jt`To import a calendar to ${BRAND_NAME}, you need the ${knowledgeBaseLink}. Download this before you start the import process.`;
return (
<div className="mb-4" data-testid="Instruction:defaultCalendarInstructions">
{defaultCalendarMessage}
</div>
);
};
export default DefaultCalendarInstructions;
| 4,862
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/InstructionsModal/Instructions
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/InstructionsModal/Instructions/default/DefaultContactsInstructions.tsx
|
import { c } from 'ttag';
import { Href } from '@proton/atoms';
import { BRAND_NAME } from '@proton/shared/lib/constants';
import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url';
const DefaultContactsInstructions = () => {
// translator: full sentence: "To import contacts to Proton, you need a CSV or a VCF (vCard) file. Download this before you start the import process."
const knowledgeBaseLink = (
<Href href={getKnowledgeBaseUrl('/exporting-contacts-from-other-mail-providers')} key="knowledgeBaseLink">
{c('Import instructions link').t`CSV or a VCF (vCard) file`}
</Href>
);
// translator: full sentence: "To import contacts to Proton, you need a CSV or a VCF (vCard) file. Download this before you start the import process."
const defaultContactsMessage = c('Import instructions')
.jt`To import contacts to ${BRAND_NAME}, you need a ${knowledgeBaseLink}. Download this before you start the import process.`;
return (
<div className="mb-4" data-testid="Instruction:defaultContactInstructions">
{defaultContactsMessage}
</div>
);
};
export default DefaultContactsInstructions;
| 4,863
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/InstructionsModal/Instructions
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/InstructionsModal/Instructions/default/DefaultMailInstructions.tsx
|
import { c } from 'ttag';
import { Href } from '@proton/atoms';
import { BRAND_NAME } from '@proton/shared/lib/constants';
import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url';
const DefaultMailInstructions = () => {
// translator: full sentence: "Depending on your email service provider, you may need to generate an app password or enable IMAP first before you can import to Proton."
const knowledgeBaseLink = (
<Href href={getKnowledgeBaseUrl('/allowing-imap-access-and-entering-imap-details')} key="knowledgeBaseLink">
{c('Import instructions link').t`app password or enable IMAP`}
</Href>
);
// translator: full sentence: "Depending on your email service provider, you may need to generate an app password or enable IMAP first before you can import to Proton."
const defaultAppPasswordMessage = c('Import instructions')
.jt`Depending on your email service provider, you may need to generate an ${knowledgeBaseLink} first before you can import to ${BRAND_NAME}.`;
return (
<div className="mb-4" data-testid="Instruction:defaultMailInstructions">
{defaultAppPasswordMessage}
</div>
);
};
export default DefaultMailInstructions;
| 4,864
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/InstructionsModal/Instructions
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/InstructionsModal/Instructions/yahoo/YahooCalendarInstructions.tsx
|
import { c } from 'ttag';
import { Href } from '@proton/atoms';
import { IMPORT_CALENDAR_FAQ_URL } from '@proton/shared/lib/calendar/constants';
import { BRAND_NAME } from '@proton/shared/lib/constants';
import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url';
const YahooCalendarInstructions = () => {
// translator: full sentence: "To import a calendar to Proton, you need the ICS file. Download it from Yahoo in 3 easy steps:"
const knowledgeBaseLink = (
<Href href={getKnowledgeBaseUrl(IMPORT_CALENDAR_FAQ_URL)} key="knowledgeBaseLink">
{c('Import instructions link').t`ICS file`}
</Href>
);
// translator: full sentence: "To import a calendar to Proton, you need the ICS file. Download it from Yahoo in 3 easy steps:"
const yahooCalendarMessage = c('Import instructions')
.jt`To import a calendar to ${BRAND_NAME}, you need the ${knowledgeBaseLink}. Download it from Yahoo in 3 easy steps:`;
// translator: full sentence: "Go to full calendar view in Yahoo"
const calendarViewLink = (
<Href href="https://calendar.yahoo.com/" key="calendarViewLink">
{c('Import instructions link').t`full calendar view`}
</Href>
);
// translator: full sentence: "Go to full calendar view in Yahoo"
const step1 = c('Import instructions step').jt`Go to ${calendarViewLink} in Yahoo.`;
const step2 = c('Import instructions step')
.t`Mouse over the calendar you want to import and open the dropdown menu.`;
// translator: full sentence: "Select Export to export the calendar as an ICS file"
const boldExport = <strong key="boldExport">{c('Import instructions emphasis').t`Export`}</strong>;
// translator: full sentence: "Select Export to export the calendar as an ICS file"
const step3 = c('Import instructions step').jt`Select ${boldExport} to export the calendar as an ICS file.`;
return (
<>
<div className="mb-4" data-testid="Instruction:yahooCalendarInstructions">
{yahooCalendarMessage}
</div>
<ol className="pl-4 mx-8">
<li className="mb-2">{step1}</li>
<li className="mb-2">{step2}</li>
<li className="mb-2">{step3}</li>
</ol>
</>
);
};
export default YahooCalendarInstructions;
| 4,865
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/InstructionsModal/Instructions
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/InstructionsModal/Instructions/yahoo/YahooContactsInstructions.tsx
|
import { c } from 'ttag';
import { Href } from '@proton/atoms';
import { BRAND_NAME } from '@proton/shared/lib/constants';
import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url';
const YahooContactsInstructions = () => {
// translator: full sentence: "To import contacts to Proton, you need a CSV or a VCF (vCard) file. Download it from Yahoo in 3 easy steps:"
const knowledgeBaseLink = (
<Href href={getKnowledgeBaseUrl('/exporting-contacts-from-other-mail-providers')} key="knowledgeBaseLink">
{c('Import instructions link').t`CSV or a VCF (vCard) file`}
</Href>
);
// translator: full sentence: "To import contacts to Proton, you need a CSV or a VCF (vCard) file. Download it from Yahoo in 3 easy steps:"
const yahooCalendarMessage = c('Import instructions')
.jt`To import contacts to ${BRAND_NAME}, you need a ${knowledgeBaseLink}. Download it from Yahoo in 3 easy steps:`;
// translator: full sentence: "Open your Yahoo contacts":
const yahooMailLink = (
<Href href="https://mail.yahoo.com/" key="yahooMailLink">
{c('Import instructions link').t`Yahoo`}
</Href>
);
// translator: full sentence: "Open your Yahoo contacts"
const step1 = c('Import instructions').jt`Open your ${yahooMailLink} contacts.`;
const step2 = c('Import instructions').t`Expand the dropdown menu by clicking on the 3 dots (...).`;
// translator: full sentence: "Select Export to CSV file"
const boldExportCSV = (
<strong key="boldExportCSV">{c('Import instructions emphasis').t`Export to CSV file`}</strong>
);
// translator: full sentence: "Select Export to CSV file"
const step3 = c('Import instructions').jt`Select ${boldExportCSV}.`;
return (
<>
<div className="mb-4" data-testid="Instruction:yahooContactInstructions">
{yahooCalendarMessage}
</div>
<ol className="pl-4 mx-8">
<li className="mb-2">{step1}</li>
<li className="mb-2">{step2}</li>
<li className="mb-2">{step3}</li>
</ol>
</>
);
};
export default YahooContactsInstructions;
| 4,866
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/InstructionsModal/Instructions
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/Imap/InstructionsModal/Instructions/yahoo/YahooMailInstructions.tsx
|
import { c } from 'ttag';
import { Href } from '@proton/atoms';
import { BRAND_NAME } from '@proton/shared/lib/constants';
import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url';
const YahooMailInstructions = () => {
// translator: full sentence: "To import emails to Proton, you need an app password from Yahoo. Get it by following these steps:"
const appPasswordLink = (
<Href href={getKnowledgeBaseUrl('/allowing-imap-access-and-entering-imap-details')} key="appPasswordLink">
{c('Import instructions link').t`app password`}
</Href>
);
// translator: full sentence: "To import emails to Proton, you need an app password from Yahoo. Get it by following these steps:"
const yahooAppPasswordMessage = c('Import instructions')
.jt`To import emails to ${BRAND_NAME}, you need an ${appPasswordLink} from Yahoo. Get it by following these steps:`;
// translator: full sentence: "Go to account info under your profile in Yahoo"
const boldAccountInfo = <strong key="boldAccountInfo">{c('Import instructions emphasis').t`Account info`}</strong>;
// translator: full sentence: "Go to account info under your profile in Yahoo"
const yahooMailLink = (
<Href href="https://mail.yahoo.com/" key="yahooMailLink">
{c('Import instructions link').t`Yahoo`}
</Href>
);
// translator: full sentence: "Go to account info under your profile in Yahoo"
const step1 = c('Import instructions').jt`Go to ${boldAccountInfo} under your profile in ${yahooMailLink}.`;
// translator: full sentence: "Go to Account security"
const boldAccountSecurity = (
<strong key="boldAccountSecurity">{c('Import instructions emphasis').t`Account security`}</strong>
);
// translator: full sentence: "Go to Account security"
const step2 = c('Import instructions').jt`Go to ${boldAccountSecurity}.`;
// translator: full sentence: "Generate the app password and use it in place of your regular password when prompted by Proton"
const boldAppPassword = (
<strong key="boldAccountSecurity">{c('Import instructions emphasis').t`app password`}</strong>
);
// translator: full sentence: "Generate the app password and use it in place of your regular password when prompted by Proton"
const step3 = c('Import instructions')
.jt`Generate the ${boldAppPassword} and use it in place of your regular password when prompted by ${BRAND_NAME}.`;
return (
<>
<div className="mb-4" data-testid="Instruction:yahooMailInstructions">
{yahooAppPasswordMessage}
</div>
<ol className="pl-4 mx-8">
<li className="mb-2">{step1}</li>
<li className="mb-2">{step2}</li>
<li className="mb-2">{step3}</li>
</ol>
</>
);
};
export default YahooMailInstructions;
| 4,867
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/OAuthModal.helpers.test.ts
|
import { EasySwitchFeatureFlag, ImportProvider } from '@proton/activation/src/interface';
import isTruthy from '@proton/utils/isTruthy';
import { getEnabledFeature } from './OAuthModal.helpers';
describe('OAuthModal helpers', () => {
it('Should return all feature enabled', () => {
const featureMap: EasySwitchFeatureFlag = {
GoogleMail: true,
GoogleMailSync: true,
GoogleCalendar: true,
GoogleContacts: true,
GoogleDrive: true,
OutlookMail: true,
OutlookCalendar: true,
OutlookContacts: true,
OtherMail: true,
OtherCalendar: true,
OtherContacts: true,
OtherDrive: true,
};
const googleService = getEnabledFeature(ImportProvider.GOOGLE, featureMap);
expect(Object.values(googleService).every(isTruthy)).toBe(true);
const outlookService = getEnabledFeature(ImportProvider.OUTLOOK, featureMap);
expect(Object.values(outlookService).every(isTruthy)).toBe(true);
const otherService = getEnabledFeature(ImportProvider.DEFAULT, featureMap);
expect(Object.values(otherService).every(isTruthy)).toBe(false);
});
it('Should return true for email and everything else false', () => {
const featureMap: EasySwitchFeatureFlag = {
GoogleMail: true,
GoogleMailSync: true,
GoogleCalendar: false,
GoogleContacts: false,
GoogleDrive: false,
OutlookMail: true,
OutlookCalendar: false,
OutlookContacts: false,
OtherMail: true,
OtherCalendar: false,
OtherContacts: false,
OtherDrive: false,
};
const expected = {
isEmailsEnabled: true,
isContactsEnabled: false,
isCalendarsEnabled: false,
};
const googleService = getEnabledFeature(ImportProvider.GOOGLE, featureMap);
expect(googleService).toStrictEqual(expected);
const outlookService = getEnabledFeature(ImportProvider.OUTLOOK, featureMap);
expect(outlookService).toStrictEqual(expected);
const otherService = getEnabledFeature(ImportProvider.DEFAULT, featureMap);
expect(Object.values(otherService).every(isTruthy)).toBe(false);
});
it('Should return true for calendar and everything else false', () => {
const featureMap: EasySwitchFeatureFlag = {
GoogleMail: false,
GoogleMailSync: false,
GoogleCalendar: true,
GoogleContacts: false,
GoogleDrive: false,
OutlookMail: false,
OutlookCalendar: true,
OutlookContacts: false,
OtherMail: false,
OtherCalendar: true,
OtherContacts: false,
OtherDrive: false,
};
const expected = {
isEmailsEnabled: false,
isContactsEnabled: false,
isCalendarsEnabled: true,
};
const googleService = getEnabledFeature(ImportProvider.GOOGLE, featureMap);
expect(googleService).toStrictEqual(expected);
const outlookService = getEnabledFeature(ImportProvider.OUTLOOK, featureMap);
expect(outlookService).toStrictEqual(expected);
const otherService = getEnabledFeature(ImportProvider.DEFAULT, featureMap);
expect(Object.values(otherService).every(isTruthy)).toBe(false);
});
it('Should return true for contact and everything else false', () => {
const featureMap: EasySwitchFeatureFlag = {
GoogleMail: false,
GoogleMailSync: false,
GoogleCalendar: false,
GoogleContacts: true,
GoogleDrive: false,
OutlookMail: false,
OutlookCalendar: false,
OutlookContacts: true,
OtherMail: false,
OtherCalendar: false,
OtherContacts: false,
OtherDrive: true,
};
const expected = {
isEmailsEnabled: false,
isContactsEnabled: true,
isCalendarsEnabled: false,
};
const googleService = getEnabledFeature(ImportProvider.GOOGLE, featureMap);
expect(googleService).toStrictEqual(expected);
const outlookService = getEnabledFeature(ImportProvider.OUTLOOK, featureMap);
expect(outlookService).toStrictEqual(expected);
const otherService = getEnabledFeature(ImportProvider.DEFAULT, featureMap);
expect(Object.values(otherService).every(isTruthy)).toBe(false);
});
});
| 4,868
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/OAuthModal.helpers.ts
|
import { EasySwitchFeatureFlag, ImportProvider } from '@proton/activation/src/interface';
const isEasySwitchMailsEnabled = (provider: ImportProvider, featureMap: EasySwitchFeatureFlag) => {
if (provider === ImportProvider.GOOGLE) {
return featureMap.GoogleMail;
}
if (provider === ImportProvider.OUTLOOK) {
return featureMap.OutlookMail;
}
return false;
};
const isEasySwitchContactsEnabled = (provider: ImportProvider, featureMap: EasySwitchFeatureFlag) => {
if (provider === ImportProvider.GOOGLE) {
return featureMap.GoogleContacts;
}
if (provider === ImportProvider.OUTLOOK) {
return featureMap.OutlookContacts;
}
return false;
};
const isEasySwitchCalendarEnabled = (provider: ImportProvider, featureMap: EasySwitchFeatureFlag) => {
if (provider === ImportProvider.GOOGLE) {
return featureMap.GoogleCalendar;
}
if (provider === ImportProvider.OUTLOOK) {
return featureMap.OutlookCalendar;
}
return false;
};
export const getEnabledFeature = (provider: ImportProvider, featureMap: EasySwitchFeatureFlag) => {
return {
isEmailsEnabled: isEasySwitchMailsEnabled(provider, featureMap),
isContactsEnabled: isEasySwitchContactsEnabled(provider, featureMap),
isCalendarsEnabled: isEasySwitchCalendarEnabled(provider, featureMap),
};
};
| 4,869
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/OAuthModal.test.tsx
|
import { fireEvent, screen, waitFor } from '@testing-library/react';
import { rest } from 'msw';
import { setupServer } from 'msw/node';
import { easySwitchRender } from '@proton/activation/src/tests/render';
import ProviderCards from '../../SettingsArea/ProviderCards/ProviderCards';
const server = setupServer();
jest.mock('@proton/components/hooks/useApiEnvironmentConfig', () => () => [
{
'importer.google.client_id': 'string',
'importer.outlook.client_id': 'string',
},
false,
]);
jest.mock('@proton/components/hooks/useUser', () => () => [
{
isAdmin: true,
isFree: true,
isMember: true,
isPaid: true,
isPrivate: true,
isSubUser: true,
isDelinquent: true,
hasNonDelinquentScope: true,
hasPaidMail: true,
hasPaidVpn: true,
canPay: true,
},
false,
]);
jest.mock('@proton/components/hooks/useFeature', () => () => {
return {
feature: {
Code: 'EasySwitch',
Type: 'boolean',
Global: true,
DefaultValue: {
GoogleMail: true,
GoogleMailSync: true,
GoogleCalendar: true,
GoogleContacts: true,
OutlookMail: true,
OutlookCalendar: true,
OutlookContacts: true,
OtherMail: true,
OtherCalendar: true,
OtherContacts: true,
},
Value: {
GoogleMail: true,
GoogleMailSync: true,
GoogleCalendar: true,
GoogleContacts: true,
OutlookMail: true,
OutlookCalendar: true,
OutlookContacts: true,
OtherMail: true,
OtherCalendar: true,
OtherContacts: true,
},
Writable: false,
},
};
});
beforeAll(() => {
server.listen();
server.use(
rest.get('/core/v4/system/config', (req, res, ctx) => {
return res(ctx.set('date', '01/01/2022'), ctx.json({}));
}),
rest.get('/calendar/v1', (req, res, ctx) => {
return res(ctx.set('date', '01/01/2022'), ctx.json({}));
})
);
});
afterEach(() => {
server.resetHandlers();
});
afterAll(() => {
server.close();
});
describe('OAuth start step', () => {
it.skip('Should render the product selection modal when clicking on Google', async () => {
easySwitchRender(<ProviderCards />);
const google = screen.getByTestId('ProviderCard:googleCard');
expect(google).toBeEnabled();
fireEvent.click(google);
await waitFor(() => screen.getByTestId('StepProducts:modal'));
});
it.skip('Should render the product selection modal when clicking on Outlook', async () => {
easySwitchRender(<ProviderCards />);
const outlook = screen.getByTestId('ProviderCard:outlookCard');
expect(outlook).toBeEnabled();
fireEvent.click(outlook);
await waitFor(() => screen.getByTestId('StepProducts:modal'));
});
it('Should render the instruction modal if Google is selected', async () => {
easySwitchRender(<ProviderCards />);
// Open the product modal
const google = screen.getByTestId('ProviderCard:googleCard');
expect(google).toBeEnabled();
fireEvent.click(google);
await waitFor(() => screen.getByTestId('StepProducts:modal'));
// Submit products modal
const submitProducts = screen.getByTestId('StepProducts:submit');
fireEvent.click(submitProducts);
// Wait for instructions modal
await waitFor(() => screen.getByTestId('StepInstruction:modal'));
// Press back button on instruction modal
const backButton = screen.getByTestId('StepInstruction:back');
fireEvent.click(backButton);
// Expect to see products modal again
await waitFor(() => screen.getByTestId('StepProducts:modal'));
});
it('Should render the product modal and fire submit', async () => {
server.use(
rest.get('/calendar/v1', (req, res, ctx) => {
return res(ctx.set('date', '01/01/2022'), ctx.json({}));
})
);
easySwitchRender(<ProviderCards />);
// Open the product modal
const outlook = screen.getByTestId('ProviderCard:outlookCard');
expect(outlook).toBeEnabled();
fireEvent.click(outlook);
await waitFor(() => screen.getByTestId('StepProducts:modal'));
// Submit products modal
const submitProducts = screen.getByTestId('StepProducts:submit');
fireEvent.click(submitProducts);
});
it('Should render the product and instructions modal when Google is selected', async () => {
server.use(
rest.get('/calendar/v1', (req, res, ctx) => {
return res(ctx.set('date', '01/01/2022'), ctx.json({}));
})
);
easySwitchRender(<ProviderCards />);
// Open the product modal
const google = screen.getByTestId('ProviderCard:googleCard');
expect(google).toBeEnabled();
fireEvent.click(google);
await waitFor(() => screen.getByTestId('StepProducts:modal'));
// Submit products modal
const submitProducts = screen.getByTestId('StepProducts:submit');
fireEvent.click(submitProducts);
// Wait for instructions modal
await waitFor(() => screen.getByTestId('StepInstruction:modal'));
// Press submit button on instruction modal
const submitButton = screen.getByTestId('StepInstruction:submit');
fireEvent.click(submitButton);
});
});
| 4,870
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/OAuthModal.tsx
|
import { useEffect } from 'react';
import { ImportProvider } from '@proton/activation/src/interface';
import {
displayConfirmLeaveModal,
initOauthMailImport,
resetOauthDraft,
} from '@proton/activation/src/logic/draft/oauthDraft/oauthDraft.actions';
import {
selectOauthDraftProvider,
selectOauthDraftStepConfirmModalDisplay,
selectOauthImportStateStep,
} from '@proton/activation/src/logic/draft/oauthDraft/oauthDraft.selector';
import { useEasySwitchDispatch, useEasySwitchSelector } from '@proton/activation/src/logic/store';
import ConfirmLeaveModal from '../ConfirmLeaveModal/ConfirmLeaveModal';
import StepInstructionsGoogle from './StepInstructions/StepInstructionsGoogle';
import StepLoadingImporter from './StepLoading/StepLoadingImporter';
import StepLoadingImporting from './StepLoading/StepLoadingImporting';
import StepPrepare from './StepPrepareOAuth/StepPrepareOAuth';
import StepProducts from './StepProducts/StepProducts';
import StepSuccess from './StepSuccess/StepSuccess';
import useOAuthModal from './useOAuthModal';
const OAuthModal = () => {
const dispatch = useEasySwitchDispatch();
const step = useEasySwitchSelector(selectOauthImportStateStep);
const provider = useEasySwitchSelector(selectOauthDraftProvider);
const confirmLeave = useEasySwitchSelector(selectOauthDraftStepConfirmModalDisplay);
const { triggerOAuth, initialLoading } = useOAuthModal();
useEffect(() => {
if (step === undefined) {
dispatch(initOauthMailImport());
}
}, []);
const handleClose = () => {
dispatch(resetOauthDraft());
};
const handleContinue = () => {
dispatch(displayConfirmLeaveModal(false));
};
return (
<>
{step === 'products' && initialLoading && <StepLoadingImporter />}
{step === 'products' && !initialLoading && <StepProducts triggerOAuth={triggerOAuth} />}
{step === 'instructions' && provider === ImportProvider.GOOGLE && (
<StepInstructionsGoogle triggerOAuth={triggerOAuth} />
)}
{step === 'loading-importer' && <StepLoadingImporter />}
{step === 'prepare-import' && <StepPrepare />}
{step === 'importing' && <StepLoadingImporting />}
{step === 'success' && <StepSuccess />}
{confirmLeave && <ConfirmLeaveModal handleClose={handleClose} handleContinue={handleContinue} />}
</>
);
};
export default OAuthModal;
| 4,871
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/useOAuthModal.ts
|
import { c } from 'ttag';
import useAvailableAddresses from '@proton/activation/src/hooks/useAvailableAddresses';
import useOAuthPopup from '@proton/activation/src/hooks/useOAuthPopup';
import { EASY_SWITCH_SOURCE, OAuthProps } from '@proton/activation/src/interface';
import { createImporterThunk } from '@proton/activation/src/logic/draft/oauthDraft/createImporter.action';
import { changeOAuthStep } from '@proton/activation/src/logic/draft/oauthDraft/oauthDraft.actions';
import {
selectOauthDraftProvider,
selectOauthImportStateScopes,
} from '@proton/activation/src/logic/draft/oauthDraft/oauthDraft.selector';
import { useEasySwitchDispatch, useEasySwitchSelector } from '@proton/activation/src/logic/store';
import {
FeatureCode,
useAddresses,
useCalendars,
useFeature,
useFolders,
useLabels,
useUser,
} from '@proton/components';
const useOAuthModal = () => {
const [user] = useUser();
const { defaultAddress } = useAvailableAddresses();
const dispatch = useEasySwitchDispatch();
const scopes = useEasySwitchSelector(selectOauthImportStateScopes);
const provider = useEasySwitchSelector(selectOauthDraftProvider);
const { triggerOAuthPopup, loadingConfig } = useOAuthPopup({
errorMessage: c('Error').t`Your import will not be processed.`,
});
// Initial loading of all required data at later stage, ensure everything is loaded ahead of time
const easySwitchFeature = useFeature(FeatureCode.EasySwitch);
const [, loadingAddresses] = useAddresses();
const [, loadingLabels] = useLabels();
const [, loadingFolders] = useFolders();
const [, loadingCalendars] = useCalendars();
const initialLoading =
loadingAddresses || loadingCalendars || loadingFolders || loadingLabels || easySwitchFeature.loading;
const triggerOAuth = (tempScopes?: string[]) => {
const finalScopes = scopes?.join(' ') ?? tempScopes?.join(' ');
if (!provider || !finalScopes) {
return;
}
triggerOAuthPopup({
provider,
scope: finalScopes,
callback: async (oAuthProps: OAuthProps) => {
const source = EASY_SWITCH_SOURCE.EASY_SWITCH_SETTINGS;
dispatch(changeOAuthStep('loading-importer'));
await dispatch(createImporterThunk({ oAuthProps, source, user, defaultAddress }));
},
});
};
return { initialLoading, loadingConfig, triggerOAuth };
};
export default useOAuthModal;
| 4,872
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepInstructions/StepInstructionsGoogle.tsx
|
import { c } from 'ttag';
import { displayConfirmLeaveModal } from '@proton/activation/src/logic/draft/imapDraft/imapDraft.actions';
import { changeOAuthStep, resetOauthDraft } from '@proton/activation/src/logic/draft/oauthDraft/oauthDraft.actions';
import { useEasySwitchDispatch } from '@proton/activation/src/logic/store';
import { Button } from '@proton/atoms/Button';
import {
ModalTwo,
ModalTwoContent,
ModalTwoFooter,
ModalTwoHeader,
PrimaryButton,
VideoInstructions,
} from '@proton/components';
import { BRAND_NAME } from '@proton/shared/lib/constants';
import oauthInstructionsMp4 from '@proton/styles/assets/videos/easySwitch/oauth-instructions.mp4';
import oauthInstructionsWebm from '@proton/styles/assets/videos/easySwitch/oauth-instructions.webm';
interface Props {
triggerOAuth: () => void;
}
const StepInstructionsGoogle = ({ triggerOAuth }: Props) => {
const dispatch = useEasySwitchDispatch();
const handleQuit = () => {
dispatch(displayConfirmLeaveModal(false));
dispatch(resetOauthDraft());
};
const handleBack = () => {
dispatch(changeOAuthStep('products'));
};
const instructions = c('Oauth instructions')
.t`Next you'll need to sign in to your Google account and grant ${BRAND_NAME} access to your data.`;
const instructionsVideo = c('Oauth instructions video')
.t`For the import to work, you must select all requested items as shown in the GIF.`;
const instructionsVideoAlt = c('Oauth instructions video alternative')
.t`Select what ${BRAND_NAME} can access: view your email messages and settings, view and download your contacts, view and download all agendas you access from Google Agenda.`;
return (
<ModalTwo open onClose={handleQuit}>
<ModalTwoHeader title={c('Title').t`Sign in and grant access`} />
<ModalTwoContent>
<div className="mb-8" data-testid="StepInstruction:modal">
{instructions}
</div>
<div className="mb-8">{instructionsVideo}</div>
<div className="sr-only">{instructionsVideoAlt}</div>
<div className="text-center mb-4 relative" aria-hidden="true">
<VideoInstructions>
<source src={oauthInstructionsWebm} type="video/webm" />
<source src={oauthInstructionsMp4} type="video/mp4" />
</VideoInstructions>
</div>
</ModalTwoContent>
<ModalTwoFooter>
<Button shape="outline" onClick={handleBack} data-testid="StepInstruction:back">
{c('Action').t`Back`}
</Button>
<PrimaryButton onClick={triggerOAuth} data-testid="StepInstruction:submit">{c('Action')
.t`Continue`}</PrimaryButton>
</ModalTwoFooter>
</ModalTwo>
);
};
export default StepInstructionsGoogle;
| 4,873
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepLoading/StepLoadingImporter.test.tsx
|
import { screen } from '@testing-library/dom';
import { easySwitchRender } from '@proton/activation/src/tests/render';
import StepLoadingImporter from './StepLoadingImporter';
describe('Test correct rendering of loading importer', () => {
it('Should render importer', () => {
easySwitchRender(<StepLoadingImporter />);
screen.getByTestId('StepLoadingImporter:modal');
});
});
| 4,874
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepLoading/StepLoadingImporter.tsx
|
import { c } from 'ttag';
import { Loader, ModalTwo, ModalTwoContent, TextLoader } from '@proton/components/components';
const StepLoadingImporter = () => {
return (
<ModalTwo open size="large">
<ModalTwoContent>
<div className="p-14 text-center w-full" data-testid="StepLoadingImporter:modal">
<Loader size="large" className="mb-4" />
<h4>{c('Loading info').t`Gathering your data`}</h4>
<TextLoader>{c('Loading info').t`We're gathering your data from your provider`}</TextLoader>
</div>
</ModalTwoContent>
</ModalTwo>
);
};
export default StepLoadingImporter;
| 4,875
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepLoading/StepLoadingImporting.test.tsx
|
import { screen } from '@testing-library/dom';
import { easySwitchRender } from '@proton/activation/src/tests/render';
import StepLoadingImporting from './StepLoadingImporting';
import useStepLoadingImporting from './useStepLoadingImporting';
jest.mock('./useStepLoadingImporting', () => ({
__esModule: true,
default: jest.fn(),
}));
const mockStepLoadingImporting = useStepLoadingImporting as any as jest.Mock<
ReturnType<typeof useStepLoadingImporting>
>;
describe('Test correct rendering of loading importing different states', () => {
it('Should render creating importing calendar state', () => {
mockStepLoadingImporting.mockImplementation(() => {
return {
createdCalendarCount: 10,
calendarsToBeCreated: 10,
isCreatingCalendar: true,
isCreatingImportTask: false,
};
});
easySwitchRender(<StepLoadingImporting />);
screen.getByTestId('StepLoadingImporting:modal');
});
it('Should render creating importing finishing state', () => {
mockStepLoadingImporting.mockImplementation(() => {
return {
createdCalendarCount: 10,
calendarsToBeCreated: 10,
isCreatingCalendar: false,
isCreatingImportTask: true,
};
});
easySwitchRender(<StepLoadingImporting />);
screen.getByTestId('StepLoadingImporting:modal');
});
it('Should render empty state', () => {
mockStepLoadingImporting.mockImplementation(() => {
return {
createdCalendarCount: 10,
calendarsToBeCreated: 10,
isCreatingCalendar: false,
isCreatingImportTask: false,
};
});
easySwitchRender(<StepLoadingImporting />);
screen.getByTestId('StepLoadingImporting:modal');
});
});
| 4,876
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepLoading/StepLoadingImporting.tsx
|
import { c, msgid } from 'ttag';
import { Loader, ModalTwo, ModalTwoContent, TextLoader } from '@proton/components/components';
import useStepLoadingImporting from './useStepLoadingImporting';
const StepLoadingImporting = () => {
const { createdCalendarCount, calendarsToBeCreated, isCreatingCalendar, isCreatingImportTask } =
useStepLoadingImporting();
const renderContent = () => {
if (isCreatingCalendar) {
// translator: the variables here are numbers, e.g. "Amount of calendars created: 3 out of 5"
const progressCopy = c('Loading info').ngettext(
msgid`Amount of calendar created: ${createdCalendarCount} of ${calendarsToBeCreated}`,
`Amount of calendars created: ${createdCalendarCount} out of ${calendarsToBeCreated}`,
calendarsToBeCreated
);
return (
<>
<h4>{c('Loading info').t`Creating new calendars`}</h4>
<TextLoader>{progressCopy}</TextLoader>
</>
);
}
if (isCreatingImportTask) {
return (
<>
<h4>{c('Loading info').t`Your import is starting`}</h4>
<TextLoader>{c('Loading info').t`Almost there`}</TextLoader>
</>
);
}
return null;
};
return (
<ModalTwo open size="large">
<ModalTwoContent>
<div className="p-14 text-center w-full" data-testid="StepLoadingImporting:modal">
<Loader size="large" className="mb-4" />
{renderContent()}
</div>
</ModalTwoContent>
</ModalTwo>
);
};
export default StepLoadingImporting;
| 4,877
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepLoading/useStepLoadingImporting.helpers.ts
|
import { c } from 'ttag';
import { startImportTask } from '@proton/activation/src/api';
import {
CalendarImportMapping,
ImportType,
IsCustomCalendarMapping,
LaunchImportPayload,
} from '@proton/activation/src/interface';
import { changeOAuthStep, resetOauthDraft } from '@proton/activation/src/logic/draft/oauthDraft/oauthDraft.actions';
import { ImporterCalendar, ImporterData } from '@proton/activation/src/logic/draft/oauthDraft/oauthDraft.interface';
import { createCalendar, removeCalendar, updateCalendarUserSettings } from '@proton/shared/lib/api/calendars';
import { setupCalendarKey } from '@proton/shared/lib/calendar/crypto/keys/setupCalendarKeys';
import { getRandomAccentColor } from '@proton/shared/lib/colors';
import { getTimezone } from '@proton/shared/lib/date/timezone';
import isDeepEqual from '@proton/shared/lib/helpers/isDeepEqual';
import { captureMessage } from '@proton/shared/lib/helpers/sentry';
import { Address, Api, DecryptedAddressKey } from '@proton/shared/lib/interfaces';
import { Calendar } from '@proton/shared/lib/interfaces/calendar';
import { GetAddressKeys } from '@proton/shared/lib/interfaces/hooks/GetAddressKeys';
import { getPrimaryKey } from '@proton/shared/lib/keys';
import isTruthy from '@proton/utils/isTruthy';
import { formatPrepareStepPayload } from '../../Imap/ImapMailModal/StepPrepareImap/StepPrepareImap.helpers';
interface StartImporterProps {
api: Api;
isLabelMapping: boolean;
products: ImportType[];
importerData: ImporterData;
getAddressKeys: GetAddressKeys;
availableAddresses: Address[];
calendars: Calendar[];
call: () => Promise<void>;
dispatch: (val: any) => void;
errorHandler: (data: any) => void;
setIsCreatingCalendar: (val: boolean) => void;
setIsCreatingImportTask: (val: boolean) => void;
setCalendarsToBeCreated: (val: number) => void;
increaseCalendarCount: () => void;
}
interface CreatedCalendarType extends ImporterCalendar {
destination: string;
}
interface CreateCalendarProps {
api: Api;
calendars: ImporterCalendar[];
hasNoCalendar: boolean;
getAddressKeys: (key: string) => Promise<DecryptedAddressKey[]>;
increaseCreatedCalendarCount: () => void;
activeAddresses?: Address[];
}
const createCalendars = async ({
api,
calendars,
hasNoCalendar,
getAddressKeys,
activeAddresses,
increaseCreatedCalendarCount,
}: CreateCalendarProps): Promise<CreatedCalendarType[]> => {
if (!activeAddresses || !activeAddresses.length) {
throw new Error(c('Error').t`No valid address found`);
}
const [{ ID: addressID }] = activeAddresses;
const { privateKey: primaryAddressKey } = getPrimaryKey(await getAddressKeys(addressID)) || {};
if (!primaryAddressKey) {
throw new Error(c('Error').t`Primary address key is not decrypted.`);
}
const tempCalendars = await Promise.all(
calendars.map(async (calendar) => {
increaseCreatedCalendarCount();
const { Calendar } = await api(
createCalendar({
Name: calendar.source,
Color: getRandomAccentColor(),
Description: calendar.description,
Display: 1,
AddressID: addressID,
IsImport: 1,
})
);
await setupCalendarKey({ api, calendarID: Calendar.ID, addressID, getAddressKeys });
return { ...calendar, destination: Calendar.ID };
})
);
if (hasNoCalendar) {
await api(updateCalendarUserSettings({ PrimaryTimezone: getTimezone(), AutoDetectPrimaryTimezone: 1 }));
}
return tempCalendars;
};
export const createImporterTask = async ({
isLabelMapping,
products,
importerData,
api,
getAddressKeys,
dispatch,
availableAddresses,
calendars,
call,
errorHandler,
setIsCreatingCalendar,
setIsCreatingImportTask,
setCalendarsToBeCreated,
increaseCalendarCount,
}: StartImporterProps) => {
if (!importerData || !products) {
throw new Error('Importer data and products should be defined');
}
let createdCalendars: CreatedCalendarType[] = [];
const importPayload: LaunchImportPayload = {
ImporterID: importerData.importerId,
};
if (products.includes(ImportType.CALENDAR)) {
setIsCreatingCalendar(true);
const importerCalendar = importerData.calendars?.calendars;
const initialCalendars = importerData.calendars?.initialFields;
const calendarToCreate = importerCalendar?.filter((item) => item.checked && !item.mergedTo) ?? [];
const calendarToBeMerged = importerCalendar?.filter((item) => item.mergedTo) ?? [];
setCalendarsToBeCreated(calendarToCreate?.length);
try {
createdCalendars = await createCalendars({
api,
calendars: calendarToCreate,
hasNoCalendar: !calendars.length,
getAddressKeys,
activeAddresses: availableAddresses,
increaseCreatedCalendarCount: () => {
increaseCalendarCount();
},
});
//Merge the mapping between created calendars and merged calendar before starting import task
const mapping: CalendarImportMapping[] = [
...createdCalendars.map((calendar) => {
return {
Source: calendar.id,
Description: calendar.description,
Destination: calendar.destination,
};
}),
...calendarToBeMerged.map((calendar) => {
if (calendar.mergedTo?.ID) {
return {
Source: calendar.id,
Description: calendar.description,
Destination: calendar.mergedTo.ID,
};
}
return null;
}),
].filter(isTruthy);
const formattedInitial = initialCalendars?.map((item) => {
return {
source: item.source,
description: item.description,
id: item.id,
checked: item.checked,
};
});
const formattedCalendars = importerCalendar?.map((item) => {
return {
source: item.source,
description: item.description,
id: item.id,
checked: item.checked,
};
});
const CustomCalendarMapping = !isDeepEqual(formattedInitial, formattedCalendars)
? IsCustomCalendarMapping.TRUE
: IsCustomCalendarMapping.FALSE;
importPayload.Calendar = {
Mapping: mapping,
CustomCalendarMapping,
};
setIsCreatingCalendar(false);
} catch (e) {
//Rollback to previous state if an error occurred during calendar creation
dispatch(changeOAuthStep('prepare-import'));
captureMessage('Error while creating calendars', {
extra: { message: e, importerID: importerData.importerId },
});
return;
}
}
if (products.includes(ImportType.MAIL)) {
const emailsFields = importerData.emails?.fields!;
const emailsInitialFields = importerData.emails?.initialFields!;
const isCustomPeriod = emailsInitialFields.importPeriod !== emailsFields?.importPeriod;
const isCustomLabel = !isDeepEqual(emailsInitialFields?.importLabel, emailsFields?.importLabel);
const isCustomMapping = !isDeepEqual(emailsInitialFields?.mapping, emailsFields?.mapping);
const payload = formatPrepareStepPayload({
isLabelMapping,
data: {
email: importerData.importedEmail,
importerID: importerData.importerId,
},
fields: emailsFields,
updatedFields: {
updatedPeriod: isCustomPeriod,
updatedLabel: isCustomLabel,
updatedMapping: isCustomMapping,
},
});
importPayload.Mail = payload.Mail;
}
if (products.includes(ImportType.CONTACTS)) {
importPayload.Contacts = {};
}
try {
setIsCreatingImportTask(true);
await api(startImportTask(importPayload));
await call();
setIsCreatingImportTask(false);
dispatch(changeOAuthStep('success'));
} catch (error) {
if (createdCalendars) {
await Promise.all(createdCalendars.map(async (cal) => api(removeCalendar(cal.destination))));
await call();
}
errorHandler(error);
dispatch(resetOauthDraft());
}
};
| 4,878
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepLoading/useStepLoadingImporting.ts
|
import { useEffect, useState } from 'react';
import useAvailableAddresses from '@proton/activation/src/hooks/useAvailableAddresses';
import { ImportProvider } from '@proton/activation/src/interface';
import {
selectOauthDraftProvider,
selectOauthImportStateImporterData,
selectOauthImportStateProducts,
} from '@proton/activation/src/logic/draft/oauthDraft/oauthDraft.selector';
import { useEasySwitchDispatch, useEasySwitchSelector } from '@proton/activation/src/logic/store';
import { useApi, useCalendars, useErrorHandler, useEventManager, useGetAddressKeys } from '@proton/components/index';
import { createImporterTask } from './useStepLoadingImporting.helpers';
const useStepLoadingImporting = () => {
const api = useApi();
const [calendars = []] = useCalendars();
const getAddressKeys = useGetAddressKeys();
const errorHandler = useErrorHandler();
const { call } = useEventManager();
const dispatch = useEasySwitchDispatch();
const { availableAddresses } = useAvailableAddresses();
const [calendarsToBeCreated, setCalendarsToBeCreated] = useState<number>(0);
const [createdCalendarCount, setCreatedCalendarCount] = useState(0);
const [isCreatingCalendar, setIsCreatingCalendar] = useState(false);
const [isCreatingImportTask, setIsCreatingImportTask] = useState(false);
const importerData = useEasySwitchSelector(selectOauthImportStateImporterData);
const products = useEasySwitchSelector(selectOauthImportStateProducts);
const provider = useEasySwitchSelector(selectOauthDraftProvider);
if (!importerData || !products || !provider) {
throw new Error('Importer data, provider and products should be defined');
}
const isLabelMapping = provider === ImportProvider.GOOGLE;
useEffect(() => {
void createImporterTask({
isLabelMapping,
products,
importerData,
api,
dispatch,
getAddressKeys,
availableAddresses,
calendars,
call,
errorHandler,
setIsCreatingCalendar,
setIsCreatingImportTask,
setCalendarsToBeCreated,
increaseCalendarCount: () => {
setCreatedCalendarCount((state) => state + 1);
},
});
}, []);
return {
createdCalendarCount,
calendarsToBeCreated,
isCreatingCalendar,
isCreatingImportTask,
};
};
export default useStepLoadingImporting;
| 4,879
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth/StepPrepareOAuth.test.tsx
|
import { screen } from '@testing-library/dom';
import { ApiMailImporterFolder } from '@proton/activation/src/api/api.interface';
import MailImportFoldersParser from '@proton/activation/src/helpers/MailImportFoldersParser/MailImportFoldersParser';
import { ImportType, MailImportDestinationFolder, TIME_PERIOD } from '@proton/activation/src/interface';
import { selectOauthImportStateImporterData } from '@proton/activation/src/logic/draft/oauthDraft/oauthDraft.selector';
import { generateMockAddress } from '@proton/activation/src/tests/data/addresses';
import { prepareState } from '@proton/activation/src/tests/data/prepareState';
import { easySwitchRender } from '@proton/activation/src/tests/render';
import { MailImportFields } from '../../CustomizeMailImportModal/CustomizeMailImportModal.interface';
import StepPrepare from './StepPrepareOAuth';
import useStepPrepare from './hooks/useStepPrepareOAuth';
import useStepPrepareEmailSummary from './hooks/useStepPrepareOAuthEmailSummary';
jest.mock('./hooks/useStepPrepareOAuth', () => ({
__esModule: true,
default: jest.fn(),
}));
jest.mock('./hooks/useStepPrepareOAuthEmailSummary', () => ({
__esModule: true,
default: jest.fn(),
}));
jest.mock('@proton/activation/src/logic/draft/oauthDraft/oauthDraft.selector', () => ({
...jest.requireActual('@proton/activation/src/logic/draft/oauthDraft/oauthDraft.selector'),
selectOauthImportStateImporterData: jest.fn(),
}));
const isLabelMapping = false;
const simpleProviderFolders: ApiMailImporterFolder[] = [
{
Source: 'New Name',
Separator: '/',
Size: 10,
Flags: [],
},
];
const simpleFields: MailImportFields = {
mapping: new MailImportFoldersParser(simpleProviderFolders, isLabelMapping).folders,
importLabel: { Color: '#fff', Name: 'label', Type: 1 },
importPeriod: TIME_PERIOD.LAST_MONTH,
importAddress: generateMockAddress(1, true),
importCategoriesDestination: MailImportDestinationFolder.INBOX,
};
const emailSummary = {
fields: simpleFields,
errors: [],
summary: '',
toEmail: '',
handleSubmitCustomizeModal: () => {},
};
const mockedUseStepPrepare = useStepPrepare as jest.Mock<ReturnType<typeof useStepPrepare>>;
const mockedUseStepPrepareEmailSummary = useStepPrepareEmailSummary as jest.Mock<
ReturnType<typeof useStepPrepareEmailSummary>
>;
const mockSelectorImporterData = selectOauthImportStateImporterData as any as jest.Mock<
ReturnType<typeof selectOauthImportStateImporterData>
>;
describe('StepPrepare test the product display, only selected products should be displayed', () => {
const defaultStepPrepare = {
products: [ImportType.CALENDAR, ImportType.CONTACTS, ImportType.MAIL],
emailChecked: true,
setEmailChecked: () => {},
contactChecked: true,
setContactChecked: () => {},
calendarChecked: true,
setCalendarChecked: () => {},
importerData: prepareState.mailImport!.importerData!,
handleCancel: () => {},
handleSubmit: () => {},
emailTitle: 'title',
hasErrors: false,
enabledFeatures: {
isEmailsEnabled: true,
isContactsEnabled: true,
isCalendarsEnabled: true,
},
allCheckboxUnselected: false,
};
it('Should render all products', () => {
mockSelectorImporterData.mockImplementation(() => prepareState.mailImport?.importerData);
mockedUseStepPrepare.mockImplementation(() => defaultStepPrepare);
mockedUseStepPrepareEmailSummary.mockImplementation(() => emailSummary);
easySwitchRender(<StepPrepare />);
screen.getByTestId('StepPrepareEmailsSummary:summary');
screen.getByTestId('StepPrepareContactsSummary:summary');
screen.getByTestId('StepPrepareCalendarSummary:summary');
});
it('Should render only email product', () => {
const emailState = { ...defaultStepPrepare, products: [ImportType.MAIL] };
mockedUseStepPrepare.mockImplementation(() => emailState);
mockedUseStepPrepareEmailSummary.mockImplementation(() => emailSummary);
easySwitchRender(<StepPrepare />);
screen.getByTestId('StepPrepareEmailsSummary:summary');
expect(screen.queryByTestId('StepPrepareContactsSummary:summary')).toBeNull();
expect(screen.queryByTestId('StepPrepareCalendarSummary:summary')).toBeNull();
});
it('Should render only contact product', () => {
const emailState = { ...defaultStepPrepare, products: [ImportType.CONTACTS] };
mockedUseStepPrepare.mockImplementation(() => emailState);
mockedUseStepPrepareEmailSummary.mockImplementation(() => emailSummary);
easySwitchRender(<StepPrepare />);
expect(screen.queryByTestId('StepPrepareEmailsSummary:summary')).toBeNull();
screen.getByTestId('StepPrepareContactsSummary:summary');
expect(screen.queryByTestId('StepPrepareCalendarSummary:summary')).toBeNull();
});
it('Should render only calendar product', () => {
const emailState = { ...defaultStepPrepare, products: [ImportType.CALENDAR] };
mockedUseStepPrepare.mockImplementation(() => emailState);
mockedUseStepPrepareEmailSummary.mockImplementation(() => emailSummary);
easySwitchRender(<StepPrepare />);
expect(screen.queryByTestId('StepPrepareEmailsSummary:summary')).toBeNull();
expect(screen.queryByTestId('StepPrepareContactsSummary:summary')).toBeNull();
screen.getByTestId('StepPrepareCalendarSummary:summary');
});
});
describe('Render errors on products', () => {
const defaultStepPrepare = {
products: [ImportType.CALENDAR, ImportType.CONTACTS, ImportType.MAIL],
emailChecked: true,
setEmailChecked: () => {},
contactChecked: true,
setContactChecked: () => {},
calendarChecked: true,
setCalendarChecked: () => {},
importerData: prepareState.mailImport!.importerData!,
handleCancel: () => {},
handleSubmit: () => {},
emailTitle: 'title',
hasErrors: false,
enabledFeatures: {
isEmailsEnabled: true,
isContactsEnabled: true,
isCalendarsEnabled: true,
},
allCheckboxUnselected: false,
};
it('Should render error box if an error is present', () => {
const stepPrepareWithError = { ...defaultStepPrepare, hasErrors: true };
mockSelectorImporterData.mockImplementation(() => prepareState.mailImport?.importerData);
mockedUseStepPrepare.mockImplementation(() => stepPrepareWithError);
mockedUseStepPrepareEmailSummary.mockImplementation(() => emailSummary);
easySwitchRender(<StepPrepare />);
screen.getByTestId('StepPrepareErrorBox:container');
});
it('should disable the submit button if all checkboxes are unchecked', () => {
const noCheckboxSelected = {
...defaultStepPrepare,
emailChecked: false,
contactChecked: false,
calendarChecked: false,
allCheckboxUnselected: true,
};
mockSelectorImporterData.mockImplementation(() => prepareState.mailImport?.importerData);
mockedUseStepPrepare.mockImplementation(() => noCheckboxSelected);
mockedUseStepPrepareEmailSummary.mockImplementation(() => emailSummary);
easySwitchRender(<StepPrepare />);
const submitButton = screen.getByText('Start import');
expect(submitButton).toBeDisabled();
});
});
| 4,880
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth/StepPrepareOAuth.tsx
|
import { c } from 'ttag';
import { ImportType } from '@proton/activation/src/interface';
import { Button } from '@proton/atoms/Button';
import { ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, PrimaryButton } from '@proton/components';
import StepProductsRowItem from '../StepProducts/StepProductsRowItem';
import StepPrepareCalendarSummary from './StepPrepareOAuthCalendarSummary';
import StepPrepareContactsSummary from './StepPrepareOAuthContactsSummary';
import StepPrepareDescription from './StepPrepareOAuthDescription';
import StepPrepareEmailsSummary from './StepPrepareOAuthEmailsSummary';
import StepPrepareErrorBox from './StepPrepareOAuthErrorBox';
import useStepPrepare from './hooks/useStepPrepareOAuth';
const StepPrepare = () => {
const {
emailChecked,
setEmailChecked,
contactChecked,
setContactChecked,
calendarChecked,
setCalendarChecked,
importerData,
handleCancel,
handleSubmit,
hasErrors,
emailTitle,
enabledFeatures,
products,
allCheckboxUnselected,
} = useStepPrepare();
const { isEmailsEnabled, isCalendarsEnabled, isContactsEnabled } = enabledFeatures;
return (
<ModalTwo size="xlarge" onClose={handleCancel} open>
<ModalTwoHeader title={c('Title').t`Customize and confirm`} />
<ModalTwoContent>
<StepPrepareDescription />
<StepPrepareErrorBox errors={hasErrors} />
<div className="max-w-custom" style={{ '--max-w-custom': '30em' }}>
{products.includes(ImportType.MAIL) && (
<StepProductsRowItem
id="mail"
label={emailTitle}
value={emailChecked}
setValue={setEmailChecked}
error={importerData?.emails?.error}
disabled={!isEmailsEnabled}
>
{isEmailsEnabled && <StepPrepareEmailsSummary isSelected={emailChecked} />}
</StepProductsRowItem>
)}
{products.includes(ImportType.CONTACTS) && (
<StepProductsRowItem
id="contact"
label={c('Label').t`Contacts`}
value={contactChecked}
setValue={setContactChecked}
error={importerData?.contacts?.error}
disabled={!isContactsEnabled}
>
{isContactsEnabled && <StepPrepareContactsSummary isSelected={contactChecked} />}
</StepProductsRowItem>
)}
{products.includes(ImportType.CALENDAR) && (
<StepProductsRowItem
id="calendar"
label={c('Label').t`Calendar`}
value={calendarChecked}
setValue={setCalendarChecked}
error={importerData?.calendars?.error}
disabled={!isCalendarsEnabled}
>
{isCalendarsEnabled && <StepPrepareCalendarSummary isSelected={calendarChecked} />}
</StepProductsRowItem>
)}
</div>
</ModalTwoContent>
<ModalTwoFooter>
<Button shape="outline" onClick={handleCancel}>
{c('Action').t`Cancel`}
</Button>
<PrimaryButton onClick={handleSubmit} disabled={hasErrors || allCheckboxUnselected}>{c('Action')
.t`Start import`}</PrimaryButton>
</ModalTwoFooter>
</ModalTwo>
);
};
export default StepPrepare;
| 4,881
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth/StepPrepareOAuthCalendarSummary.tsx
|
import { c, msgid } from 'ttag';
import { updateCalendarData } from '@proton/activation/src/logic/draft/oauthDraft/oauthDraft.actions';
import { useEasySwitchDispatch } from '@proton/activation/src/logic/store';
import { Icon, UnderlineButton, useModalState } from '@proton/components';
import isTruthy from '@proton/utils/isTruthy';
import CustomizeCalendarImportModal from './CustomizeCalendarImportModal/CustomizeCalendarImportModal';
import useCustomizeCalendarImportModal from './CustomizeCalendarImportModal/useCustomizeCalendarImportModal';
interface Props {
isSelected: boolean;
}
const StepPrepareCalendarSummary = ({ isSelected }: Props) => {
const [displayCustomizeModalProps, handleDisplayCustomizeModal, renderCustomizeModal] = useModalState();
const dispatch = useEasySwitchDispatch();
const {
providerCalendarsState,
derivedValues,
activeWritableCalendars,
handleCalendarToggle,
handleMappingChange,
} = useCustomizeCalendarImportModal();
const { calendarsToBeCreatedCount, totalCalendarsCount, calendarsToBeMergedCount } = derivedValues;
const calendarCount = calendarsToBeCreatedCount + calendarsToBeMergedCount;
if (!isSelected) {
return null;
}
const handleSubmit = () => {
dispatch(updateCalendarData(providerCalendarsState));
displayCustomizeModalProps.onClose();
};
const calendarsFragment = c('Info').ngettext(
msgid`Import ${calendarCount} of ${totalCalendarsCount} calendar`,
`Import ${calendarCount} of ${totalCalendarsCount} calendars`,
totalCalendarsCount
);
const toBeCreatedFragment = calendarsToBeCreatedCount
? c('Info').ngettext(
msgid`Create ${calendarsToBeCreatedCount} new calendar`,
`Create ${calendarsToBeCreatedCount} new calendars`,
calendarsToBeCreatedCount
)
: null;
const toBeMergedFragment = calendarsToBeMergedCount
? c('Info').ngettext(
msgid`${calendarsToBeMergedCount} merged calendar`,
`${calendarsToBeMergedCount} merged calendars`,
calendarsToBeMergedCount
)
: null;
const mappingFragment = [toBeCreatedFragment, toBeMergedFragment].filter(isTruthy).join(` ${c('Info').t`and`} `);
const summary = `${calendarsFragment}: ${mappingFragment}`;
return (
<>
{derivedValues.calendarLimitReached ? (
<div className="flex color-danger">
<Icon name="exclamation-circle-filled" className="flex-align-self-center mr-2" />
{c('Error').t`Calendar limit reached`}
</div>
) : (
<div className="color-weak" data-testid="StepPrepareCalendarSummary:summary">
{summary}
</div>
)}
<UnderlineButton
onClick={() => handleDisplayCustomizeModal(true)}
className="flex-align-self-start pb-0"
>{c('Action').t`Customize`}</UnderlineButton>
{renderCustomizeModal && (
<CustomizeCalendarImportModal
handleSubmit={handleSubmit}
modalProps={displayCustomizeModalProps}
providerCalendarsState={providerCalendarsState}
derivedValues={derivedValues}
activeWritableCalendars={activeWritableCalendars}
handleCalendarToggle={handleCalendarToggle}
handleMappingChange={handleMappingChange}
/>
)}
</>
);
};
export default StepPrepareCalendarSummary;
| 4,882
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth/StepPrepareOAuthContactsSummary.tsx
|
import { c, msgid } from 'ttag';
import { selectOauthImportStateImporterData } from '@proton/activation/src/logic/draft/oauthDraft/oauthDraft.selector';
import { useEasySwitchSelector } from '@proton/activation/src/logic/store';
import { MAX_CONTACTS_PER_USER } from '@proton/shared/lib/contacts/constants';
interface Props {
isSelected: boolean;
}
const StepPrepareContactsSummary = ({ isSelected }: Props) => {
const importerData = useEasySwitchSelector(selectOauthImportStateImporterData);
const { contacts } = importerData!;
// Don't display anything if Contact isn't selected or if there is no data
if (!isSelected || contacts === undefined) {
return null;
}
return (
<span className="color-weak" data-testid="StepPrepareContactsSummary:summary">
{c('Info').ngettext(
msgid`All your contacts will be imported, up to a limit of ${MAX_CONTACTS_PER_USER}`,
`All your contacts will be imported, up to a limit of ${MAX_CONTACTS_PER_USER}`,
MAX_CONTACTS_PER_USER
)}
</span>
);
};
export default StepPrepareContactsSummary;
| 4,883
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth/StepPrepareOAuthDescription.tsx
|
import { c } from 'ttag';
import { selectOauthImportStateImporterData } from '@proton/activation/src/logic/draft/oauthDraft/oauthDraft.selector';
import { useEasySwitchSelector } from '@proton/activation/src/logic/store';
import { BRAND_NAME } from '@proton/shared/lib/constants';
const StepPrepareDescription = () => {
const importerData = useEasySwitchSelector(selectOauthImportStateImporterData);
const importedEmailAddressStrong = <strong key={importerData?.importedEmail}>{importerData?.importedEmail}</strong>;
return (
<>
<div className="mb-4">
{c('Info')
.jt`Your data is ready to import from ${importedEmailAddressStrong} to your ${BRAND_NAME} account.`}
</div>
<div>{c('Info').t`Just confirm your selection and we'll do the rest.`}</div>
</>
);
};
export default StepPrepareDescription;
| 4,884
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth/StepPrepareOAuthDisabledCheckbox.tsx
|
import { Checkbox } from '@proton/components/components';
interface Props {
id: string;
children: React.ReactNode;
}
const StepPrepareDisabledCheckbox = ({ id, children }: Props) => (
<div className="py-5 border-bottom flex label w-full cursor-default color-weak">
<Checkbox id={id} className="mr-2 flex-align-self-start" disabled />
<div className="flex flex-column flex-item-fluid">{children}</div>
</div>
);
export default StepPrepareDisabledCheckbox;
| 4,885
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth/StepPrepareOAuthEmailsSummary.tsx
|
import { c } from 'ttag';
import { ImportProvider } from '@proton/activation/src/interface';
import { selectOauthDraftProvider } from '@proton/activation/src/logic/draft/oauthDraft/oauthDraft.selector';
import { useEasySwitchSelector } from '@proton/activation/src/logic/store';
import { UnderlineButton, useModalState } from '@proton/components';
import CustomizeMailImportModal from '../../CustomizeMailImportModal/CustomizeMailImportModal';
import StepPrepareEmailsSummaryText from './StepPrepareOAuthEmailsSummaryText';
import useStepPrepareEmailSummary from './hooks/useStepPrepareOAuthEmailSummary';
interface Props {
isSelected: boolean;
}
const StepPrepareEmailsSummary = ({ isSelected }: Props) => {
const provider = useEasySwitchSelector(selectOauthDraftProvider);
const [displayCustomizeModalProps, handleDisplayCustomizeModal, renderCustomizeModal] = useModalState();
const { fields, errors, summary, toEmail, handleSubmitCustomizeModal } = useStepPrepareEmailSummary({
handleCloseCustomizeModal: () => handleDisplayCustomizeModal(false),
});
if (!isSelected) {
return null;
}
return (
<>
<StepPrepareEmailsSummaryText label={fields.importLabel} errors={errors} summary={summary} />
<UnderlineButton
className="flex-align-self-start pb-0"
onClick={() => handleDisplayCustomizeModal(true)}
>{c('Action').t`Customize`}</UnderlineButton>
{renderCustomizeModal && (
<CustomizeMailImportModal
displayCategories={provider === ImportProvider.GOOGLE}
fields={fields}
foldersOpened={errors.length > 0}
importedEmail={toEmail}
isLabelMapping={provider === ImportProvider.GOOGLE}
modalProps={displayCustomizeModalProps}
onSubmit={handleSubmitCustomizeModal}
/>
)}
</>
);
};
export default StepPrepareEmailsSummary;
| 4,886
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth/StepPrepareOAuthEmailsSummaryError.tsx
|
import { c } from 'ttag';
import { MailImportPayloadError } from '@proton/activation/src/interface';
import { Icon } from '@proton/components';
import { MAIL_APP_NAME } from '@proton/shared/lib/constants';
interface Props {
errors: MailImportPayloadError[];
}
const StepPrepareEmailsSummaryError = ({ errors }: Props) => {
return (
<div className="flex color-danger">
<Icon name="exclamation-circle-filled" className="mr-2 flex-nowrap" style={{ marginTop: 4 }} />
<div className="flex-item-fluid">
{errors.includes(MailImportPayloadError.MAX_FOLDERS_LIMIT_REACHED) && (
<div className="mb-4">
{c('Error')
.t`There are too many folders in your external account. Please customize the import to delete some folders.`}
</div>
)}
{errors.includes(MailImportPayloadError.LABEL_NAMES_TOO_LONG) && (
<div className="mb-4">
{c('Error')
.t`Some of your label names exceed ${MAIL_APP_NAME}'s maximum character limit. Please customize the import to edit these names.`}
</div>
)}
{errors.includes(MailImportPayloadError.FOLDER_NAMES_TOO_LONG) && (
<div className="mb-4">
{c('Error')
.t`Some of your folder names exceed ${MAIL_APP_NAME}'s maximum character limit. Please customize the import to edit these names.`}
</div>
)}
{errors.includes(MailImportPayloadError.UNAVAILABLE_NAMES) && (
<div className="mb-4">
{c('Error')
.t`Some of your label names are unavailable. Please customize the import to edit these names.`}
</div>
)}
{errors.includes(MailImportPayloadError.RESERVED_NAMES) && (
<div className="mb-4">
{c('Error')
.t`Some of your label names are reserved. Please customize the import to edit these names.`}
</div>
)}
</div>
</div>
);
};
export default StepPrepareEmailsSummaryError;
| 4,887
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth/StepPrepareOAuthEmailsSummaryText.tsx
|
import { MailImportPayloadError } from '@proton/activation/src/interface';
import { LabelStack } from '@proton/components';
import { Label } from '@proton/shared/lib/interfaces';
import StepPrepareEmailsSummaryError from './StepPrepareOAuthEmailsSummaryError';
interface Props {
errors: MailImportPayloadError[];
label: Pick<Label, 'Color' | 'Name' | 'Type'>;
summary: string;
}
const StepPrepareEmailsSummaryText = ({ errors, summary, label }: Props) => {
return (
<>
{errors.length > 0 ? (
<StepPrepareEmailsSummaryError errors={errors} />
) : (
<div className="color-weak" data-testid="StepPrepareEmailsSummary:summary">
<span>
{summary}{' '}
<LabelStack
key="label"
labels={[
{
name: label.Name,
color: label.Color,
},
]}
/>
</span>
</div>
)}
</>
);
};
export default StepPrepareEmailsSummaryText;
| 4,888
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth/StepPrepareOAuthErrorBox.tsx
|
import { c, msgid } from 'ttag';
interface Props {
errors: boolean;
}
const StepPrepareErrorBox = ({ errors }: Props) => {
if (!errors) {
return null;
}
return (
<div
className="rounded-lg p-4 mt-4 bg-danger color-white text-semibold border-none"
data-testid="StepPrepareErrorBox:container"
>
{c('Error').ngettext(
msgid`Please fix the highlighted conflict to proceed.`,
`Please fix the highlighted conflicts to proceed.`,
0
)}
</div>
);
};
export default StepPrepareErrorBox;
| 4,889
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth/CustomizeCalendarImportModal/CustomizeCalendarImportModal.test.tsx
|
import { fireEvent, screen } from '@testing-library/dom';
import useAvailableAddresses from '@proton/activation/src/hooks/useAvailableAddresses';
import { ImporterCalendar } from '@proton/activation/src/logic/draft/oauthDraft/oauthDraft.interface';
import { selectOauthImportStateImporterData } from '@proton/activation/src/logic/draft/oauthDraft/oauthDraft.selector';
import { generateMockAddressArray } from '@proton/activation/src/tests/data/addresses';
import { prepareState } from '@proton/activation/src/tests/data/prepareState';
import { easySwitchRender } from '@proton/activation/src/tests/render';
import { ModalStateProps } from '@proton/components/index';
import { CALENDAR_DISPLAY, CALENDAR_TYPE } from '@proton/shared/lib/calendar/constants';
import { CalendarMember, VisualCalendar } from '@proton/shared/lib/interfaces/calendar';
import CustomizeCalendarImportModal from './CustomizeCalendarImportModal';
import { DerivedCalendarType } from './useCustomizeCalendarImportModal';
const modalProps: ModalStateProps = {
key: 'modalProps',
open: true,
onClose: () => {},
onExit: () => {},
};
const calendarMember: CalendarMember = {
ID: 'id',
CalendarID: 'CalendarID',
AddressID: 'AddressID',
Flags: 1,
Name: 'Name',
Description: 'Description',
Email: 'Email',
Permissions: 1,
Color: 'Color',
Display: CALENDAR_DISPLAY.VISIBLE,
Priority: 1,
};
const visualCalendar: VisualCalendar = {
Owner: { Email: 'testing@proton.ch' },
Members: [calendarMember],
ID: 'id',
Type: CALENDAR_TYPE.PERSONAL,
Name: 'visualCalendar',
Description: 'visualCalendar',
Color: 'visualCalendar',
Display: CALENDAR_DISPLAY.VISIBLE,
Email: 'testing@proton.ch',
Flags: 1,
Permissions: 1,
Priority: 1,
};
const importerCalendar: ImporterCalendar = {
source: 'testing',
description: 'testing',
id: 'testing',
checked: true,
};
const derivedValuesNoErrors: DerivedCalendarType = {
selectedCalendars: [importerCalendar],
calendarsToBeCreatedCount: 1,
calendarLimitReached: false,
selectedCalendarsCount: 1,
disabled: false,
calendarsToFixCount: 0,
canMerge: true,
totalCalendarsCount: 10,
calendarsToBeMergedCount: 2,
};
jest.mock('@proton/activation/src/logic/draft/oauthDraft/oauthDraft.selector', () => ({
...jest.requireActual('@proton/activation/src/logic/draft/oauthDraft/oauthDraft.selector'),
selectOauthImportStateImporterData: jest.fn(),
}));
const addresses = generateMockAddressArray(3, true);
const mockUseAddressValue = {
availableAddresses: addresses,
loading: false,
defaultAddress: addresses[0],
};
jest.mock('@proton/activation/src/hooks/useAvailableAddresses');
const mockUseAvailableAddresses = useAvailableAddresses as jest.MockedFunction<any>;
const mockSelectorImporterData = selectOauthImportStateImporterData as any as jest.Mock<
ReturnType<typeof selectOauthImportStateImporterData>
>;
describe('CustomizeCalendarImportModal', () => {
it('Should render customize calendar modal', () => {
mockUseAvailableAddresses.mockReturnValue(mockUseAddressValue);
mockSelectorImporterData.mockImplementation(() => prepareState.mailImport?.importerData);
const standardProps = {
modalProps,
providerCalendarsState: [importerCalendar],
derivedValues: derivedValuesNoErrors,
activeWritableCalendars: [visualCalendar],
handleSubmit: () => {},
handleCalendarToggle: () => {},
handleMappingChange: () => {},
};
easySwitchRender(<CustomizeCalendarImportModal {...standardProps} />);
screen.getByTestId('CustomizeCalendarImportModal:description');
});
it('Should render calendar limit reached', () => {
mockUseAvailableAddresses.mockReturnValue(mockUseAddressValue);
mockSelectorImporterData.mockImplementation(() => prepareState.mailImport?.importerData);
const derivedValuesWithErrors = { ...derivedValuesNoErrors, calendarLimitReached: true };
const standardProps = {
modalProps,
providerCalendarsState: [importerCalendar],
derivedValues: derivedValuesWithErrors,
activeWritableCalendars: [visualCalendar],
handleSubmit: () => {},
handleCalendarToggle: () => {},
handleMappingChange: () => {},
};
easySwitchRender(<CustomizeCalendarImportModal {...standardProps} />);
screen.getByTestId('CustomizeCalendarImportModalLimitReached:container');
});
it('Should render different elements if cannot merge', () => {
mockUseAvailableAddresses.mockReturnValue(mockUseAddressValue);
mockSelectorImporterData.mockImplementation(() => prepareState.mailImport?.importerData);
const derivedValuesNoMerge = { ...derivedValuesNoErrors, canMerge: false };
const standardProps = {
modalProps,
providerCalendarsState: [importerCalendar],
derivedValues: derivedValuesNoMerge,
activeWritableCalendars: [visualCalendar],
handleSubmit: () => {},
handleCalendarToggle: () => {},
handleMappingChange: () => {},
};
easySwitchRender(<CustomizeCalendarImportModal {...standardProps} />);
screen.getByTestId('CustomizeCalendarImportModal:description');
});
it('Should click the checkbox of a calendar', () => {
mockUseAvailableAddresses.mockReturnValue(mockUseAddressValue);
mockSelectorImporterData.mockImplementation(() => prepareState.mailImport?.importerData);
const standardProps = {
modalProps,
providerCalendarsState: [importerCalendar],
derivedValues: derivedValuesNoErrors,
activeWritableCalendars: [visualCalendar],
handleSubmit: () => {},
handleCalendarToggle: () => {},
handleMappingChange: () => {},
};
easySwitchRender(<CustomizeCalendarImportModal {...standardProps} />);
const checkboxes = screen.getAllByTestId('CustomizeCalendarImportRow:checkbox');
expect(checkboxes).toHaveLength(standardProps.providerCalendarsState.length);
fireEvent.click(checkboxes[0]);
});
});
| 4,890
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth/CustomizeCalendarImportModal/CustomizeCalendarImportModal.tsx
|
import { c } from 'ttag';
import { ImporterCalendar } from '@proton/activation/src/logic/draft/oauthDraft/oauthDraft.interface';
import { Button } from '@proton/atoms/Button';
import { ModalStateProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader } from '@proton/components';
import { PrimaryButton } from '@proton/components/components';
import { BRAND_NAME } from '@proton/shared/lib/constants';
import { VisualCalendar } from '@proton/shared/lib/interfaces/calendar';
import CustomizeCalendarImportModalLimitReached from './CustomizeCalendarImportModalLimitReached';
import CustomizeCalendarImportModalTableHeader from './CustomizeCalendarImportModalTableHeader';
import CustomizeCalendarImportRow from './CustomizeCalendarImportRow';
import { DerivedCalendarType } from './useCustomizeCalendarImportModal';
interface Props {
modalProps: ModalStateProps;
providerCalendarsState: ImporterCalendar[];
derivedValues: DerivedCalendarType;
activeWritableCalendars: VisualCalendar[];
handleSubmit: () => void;
handleCalendarToggle: (cal: ImporterCalendar) => void;
handleMappingChange: (cal: ImporterCalendar, destinationCalendar?: VisualCalendar) => void;
}
const CustomizeCalendarImportModal = ({
modalProps,
providerCalendarsState,
derivedValues,
activeWritableCalendars,
handleSubmit,
handleCalendarToggle,
handleMappingChange,
}: Props) => {
const {
canMerge,
calendarLimitReached,
calendarsToFixCount,
calendarsToBeCreatedCount,
selectedCalendarsCount,
selectedCalendars,
disabled,
} = derivedValues;
return (
<ModalTwo {...modalProps} size="xlarge">
<ModalTwoHeader title={c('Title').t`Customize calendar import`} />
<ModalTwoContent>
<div className="mb-4" data-testid="CustomizeCalendarImportModal:description">
{c('Info')
.t`Select which calendars to import. A new calendar will be created for each imported calendar according to the number of calendars available in your plan.`}
{canMerge &&
` ${c('Info').t`You can also merge imported calendars with existing ${BRAND_NAME} calendars.`}`}
</div>
{calendarLimitReached && (
<CustomizeCalendarImportModalLimitReached
canMerge={canMerge}
calendarsToFixCount={calendarsToFixCount}
/>
)}
<CustomizeCalendarImportModalTableHeader
calendarLimitReached={calendarLimitReached}
calendarsToBeCreatedCount={calendarsToBeCreatedCount}
selectedCalendarsTotal={selectedCalendarsCount}
selectedCalendars={selectedCalendars}
/>
{providerCalendarsState.map((calendar) => (
<CustomizeCalendarImportRow
key={calendar.id}
calendar={calendar}
toggleChecked={handleCalendarToggle}
activeCalendars={activeWritableCalendars}
updateCalendarMapping={handleMappingChange}
calendarLimitReached={calendarLimitReached}
/>
))}
</ModalTwoContent>
<ModalTwoFooter>
<Button shape="outline" onClick={() => modalProps.onClose()}>{c('Action').t`Cancel`}</Button>
<PrimaryButton disabled={disabled} onClick={handleSubmit}>{c('Action').t`Save`}</PrimaryButton>
</ModalTwoFooter>
</ModalTwo>
);
};
export default CustomizeCalendarImportModal;
| 4,891
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth/CustomizeCalendarImportModal/CustomizeCalendarImportModalLimitReached.tsx
|
import { c, msgid } from 'ttag';
import { BRAND_NAME } from '@proton/shared/lib/constants';
interface Props {
canMerge: boolean;
calendarsToFixCount: number;
}
const CustomizeCalendarImportModalLimitReached = ({ canMerge, calendarsToFixCount }: Props) => {
return (
<div
className="rounded-lg p-4 mb-4 bg-danger color-white text-semibold border-none"
data-testid="CustomizeCalendarImportModalLimitReached:container"
>
{c('Error').t`You have reached the maximum number of calendars. Some calendars couldn't be imported.`}
<ul className="m-0">
<li>
{canMerge
? c('Error').ngettext(
msgid`Deselect at least ${calendarsToFixCount} calendar or`,
`Deselect at least ${calendarsToFixCount} calendars or`,
calendarsToFixCount
)
: c('Error').ngettext(
msgid`Deselect at least ${calendarsToFixCount} calendar`,
`Deselect at least ${calendarsToFixCount} calendars`,
calendarsToFixCount
)}
</li>
{canMerge && (
<li>
{c('Error').ngettext(
msgid`Merge at least ${calendarsToFixCount} calendar with an existing ${BRAND_NAME} calendar`,
`Merge at least ${calendarsToFixCount} calendars with existing ${BRAND_NAME} calendars`,
calendarsToFixCount
)}
</li>
)}
</ul>
</div>
);
};
export default CustomizeCalendarImportModalLimitReached;
| 4,892
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth/CustomizeCalendarImportModal/CustomizeCalendarImportModalTableHeader.tsx
|
import { c, msgid } from 'ttag';
import useAvailableAddresses from '@proton/activation/src/hooks/useAvailableAddresses';
import { selectOauthImportStateImporterData } from '@proton/activation/src/logic/draft/oauthDraft/oauthDraft.selector';
import { useEasySwitchSelector } from '@proton/activation/src/logic/store';
import { Icon } from '@proton/components';
import clsx from '@proton/utils/clsx';
interface Props {
calendarLimitReached: boolean;
calendarsToBeCreatedCount: number;
selectedCalendarsTotal: number;
selectedCalendars: any[];
}
const CustomizeCalendarImportModalTableHeader = ({
calendarLimitReached,
calendarsToBeCreatedCount,
selectedCalendarsTotal,
selectedCalendars,
}: Props) => {
const { defaultAddress } = useAvailableAddresses();
const importerData = useEasySwitchSelector(selectOauthImportStateImporterData);
const providerCalendars = importerData?.calendars?.calendars!;
const importedEmailAddress = importerData?.importedEmail;
// translator: the variables here are the number of selected calendar and number of total calendar. Example of the complete sentence: "5 of 7 calendars"
const calendarsSelectedCopy = c('Info').ngettext(
msgid`${selectedCalendarsTotal} of ${providerCalendars.length} calendar`,
`${selectedCalendarsTotal} of ${providerCalendars.length} calendars`,
providerCalendars.length
);
// translator: the variable ${calendarsToBeCreatedCount} is the number of calendars to be created. Example of the complete sentence: "5 new calendars"
const calendarsToBeCreatedCopy = c('Info').ngettext(
msgid`${calendarsToBeCreatedCount} new calendar`,
`${calendarsToBeCreatedCount} new calendars`,
calendarsToBeCreatedCount
);
const calendarsToBeMergedCount = selectedCalendars.length - calendarsToBeCreatedCount;
// translator: the variable ${calendarsToBeMergedCount} is the number of calendars to be merged with an existing Proton calendar. Example of the complete sentence: "5 merged calendars".
const calendarsToBeMergedCopy = c('Info').ngettext(
msgid`${calendarsToBeMergedCount} merged calendar`,
`${calendarsToBeMergedCount} merged calendars`,
calendarsToBeMergedCount
);
const importSummaryRenderer = () => {
return (
<>
{!!calendarsToBeCreatedCount && calendarsToBeCreatedCopy}
{!!calendarsToBeCreatedCount && !!calendarsToBeMergedCount && <br />}
{!!calendarsToBeMergedCount && calendarsToBeMergedCopy}
</>
);
};
return (
<div className="flex mt-8">
<div className="flex-item-fluid">
<div className="text-sm text-bold m-0 lh100 mb-2">{c('Info').t`Import from`}</div>
<strong className="block mb-2">{importedEmailAddress}</strong>
<div className="color-weak">{calendarsSelectedCopy}</div>
</div>
<div className="flex-item-fluid">
<div className="text-sm text-bold m-0 lh100 mb-2">{c('Info').t`Create in`}</div>
<strong className="block mb-2">{defaultAddress.Email}</strong>
{selectedCalendarsTotal > 0 && (
<div className={clsx(['flex', calendarLimitReached ? 'color-danger' : 'color-weak'])}>
{calendarLimitReached && (
<Icon
name="exclamation-circle-filled"
className="color-danger flex-align-self-center mr-2"
/>
)}
{importSummaryRenderer()}
</div>
)}
</div>
</div>
);
};
export default CustomizeCalendarImportModalTableHeader;
| 4,893
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth/CustomizeCalendarImportModal/CustomizeCalendarImportRow.tsx
|
import { ImporterCalendar } from '@proton/activation/src/logic/draft/oauthDraft/oauthDraft.interface';
import { Checkbox, Label } from '@proton/components/components';
import { VisualCalendar } from '@proton/shared/lib/interfaces/calendar';
import clsx from '@proton/utils/clsx';
import CustomizeCalendarImportRowSelect from './CustomizeCalendarImportRowSelect';
interface Props {
calendar: ImporterCalendar;
calendarLimitReached: boolean;
activeCalendars: VisualCalendar[];
toggleChecked: (calendar: ImporterCalendar) => void;
updateCalendarMapping: (calendar: ImporterCalendar, destinationCalendar?: VisualCalendar) => void;
}
const CustomizeCalendarImportRow = ({
calendar,
calendarLimitReached,
activeCalendars,
toggleChecked,
updateCalendarMapping,
}: Props) => {
const { checked, source } = calendar;
return (
<Label htmlFor={calendar.id} className="w-full label flex flex-flex-align-items-center py-7 border-bottom">
<div className={clsx(['flex flex-item-fluid', checked && 'mr-4'])}>
<Checkbox
id={calendar.id}
checked={checked}
onChange={() => toggleChecked(calendar)}
className="mr-2"
data-testid="CustomizeCalendarImportRow:checkbox"
/>
<div className="flex-item-fluid text-ellipsis" title={source}>
{source}
</div>
</div>
{checked && (
<div className="flex-item-fluid">
{
<CustomizeCalendarImportRowSelect
calendar={calendar}
calendarLimitReached={calendarLimitReached}
activeCalendars={activeCalendars}
updateCalendarMapping={updateCalendarMapping}
/>
}
</div>
)}
</Label>
);
};
export default CustomizeCalendarImportRow;
| 4,894
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth/CustomizeCalendarImportModal/CustomizeCalendarImportRowSelect.tsx
|
import { c } from 'ttag';
import { CALENDAR_TO_BE_CREATED_PREFIX } from '@proton/activation/src/constants';
import { ImporterCalendar } from '@proton/activation/src/logic/draft/oauthDraft/oauthDraft.interface';
import { LabelStack, Option, SelectTwo } from '@proton/components/components';
import { VisualCalendar } from '@proton/shared/lib/interfaces/calendar';
import clsx from '@proton/utils/clsx';
interface Props {
calendar: ImporterCalendar;
calendarLimitReached: boolean;
activeCalendars: VisualCalendar[];
updateCalendarMapping: (calendar: ImporterCalendar, destinationCalendar?: VisualCalendar) => void;
}
const CustomizeCalendarImportRowSelect = ({
calendar,
calendarLimitReached,
activeCalendars,
updateCalendarMapping,
}: Props) => {
const { source } = calendar;
const options = activeCalendars.map(({ ID, Name }) => <Option key={ID} value={ID} title={Name} />);
const calendarToBeCreatedValue = `${CALENDAR_TO_BE_CREATED_PREFIX}${calendar.source}`;
const value = calendar.mergedTo ? calendar.mergedTo.ID : calendar.source;
// translator; when managing calendar import, calendars can be created or merged. The text is displayed next to the calendar row and the value can be "merged" (this case) or "new"
const mergedLabel = c('Info').t`Merged`;
// translator; when managing calendar import, calendars can be created or merged. The text is displayed next to the calendar row and the value can be "merged" or "new" (this case)
const newLabel = c('Info').t`New`;
const newMergeLabel = (
<LabelStack
labels={[
{
name: !!calendar.mergedTo ? mergedLabel : newLabel,
},
]}
/>
);
const handleMappingChange = (id: string) => {
const selectedActiveCalendar = activeCalendars.find((cal) => cal.ID === id);
updateCalendarMapping(calendar, selectedActiveCalendar);
};
const createNewCalendarLabel = c('Option group label').t`Create new calendar`;
const mergeCalendarLabel = c('Option group label').t`Merge with calendar`;
return (
<div className="flex flex-nowrap">
{options.length > 0 ? (
<>
<div className="flex-item-fluid mr-4">
<SelectTwo
value={value}
onChange={({ value }) => handleMappingChange(value)}
className={clsx([calendarLimitReached && 'border-danger'])}
>
{[
<li className="dropdown-item" key="label-create">
<span
className="w-full px-4 py-2 block text-ellipsis text-left outline-none text-semibold"
title={createNewCalendarLabel}
>
{createNewCalendarLabel}
</span>
</li>,
<Option
key={calendarToBeCreatedValue}
value={calendar.source}
title={source}
truncate
/>,
<hr key="separator" className="my-2" />,
<li className="dropdown-item" key="label-merge">
<span
className="w-full px-4 py-2 block text-ellipsis text-left outline-none text-semibold"
title={mergeCalendarLabel}
>
{mergeCalendarLabel}
</span>
</li>,
...options,
]}
</SelectTwo>
</div>
<div className="flex-item-noshrink flex-align-self-center">{newMergeLabel}</div>
</>
) : (
<>
<div className="mr-4 text-ellipsis" title={source}>
{source}
</div>
<div className="flex-item-noshrink flex-align-self-center">{newMergeLabel}</div>
</>
)}
</div>
);
};
export default CustomizeCalendarImportRowSelect;
| 4,895
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth/CustomizeCalendarImportModal/useCustomizeCalendarImportModal.ts
|
import { useState } from 'react';
import { ImporterCalendar } from '@proton/activation/src/logic/draft/oauthDraft/oauthDraft.interface';
import { selectOauthImportStateImporterData } from '@proton/activation/src/logic/draft/oauthDraft/oauthDraft.selector';
import { useEasySwitchSelector } from '@proton/activation/src/logic/store';
import { useCalendars, useUser } from '@proton/components';
import {
getProbablyActiveCalendars,
getVisualCalendars,
getWritableCalendars,
} from '@proton/shared/lib/calendar/calendar';
import { willUserReachCalendarsLimit } from '@proton/shared/lib/calendar/calendarLimits';
import { MAX_CALENDARS_FREE, MAX_CALENDARS_PAID } from '@proton/shared/lib/calendar/constants';
import { VisualCalendar } from '@proton/shared/lib/interfaces/calendar';
export interface DerivedCalendarType {
selectedCalendars: ImporterCalendar[];
calendarsToBeCreatedCount: number;
calendarLimitReached: boolean;
selectedCalendarsCount: number;
disabled: boolean;
calendarsToFixCount: number;
canMerge: boolean;
totalCalendarsCount: number;
calendarsToBeMergedCount: number;
}
const useCustomizeCalendarImportModal = () => {
const [calendars = []] = useCalendars();
const [user] = useUser();
const importerData = useEasySwitchSelector(selectOauthImportStateImporterData);
const providerCalendars = importerData?.calendars?.calendars!;
const visualCalendars = getVisualCalendars(calendars);
const activeWritableCalendars = getWritableCalendars(getProbablyActiveCalendars(visualCalendars));
const [providerCalendarsState, setProviderCalendarsState] = useState<ImporterCalendar[]>(
providerCalendars.map((calendar) => {
return {
...calendar,
newCalendar: !activeWritableCalendars.some(({ ID }) => ID === calendar.id),
};
})
);
const handleCalendarToggle = (cal: ImporterCalendar) => {
const updatedCalendar = providerCalendarsState.map((item) => {
if (item.id === cal.id) {
return { ...item, checked: !item.checked };
}
return item;
});
setProviderCalendarsState(updatedCalendar);
};
const handleMappingChange = (cal: ImporterCalendar, destinationCalendar?: VisualCalendar) => {
const updatedCalendar = providerCalendarsState.map((item) => {
if (item.id === cal.id) {
return { ...item, mergedTo: destinationCalendar, newCalendar: !Boolean(destinationCalendar) };
}
return item;
});
setProviderCalendarsState(updatedCalendar);
};
const selectedCalendars = providerCalendarsState.filter((x) => x.checked);
const calendarsToBeCreatedCount = selectedCalendars.filter(({ newCalendar }) => newCalendar).length;
const calendarLimitReached = willUserReachCalendarsLimit(
visualCalendars,
calendarsToBeCreatedCount,
!user.hasPaidMail
);
const selectedCalendarsCount = selectedCalendars.length;
const disabled = calendarLimitReached || selectedCalendarsCount === 0;
const canMerge = activeWritableCalendars.length > 0;
const totalCalendarsCount = providerCalendarsState.length;
const calendarsToBeMergedCount = providerCalendarsState.filter((cal) => !!cal.mergedTo).length;
const maxCalendars = user.hasPaidMail ? MAX_CALENDARS_PAID : MAX_CALENDARS_FREE;
const totalCalendars = calendarsToBeCreatedCount + visualCalendars.length;
const calendarsToFixCount = totalCalendars - maxCalendars;
const derivedValues: DerivedCalendarType = {
calendarsToBeCreatedCount,
calendarsToBeMergedCount,
selectedCalendarsCount,
totalCalendarsCount,
calendarsToFixCount,
calendarLimitReached,
disabled,
canMerge,
selectedCalendars,
};
return {
providerCalendars,
derivedValues,
providerCalendarsState,
setProviderCalendarsState,
activeWritableCalendars,
handleCalendarToggle,
handleMappingChange,
};
};
export default useCustomizeCalendarImportModal;
| 4,896
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth/hooks/useStepPrepareOAuth.helpers.test.ts
|
import { MailImportFolder } from '@proton/activation/src/helpers/MailImportFoldersParser/MailImportFoldersParser';
import {
ImportType,
MailImportDestinationFolder,
MailImportGmailCategories,
TIME_PERIOD,
} from '@proton/activation/src/interface';
import { ImporterCalendar, ImporterData } from '@proton/activation/src/logic/draft/oauthDraft/oauthDraft.interface';
import { generateMockAddress } from '@proton/activation/src/tests/data/addresses';
import { Label } from '@proton/shared/lib/interfaces';
import { Folder } from '@proton/shared/lib/interfaces/Folder';
import { VisualCalendar } from '@proton/shared/lib/interfaces/calendar';
import { generateOwnedPersonalCalendars } from '@proton/testing/lib/builders';
import { getMailCustomLabel, importerHasErrors } from './useStepPrepareOAuth.helpers';
const dummyCalendar: ImporterCalendar = {
source: 'source',
description: 'description',
id: 'id 1',
checked: true,
};
const dummyFolder: MailImportFolder = {
id: 'id',
checked: true,
color: 'test color',
isSystemFolderChild: false,
folderChildIDS: [''],
protonPath: [
'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean m',
],
providerPath: ['providerPath'],
separator: '/',
size: 0,
category: undefined,
folderParentID: '',
systemFolder: MailImportDestinationFolder.ARCHIVE,
};
const dummyShortPathFolder: MailImportFolder = {
id: 'id',
checked: true,
color: 'test color',
isSystemFolderChild: false,
folderChildIDS: [''],
protonPath: ['Lorem'],
providerPath: ['providerPath'],
separator: '/',
size: 0,
category: undefined,
folderParentID: '',
systemFolder: MailImportDestinationFolder.ARCHIVE,
};
describe('getMailCustomLabel', () => {
it('Should return the appropriate mail label', () => {
const labelBigBang = getMailCustomLabel(TIME_PERIOD.BIG_BANG);
expect(labelBigBang).toBe('Emails (all messages)');
const labelLastYear = getMailCustomLabel(TIME_PERIOD.LAST_YEAR);
expect(labelLastYear).toBe('Emails (last 12 months)');
const label3Month = getMailCustomLabel(TIME_PERIOD.LAST_3_MONTHS);
expect(label3Month).toBe('Emails (last 3 months)');
const label1Month = getMailCustomLabel(TIME_PERIOD.LAST_MONTH);
expect(label1Month).toBe('Emails (last month)');
const labelDefault = getMailCustomLabel();
expect(labelDefault).toBe('Email');
});
});
describe('importerHasErrors calendar tests', () => {
it('Should return an error if number of calendars exceed MAX_CALENDARS_PAID for paid user (max 25)', () => {
const dummyCalendarArray = Array(20).fill(dummyCalendar);
const products: ImportType[] = [ImportType.CALENDAR];
const importerData: ImporterData = {
importedEmail: 'test@proton.me',
importerId: '1',
calendars: { calendars: dummyCalendarArray },
};
const labels: Label[] = [];
const folders: Folder[] = [];
const calendars: VisualCalendar[] = generateOwnedPersonalCalendars(10);
const mailChecked = false;
const calendarChecked = true;
const isFreeUser = false;
const errors = importerHasErrors(
products,
importerData,
labels,
folders,
calendars,
mailChecked,
calendarChecked,
true,
isFreeUser
);
expect(errors).toBe(true);
});
it('Should NOT return an error if number of calendars is below MAX_CALENDARS_PAID for paid user (max 25)', () => {
const dummyCalendarArray = Array(20).fill(dummyCalendar);
const products: ImportType[] = [ImportType.CALENDAR];
const importerData: ImporterData = {
importedEmail: 'test@proton.me',
importerId: '1',
calendars: { calendars: dummyCalendarArray },
};
const labels: Label[] = [];
const folders: Folder[] = [];
const calendars: VisualCalendar[] = generateOwnedPersonalCalendars(2);
const mailChecked = false;
const calendarChecked = true;
const isFreeUser = false;
const errors = importerHasErrors(
products,
importerData,
labels,
folders,
calendars,
mailChecked,
calendarChecked,
true,
isFreeUser
);
expect(errors).toBe(false);
});
it('Should return an error if number of calendars exceed MAX_CALENDARS_FREE for free user (max 3)', () => {
const dummyCalendarArray = Array(25).fill(dummyCalendar);
const products: ImportType[] = [ImportType.CALENDAR];
const importerData: ImporterData = {
importedEmail: 'test@proton.me',
importerId: '1',
calendars: { calendars: dummyCalendarArray },
};
const labels: Label[] = [];
const folders: Folder[] = [];
const calendars: VisualCalendar[] = generateOwnedPersonalCalendars(10);
const mailChecked = false;
const calendarChecked = true;
const isFreeUser = true;
const errors = importerHasErrors(
products,
importerData,
labels,
folders,
calendars,
mailChecked,
calendarChecked,
true,
isFreeUser
);
expect(errors).toBe(true);
});
it('Should NOT return an error if number of calendars is below MAX_CALENDARS_FREE for paid user (max 3)', () => {
const dummyCalendarArray = Array(1).fill(dummyCalendar);
const products: ImportType[] = [ImportType.CALENDAR];
const importerData: ImporterData = {
importedEmail: 'test@proton.me',
importerId: '1',
calendars: { calendars: dummyCalendarArray },
};
const labels: Label[] = [];
const folders: Folder[] = [];
const calendars: VisualCalendar[] = generateOwnedPersonalCalendars(1);
const mailChecked = false;
const calendarChecked = true;
const isFreeUser = true;
const errors = importerHasErrors(
products,
importerData,
labels,
folders,
calendars,
mailChecked,
calendarChecked,
true,
isFreeUser
);
expect(errors).toBe(false);
});
});
describe('importerHasErrors test check and general behavior', () => {
it('Should not return an error if number of calendars exceed MAX_CALENDARS_PAID but no calendar product', () => {
const dummyCalendarArray = Array(20).fill(dummyCalendar);
const products: ImportType[] = [ImportType.CONTACTS];
const importerData: ImporterData = {
importedEmail: 'test@proton.me',
importerId: '1',
calendars: { calendars: dummyCalendarArray },
};
const labels: Label[] = [];
const folders: Folder[] = [];
const calendars: VisualCalendar[] = generateOwnedPersonalCalendars(1);
const mailChecked = false;
const calendarChecked = true;
const errors = importerHasErrors(
products,
importerData,
labels,
folders,
calendars,
mailChecked,
calendarChecked,
true,
true
);
expect(errors).toBe(false);
});
it('Should not return an error if number of calendars exceed MAX_CALENDARS_PAID but calendar not checked', () => {
const dummyCalendarArray = Array(20).fill(dummyCalendar);
const products: ImportType[] = [ImportType.CALENDAR];
const importerData: ImporterData = {
importedEmail: 'test@proton.me',
importerId: '1',
calendars: { calendars: dummyCalendarArray },
};
const labels: Label[] = [];
const folders: Folder[] = [];
const calendars: VisualCalendar[] = generateOwnedPersonalCalendars(1);
const mailChecked = false;
const calendarChecked = false;
const errors = importerHasErrors(
products,
importerData,
labels,
folders,
calendars,
mailChecked,
calendarChecked,
true,
false
);
expect(errors).toBe(false);
});
it('Should return no errors', () => {
const products: ImportType[] = [ImportType.CONTACTS];
const importerData: ImporterData = { importedEmail: 'test@proton.me', importerId: '1' };
const labels: Label[] = [];
const folders: Folder[] = [];
const calendars: VisualCalendar[] = [];
const mailChecked = false;
const calendarChecked = false;
const errors = importerHasErrors(
products,
importerData,
labels,
folders,
calendars,
mailChecked,
calendarChecked,
true,
true
);
expect(errors).toBe(false);
});
it('Should return an error if email mapping has errors', () => {
const products: ImportType[] = [ImportType.MAIL];
const importerData: ImporterData = {
importedEmail: 'test@proton.me',
importerId: '1',
emails: {
fields: {
importAddress: generateMockAddress(0, true),
mapping: [dummyFolder, dummyFolder],
importPeriod: TIME_PERIOD.BIG_BANG,
importLabel: { Color: 'red', Name: 'name', Type: 1 },
importCategoriesDestination: MailImportDestinationFolder.ALL_DRAFTS,
},
},
};
const labels: Label[] = [];
const folders: Folder[] = [
{
ID: 'id',
Name: 'path',
Color: 'red',
Path: 'path',
Expanded: 1,
Type: 1,
Order: 1,
ParentID: '',
Notify: 1,
},
];
const calendars: VisualCalendar[] = [];
const mailChecked = true;
const calendarChecked = false;
const errors = importerHasErrors(
products,
importerData,
labels,
folders,
calendars,
mailChecked,
calendarChecked,
true,
false
);
expect(errors).toBe(true);
});
it('Should not return an error if email mapping has errors but is not in products', () => {
const products: ImportType[] = [ImportType.CONTACTS];
const importerData: ImporterData = {
importedEmail: 'test@proton.me',
importerId: '1',
emails: {
fields: {
importAddress: generateMockAddress(0, true),
mapping: [dummyFolder, dummyFolder],
importPeriod: TIME_PERIOD.BIG_BANG,
importLabel: { Color: 'red', Name: 'name', Type: 1 },
importCategoriesDestination: MailImportDestinationFolder.ALL_DRAFTS,
},
},
};
const labels: Label[] = [];
const folders: Folder[] = [
{
ID: 'id',
Name: 'path',
Color: 'red',
Path: 'path',
Expanded: 1,
Type: 1,
Order: 1,
ParentID: '',
Notify: 1,
},
];
const calendars: VisualCalendar[] = [];
const mailChecked = false;
const calendarChecked = false;
const errors = importerHasErrors(
products,
importerData,
labels,
folders,
calendars,
mailChecked,
calendarChecked,
true,
false
);
expect(errors).toBe(false);
});
it('Should not return an error if email mapping has errors but is unchecked', () => {
const products: ImportType[] = [ImportType.MAIL];
const importerData: ImporterData = {
importedEmail: 'test@proton.me',
importerId: '1',
emails: {
fields: {
importAddress: generateMockAddress(0, true),
mapping: [dummyFolder, dummyFolder],
importPeriod: TIME_PERIOD.BIG_BANG,
importLabel: { Color: 'red', Name: 'name', Type: 1 },
importCategoriesDestination: MailImportDestinationFolder.ALL_DRAFTS,
},
},
};
const labels: Label[] = [];
const folders: Folder[] = [
{
ID: 'id',
Name: 'path',
Color: 'red',
Path: 'path',
Expanded: 1,
Type: 1,
Order: 1,
ParentID: '',
Notify: 1,
},
];
const calendars: VisualCalendar[] = [];
const mailChecked = false;
const calendarChecked = false;
const errors = importerHasErrors(
products,
importerData,
labels,
folders,
calendars,
mailChecked,
calendarChecked,
true,
false
);
expect(errors).toBe(false);
});
it('Should not return an error if email mapping has errors but no mapping', () => {
const products: ImportType[] = [ImportType.MAIL];
const importerData: ImporterData = {
importedEmail: 'test@proton.me',
importerId: '1',
};
const labels: Label[] = [];
const folders: Folder[] = [
{
ID: 'id',
Name: 'path',
Color: 'red',
Path: 'path',
Expanded: 1,
Type: 1,
Order: 1,
ParentID: '',
Notify: 1,
},
];
const calendars: VisualCalendar[] = [];
const mailChecked = false;
const calendarChecked = false;
const errors = importerHasErrors(
products,
importerData,
labels,
folders,
calendars,
mailChecked,
calendarChecked,
true,
false
);
expect(errors).toBe(false);
});
});
describe('importerHasErrors test for Gmail imports', () => {
const socialFolder = {
id: 'id',
checked: true,
color: 'test color',
isSystemFolderChild: false,
folderChildIDS: [''],
protonPath: ['Social'],
providerPath: ['Social'],
separator: '/',
size: 0,
category: MailImportGmailCategories.SOCIAL,
folderParentID: '',
systemFolder: MailImportDestinationFolder.ARCHIVE,
};
it('Should not return an error when Social folder and label exists when Gmail import', () => {
const products: ImportType[] = [ImportType.MAIL];
const importerData: ImporterData = {
importedEmail: 'test@proton.me',
importerId: '1',
emails: {
fields: {
importAddress: generateMockAddress(0, true),
mapping: [dummyShortPathFolder, dummyShortPathFolder, socialFolder],
importPeriod: TIME_PERIOD.BIG_BANG,
importLabel: { Color: 'red', Name: 'name', Type: 1 },
importCategoriesDestination: MailImportDestinationFolder.ALL_DRAFTS,
},
},
};
const labels: Label[] = [
{
ID: 'id',
Name: 'Social',
Color: 'color',
Type: 1,
Order: 1,
Path: 'Social',
},
];
const folders: Folder[] = [
{
ID: 'id',
Name: 'Social',
Color: 'red',
Path: '/Social',
Expanded: 1,
Type: 1,
Order: 1,
ParentID: '',
Notify: 1,
},
];
const calendars: VisualCalendar[] = [];
const mailChecked = true;
const calendarChecked = false;
const errors = importerHasErrors(
products,
importerData,
labels,
folders,
calendars,
mailChecked,
calendarChecked,
true,
false
);
expect(errors).toBe(false);
});
it('Should not return an error when Social folder and label exists when non Gmail import', () => {
const products: ImportType[] = [ImportType.MAIL];
const importerData: ImporterData = {
importedEmail: 'test@proton.me',
importerId: '1',
emails: {
fields: {
importAddress: generateMockAddress(0, true),
mapping: [dummyShortPathFolder, dummyShortPathFolder, socialFolder],
importPeriod: TIME_PERIOD.BIG_BANG,
importLabel: { Color: 'red', Name: 'name', Type: 1 },
importCategoriesDestination: MailImportDestinationFolder.ALL_DRAFTS,
},
},
};
const labels: Label[] = [
{
ID: 'id',
Name: 'Social',
Color: 'color',
Type: 1,
Order: 1,
Path: 'Social',
},
];
const folders: Folder[] = [
{
ID: 'id',
Name: 'Social',
Color: 'red',
Path: '/Social',
Expanded: 1,
Type: 1,
Order: 1,
ParentID: '',
Notify: 1,
},
];
const calendars: VisualCalendar[] = [];
const mailChecked = true;
const calendarChecked = false;
const errors = importerHasErrors(
products,
importerData,
labels,
folders,
calendars,
mailChecked,
calendarChecked,
false,
false
);
expect(errors).toBe(true);
});
});
| 4,897
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth/hooks/useStepPrepareOAuth.helpers.ts
|
import { c } from 'ttag';
import { getMailMappingErrors } from '@proton/activation/src/helpers/getMailMappingErrors';
import { ImportType, TIME_PERIOD } from '@proton/activation/src/interface';
import { ImporterData } from '@proton/activation/src/logic/draft/oauthDraft/oauthDraft.interface';
import { willUserReachCalendarsLimit } from '@proton/shared/lib/calendar/calendarLimits';
import { Label } from '@proton/shared/lib/interfaces';
import { Folder } from '@proton/shared/lib/interfaces/Folder';
import { VisualCalendar } from '@proton/shared/lib/interfaces/calendar';
import isTruthy from '@proton/utils/isTruthy';
export const getMailCustomLabel = (period?: TIME_PERIOD) => {
if (!period) {
return c('Label').t`Email`;
}
switch (period) {
case TIME_PERIOD.BIG_BANG:
return c('Label').t`Emails (all messages)`;
case TIME_PERIOD.LAST_YEAR:
return c('Label').t`Emails (last 12 months)`;
case TIME_PERIOD.LAST_3_MONTHS:
return c('Label').t`Emails (last 3 months)`;
case TIME_PERIOD.LAST_MONTH:
return c('Label').t`Emails (last month)`;
}
};
export const importerHasErrors = (
products: ImportType[],
importerData: ImporterData,
labels: Label[],
folders: Folder[],
calendars: VisualCalendar[],
mailChecked: boolean,
calendarChecked: boolean,
isLabelMapping: boolean,
isFreeUser: boolean
) => {
const hasErrors = [];
if (products?.includes(ImportType.MAIL) && mailChecked) {
const mailMapping = importerData?.emails?.fields?.mapping;
if (mailMapping) {
const hasMailErrors = getMailMappingErrors(mailMapping, isLabelMapping, labels, folders);
hasErrors.push(...hasMailErrors.errors);
}
}
if (products?.includes(ImportType.CALENDAR) && calendarChecked) {
const calendarsToBeCreatedCount =
importerData?.calendars?.calendars?.filter((item) => item.checked && !item.mergedTo).length ?? 0;
const limitReached = willUserReachCalendarsLimit(calendars, calendarsToBeCreatedCount, isFreeUser);
hasErrors.push(limitReached);
}
return hasErrors.some(isTruthy);
};
| 4,898
|
0
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth
|
petrpan-code/ProtonMail/WebClients/packages/activation/src/components/Modals/OAuth/StepPrepareOAuth/hooks/useStepPrepareOAuth.ts
|
import { useState } from 'react';
import { EasySwitchFeatureFlag, ImportProvider, ImportType } from '@proton/activation/src/interface';
import {
changeOAuthStep,
displayConfirmLeaveModal,
submitProducts,
} from '@proton/activation/src/logic/draft/oauthDraft/oauthDraft.actions';
import {
selectOauthDraftProvider,
selectOauthImportStateImporterData,
selectOauthImportStateProducts,
} from '@proton/activation/src/logic/draft/oauthDraft/oauthDraft.selector';
import { useEasySwitchDispatch, useEasySwitchSelector } from '@proton/activation/src/logic/store';
import { FeatureCode, useCalendars, useFeature, useFolders, useLabels, useUser } from '@proton/components/index';
import { getVisualCalendars } from '@proton/shared/lib/calendar/calendar';
import isTruthy from '@proton/utils/isTruthy';
import { getEnabledFeature } from '../../OAuthModal.helpers';
import { getMailCustomLabel, importerHasErrors } from './useStepPrepareOAuth.helpers';
const useStepPrepare = () => {
const dispatch = useEasySwitchDispatch();
const products = useEasySwitchSelector(selectOauthImportStateProducts);
const provider = useEasySwitchSelector(selectOauthDraftProvider);
const importerData = useEasySwitchSelector(selectOauthImportStateImporterData);
if (!products || !importerData || !provider) {
throw new Error('products or importerData must be defined');
}
const [user] = useUser();
const [labels = []] = useLabels();
const [folders = []] = useFolders();
const [calendars = []] = useCalendars();
const visualCalendars = getVisualCalendars(calendars);
const emailSelected = products.includes(ImportType.MAIL);
const contactSelected = products.includes(ImportType.CONTACTS);
const calendarSelected = products.includes(ImportType.CALENDAR);
const emailsHasError = !!importerData.emails?.error;
const contactsHasError = !!importerData.contacts?.error;
const calendarsHasError = !!importerData.calendars?.error;
const [emailChecked, setEmailChecked] = useState(emailSelected && !emailsHasError);
const [contactChecked, setContactChecked] = useState(contactSelected && !contactsHasError);
const [calendarChecked, setCalendarChecked] = useState(calendarSelected && !calendarsHasError);
const isLabelMapping = provider === ImportProvider.GOOGLE;
const emailTitle = getMailCustomLabel(importerData.emails?.fields?.importPeriod);
const hasErrors = importerHasErrors(
products,
importerData,
labels,
folders,
visualCalendars,
emailChecked,
calendarChecked,
isLabelMapping,
!user.hasPaidMail
);
const easySwitchFeature = useFeature<EasySwitchFeatureFlag>(FeatureCode.EasySwitch);
const featureMap = easySwitchFeature.feature!.Value;
const handleSubmit = () => {
const products = [
emailChecked && ImportType.MAIL,
contactChecked && ImportType.CONTACTS,
calendarChecked && ImportType.CALENDAR,
].filter(isTruthy);
dispatch(submitProducts(products));
dispatch(changeOAuthStep('importing'));
};
const handleCancel = () => {
dispatch(displayConfirmLeaveModal(true));
};
return {
products,
emailChecked,
setEmailChecked,
contactChecked,
setContactChecked,
calendarChecked,
setCalendarChecked,
importerData,
handleCancel,
handleSubmit,
emailTitle,
hasErrors,
enabledFeatures: getEnabledFeature(provider, featureMap),
allCheckboxUnselected: !emailChecked && !contactChecked && !calendarChecked,
};
};
export default useStepPrepare;
| 4,899
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.