index
int64
0
0
repo_id
stringlengths
16
181
file_path
stringlengths
28
270
content
stringlengths
1
11.6M
__index_level_0__
int64
0
10k
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/notifications/UndoActionNotification.tsx
import { ReactNode } from 'react'; import { CustomNotificationProps } from '@proton/components'; import UndoNotificationButton from './UndoNotificationButton'; interface Props extends CustomNotificationProps { children: ReactNode; additionalButton?: ReactNode; onUndo?: () => void; } const UndoActionNotification = ({ children, additionalButton = null, onUndo, onClose }: Props) => ( <> <span>{children}</span> {additionalButton ? additionalButton : null} {onUndo ? ( <UndoNotificationButton onUndo={() => { onClose?.(); onUndo(); }} /> ) : null} </> ); export default UndoActionNotification;
3,700
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/notifications/UndoNotificationButton.tsx
import { c } from 'ttag'; import { NotificationButton } from '@proton/components'; interface Props { onUndo: () => void; className?: string; disabled?: boolean; } const UndoNotificationButton = ({ onUndo, disabled, className }: Props) => ( <NotificationButton onClick={onUndo} disabled={disabled} className={className}> {c('Action').t`Undo`} </NotificationButton> ); export default UndoNotificationButton;
3,701
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/onboarding/MailOnboardingModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { OnboardingContent, OnboardingModal, OnboardingStep, OnboardingStepRenderCallback } from '@proton/components'; import { MAIL_APP_NAME } from '@proton/shared/lib/constants'; import onboardingMailWelcome from '@proton/styles/assets/img/onboarding/mail-welcome.svg'; interface Props { showGenericSteps?: boolean; onDone?: () => void; onExit?: () => void; open?: boolean; } const MailOnboardingModal = (props: Props) => { const appName = MAIL_APP_NAME; return ( <OnboardingModal {...props}> {[ ({ onNext, displayGenericSteps }: OnboardingStepRenderCallback) => ( <OnboardingStep> <OnboardingContent img={<img src={onboardingMailWelcome} alt={c('Onboarding').t`Welcome to ${appName}`} />} title={c('Onboarding').t`Welcome to ${appName}`} description={c('Onboarding') .t`Where privacy and security meet productivity and ease of use.`} /> <footer> <Button size="large" color="norm" fullWidth onClick={onNext}> {displayGenericSteps ? c('Onboarding Action').t`Next` : c('Onboarding Action').t`Start using ${appName}`} </Button> </footer> </OnboardingStep> ), ]} </OnboardingModal> ); }; export default MailOnboardingModal;
3,702
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/onboarding/MailOnboardingWrapper.tsx
import { useEffect, useState } from 'react'; import { EasySwitchProvider } from '@proton/activation/index'; import useModalState from '@proton/components/components/modalTwo/useModalState'; import { useFlag } from '@proton/components/containers'; import { GmailSyncModal } from '@proton/components/containers/gmailSyncModal'; import { useApi, useUserSettings } from '@proton/components/hooks'; import useWelcomeFlags from '@proton/components/hooks/useWelcomeFlags'; import { updateFlags, updateWelcomeFlags } from '@proton/shared/lib/api/settings'; import noop from '@proton/utils/noop'; import MailStartupModals from '../../containers/MailStartupModals'; const MailOnboardingWrapper = () => { const api = useApi(); const [userSettings] = useUserSettings(); const [welcomeFlags, setWelcomeFlagsDone] = useWelcomeFlags(); // The modal state is handled inside the MailStartupModals component const [openStartupModal, setOpenStartupModal] = useState(false); const [syncModalProps, setSyncModalOpen, renderSyncModal] = useModalState(); const isImporterInMaintenance = useFlag('MaintenanceImporter'); useEffect(() => { // Show the onboarding modal if easy switch importer are disabled for maintenance if (isImporterInMaintenance) { setOpenStartupModal(!welcomeFlags.isDone); } else { setSyncModalOpen(!welcomeFlags.isDone); } }, [welcomeFlags]); const handleSyncCallback = async (hasError: boolean) => { if (!hasError) { setWelcomeFlagsDone(); if (welcomeFlags.isWelcomeFlow) { // Set generic welcome to true await api(updateFlags({ Welcomed: 1 })).catch(noop); } if (!userSettings.WelcomeFlag) { // Set product specific welcome to true await api(updateWelcomeFlags()).catch(noop); } setSyncModalOpen(false); } }; const handleSyncSkip = () => { setOpenStartupModal(true); }; return ( <EasySwitchProvider> <> {renderSyncModal && !isImporterInMaintenance && ( <GmailSyncModal onSyncCallback={handleSyncCallback} onSyncSkipCallback={handleSyncSkip} {...syncModalProps} /> )} <MailStartupModals onboardingOpen={openStartupModal} /> </> </EasySwitchProvider> ); }; export default MailOnboardingWrapper;
3,703
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/sidebar/AlmostAllMailSpotlight.tsx
import { ReactNode } from 'react'; import { c } from 'ttag'; import { SettingsLink, Spotlight } from '@proton/components/components'; import { APPS } from '@proton/shared/lib/constants'; interface Props { children: ReactNode; show: boolean; onDisplayed: () => void; onClose: () => void; } const AlmostAllMailSpotlight = ({ children, show, onDisplayed, onClose }: Props) => { const settingsLink = ( <SettingsLink key="to-messages-settings" app={APPS.PROTONACCOUNT} path="/general#messages">{c('Spotlight') .t`Change setting`}</SettingsLink> ); return ( <Spotlight show={show} onDisplayed={onDisplayed} onClose={onClose} originalPlacement="bottom-start" type="new" className="ml-4" content={ <p className="m-0">{ // translator: `Almost all mail` is a new true-by-default setting that enables to exclude Trash/Spam message from `All Mail` location c('Spotlight') .jt`Spam and Trash emails are now automatically excluded from All Mail. ${settingsLink}` }</p> } > {children} </Spotlight> ); }; export default AlmostAllMailSpotlight;
3,704
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/sidebar/EditLabelContext.tsx
import { Reducer, createContext, useCallback, useContext, useMemo, useReducer } from 'react'; import { useHistory, useLocation } from 'react-router-dom'; import { useModalState } from '@proton/components/components'; import DeleteLabelModal from '@proton/components/containers/labels/modals/DeleteLabelModal'; import EditLabelModal from '@proton/components/containers/labels/modals/EditLabelModal'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { Label } from '@proton/shared/lib/interfaces'; import { getStandardFolders } from '../../helpers/labels'; type LabelType = 'label' | 'folder'; interface LabelActionsContext { createLabel: (type: LabelType) => void; editLabel: (type: LabelType, label: Label) => void; deleteLabel: (type: LabelType, label: Label) => void; } const referralContext = createContext<LabelActionsContext | undefined>(undefined); export const useLabelActionsContext = () => { const context = useContext(referralContext); if (context === undefined) { throw new Error('Component should be wrapped inside LabelActionsContextProvider'); } return context; }; type State = { type: LabelType | undefined; label: Label | undefined; action: 'create' | 'edit' | 'delete' | undefined; }; type Action = | { type: 'create'; payload: Pick<State, 'type'> } | { type: 'edit'; payload: Pick<State, 'label' | 'type'> } | { type: 'delete'; payload: Pick<State, 'label' | 'type'> } | { type: 'reset' }; const reducer = (state: State, action: Action) => { switch (action.type) { case 'create': return { action: action.type, type: action.payload.type, label: undefined }; case 'edit': return { action: action.type, ...action.payload }; case 'delete': return { action: action.type, ...action.payload }; case 'reset': return { action: undefined, label: undefined, type: undefined }; } }; export const LabelActionsContextProvider = ({ children }: { children: React.ReactNode }) => { const location = useLocation(); const history = useHistory(); const [{ type, label, action }, dispatch] = useReducer<Reducer<State, Action>>(reducer, { type: undefined, label: undefined, action: undefined, }); const [modalProps, openModal, renderModal] = useModalState(); const resetContextAndCloseModal = useCallback(() => { dispatch({ type: 'reset' }); modalProps.onClose(); }, []); const contextProviderValue = useMemo( () => ({ createLabel: (type: LabelType) => { dispatch({ type: 'create', payload: { type } }); openModal(true); }, editLabel: (type: LabelType, label: Label) => { dispatch({ type: 'edit', payload: { label, type } }); openModal(true); }, deleteLabel: (type: LabelType, label: Label) => { dispatch({ type: 'delete', payload: { label, type } }); openModal(true); }, }), [] ); const redirectToInbox = () => { const systemFolders = getStandardFolders(); history.push(systemFolders[MAILBOX_LABEL_IDS.INBOX].to); }; return ( <referralContext.Provider value={contextProviderValue}> {children} {action === 'create' && renderModal && ( <EditLabelModal {...modalProps} type={type} mode="create" onCloseCustomAction={resetContextAndCloseModal} /> )} {action === 'edit' && renderModal && ( <EditLabelModal {...modalProps} type={type} mode="edition" label={label} onCloseCustomAction={resetContextAndCloseModal} /> )} {action === 'delete' && renderModal && label && ( <DeleteLabelModal {...modalProps} label={label} onRemove={() => { const userOnLabelPage = location.pathname.includes(label.ID); if (userOnLabelPage) { redirectToInbox(); } resetContextAndCloseModal(); }} /> )} </referralContext.Provider> ); };
3,705
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/sidebar/LocationAside.tsx
import { c, msgid } from 'ttag'; import { ReloadSpinner } from '@proton/components'; import { VIEW_MODE } from '@proton/shared/lib/mail/mailSettings'; import clsx from '@proton/utils/clsx'; import useMailModel from 'proton-mail/hooks/useMailModel'; interface Props { unreadCount?: number; active?: boolean; weak?: boolean; refreshing?: boolean; itemOptions?: React.ReactNode; shouldDisplayTotal: boolean; hideCountOnHover: boolean; onRefresh?: () => void; isOptionDropdownOpened?: boolean; } const { GROUP } = VIEW_MODE; const UNREAD_LIMIT = 9999; const LocationAside = ({ unreadCount = 0, active = false, refreshing = false, onRefresh, weak = false, shouldDisplayTotal, hideCountOnHover, itemOptions, isOptionDropdownOpened, }: Props) => { const mailSettings = useMailModel('MailSettings'); const getUnreadTitle = () => { if (shouldDisplayTotal) { return c('Info').ngettext( msgid`${unreadCount} scheduled message`, `${unreadCount} scheduled messages`, unreadCount ); } if (mailSettings.ViewMode === GROUP) { return c('Info').ngettext( msgid`${unreadCount} unread conversation`, `${unreadCount} unread conversations`, unreadCount ); } return c('Info').ngettext(msgid`${unreadCount} unread message`, `${unreadCount} unread messages`, unreadCount); }; const unreadText = unreadCount > UNREAD_LIMIT ? '9999+' : unreadCount; return ( <> {active && ( <ReloadSpinner className={clsx([unreadCount > 0 ? 'mr-2' : 'mr-0.5'])} refreshing={refreshing} onRefresh={onRefresh} data-testid="navigation-link:refresh-folder" /> )} {unreadCount > 0 ? ( <span className={clsx([ 'navigation-counter-item px-1 flex-item-noshrink', hideCountOnHover && 'group-hover:hidden', weak && 'navigation-counter-item--weak pl-0', isOptionDropdownOpened && 'hidden', ])} title={getUnreadTitle()} aria-label={getUnreadTitle()} data-testid="navigation-link:unread-count" data-unread-count={unreadText} > {unreadText} </span> ) : null} {itemOptions && ( <span className={clsx( 'group-hover:opacity-100 group-hover:opacity-100-no-width flex-item-noshrink hidden md:flex mr-custom right-custom', isOptionDropdownOpened && 'is-active' )} style={{ '--mr-custom': 'calc(var(--space-1) * -1)', '--right-custom': 'var(--space-2)' }} > {itemOptions} </span> )} </> ); }; export default LocationAside;
3,706
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/sidebar/MailSidebar.test.tsx
import { act } from 'react-dom/test-utils'; import { fireEvent, getAllByText } from '@testing-library/react'; import { Location } from 'history'; import loudRejection from 'loud-rejection'; import { getAppVersion } from '@proton/components'; import useEventManager from '@proton/components/hooks/useEventManager'; import { LABEL_TYPE, MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { removeItem, setItem } from '@proton/shared/lib/helpers/storage'; import { CHECKLIST_DISPLAY_TYPE } from '@proton/shared/lib/interfaces'; import range from '@proton/utils/range'; import { ContextState, useGetStartedChecklist, } from '../../containers/onboardingChecklist/provider/GetStartedChecklistProvider'; import { addToCache, assertFocus, clearAll, config, getDropdown, getHistory, minimalCache, render, } from '../../helpers/test/helper'; import { SYSTEM_FOLDER_SECTION } from '../../hooks/useMoveSystemFolders'; import MailSidebar from './MailSidebar'; jest.mock('../../../../CHANGELOG.md', () => 'ProtonMail Changelog'); jest.mock('../../containers/onboardingChecklist/provider/GetStartedChecklistProvider', () => ({ __esModule: true, useGetStartedChecklist: jest.fn(), default: ({ children }: { children: any }) => <>{children}</>, })); jest.mock('../../containers/onboardingChecklist/provider/GetStartedChecklistProvider'); const mockedReturn = useGetStartedChecklist as jest.MockedFunction<any>; loudRejection(); const labelID = 'labelID'; const props = { labelID, location: {} as Location, onToggleExpand: jest.fn(), }; const folder = { ID: 'folder1', Type: LABEL_TYPE.MESSAGE_FOLDER, Name: 'folder1' }; const subfolder = { ID: 'folder2', Type: LABEL_TYPE.MESSAGE_FOLDER, Name: 'folder2', ParentID: folder.ID }; const label = { ID: 'label1', Type: LABEL_TYPE.MESSAGE_LABEL, Name: 'label1' }; const systemFolders = [ { ID: MAILBOX_LABEL_IDS.INBOX, Name: 'inbox', Path: 'inbox', Type: LABEL_TYPE.SYSTEM_FOLDER, Order: 1, Display: SYSTEM_FOLDER_SECTION.MAIN, }, { ID: MAILBOX_LABEL_IDS.SCHEDULED, Name: 'all scheduled', Path: 'all scheduled', Type: LABEL_TYPE.SYSTEM_FOLDER, Order: 3, Display: SYSTEM_FOLDER_SECTION.MAIN, }, { ID: MAILBOX_LABEL_IDS.DRAFTS, Name: 'drafts', Path: 'drafts', Type: LABEL_TYPE.SYSTEM_FOLDER, Order: 4, Display: SYSTEM_FOLDER_SECTION.MAIN, }, { ID: MAILBOX_LABEL_IDS.SENT, Name: 'sent', Path: 'sent', Type: LABEL_TYPE.SYSTEM_FOLDER, Order: 5, Display: SYSTEM_FOLDER_SECTION.MAIN, }, { ID: MAILBOX_LABEL_IDS.ALL_MAIL, Name: 'all mail', Path: 'all mail', Type: LABEL_TYPE.SYSTEM_FOLDER, Order: 11, Display: SYSTEM_FOLDER_SECTION.MAIN, }, ]; const inboxMessages = { LabelID: MAILBOX_LABEL_IDS.INBOX, Unread: 3, Total: 20 }; const allMailMessages = { LabelID: MAILBOX_LABEL_IDS.ALL_MAIL, Unread: 10000, Total: 10001 }; const scheduledMessages = { LabelID: MAILBOX_LABEL_IDS.SCHEDULED, Unread: 1, Total: 4 }; const folderMessages = { LabelID: folder.ID, Unread: 1, Total: 2 }; const labelMessages = { LabelID: label.ID, Unread: 2, Total: 3 }; const setupTest = (labels: any[] = [], messageCounts: any[] = [], conversationCounts: any[] = []) => { // open the more section otherwise it's closed by default setItem('item-display-more-items', 'true'); minimalCache(); addToCache('Labels', labels); addToCache('MessageCounts', messageCounts); addToCache('ConversationCounts', conversationCounts); mockedReturn.mockReturnValue({ displayState: CHECKLIST_DISPLAY_TYPE.FULL, items: new Set(), } as ContextState); }; describe('MailSidebar', () => { const setup = async () => { minimalCache(); mockedReturn.mockReturnValue({ displayState: CHECKLIST_DISPLAY_TYPE.FULL, items: new Set(), } as ContextState); const result = await render(<MailSidebar {...props} />, false); return { ...result }; }; afterEach(() => { clearAll(); // We need to remove the item from the localStorage otherwise it will keep the previous state removeItem('item-display-folders'); removeItem('item-display-labels'); }); it('should redirect on inbox when click on logo', async () => { const { getByTestId } = await setup(); const logo = getByTestId('main-logo') as HTMLAnchorElement; fireEvent.click(logo); const history = getHistory(); expect(history.length).toBe(1); expect(history.location.pathname).toBe('/inbox'); }); it('should open app dropdown', async () => { const { getByTitle } = await setup(); const appsButton = getByTitle('Proton applications'); fireEvent.click(appsButton); const dropdown = await getDropdown(); getAllByText(dropdown, 'Proton Mail'); getAllByText(dropdown, 'Proton Calendar'); getAllByText(dropdown, 'Proton Drive'); getAllByText(dropdown, 'Proton VPN'); }); it('should show folder tree', async () => { setupTest([folder, subfolder]); const { getByTestId, queryByTestId } = await render(<MailSidebar {...props} />, false); const folderElement = getByTestId(`navigation-link:${folder.ID}`); const folderIcon = folderElement.querySelector('svg:not(.navigation-icon--expand)'); expect(folderElement.textContent).toContain(folder.Name); expect((folderIcon?.firstChild as Element).getAttribute('xlink:href')).toBe('#ic-folders'); const subfolderElement = getByTestId(`navigation-link:${subfolder.ID}`); const subfolderIcon = subfolderElement.querySelector('svg'); expect(subfolderElement.textContent).toContain(subfolder.Name); expect((subfolderIcon?.firstChild as Element).getAttribute('xlink:href')).toBe('#ic-folder'); const collapseButton = folderElement.querySelector('button'); if (collapseButton) { fireEvent.click(collapseButton); } expect(queryByTestId(`sidebar-item-${subfolder.ID}`)).toBeNull(); }); it('should show label list', async () => { setupTest([label]); const { getByTestId } = await render(<MailSidebar {...props} />, false); const labelElement = getByTestId(`navigation-link:${label.ID}`); const labelIcon = labelElement.querySelector('svg'); expect(labelElement.textContent).toContain(label.Name); expect((labelIcon?.firstChild as Element).getAttribute('xlink:href')).toBe('#ic-circle-filled'); }); it('should show unread counters', async () => { setupTest( [folder, label, ...systemFolders], [], [inboxMessages, allMailMessages, folderMessages, labelMessages] ); const { getByTestId } = await render(<MailSidebar {...props} />, false); const inboxElement = getByTestId(`navigation-link:inbox`); const allMailElement = getByTestId(`navigation-link:all-mail`); const folderElement = getByTestId(`navigation-link:${folder.ID}`); const labelElement = getByTestId(`navigation-link:${label.ID}`); const inBoxLocationAside = inboxElement.querySelector('.navigation-counter-item'); const allMailLocationAside = allMailElement.querySelector('.navigation-counter-item'); const folderLocationAside = folderElement.querySelector('.navigation-counter-item'); const labelLocationAside = labelElement.querySelector('.navigation-counter-item'); expect(inBoxLocationAside?.innerHTML).toBe(`${inboxMessages.Unread}`); expect(allMailLocationAside?.innerHTML).toBe('9999+'); expect(folderLocationAside?.innerHTML).toBe(`${folderMessages.Unread}`); expect(labelLocationAside?.innerHTML).toBe(`${labelMessages.Unread}`); }); it('should navigate to the label on click', async () => { setupTest([folder]); const { getByTestId } = await render(<MailSidebar {...props} />, false); const folderElement = getByTestId(`navigation-link:${folder.ID}`); const history = getHistory(); expect(history.location.pathname).toBe('/inbox'); act(() => { fireEvent.click(folderElement); }); expect(history.location.pathname).toBe(`/${folder.ID}`); }); it('should call event manager on click if already on label', async () => { setupTest([folder]); const { getByTestId } = await render(<MailSidebar {...props} />, false); const folderElement = getByTestId(`navigation-link:${folder.ID}`); // Click on the label to be redirected in it act(() => { fireEvent.click(folderElement); }); // Check if we are in the label expect(getHistory().location.pathname).toBe(`/${folder.ID}`); // Click again on the label to trigger the event manager act(() => { fireEvent.click(folderElement); }); expect(useEventManager.call).toHaveBeenCalled(); }); it('should show app version and changelog', async () => { setupTest(); const { getByText } = await render(<MailSidebar {...props} />, false); const appVersion = getAppVersion(config.APP_VERSION); const appVersionButton = getByText(appVersion); // Check if the changelog modal opens on click fireEvent.click(appVersionButton); getByText("What's new"); getByText('ProtonMail Changelog'); }); it('should be updated when counters are updated', async () => { setupTest(systemFolders, [], [inboxMessages]); const { getByTestId } = await render(<MailSidebar {...props} />, false); const inboxElement = getByTestId('navigation-link:inbox'); const inBoxLocationAside = inboxElement.querySelector('.navigation-counter-item'); expect(inBoxLocationAside?.innerHTML).toBe(`${inboxMessages.Unread}`); const inboxMessagesUpdated = { LabelID: '0', Unread: 7, Total: 21 }; act(() => { addToCache('ConversationCounts', [inboxMessagesUpdated]); }); expect(inBoxLocationAside?.innerHTML).toBe(`${inboxMessagesUpdated.Unread}`); }); it('should not show scheduled sidebar item when feature flag is disabled', async () => { setupTest(systemFolders, [], [scheduledMessages]); const { queryByTestId } = await render(<MailSidebar {...props} />, false); expect(queryByTestId(`Scheduled`)).toBeNull(); }); it('should show scheduled sidebar item if scheduled messages', async () => { setupTest(systemFolders, [], [scheduledMessages]); const { getByTestId } = await render(<MailSidebar {...props} />, false); const scheduledLocationAside = getByTestId(`navigation-link:unread-count`); // We have two navigation counters for scheduled messages, one to display the number of scheduled messages and one for unread scheduled messages expect(scheduledLocationAside.innerHTML).toBe(`${scheduledMessages.Total}`); }); it('should not show scheduled sidebar item without scheduled messages', async () => { setupTest([], [], []); const { queryByTestId } = await render(<MailSidebar {...props} />, false); expect(queryByTestId(`Scheduled`)).toBeNull(); }); describe('Sidebar hotkeys', () => { it('should navigate with the arrow keys', async () => { setupTest([label, folder, ...systemFolders]); const { getByTestId, getByTitle, container } = await render(<MailSidebar {...props} />, false); const sidebar = container.querySelector('nav > div') as HTMLDivElement; const More = getByTitle('Less'); // When opened, it becomes "LESS" const Folders = getByTitle('Folders'); const Labels = getByTitle('Labels'); const Inbox = getByTestId('navigation-link:inbox'); const Drafts = getByTestId('navigation-link:drafts'); const Folder = getByTestId(`navigation-link:${folder.ID}`); const Label = getByTestId(`navigation-link:${label.ID}`); const down = () => fireEvent.keyDown(sidebar, { key: 'ArrowDown' }); const up = () => fireEvent.keyDown(sidebar, { key: 'ArrowUp' }); const ctrlDown = () => fireEvent.keyDown(sidebar, { key: 'ArrowDown', ctrlKey: true }); const ctrlUp = () => fireEvent.keyDown(sidebar, { key: 'ArrowUp', ctrlKey: true }); down(); assertFocus(Inbox); down(); assertFocus(Drafts); range(0, 3).forEach(down); assertFocus(More); down(); assertFocus(Folders); down(); assertFocus(Folder); down(); assertFocus(Labels); down(); assertFocus(Label); up(); assertFocus(Labels); up(); assertFocus(Folder); up(); assertFocus(Folders); range(0, 10).forEach(up); assertFocus(Inbox); ctrlDown(); assertFocus(Label); ctrlUp(); assertFocus(Inbox); }); it('should navigate to list with right key', async () => { setupTest([label, folder]); const TestComponent = () => { return ( <> <MailSidebar {...props} /> <div data-shortcut-target="item-container" tabIndex={-1}> test </div> </> ); }; const { container } = await render(<TestComponent />, false); const sidebar = container.querySelector('nav > div') as HTMLDivElement; fireEvent.keyDown(sidebar, { key: 'ArrowRight' }); const target = document.querySelector('[data-shortcut-target="item-container"]'); assertFocus(target); }); }); }); describe('Sidebar checklist display', () => { beforeEach(() => { minimalCache(); }); it('Should display the checklist if state is reduced', async () => { mockedReturn.mockReturnValue({ displayState: CHECKLIST_DISPLAY_TYPE.REDUCED, items: new Set(), } as ContextState); const { getByTestId, container } = await render(<MailSidebar {...props} />, false); getByTestId('onboarding-checklist'); const nav = container.querySelector('nav'); expect(nav?.childNodes.length).toEqual(3); }); it('Should not display the checklist if state is full', async () => { mockedReturn.mockReturnValue({ displayState: CHECKLIST_DISPLAY_TYPE.FULL, items: new Set(), } as ContextState); const { queryByTestId, container } = await render(<MailSidebar {...props} />, false); const checklistWrapper = queryByTestId('onboarding-checklist'); const nav = container.querySelector('nav'); expect(checklistWrapper).toBeNull(); expect(nav?.childNodes.length).toEqual(2); }); it('Should not display the checklist if state is hidden', async () => { mockedReturn.mockReturnValue({ displayState: CHECKLIST_DISPLAY_TYPE.HIDDEN, items: new Set(), } as ContextState); const { queryByTestId, container } = await render(<MailSidebar {...props} />, false); const checklistWrapper = queryByTestId('onboarding-checklist'); const nav = container.querySelector('nav'); expect(checklistWrapper).toBeNull(); expect(nav?.childNodes.length).toEqual(2); }); it('Should hide the checklist when pressing the cross button in the sidebar', async () => { const mockedChangeDisplay = jest.fn(); mockedReturn.mockReturnValue({ displayState: CHECKLIST_DISPLAY_TYPE.REDUCED, items: new Set(), changeChecklistDisplay: mockedChangeDisplay, } as Partial<ContextState>); const { container, getByTestId } = await render(<MailSidebar {...props} />, false); const nav = container.querySelector('nav'); expect(nav?.childNodes.length).toEqual(3); const closeButton = getByTestId('onboarding-checklist-header-hide-button'); fireEvent.click(closeButton); expect(mockedChangeDisplay).toHaveBeenCalledWith(CHECKLIST_DISPLAY_TYPE.HIDDEN); }); });
3,707
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/sidebar/MailSidebar.tsx
import { memo, useCallback } from 'react'; import { AppsDropdown, MainLogo, Sidebar, SidebarContactItem, SidebarNav, useDrawer } from '@proton/components'; import useDisplayContactsWidget from '@proton/components/hooks/useDisplayContactsWidget'; import { APPS } from '@proton/shared/lib/constants'; import { DRAWER_NATIVE_APPS } from '@proton/shared/lib/drawer/interfaces'; import { CHECKLIST_DISPLAY_TYPE } from '@proton/shared/lib/interfaces'; import { MESSAGE_ACTIONS } from '../../constants'; import { useOnCompose } from '../../containers/ComposeProvider'; import { useGetStartedChecklist } from '../../containers/onboardingChecklist/provider/GetStartedChecklistProvider'; import { ComposeTypes } from '../../hooks/composer/useCompose'; import { layoutActions } from '../../logic/layout/layoutSlice'; import { selectLayoutIsExpanded } from '../../logic/layout/layoutSliceSelectors'; import { useAppDispatch, useAppSelector } from '../../logic/store'; import UsersOnboardingChecklist from '../checklist/UsersOnboardingChecklist'; import MailSidebarDriveSpotlight from './MailSidebarDriveSpotlight'; import MailSidebarList from './MailSidebarList'; import MailSidebarPrimaryButton from './MailSidebarPrimaryButton'; import SidebarVersion from './SidebarVersion'; interface Props { labelID: string; } const MailSidebar = ({ labelID }: Props) => { const onCompose = useOnCompose(); const dispatch = useAppDispatch(); const expanded = useAppSelector(selectLayoutIsExpanded); const { toggleDrawerApp } = useDrawer(); const { displayState } = useGetStartedChecklist(); const handleCompose = useCallback(() => { onCompose({ type: ComposeTypes.newMessage, action: MESSAGE_ACTIONS.NEW }); }, [onCompose]); const logo = <MainLogo to="/inbox" data-testid="main-logo" />; const displayContactsInHeader = useDisplayContactsWidget(); return ( <> <Sidebar appsDropdown={ <MailSidebarDriveSpotlight renderDropdown={(hideSpotlight) => ( <AppsDropdown app={APPS.PROTONMAIL} onDropdownClick={hideSpotlight} /> )} /> } expanded={expanded} onToggleExpand={() => { dispatch(layoutActions.toggleSidebarExpand()); }} primary={<MailSidebarPrimaryButton handleCompose={handleCompose} />} logo={logo} version={<SidebarVersion />} contactsButton={ displayContactsInHeader && ( <SidebarContactItem onClick={() => { dispatch(layoutActions.setSidebarExpanded(false)); toggleDrawerApp({ app: DRAWER_NATIVE_APPS.CONTACTS })(); }} /> ) } > <SidebarNav className="flex"> <MailSidebarList labelID={labelID} /> {displayState === CHECKLIST_DISPLAY_TYPE.REDUCED && <UsersOnboardingChecklist smallVariant />} </SidebarNav> </Sidebar> </> ); }; export default memo(MailSidebar);
3,708
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/sidebar/MailSidebarDriveSpotlight.test.tsx
import { render, screen } from '@testing-library/react'; import { getUnixTime, subDays } from 'date-fns'; import * as spotlightModule from '@proton/components/components/spotlight/Spotlight'; import * as useDriveWindowsGASpotlightModule from '@proton/components/hooks/useDriveWindowsGASpotlight'; import * as useFeatureModule from '@proton/components/hooks/useFeature'; import * as useSpotlightOnFeatureModule from '@proton/components/hooks/useSpotlightOnFeature'; import * as useWelcomeFlagsModule from '@proton/components/hooks/useWelcomeFlags'; import * as browserHelpersModule from '@proton/shared/lib/helpers/browser'; import { SpotlightMock, mockUseActiveBreakpoint, mockUseFeature, mockUseSpotlightOnFeature, mockUseUser, } from '@proton/testing/index'; import noop from '@proton/utils/noop'; import MailSidebarDriveSpotlight from './MailSidebarDriveSpotlight'; describe('MailSidebarDriveSpotlight', () => { const spotlightMock = jest.spyOn(spotlightModule, 'default'); const useWelcomeFlagsMock = jest.spyOn(useWelcomeFlagsModule, 'default'); const useFeatureMock = jest.spyOn(useFeatureModule, 'default'); const useSpotlightOnFeatureMock = jest.spyOn(useSpotlightOnFeatureModule, 'default'); const useDriveWindowsGASpotlightMock = jest.spyOn(useDriveWindowsGASpotlightModule, 'useDriveWindowsGASpotlight'); const isWindows = jest.spyOn(browserHelpersModule, 'isWindows'); beforeEach(() => { isWindows.mockReturnValue(true); spotlightMock.mockImplementation(SpotlightMock); useWelcomeFlagsMock.mockReturnValue([ { isDone: true, hasGenericWelcomeStep: false, isWelcomeFlow: false }, noop, ]); useDriveWindowsGASpotlightMock.mockReturnValue([ { show: true, content: 'spotlight', originalPlacement: 'bottom', size: 'large', onClose: noop, }, noop, ]); mockUseActiveBreakpoint({ isNarrow: false }); mockUseFeature({ feature: { Value: true } }); mockUseSpotlightOnFeature({ show: true }); mockUseUser([ { CreateTime: getUnixTime(subDays(new Date(), 2)), }, false, ]); }); afterEach(() => { jest.clearAllMocks(); }); const setup = () => { return render( <MailSidebarDriveSpotlight renderDropdown={(hideSpotlight) => <div onClick={hideSpotlight}>{'content'}</div>} /> ); }; it('Should render child and spotlight', () => { setup(); // Ensure we call the right FF in first call expect(useFeatureMock.mock.calls[0][0]).toBe('DriveWindowsGAMailSpotlightShown'); expect(screen.getByText('content')).toBeInTheDocument(); expect(screen.getByText('spotlight')).toBeInTheDocument(); }); it('Should not render spotlight when feature flag is false', () => { useFeatureMock.mockReturnValue({ feature: { Value: false } } as any); setup(); expect(screen.getByText('content')).toBeInTheDocument(); expect(screen.queryByText('spotlight')).toBe(null); }); it('Should not render spotlight when feature flag has been displayed', () => { useSpotlightOnFeatureMock.mockReturnValue({ show: false, onDisplayed: () => {}, onClose: () => {} }); setup(); expect(screen.getByText('content')).toBeInTheDocument(); expect(screen.queryByText('spotlight')).toBe(null); }); it('Should not render spotlight when feature is not on windows', () => { isWindows.mockReturnValue(false); setup(); expect(screen.getByText('content')).toBeInTheDocument(); expect(screen.queryByText('spotlight')).toBe(null); }); it('Should not render spotlight when user created account less than two days ago', () => { mockUseUser([ { CreateTime: getUnixTime(subDays(new Date(), 1)), }, false, ]); setup(); expect(screen.getByText('content')).toBeInTheDocument(); expect(screen.queryByText('spotlight')).toBe(null); }); it('Should not render spotlight when user is on mobile screen', () => { mockUseActiveBreakpoint({ isNarrow: true }); setup(); expect(screen.getByText('content')).toBeInTheDocument(); expect(screen.queryByText('spotlight')).toBe(null); }); });
3,709
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/sidebar/MailSidebarDriveSpotlight.tsx
import React, { useCallback } from 'react'; import { addDays, fromUnixTime } from 'date-fns'; import Spotlight from '@proton/components/components/spotlight/Spotlight'; import { FeatureCode } from '@proton/components/containers'; import { useActiveBreakpoint, useDriveWindowsGASpotlight, useFeature, useSpotlightOnFeature, useUser, useWelcomeFlags, } from '@proton/components/hooks'; import { isWindows } from '@proton/shared/lib/helpers/browser'; interface Props { renderDropdown: (hideSpotlight: () => void) => React.ReactElement; } /** * @deprecated Remove when operation is finished * MAILWEB-4357 */ const MailSidebarDriveSpotlight = ({ renderDropdown }: Props) => { const [user] = useUser(); const [spotlightProps, setShowSpotlight] = useDriveWindowsGASpotlight({ placement: 'bottom' }); const isSpotlightActive = !!useFeature(FeatureCode.DriveWindowsGAMailSpotlightShown).feature?.Value; const { show, onDisplayed } = useSpotlightOnFeature(FeatureCode.DriveWindowsGAMailSpotlight, isSpotlightActive); const userAccountHasMoreThanTwoDays = new Date() > addDays(fromUnixTime(user.CreateTime), 2); const { isNarrow } = useActiveBreakpoint(); const [{ isDone }] = useWelcomeFlags(); const hideSpotlight = useCallback(() => setShowSpotlight(false), []); /** * 1. The spotlight is active * 2. User has not seen the spotlight yet * 3. User is on windows * 4. User is not on a mobile screen * 5. User has done the welcome flow * 6. User has created his account more than 2 days ago */ const displaySpotlight = isSpotlightActive && show && isWindows() && !isNarrow && isDone && userAccountHasMoreThanTwoDays; if (displaySpotlight) { // Render children (AppsDropdown) with onDropdownClick to close the Spotlight return ( <Spotlight {...spotlightProps} onDisplayed={onDisplayed}> {renderDropdown(hideSpotlight)} </Spotlight> ); } return renderDropdown(hideSpotlight); }; export default MailSidebarDriveSpotlight;
3,710
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/sidebar/MailSidebarList.tsx
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useLocation } from 'react-router-dom'; import { c } from 'ttag'; import { HotkeyTuple, SidebarList, SimpleSidebarListItemHeader, useConversationCounts, useFolders, useHotkeys, useLabels, useLocalState, useMessageCounts, useSystemFolders, useUser, } from '@proton/components'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { hasBit } from '@proton/shared/lib/helpers/bitset'; import { scrollIntoView } from '@proton/shared/lib/helpers/dom'; import { buildTreeview } from '@proton/shared/lib/helpers/folder'; import { getItem, setItem } from '@proton/shared/lib/helpers/storage'; import { Folder, FolderWithSubFolders } from '@proton/shared/lib/interfaces/Folder'; import { SHOW_MOVED } from '@proton/shared/lib/mail/mailSettings'; import isTruthy from '@proton/utils/isTruthy'; import useMailModel from 'proton-mail/hooks/useMailModel'; import { LABEL_IDS_TO_HUMAN } from '../../constants'; import { getCounterMap } from '../../helpers/elements'; import { useDeepMemo } from '../../hooks/useDeepMemo'; import { LabelActionsContextProvider } from './EditLabelContext'; import MailSidebarListActions from './MailSidebarListActions'; import MailSidebarSystemFolders from './MailSidebarSystemFolders'; import SidebarFolders from './SidebarFolders'; import SidebarLabels from './SidebarLabels'; export type UnreadCounts = { [labelID: string]: number | undefined }; interface Props { labelID: string; } const formatFolderID = (folderID: string): string => `folder_expanded_state_${folderID}`; const MailSidebarList = ({ labelID: currentLabelID }: Props) => { const location = useLocation(); const [user] = useUser(); const [conversationCounts] = useConversationCounts(); const [messageCounts] = useMessageCounts(); const mailSettings = useMailModel('MailSettings'); const [systemFolders] = useSystemFolders(); const [labels] = useLabels(); const [folders, loadingFolders] = useFolders(); const numFolders = folders?.length || 0; const numLabels = labels?.length || 0; // Use user.ID or item because in the tests user ID is undefined const [displayFolders, toggleFolders] = useLocalState(numFolders > 0, `${user.ID || 'item'}-display-folders`); const [displayLabels, toggleLabels] = useLocalState(numLabels > 0, `${user.ID || 'item'}-display-labels`); const [displayMoreItems, toggleDisplayMoreItems] = useLocalState(false, `${user.ID || 'item'}-display-more-items`); const sidebarRef = useRef<HTMLDivElement>(null); const [focusedItem, setFocusedItem] = useState<string | null>(null); const [foldersUI, setFoldersUI] = useState<Folder[]>([]); const foldersTreeview = useMemo(() => buildTreeview(foldersUI), [foldersUI]); useEffect(() => { if (folders) { setFoldersUI( folders.map((folder) => ({ ...folder, Expanded: getItem(formatFolderID(folder.ID)) === 'false' ? 0 : 1, })) ); } }, [folders]); const handleToggleFolder = useCallback( (folder: Folder, expanded: boolean) => { // Update view setFoldersUI( foldersUI.map((folderItem: Folder) => { if (folderItem.ID === folder.ID) { return { ...folderItem, Expanded: expanded ? 1 : 0, }; } return folderItem; }) ); // Save expanded state locally setItem(formatFolderID(folder.ID), `${expanded}`); }, [foldersUI] ); const treeviewReducer = (acc: string[], folder: FolderWithSubFolders) => { acc.push(folder.ID); if (folder.Expanded) { folder.subfolders?.forEach((folder) => treeviewReducer(acc, folder)); } return acc; }; const reduceFolderTreeview = useMemo( () => foldersTreeview.reduce((acc: string[], folder: FolderWithSubFolders) => treeviewReducer(acc, folder), []), [foldersTreeview] ); const updateFocusItem = useCallback((item: string) => { setFocusedItem(item); const element = sidebarRef?.current?.querySelector(`[data-shortcut-target~="${item}"]`) as HTMLElement; // If the active element is already contained inside the item, don't re-focus the parent. This can happen when there's a button // inside the item which we want to take focus instead of the parent. if (element?.contains(document.activeElement) || document.activeElement === element) { return; } element?.focus(); scrollIntoView(element, { block: 'nearest' }); }, []); const counterMap = useDeepMemo(() => { if (!mailSettings || !labels || !folders || !conversationCounts || !messageCounts) { return {}; } const all = [...labels, ...folders]; const labelCounterMap = getCounterMap(all, conversationCounts, messageCounts, mailSettings); const unreadCounterMap = Object.entries(labelCounterMap).reduce<UnreadCounts>((acc, [id, labelCount]) => { acc[id] = labelCount?.Unread; return acc; }, {}); return unreadCounterMap; }, [mailSettings, labels, folders, conversationCounts, messageCounts, location]); const totalMessagesMap = useDeepMemo(() => { if (!mailSettings || !labels || !folders || !conversationCounts || !messageCounts) { return {}; } const all = [...labels, ...folders]; const labelCounterMap = getCounterMap(all, conversationCounts, messageCounts, mailSettings); const unreadCounterMap = Object.entries(labelCounterMap).reduce<UnreadCounts>((acc, [id, labelCount]) => { acc[id] = labelCount?.Total; return acc; }, {}); return unreadCounterMap; }, [messageCounts, conversationCounts, labels, folders, mailSettings, location]); const showScheduled = (totalMessagesMap[MAILBOX_LABEL_IDS.SCHEDULED] || 0) > 0; const showSnoozed = (totalMessagesMap[MAILBOX_LABEL_IDS.SNOOZED] || 0) > 0; const visibleSystemFolders = systemFolders?.filter((systemFolder) => { if (systemFolder.ID === MAILBOX_LABEL_IDS.OUTBOX) { return false; } if (systemFolder.ID === MAILBOX_LABEL_IDS.ALL_SENT) { return hasBit(mailSettings.ShowMoved, SHOW_MOVED.SENT); } if (systemFolder.ID === MAILBOX_LABEL_IDS.SENT) { return !hasBit(mailSettings.ShowMoved, SHOW_MOVED.SENT); } if (systemFolder.ID === MAILBOX_LABEL_IDS.ALL_DRAFTS) { return hasBit(mailSettings.ShowMoved, SHOW_MOVED.DRAFTS); } if (systemFolder.ID === MAILBOX_LABEL_IDS.DRAFTS) { return !hasBit(mailSettings.ShowMoved, SHOW_MOVED.DRAFTS); } if (systemFolder.ID === MAILBOX_LABEL_IDS.SCHEDULED) { return showScheduled; } if (systemFolder.ID === MAILBOX_LABEL_IDS.SNOOZED) { return showSnoozed; } return true; }); const sidebarListItems = useMemo(() => { const foldersArray = folders?.length ? reduceFolderTreeview : ['add-folder']; const labelsArray = labels?.length ? labels.map((f) => f.ID) : ['add-label']; const topSystemFolders: string[] = []; const bottomSystemFolders: string[] = []; visibleSystemFolders?.forEach((folder) => { const humanLabelID = LABEL_IDS_TO_HUMAN[folder.ID as MAILBOX_LABEL_IDS]; if (folder.Display) { topSystemFolders.push(humanLabelID); } else { bottomSystemFolders.push(humanLabelID); } }); return [ topSystemFolders?.length && topSystemFolders, 'toggle-more-items', displayMoreItems && bottomSystemFolders?.length && bottomSystemFolders, 'toggle-folders', displayFolders && foldersArray, 'toggle-labels', displayLabels && labelsArray, ] .flat(1) .filter(isTruthy); }, [ reduceFolderTreeview, folders, labels, visibleSystemFolders, showScheduled, showSnoozed, displayFolders, displayLabels, displayMoreItems, ]); const shortcutHandlers: HotkeyTuple[] = [ [ 'ArrowUp', (e) => { e.preventDefault(); const currentIndex = sidebarListItems.indexOf(focusedItem || ''); const previousIndex = currentIndex !== -1 ? Math.max(0, currentIndex - 1) : sidebarListItems.length - 1; updateFocusItem(sidebarListItems[previousIndex]); }, ], [ ['Meta', 'ArrowUp'], (e) => { e.preventDefault(); updateFocusItem(sidebarListItems[0]); }, ], [ 'ArrowDown', (e) => { e.preventDefault(); const currentIndex = sidebarListItems.indexOf(focusedItem || ''); const nextIndex = currentIndex !== -1 ? Math.min(sidebarListItems.length - 1, currentIndex + 1) : 0; updateFocusItem(sidebarListItems[nextIndex]); }, ], [ ['Meta', 'ArrowDown'], (e) => { e.preventDefault(); updateFocusItem(sidebarListItems[sidebarListItems.length - 1]); }, ], [ 'ArrowRight', () => { const element = (document.querySelector( '[data-shortcut-target="item-container"][data-shortcut-target-selected="true"]' ) as HTMLElement) || (document.querySelector('[data-shortcut-target="item-container"]') as HTMLElement); element?.focus(); }, ], ]; useHotkeys(sidebarRef, shortcutHandlers); return ( <LabelActionsContextProvider> <div ref={sidebarRef} tabIndex={-1} className="outline-none flex-item-grow-2"> <SidebarList> <MailSidebarSystemFolders counterMap={counterMap} currentLabelID={currentLabelID} location={location} mailSettings={mailSettings} setFocusedItem={setFocusedItem} totalMessagesMap={totalMessagesMap} displayMoreItems={displayMoreItems} showScheduled={showScheduled} showSnoozed={showSnoozed} onToggleMoreItems={toggleDisplayMoreItems} /> <SimpleSidebarListItemHeader toggle={displayFolders} onToggle={(display: boolean) => toggleFolders(display)} text={c('Link').t`Folders`} title={c('Link').t`Folders`} id="toggle-folders" onFocus={setFocusedItem} right={<MailSidebarListActions type="folder" items={folders || []} />} spaceAbove /> {displayFolders && ( <SidebarFolders currentLabelID={currentLabelID} counterMap={counterMap} folders={folders || []} loadingFolders={loadingFolders} updateFocusItem={updateFocusItem} handleToggleFolder={handleToggleFolder} foldersTreeview={foldersTreeview} /> )} <SimpleSidebarListItemHeader toggle={displayLabels} onToggle={(display: boolean) => toggleLabels(display)} text={c('Link').t`Labels`} title={c('Link').t`Labels`} id="toggle-labels" onFocus={setFocusedItem} right={<MailSidebarListActions type="label" items={labels || []} />} spaceAbove /> {displayLabels && ( <SidebarLabels currentLabelID={currentLabelID} counterMap={counterMap} labels={labels || []} updateFocusItem={updateFocusItem} /> )} </SidebarList> </div> </LabelActionsContextProvider> ); }; export default MailSidebarList;
3,711
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/sidebar/MailSidebarListActions.tsx
import { c } from 'ttag'; import { Icon, LabelsUpsellModal, SidebarListItemHeaderLink, Tooltip, useModalState, } from '@proton/components/components'; import { useUser } from '@proton/components/hooks'; import { APPS, MAIL_UPSELL_PATHS } from '@proton/shared/lib/constants'; import { hasReachedFolderLimit, hasReachedLabelLimit } from '@proton/shared/lib/helpers/folder'; import { Label } from '@proton/shared/lib/interfaces'; import { Folder } from '@proton/shared/lib/interfaces/Folder'; import { useLabelActionsContext } from './EditLabelContext'; interface LabelsProps { type: 'label'; items: Label[]; } interface FoldersProps { type: 'folder'; items: Folder[]; } export type Props = LabelsProps | FoldersProps; const MailSidebarListActions = ({ type, items }: Props) => { const [user] = useUser(); const { createLabel } = useLabelActionsContext(); const [upsellModalProps, handleUpsellModalDisplay, renderUpsellModal] = useModalState(); const handleCreate = () => { const canCreate = type === 'folder' ? !hasReachedFolderLimit(user, items) : !hasReachedLabelLimit(user, items); if (canCreate) { createLabel(type); } else { handleUpsellModalDisplay(true); } }; return ( <div className="flex flex-align-items-center"> <Tooltip title={type === 'label' ? c('Action').t`Create a new label` : c('Action').t`Create a new folder`}> <button type="button" className="flex navigation-link-header-group-control flex-item-noshrink" onClick={handleCreate} data-testid={type === 'label' ? 'navigation-link:add-label' : 'navigation-link:add-folder'} > <Icon name="plus" alt={type === 'label' ? c('Action').t`Create a new label` : c('Action').t`Create a new folder`} /> </button> </Tooltip> <Tooltip title={type === 'label' ? c('Info').t`Manage your labels` : c('Info').t`Manage your folders`}> <SidebarListItemHeaderLink to="/mail/folders-labels" toApp={APPS.PROTONACCOUNT} icon="cog-wheel" alt={type === 'label' ? c('Info').t`Manage your labels` : c('Link').t`Manage your folders`} target="_self" data-testid="navigation-link:labels-settings" /> </Tooltip> {renderUpsellModal && ( <LabelsUpsellModal modalProps={upsellModalProps} feature={ type === 'label' ? MAIL_UPSELL_PATHS.UNLIMITED_LABELS : MAIL_UPSELL_PATHS.UNLIMITED_FOLDERS } /> )} </div> ); }; export default MailSidebarListActions;
3,712
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/sidebar/MailSidebarPrimaryButton.tsx
import { c } from 'ttag'; import { Kbd } from '@proton/atoms'; import { SidebarPrimaryButton, Tooltip } from '@proton/components'; import useMailModel from 'proton-mail/hooks/useMailModel'; interface Props { handleCompose: () => void; } const MailSidebarPrimaryButton = ({ handleCompose }: Props) => { const { Shortcuts } = useMailModel('MailSettings'); const titlePrimaryButton = Shortcuts ? ( <> {c('Title').t`New message`} <br /> <Kbd shortcut="N" /> </> ) : null; const sideBarPrimaryButton = Shortcuts ? ( <Tooltip title={titlePrimaryButton} originalPlacement="top"> <SidebarPrimaryButton className="hidden md:inline" onClick={handleCompose} data-testid="sidebar:compose"> {c('Action').t`New message`} </SidebarPrimaryButton> </Tooltip> ) : ( <SidebarPrimaryButton className="hidden md:inline" onClick={handleCompose} data-testid="sidebar:compose"> {c('Action').t`New message`} </SidebarPrimaryButton> ); return sideBarPrimaryButton; }; export default MailSidebarPrimaryButton;
3,713
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/sidebar/MailSidebarSystemFolders.tsx
import { DragEvent, DragEventHandler, useEffect, useRef, useState } from 'react'; import { Location } from 'history'; import { c } from 'ttag'; import { FeatureCode, SimpleSidebarListItemHeader, useActiveBreakpoint, useFeature, useSpotlightOnFeature, useWelcomeFlags, } from '@proton/components'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { MailSettings } from '@proton/shared/lib/interfaces'; import clsx from '@proton/utils/clsx'; import { isConversationMode } from '../../helpers/mailSettings'; import useMoveSystemFolders, { SYSTEM_FOLDER_SECTION } from '../../hooks/useMoveSystemFolders'; import AlmostAllMailSpotlight from './AlmostAllMailSpotlight'; import { UnreadCounts } from './MailSidebarList'; import SidebarItem from './SidebarItem'; interface Props { counterMap: UnreadCounts; currentLabelID: string; location: Location; mailSettings: MailSettings; setFocusedItem: (id: string) => void; totalMessagesMap: UnreadCounts; displayMoreItems: boolean; showScheduled: boolean; showSnoozed: boolean; onToggleMoreItems: (display: boolean) => void; } const DND_MORE_FOLDER_ID = 'DND_MORE_FOLDER_ID'; interface DnDWrapperProps extends React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement> { isDnDAllowed: boolean; children: React.ReactElement; } const DnDElementWrapper = ({ isDnDAllowed, children, ...rest }: DnDWrapperProps) => { return isDnDAllowed ? <div {...rest}>{children}</div> : children; }; const MailSidebarSystemFolders = ({ counterMap, currentLabelID, location, mailSettings, setFocusedItem, showScheduled, showSnoozed, totalMessagesMap, displayMoreItems, onToggleMoreItems, }: Props) => { const { ShowMoved, AlmostAllMail } = mailSettings; const [sidebarElements, moveSidebarElement] = useMoveSystemFolders({ showMoved: ShowMoved, showScheduled, showSnoozed, showAlmostAllMail: AlmostAllMail, }); const isConversation = isConversationMode(currentLabelID, mailSettings, location); const lastDragTimeRef = useRef<number>(); const isDragging = useRef<boolean>(); const dragOverlay = useRef<HTMLDivElement>(); const [draggedElementId, setDraggedElementId] = useState<MAILBOX_LABEL_IDS | undefined>(); const [dragOveredElementId, setDragOveredElementId] = useState<string | undefined>(); const [isOverMoreFolder, setIsOverMoreFolder] = useState<boolean>(); const [{ isWelcomeFlow }] = useWelcomeFlags(); const { isNarrow } = useActiveBreakpoint(); const isAlmostAllMailEnabled = !!useFeature(FeatureCode.AlmostAllMail).feature?.Value; const { show: showAlmostAllMailSpotlight, onDisplayed: onAlmostAllMailSpotlightDisplayed, onClose: onAlmostAllMailSpotlightClose, } = useSpotlightOnFeature( FeatureCode.AlmostAllMailSpotlight, isAlmostAllMailEnabled && !isWelcomeFlow && !isNarrow ); const getCommonProps = (labelID: string) => ({ currentLabelID, labelID, isConversation, unreadCount: counterMap[labelID], totalMessagesCount: totalMessagesMap[labelID] || 0, }); type HandleDragOver = ( elementId: MAILBOX_LABEL_IDS | typeof DND_MORE_FOLDER_ID ) => DragEventHandler<HTMLDivElement>; const handleDragOver: HandleDragOver = (elementId) => (event) => { if (!isDragging.current) { event.preventDefault(); return; } // "dragover" event must be prevented to allow "drop" event event.preventDefault(); if (elementId === DND_MORE_FOLDER_ID && displayMoreItems === false) { setIsOverMoreFolder(true); } else { setIsOverMoreFolder(false); } setDragOveredElementId(elementId); lastDragTimeRef.current = Date.now(); }; const handleDragStart = (labelId: MAILBOX_LABEL_IDS) => (event: DragEvent<HTMLDivElement>) => { if (labelId === MAILBOX_LABEL_IDS.INBOX) { event.preventDefault(); event.stopPropagation(); return; } const draggedSystemFolder = sidebarElements.find((element) => labelId === element.labelID); if (!draggedSystemFolder) { return; } const sidebarElementName = draggedSystemFolder.text; dragOverlay.current = document.createElement('div'); // translator: This is the text overlay following the cursor when dragging a sidebar element. Ex: Move Inbox dragOverlay.current.innerHTML = c('Label').t`Move ${sidebarElementName}`; dragOverlay.current.className = 'absolute bg-weak text-white py-2 px-4 rounded'; document.body.appendChild(dragOverlay.current); event.dataTransfer.setDragImage(dragOverlay.current, 0, 30); setDraggedElementId(labelId); isDragging.current = true; }; const handleResetDragState = () => { isDragging.current = false; setDraggedElementId(undefined); setDragOveredElementId(undefined); setIsOverMoreFolder(undefined); if (dragOverlay.current) { document.body.removeChild(dragOverlay.current); lastDragTimeRef.current = undefined; isDragging.current = undefined; dragOverlay.current = undefined; } }; type HandleDrop = ( droppedId: MAILBOX_LABEL_IDS | 'MORE_FOLDER_ITEM', draggedId: MAILBOX_LABEL_IDS | undefined ) => DragEventHandler; const handleDrop: HandleDrop = (droppedId, draggedId) => (event: DragEvent<HTMLDivElement>) => { event.preventDefault(); if (!isDragging.current || !draggedId) { return; } handleResetDragState(); moveSidebarElement(draggedId, droppedId); }; const getDnDClasses = (hoveredId: MAILBOX_LABEL_IDS, draggedId: MAILBOX_LABEL_IDS | undefined) => { if (dragOveredElementId !== hoveredId || hoveredId === draggedId || draggedId === MAILBOX_LABEL_IDS.INBOX) { return ''; } const draggedElementOrder = sidebarElements.find((el) => el.labelID === draggedId)?.order; const hoveredElementOrder = sidebarElements.find((el) => el.labelID === hoveredId)?.order; if (!draggedElementOrder || !hoveredElementOrder) { return undefined; } const goesUp = draggedElementOrder > hoveredElementOrder; if (hoveredId === MAILBOX_LABEL_IDS.INBOX) { return 'border-bottom'; } return goesUp ? 'border-top' : 'border-bottom'; }; // Set dragOveredElementId useEffect(() => { if (!dragOveredElementId) { return; } const interval = setInterval(() => { const lastDragTime = lastDragTimeRef.current || 0; const elapsedTime = Date.now() - lastDragTime; if (elapsedTime > 300) { setDragOveredElementId(undefined); lastDragTimeRef.current = undefined; } }, 150); return () => { clearInterval(interval); }; }, [dragOveredElementId]); // Opens the "more" folder useEffect(() => { if (!isOverMoreFolder) { return; } const OPEN_FOLDER_AFTER = 1000; const now = Date.now(); const timeout = setTimeout(() => { const lastDragOverTime = lastDragTimeRef.current || 0; if (now - 50 < lastDragOverTime) { onToggleMoreItems(true); } }, OPEN_FOLDER_AFTER); return () => { clearTimeout(timeout); }; }, [isOverMoreFolder]); return ( <> {sidebarElements .filter((element) => element.display === SYSTEM_FOLDER_SECTION.MAIN) .map((element) => ( <DnDElementWrapper isDnDAllowed key={element.ID} onDragStart={handleDragStart(element.labelID)} onDragEnd={handleResetDragState} onDragOver={handleDragOver(element.labelID)} onDrop={handleDrop(element.labelID, draggedElementId)} className={clsx([getDnDClasses(element.labelID, draggedElementId)])} onClick={(e) => e.stopPropagation()} > <SidebarItem {...getCommonProps(element.labelID)} icon={element.icon} id={element.ID} hideCountOnHover={false} isFolder={element.labelID !== MAILBOX_LABEL_IDS.STARRED} onFocus={setFocusedItem} shortcutText={element.shortcutText} text={element.text} /> </DnDElementWrapper> ))} <DnDElementWrapper isDnDAllowed key={'MORE_FOLDER_ITEM'} onDragOver={handleDragOver(DND_MORE_FOLDER_ID)} onDrop={handleDrop('MORE_FOLDER_ITEM', draggedElementId)} > <SimpleSidebarListItemHeader toggle={displayMoreItems} onToggle={(display: boolean) => onToggleMoreItems(display)} text={displayMoreItems ? c('Link').t`Less` : c('Link').t`More`} title={displayMoreItems ? c('Link').t`Less` : c('Link').t`More`} id="toggle-more-items" onFocus={setFocusedItem} /> </DnDElementWrapper> {displayMoreItems ? sidebarElements .filter((element) => element.display === SYSTEM_FOLDER_SECTION.MORE) .map((element) => { const child = ( <DnDElementWrapper isDnDAllowed onClick={(e) => e.stopPropagation()} key={element.ID} onDragStart={handleDragStart(element.labelID)} onDragEnd={handleResetDragState} onDragOver={handleDragOver(element.labelID)} onDrop={handleDrop(element.labelID, draggedElementId)} className={clsx([getDnDClasses(element.labelID, draggedElementId)])} > <SidebarItem {...getCommonProps(element.labelID)} icon={element.icon} id={element.ID} isFolder={element.labelID !== MAILBOX_LABEL_IDS.STARRED} hideCountOnHover={false} onFocus={setFocusedItem} shortcutText={element.shortcutText} text={element.text} /> </DnDElementWrapper> ); return element.labelID === MAILBOX_LABEL_IDS.ALMOST_ALL_MAIL ? ( <AlmostAllMailSpotlight key={`spotlight-${element.ID}`} show={showAlmostAllMailSpotlight} onDisplayed={onAlmostAllMailSpotlightDisplayed} onClose={onAlmostAllMailSpotlightClose} > <div>{child}</div> </AlmostAllMailSpotlight> ) : ( child ); }) : null} </> ); }; export default MailSidebarSystemFolders;
3,714
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/sidebar/SidebarFolder.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { FolderIcon, HotkeyTuple, Icon } from '@proton/components'; import { formatFolderName } from '@proton/shared/lib/helpers/folder'; import { FolderWithSubFolders } from '@proton/shared/lib/interfaces/Folder'; import clsx from '@proton/utils/clsx'; import SidebarItem from './SidebarItem'; import SidebarLabelActions from './SidebarLabelActions'; interface Props { currentLabelID: string; folder: FolderWithSubFolders; level: number; onToggle: (folder: FolderWithSubFolders, expanded: boolean) => void; unreadCount?: number; expanded?: boolean; onFocus: (id: string) => void; id: string; treeMode?: boolean; } const SidebarFolder = ({ currentLabelID, folder, level, onToggle, unreadCount, expanded, onFocus, id, treeMode = true, }: Props) => { const [isOptionDropdownOpened, setIsOptionDropdownOpened] = useState(false); const shortcutHandlers: HotkeyTuple[] = [ [ 'ArrowRight', (e) => { if (!expanded) { e.stopPropagation(); onToggle(folder, true); } }, ], [ 'ArrowLeft', () => { if (expanded) { onToggle(folder, false); } }, ], ]; const noChevron = treeMode ? <span className="navigation-icon-empty flex-item-noshrink" /> : null; return ( <SidebarItem currentLabelID={currentLabelID} labelID={folder.ID} isFolder text={folder.Name} unreadCount={unreadCount} shortcutHandlers={shortcutHandlers} id={id} onFocus={onFocus} isOptionDropdownOpened={isOptionDropdownOpened} content={ <div className="flex flex-nowrap flex-align-items-center gap-2" data-level={level}> {folder.subfolders?.length ? ( <button type="button" className="flex-item-noshrink navigation-link--expand relative interactive-pseudo-inset interactive--no-background" aria-expanded={!!folder.Expanded} onClick={(e) => { e.stopPropagation(); e.preventDefault(); onToggle(folder, !expanded); }} > <Icon name="chevron-down-filled" className={clsx([ 'navigation-icon navigation-icon--expand', !folder.Expanded && 'rotateZ-270', ])} /> </button> ) : ( noChevron )} <FolderIcon className="navigation-icon flex-item-noshrink" alt={c('Info').t`Folder`} folder={folder} /> <div className="text-ellipsis">{formatFolderName(level, folder.Name)}</div> </div> } itemOptions={ <SidebarLabelActions type={'folder'} element={folder} onToggleDropdown={setIsOptionDropdownOpened} /> } /> ); }; export default SidebarFolder;
3,715
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/sidebar/SidebarFolders.tsx
import { ReactNode, memo } from 'react'; import * as React from 'react'; import { c } from 'ttag'; import { Folder, FolderWithSubFolders } from '@proton/shared/lib/interfaces/Folder'; import { getUnreadCount } from '../../helpers/sidebar'; import { UnreadCounts } from './MailSidebarList'; import SidebarFolder from './SidebarFolder'; interface Props { currentLabelID: string; counterMap: UnreadCounts; folders: Folder[]; loadingFolders: boolean; updateFocusItem: (item: string) => void; handleToggleFolder: (folder: Folder, expanded: boolean) => void; foldersTreeview: FolderWithSubFolders[]; } const SidebarFolders = ({ currentLabelID, counterMap, folders, loadingFolders, updateFocusItem, handleToggleFolder, foldersTreeview, }: Props) => { const onlyOneLevel = foldersTreeview.every((folder) => !folder.subfolders?.length); const emptyFolders = !loadingFolders && !folders?.length; const treeviewReducer = (acc: ReactNode[], folder: FolderWithSubFolders, level = 0): any[] => { acc.push( <SidebarFolder key={folder.ID} currentLabelID={currentLabelID} folder={folder} level={level} onToggle={handleToggleFolder} expanded={Boolean(folder.Expanded)} unreadCount={getUnreadCount(counterMap, folder)} id={folder.ID} onFocus={updateFocusItem} treeMode={!onlyOneLevel} /> ); if (folder.Expanded && Array.isArray(folder.subfolders) && folder.subfolders.length) { folder.subfolders.forEach((folder: FolderWithSubFolders) => treeviewReducer(acc, folder, level + 1)); } return acc; }; return emptyFolders ? ( <div className="py-2 ml-7 text-sm color-weak">{c('Description').t`No folders`}</div> ) : ( <> {foldersTreeview.reduce( (acc: React.ReactNode[], folder: FolderWithSubFolders) => treeviewReducer(acc, folder), [] )} </> ); }; export default memo(SidebarFolders);
3,716
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/sidebar/SidebarItem.tsx
import { ReactNode, memo, useRef } from 'react'; import { useHistory } from 'react-router-dom'; import { HotkeyTuple, IconName, IconSize, SidebarListItem, SidebarListItemContent, SidebarListItemContentIcon, SidebarListItemLink, useEventManager, useHotkeys, useItemsDroppable, } from '@proton/components'; import { useLoading } from '@proton/hooks'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { wait } from '@proton/shared/lib/helpers/promise'; import clsx from '@proton/utils/clsx'; import isTruthy from '@proton/utils/isTruthy'; import noop from '@proton/utils/noop'; import useMailModel from 'proton-mail/hooks/useMailModel'; import { LABEL_IDS_TO_HUMAN } from '../../constants'; import { shouldDisplayTotal } from '../../helpers/labels'; import { useApplyLabels } from '../../hooks/actions/useApplyLabels'; import { useMoveToFolder } from '../../hooks/actions/useMoveToFolder'; import { useGetElementsFromIDs } from '../../hooks/mailbox/useElements'; import LocationAside from './LocationAside'; const { ALL_MAIL, ALMOST_ALL_MAIL, DRAFTS, ALL_DRAFTS, SENT, ALL_SENT, SCHEDULED, SNOOZED } = MAILBOX_LABEL_IDS; const NO_DROP: string[] = [ALL_MAIL, ALMOST_ALL_MAIL, DRAFTS, ALL_DRAFTS, SENT, ALL_SENT, SCHEDULED, SNOOZED]; const defaultShortcutHandlers: HotkeyTuple[] = []; interface Props { currentLabelID: string; labelID: string; isFolder: boolean; hideCountOnHover?: boolean; icon?: IconName; iconSize?: IconSize; text: string; shortcutText?: string; content?: ReactNode; itemOptions?: ReactNode; color?: string; unreadCount?: number; totalMessagesCount?: number; shortcutHandlers?: HotkeyTuple[]; onFocus?: (id: string) => void; isOptionDropdownOpened?: boolean; id?: string; } const SidebarItem = ({ currentLabelID, labelID, icon, iconSize, text, shortcutText, content = text, itemOptions, color, isFolder, hideCountOnHover = true, unreadCount, totalMessagesCount = 0, shortcutHandlers = defaultShortcutHandlers, onFocus = noop, id, isOptionDropdownOpened, }: Props) => { const { call } = useEventManager(); const history = useHistory(); const { Shortcuts } = useMailModel('MailSettings'); const getElementsFromIDs = useGetElementsFromIDs(); const [refreshing, withRefreshing] = useLoading(false); const applyLabels = useApplyLabels(); const { moveToFolder, moveScheduledModal, moveSnoozedModal, moveAllModal, moveToSpamModal } = useMoveToFolder(); const humanID = LABEL_IDS_TO_HUMAN[labelID as MAILBOX_LABEL_IDS] ? LABEL_IDS_TO_HUMAN[labelID as MAILBOX_LABEL_IDS] : labelID; const link = `/${humanID}`; const isActive = labelID === currentLabelID; const ariaCurrent = isActive ? 'page' : undefined; const needsTotalDisplay = shouldDisplayTotal(labelID); const handleClick = (event: React.MouseEvent<HTMLAnchorElement>) => { if ( history.location.pathname.endsWith(link) && // No search, no paging, nothing history.location.hash === '' && // Not already refreshing !refreshing ) { event.preventDefault(); void withRefreshing(Promise.all([call(), wait(1000)])); } }; const handleRefresh = () => { void withRefreshing(Promise.all([call(), wait(1000)])); }; const canDrop = () => { const isNonDroppableFolder = NO_DROP.includes(labelID); return !isActive && !isNonDroppableFolder; }; const { dragOver, dragProps, handleDrop } = useItemsDroppable(canDrop, isFolder ? 'move' : 'link', (itemIDs) => { const elements = getElementsFromIDs(itemIDs); if (canDrop()) { if (isFolder) { void moveToFolder(elements, labelID, text, currentLabelID, false); } else { void applyLabels(elements, { [labelID]: true }, false); } } }); const elementRef = useRef<HTMLAnchorElement>(null); useHotkeys(elementRef, shortcutHandlers); return ( <SidebarListItem className={clsx([ dragOver && 'navigation__dragover', 'group-hover-hide-container group-hover-opacity-container', ])} data-testid={`sidebar-label:${text}`} > <SidebarListItemLink aria-current={ariaCurrent} to={link} onClick={handleClick} {...dragProps} onDrop={handleDrop} ref={elementRef} data-testid={`navigation-link:${humanID}`} data-shortcut-target={['navigation-link', id].filter(isTruthy).join(' ')} onFocus={() => onFocus(id || '')} > <SidebarListItemContent left={icon ? <SidebarListItemContentIcon name={icon} color={color} size={iconSize} /> : undefined} right={ <LocationAside unreadCount={needsTotalDisplay ? totalMessagesCount : unreadCount} weak={labelID !== MAILBOX_LABEL_IDS.INBOX} active={isActive} refreshing={refreshing} onRefresh={handleRefresh} shouldDisplayTotal={needsTotalDisplay} hideCountOnHover={hideCountOnHover} itemOptions={itemOptions} isOptionDropdownOpened={isOptionDropdownOpened} /> } > <span className="text-ellipsis" title={shortcutText !== undefined && Shortcuts ? `${text} ${shortcutText}` : text} > {content} </span> </SidebarListItemContent> </SidebarListItemLink> {moveScheduledModal} {moveSnoozedModal} {moveAllModal} {moveToSpamModal} </SidebarListItem> ); }; export default memo(SidebarItem);
3,717
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/sidebar/SidebarLabelActions.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { DropdownMenuButton, Icon, SimpleDropdown, Tooltip } from '@proton/components/components'; import { Label } from '@proton/shared/lib/interfaces'; import { useLabelActionsContext } from './EditLabelContext'; interface Props { type: 'folder' | 'label'; element: Label; onToggleDropdown: (value: boolean) => void; } const SidebarLabelActions = ({ type, element, onToggleDropdown }: Props) => { const { editLabel, deleteLabel } = useLabelActionsContext(); return ( <span // Stop click propagation to avoid Label/Folder selection onClick={(e) => { e.preventDefault(); e.stopPropagation(); }} // To keep dropdown keyboard interactions working onFocus={(e) => { e.stopPropagation(); }} className="block" > <Tooltip title={type === 'folder' ? c('Title').t`Folder options` : c('Title').t`Label options`}> <SimpleDropdown as={Button} className="rounded-sm" icon hasCaret={false} shape="ghost" size="small" content={<Icon name="three-dots-horizontal" />} onToggle={onToggleDropdown} > <DropdownMenuButton className="text-left" onClick={() => { editLabel(type, element); }} > {type === 'folder' ? c('Action').t`Edit folder` : c('Action').t`Edit label`} </DropdownMenuButton> <DropdownMenuButton className="text-left color-danger" onClick={() => { deleteLabel(type, element); }} > {type === 'folder' ? c('Action').t`Delete folder` : c('Action').t`Delete label`} </DropdownMenuButton> </SimpleDropdown> </Tooltip> </span> ); }; export default SidebarLabelActions;
3,718
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/sidebar/SidebarLabels.tsx
import { memo, useState } from 'react'; import { c } from 'ttag'; import { Label } from '@proton/shared/lib/interfaces/Label'; import { UnreadCounts } from './MailSidebarList'; import SidebarItem from './SidebarItem'; import SidebarLabelActions from './SidebarLabelActions'; interface LabelProps { currentLabelID: string; counterMap: UnreadCounts; label: Label; updateFocusItem: (item: string) => void; } const SidebarLabel = ({ currentLabelID, counterMap, label, updateFocusItem }: LabelProps) => { const [isOptionDropdownOpened, setIsOptionDropdownOpened] = useState(false); return ( <SidebarItem currentLabelID={currentLabelID} labelID={label.ID} isOptionDropdownOpened={isOptionDropdownOpened} icon="circle-filled" iconSize={16} text={label.Name} color={label.Color} isFolder={false} unreadCount={counterMap[label.ID]} id={label.ID} onFocus={updateFocusItem} itemOptions={ <SidebarLabelActions type={'label'} element={label} onToggleDropdown={setIsOptionDropdownOpened} /> } /> ); }; interface LabelsProps { currentLabelID: string; counterMap: UnreadCounts; labels: Label[]; updateFocusItem: (item: string) => void; } const SidebarLabels = ({ currentLabelID, counterMap, labels, updateFocusItem }: LabelsProps) => { return labels.length === 0 ? ( <div className="py-2 ml-7 text-sm color-weak">{c('Description').t`No labels`}</div> ) : ( <> {labels.map((label) => ( <SidebarLabel key={label.ID} label={label} updateFocusItem={updateFocusItem} currentLabelID={currentLabelID} counterMap={counterMap} /> ))} </> ); }; export default memo(SidebarLabels);
3,719
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/sidebar/SidebarVersion.tsx
import { AppVersion } from '@proton/components'; import changelog from '../../../../CHANGELOG.md'; const SidebarVersion = () => { return <AppVersion changelog={changelog} />; }; export default SidebarVersion;
3,720
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/simpleLogin/SimpleLoginModal.scss
@import '~@proton/styles/scss/lib'; .simple-login-modal { // Special case otherwise modal is not properly displayed --size: #{rem(700)}; }
3,721
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/simpleLogin/SimpleLoginModal.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, PrimaryButton, useApi, } from '@proton/components'; import { createSLUser } from '@proton/shared/lib/api/simpleLogin'; import { TelemetrySimpleLoginEvents } from '@proton/shared/lib/api/telemetry'; import { BRAND_NAME, SIMPLE_LOGIN_EXTENSION_LINKS } from '@proton/shared/lib/constants'; import { isSafari } from '@proton/shared/lib/helpers/browser'; import connectSimpleLoginSvg from '@proton/styles/assets/img/illustrations/connect-simple-login.svg'; import { useSimpleLoginExtension } from '../../hooks/simpleLogin/useSimpleLoginExtension'; import { useSimpleLoginTelemetry } from '../../hooks/simpleLogin/useSimpleLoginTelemetry'; import './SimpleLoginModal.scss'; interface Props extends ModalProps {} const SimpleLoginModal = ({ ...rest }: Props) => { const [loading, setLoading] = useState(false); const { canUseExtension } = useSimpleLoginExtension(); const { handleSendTelemetryData } = useSimpleLoginTelemetry(); const api = useApi(); const { onClose } = rest; const BRAND_NAME_TWO = BRAND_NAME; const installAndGoText = isSafari() ? // translator: Full sentence "Your Proton Account includes SimpleLogin. Install the browser extension with one click to get started."" c('Info') .t`Your ${BRAND_NAME} Account includes SimpleLogin. Install the browser extension with one click to get started.` : // translator: Full sentence "SimpleLogin is a Proton service, and your Proton Account includes hide-my-email aliases. To start masking your email address, go to SimpleLogin and create your first alias." c('Info') .t`SimpleLogin is a ${BRAND_NAME} service, and your ${BRAND_NAME_TWO} Account includes hide-my-email aliases. To start masking your email address, go to SimpleLogin and create your first alias.`; const handlePluginAction = async () => { setLoading(true); let url = ''; // In Safari there is no browser extension, so we redirect to the SL dashboard if (isSafari()) { void api(createSLUser()); url = SIMPLE_LOGIN_EXTENSION_LINKS.DASHBOARD; } else { // Otherwise, we can open the extension const { Redirect } = await api(createSLUser('browser_extension')); url = Redirect; } setLoading(false); // We need to send a telemetry request when the user clicks on the go to SL button handleSendTelemetryData(TelemetrySimpleLoginEvents.go_to_simplelogin, {}, true); window.open(url, '_blank'); onClose?.(); }; const getButtonText = () => { if (!canUseExtension) { return c('Action').t`Go to SimpleLogin`; } return c('Action').t`Get SimpleLogin extension`; }; return ( <ModalTwo {...rest} className="simple-login-modal"> <ModalTwoHeader title={c('Title').t`Hide your email with SimpleLogin by ${BRAND_NAME}`} /> <ModalTwoContent> <div className="text-center"> <img src={connectSimpleLoginSvg} alt={c('Alternative text for SimpleLogin image').t`SimpleLogin`} /> </div> <div>{c('Info') .t`SimpleLogin provides a simple way to create logins at untrusted third-party sites where you don't want to expose your actual email address.`}</div> <br /> <div className="mb-2"> <strong>{c('Info').t`How hide-my-email aliases works`}</strong> </div> <ul className="my-0"> <li className="mb-4">{c('Info') .t`When giving out your email, use a unique, disposable hide-my-email alias instead of your real email address.`}</li> <li className="mb-4">{c('Info') .t`Email is forwarded to your mailbox; your email address stays hidden.`}</li> <li>{c('Info') .t`If your alias is sold, leaked, or abused, simply disable it to stop receiving spam.`}</li> </ul> <br /> <div className="mb-2"> <strong>{c('Info').t`Using SimpleLogin is easy`}</strong> </div> <div>{installAndGoText}</div> </ModalTwoContent> <ModalTwoFooter> <PrimaryButton onClick={handlePluginAction} className="ml-auto" loading={loading}> {getButtonText()} </PrimaryButton> </ModalTwoFooter> </ModalTwo> ); }; export default SimpleLoginModal;
3,722
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/toolbar/DeleteButton.tsx
import { c } from 'ttag'; import { Kbd } from '@proton/atoms'; import { Icon, ToolbarButton } from '@proton/components'; import { useLoading } from '@proton/hooks'; import { metaKey } from '@proton/shared/lib/helpers/browser'; import useMailModel from 'proton-mail/hooks/useMailModel'; interface Props { selectedIDs: string[]; onDelete: () => Promise<void>; } const DeleteButton = ({ onDelete, selectedIDs = [] }: Props) => { const [loading, withLoading] = useLoading(); const { Shortcuts } = useMailModel('MailSettings'); const titleDelete = Shortcuts ? ( <> {c('Action').t`Delete permanently`} <br /> <Kbd shortcut={metaKey} /> + <Kbd shortcut="Backspace" /> </> ) : ( c('Action').t`Delete permanently` ); return ( <ToolbarButton title={titleDelete} onClick={() => withLoading(onDelete())} disabled={loading || !selectedIDs.length} data-testid="toolbar:deletepermanently" icon={<Icon name="cross-circle" alt={c('Action').t`Delete permanently`} />} /> ); }; export default DeleteButton;
3,723
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/toolbar/EmptyButton.tsx
import { c } from 'ttag'; import { Kbd, Vr } from '@proton/atoms'; import { Icon, ToolbarButton, useLabels } from '@proton/components'; import { useLoading } from '@proton/hooks'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { metaKey, shiftKey } from '@proton/shared/lib/helpers/browser'; import useMailModel from 'proton-mail/hooks/useMailModel'; import { isCustomLabel, labelIncludes } from '../../helpers/labels'; import { useEmptyLabel } from '../../hooks/actions/useEmptyLabel'; import { Breakpoints } from '../../models/utils'; const { DRAFTS, ALL_DRAFTS, ALL_MAIL, ALMOST_ALL_MAIL, INBOX, SENT, ALL_SENT, ARCHIVE, STARRED, TRASH, SPAM } = MAILBOX_LABEL_IDS; interface Props { labelID: string; breakpoints: Breakpoints; elementIDs: string[]; } const EmptyButton = ({ labelID = '', breakpoints, elementIDs }: Props) => { const [loading, withLoading] = useLoading(); const [labels = []] = useLabels(); const { emptyLabel, modal: deleteAllModal } = useEmptyLabel(); const { Shortcuts } = useMailModel('MailSettings'); const displayEmpty = !breakpoints.isNarrow && !labelIncludes(labelID, INBOX, DRAFTS, ALL_DRAFTS, STARRED, SENT, ALL_SENT, ARCHIVE, ALL_MAIL, ALMOST_ALL_MAIL); if (!displayEmpty) { return null; } const handleClick = () => withLoading(emptyLabel(labelID)); const isLabel = isCustomLabel(labelID, labels); let title; if (labelID === TRASH) { title = c('Action').t`Empty trash`; } else if (labelID === SPAM) { title = c('Action').t`Empty spam`; } else if (isLabel) { title = c('Action').t`Empty label`; } else { title = c('Action').t`Empty folder`; } const titleEmpty = Shortcuts ? ( <> {title} <br /> <Kbd shortcut={metaKey} /> + <Kbd shortcut={shiftKey} /> + <Kbd shortcut="Backspace" /> </> ) : ( title ); return ( <> <Vr /> <ToolbarButton disabled={loading || !elementIDs.length} title={titleEmpty} onClick={handleClick} data-testid="toolbar:empty-folder" icon={<Icon name="broom" alt={title} />} /> {deleteAllModal} </> ); }; export default EmptyButton;
3,724
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/toolbar/FilterActions.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { DropdownMenu, DropdownMenuButton, SimpleDropdown } from '@proton/components'; import { MailSettings } from '@proton/shared/lib/interfaces'; import { MESSAGE_BUTTONS } from '@proton/shared/lib/mail/mailSettings'; import clsx from '@proton/utils/clsx'; import { Filter } from '../../models/tools'; interface Props { filter: Filter; onFilter: (filter: Filter) => void; mailSettings: MailSettings; dropdown?: boolean; } const FilterActions = ({ filter = {}, mailSettings, onFilter, dropdown }: Props) => { const noFilterApply = !Object.values(filter).length; const FILTER_OPTIONS = { SHOW_ALL: c('Filter option').t`All`, SHOW_UNREAD: c('Filter option').t`Unread`, SHOW_READ: c('Filter option').t`Read`, SHOW_MOVED_MESSAGE: c('Filter option').t`Show moved message`, HIDE_MOVED_MESSAGE: c('Filter option').t`Hide moved message`, HAS_FILE: c('Filter option to only show message with attachments').t`Has file`, }; const readUnreadButtons = [ { text: FILTER_OPTIONS.SHOW_READ, ID: 'filter-dropdown:show-read', isActive: filter.Unread === 0, onClick() { if (filter.Unread !== 0) { onFilter({ Unread: 0 }); } }, }, { text: FILTER_OPTIONS.SHOW_UNREAD, ID: 'filter-dropdown:show-unread', isActive: filter.Unread === 1, onClick() { if (filter.Unread !== 1) { onFilter({ Unread: 1 }); } }, }, ]; const buttons = [ { text: FILTER_OPTIONS.SHOW_ALL, ID: 'filter-dropdown:show-all', isActive: noFilterApply, onClick() { if (!noFilterApply) { onFilter({}); } }, }, ...(mailSettings.MessageButtons === MESSAGE_BUTTONS.READ_UNREAD ? readUnreadButtons : readUnreadButtons.reverse()), { text: FILTER_OPTIONS.HAS_FILE, ID: 'filter-dropdown:has-file', isActive: filter.Attachments === 1, onClick() { onFilter({ Attachments: 1 }); }, }, ]; if (dropdown) { const { text = '' } = buttons.find(({ isActive }) => isActive) || {}; return ( <SimpleDropdown as={Button} shape="ghost" size="small" hasCaret={true} className="toolbar-button toolbar-button--small" content={ <span className="flex flex-align-items-center flex-nowrap" data-testid="toolbar:filter-dropdown"> <span className="text-sm m-0">{text}</span> </span> } > <DropdownMenu> <div className="text-bold w-full px-4 py-2">{c('Filter').t`Show`}</div> {buttons.map(({ ID, text, isActive, onClick }) => { return ( <DropdownMenuButton key={ID} data-testid={ID} onClick={onClick} className="text-left" isSelected={isActive} > {text} </DropdownMenuButton> ); })} </DropdownMenu> </SimpleDropdown> ); } return ( <div className="flex flex-nowrap md:gap-1"> {buttons.map(({ ID, text, isActive, onClick }) => { return ( <Button key={ID} data-testid={ID} size="small" shape="ghost" aria-pressed={isActive} className={clsx([ 'toolbar-button toolbar-button--small text-sm m-0', isActive && 'no-pointer-events bg-strong', ])} onClick={onClick} > {text} </Button> ); })} </div> ); }; export default FilterActions;
3,725
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/toolbar/LabelName.tsx
import React from 'react'; interface Props { selectedIDs: string[]; labelName: string; } const LabelName = ({ selectedIDs = [], labelName }: Props) => { return ( <> {selectedIDs.length === 0 && ( <div className="flex-item-fluid"> <h2 title={labelName} className="text-lg text-bold text-ellipsis"> {labelName} </h2> </div> )} </> ); }; export default LabelName;
3,726
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/toolbar/LabelsAndFolders.tsx
import { Ref } from 'react'; import { c } from 'ttag'; import { Kbd, Vr } from '@proton/atoms'; import { DropdownSizeUnit, Icon } from '@proton/components'; import useMailModel from 'proton-mail/hooks/useMailModel'; import { Breakpoints } from '../../models/utils'; import LabelDropdown, { labelDropdownContentProps } from '../dropdown/LabelDropdown'; import MoveDropdown, { moveDropdownContentProps } from '../dropdown/MoveDropdown'; import ToolbarDropdown from './ToolbarDropdown'; interface Props { labelID: string; selectedIDs: string[]; breakpoints: Breakpoints; labelDropdownToggleRef: Ref<() => void>; moveDropdownToggleRef: Ref<() => void>; } const LabelsAndFolders = ({ labelID, selectedIDs, breakpoints, labelDropdownToggleRef, moveDropdownToggleRef, }: Props) => { const { Shortcuts } = useMailModel('MailSettings'); if (!selectedIDs.length) { return null; } const titleMove = Shortcuts ? ( <> {c('Title').t`Move to`} <br /> <Kbd shortcut="M" /> </> ) : ( c('Title').t`Move to` ); const titleLabel = Shortcuts ? ( <> {c('Title').t`Label as`} <br /> <Kbd shortcut="L" /> </> ) : ( c('Title').t`Label as` ); return ( <> <Vr /> <ToolbarDropdown autoClose={false} dropdownSize={{ maxWidth: '22em', maxHeight: DropdownSizeUnit.Viewport }} disabled={!selectedIDs || !selectedIDs.length} content={<Icon className="toolbar-icon" name="folder-arrow-in" />} dropDownClassName="move-dropdown" className="move-dropdown-button" title={titleMove} data-testid="toolbar:moveto" externalToggleRef={moveDropdownToggleRef} hasCaret={false} > {{ contentProps: moveDropdownContentProps, render: ({ onClose, onLock }) => ( <MoveDropdown labelID={labelID} selectedIDs={selectedIDs} onClose={onClose} onLock={onLock} breakpoints={breakpoints} /> ), }} </ToolbarDropdown> <ToolbarDropdown autoClose={false} dropdownSize={{ maxWidth: '22em', maxHeight: DropdownSizeUnit.Viewport }} disabled={!selectedIDs || !selectedIDs.length} content={<Icon className="toolbar-icon" name="tag" />} dropDownClassName="label-dropdown" className="label-dropdown-button" title={titleLabel} data-testid="toolbar:labelas" externalToggleRef={labelDropdownToggleRef} hasCaret={false} > {{ contentProps: labelDropdownContentProps, render: ({ onClose, onLock }) => ( <LabelDropdown labelID={labelID} selectedIDs={selectedIDs} onClose={onClose} onLock={onLock} breakpoints={breakpoints} /> ), }} </ToolbarDropdown> </> ); }; export default LabelsAndFolders;
3,727
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/toolbar/MoreActions.tsx
import { useRef } from 'react'; import { c } from 'ttag'; import { DropdownMenu, DropdownMenuButton, Icon } from '@proton/components/components'; import { FeatureCode } from '@proton/components/containers'; import { useFeature } from '@proton/components/hooks'; import noop from '@proton/utils/noop'; import { useGetElementsFromIDs } from '../../hooks/mailbox/useElements'; import useBlockSender from '../../hooks/useBlockSender'; import { Element } from '../../models/element'; import ToolbarDropdown from './ToolbarDropdown'; interface Props { selectedIDs: string[]; } const MoreActions = ({ selectedIDs }: Props) => { const externalCloseRef = useRef<() => void>(noop); const { feature: blockSenderInToolbarFeature } = useFeature(FeatureCode.BlockSenderInToolbar); const closeDropdown = () => { externalCloseRef.current?.(); }; const getElementsFromIDs = useGetElementsFromIDs(); const { canShowBlockSender, handleClickBlockSender, blockSenderModal } = useBlockSender({ elements: [...(getElementsFromIDs(selectedIDs) || ({} as Element))], onCloseDropdown: closeDropdown, }); const blockSenderMenuButton = ( <DropdownMenuButton className="flex flex-align-items-center text-left" onClick={handleClickBlockSender} data-testid="toolbar:block-sender" disabled={!canShowBlockSender} > <Icon name="circle-slash" className="mr-2" /> {c('Action').t`Block senders`} </DropdownMenuButton> ); const dropdownMenuButtons = [blockSenderMenuButton]; // If there is no sender to block, disable the button // If we add more actions in this dropdown, need to update this condition const isToolbarButtonDisabled = !canShowBlockSender; if (!selectedIDs.length || !blockSenderInToolbarFeature?.Value) { return null; } return ( <> <ToolbarDropdown disabled={isToolbarButtonDisabled} content={<Icon className="toolbar-icon" name="three-dots-horizontal" />} dropDownClassName="move-dropdown" className="move-dropdown-button" title={c('Title').t`More actions`} data-testid="toolbar:more-actions" hasCaret={false} externalCloseRef={externalCloseRef} > {{ render: () => <DropdownMenu>{dropdownMenuButtons.map((button) => button)}</DropdownMenu> }} </ToolbarDropdown> {blockSenderModal} </> ); }; export default MoreActions;
3,728
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/toolbar/MoreDropdown.test.tsx
import { fireEvent, render } from '@testing-library/react'; import useSnooze from '../../hooks/actions/useSnooze'; import { useLabelActions } from '../../hooks/useLabelActions'; import MoreDropdown from './MoreDropdown'; jest.mock('../../hooks/useLabelActions'); jest.mock('../../hooks/actions/useSnooze'); jest.mock('../../hooks/actions/useEmptyLabel', () => ({ useEmptyLabel: () => ({ emptyLabel: '', modal: null }), })); jest.mock('../../hooks/actions/useMoveAll', () => ({ useMoveAll: () => ({ moveAll: '', modal: null }), })); const BREAKPOINTS = { breakpoint: '', isLargeDesktop: false, isMediumDesktop: false, isSmallDesktop: false, isDesktop: false, isTablet: false, isMobile: false, isTinyMobile: false, isNarrow: false, }; const props = { labelID: '1', elementIDs: [''], selectedIDs: ['a', 'b'], isSearch: false, isNarrow: false, isTiny: false, isExtraTiny: false, onMove: jest.fn(), onDelete: jest.fn(), breakpoints: BREAKPOINTS, }; const isTinyProps = { ...props, isTiny: true, }; const isExtraTinyProps = { ...props, isExtraTiny: true, }; const isNarrowProps = { ...props, isNarrow: true, }; describe('MoreDropdown', () => { const useSnoozeMock = useSnooze as jest.Mock; const useLabelActionMock = useLabelActions as jest.Mock; beforeAll(() => { useLabelActionMock.mockReturnValue([[''], ['']]); useSnoozeMock.mockReturnValue({ isSnoozeEnabled: true, canSnooze: jest.fn(), canUnsnooze: jest.fn(), }); }); afterAll(() => { useLabelActionMock.mockReset(); useSnoozeMock.mockReset(); }); it('should contain all option in more when screen is tiny', () => { const { getByTestId } = render(<MoreDropdown {...isTinyProps} />); const moreButton = getByTestId('toolbar:more-dropdown'); fireEvent.click(moreButton); expect(getByTestId('toolbar:more-dropdown--moveto')); expect(getByTestId('toolbar:more-dropdown--labelas')); expect(getByTestId('toolbar:more-dropdown--snooze')); }); it('should contain no option in more when all breakpoints are false', () => { const { getByTestId, queryByTestId } = render(<MoreDropdown {...props} />); const moreButton = getByTestId('toolbar:more-dropdown'); fireEvent.click(moreButton); expect(queryByTestId('toolbar:more-dropdown--moveto')).toBeNull(); expect(queryByTestId('toolbar:more-dropdown--labelas')).toBeNull(); expect(queryByTestId('toolbar:more-dropdown--snooze')).toBeNull(); }); it('should contain no option in more when screen narrow', () => { const { getByTestId, queryByTestId } = render(<MoreDropdown {...isNarrowProps} />); const moreButton = getByTestId('toolbar:more-dropdown'); fireEvent.click(moreButton); expect(queryByTestId('toolbar:more-dropdown--moveto')).toBeNull(); expect(queryByTestId('toolbar:more-dropdown--labelas')).toBeNull(); expect(queryByTestId('toolbar:more-dropdown--snooze')).toBeNull(); }); it('should contain no option in more when screen is extra tiny', () => { const { getByTestId, queryByTestId } = render(<MoreDropdown {...isExtraTinyProps} />); const moreButton = getByTestId('toolbar:more-dropdown'); fireEvent.click(moreButton); expect(queryByTestId('toolbar:more-dropdown--moveto')).toBeNull(); expect(queryByTestId('toolbar:more-dropdown--labelas')).toBeNull(); expect(queryByTestId('toolbar:more-dropdown--snooze')).toBeNull(); }); it('should have move and label action when snooze is disabled and screen tiny', () => { useSnoozeMock.mockReturnValue({ isSnoozeEnabled: false, canSnooze: jest.fn(), canUnsnooze: jest.fn(), }); const { getByTestId } = render(<MoreDropdown {...isTinyProps} />); const moreButton = getByTestId('toolbar:more-dropdown'); fireEvent.click(moreButton); expect(getByTestId('toolbar:more-dropdown--moveto')); expect(getByTestId('toolbar:more-dropdown--labelas')); }); it('should have all move actions returned by useLabelAction hook', () => { useLabelActionMock.mockReturnValue([['inbox', 'trash', 'archive', 'spam', 'nospam', 'delete'], ['']]); const { getByTestId } = render(<MoreDropdown {...isExtraTinyProps} />); const moreButton = getByTestId('toolbar:more-dropdown'); fireEvent.click(moreButton); expect(getByTestId('toolbar:more-dropdown--movetoinbox')); expect(getByTestId('toolbar:more-dropdown--movetonospam')); expect(getByTestId('toolbar:more-dropdown--movetonoarchive')); expect(getByTestId('toolbar:more-dropdown--movetotrash')); expect(getByTestId('toolbar:more-dropdown--movetospam')); expect(getByTestId('toolbar:more-dropdown--delete')); }); it('should have only move actions returned by useLabelAction hook', () => { useLabelActionMock.mockReturnValue([['inbox', 'trash', 'error'], ['not real']]); const { getByTestId } = render(<MoreDropdown {...isExtraTinyProps} />); const moreButton = getByTestId('toolbar:more-dropdown'); fireEvent.click(moreButton); expect(getByTestId('toolbar:more-dropdown--movetoinbox')); expect(getByTestId('toolbar:more-dropdown--movetotrash')); }); it('should have no move actions when screen is not extra tiny', () => { useLabelActionMock.mockReturnValue([['inbox', 'trash', 'archive', 'spam', 'nospam', 'delete'], ['']]); const { getByTestId, queryByTestId } = render(<MoreDropdown {...isTinyProps} />); const moreButton = getByTestId('toolbar:more-dropdown'); fireEvent.click(moreButton); expect(queryByTestId('toolbar:more-dropdown--movetoinbox')).toBeNull(); expect(queryByTestId('toolbar:more-dropdown--movetonospam')).toBeNull(); expect(queryByTestId('toolbar:more-dropdown--movetonoarchive')).toBeNull(); expect(queryByTestId('toolbar:more-dropdown--movetotrash')).toBeNull(); expect(queryByTestId('toolbar:more-dropdown--movetospam')).toBeNull(); expect(queryByTestId('toolbar:more-dropdown--delete')).toBeNull(); }); });
3,729
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/toolbar/MoreDropdown.tsx
import { c } from 'ttag'; import { DropdownMenu, DropdownMenuButton, Icon, useModalState } from '@proton/components'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import clsx from '@proton/utils/clsx'; import { canMoveAll, labelIncludes } from '../../helpers/labels'; import { useEmptyLabel } from '../../hooks/actions/useEmptyLabel'; import { useMoveAll } from '../../hooks/actions/useMoveAll'; import useSnooze from '../../hooks/actions/useSnooze'; import { useLabelActions } from '../../hooks/useLabelActions'; import { Breakpoints } from '../../models/utils'; import LabelDropdown, { labelDropdownContentProps } from '../dropdown/LabelDropdown'; import MoveDropdown, { moveDropdownContentProps } from '../dropdown/MoveDropdown'; import SnoozeUpsellModal from '../list/snooze/components/SnoozeUpsellModal'; import SnoozeToolbarDropdownStepWrapper, { SnoozeToolbarDropdownStepWrapperProps, } from '../list/snooze/containers/SnoozeToolbarDropdownStepWrapper'; import { DropdownRender } from '../message/header/HeaderDropdown'; import ToolbarDropdown from './ToolbarDropdown'; const { DRAFTS, ALL_DRAFTS, ALL_MAIL, ALMOST_ALL_MAIL, INBOX, SENT, ALL_SENT, ARCHIVE, STARRED, SCHEDULED, TRASH, SPAM, } = MAILBOX_LABEL_IDS; const canEmpty = (labelID: string, elementIDs: string[], selectedIDs: string[], isSearch: boolean) => { return ( !labelIncludes( labelID, INBOX, DRAFTS, ALL_DRAFTS, STARRED, SENT, ALL_SENT, ARCHIVE, ALL_MAIL, ALMOST_ALL_MAIL, SCHEDULED ) && elementIDs.length > 0 && selectedIDs.length === 0 && !isSearch ); }; interface Props { labelID: string; elementIDs: string[]; selectedIDs: string[]; isSearch: boolean; isNarrow: boolean; isTiny: boolean; isExtraTiny: boolean; onMove: (labelID: string) => void; onDelete: () => void; breakpoints: Breakpoints; } const MoreDropdown = ({ labelID, elementIDs, selectedIDs, isSearch, isTiny, isExtraTiny, onMove, onDelete, breakpoints, }: Props) => { let [firstActions, actions] = useLabelActions(labelID); if (isExtraTiny) { actions = [...firstActions, ...actions]; } const { isSnoozeEnabled, canSnooze, canUnsnooze } = useSnooze(); const { emptyLabel, modal: deleteAllModal } = useEmptyLabel(); const { moveAll, modal: moveAllModal } = useMoveAll(); const [upsellModalProps, handleUpsellModalDisplay, renderUpsellModal] = useModalState(); const inMore = { move: actions.length > 0 && selectedIDs.length > 0, additionalDropdowns: isTiny && selectedIDs.length > 0, moveAllToArchive: canMoveAll(labelID, ARCHIVE, elementIDs, selectedIDs, isSearch), moveAllToTrash: canMoveAll(labelID, TRASH, elementIDs, selectedIDs, isSearch), delete: canEmpty(labelID, elementIDs, selectedIDs, isSearch), }; const none = Object.values(inMore).every((visible) => !visible); if (none) { return null; } const handleEmptyLabel = () => emptyLabel(labelID); const handleMoveAllToArchive = () => moveAll(labelID, ARCHIVE); const handleMoveAllToTrash = () => moveAll(labelID, TRASH); const inbox = ( <DropdownMenuButton key="context-menu-inbox" className="text-left" onClick={() => onMove(INBOX)} data-testid="toolbar:more-dropdown--movetoinbox" > <Icon name="inbox" className="mr-2" /> {c('Action').t`Move to inbox`} </DropdownMenuButton> ); const nospam = ( <DropdownMenuButton key="context-menu-nospam" className="text-left" onClick={() => onMove(INBOX)} data-testid="toolbar:more-dropdown--movetonospam" > <Icon name="fire-slash" className="mr-2" /> {c('Action').t`Move to inbox (not spam)`} </DropdownMenuButton> ); const archive = ( <DropdownMenuButton key="context-menu-archive" className="text-left" onClick={() => onMove(ARCHIVE)} data-testid="toolbar:more-dropdown--movetonoarchive" > <Icon name="archive-box" className="mr-2" /> {c('Action').t`Move to archive`} </DropdownMenuButton> ); const trash = ( <DropdownMenuButton key="context-menu-trash" className="text-left" onClick={() => onMove(TRASH)} data-testid="toolbar:more-dropdown--movetotrash" > <Icon name="trash" className="mr-2" /> {c('Action').t`Move to trash`} </DropdownMenuButton> ); const spam = ( <DropdownMenuButton key="context-menu-spam" className="text-left" onClick={() => onMove(SPAM)} data-testid="toolbar:more-dropdown--movetospam" > <Icon name="fire" className="mr-2" /> {c('Action').t`Move to spam`} </DropdownMenuButton> ); const deleteButton = ( <DropdownMenuButton key="context-menu-delete" className="text-left" onClick={() => onDelete()} data-testid="toolbar:more-dropdown--delete" > <Icon name="cross-circle" className="mr-2" /> {c('Action').t`Delete`} </DropdownMenuButton> ); const allMoveButtons = { inbox, trash, archive, spam, nospam, delete: deleteButton }; const moveButtons = actions.map((action) => allMoveButtons[action]); const additionalDropdowns: DropdownRender[] | undefined = inMore.additionalDropdowns ? [ { contentProps: moveDropdownContentProps, render: ({ onClose, onLock }) => ( <MoveDropdown labelID={labelID} selectedIDs={selectedIDs} onClose={onClose} onLock={onLock} breakpoints={breakpoints} /> ), }, { contentProps: labelDropdownContentProps, render: ({ onClose, onLock }) => ( <LabelDropdown labelID={labelID} selectedIDs={selectedIDs} onClose={onClose} onLock={onLock} breakpoints={breakpoints} /> ), }, ] : undefined; if (isSnoozeEnabled && selectedIDs.length && (canSnooze || canUnsnooze)) { additionalDropdowns?.push({ contentProps: SnoozeToolbarDropdownStepWrapperProps, render: ({ onClose, onLock }) => ( <SnoozeToolbarDropdownStepWrapper onClose={onClose} onLock={onLock} selectedIDs={selectedIDs} displayUpsellModal={() => handleUpsellModalDisplay(true)} /> ), }); } return ( <> <ToolbarDropdown title={c('Action').t`More`} content={<Icon className="toolbar-icon" name="three-dots-horizontal" alt={c('Action').t`More`} />} data-testid="toolbar:more-dropdown" hasCaret={false} additionalDropdowns={additionalDropdowns} > {{ render: ({ onOpenAdditional }) => ( <DropdownMenu> {inMore.move ? moveButtons : null} {inMore.additionalDropdowns ? ( <> <DropdownMenuButton className={clsx('text-left', inMore.move && 'border-top')} onClick={() => onOpenAdditional(0)} data-testid="toolbar:more-dropdown--moveto" > <Icon name="folder-arrow-in" className="mr-2" /> {c('Title').t`Move to`} </DropdownMenuButton> <DropdownMenuButton className="text-left" onClick={() => onOpenAdditional(1)} data-testid="toolbar:more-dropdown--labelas" > <Icon name="tag" className="mr-2" /> {c('Title').t`Label as`} </DropdownMenuButton> {isSnoozeEnabled && (canSnooze || canUnsnooze) && ( <DropdownMenuButton className="text-left" onClick={() => onOpenAdditional(2)} data-testid="toolbar:more-dropdown--snooze" > <Icon name="bell" className="mr-2" /> {c('Title').t`Snooze message`} </DropdownMenuButton> )} </> ) : null} {inMore.moveAllToTrash ? ( <DropdownMenuButton className="text-left" onClick={handleMoveAllToTrash} data-testid="toolbar:moveAllToTrash" > <Icon name="trash" className="mr-2" /> { // translator: This action will move all messages from the location to trash // Beware when translating this one because we might also have a button below, // which is deleting all messages. This is different c('Action').t`Move all to trash` } </DropdownMenuButton> ) : null} {inMore.moveAllToArchive ? ( <DropdownMenuButton className="text-left" onClick={handleMoveAllToArchive} data-testid="toolbar:moveAllToArchive" > <Icon name="archive-box" className="mr-2" /> {c('Action').t`Move all to archive`} </DropdownMenuButton> ) : null} {inMore.delete ? ( <DropdownMenuButton className="text-left color-danger" onClick={handleEmptyLabel} data-testid="toolbar:more-empty" > <Icon name="cross-circle" className="mr-2" /> { // translator: This action will delete permanently all messages from the location // Beware when translating this one because we might also have a button on top, // which is moving messages to trash. This is different c('Action').t`Delete all` } </DropdownMenuButton> ) : null} </DropdownMenu> ), }} </ToolbarDropdown> {deleteAllModal} {moveAllModal} {renderUpsellModal && <SnoozeUpsellModal {...upsellModalProps} />} </> ); }; export default MoreDropdown;
3,730
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/toolbar/MoveButtons.test.tsx
import { screen } from '@testing-library/react'; import { LABEL_TYPE, MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { Label } from '@proton/shared/lib/interfaces'; import { addToCache, clearAll, minimalCache, render } from '../../helpers/test/helper'; import MoveButtons from './MoveButtons'; const labelID = 'labelID'; const folderID = 'folderID'; const labels: Label[] = [ { ID: labelID, Type: LABEL_TYPE.MESSAGE_LABEL } as Label, { ID: folderID, Type: LABEL_TYPE.MESSAGE_FOLDER } as Label, ]; const getProps = (labelID: string) => { return { labelID, isExtraTiny: false, isNarrow: false, isTiny: false, selectedIDs: ['randomID'], onMove: jest.fn(), onDelete: jest.fn(), }; }; describe('MoveButtons', () => { afterEach(clearAll); it.each` labelID | label ${MAILBOX_LABEL_IDS.INBOX} | ${'Inbox'} ${MAILBOX_LABEL_IDS.STARRED} | ${'Starred'} ${MAILBOX_LABEL_IDS.ALL_MAIL} | ${'All Mail'} ${folderID} | ${'Custom folders'} ${labelID} | ${'Custom labels'} `('should display trash, archive and spam actions in $label', async ({ labelID }) => { const props = getProps(labelID); minimalCache(); addToCache('Labels', labels); await render(<MoveButtons {...props} />, false); // Actions displayed screen.getByText('Move to trash'); screen.getByText('Move to archive'); screen.getByText('Move to spam'); // Actions not displayed expect(screen.queryByText('Move to inbox')).toBeNull(); expect(screen.queryByText('Move to inbox (not spam)')).toBeNull(); expect(screen.queryByText('Delete permanently')).toBeNull(); }); it.each` labelID | label ${MAILBOX_LABEL_IDS.DRAFTS} | ${'Drafts'} ${MAILBOX_LABEL_IDS.ALL_DRAFTS} | ${'All Drafts'} ${MAILBOX_LABEL_IDS.SENT} | ${'Sent'} ${MAILBOX_LABEL_IDS.ALL_SENT} | ${'All Sent'} `(`should display trash, archive and delete actions in $label`, async ({ labelID }) => { const props = getProps(labelID); await render(<MoveButtons {...props} />); // Actions displayed screen.getByText('Move to trash'); screen.getByText('Move to archive'); screen.getByText('Delete permanently'); // Actions not displayed expect(screen.queryByText('Move to inbox')).toBeNull(); expect(screen.queryByText('Move to inbox (not spam)')).toBeNull(); expect(screen.queryByText('Move to spam')).toBeNull(); }); it('should display trash and archive actions in Scheduled', async () => { const props = getProps(MAILBOX_LABEL_IDS.SCHEDULED); await render(<MoveButtons {...props} />); // Actions displayed screen.getByText('Move to trash'); screen.getByText('Move to archive'); // Actions not displayed expect(screen.queryByText('Move to inbox')).toBeNull(); expect(screen.queryByText('Move to inbox (not spam)')).toBeNull(); expect(screen.queryByText('Delete permanently')).toBeNull(); expect(screen.queryByText('Move to spam')).toBeNull(); }); it('should display trash, inbox and spam actions in Archive', async () => { const props = getProps(MAILBOX_LABEL_IDS.ARCHIVE); await render(<MoveButtons {...props} />); // Actions displayed screen.getByText('Move to trash'); screen.getByText('Move to inbox'); screen.getByText('Move to spam'); // Actions not displayed expect(screen.queryByText('Move to archive')).toBeNull(); expect(screen.queryByText('Move to inbox (not spam)')).toBeNull(); expect(screen.queryByText('Delete permanently')).toBeNull(); }); it('should display trash, nospam and delete actions in Spam', async () => { const props = getProps(MAILBOX_LABEL_IDS.SPAM); await render(<MoveButtons {...props} />); // Actions displayed screen.getByText('Move to trash'); screen.getByText('Move to inbox (not spam)'); screen.getByText('Delete permanently'); // Actions not displayed expect(screen.queryByText('Move to inbox')).toBeNull(); expect(screen.queryByText('Move to archive')).toBeNull(); expect(screen.queryByText('Move to spam')).toBeNull(); }); it('should display inbox, archive and delete actions in Trash', async () => { const props = getProps(MAILBOX_LABEL_IDS.TRASH); await render(<MoveButtons {...props} />); // Actions displayed screen.getByText('Move to inbox'); screen.getByText('Move to archive'); screen.getByText('Delete permanently'); // Actions not displayed expect(screen.queryByText('Move to trash')).toBeNull(); expect(screen.queryByText('Move to inbox (not spam)')).toBeNull(); expect(screen.queryByText('Move to spam')).toBeNull(); }); });
3,731
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/toolbar/MoveButtons.tsx
import { c } from 'ttag'; import { Kbd, Vr } from '@proton/atoms'; import { Icon, ToolbarButton } from '@proton/components'; import { useLoading } from '@proton/hooks'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import useMailModel from 'proton-mail/hooks/useMailModel'; import { useLabelActions } from '../../hooks/useLabelActions'; import DeleteButton from './DeleteButton'; const { TRASH, SPAM, ARCHIVE, INBOX } = MAILBOX_LABEL_IDS; interface Props { labelID: string; isExtraTiny: boolean; isNarrow: boolean; viewportIsNarrow?: boolean; selectedIDs: string[]; onMove: (labelID: string) => Promise<void>; onDelete: () => Promise<void>; } const MoveButtons = ({ labelID = '', isExtraTiny, viewportIsNarrow, selectedIDs = [], onMove, onDelete }: Props) => { const { Shortcuts } = useMailModel('MailSettings'); const [loading, withLoading] = useLoading(); let [actions] = useLabelActions(labelID); if (isExtraTiny) { actions = []; } if (!selectedIDs.length) { return null; } const titleInbox = Shortcuts ? ( <> {c('Action').t`Move to inbox`} <br /> <Kbd shortcut="I" /> </> ) : ( c('Action').t`Move to inbox` ); const inbox = ( <ToolbarButton key="inbox" title={titleInbox} onClick={() => withLoading(onMove(INBOX))} disabled={loading || !selectedIDs.length} data-testid="toolbar:movetoinbox" icon={<Icon name="inbox" alt={c('Action').t`Move to inbox`} />} /> ); const titleArchive = Shortcuts ? ( <> {c('Action').t`Move to archive`} <br /> <Kbd shortcut="A" /> </> ) : ( c('Action').t`Move to archive` ); const archive = ( <ToolbarButton key="archive" title={titleArchive} onClick={() => withLoading(onMove(ARCHIVE))} disabled={!selectedIDs.length} data-testid="toolbar:movetoarchive" icon={<Icon name="archive-box" alt={c('Action').t`Move to archive`} />} /> ); const titleSpam = Shortcuts ? ( <> {c('Action').t`Move to spam`} <br /> <Kbd shortcut="S" /> </> ) : ( c('Action').t`Move to spam` ); const spam = ( <ToolbarButton key="spam" title={titleSpam} onClick={() => withLoading(onMove(SPAM))} disabled={loading || !selectedIDs.length} data-testid="toolbar:movetospam" icon={<Icon name="fire" alt={c('Action').t`Move to spam`} />} /> ); const titleNoSpam = Shortcuts ? ( <> {c('Action').t`Move to inbox (not spam)`} <br /> <Kbd shortcut="I" /> </> ) : ( c('Action').t`Move to inbox (not spam)` ); const nospam = ( <ToolbarButton key="nospam" title={titleNoSpam} onClick={() => withLoading(onMove(INBOX))} disabled={loading || !selectedIDs.length} data-testid="toolbar:movetonospam" icon={<Icon name="fire-slash" alt={c('Action').t`Move to inbox (not spam)`} />} /> ); const titleTrash = Shortcuts ? ( <> {c('Action').t`Move to trash`} <br /> <Kbd shortcut="T" /> </> ) : ( c('Action').t`Move to trash` ); const trash = ( <ToolbarButton key="trash" title={titleTrash} onClick={() => withLoading(onMove(TRASH))} disabled={loading || !selectedIDs.length} data-testid="toolbar:movetotrash" icon={<Icon name="trash" alt={c('Action').t`Move to trash`} />} /> ); const deleteButton = <DeleteButton key="delete" selectedIDs={selectedIDs} onDelete={onDelete} />; const allButtons = { inbox, trash, archive, spam, nospam, delete: deleteButton }; const buttons = actions.map((action) => allButtons[action]); return ( <> {!viewportIsNarrow && <Vr />} {buttons} </> ); }; export default MoveButtons;
3,732
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/toolbar/NavigationControls.tsx
import { useLocation } from 'react-router'; import { c } from 'ttag'; import { Kbd } from '@proton/atoms'; import { Icon, ToolbarButton } from '@proton/components'; import useMailModel from 'proton-mail/hooks/useMailModel'; import { isConversationMode } from '../../helpers/mailSettings'; interface Props { loading: boolean; conversationMode: boolean; elementID?: string; messageID?: string; elementIDs: string[]; onElement: (elementID?: string, preventComposer?: boolean) => void; labelID: string; } const NavigationControls = ({ loading, conversationMode, elementID, messageID, elementIDs, onElement, labelID, }: Props) => { const location = useLocation(); const mailSettings = useMailModel('MailSettings'); const { Shortcuts } = mailSettings; const ID = !isConversationMode(labelID, mailSettings, location) && messageID ? messageID : elementID; const index = elementIDs.findIndex((id) => id === ID); const handleNext = () => onElement(elementIDs[index + 1], true); const handlePrevious = () => onElement(elementIDs[index - 1], true); const titlePreviousConversation = Shortcuts ? ( <> {c('Title').t`Previous conversation`} <br /> <Kbd shortcut="K" /> </> ) : ( c('Title').t`Previous conversation` ); const titlePreviousMessage = Shortcuts ? ( <> {c('Title').t`Previous message`} <br /> <Kbd shortcut="K" /> </> ) : ( c('Title').t`Previous message` ); const titleNextConversation = Shortcuts ? ( <> {c('Title').t`Next conversation`} <br /> <Kbd shortcut="J" /> </> ) : ( c('Title').t`Next conversation` ); const titleNextMessage = Shortcuts ? ( <> {c('Title').t`Next message`} <br /> <Kbd shortcut="J" /> </> ) : ( c('Title').t`Next message` ); return ( <> <ToolbarButton disabled={loading || index <= 0} title={conversationMode ? titlePreviousConversation : titlePreviousMessage} onClick={handlePrevious} className="hidden lg:flex" data-testid="toolbar:previous-element" icon={ <Icon name="arrow-up" alt={conversationMode ? c('Action').t`Previous conversation` : c('Action').t`Previous message`} /> } /> <ToolbarButton disabled={loading || index >= elementIDs.length - 1} title={conversationMode ? titleNextConversation : titleNextMessage} onClick={handleNext} className="hidden lg:flex" data-testid="toolbar:next-element" icon={ <Icon name="arrow-down" alt={conversationMode ? c('Action').t`Next conversation` : c('Action').t`Next message`} /> } /> </> ); }; export default NavigationControls;
3,733
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/toolbar/PagingControls.tsx
import { useLocation } from 'react-router'; import { c } from 'ttag'; import { Scroll } from '@proton/atoms'; import { DropdownMenu, DropdownMenuButton, EllipsisLoader, Icon, ToolbarButton } from '@proton/components'; import clsx from '@proton/utils/clsx'; import { useEncryptedSearchContext } from '../../containers/EncryptedSearchProvider'; import { isSearch as testIsSearch } from '../../helpers/elements'; import { extractSearchParameters } from '../../helpers/mailboxUrl'; import { usePaging } from '../../hooks/usePaging'; import ToolbarDropdown from './ToolbarDropdown'; interface Props { loading: boolean; page: number; total: number | undefined; onPage: (page: number) => void; } const PagingControls = ({ loading, page: inputPage, total: inputTotal, onPage: inputOnPage }: Props) => { const location = useLocation(); const { onPrevious, onNext, onPage, page, total } = usePaging(inputPage, inputTotal, inputOnPage); const { esStatus } = useEncryptedSearchContext(); const { dbExists, esEnabled, isSearchPartial, getCacheStatus, isSearching } = esStatus; const searchParameters = extractSearchParameters(location); const isSearch = testIsSearch(searchParameters); const { isCacheLimited } = getCacheStatus(); const useLoadMore = isSearch && !loading && dbExists && esEnabled && isCacheLimited && isSearchPartial; const loadMore = isSearching ? ( <div className="flex flex-justify-center"> <EllipsisLoader /> </div> ) : ( <DropdownMenuButton className="text-underline" onClick={() => onPage(total)} aria-label={c('Action').t`Load more`} data-testid="toolbar:load-more" > {c('Action').t`Load more`} </DropdownMenuButton> ); const totalText = total || 1; // total is 0 when no items const paginationLabel = ( <> {page} <span>/</span> {totalText} </> ); return ( <div className="flex flex-item-noshrink"> <ToolbarButton disabled={loading || page <= 1} title={c('Action').t`Previous page`} onClick={onPrevious} className="on-rtl-mirror toolbar-button--small toolbar-button--small-icon" icon={<Icon name="chevron-left" alt={c('Action').t`Previous page`} />} data-testid="toolbar:previous-page" /> <ToolbarDropdown title={c('Action').t`Change page`} content={paginationLabel} disabled={loading || total <= 1} data-testid="toolbar:page-number-dropdown" hasCaret={false} className="toolbar-button--small interactive--no-background toolbar-page-number-dropdown text-tabular-nums" > {{ render: () => ( <DropdownMenu> <Scroll> {[...Array(total)].map((_, i) => { const pageNumber = i + 1; // paging tooling is 0 based const active = page === pageNumber; return ( <DropdownMenuButton key={i} // eslint-disable-line react/no-array-index-key loading={loading} aria-selected={active} isSelected={active} onClick={() => onPage(i + 1)} aria-label={c('Action').t`Page ${pageNumber}`} data-testid={`toolbar:page-number-${pageNumber}`} className={clsx(['flex flex-row'])} > <span className="text-left flex-item-fluid">{pageNumber}</span> {active ? <Icon name="checkmark" className="mt-0.5" /> : null} </DropdownMenuButton> ); })} {useLoadMore && loadMore} </Scroll> </DropdownMenu> ), }} </ToolbarDropdown> <ToolbarButton disabled={loading || page >= total} title={c('Action').t`Next page`} onClick={onNext} className="on-rtl-mirror toolbar-button--small toolbar-button--small-icon" icon={<Icon name="chevron-right" alt={c('Action').t`Next page`} />} data-testid="toolbar:next-page" /> </div> ); }; export default PagingControls;
3,734
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/toolbar/ReadUnreadButtons.tsx
import { useMemo } from 'react'; import { useSelector } from 'react-redux'; import { c } from 'ttag'; import { Kbd } from '@proton/atoms'; import { Icon, ToolbarButton } from '@proton/components'; import useMailModel from 'proton-mail/hooks/useMailModel'; import { MARK_AS_STATUS } from '../../hooks/actions/useMarkAs'; import { elementsAreUnread as elementsAreUnreadSelector } from '../../logic/elements/elementsSelectors'; const { READ, UNREAD } = MARK_AS_STATUS; interface Props { selectedIDs: string[]; onMarkAs: (status: MARK_AS_STATUS) => Promise<void>; } const ReadUnreadButtons = ({ selectedIDs, onMarkAs }: Props) => { const { Shortcuts } = useMailModel('MailSettings'); const elementsAreUnread = useSelector(elementsAreUnreadSelector); const buttonMarkAsRead = useMemo(() => { const allRead = selectedIDs.every((elementID) => !elementsAreUnread[elementID]); return !allRead; }, [selectedIDs, elementsAreUnread]); if (!selectedIDs.length) { return null; } const titleRead = Shortcuts ? ( <> {c('Action').t`Mark as read`} <br /> <Kbd shortcut="R" /> </> ) : ( c('Action').t`Mark as read` ); const titleUnread = Shortcuts ? ( <> {c('Action').t`Mark as unread`} <br /> <Kbd shortcut="U" /> </> ) : ( c('Action').t`Mark as unread` ); return ( <> {buttonMarkAsRead ? ( <ToolbarButton key="read" title={titleRead} disabled={!selectedIDs.length} onClick={() => onMarkAs(READ)} data-testid="toolbar:read" icon={<Icon name="envelope-open" alt={c('Action').t`Mark as read`} />} /> ) : ( <ToolbarButton key="unread" title={titleUnread} disabled={!selectedIDs.length} onClick={() => onMarkAs(UNREAD)} data-testid="toolbar:unread" icon={<Icon name="envelope-dot" alt={c('Action').t`Mark as unread`} />} /> )} </> ); }; export default ReadUnreadButtons;
3,735
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/toolbar/SelectAll.tsx
import { c } from 'ttag'; import { Checkbox, DropdownMenu, DropdownMenuButton, Icon, Tooltip } from '@proton/components'; import { isStarred, isUnread } from '../../helpers/elements'; import { useGetElementsFromIDs } from '../../hooks/mailbox/useElements'; import ToolbarDropdown from './ToolbarDropdown'; interface Props { labelID: string; loading?: boolean; disabled?: boolean; elementIDs: string[]; checkedIDs: string[]; onCheck: (IDs: string[], checked: boolean, replace: boolean) => void; } const SelectAll = ({ labelID, loading, disabled, elementIDs, checkedIDs, onCheck }: Props) => { const getElementsFromIDs = useGetElementsFromIDs(); const checked = elementIDs.length ? elementIDs.length === checkedIDs.length : false; const indeterminate = elementIDs.length ? checkedIDs.length > 0 && elementIDs.length !== checkedIDs.length : false; const handleAll = (checked: boolean) => () => onCheck(elementIDs, checked, true); const handleRead = (read: boolean) => () => onCheck( getElementsFromIDs(elementIDs) .filter((element) => read === !isUnread(element, labelID)) .map(({ ID = '' }) => ID), true, true ); const handleStarred = (starred: boolean) => () => onCheck( getElementsFromIDs(elementIDs) .filter((element) => starred === isStarred(element)) .map(({ ID = '' }) => ID), true, true ); return ( <div className="flex flex-nowrap flex-item-noshrink select-all-wrapper rounded p-1 m-auto"> <Tooltip title={checked ? c('Action').t`Deselect all messages` : c('Action').t`Select all messages`}> <span className="select-all-container flex pl-1 md:pl-0"> <Checkbox className="select-all" checked={checked} indeterminate={indeterminate} id="idSelectAll" disabled={disabled} loading={loading} onChange={({ target }) => handleAll(target.checked)()} data-testid="toolbar:select-all-checkbox" > <span className="sr-only"> {checked ? c('Action').t`Deselect all messages` : c('Action').t`Select all messages`} </span> </Checkbox> </span> </Tooltip> <ToolbarDropdown disabled={disabled} loading={loading} title={c('Title').t`More selections`} data-testid="toolbar:select-all-dropdown" className="toolbar-button--dropdown-more-selections" > {{ render: () => ( <DropdownMenu> <DropdownMenuButton className="flex flex-align-items-center text-left" onClick={handleAll(true)} data-testid="toolbar:select-all" > <Icon name="checkmark-triple" className="mr-2" /> {c('Action').t`Select All`} </DropdownMenuButton> <DropdownMenuButton className="flex flex-align-items-center text-left" onClick={handleRead(true)} data-testid="toolbar:all-read" > <Icon name="envelope-open" className="mr-2" /> {c('Action').t`All Read`} </DropdownMenuButton> <DropdownMenuButton className="flex flex-align-items-center text-left" onClick={handleRead(false)} data-testid="toolbar:all-unread" > <Icon name="envelope-dot" className="mr-2" /> {c('Action').t`All Unread`} </DropdownMenuButton> <DropdownMenuButton className="flex flex-align-items-center text-left" onClick={handleStarred(true)} data-testid="toolbar:all-starred" > <Icon name="star-filled" className="mr-2" /> {c('Action').t`All Starred`} </DropdownMenuButton> <DropdownMenuButton className="flex flex-align-items-center text-left" onClick={handleStarred(false)} data-testid="toolbar:all-unstarred" > <Icon name="star" className="mr-2" /> {c('Action').t`All Unstarred`} </DropdownMenuButton> </DropdownMenu> ), }} </ToolbarDropdown> </div> ); }; export default SelectAll;
3,736
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/toolbar/SortDropdown.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { DropdownMenu, DropdownMenuButton, Icon, SimpleDropdown } from '@proton/components'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import clsx from '@proton/utils/clsx'; import { useEncryptedSearchContext } from '../../containers/EncryptedSearchProvider'; import { Sort } from '../../models/tools'; const TIME = 'Time'; const SIZE = 'Size'; interface Props { labelID?: string; conversationMode: boolean; sort: Sort; onSort: (sort: Sort) => void; className?: string; isSearch: boolean; hasCaret?: boolean; } const SortDropdown = ({ labelID, conversationMode, hasCaret, sort: { sort, desc }, onSort, className, isSearch, }: Props) => { const { esStatus } = useEncryptedSearchContext(); const { dbExists, esEnabled } = esStatus; const hideSizeSorting = isSearch && dbExists && esEnabled; const isScheduledLabel = labelID === MAILBOX_LABEL_IDS.SCHEDULED; const SORT_OPTIONS = { SMALL_TO_LARGE: c('Sort option').t`Smallest first`, LARGE_TO_SMALL: c('Sort option').t`Largest first`, NEW_TO_OLD: c('Sort option').t`Newest first`, OLD_TO_NEW: c('Sort option').t`Oldest first`, }; const getIcon = () => { if (sort === SIZE && !desc) { return <Icon className="toolbar-icon" name="size-arrow-up" title={SORT_OPTIONS.SMALL_TO_LARGE} />; } if (sort === SIZE && desc) { return <Icon className="toolbar-icon" name="size-arrow-down" title={SORT_OPTIONS.LARGE_TO_SMALL} />; } if (sort === TIME && !desc) { // If we are on the scheduled label, we reverse the default sort to have the next to be sent on top (but still displayed as newest) return !isScheduledLabel ? ( <Icon className="toolbar-icon" name="list-arrow-up" title={SORT_OPTIONS.OLD_TO_NEW} /> ) : ( <Icon className="toolbar-icon" name="list-arrow-down" title={SORT_OPTIONS.NEW_TO_OLD} /> ); } return !isScheduledLabel ? ( <Icon className="toolbar-icon" name="list-arrow-down" title={SORT_OPTIONS.NEW_TO_OLD} /> ) : ( <Icon className="toolbar-icon" name="list-arrow-up" title={SORT_OPTIONS.OLD_TO_NEW} /> ); }; return ( <SimpleDropdown as={Button} shape="ghost" size="small" hasCaret={hasCaret} originalPlacement="top-end" className={clsx(className, 'toolbar-button toolbar-button--small toolbar-button--small-icon')} content={ <span className="flex flex-align-items-center flex-nowrap" data-testid="toolbar:sort-dropdown"> {getIcon()} </span> } title={conversationMode ? c('Title').t`Sort conversations` : c('Title').t`Sort messages`} > <DropdownMenu> <DropdownMenuButton data-testid="toolbar:sort-new-to-old" isSelected={!isScheduledLabel ? sort === TIME && desc : sort === TIME && !desc} className="text-left flex gap-2" onClick={() => onSort({ sort: TIME, desc: true })} > <Icon className="toolbar-icon" name="list-arrow-down" /> <span>{SORT_OPTIONS.NEW_TO_OLD}</span> </DropdownMenuButton> <DropdownMenuButton data-testid="toolbar:sort-old-to-new" isSelected={!isScheduledLabel ? sort === TIME && !desc : sort === TIME && desc} className="text-left flex gap-2" onClick={() => onSort({ sort: TIME, desc: false })} > <Icon className="toolbar-icon" name="list-arrow-up" /> <span>{SORT_OPTIONS.OLD_TO_NEW}</span> </DropdownMenuButton> {!hideSizeSorting && ( <DropdownMenuButton data-testid="toolbar:sort-desc" isSelected={sort === SIZE && desc} className="text-left flex gap-2" onClick={() => onSort({ sort: SIZE, desc: true })} > <Icon className="toolbar-icon" name="size-arrow-down" /> <span>{SORT_OPTIONS.LARGE_TO_SMALL}</span> </DropdownMenuButton> )} {!hideSizeSorting && ( <DropdownMenuButton data-testid="toolbar:sort-asc" isSelected={sort === SIZE && !desc} className="text-left flex gap-2" onClick={() => onSort({ sort: SIZE, desc: false })} > <Icon className="toolbar-icon" name="size-arrow-up" /> <span>{SORT_OPTIONS.SMALL_TO_LARGE}</span> </DropdownMenuButton> )} </DropdownMenu> </SimpleDropdown> ); }; export default SortDropdown;
3,737
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/toolbar/SortDropdownMenu.tsx
import { c } from 'ttag'; import { DropdownMenu, DropdownMenuButton, Icon } from '@proton/components'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import clsx from '@proton/utils/clsx'; import { useEncryptedSearchContext } from '../../containers/EncryptedSearchProvider'; import { Sort } from '../../models/tools'; const TIME = 'Time'; const SIZE = 'Size'; interface Props { labelID: string; sort: Sort; onSort: (sort: Sort) => void; isSearch: boolean; borderBottom?: boolean; } const SortDropdownMenu = ({ labelID, sort: { sort, desc }, onSort, isSearch, borderBottom }: Props) => { const isScheduledLabel = labelID === MAILBOX_LABEL_IDS.SCHEDULED; const { esStatus } = useEncryptedSearchContext(); const { dbExists, esEnabled } = esStatus; const hideSizeSorting = isSearch && dbExists && esEnabled; const SORT_OPTIONS = { SMALL_TO_LARGE: c('Sort option').t`Smallest first`, LARGE_TO_SMALL: c('Sort option').t`Largest first`, NEW_TO_OLD: c('Sort option').t`Newest first`, OLD_TO_NEW: c('Sort option').t`Oldest first`, }; const isNewToOld = !isScheduledLabel ? sort === TIME && desc : sort === TIME && !desc; const isOldToNew = !isScheduledLabel ? sort === TIME && !desc : sort === TIME && desc; const isLargeToSmall = sort === SIZE && desc; const isSmallToLarge = sort === SIZE && !desc; return ( <DropdownMenu> <div className="text-bold w-full px-4 py-2">{c('Sort').t`Sort`}</div> <DropdownMenuButton data-testid="toolbar:sort-new-to-old" aria-current={isNewToOld} isSelected={isNewToOld} className="flex flex-row" onClick={() => onSort({ sort: TIME, desc: true })} > <span className="text-left flex-item-fluid">{SORT_OPTIONS.NEW_TO_OLD}</span> {isNewToOld ? <Icon name="checkmark" className="flex-item-noshrink mt-0.5" /> : null} </DropdownMenuButton> <DropdownMenuButton data-testid="toolbar:sort-old-to-new" aria-current={isOldToNew} isSelected={isOldToNew} className={clsx(['flex flex-row', borderBottom && hideSizeSorting && 'border-bottom'])} onClick={() => onSort({ sort: TIME, desc: false })} > <span className="text-left flex-item-fluid">{SORT_OPTIONS.OLD_TO_NEW}</span> {isOldToNew ? <Icon name="checkmark" className="flex-item-noshrink mt-0.5" /> : null} </DropdownMenuButton> {!hideSizeSorting && ( <DropdownMenuButton data-testid="toolbar:sort-desc" aria-current={isLargeToSmall} isSelected={isLargeToSmall} className="flex flex-row" onClick={() => onSort({ sort: SIZE, desc: true })} > <span className="text-left flex-item-fluid">{SORT_OPTIONS.LARGE_TO_SMALL}</span> {isLargeToSmall ? <Icon name="checkmark" className="flex-item-noshrink mt-0.5" /> : null} </DropdownMenuButton> )} {!hideSizeSorting && ( <DropdownMenuButton data-testid="toolbar:sort-asc" aria-current={isSmallToLarge} isSelected={isSmallToLarge} className={clsx(['flex flex-row', borderBottom && 'border-bottom'])} onClick={() => onSort({ sort: SIZE, desc: false })} > <span className="text-left flex-item-fluid">{SORT_OPTIONS.SMALL_TO_LARGE}</span> {isSmallToLarge ? <Icon name="checkmark" className="flex-item-noshrink mt-0.5" /> : null} </DropdownMenuButton> )} </DropdownMenu> ); }; export default SortDropdownMenu;
3,738
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/toolbar/Toolbar.tsx
import { Ref, memo } from 'react'; import { pick } from '@proton/shared/lib/helpers/object'; import { MARK_AS_STATUS } from '../../hooks/actions/useMarkAs'; import { Breakpoints } from '../../models/utils'; import { Props as ListSettingsProps } from '../list/ListSettings'; import SelectAll from './SelectAll'; import ToolbarColumnWide from './ToolbarColumnWide'; import ToolbarHeaderMessageNarrow from './ToolbarHeaderMessageNarrow'; import ToolbarHeaderMessageWide from './ToolbarHeaderMessageWide'; import ToolbarHeaderNarrow from './ToolbarHeaderNarrow'; import ToolbarNarrow from './ToolbarNarrow'; import ToolbarRowWide from './ToolbarRowWide'; const defaultSelectedIDs: string[] = []; const BASE_TOOLBAR_CLASSNAME = 'toolbar toolbar--heavy flex flex-nowrap flex-item-noshrink flex-align-items-center gap-2 no-print flex-item-fluid-auto'; export interface Props extends ListSettingsProps { loading?: boolean; onCheck: (IDs: string[], checked: boolean, replace: boolean) => void; labelID: string; elementID?: string; messageID?: string; selectedIDs: string[]; checkedIDs: string[]; elementIDs: string[]; columnMode: boolean; conversationMode: boolean; breakpoints: Breakpoints; page: number; total: number | undefined; isSearch: boolean; onPage: (page: number) => void; onBack: () => void; onElement: (elementID: string | undefined) => void; onMarkAs: (status: MARK_AS_STATUS) => Promise<void>; onMove: (labelID: string) => Promise<void>; onDelete: () => Promise<void>; labelDropdownToggleRef: Ref<() => void>; moveDropdownToggleRef: Ref<() => void>; bordered?: boolean; toolbarInHeader?: boolean; } type Variant = | 'columnWide' | 'rowWide' | 'headerMessageWide' | 'headerMessageNarrow' | 'headerNarrow' | 'narrow' | undefined; const Toolbar = (props: Props) => { const { elementID, columnMode, breakpoints, selectedIDs = defaultSelectedIDs, toolbarInHeader } = props; const viewPortIsNarrow = breakpoints.isNarrow || breakpoints.isTablet; const listInView = columnMode || !elementID; const variant = Object.entries({ headerNarrow: () => toolbarInHeader && viewPortIsNarrow && listInView, narrow: () => !toolbarInHeader && viewPortIsNarrow, headerMessageNarrow: () => !listInView && !columnMode && toolbarInHeader && viewPortIsNarrow && selectedIDs.length !== 0, headerMessageWide: () => !listInView && !columnMode && toolbarInHeader && !viewPortIsNarrow, rowWide: () => listInView && !columnMode && !viewPortIsNarrow, columnWide: () => listInView && columnMode && !viewPortIsNarrow, }).find(([, value]) => value() === true)?.[0] as Variant; const selectAllProps = pick(props, ['labelID', 'elementIDs', 'checkedIDs', 'onCheck', 'loading']); const commonProps = { ...props, // Base css class classname: BASE_TOOLBAR_CLASSNAME, selectAll: <SelectAll {...selectAllProps} />, }; return ( <> {'headerNarrow' === variant && <ToolbarHeaderNarrow {...commonProps} />} {'narrow' === variant && <ToolbarNarrow {...commonProps} />} {'headerMessageNarrow' === variant && <ToolbarHeaderMessageNarrow {...commonProps} />} {'headerMessageWide' === variant && <ToolbarHeaderMessageWide {...commonProps} />} {'rowWide' === variant && <ToolbarRowWide {...commonProps} />} {'columnWide' === variant && <ToolbarColumnWide {...commonProps} />} </> ); }; export default memo(Toolbar);
3,739
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/toolbar/ToolbarColumnWide.tsx
import { useMemo, useRef } from 'react'; import { c } from 'ttag'; import { useElementBreakpoints, useFolders, useLabels } from '@proton/components/hooks'; import clsx from '@proton/utils/clsx'; import { getLabelName } from '../../helpers/labels'; import { getToolbarResponsiveSizes } from '../../helpers/toolbar/getToolbarResponsiveSizes'; import ListSettings from '../list/ListSettings'; import SnoozeToolbarDropdown from '../list/snooze/containers/SnoozeToolbarDropdown'; import LabelName from './LabelName'; import LabelsAndFolders from './LabelsAndFolders'; import MoreActions from './MoreActions'; import MoreDropdown from './MoreDropdown'; import MoveButtons from './MoveButtons'; import PagingControls from './PagingControls'; import ReadUnreadButtons from './ReadUnreadButtons'; import { Props as ToolbarProps } from './Toolbar'; interface Props extends Omit<ToolbarProps, 'columnMode' | 'onBack' | 'onElement' | 'onCheck'> { classname: string; } const BREAKPOINTS = { extratiny: 0, tiny: 150, small: 440, medium: 700, large: 1100, }; const ToolbarColumnWide = ({ classname, selectAll, sort, onSort, filter, onFilter, conversationMode, mailSettings, isSearch, labelID, selectedIDs, onMarkAs, onMove, onDelete, breakpoints, labelDropdownToggleRef, moveDropdownToggleRef, elementIDs, loading = false, page, onPage, total, }: Props) => { const toolbarRef = useRef<HTMLDivElement>(null); const breakpoint = useElementBreakpoints(toolbarRef, BREAKPOINTS); const { localIsTiny, localIsExtraTiny, localIsNarrow } = getToolbarResponsiveSizes(breakpoint); const [labels] = useLabels(); const [folders] = useFolders(); const labelName = useMemo(() => getLabelName(labelID, labels, folders), [labelID, labels, folders]); return ( <div> <nav className={clsx( classname, 'flex-justify-space-between py-1 pr-2', selectedIDs.length === 0 ? 'pl-4' : 'pl-3' )} data-shortcut-target="mailbox-toolbar" aria-label={c('Label').t`Toolbar`} ref={toolbarRef} > <div className="flex flex-align-items-center flex-nowrap toolbar-inner gap-2"> <LabelName selectedIDs={selectedIDs} labelName={labelName} /> <ReadUnreadButtons selectedIDs={selectedIDs} onMarkAs={onMarkAs} /> <MoveButtons labelID={labelID} isExtraTiny={localIsExtraTiny} isNarrow={localIsNarrow} selectedIDs={selectedIDs} onMove={onMove} onDelete={onDelete} /> {!localIsExtraTiny ? ( <LabelsAndFolders labelID={labelID} selectedIDs={selectedIDs} breakpoints={breakpoints} labelDropdownToggleRef={labelDropdownToggleRef} moveDropdownToggleRef={moveDropdownToggleRef} /> ) : null} {!localIsExtraTiny ? <SnoozeToolbarDropdown labelID={labelID} selectedIDs={selectedIDs} /> : null} <MoreDropdown labelID={labelID} elementIDs={elementIDs} selectedIDs={selectedIDs} isSearch={isSearch} isNarrow={localIsNarrow} isTiny={localIsExtraTiny} isExtraTiny={localIsExtraTiny} onMove={onMove} onDelete={onDelete} breakpoints={breakpoints} /> <MoreActions selectedIDs={selectedIDs} /> </div> {(!localIsTiny && selectedIDs.length > 0) || selectedIDs.length === 0 ? ( <div className="flex flex-align-items-center flex-item-noshrink toolbar-inner gap-2"> <PagingControls loading={loading} page={page} total={total} onPage={onPage} /> </div> ) : undefined} </nav> <div className="toolbar flex gap-2 flex-nowrap flex-justify-space-between bg-norm border-bottom border-weak pl-4 pr-2 py-1"> <div className="mr-auto">{selectAll}</div> <div className="ml-auto"> <ListSettings sort={sort} onSort={onSort} onFilter={onFilter} filter={filter} conversationMode={conversationMode} mailSettings={mailSettings} isSearch={isSearch} labelID={labelID} filterAsDropdown={localIsTiny} /> </div> </div> </div> ); }; export default ToolbarColumnWide;
3,740
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/toolbar/ToolbarDropdown.tsx
import { ReactNode, Ref, useImperativeHandle, useState } from 'react'; import { Dropdown, DropdownButton, DropdownButtonProps, DropdownProps, DropdownSizeUnit, Tooltip, generateUID, usePopperAnchor, } from '@proton/components'; import clsx from '@proton/utils/clsx'; export interface DropdownRenderProps { onClose: () => void; onLock: (lock: boolean) => void; onOpenAdditional: (index: number) => void; } export interface DropdownRender { contentProps?: DropdownProps['contentProps']; render: (props: DropdownRenderProps) => ReactNode; } interface Props extends Omit<DropdownButtonProps<'button'>, 'title' | 'content'> { hasCaret?: boolean; autoClose?: boolean; title?: ReactNode; className?: string; dropDownClassName?: string; content?: ReactNode; children: DropdownRender; disabled?: boolean; dropdownSize?: DropdownProps['size']; /** * Used on mobile to open an additional dropdown from the dropdown * The handler onOpenAdditional is passed to use them */ additionalDropdowns?: DropdownRender[]; externalToggleRef?: Ref<() => void>; externalCloseRef?: Ref<() => void>; } const ToolbarDropdown = ({ title, content, className, dropDownClassName, children, hasCaret = true, autoClose = true, disabled = false, dropdownSize, additionalDropdowns, externalToggleRef, externalCloseRef, ...rest }: Props) => { const [uid] = useState(generateUID('dropdown')); const [lock, setLock] = useState(false); const [additionalOpen, setAdditionalOpen] = useState<number>(); const { anchorRef, isOpen, toggle, close } = usePopperAnchor<HTMLButtonElement>(); const handleAdditionalClose = () => { setAdditionalOpen(undefined); }; useImperativeHandle(externalToggleRef, () => toggle, []); useImperativeHandle(externalCloseRef, () => close, []); return ( <> <Tooltip title={title}> <DropdownButton as="button" type="button" ref={anchorRef} isOpen={isOpen} onClick={toggle} hasCaret={hasCaret} disabled={disabled} caretClassName="toolbar-icon" className={clsx([ 'toolbar-button flex flex-align-items-center', hasCaret && 'toolbar-button--dropdown', className, ])} {...rest} > {content} </DropdownButton> </Tooltip> <Dropdown id={uid} originalPlacement="bottom" autoClose={autoClose} autoCloseOutside={!lock} isOpen={isOpen} size={dropdownSize} anchorRef={anchorRef} onClose={close} className={clsx(['toolbar-dropdown', dropDownClassName])} contentProps={children.contentProps} > {children.render({ onClose: close, onLock: setLock, onOpenAdditional: setAdditionalOpen })} </Dropdown> {additionalDropdowns?.map((additionalDropdown, index) => { return ( <Dropdown key={index} // eslint-disable-line react/no-array-index-key id={`${uid}-${index}`} className={dropDownClassName} originalPlacement="bottom" autoClose={false} autoCloseOutside={!lock} isOpen={additionalOpen === index} size={{ maxWidth: DropdownSizeUnit.Viewport, maxHeight: DropdownSizeUnit.Viewport }} anchorRef={anchorRef} onClose={handleAdditionalClose} contentProps={additionalDropdown.contentProps} > {additionalDropdown.render({ onClose: handleAdditionalClose, onLock: setLock, onOpenAdditional: setAdditionalOpen, })} </Dropdown> ); })} </> ); }; export default ToolbarDropdown;
3,741
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/toolbar/ToolbarHeaderMessageNarrow.tsx
import { useRef } from 'react'; import { c } from 'ttag'; import { Icon, ToolbarButton } from '@proton/components/components'; import { useActiveBreakpoint, useElementBreakpoints } from '@proton/components/hooks'; import clsx from '@proton/utils/clsx'; import { getToolbarResponsiveSizes } from '../../helpers/toolbar/getToolbarResponsiveSizes'; import SnoozeToolbarDropdown from '../list/snooze/containers/SnoozeToolbarDropdown'; import LabelsAndFolders from './LabelsAndFolders'; import MoreActions from './MoreActions'; import MoreDropdown from './MoreDropdown'; import MoveButtons from './MoveButtons'; import NavigationControls from './NavigationControls'; import ReadUnreadButtons from './ReadUnreadButtons'; import { Props as ToolbarProps } from './Toolbar'; interface Props extends Omit<ToolbarProps, 'onCheck' | 'columnMode' | 'sort' | 'onSort' | 'filter' | 'onFilter' | 'mailSettings'> { classname: string; } const BREAKPOINTS = { extratiny: 0, tiny: 270, small: 320, medium: 700, large: 1100, }; const ToolbarHeaderMessageNarrow = ({ classname, onBack, conversationMode, elementIDs, elementID, messageID, onElement, selectedIDs, onMarkAs, labelID, onMove, onDelete, breakpoints, loading = false, labelDropdownToggleRef, moveDropdownToggleRef, isSearch, }: Props) => { const toolbarRef = useRef<HTMLDivElement>(null); const breakpoint = useElementBreakpoints(toolbarRef, BREAKPOINTS); const { localIsExtraTiny, localIsNarrow } = getToolbarResponsiveSizes(breakpoint); // We override this value because the "more" dropdown is not displayed in the toolbar otherwise const isTiny = localIsNarrow; const viewportBreakpoint = useActiveBreakpoint(); return ( <div className="flex w-full"> <nav className={clsx(classname, 'toolbar--in-container')} data-shortcut-target="mailbox-toolbar" aria-label={c('Label').t`Toolbar`} ref={toolbarRef} > <div className="flex flex-align-items-center toolbar-inner gap-2"> <ToolbarButton icon={<Icon name="arrow-left" alt={c('Action').t`Back`} />} onClick={onBack} data-testid="toolbar:back-button" /> <ReadUnreadButtons selectedIDs={selectedIDs} onMarkAs={onMarkAs} /> <MoveButtons labelID={labelID} isExtraTiny={localIsExtraTiny} isNarrow={localIsNarrow} viewportIsNarrow={viewportBreakpoint.isNarrow} selectedIDs={selectedIDs} onMove={onMove} onDelete={onDelete} /> {!isTiny ? ( <LabelsAndFolders labelID={labelID} selectedIDs={selectedIDs} breakpoints={breakpoints} labelDropdownToggleRef={labelDropdownToggleRef} moveDropdownToggleRef={moveDropdownToggleRef} /> ) : null} {!isTiny ? <SnoozeToolbarDropdown labelID={labelID} selectedIDs={selectedIDs} /> : null} <MoreDropdown labelID={labelID} elementIDs={elementIDs} selectedIDs={selectedIDs} isSearch={isSearch} isNarrow={localIsNarrow} isTiny={isTiny} isExtraTiny={localIsExtraTiny} onMove={onMove} onDelete={onDelete} breakpoints={breakpoints} /> <MoreActions selectedIDs={selectedIDs} /> <NavigationControls loading={loading} conversationMode={conversationMode} elementID={elementID} messageID={messageID} elementIDs={elementIDs} onElement={onElement} labelID={labelID} /> </div> </nav> </div> ); }; export default ToolbarHeaderMessageNarrow;
3,742
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/toolbar/ToolbarHeaderMessageWide.tsx
import { useRef } from 'react'; import { c } from 'ttag'; import { Vr } from '@proton/atoms/Vr'; import { Icon, ToolbarButton } from '@proton/components/components'; import { useElementBreakpoints } from '@proton/components/hooks'; import clsx from '@proton/utils/clsx'; import { getToolbarResponsiveSizes } from '../../helpers/toolbar/getToolbarResponsiveSizes'; import SnoozeToolbarDropdown from '../list/snooze/containers/SnoozeToolbarDropdown'; import LabelsAndFolders from './LabelsAndFolders'; import MoveButtons from './MoveButtons'; import NavigationControls from './NavigationControls'; import ReadUnreadButtons from './ReadUnreadButtons'; import { Props as ToolbarProps } from './Toolbar'; interface Props extends Omit< ToolbarProps, 'onCheck' | 'columnMode' | 'total' | 'isSearch' | 'sort' | 'onSort' | 'onFilter' | 'filter' | 'mailSettings' > { classname: string; } const BREAKPOINTS = { extratiny: 0, tiny: 100, small: 440, medium: 700, large: 1100, }; const ToolbarHeaderMessageWide = ({ classname, onBack, conversationMode, elementIDs, elementID, messageID, onElement, selectedIDs, onMarkAs, labelID, onMove, onDelete, breakpoints, loading = false, labelDropdownToggleRef, moveDropdownToggleRef, }: Props) => { const toolbarRef = useRef<HTMLDivElement>(null); const breakpoint = useElementBreakpoints(toolbarRef, BREAKPOINTS); const { localIsTiny, localIsNarrow } = getToolbarResponsiveSizes(breakpoint); return ( <div> <nav className={clsx(classname, 'toolbar--in-container')} data-shortcut-target="mailbox-toolbar" aria-label={c('Label').t`Toolbar`} ref={toolbarRef} > <div className="flex flex-align-items-center toolbar-inner flex-nowrap gap-2"> <ToolbarButton icon={<Icon name="arrow-left" alt={c('Action').t`Back`} />} onClick={onBack} data-testid="toolbar:back-button" /> <ReadUnreadButtons selectedIDs={selectedIDs} onMarkAs={onMarkAs} /> <MoveButtons labelID={labelID} isExtraTiny={breakpoint === 'extratiny'} isNarrow={localIsNarrow} selectedIDs={selectedIDs} onMove={onMove} onDelete={onDelete} /> <LabelsAndFolders labelID={labelID} selectedIDs={selectedIDs} breakpoints={breakpoints} labelDropdownToggleRef={labelDropdownToggleRef} moveDropdownToggleRef={moveDropdownToggleRef} /> <SnoozeToolbarDropdown labelID={labelID} selectedIDs={selectedIDs} /> {!localIsTiny ? ( <> <Vr /> <NavigationControls loading={loading} conversationMode={conversationMode} elementID={elementID} messageID={messageID} elementIDs={elementIDs} onElement={onElement} labelID={labelID} /> </> ) : null} </div> </nav> </div> ); }; export default ToolbarHeaderMessageWide;
3,743
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/toolbar/ToolbarHeaderNarrow.tsx
import { useMemo, useRef } from 'react'; import { c } from 'ttag'; import { useActiveBreakpoint, useElementBreakpoints, useFolders, useLabels } from '@proton/components/hooks'; import clsx from '@proton/utils/clsx'; import { getLabelName } from '../../helpers/labels'; import { getToolbarResponsiveSizes } from '../../helpers/toolbar/getToolbarResponsiveSizes'; import SnoozeToolbarDropdown from '../list/snooze/containers/SnoozeToolbarDropdown'; import LabelName from './LabelName'; import LabelsAndFolders from './LabelsAndFolders'; import MoreActions from './MoreActions'; import MoreDropdown from './MoreDropdown'; import MoveButtons from './MoveButtons'; import ReadUnreadButtons from './ReadUnreadButtons'; import { Props as ToolbarProps } from './Toolbar'; interface Props extends ToolbarProps { classname: string; } const BREAKPOINTS = { extratiny: 0, tiny: 220, small: 300, medium: 700, large: 1100, }; const ToolbarHeaderNarrow = ({ breakpoints, classname, elementIDs, labelDropdownToggleRef, labelID, moveDropdownToggleRef, onDelete, onMarkAs, onMove, selectedIDs, isSearch, }: Props) => { const toolbarRef = useRef<HTMLDivElement>(null); const breakpoint = useElementBreakpoints(toolbarRef, BREAKPOINTS); const { localIsTiny, localIsExtraTiny, localIsNarrow } = getToolbarResponsiveSizes(breakpoint); const [labels] = useLabels(); const [folders] = useFolders(); const labelName = useMemo(() => getLabelName(labelID, labels, folders), [labelID, labels, folders]); const viewportBreakpoint = useActiveBreakpoint(); return ( <div className="flex w-full"> <nav className={clsx(classname, 'toolbar--in-container')} data-shortcut-target="mailbox-toolbar" aria-label={c('Label').t`Toolbar`} ref={toolbarRef} > <div className={clsx('flex flex-align-items-center toolbar-inner gap-2', !selectedIDs.length && 'pl-2')} > <LabelName selectedIDs={selectedIDs} labelName={labelName} /> <ReadUnreadButtons selectedIDs={selectedIDs} onMarkAs={onMarkAs} /> <MoveButtons labelID={labelID} isExtraTiny={localIsExtraTiny} isNarrow={localIsNarrow} viewportIsNarrow={viewportBreakpoint.isNarrow} selectedIDs={selectedIDs} onMove={onMove} onDelete={onDelete} /> {!localIsTiny ? ( <LabelsAndFolders labelID={labelID} selectedIDs={selectedIDs} breakpoints={breakpoints} labelDropdownToggleRef={labelDropdownToggleRef} moveDropdownToggleRef={moveDropdownToggleRef} /> ) : null} {!localIsTiny ? <SnoozeToolbarDropdown labelID={labelID} selectedIDs={selectedIDs} /> : null} <MoreDropdown labelID={labelID} elementIDs={elementIDs} selectedIDs={selectedIDs} isSearch={isSearch} isNarrow={localIsNarrow} isTiny={localIsTiny} isExtraTiny={localIsExtraTiny} onMove={onMove} onDelete={onDelete} breakpoints={breakpoints} /> <MoreActions selectedIDs={selectedIDs} /> </div> </nav> </div> ); }; export default ToolbarHeaderNarrow;
3,744
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/toolbar/ToolbarNarrow.tsx
import React, { useRef } from 'react'; import { c } from 'ttag'; import { useElementBreakpoints } from '@proton/components/hooks'; import clsx from '@proton/utils/clsx'; import ListSettings, { Props as ListSettingsProps } from '../list/ListSettings'; interface Props extends ListSettingsProps { classname: string; labelID: string; isSearch: boolean; } const BREAKPOINTS = { extratiny: 0, tiny: 100, small: 400, medium: 700, large: 1100, }; const ToolbarNarrow = ({ classname, selectAll, sort, onSort, filter, onFilter, conversationMode, mailSettings, isSearch, labelID, }: Props) => { const toolbarRef = useRef<HTMLDivElement>(null); const breakpoint = useElementBreakpoints(toolbarRef, BREAKPOINTS); return ( <div> <nav className={clsx(classname, 'flex-justify-space-between py-1 pl-3 pr-2')} data-shortcut-target="mailbox-toolbar" aria-label={c('Label').t`Toolbar`} ref={toolbarRef} > <div className="flex flex-align-items-center toolbar-inner gap-2">{selectAll}</div> <div className="flex flex-align-items-center toolbar-inner gap-2"> <ListSettings sort={sort} onSort={onSort} onFilter={onFilter} filter={filter} conversationMode={conversationMode} mailSettings={mailSettings} isSearch={isSearch} labelID={labelID} filterAsDropdown={breakpoint === 'tiny'} /> </div> </nav> </div> ); }; export default ToolbarNarrow;
3,745
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/toolbar/ToolbarRowWide.tsx
import { useMemo, useRef } from 'react'; import { c } from 'ttag'; import { useElementBreakpoints, useFolders, useLabels } from '@proton/components/hooks'; import clsx from '@proton/utils/clsx'; import { getLabelName } from '../../helpers/labels'; import { getToolbarResponsiveSizes } from '../../helpers/toolbar/getToolbarResponsiveSizes'; import ListSettings from '../list/ListSettings'; import SnoozeToolbarDropdown from '../list/snooze/containers/SnoozeToolbarDropdown'; import LabelName from './LabelName'; import LabelsAndFolders from './LabelsAndFolders'; import MoreActions from './MoreActions'; import MoreDropdown from './MoreDropdown'; import MoveButtons from './MoveButtons'; import PagingControls from './PagingControls'; import ReadUnreadButtons from './ReadUnreadButtons'; import { Props as ToolbarProps } from './Toolbar'; interface Props extends Omit<ToolbarProps, 'onCheck' | 'checkedIDs' | 'columnMode' | 'onBack' | 'onElement'> { classname: string; } const BREAKPOINTS = { extratiny: 0, tiny: 100, small: 400, medium: 800, large: 1100, }; const ToolbarRowWide = ({ classname, selectAll, sort, onSort, filter, onFilter, conversationMode, mailSettings, isSearch, labelID, selectedIDs, onMarkAs, onMove, onDelete, breakpoints, labelDropdownToggleRef, moveDropdownToggleRef, elementIDs, loading = false, page, onPage, total, }: Props) => { const toolbarRef = useRef<HTMLDivElement>(null); const breakpoint = useElementBreakpoints(toolbarRef, BREAKPOINTS); const { localIsTiny, localIsExtraTiny, localIsNarrow } = getToolbarResponsiveSizes(breakpoint); const localIsNarrowAndMedium = localIsNarrow || breakpoint === 'medium'; const [labels] = useLabels(); const [folders] = useFolders(); const labelName = useMemo(() => getLabelName(labelID, labels, folders), [labelID, labels, folders]); return ( <div> <nav className={clsx(classname, 'flex-justify-space-between py-1 pl-4 pr-2')} data-shortcut-target="mailbox-toolbar" aria-label={c('Label').t`Toolbar`} ref={toolbarRef} > <div className="flex flex-align-items-center flex-nowrap toolbar-inner gap-2"> {selectAll} <LabelName selectedIDs={selectedIDs} labelName={labelName} /> <ReadUnreadButtons selectedIDs={selectedIDs} onMarkAs={onMarkAs} /> <MoveButtons labelID={labelID} isExtraTiny={localIsExtraTiny} isNarrow={localIsNarrow} selectedIDs={selectedIDs} onMove={onMove} onDelete={onDelete} /> {!localIsTiny ? ( <LabelsAndFolders labelID={labelID} selectedIDs={selectedIDs} breakpoints={breakpoints} labelDropdownToggleRef={labelDropdownToggleRef} moveDropdownToggleRef={moveDropdownToggleRef} /> ) : null} {!localIsTiny ? <SnoozeToolbarDropdown selectedIDs={selectedIDs} labelID={labelID} /> : null} <MoreDropdown labelID={labelID} elementIDs={elementIDs} selectedIDs={selectedIDs} isSearch={isSearch} isNarrow={localIsNarrow} isTiny={localIsTiny} isExtraTiny={localIsExtraTiny} onMove={onMove} onDelete={onDelete} breakpoints={breakpoints} /> <MoreActions selectedIDs={selectedIDs} /> </div> <div className="flex flex-align-items-center flex-item-noshrink flex-nowrap toolbar-inner gap-2"> <ListSettings sort={sort} onSort={onSort} onFilter={onFilter} filter={filter} conversationMode={conversationMode} mailSettings={mailSettings} isSearch={isSearch} labelID={labelID} filterAsDropdown={localIsNarrowAndMedium} /> <PagingControls loading={loading} page={page} total={total} onPage={onPage} /> </div> </nav> </div> ); }; export default ToolbarRowWide;
3,746
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/toolbar
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/toolbar/__mocks__/Toolbar.tsx
export const props: any = {}; const Toolbar = (newProps: any) => { Object.assign(props, newProps); return 'Toolbar'; }; export default Toolbar;
3,747
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/view/EmptyListPlaceholder.test.tsx
import { screen } from '@testing-library/react'; import { CHECKLIST_DISPLAY_TYPE } from '@proton/shared/lib/interfaces'; import { ContextState, useGetStartedChecklist, } from '../../containers/onboardingChecklist/provider/GetStartedChecklistProvider'; import { render } from '../../helpers/test/helper'; import EmptyListPlaceholder from './EmptyListPlaceholder'; jest.mock('../../containers/onboardingChecklist/provider/GetStartedChecklistProvider', () => ({ __esModule: true, useGetStartedChecklist: jest.fn(), default: ({ children }: { children: any }) => <>{children}</>, })); jest.mock('../../containers/onboardingChecklist/provider/GetStartedChecklistProvider'); const mockedReturn = useGetStartedChecklist as jest.MockedFunction<typeof useGetStartedChecklist>; describe('EmptyListPlaceholder', () => { it('Should display checklist when no mails are present', async () => { mockedReturn.mockReturnValue({ displayState: CHECKLIST_DISPLAY_TYPE.FULL, items: new Set() } as ContextState); await render(<EmptyListPlaceholder labelID="labelID" isSearch={false} isUnread={false} />); screen.getByTestId('onboarding-checklist'); }); it('Should display placeholder when checklist is not reduced', async () => { mockedReturn.mockReturnValue({ displayState: CHECKLIST_DISPLAY_TYPE.REDUCED, items: new Set(), } as ContextState); await render(<EmptyListPlaceholder labelID="labelID" isSearch={false} isUnread={false} />); screen.getByTestId('empty-view-placeholder--empty-title'); }); it('Should display placeholder when checklist is not hidden', async () => { mockedReturn.mockReturnValue({ displayState: CHECKLIST_DISPLAY_TYPE.HIDDEN, items: new Set(), } as ContextState); await render(<EmptyListPlaceholder labelID="labelID" isSearch={false} isUnread={false} />); screen.getByTestId('empty-view-placeholder--empty-title'); }); });
3,748
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/view/EmptyListPlaceholder.tsx
import { CHECKLIST_DISPLAY_TYPE } from '@proton/shared/lib/interfaces'; import { useGetStartedChecklist } from '../../containers/onboardingChecklist/provider/GetStartedChecklistProvider'; import UsersOnboardingChecklist from '../checklist/UsersOnboardingChecklist'; import EmptyView from './EmptyView'; interface Props { labelID: string; isSearch: boolean; isUnread: boolean; } const EmptyListPlaceholder = ({ labelID, isSearch, isUnread }: Props) => { const { displayState } = useGetStartedChecklist(); if (displayState === CHECKLIST_DISPLAY_TYPE.FULL) { return <UsersOnboardingChecklist />; } return <EmptyView labelID={labelID} isSearch={isSearch} isUnread={isUnread} />; }; export default EmptyListPlaceholder;
3,749
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/view/EmptyView.tsx
import { c } from 'ttag'; import { Button, Href } from '@proton/atoms'; import { EmptyViewContainer, FeatureCode, Loader, useFeature, useModalState } from '@proton/components'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import noResultInboxSvg from '@proton/styles/assets/img/illustrations/empty-mailbox.svg'; import noResultSearchSvg from '@proton/styles/assets/img/illustrations/empty-search.svg'; import noSpamSvg from '@proton/styles/assets/img/illustrations/no-messages-in-spam.svg'; import noUnreadSvg from '@proton/styles/assets/img/illustrations/no-unread-messages.svg'; import { MESSAGE_ACTIONS } from '../../constants'; import { useOnCompose } from '../../containers/ComposeProvider'; import { useEncryptedSearchContext } from '../../containers/EncryptedSearchProvider'; import { ComposeTypes } from '../../hooks/composer/useCompose'; import { useSimpleLoginExtension } from '../../hooks/simpleLogin/useSimpleLoginExtension'; import EnableEncryptedSearchModal from '../header/search/AdvancedSearchFields/EnableEncryptedSearchModal'; import SimpleLoginPlaceholder from './SimpleLoginPlaceholder'; interface Props { labelID: string; isSearch: boolean; isUnread: boolean; } const EmptyView = ({ labelID, isSearch, isUnread }: Props) => { const { feature: simpleLoginIntegrationFeature, loading: loadingSimpleLoadingFeature } = useFeature( FeatureCode.SLIntegration ); const { hasSimpleLogin, isFetchingAccountLinked } = useSimpleLoginExtension(); const { esStatus } = useEncryptedSearchContext(); const { isEnablingContentSearch, isContentIndexingPaused, contentIndexingDone, isEnablingEncryptedSearch } = esStatus; const [enableESModalProps, setEnableESModalOpen, renderEnableESModal] = useModalState(); const isInbox = labelID === MAILBOX_LABEL_IDS.INBOX && !isSearch; const isScheduled = labelID === MAILBOX_LABEL_IDS.SCHEDULED && !isSearch; const isSnoozed = labelID === MAILBOX_LABEL_IDS.SNOOZED && !isSearch; const isSpam = labelID === MAILBOX_LABEL_IDS.SPAM && !isSearch; const isFolder = !isInbox && !isScheduled && !isSnoozed && !isSearch && !isSpam; // We want to hide the "enable ES" part from the point when the user enables it. We do not want to see the downloading part from here const encryptedSearchEnabled = isEnablingContentSearch || isContentIndexingPaused || contentIndexingDone || isEnablingEncryptedSearch; const onCompose = useOnCompose(); const scheduleCTAButton = ( <Button title={c('Action').t`Create new message`} onClick={() => onCompose({ type: ComposeTypes.newMessage, action: MESSAGE_ACTIONS.NEW })} > {c('Action').t`Create new message`} </Button> ); const imageProps = (() => { if (isSpam) { return { src: noSpamSvg, alt: c('Search - no results').t`No messages found` }; } if (isUnread) { return { src: noUnreadSvg, alt: c('Search - no results').t`No unread messages found` }; } if (isSearch) { return { src: noResultSearchSvg, alt: c('Search - no results').t`No results found` }; } if (isFolder) { return { src: noResultSearchSvg, alt: c('Search - no results').t`No messages found` }; } if (isInbox) { return { src: noResultInboxSvg, alt: c('Search - no results').t`No messages found` }; } if (isScheduled) { return { src: noResultSearchSvg, alt: c('Search - no results').t`No messages scheduled` }; } if (isSnoozed) { return { src: noResultSearchSvg, alt: c('Search - no results').t`No snoozed messages` }; } })(); const showSimpleLoginPlaceholder = simpleLoginIntegrationFeature?.Value && isSpam && !hasSimpleLogin; if (loadingSimpleLoadingFeature || isFetchingAccountLinked) { return ( <div className="m-auto text-center p-7 max-w-full"> <Loader /> </div> ); } return showSimpleLoginPlaceholder ? ( <div className="m-auto text-center p-7 max-w-full"> <SimpleLoginPlaceholder /> </div> ) : ( <EmptyViewContainer imageProps={imageProps}> <h3 className="text-bold" data-testid="empty-view-placeholder--empty-title"> {isSearch ? c('Search - no results').t`No results found` : isFolder ? c('Search - no results').t`No messages found` : isScheduled ? c('Search - no results').t`No messages scheduled` : c('Search - no results').t`No messages found`} </h3> <p> {isSearch ? ( // TODO: Add a link on clear it when search will work <> {encryptedSearchEnabled ? ( <>{c('Info').t`You can either update your search query or clear it`}</> ) : ( <> {c('Info') .t`For more search results, try searching for this keyword in the content of your email messages.`} <br /> <Href href={getKnowledgeBaseUrl('/search-message-content')}> {c('Info').t`Learn more`} </Href> </> )} </> ) : isFolder ? ( c('Info').t`You do not have any messages here` ) : isScheduled ? ( scheduleCTAButton ) : ( c('Info').t`Seems like you are all caught up for now` )} </p> {isSearch && !encryptedSearchEnabled && ( <Button onClick={() => setEnableESModalOpen(true)} data-testid="encrypted-search:activate"> {c('Action').t`Enable`} </Button> )} {renderEnableESModal && <EnableEncryptedSearchModal openSearchAfterEnabling {...enableESModalProps} />} </EmptyViewContainer> ); }; export default EmptyView;
3,750
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/view/PlaceholderView.tsx
import { useMemo } from 'react'; import { useLocation } from 'react-router'; import { useConversationCounts, useMessageCounts } from '@proton/components'; import { LabelCount } from '@proton/shared/lib/interfaces/Label'; import useMailModel from 'proton-mail/hooks/useMailModel'; import { ELEMENT_TYPES } from '../../constants'; import { getCurrentType } from '../../helpers/elements'; import SelectionPane from './SelectionPane'; import WelcomePane from './WelcomePane'; interface Props { welcomeFlag: boolean; labelID: string; checkedIDs?: string[]; onCheckAll: (checked: boolean) => void; } const PlaceholderView = ({ welcomeFlag, labelID = '', checkedIDs = [], onCheckAll }: Props) => { const location = useLocation(); const mailSettings = useMailModel('MailSettings'); const [conversationCounts = []] = useConversationCounts() as [LabelCount[] | undefined, boolean, Error]; const [messageCounts = []] = useMessageCounts() as [LabelCount[] | undefined, boolean, Error]; const type = getCurrentType({ mailSettings, labelID, location }); const labelCount = useMemo(() => { const counters = type === ELEMENT_TYPES.CONVERSATION ? conversationCounts : messageCounts; return counters.find((counter) => counter.LabelID === labelID); }, [labelID, conversationCounts, messageCounts]); return welcomeFlag ? ( <WelcomePane mailSettings={mailSettings} location={location} labelCount={labelCount} /> ) : ( <SelectionPane labelID={labelID} mailSettings={mailSettings} location={location} labelCount={labelCount} checkedIDs={checkedIDs} onCheckAll={onCheckAll} /> ); }; export default PlaceholderView;
3,751
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/view/SelectionPane.tsx
import { useEffect, useMemo, useState } from 'react'; import { useLocation } from 'react-router-dom'; import { Location } from 'history'; import { c, msgid } from 'ttag'; import { Button, Href } from '@proton/atoms'; import { FeatureCode, Loader, useFeature, useFolders, useLabels, useModalState } from '@proton/components'; import getBoldFormattedText from '@proton/components/helpers/getBoldFormattedText'; import { TelemetrySimpleLoginEvents } from '@proton/shared/lib/api/telemetry'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { MailSettings } from '@proton/shared/lib/interfaces'; import { LabelCount } from '@proton/shared/lib/interfaces/Label'; import conversationSvg from '@proton/styles/assets/img/illustrations/selected-emails.svg'; import { useEncryptedSearchContext } from '../../containers/EncryptedSearchProvider'; import { isSearch as testIsSearch } from '../../helpers/elements'; import { getLabelName, isCustomLabel as testIsCustomLabel } from '../../helpers/labels'; import { isConversationMode } from '../../helpers/mailSettings'; import { extractSearchParameters } from '../../helpers/mailboxUrl'; import { useSimpleLoginExtension } from '../../hooks/simpleLogin/useSimpleLoginExtension'; import { useSimpleLoginTelemetry } from '../../hooks/simpleLogin/useSimpleLoginTelemetry'; import { useDeepMemo } from '../../hooks/useDeepMemo'; import { total as totalSelector } from '../../logic/elements/elementsSelectors'; import { useAppSelector } from '../../logic/store'; import { SearchParameters } from '../../models/tools'; import EnableEncryptedSearchModal from '../header/search/AdvancedSearchFields/EnableEncryptedSearchModal'; import SimpleLoginPlaceholder from './SimpleLoginPlaceholder'; interface Props { labelID: string; mailSettings: MailSettings; location: Location; labelCount: LabelCount | undefined; checkedIDs?: string[]; onCheckAll: (checked: boolean) => void; } const { SPAM } = MAILBOX_LABEL_IDS; const SelectionPane = ({ labelID, mailSettings, location, labelCount, checkedIDs = [], onCheckAll }: Props) => { const appLocation = useLocation(); const { feature: simpleLoginIntegrationFeature, loading: loadingSimpleLoadingFeature } = useFeature( FeatureCode.SLIntegration ); const { hasSimpleLogin, isFetchingAccountLinked } = useSimpleLoginExtension(); const { handleSendTelemetryData } = useSimpleLoginTelemetry(); const [placeholderSLSeenSent, setPlaceholderSLSeenSent] = useState(false); const conversationMode = isConversationMode(labelID, mailSettings, location); // We display 50 elements maximum in the list. To know how much results are matching a search, we store it in Redux, in elements.total const elementsFoundCount = useAppSelector(totalSelector) || 0; const [labels] = useLabels(); const [folders] = useFolders(); const { esStatus } = useEncryptedSearchContext(); const { isEnablingContentSearch, isContentIndexingPaused, contentIndexingDone, isEnablingEncryptedSearch } = esStatus; const [enableESModalProps, setEnableESModalOpen, renderEnableESModal] = useModalState(); const isCustomLabel = testIsCustomLabel(labelID, labels); const total = labelCount?.Total || 0; const checkeds = checkedIDs.length; const labelName = useMemo(() => getLabelName(labelID, labels, folders), [labelID, labels, folders]); const count = checkeds || total; const searchParameters = useDeepMemo<SearchParameters>(() => extractSearchParameters(appLocation), [appLocation]); const isSearch = testIsSearch(searchParameters); // We want to hide the "enable ES" part from the point when the user enables it. We do not want to see the downloading part from here const encryptedSearchEnabled = isEnablingContentSearch || isContentIndexingPaused || contentIndexingDone || isEnablingEncryptedSearch; /* * With ttag we cannot have JSX in plural forms * We need a workaround to have the number of messages/conversations in a strong tag * So we are surrounding the bold part with ** to replace it later by a strong tag */ const getFolderText = () => { if (checkeds) { // translator: To have plural forms AND a part in bold, we need to surround the bold part with "**" so that we can replace it by a <strong> tag in the code. Here, "{count} conversation/s" will be bold. You need to put them in your translation too. return conversationMode ? c('Info').ngettext( msgid`You selected **${count} conversation** from this folder`, `You selected **${count} conversations** from this folder`, count ) : // translator: To have plural forms AND a part in bold, we need to surround the bold part with "**" so that we can replace it by a <strong> tag in the code. Here, "{count} message/s" will be bold. You need to put them in your translation too. c('Info').ngettext( msgid`You selected **${count} message** from this folder`, `You selected **${count} messages** from this folder`, count ); } // translator: To have plural forms AND a part in bold, we need to surround the bold part with "**" so that we can replace it by a <strong> tag in the code. Here, "{count} conversation/s" will be bold. You need to put them in your translation too. return conversationMode ? c('Info').ngettext( msgid`You have **${count} conversation** stored in this folder`, `You have **${count} conversations** stored in this folder`, count ) : // translator: To have plural forms AND a part in bold, we need to surround the bold part with "**" so that we can replace it by a <strong> tag in the code. Here, "{count} message/s" will be bold. You need to put them in your translation too. c('Info').ngettext( msgid`You have **${count} message** stored in this folder`, `You have **${count} messages** stored in this folder`, count ); }; /* * With ttag we cannot have JSX in plural forms * We need a workaround to have the number of messages/conversations in a strong tag * So we are surrounding the bold part with ** to replace it later by a strong tag */ const getLabelText = () => { if (checkeds) { // translator: To have plural forms AND a part in bold, we need to surround the bold part with "**" so that we can replace it by a <strong> tag in the code. Here, "{count} conversation/s" will be bold. You need to put them in your translation too. return conversationMode ? c('Info').ngettext( msgid`You selected **${count} conversation** with this label`, `You selected **${count} conversations** with this label`, count ) : // translator: To have plural forms AND a part in bold, we need to surround the bold part with "**" so that we can replace it by a <strong> tag in the code. Here, "{count} message/s" will be bold. You need to put them in your translation too. c('Info').ngettext( msgid`You selected **${count} message** with this label`, `You selected **${count} messages** with this label`, count ); } // translator: To have plural forms AND a part in bold, we need to surround the bold part with "**" so that we can replace it by a <strong> tag in the code. Here, "{count} conversation/s" will be bold. You need to put them in your translation too. return conversationMode ? c('Info').ngettext( msgid`You have **${count} conversation** tagged with this label`, `You have **${count} conversations** tagged with this label`, count ) : // translator: To have plural forms AND a part in bold, we need to surround the bold part with "**" so that we can replace it by a <strong> tag in the code. Here, "{count} message/s" will be bold. You need to put them in your translation too. c('Info').ngettext( msgid`You have **${count} message** tagged with this label`, `You have **${count} messages** tagged with this label`, count ); }; const getSelectionPaneText = () => { if (isSearch && !checkeds) { /* translator: To have plural forms AND a part in bold, we need to surround the bold part with "**" so that we can replace it by a <strong> tag in the code. Here, "{numberOfElements} result/s" will be bold. You need to put them in your translation too. * ${elementsFoundCount} is the number of elements found during search * ${labelName} is the name of the label/folder the in which the user is performing a search * Full string for reference: 3 results found in Inbox */ return c('Info').ngettext( msgid`**${elementsFoundCount}** result found in ${labelName}`, `**${elementsFoundCount}** results found in ${labelName}`, elementsFoundCount ); } else { return isCustomLabel ? getLabelText() : getFolderText(); } }; const text = getSelectionPaneText(); const showText = checkeds || labelCount; const showSimpleLoginPlaceholder = simpleLoginIntegrationFeature?.Value && checkeds === 0 && labelID === SPAM && !hasSimpleLogin; // If the user sees the SL placeholder, we need to send once a telemetry request useEffect(() => { if (showSimpleLoginPlaceholder && !placeholderSLSeenSent) { // We need to send to telemetry the total number of messages that the user has in spam handleSendTelemetryData(TelemetrySimpleLoginEvents.spam_view, {}, false, total); setPlaceholderSLSeenSent(true); } }, [showSimpleLoginPlaceholder]); if (loadingSimpleLoadingFeature || isFetchingAccountLinked) { return ( <div className="flex h-full py-4 px-7"> <div className="m-auto text-center max-w-custom" style={{ '--max-w-custom': '30em' }}> <Loader /> </div> </div> ); } return ( <div className="m-auto text-center p-7 max-w-full" data-testid="section-pane--wrapper"> {showSimpleLoginPlaceholder ? ( <SimpleLoginPlaceholder /> ) : ( <> {checkeds === 0 && labelName && ( <h3 className="text-bold lh-rg text-ellipsis" title={labelName}> {labelName} </h3> )} <div className="mb-8"> <p className="mb-2 text-keep-space">{showText ? getBoldFormattedText(text) : null}</p> {isSearch && !encryptedSearchEnabled && ( <> <p> {c('Info') .t`For more search results, try searching for this keyword in the content of your email messages.`} <br /> <Href href={getKnowledgeBaseUrl('/search-message-content')}> {c('Info').t`Learn more`} </Href> </p> <Button onClick={() => setEnableESModalOpen(true)} data-testid="encrypted-search:activate" > {c('Action').t`Enable`} </Button> </> )} </div> <div className="mb-8"> <img src={conversationSvg} alt={c('Alternative text for conversation image').t`Conversation`} className="h-auto" /> </div> {checkeds > 0 && <Button onClick={() => onCheckAll(false)}>{c('Action').t`Deselect`}</Button>} </> )} {renderEnableESModal && <EnableEncryptedSearchModal openSearchAfterEnabling {...enableESModalProps} />} </div> ); }; export default SelectionPane;
3,752
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/view/SimpleLoginPlaceholder.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useModalState } from '@proton/components/components'; import { TelemetrySimpleLoginEvents } from '@proton/shared/lib/api/telemetry'; import connectSimpleLoginSvg from '@proton/styles/assets/img/illustrations/connect-simple-login.svg'; import { useSimpleLoginTelemetry } from '../../hooks/simpleLogin/useSimpleLoginTelemetry'; import SimpleLoginModal from '../simpleLogin/SimpleLoginModal'; const SimpleLoginPlaceholder = () => { const { handleSendTelemetryData } = useSimpleLoginTelemetry(); const [simpleLoginModalProps, setSimpleLoginModalOpen, renderSimpleLoginModal] = useModalState(); const handleSimpleLoginModal = () => { // We need to send a telemetry request when the user clicks on the mask my email button handleSendTelemetryData(TelemetrySimpleLoginEvents.simplelogin_modal_view, {}, true); setSimpleLoginModalOpen(true); }; return ( <> <div className="mb-8"> <img src={connectSimpleLoginSvg} alt={c('Alternative text for conversation image').t`Conversation`} className="h-auto" /> </div> <h2 className="text-bold">{c('Title').t`Don't give spam a chance`}</h2> <p className="mx-auto text-center max-w-custom" style={{ '--max-w-custom': '30em' }}> {c('Info') .t`They can't spam you if they don't know your email address. Protect your inbox with hide-my-email aliases.`} </p> <Button onClick={() => handleSimpleLoginModal()} color="norm" shape="outline"> {c('Action').t`Hide my email`} </Button> {renderSimpleLoginModal && <SimpleLoginModal {...simpleLoginModalProps} />} </> ); }; export default SimpleLoginPlaceholder;
3,753
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/components/view/WelcomePane.tsx
import * as React from 'react'; import { Location } from 'history'; import { c, msgid } from 'ttag'; import { Loader, useUser } from '@proton/components'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { MailSettings } from '@proton/shared/lib/interfaces'; import { LabelCount } from '@proton/shared/lib/interfaces/Label'; import envelope from '@proton/styles/assets/img/illustrations/welcome-pane.svg'; import capitalize from '@proton/utils/capitalize'; import { isConversationMode } from '../../helpers/mailSettings'; interface ContainerProps { children: React.ReactNode; } const Container = ({ children }: ContainerProps) => ( <div className="flex h-full scroll-if-needed py-4 px-7"> <div className="m-auto text-center max-w-custom" style={{ '--max-w-custom': '30em' }}> {children} </div> </div> ); interface Props { mailSettings: MailSettings; location: Location; labelCount: LabelCount | undefined; } const WelcomePane = ({ mailSettings, location, labelCount }: Props) => { const conversationMode = isConversationMode(MAILBOX_LABEL_IDS.INBOX, mailSettings, location); const [user, loadingUser] = useUser(); const unread = labelCount?.Unread || 0; const total = labelCount?.Total || 0; const userName = ( <span key="display-name" className="inline-block max-w-full text-ellipsis align-bottom"> {capitalize(user.DisplayName)} </span> ); const unreadsLabel = conversationMode ? ( <strong key="unreads-label"> {c('Info').ngettext(msgid`${unread} unread conversation`, `${unread} unread conversations`, unread)} </strong> ) : ( <strong key="unreads-label"> {c('Info').ngettext(msgid`${unread} unread message`, `${unread} unread messages`, unread)} </strong> ); const totalLabel = conversationMode ? ( <strong key="total-label"> {c('Info').ngettext(msgid`${total} conversation`, `${total} conversations`, total)} </strong> ) : ( <strong key="total-label">{c('Info').ngettext(msgid`${total} message`, `${total} messages`, total)}</strong> ); const counterMessage = unread ? c('Info').jt`You have ${unreadsLabel} in your inbox.` : c('Info').jt`You have ${totalLabel} in your inbox.`; if (loadingUser) { return ( <Container> <Loader /> </Container> ); } return ( <> <Container> <h1>{user.DisplayName ? c('Title').jt`Welcome ${userName}` : c('Title').t`Welcome`}</h1> <p className="text-keep-space">{labelCount ? counterMessage : null}</p> <hr className="my-8" /> <div className="text-rg"> <img className="h-auto" src={envelope} alt={c('Alternative text for welcome image').t`Welcome`} /> </div> </Container> </> ); }; export default WelcomePane;
3,754
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/ComposeProvider.tsx
import { ReactNode, createContext, useContext } from 'react'; import { MESSAGE_ACTIONS } from '../constants'; import { mailtoParser } from '../helpers/url'; import { ComposeTypes, OnCompose } from '../hooks/composer/useCompose'; const ComposeProviderContext = createContext<OnCompose>(null as any); export const useOnCompose = () => { return useContext(ComposeProviderContext); }; export const useOnMailTo = () => { const onCompose = useOnCompose(); return (src: string) => { const referenceMessage = mailtoParser(src); onCompose({ type: ComposeTypes.newMessage, action: MESSAGE_ACTIONS.NEW, referenceMessage }); }; }; interface Props { children: ReactNode; onCompose: OnCompose; } export const ComposeProvider = ({ children, onCompose }: Props) => { return <ComposeProviderContext.Provider value={onCompose}>{children}</ComposeProviderContext.Provider>; };
3,755
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/ComposerContainer.test.tsx
import { act } from '@testing-library/react'; import { getAppName } from '@proton/shared/lib/apps/helper'; import { APPS, MIME_TYPES } from '@proton/shared/lib/constants'; import { Recipient } from '@proton/shared/lib/interfaces'; import { FORWARDED_MESSAGE } from '@proton/shared/lib/mail/messages'; import { MESSAGE_ACTIONS } from '../constants'; import { formatFullDate } from '../helpers/date'; import { addAddressToCache, clearAll, minimalCache, render, tick } from '../helpers/test/helper'; import { preparePlainText } from '../helpers/transforms/transforms'; import { ComposeTypes, OnCompose } from '../hooks/composer/useCompose'; import { MessageState } from '../logic/messages/messagesTypes'; import { Breakpoints } from '../models/utils'; import { useOnCompose } from './ComposeProvider'; import ComposerContainer from './ComposerContainer'; const ID = 'ID'; const Email = 'me@test.com'; const Signature = 'Signature'; const Sender = { Name: 'sender', Address: 'sender@test.com', }; const protonmailAppName = getAppName(APPS.PROTONMAIL); describe('ComposerContainer', () => { afterEach(clearAll); it('should reply to a plaintext message with the right content', async () => { let onCompose: OnCompose; const content = `mail content with a link -> https://protonmail.com/`; minimalCache(); addAddressToCache({ Email, Signature }); const message = { localID: ID, data: { ID, MIMEType: 'text/plain' as MIME_TYPES, Subject: '', Sender, ToList: [] as Recipient[], }, decryption: { decryptedBody: content, }, messageDocument: { initialized: true, }, ...(await preparePlainText(content, false)), } as MessageState; const Inside = () => { onCompose = useOnCompose(); return null; }; const { findByTestId, unmount } = await render( <ComposerContainer breakpoints={{} as Breakpoints}> <Inside /> </ComposerContainer>, false ); await act(async () => { onCompose({ type: ComposeTypes.newMessage, action: MESSAGE_ACTIONS.REPLY, referenceMessage: message, }); }); const textarea = (await findByTestId('editor-textarea')) as HTMLTextAreaElement; expect(textarea.value).toBe(` ${Signature} Sent with ${protonmailAppName} secure email. On ${formatFullDate(new Date(0))}, ${Sender.Name} <${Sender.Address}> wrote: > mail content > with a link -> https://protonmail.com/`); // Wait for Address focus action await tick(); // Unmount unless the container will listen the reset action unmount(); }); it('should forward to a plaintext message with the right content', async () => { let onCompose: OnCompose; const content = `mail content with a link -> https://protonmail.com/`; minimalCache(); addAddressToCache({ Email, Signature }); const me = { Name: 'me', Address: 'me@protonmail.com' }; const toRecipient = { Name: 'toRecipient', Address: 'toRecipient@protonmail.com' }; const ccRecipient = { Name: 'ccRecipient', Address: 'ccRecipient@protonmail.com' }; const ccRecipient2 = { Name: '', Address: 'ccRecipient2@protonmail.com' }; const messageSubject = 'Message subject'; const message = { localID: ID, data: { ID, MIMEType: 'text/plain' as MIME_TYPES, Subject: messageSubject, Sender, ToList: [me, toRecipient] as Recipient[], CCList: [ccRecipient, ccRecipient2] as Recipient[], }, decryption: { decryptedBody: content, }, messageDocument: { initialized: true, }, ...(await preparePlainText(content, false)), } as MessageState; const Inside = () => { onCompose = useOnCompose(); return null; }; const { findByTestId, unmount } = await render( <ComposerContainer breakpoints={{} as Breakpoints}> <Inside /> </ComposerContainer>, false ); await act(async () => { onCompose({ type: ComposeTypes.newMessage, action: MESSAGE_ACTIONS.FORWARD, referenceMessage: message, }); }); const textarea = (await findByTestId('editor-textarea')) as HTMLTextAreaElement; expect(textarea.value).toBe(` ${Signature} Sent with ${protonmailAppName} secure email. ${FORWARDED_MESSAGE} From: ${Sender.Name} <${Sender.Address}> Date: On ${formatFullDate(new Date(0))} Subject: ${messageSubject} To: ${me.Name} <${me.Address}>, ${toRecipient.Name} <${toRecipient.Address}> CC: ${ccRecipient.Name} <${ccRecipient.Address}>, ${ccRecipient2.Address} <${ccRecipient2.Address}> > mail content > with a link -> https://protonmail.com/`); // Wait for Address focus action await tick(); // Unmount unless the container will listen the reset action unmount(); }); });
3,756
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/ComposerContainer.tsx
import { ReactNode, memo, useEffect, useRef, useState } from 'react'; import { c } from 'ttag'; import { useBeforeUnload, useDrawerWidth } from '@proton/components'; import ComposerFrame from '../components/composer/ComposerFrame'; import { MAX_ACTIVE_COMPOSER_DESKTOP, MAX_ACTIVE_COMPOSER_MOBILE } from '../helpers/composerPositioning'; import { useCompose } from '../hooks/composer/useCompose'; import { useClickMailContent } from '../hooks/useClickMailContent'; import { selectOpenedComposersIds } from '../logic/composers/composerSelectors'; import { composerActions } from '../logic/composers/composersSlice'; import { useAppDispatch, useAppSelector } from '../logic/store'; import { Breakpoints } from '../models/utils'; import { ComposeProvider } from './ComposeProvider'; import '../components/composer/composer.scss'; interface Props { breakpoints: Breakpoints; children: ReactNode; } const ComposerContainer = ({ breakpoints, children }: Props) => { const dispatch = useAppDispatch(); const composerIDs = useAppSelector(selectOpenedComposersIds); const [focusedComposerID, setFocusedComposerID] = useState<string>(); const drawerOffset = useDrawerWidth(); const returnFocusToElementRef = useRef<HTMLElement | null>(null); const isComposerOpened = composerIDs.length > 0; useClickMailContent(() => setFocusedComposerID(undefined)); const maxActiveComposer = breakpoints.isNarrow ? MAX_ACTIVE_COMPOSER_MOBILE : MAX_ACTIVE_COMPOSER_DESKTOP; const handleClose = (composerId: string) => () => { dispatch(composerActions.removeComposer({ ID: composerId })); const remainingComposerIDs = composerIDs.filter((id) => id !== composerId); if (remainingComposerIDs.length) { setFocusedComposerID(remainingComposerIDs[0]); } }; const { handleCompose, storageCapacityModal, sendingFromDefaultAddressModal, sendingOriginalMessageModal } = useCompose({ focusComposer: setFocusedComposerID, maxActiveComposer, openedComposerIDs: composerIDs, returnFocusToElementRef, }); const handleFocus = (composerID: string) => () => { setFocusedComposerID(composerID); }; // After closing all composers, focus goes back to previously focused element useEffect(() => { if (composerIDs.length === 0 && returnFocusToElementRef.current) { returnFocusToElementRef.current.focus(); returnFocusToElementRef.current = null; } }, [composerIDs]); useBeforeUnload( isComposerOpened ? c('Info').t`The data you have entered in the draft may not be saved if you leave the page.` : '' ); return ( <ComposeProvider onCompose={handleCompose}> {children} <div> {composerIDs.map((composerID, i) => ( <ComposerFrame key={composerID} index={i} composerID={composerID} count={composerIDs.length} focus={composerID === focusedComposerID} breakpoints={breakpoints} onFocus={handleFocus(composerID)} onClose={handleClose(composerID)} drawerOffset={drawerOffset} /> ))} </div> {sendingFromDefaultAddressModal} {sendingOriginalMessageModal} {storageCapacityModal} </ComposeProvider> ); }; export default memo(ComposerContainer);
3,757
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/EncryptedSearchProvider.tsx
import { ReactNode, createContext, useContext, useEffect, useMemo, useRef, useState } from 'react'; import { useHistory } from 'react-router-dom'; import { c } from 'ttag'; import { FeatureCode, useAddresses, useApi, useFeature, useGetMessageCounts, useGetUserKeys, useSubscribeEventManager, useUser, useWelcomeFlags, } from '@proton/components'; import { checkVersionedESDB, contentIndexingProgress, getIndexKey, useEncryptedSearch, wrappedGetOldestInfo, } from '@proton/encrypted-search'; import { SECOND } from '@proton/shared/lib/constants'; import { EVENT_ERRORS } from '@proton/shared/lib/errors'; import { isMobile } from '@proton/shared/lib/helpers/browser'; import { isElectronApp } from '@proton/shared/lib/helpers/desktop'; import { getItem, removeItem, setItem } from '@proton/shared/lib/helpers/storage'; import { isFree } from '@proton/shared/lib/user/helpers'; import { defaultESContextMail, defaultESMailStatus } from '../constants'; import { convertEventType, getESCallbacks, getESFreeBlobKey, parseSearchParams } from '../helpers/encryptedSearch'; import { useGetMessageKeys } from '../hooks/message/useGetMessageKeys'; import { ESBaseMessage, ESDBStatusMail, ESMessageContent, EncryptedSearchFunctionsMail, NormalizedSearchParams, } from '../models/encryptedSearch'; import { Event } from '../models/event'; const EncryptedSearchContext = createContext<EncryptedSearchFunctionsMail>(defaultESContextMail); export const useEncryptedSearchContext = () => useContext(EncryptedSearchContext); interface Props { children?: ReactNode; } const EncryptedSearchProvider = ({ children }: Props) => { const history = useHistory(); const [user] = useUser(); const getMessageKeys = useGetMessageKeys(); const getUserKeys = useGetUserKeys(); const getMessageCounts = useGetMessageCounts(); const api = useApi(); const [welcomeFlags] = useWelcomeFlags(); const { feature: featureES, update: updateSpotlightES } = useFeature(FeatureCode.SpotlightEncryptedSearch); const { feature: esAutomaticBackgroundIndexingFeature } = useFeature(FeatureCode.ESAutomaticBackgroundIndexing); const { isSearch, page } = parseSearchParams(history.location); const [addresses] = useAddresses(); const [esMailStatus, setESMailStatus] = useState<ESDBStatusMail>(defaultESMailStatus); // Allow to track changes in page to set the elements list accordingly const pageRef = useRef<number>(0); const esCallbacks = getESCallbacks({ getMessageKeys, getMessageCounts, api, user, history, numAddresses: addresses.length, }); const contentIndexingSuccessMessage = c('Success').t`Message content search enabled`; const esLibraryFunctions = useEncryptedSearch<ESBaseMessage, NormalizedSearchParams, ESMessageContent>({ refreshMask: EVENT_ERRORS.MAIL, esCallbacks, contentIndexingSuccessMessage, sendMetricsOnSearch: true, }); /** * Open the advanced search dropdown */ const openDropdown = () => { setESMailStatus((esMailStatus) => ({ ...esMailStatus, dropdownOpened: true, })); }; /** * Close the advanced search dropdown */ const closeDropdown = () => { setESMailStatus((esMailStatus) => ({ ...esMailStatus, dropdownOpened: false, })); }; /** * Temporarily disable ES for times when search is too slow and a server-side * search is needed. The toggle is set automatically back on upon exiting search mode */ const setTemporaryToggleOff = () => { setESMailStatus((esMailStatus) => ({ ...esMailStatus, temporaryToggleOff: true, })); void esLibraryFunctions.toggleEncryptedSearch(); }; /** * Report the status of IndexedDB with the addition of Mail-specific fields */ const esStatus = useMemo( () => ({ ...esLibraryFunctions.esStatus, ...esMailStatus, }), [esLibraryFunctions.esStatus, esMailStatus] ); /** * Initialize ES */ const initializeESMail = async () => { if (isElectronApp() || (isFree(user) && !!esAutomaticBackgroundIndexingFeature?.Value)) { if (!(await checkVersionedESDB(user.ID))) { // Avoid indexing for incognito users, and users that only log in on a device once // If initialIndexing is set, it means that the user is most likely not in incognito mode, since they have persistent storage // (or they loaded the page twice in a single incognito session) const initialIndexing = getItem(getESFreeBlobKey(user.ID)) === 'true'; if (initialIndexing) { // Start indexing const success = await esLibraryFunctions.enableEncryptedSearch({ isBackgroundIndexing: true }); if (success) { await esLibraryFunctions.enableContentSearch({ isBackgroundIndexing: true }); removeItem(getESFreeBlobKey(user.ID)); } return; } else { setItem(getESFreeBlobKey(user.ID), 'true'); return; } } } // Enable encrypted search for all new users. For paid users only, // automatically enable content search too if (isElectronApp() || (welcomeFlags.isWelcomeFlow && !isMobile())) { // Prevent showing the spotlight for ES to them (as long as the spotlight feature exists) if (featureES !== undefined) { await updateSpotlightES(false); } return esLibraryFunctions.enableEncryptedSearch({ showErrorNotification: false }).then((success) => { if (success) { return esLibraryFunctions.enableContentSearch({ notify: false }); } }); } // Existence of IDB is checked since the following operations interact with it if (!(await checkVersionedESDB(user.ID))) { return; } let contentProgress = await contentIndexingProgress.read(user.ID); if (!contentProgress) { return esLibraryFunctions.initializeES(); } // We need to cache the metadata directly, since the library is // not yet initialised, i.e. the flags in memory are not yet set. // The reason for not initialising the library just yet is that // in case an upgrade/downgrade is needed, the flags would be set // incorrectly due to the way we encode the latter const indexKey = await getIndexKey(getUserKeys, user.ID); if (!indexKey) { return esLibraryFunctions.esDelete(); } return esLibraryFunctions.initializeES(); }; useSubscribeEventManager(async (event: Event) => esLibraryFunctions.handleEvent(convertEventType(event, addresses.length)) ); /** * Keep the current page always up to date to avoid pagination glitches */ useEffect(() => { pageRef.current = page; }, [page]); /** * In case content indexing finished, we need to update the last content * time to show appropriate UI */ useEffect(() => { const run = async () => { const timepoint = await wrappedGetOldestInfo(user.ID); if (timepoint) { setESMailStatus((esMailStatus) => ({ ...esMailStatus, lastContentTime: timepoint.timepoint[0] * SECOND, })); } }; const { dbExists, contentIndexingDone } = esStatus; if (dbExists && contentIndexingDone) { void run(); } }, [esStatus.contentIndexingDone]); /** * Re-enable ES in case it was disabled because of a slow search */ useEffect(() => { if (!isSearch) { const { temporaryToggleOff } = esMailStatus; if (temporaryToggleOff) { void esLibraryFunctions.toggleEncryptedSearch(); // Remove the temporary switch-off of ES setESMailStatus((esMailStatus) => ({ ...esMailStatus, temporaryToggleOff: false, })); } } }, [isSearch]); useEffect(() => { void initializeESMail(); }, []); const esFunctions = { ...esLibraryFunctions, esStatus, openDropdown, closeDropdown, setTemporaryToggleOff, }; return <EncryptedSearchContext.Provider value={esFunctions}>{children}</EncryptedSearchContext.Provider>; }; export default EncryptedSearchProvider;
3,758
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/LegacyMessagesMigrationContainer.tsx
import { useEffect } from 'react'; import { useApi, useGetAddressKeys } from '@proton/components'; import { getApiWithAbort, getSilentApi } from '@proton/shared/lib/api/helpers/customConfig'; import { makeLegacyMessageIDsFetcher, migrateMultiple } from '@proton/shared/lib/mail/legacyMessagesMigration/helpers'; import noop from '@proton/utils/noop'; const LegacyMessagesMigrationContainer = () => { const api = useApi(); const getAddressKeys = useGetAddressKeys(); useEffect(() => { const abortController = new AbortController(); const { signal } = abortController; // Since the migration happens in the background with the user unaware of it, // we silence API to avoid displaying possible errors in the UI const silentApiWithAbort = getApiWithAbort(getSilentApi(api), signal); const run = async () => { const it = makeLegacyMessageIDsFetcher(silentApiWithAbort); let result = await it.next(); while (!result.done) { const messageIDs = result.value.map(({ ID }) => ID); await migrateMultiple({ messageIDs, api: silentApiWithAbort, getAddressKeys }).catch(noop); result = await it.next(); } }; void run(); return () => { abortController.abort(); }; }, []); return null; }; export default LegacyMessagesMigrationContainer;
3,759
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/MailStartupModals.tsx
import { useEffect, useRef } from 'react'; import { FeatureCode, RebrandingFeedbackModal, getShouldOpenReferralModal, useFeature, useModalState, useRebrandingFeedback, useSubscription, useWelcomeFlags, } from '@proton/components'; import { OPEN_OFFER_MODAL_EVENT } from '@proton/shared/lib/constants'; import MailOnboardingModal from '../components/onboarding/MailOnboardingModal'; interface Props { onboardingOpen: boolean; } const MailStartupModals = ({ onboardingOpen }: Props) => { // Onboarding modal const [onboardingModal, setOnboardingModal, renderOnboardingModal] = useModalState(); // Referral modal const [subscription] = useSubscription(); const seenReferralModal = useFeature<boolean>(FeatureCode.SeenReferralModal); const shouldOpenReferralModal = getShouldOpenReferralModal({ subscription, feature: seenReferralModal.feature }); const [rebrandingFeedbackModal, setRebrandingFeedbackModal, renderRebrandingFeedbackModal] = useModalState(); const handleRebrandingFeedbackModalDisplay = useRebrandingFeedback(); const [, setWelcomeFlagsDone] = useWelcomeFlags(); const onceRef = useRef(false); useEffect(() => { if (onceRef.current) { return; } const openModal = (setModalOpen: (newValue: boolean) => void) => { onceRef.current = true; setModalOpen(true); }; if (onboardingOpen) { openModal(setOnboardingModal); } else if (shouldOpenReferralModal.open) { onceRef.current = true; document.dispatchEvent(new CustomEvent(OPEN_OFFER_MODAL_EVENT)); } else if (handleRebrandingFeedbackModalDisplay) { openModal(setRebrandingFeedbackModal); } }, [shouldOpenReferralModal.open, handleRebrandingFeedbackModalDisplay, onboardingOpen]); return ( <> {renderOnboardingModal && ( <MailOnboardingModal onDone={() => { setWelcomeFlagsDone(); onboardingModal.onClose(); }} onExit={onboardingModal.onExit} open={onboardingModal.open} /> )} {renderRebrandingFeedbackModal && ( <RebrandingFeedbackModal onMount={handleRebrandingFeedbackModalDisplay} {...rebrandingFeedbackModal} /> )} </> ); }; export default MailStartupModals;
3,760
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/PageContainer.test.tsx
import { fireEvent } from '@testing-library/react'; import { getAppName } from '@proton/shared/lib/apps/helper'; import { APPS } from '@proton/shared/lib/constants'; import { SHORTCUTS } from '@proton/shared/lib/mail/mailSettings'; import { addApiMock, addToCache, assertFocus, clearAll, minimalCache, onCompose, render, tick, } from '../helpers/test/helper'; import { Breakpoints } from '../models/utils'; import PageContainer from './PageContainer'; jest.setTimeout(20000); describe('PageContainer', () => { const props = { breakpoints: {} as Breakpoints, isComposerOpened: false, }; beforeAll(() => { global.fetch = jest.fn(); }); beforeEach(clearAll); const setup = async ({ Component = PageContainer } = {}) => { addApiMock('importer/v1/importers', () => ({ Importers: [] })); addApiMock('settings/calendar', () => ({})); addApiMock('calendar/v1', () => ({})); addApiMock('payments/v4/plans', () => ({})); addApiMock('mail/v4/conversations', () => ({})); addApiMock('domains/optin', () => ({})); addApiMock('payments/v4/subscription/latest', () => ({})); addApiMock('mail/v4/incomingdefaults', () => ({ IncomingDefaults: [], Total: 0, GlobalTotal: 0, })); minimalCache(); addToCache('MailSettings', { Shortcuts: SHORTCUTS.ENABLED }); const renderResult = await render(<Component {...props} />, false); const { container } = renderResult; return { ...renderResult, questionMark: () => fireEvent.keyDown(container, { key: '?' }), tab: () => fireEvent.keyDown(container, { key: 'Tab' }), slash: () => fireEvent.keyDown(container, { key: '/' }), n: () => fireEvent.keyDown(container, { key: 'N' }), }; }; describe('hotkeys', () => { it('should open hotkeys modal on ?', async () => { const { questionMark, getByText } = await setup(); const appName = getAppName(APPS.PROTONMAIL); questionMark(); getByText(`${appName} Keyboard Shortcuts`); }); it('should focus element list on Tab', async () => { const Component = () => { return ( <> <PageContainer {...props} /> <div data-shortcut-target="item-container" tabIndex={-1} /> </> ); }; const { tab } = await setup({ Component: Component as any }); tab(); const itemContainer = document.querySelector('[data-shortcut-target="item-container"]'); assertFocus(itemContainer); }); it('should focus search bar on /', async () => { const { slash } = await setup(); slash(); await tick(); const search = document.querySelector('[data-shorcut-target="searchbox-field"]'); assertFocus(search); }); it('should open composer on a N', async () => { const { n } = await setup(); n(); expect(onCompose).toHaveBeenCalled(); }); }); });
3,761
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/PageContainer.tsx
import { Ref, forwardRef, memo } from 'react'; import { Redirect, useRouteMatch } from 'react-router-dom'; import { FeatureCode, MailShortcutsModal, useFeatures, useFolders, useLabels, useModalState, useOpenDrawerOnLoad, useUserSettings, } from '@proton/components'; import { UserSettings } from '@proton/shared/lib/interfaces'; import { Label } from '@proton/shared/lib/interfaces/Label'; import useMailModel from 'proton-mail/hooks/useMailModel'; import PrivateLayout from '../components/layout/PrivateLayout'; import MailOnboardingWrapper from '../components/onboarding/MailOnboardingWrapper'; import { LabelActionsContextProvider } from '../components/sidebar/EditLabelContext'; import { HUMAN_TO_LABEL_IDS } from '../constants'; import { MailUrlParams } from '../helpers/mailboxUrl'; import { useContactsListener } from '../hooks/contact/useContactsListener'; import { useConversationsEvent } from '../hooks/events/useConversationsEvents'; import { useMessagesEvents } from '../hooks/events/useMessagesEvents'; import useIncomingDefaultsEvents from '../hooks/incomingDefaults/useIncomingDefaultsEvents'; import useIncomingDefaultsLoad from '../hooks/incomingDefaults/useIncomingDefaultsLoad'; import { usePageHotkeys } from '../hooks/mailbox/usePageHotkeys'; import { useDeepMemo } from '../hooks/useDeepMemo'; import { Breakpoints } from '../models/utils'; import LegacyMessagesMigrationContainer from './LegacyMessagesMigrationContainer'; import MailboxContainer from './mailbox/MailboxContainer'; interface Props { params: MailUrlParams; breakpoints: Breakpoints; } const PageContainer = ({ params: { elementID, labelID, messageID }, breakpoints }: Props, ref: Ref<HTMLDivElement>) => { const [userSettings] = useUserSettings(); const mailSettings = useMailModel('MailSettings'); const [mailShortcutsProps, setMailShortcutsModalOpen] = useModalState(); useOpenDrawerOnLoad(); const { getFeature } = useFeatures([FeatureCode.LegacyMessageMigrationEnabled]); const { feature: runLegacyMessageFeature } = getFeature(FeatureCode.LegacyMessageMigrationEnabled); const runLegacyMessageMigration = runLegacyMessageFeature?.Value; useContactsListener(); useConversationsEvent(); useMessagesEvents(); /** * Incoming defaults * - cache loading * - events subscription */ useIncomingDefaultsLoad(); useIncomingDefaultsEvents(); usePageHotkeys({ onOpenShortcutsModal: () => setMailShortcutsModalOpen(true) }); if (!labelID) { return <Redirect to="/inbox" />; } return ( <PrivateLayout ref={ref} labelID={labelID} elementID={elementID} breakpoints={breakpoints}> <MailOnboardingWrapper /> {runLegacyMessageMigration && <LegacyMessagesMigrationContainer />} <LabelActionsContextProvider> <MailboxContainer labelID={labelID} mailSettings={mailSettings} userSettings={userSettings as UserSettings} breakpoints={breakpoints} elementID={elementID} messageID={messageID} /> </LabelActionsContextProvider> <MailShortcutsModal {...mailShortcutsProps} /> </PrivateLayout> ); }; const MemoPageContainer = memo(forwardRef(PageContainer)); interface PageParamsParserProps { breakpoints: Breakpoints; } const PageParamsParser = (props: PageParamsParserProps, ref: Ref<HTMLDivElement>) => { const [labels = []] = useLabels(); const [folders = []] = useFolders(); const match = useRouteMatch<MailUrlParams>(); const params = useDeepMemo(() => { const labelIDs = [...labels, ...folders].map(({ ID }: Label) => ID); const { elementID, labelID: currentLabelID = '', messageID } = (match || {}).params || {}; const labelID = HUMAN_TO_LABEL_IDS[currentLabelID] || (labelIDs.includes(currentLabelID) && currentLabelID); return { elementID, labelID, messageID }; }, [match]); return <MemoPageContainer ref={ref} {...props} params={params} />; }; export default forwardRef(PageParamsParser);
3,762
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/eo/EOContainer.tsx
import { useCallback, useState } from 'react'; import { Provider as ReduxProvider } from 'react-redux'; import { ModalsChildren } from '@proton/components'; import ForceRefreshContext from '@proton/components/containers/forceRefresh/context'; import { APPS } from '@proton/shared/lib/constants'; import { store } from '../../logic/eo/eoStore'; import EOPageContainer from './EOPageContainer'; import FakeEventManagerProvider from './FakeEventManagerProvider'; import EOLayout from './layout/EOLayout'; const EOContainer = () => { const [, setState] = useState(1); const refresh = useCallback(() => setState((i) => i + 1), []); return ( <FakeEventManagerProvider> <ForceRefreshContext.Provider value={refresh}> <EOLayout toApp={APPS.PROTONMAIL}> <ReduxProvider store={store}> <EOPageContainer /> </ReduxProvider> </EOLayout> <ModalsChildren /> </ForceRefreshContext.Provider> </FakeEventManagerProvider> ); }; export default EOContainer;
3,763
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/eo/EOPageContainer.tsx
import { useEffect } from 'react'; import { Route, Switch } from 'react-router-dom'; import { UnAuthenticated } from '@proton/components'; import createSecureSessionStorage from '@proton/shared/lib/authentication/createSecureSessionStorage'; import ViewEOMessage from '../../components/eo/message/ViewEOMessage'; import EOReply from '../../components/eo/reply/EOReply'; import EOUnlock from '../../components/eo/unlock/EOUnlock'; import { EO_MESSAGE_REDIRECT_PATH, EO_REDIRECT_PATH, EO_REPLY_REDIRECT_PATH } from '../../constants'; import { init } from '../../logic/eo/eoActions'; import { useAppDispatch } from '../../logic/store'; const { set, get } = createSecureSessionStorage(); const PageContainer = () => { const dispatch = useAppDispatch(); useEffect(() => { const initStore = async () => { await dispatch(init({ get })); }; void initStore(); }, []); return ( <UnAuthenticated> <Switch> <Route path={`${EO_MESSAGE_REDIRECT_PATH}/:id?`}> <ViewEOMessage setSessionStorage={set} /> </Route> <Route path={`${EO_REPLY_REDIRECT_PATH}/:id?`}> <EOReply setSessionStorage={set} /> </Route> <Route path={`${EO_REDIRECT_PATH}/:id?`}> <EOUnlock setSessionStorage={set} /> </Route> <Route path="*"> <EOUnlock setSessionStorage={set} /> </Route> </Switch> </UnAuthenticated> ); }; export default PageContainer;
3,764
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/eo/FakeEventManagerProvider.tsx
import { ReactNode } from 'react'; import EventManagerContext from '@proton/components/containers/eventManager/context'; import createEventManager from '@proton/shared/lib/eventManager/eventManager'; interface Props { children: ReactNode; } /** This Provider is used in EO. In some components (e.g. LinkConfirmationModal) we are using the Event Manager, But we do not have any session in EO, meaning that we need to "Fake" calls to this Provider */ const FakeEventManagerProvider = ({ children }: Props) => { const fakeEventManager = { // eslint-disable-next-line @typescript-eslint/no-unused-vars setEventID: (eventID: string) => {}, getEventID: () => { return undefined; }, start: () => {}, stop: () => {}, call: () => { // @ts-ignore return new Promise<void>(); }, reset: () => {}, } as ReturnType<typeof createEventManager>; return <EventManagerContext.Provider value={fakeEventManager}>{children}</EventManagerContext.Provider>; }; export default FakeEventManagerProvider;
3,765
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/eo
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/eo/layout/EOLanguageSelect.tsx
import { addDays } from 'date-fns'; import { DropdownMenu, DropdownMenuButton, SimpleDropdown, useConfig, useForceRefresh } from '@proton/components'; import { setCookie } from '@proton/shared/lib/helpers/cookies'; import { getSecondLevelDomain } from '@proton/shared/lib/helpers/url'; import { localeCode } from '@proton/shared/lib/i18n'; import { getBrowserLocale, getClosestLocaleCode } from '@proton/shared/lib/i18n/helper'; import { loadDateLocale, loadLocale } from '@proton/shared/lib/i18n/loadLocale'; import { TtagLocaleMap } from '@proton/shared/lib/interfaces/Locale'; interface Props { className?: string; locales?: TtagLocaleMap; } const cookieDomain = `.${getSecondLevelDomain(window.location.hostname)}`; const LanguageSelect = ({ className, locales = {} }: Props) => { const forceRefresh = useForceRefresh(); const { LOCALES = {} } = useConfig(); const handleChange = async (newLocale: string) => { const localeCode = getClosestLocaleCode(newLocale, locales); await Promise.all([loadLocale(localeCode, locales), loadDateLocale(localeCode, getBrowserLocale())]); setCookie({ cookieName: 'Locale', cookieValue: localeCode, expirationDate: addDays(new Date(), 30).toUTCString(), cookieDomain, path: '/', }); forceRefresh(); }; const languages = Object.keys(LOCALES).map((value) => ( <DropdownMenuButton className="text-left" key={value} onClick={() => handleChange(value)}> {LOCALES[value]} </DropdownMenuButton> )); const selectedLanguage = ( <> <span className="ml-2">{LOCALES[localeCode]}</span> </> ); return ( <SimpleDropdown as="button" type="button" content={selectedLanguage} className={className}> <DropdownMenu>{languages}</DropdownMenu> </SimpleDropdown> ); }; export default LanguageSelect;
3,766
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/eo
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/eo/layout/EOLayout.scss
/* * signup specific styles */ @import '~@proton/styles/scss/lib'; .eo-layout { // nice mountains image has left :'-( &-bg { background-color: var(--background-norm); @include media('>xsmall') { background: linear-gradient(68.66deg, #e8e2ff 1.3%, #f7f5ff 50%); } } // main content transition: max-inline-size 0.15s easing(ease-in); border-radius: var(--border-radius-lg); &-header { padding-inline: em(48); padding-block: 0.5em 0; } &-title { font-size: 2em; font-weight: normal; } &-main-content { padding-inline: em(48); padding-block: em(24); @include media('<=small') { padding-inline: em(20); } @include media('<=xsmall') { padding-inline: 2px; padding-block: 0; } } &-container-challenge { min-block-size: rem(100); } @include media('<=xsmall') { .message-attachmentList-item-container { max-inline-size: 100%; } .composer-attachment-list-wrapper { flex-wrap: nowrap; } } } .eo-layout-container { @include media('<=small') { .payment-left, .payment-right { inline-size: 100%; padding-inline: 0; } } }
3,767
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/eo
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/eo/layout/EOLayout.tsx
import { ReactNode } from 'react'; import { c } from 'ttag'; import { ButtonLike, Href } from '@proton/atoms'; import { AppLink, CalendarLogo, DriveLogo, Logo, MailLogo, PublicTopBanners, VpnLogo, getAppVersion, useConfig, } from '@proton/components'; import { APP_NAMES, BRAND_NAME, CALENDAR_APP_NAME, DRIVE_APP_NAME, MAIL_APP_NAME, VPN_APP_NAME, } from '@proton/shared/lib/constants'; import { getPrivacyPolicyURL, getStaticURL, getTermsURL } from '@proton/shared/lib/helpers/url'; import { locales } from '@proton/shared/lib/i18n/locales'; import LanguageSelect from './EOLanguageSelect'; import './EOLayout.scss'; export interface Props { children: ReactNode; hasLanguageSelect?: boolean; toApp: APP_NAMES; } const EOLayout = ({ children, toApp, hasLanguageSelect = true }: Props) => { const { APP_VERSION } = useConfig(); const termsLink = <Href key="terms" className="eo-footer-link" href={getTermsURL()}>{c('Link').t`Terms`}</Href>; const privacyLink = ( <Href key="privacy" className="eo-footer-link" href={getPrivacyPolicyURL()}>{c('Link').t`Privacy policy`}</Href> ); const appVersion = getAppVersion(APP_VERSION); const size = 48; return ( <div className="flex-no-min-children flex-nowrap flex-column h-full eo-layout-bg scroll-if-needed"> <PublicTopBanners /> <header className="flex flex-nowrap flex-justify-space-between flex-align-items-center flex-item-noshrink p-7 on-tiny-mobile-flex-column"> <AppLink to="/" toApp={toApp} target="_self"> <Logo appName={toApp} /> </AppLink> <div className="flex flex-nowrap flex-align-items-center on-mobile-flex-column"> <div className="ml-0 md:ml-4"> <Href href="/signup" target="_self"> <ButtonLike className="text-semibold" shape="outline" color="norm" pill>{c('Link') .t`Sign up for free`}</ButtonLike> </Href> </div> </div> </header> <div className="eo-layout-container sm:mx-7 flex-item-fluid flex flex-nowrap flex-column"> <div>{children}</div> <div className="mx-auto mt-8"> <Href href={getStaticURL('/mail')} className="inline-block m-0 md:mx-2 w-1/4 sm:w-auto" title={MAIL_APP_NAME} > <MailLogo variant="glyph-only" size={size} /> </Href> <Href href={getStaticURL('/calendar')} className="inline-block m-0 md:mx-2 w-1/4 sm:w-auto" title={CALENDAR_APP_NAME} > <CalendarLogo variant="glyph-only" size={size} /> </Href> <Href href={getStaticURL('/drive')} className="inline-block m-0 md:mx-2 w-1/4 sm:w-auto" title={DRIVE_APP_NAME} > <DriveLogo variant="glyph-only" size={size} /> </Href> <Href href="https://protonvpn.com" className="inline-block m-0 md:mx-2 w-1/4 sm:w-auto" title={VPN_APP_NAME} > <VpnLogo variant="glyph-only" size={size} /> </Href> </div> </div> <footer className="flex-item-noshrink text-center p-4"> <div> { // translator: full sentence 'Proton. Privacy by default.' c('Footer').t`${BRAND_NAME}. Privacy by default.` } </div> <div className="text-center text-sm m-0 pt-4 pb-2 flex-item-noshrink"> <span className="block md:inline">{termsLink}</span> <span className="color-weak px-3 hidden md:inline" aria-hidden="true"> | </span> <span className="block md:inline">{privacyLink}</span> <span className="color-weak px-3 hidden md:inline" aria-hidden="true"> | </span> <span className="block md:inline">{c('Info').jt`Version ${appVersion}`}</span> <span className="color-weak px-3 hidden md:inline" aria-hidden="true"> | </span> {hasLanguageSelect && ( <span className="block md:inline-flex"> <LanguageSelect className="align-baseline color-primary mx-auto" locales={locales} /> </span> )} </div> </footer> </div> ); }; export default EOLayout;
3,768
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/eo
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/eo/layout/bg-mountains.svg
<svg width="1440" height="1152" viewBox="0 0 1440 1152" fill="none" xmlns="http://www.w3.org/2000/svg"> <g clip-path="url(#clip0)"> <rect width="1440" height="1152" fill="url(#paint0_linear)" /> <path d="M1653.8 718.387C1626.48 710.276 1607.28 711.36 1595.03 713.689C1577.06 717.102 1544.31 728.786 1523.36 740.35C1518.99 742.759 1510.54 747.698 1501.07 746.614C1495.39 745.972 1493.63 743.603 1485.1 742.799C1480.36 742.358 1475.99 742.599 1470.72 742.88C1463.21 743.281 1460.39 744.004 1456.35 742.96C1452.47 741.956 1448.3 740.631 1444.87 739.387C1439.65 737.54 1434.75 738.583 1430.09 739.748C1416.66 743.161 1413.39 746.453 1404.53 749.385C1395.26 752.436 1375.41 758.981 1359.08 754.685C1356.5 754.002 1351.93 752.476 1344.7 751.392C1335.88 750.067 1331.06 750.589 1328.73 750.91C1325.63 751.352 1323.51 752.035 1319.95 753.199C1309.42 756.612 1309.7 758.62 1304.8 758.86C1300.03 759.101 1297.7 757.254 1291.25 757.817C1289.82 757.937 1288.43 758.057 1286.71 758.579C1283.85 759.463 1283.57 760.386 1280.87 761.029C1279.12 761.43 1277.65 761.43 1275.81 761.43C1273.48 761.43 1272.79 761.069 1270.21 760.908C1270.21 760.908 1268.13 760.788 1265.15 760.948C1258.49 761.31 1251.14 763.639 1250 764L1654 761.751L1653.8 718.387Z" fill="#353F6C" /> <path d="M169 720C169 720 151.752 719.768 139.229 715.361C129.728 712.01 128.331 712.784 124.14 714.175C120.812 715.309 117.281 715.979 113.674 716.134C108.594 716.34 104.25 715.464 101.557 712.191C97.9758 707.809 94.3687 704.381 84.3857 702.809C73.9962 701.237 77.1461 694.665 59.9997 696.546C42.8533 698.428 40.0591 699.278 32.8957 692.423C25.7323 685.567 18.7213 684.046 10.4403 685.284C2.15918 686.521 0 680 0 680L0.12701 720H169Z" fill="#353F6C" /> <path d="M80 755C84.5887 754.841 89.5572 751.786 91.9054 751.012C95.7186 749.762 96.5372 748.771 100.587 747.818C102.246 747.421 105.262 746.747 109.162 746.925C112.932 747.084 113.406 747.878 116.422 747.719C119.632 747.541 121.01 746.549 123.682 745.815C128.744 744.426 133.29 745.14 135.617 745.914C140.615 747.58 139.947 747.838 146.022 749.604C150.826 751.012 154.575 752.103 159.034 751.409C162.675 750.834 163.472 748.909 168.513 746.707C173.447 744.545 176.14 744.704 179.651 745.715C183.292 746.747 183.917 747.917 188.333 748.215C190.358 748.354 190.66 748.017 194.516 748.017C195.981 748.017 198.739 747.997 201.13 748.314C205.611 748.89 207.83 750.497 211.428 752.004C214.401 753.254 218.839 754.643 225 755H81.5H80Z" fill="#353F6C" /> <path d="M1563.5 913.994L1551.75 889.08L1502.98 849.847L1478.69 824.737L1427.38 790.8L1420.13 781.188L1364.11 834.153L1318.87 873.387L1283.81 890.65L1254.04 899.673L1237 913.994H1563.5Z" fill="url(#paint1_linear)" /> <path d="M1414.84 786.297L1430.71 821.607H1446.38L1471.45 859.271L1412.3 914.002V874.18L1364.31 914.002H1563.5C1563.5 914.002 1554.88 890.266 1553.32 889.677C1551.75 889.089 1503.18 849.855 1503.18 849.855L1478.89 824.746L1427.38 790.808L1420.13 781L1414.84 786.297Z" fill="url(#paint2_linear)" /> <path d="M152.769 927.995L142.519 906.266L99.9831 872.047L78.8006 850.147L50.7223 825.519L27.7233 812.164L-21.1333 858.36L-60.5943 892.579L-91.1723 907.635L-117.138 915.505L-132 927.995H152.769Z" fill="url(#paint3_linear)" /> <path d="M23.11 816.62L42.4298 828.326L72.0744 876.445L56.827 881.339L32.4059 910.557L0.571188 900.09L-20.9634 928.002H152.768C152.768 928.002 145.251 907.3 143.885 906.787C142.518 906.273 100.153 872.054 100.153 872.054L78.9705 850.154L50.6132 825.519L27.7223 812L23.11 816.62Z" fill="url(#paint4_linear)" /> <path d="M983.346 913.721L962.102 885.395C962.102 885.395 938.936 880.236 937.014 879.629C935.092 879.022 910.004 860.004 910.004 860.004L858.513 929.097L812.788 967.032L774.853 1005.68L983.346 953.578V913.721Z" fill="url(#paint5_linear)" /> <path d="M913.241 971.075V932.836L933.776 909.67L929.932 901.375L944.095 895.002L910.003 860L937.013 879.625L962.101 885.391L983.345 913.717V953.574L913.241 971.075Z" fill="url(#paint6_linear)" /> <path d="M920.257 948.906L994.532 879.936L1048.55 849.189L1106.07 790.106L1117.04 788.297L1131.99 800.958L1181.06 746.337L1203.85 731.747L1227.61 701H1233.39L1298.63 798.426L1312.37 803.852L1366.99 874.992L1391.59 884.156L1430.54 911.888L920.257 948.906Z" fill="url(#paint7_linear)" /> <path d="M1131.52 801.176L1112.84 821.554L1118.86 806.602H1114.04L1105.6 790.324L1116.57 788.516L1131.52 801.176Z" fill="url(#paint8_linear)" /> <path d="M1203.39 731.969L1225.94 764.283L1209.66 763.68L1180.6 746.559L1203.39 731.969Z" fill="url(#paint9_linear)" /> <path d="M1288.64 834.93L1221.48 912.099H1375.45L1354.59 874.48L1340.73 888.105L1291.17 803.822L1311.91 804.063L1298.16 798.637L1232.93 701.211H1227.14L1223.52 705.913L1275.25 788.508L1251.26 811.418L1288.64 834.93Z" fill="url(#paint10_linear)" /> <path d="M1391.13 884.371L1383.41 893.053L1400.89 912.104H1430.07L1391.13 884.371Z" fill="url(#paint11_linear)" /> <path d="M1201.34 912.108L1226.66 874.488L1156.85 912.108H1201.34Z" fill="url(#paint12_linear)" /> <path d="M570 1082C570 1082 858.781 902.457 1339.64 902.457C1488 902.457 1636 984.998 1636 984.998L1776 1082H698.896H570Z" fill="#171F3C" /> <path d="M1287 914L1302.5 871L1318 914H1287Z" fill="#171F3C" /> <path d="M1272 921L1288 878L1304 921H1272Z" fill="#171F3C" /> <path d="M1151 934L1167.5 889L1184 934H1151Z" fill="#171F3C" /> <path d="M1130 922L1146.5 877L1163 922H1130Z" fill="#171F3C" /> <path d="M1221 914L1236.5 871L1252 914H1221Z" fill="#171F3C" /> <path d="M1247 913L1268.45 854L1290 913H1247Z" fill="#171F3C" /> <path d="M1312 913L1333.55 854L1355 913H1312Z" fill="#171F3C" /> <path d="M1368 919L1389.55 860L1411 919H1368Z" fill="#171F3C" /> <path d="M1351 916L1363.53 882L1376 916H1351Z" fill="#171F3C" /> <path d="M1059 948L1076 901L1093 948H1059Z" fill="#171F3C" /> <path d="M1031 939L1049.45 888L1068 939H1031Z" fill="#171F3C" /> <path d="M1004 934L1023.05 883L1042 934H1004Z" fill="#171F3C" /> <path d="M964 965L982.948 914L1002 965H964Z" fill="#171F3C" /> <path d="M872 969L889 923L906 969H872Z" fill="#171F3C" /> <path d="M828 989L845 942L862 989H828Z" fill="#171F3C" /> <path d="M849 994L866 948L883 994H849Z" fill="#171F3C" /> <path d="M783 1001L800 955L817 1001H783Z" fill="#171F3C" /> <path d="M632.103 1064.51L647.768 1021.63L663.546 1064.51H632.103Z" fill="#171F3C" /> <path d="M590.826 1082L614.723 1017.17L638.505 1082H590.826Z" fill="#171F3C" /> <path d="M167.34 821.649L196.94 777.191L238.289 772.814L274.339 734H289.312L301.405 747.591H310.274L365.559 818.194L384.793 827.754H418.425L435.932 833.973H446.182C446.182 833.973 493.059 887.185 495.708 887.876C498.357 888.682 542.815 902.273 542.815 902.273L549.15 915.173L581.054 931.413L629.198 967.463L809.449 1038.53H565.39L31.6621 940.627L71.1676 884.305L115.971 861.961L149.718 826.487L167.34 821.649Z" fill="url(#paint13_linear)" /> <path d="M285.856 734L360.491 837.313L371.778 837.544L393.201 857.815L410.247 850.789L449.753 851.25L499.048 898.702L495.593 887.876L446.182 833.973H435.931H417.388L418.425 827.754H384.793L365.443 818.194L310.274 747.591H301.29L289.312 734H285.856Z" fill="url(#paint14_linear)" /> <path d="M206.27 827.293L196.825 777.191L167.34 821.65L163.078 826.832L149.718 826.487L115.971 861.961L103.417 884.536L71.1677 884.306L31.6621 940.512H148.451L171.947 899.163L118.044 923.35L109.982 915.634L115.741 902.503L183.81 870.139L193.485 851.595H162.733L202.239 834.895" fill="url(#paint15_linear)" /> <path d="M162 934.546L207.8 896.256L241.535 877.665L267.636 851.564H276.378L313.067 890.715L323.163 892.562L382.137 846.516L402.328 823H424.244L464.75 886.283L573.217 987.364L162 934.546Z" fill="url(#paint16_linear)" /> <path d="M464.75 886.283L424.244 823H415.502L429.784 847.747H416.364L432.37 868.431L430.646 849.347L454.162 890.223H428.061L468.69 973.944L573.218 987.364L464.75 886.283Z" fill="url(#paint17_linear)" /> <path d="M323.162 892.561L294.968 912.876V880.988L282.287 867.445H267.759L276.377 851.562L313.067 890.714L323.162 892.561Z" fill="url(#paint18_linear)" /> <path d="M362.069 924.942V899.949L327.842 924.942H362.069Z" fill="url(#paint19_linear)" /> <path d="M840.628 1029.51C840.628 1029.51 617.782 1019.29 472.871 945.915C327.96 872.536 166.92 847.173 19.4238 945.792C19.4238 998.733 19.4238 1029.51 19.4238 1029.51H840.628Z" fill="#171F3B" /> <path d="M577 997L593.964 950L611 997H577Z" fill="#171F3B" /> <path d="M547 1006L564.5 959L582 1006H547Z" fill="#171F3B" /> <path d="M132 897L149.5 849L167 897H132Z" fill="#171F3B" /> <path d="M-10 954L21.5511 868L53 954H-10Z" fill="#171F3B" /> <path d="M30 957L53.9497 891L78 957H30Z" fill="#171F3B" /> <path d="M161 886L179 837L197 886H161Z" fill="#171F3B" /> <path d="M177.258 917.341L201.583 852.168L225.909 917.341H177.258Z" fill="#171F3B" /> <path d="M375 933L395.5 878L416 933H375Z" fill="#171F3B" /> <path d="M312 918L330 870L348 918H312Z" fill="#171F3B" /> <path d="M335 907L352.5 859L370 907H335Z" fill="#171F3B" /> <path d="M399 955L419 900L439 955H399Z" fill="#171F3B" /> <path d="M604 1001L618.038 964L632 1001H604Z" fill="#171F3B" /> <path d="M755 1033.13L766.884 1001L778.866 1033.13H755Z" fill="#171F3B" /> <path d="M690 1019.11L700.513 998L711.112 1019.11H690Z" fill="#171F3B" /> <path d="M681 1020L688.967 1004L697 1020H681Z" fill="#171F3B" /> <path d="M515 980.112L525.513 959L536.112 980.112H515Z" fill="#171F3B" /> <path d="M499 972L511.449 947L524 972H499Z" fill="#171F3B" /> <path d="M814.302 1033L824.815 1004.54L835.415 1033H814.302Z" fill="#171F3B" /> <path d="M783.092 1033L800.461 987.105L817.973 1033H783.092Z" fill="#171F3B" /> <rect y="1028" width="1440" height="151" fill="#171F3B" /> <rect y="941" width="75" height="168" fill="#171F3B" /> <path d="M1051 764H1113C1107.68 763.678 1103.84 762.424 1101.25 761.296C1098.11 759.935 1096.21 758.485 1092.33 757.966C1090.26 757.679 1087.89 757.59 1086.62 757.608C1083.28 757.626 1081.39 759.219 1079.64 759.112C1075.81 758.843 1076.88 756.569 1073.73 755.638C1070.68 754.743 1068.35 754.582 1064.08 756.533C1059.94 758.396 1059.9 761.189 1054.58 762.747C1053.85 762.961 1053.13 763.194 1052.42 763.463L1051 764Z" fill="#353F6C" /> <path d="M1387.78 692.562C1389.55 692.289 1391.38 692.016 1393.15 691.634C1424.39 685.194 1433.89 680.446 1441.13 675.644C1443.06 674.334 1447.03 671.496 1453.08 670.514C1461.53 669.149 1466.17 672.751 1475.24 673.679C1479.21 674.116 1487.81 674.388 1496.57 670.514C1501.32 668.44 1501.84 666.966 1506.85 665.493C1509.19 664.783 1515.24 663.092 1522.18 664.62C1528.02 665.929 1527.6 668.003 1533.34 669.368C1538.97 670.677 1539.55 668.713 1549.25 669.204C1558.58 669.695 1562.49 671.714 1563.85 672.533C1565.99 673.788 1565.78 674.17 1568.96 676.571C1571.67 678.591 1576.58 682.247 1582.05 683.939C1588.15 685.795 1588.68 683.23 1599.47 684.266C1602.18 684.539 1606.98 685.031 1612.72 686.886C1618.61 688.796 1618.98 689.942 1623.88 691.088C1628.1 692.071 1631.55 692.016 1636.55 691.961C1643.12 691.852 1645.05 691.197 1648.65 691.088C1653.24 690.925 1659.81 691.743 1668 696H1364L1387.78 692.562Z" fill="#353F6C" /> </g> <defs> <linearGradient id="paint0_linear" x1="718.08" y1="0" x2="718.08" y2="1035.8" gradientUnits="userSpaceOnUse"> <stop offset="0.03125" stop-color="#263163" /> <stop offset="0.486095" stop-color="#263163" /> <stop offset="1" stop-color="#151B38" /> </linearGradient> <linearGradient id="paint1_linear" x1="1442.97" y1="772" x2="1398.34" y2="875.481" gradientUnits="userSpaceOnUse" > <stop stop-color="#323E70" /> <stop offset="1" stop-color="#171F3B" /> </linearGradient> <linearGradient id="paint2_linear" x1="1451.97" y1="769.5" x2="1443.9" y2="909.996" gradientUnits="userSpaceOnUse" > <stop offset="0.0891991" stop-color="#5E6A9E" /> <stop offset="1" stop-color="#5E6A9E" stop-opacity="0" /> </linearGradient> <linearGradient id="paint3_linear" x1="-9.10928" y1="812" x2="31.2708" y2="911.659" gradientUnits="userSpaceOnUse" > <stop stop-color="#323E70" /> <stop offset="1" stop-color="#1C2342" /> </linearGradient> <linearGradient id="paint4_linear" x1="9.00831" y1="799.229" x2="33.9631" y2="906.728" gradientUnits="userSpaceOnUse" > <stop offset="0.0891991" stop-color="#576396" /> <stop offset="1" stop-color="#546094" stop-opacity="0" /> </linearGradient> <linearGradient id="paint5_linear" x1="868.5" y1="887.5" x2="927.558" y2="940.159" gradientUnits="userSpaceOnUse" > <stop stop-color="#323E70" /> <stop offset="1" stop-color="#171F3B" /> </linearGradient> <linearGradient id="paint6_linear" x1="885" y1="746" x2="947" y2="923" gradientUnits="userSpaceOnUse"> <stop stop-color="#707CB1" /> <stop offset="1" stop-color="#5E6A9E" stop-opacity="0" /> </linearGradient> <linearGradient id="paint7_linear" x1="1184" y1="764.5" x2="1217.26" y2="907.421" gradientUnits="userSpaceOnUse" > <stop stop-color="#323D6F" /> <stop offset="1" stop-color="#171F3B" /> </linearGradient> <linearGradient id="paint8_linear" x1="1118.59" y1="783.087" x2="1118.59" y2="822.511" gradientUnits="userSpaceOnUse" > <stop offset="0.0891991" stop-color="#5E6A9E" /> <stop offset="1" stop-color="#5E6A9E" stop-opacity="0" /> </linearGradient> <linearGradient id="paint9_linear" x1="1176.35" y1="748.127" x2="1226.27" y2="748.127" gradientUnits="userSpaceOnUse" > <stop offset="0.0891991" stop-color="#687096" /> <stop offset="1" stop-color="#687096" stop-opacity="0" /> </linearGradient> <linearGradient id="paint10_linear" x1="1174.25" y1="783.258" x2="1372.66" y2="870.664" gradientUnits="userSpaceOnUse" > <stop offset="0.0891991" stop-color="#687096" /> <stop offset="1" stop-color="#5E6A9E" stop-opacity="0" /> </linearGradient> <linearGradient id="paint11_linear" x1="1384.04" y1="895.4" x2="1429.43" y2="906.136" gradientUnits="userSpaceOnUse" > <stop offset="0.0891991" stop-color="#5E6A9E" /> <stop offset="1" stop-color="#5E6A9E" stop-opacity="0" /> </linearGradient> <linearGradient id="paint12_linear" x1="1168.51" y1="916.35" x2="1271.87" y2="863.891" gradientUnits="userSpaceOnUse" > <stop offset="0.0891991" stop-color="#687096" /> <stop offset="1" stop-color="#5E6A9E" stop-opacity="0" /> </linearGradient> <linearGradient id="paint13_linear" x1="343.5" y1="750.5" x2="272.787" y2="931.199" gradientUnits="userSpaceOnUse" > <stop stop-color="#344074" /> <stop offset="1" stop-color="#1C2342" /> </linearGradient> <linearGradient id="paint14_linear" x1="359.852" y1="686.495" x2="411.765" y2="893.202" gradientUnits="userSpaceOnUse" > <stop offset="0.0891991" stop-color="#5A669A" /> <stop offset="1" stop-color="#5A669A" stop-opacity="0" /> </linearGradient> <linearGradient id="paint15_linear" x1="259.709" y1="830.767" x2="143.802" y2="868.176" gradientUnits="userSpaceOnUse" > <stop offset="0.0891991" stop-color="#556094" /> <stop offset="1" stop-color="#546094" stop-opacity="0" /> </linearGradient> <linearGradient id="paint16_linear" x1="367.609" y1="823" x2="371.849" y2="940.623" gradientUnits="userSpaceOnUse" > <stop stop-color="#344074" /> <stop offset="1" stop-color="#1C2342" /> </linearGradient> <linearGradient id="paint17_linear" x1="380.527" y1="869.441" x2="568.778" y2="952.409" gradientUnits="userSpaceOnUse" > <stop stop-color="#5E6A9E" /> <stop offset="1" stop-color="#5E6A9E" stop-opacity="0" /> </linearGradient> <linearGradient id="paint18_linear" x1="283.32" y1="869.046" x2="309.661" y2="903.502" gradientUnits="userSpaceOnUse" > <stop stop-color="#546094" /> <stop offset="1" stop-color="#546093" stop-opacity="0" /> </linearGradient> <linearGradient id="paint19_linear" x1="333.822" y1="926.784" x2="388.302" y2="899.133" gradientUnits="userSpaceOnUse" > <stop offset="0.0891991" stop-color="#687096" /> <stop offset="1" stop-color="#687096" stop-opacity="0" /> </linearGradient> <clipPath id="clip0"> <rect width="1440" height="1152" fill="white" /> </clipPath> </defs> </svg>
3,769
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox/MailboxContainer.tsx
import { RefObject, memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useHistory, useLocation } from 'react-router-dom'; import { c } from 'ttag'; import { Commander, CommanderItemInterface, DrawerSidebar, ErrorBoundary, PrivateMainArea, QuickSettingsAppButton, useCalendarUserSettings, useCalendars, useFolders, useItemsSelection, useLabels, useModalState, } from '@proton/components'; import DrawerVisibilityButton from '@proton/components/components/drawer/DrawerVisibilityButton'; import { useCalendarsInfoCoreListener } from '@proton/components/containers/eventManager/calendar/useCalendarsInfoListener'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { hasBit } from '@proton/shared/lib/helpers/bitset'; import { getSearchParams } from '@proton/shared/lib/helpers/url'; import { MailSettings, UserSettings } from '@proton/shared/lib/interfaces'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { SHOW_MOVED, VIEW_MODE } from '@proton/shared/lib/mail/mailSettings'; import { isDraft } from '@proton/shared/lib/mail/messages'; import clsx from '@proton/utils/clsx'; import SpotlightEmailForwarding from 'proton-mail/components/header/SpotlightEmailForwarding'; import useMailDrawer from 'proton-mail/hooks/drawer/useMailDrawer'; import ConversationView from '../../components/conversation/ConversationView'; import MailHeader from '../../components/header/MailHeader'; import List from '../../components/list/List'; import useScrollToTop from '../../components/list/useScrollToTop'; import MessageOnlyView from '../../components/message/MessageOnlyView'; import { useLabelActionsContext } from '../../components/sidebar/EditLabelContext'; import Toolbar from '../../components/toolbar/Toolbar'; import { LABEL_IDS_TO_HUMAN, MAILTO_PROTOCOL_HANDLER_SEARCH_PARAM, MESSAGE_ACTIONS } from '../../constants'; import { isMessage, isSearch as testIsSearch } from '../../helpers/elements'; import { getFolderName } from '../../helpers/labels'; import { isColumnMode, isConversationMode } from '../../helpers/mailSettings'; import { extractSearchParameters, filterFromUrl, pageFromUrl, setFilterInUrl, setPageInUrl, setParamsInLocation, setSortInUrl, sortFromUrl, } from '../../helpers/mailboxUrl'; import { MARK_AS_STATUS, useMarkAs } from '../../hooks/actions/useMarkAs'; import { usePermanentDelete } from '../../hooks/actions/usePermanentDelete'; import { ComposeTypes } from '../../hooks/composer/useCompose'; import { useApplyEncryptedSearch } from '../../hooks/mailbox/useApplyEncryptedSearch'; import { useElements, useGetElementsFromIDs } from '../../hooks/mailbox/useElements'; import { useMailboxFavicon } from '../../hooks/mailbox/useMailboxFavicon'; import { useMailboxFocus } from '../../hooks/mailbox/useMailboxFocus'; import { useMailboxHotkeys } from '../../hooks/mailbox/useMailboxHotkeys'; import { useMailboxPageTitle } from '../../hooks/mailbox/useMailboxPageTitle'; import useNewEmailNotification from '../../hooks/mailbox/useNewEmailNotification'; import usePreLoadElements from '../../hooks/mailbox/usePreLoadElements'; import { useWelcomeFlag } from '../../hooks/mailbox/useWelcomeFlag'; import { useDeepMemo } from '../../hooks/useDeepMemo'; import { useResizeMessageView } from '../../hooks/useResizeMessageView'; import { selectComposersCount } from '../../logic/composers/composerSelectors'; import { useAppSelector } from '../../logic/store'; import { Filter, SearchParameters, Sort } from '../../models/tools'; import { Breakpoints } from '../../models/utils'; import { useOnCompose, useOnMailTo } from '../ComposeProvider'; import MailboxContainerPlaceholder from './MailboxContainerPlaceholder'; import { MailboxContainerContextProvider } from './MailboxContainerProvider'; interface Props { labelID: string; mailSettings: MailSettings; userSettings: UserSettings; breakpoints: Breakpoints; elementID?: string; messageID?: string; } const MailboxContainer = ({ labelID: inputLabelID, mailSettings, userSettings, breakpoints, elementID, messageID, }: Props) => { const location = useLocation(); const history = useHistory(); const [labels] = useLabels(); const [folders] = useFolders(); const { createLabel } = useLabelActionsContext(); const getElementsFromIDs = useGetElementsFromIDs(); const markAs = useMarkAs(); const listRef = useRef<HTMLDivElement>(null); const forceRowMode = breakpoints.isNarrow || breakpoints.isTablet || breakpoints.isSmallDesktop; const columnModeSetting = isColumnMode(mailSettings); const columnMode = columnModeSetting && !forceRowMode; const columnLayout = columnModeSetting || forceRowMode; const labelIDs = (labels || []).map(({ ID }) => ID); const messageContainerRef = useRef<HTMLElement>(null); const mainAreaRef = useRef<HTMLDivElement>(null); const resizeAreaRef = useRef<HTMLButtonElement>(null); const composersCount = useAppSelector(selectComposersCount); const isComposerOpened = composersCount > 0; const onMailTo = useOnMailTo(); const { drawerSidebarButtons, showDrawerSidebar } = useMailDrawer(); const { enableResize, resetWidth, scrollBarWidth, isResizing } = useResizeMessageView( mainAreaRef, resizeAreaRef, listRef ); const page = pageFromUrl(location); const searchParams = getSearchParams(location.hash); const isConversationContentView = mailSettings.ViewMode === VIEW_MODE.GROUP; const searchParameters = useDeepMemo<SearchParameters>(() => extractSearchParameters(location), [location]); const isSearch = testIsSearch(searchParameters); const sort = useMemo<Sort>(() => sortFromUrl(location, inputLabelID), [searchParams.sort, inputLabelID]); const filter = useMemo<Filter>(() => filterFromUrl(location), [searchParams.filter]); const navigateTo = (labelID: MAILBOX_LABEL_IDS) => { history.push(`/${LABEL_IDS_TO_HUMAN[labelID]}`); }; // Open a composer when the url contains a mailto query useEffect(() => { if (!isSearch && location.hash) { const searchParams = location.hash.substring(1).split('&'); searchParams.forEach((param) => { const pair = param.split('='); if (pair[0] === MAILTO_PROTOCOL_HANDLER_SEARCH_PARAM) { try { onMailTo(decodeURIComponent(pair[1])); } catch (e: any) { console.error(e); } } }); } }, [location.hash, isSearch]); const handlePage = useCallback( (pageNumber: number) => { history.push(setPageInUrl(history.location, pageNumber)); }, [history] ); const handleSort = useCallback((sort: Sort) => history.push(setSortInUrl(history.location, sort)), [history]); const handleFilter = useCallback( (filter: Filter) => history.push(setFilterInUrl(history.location, filter)), [history] ); const [isMessageOpening, setIsMessageOpening] = useState(false); const onMessageLoad = useCallback(() => setIsMessageOpening(true), []); const onMessageReady = useCallback(() => setIsMessageOpening(false), [setIsMessageOpening]); const elementsParams = { conversationMode: isConversationMode(inputLabelID, mailSettings, location), labelID: inputLabelID, page: pageFromUrl(location), sort, filter, search: searchParameters, onPage: handlePage, }; const { labelID, elements, elementIDs, loading, placeholderCount, total } = useElements(elementsParams); const { handleDelete: permanentDelete, modal: deleteModal } = usePermanentDelete(labelID); useApplyEncryptedSearch(elementsParams); const handleBack = useCallback( () => history.push(setParamsInLocation(history.location, { labelID })), [history, labelID] ); const onCompose = useOnCompose(); useMailboxPageTitle(labelID, location); useMailboxFavicon(labelID, location); useScrollToTop(listRef as RefObject<HTMLElement>, [page, labelID, sort, filter, searchParameters]); const { checkedIDs, selectedIDs, handleCheck, handleCheckAll, handleCheckOne, handleCheckOnlyOne, handleCheckRange, } = useItemsSelection(elementID, elementIDs, [elementID, labelID]); useNewEmailNotification(() => handleCheckAll(false)); // Launch two calendar-specific API calls here to boost calendar widget performance useCalendars(); useCalendarUserSettings(); // listen to calendar "core" updates useCalendarsInfoCoreListener(); const elementsLength = loading ? placeholderCount : elements.length; const showList = columnMode || !elementID; const showContentPanel = (columnMode && !!elementsLength) || !!elementID; const showPlaceholder = !breakpoints.isNarrow && (!elementID || !!checkedIDs.length); const showContentView = showContentPanel && !!elementID; const elementIDForList = checkedIDs.length ? undefined : elementID; const [commanderModalProps, showCommander, commanderRender] = useModalState(); const { focusIndex, getFocusedId, setFocusIndex, handleFocus, focusOnLastMessage } = useMailboxFocus({ elementIDs, page, showList, listRef, labelID, isComposerOpened, }); const welcomeFlag = useWelcomeFlag([labelID, selectedIDs.length]); const handleElement = useCallback( (elementID: string | undefined, preventComposer = false) => { const fetchElementThenCompose = async () => { // Using the getter to prevent having elements in dependency of the callback const [element] = getElementsFromIDs([elementID || '']); if (isMessage(element) && isDraft(element) && !preventComposer) { void onCompose({ type: ComposeTypes.existingDraft, existingDraft: { localID: element.ID as string, data: element as Message }, fromUndo: false, }); } if (isConversationContentView && isMessage(element)) { onMessageLoad(); history.push( setParamsInLocation(history.location, { labelID, elementID: (element as Message).ConversationID, messageID: element.ID, }) ); } else { onMessageLoad(); history.push(setParamsInLocation(history.location, { labelID, elementID: element.ID })); } handleCheckAll(false); }; void fetchElementThenCompose(); }, [onCompose, isConversationContentView, labelID, history] ); const handleMarkAs = useCallback( async (status: MARK_AS_STATUS) => { const isUnread = status === MARK_AS_STATUS.UNREAD; const elements = getElementsFromIDs(selectedIDs); if (isUnread) { handleBack(); } await markAs(elements, labelID, status); }, [selectedIDs, labelID, handleBack] ); const handleDelete = useCallback(async () => { await permanentDelete(selectedIDs); }, [selectedIDs, permanentDelete]); const conversationMode = isConversationMode(labelID, mailSettings, location); usePreLoadElements({ elements, labelID, loading }); const { elementRef, labelDropdownToggleRef, moveDropdownToggleRef, moveScheduledModal, moveSnoozedModal, moveAllModal, moveToSpamModal, permanentDeleteModal, moveToFolder, } = useMailboxHotkeys( { labelID, elementID, messageID, elementIDs, checkedIDs, selectedIDs, focusIndex, columnLayout, isMessageOpening, location, }, { focusOnLastMessage, getFocusedId, handleBack, handleCheck, handleCheckOnlyOne, handleCheckRange, handleElement, handleFilter, handleCheckAll, setFocusIndex, showCommander, } ); const handleMove = useCallback( async (LabelID: string) => { const folderName = getFolderName(LabelID, folders); const elements = getElementsFromIDs(selectedIDs); await moveToFolder(elements, LabelID, folderName, labelID, false); if (selectedIDs.includes(elementID || '')) { handleBack(); } }, [selectedIDs, elementID, labelID, labelIDs, folders, handleBack] ); const toolbar = (toolbarInHeader?: boolean) => { return ( <Toolbar labelID={labelID} elementID={elementID} messageID={messageID} selectedIDs={selectedIDs} checkedIDs={checkedIDs} elementIDs={elementIDs} columnMode={columnMode} conversationMode={conversationMode} breakpoints={breakpoints} onCheck={handleCheck} page={page} total={total} isSearch={isSearch} onPage={handlePage} onBack={handleBack} onElement={handleElement} onMarkAs={handleMarkAs} onMove={handleMove} onDelete={handleDelete} labelDropdownToggleRef={labelDropdownToggleRef} moveDropdownToggleRef={moveDropdownToggleRef} bordered sort={sort} onSort={handleSort} onFilter={handleFilter} filter={filter} mailSettings={mailSettings} toolbarInHeader={toolbarInHeader} /> ); }; const commanderList = useMemo<CommanderItemInterface[]>( () => [ { icon: 'envelope', label: c('Commander action').t`New message`, value: 'compose', action: () => onCompose({ type: ComposeTypes.newMessage, action: MESSAGE_ACTIONS.NEW }), shortcuts: ['N'], }, { icon: 'tag', label: c('Commander action').t`Create a new label`, value: 'create-label', action: () => createLabel('label'), }, { icon: 'folder', label: c('Commander action').t`Create a new folder`, value: 'create-folder', action: () => createLabel('folder'), }, { icon: 'envelope-magnifying-glass', label: c('Commander action').t`Search`, value: 'search', action: () => { const button = document.querySelector('[data-shorcut-target="searchbox-button"]') as HTMLElement; button?.dispatchEvent( new MouseEvent('click', { view: window, bubbles: true, cancelable: false, }) ); }, shortcuts: ['/'], }, { icon: 'inbox', label: c('Commander action').t`Go to Inbox`, value: 'inbox', action: () => navigateTo(MAILBOX_LABEL_IDS.INBOX), shortcuts: ['G', 'I'], }, { icon: 'file-lines', label: c('Commander action').t`Go to Drafts`, value: 'drafts', action: () => navigateTo( hasBit(mailSettings.ShowMoved, SHOW_MOVED.DRAFTS) ? MAILBOX_LABEL_IDS.ALL_DRAFTS : MAILBOX_LABEL_IDS.DRAFTS ), shortcuts: ['G', 'D'], }, { icon: 'paper-plane-horizontal', label: c('Commander action').t`Go to Sent`, value: 'sent', action: () => navigateTo( hasBit(mailSettings.ShowMoved, SHOW_MOVED.SENT) ? MAILBOX_LABEL_IDS.ALL_SENT : MAILBOX_LABEL_IDS.SENT ), shortcuts: ['G', 'E'], }, { icon: 'archive-box', label: c('Commander action').t`Go to Archive`, value: 'archive', action: () => navigateTo(MAILBOX_LABEL_IDS.ARCHIVE), shortcuts: ['G', 'A'], }, { icon: 'star', label: c('Commander action').t`Go to Starred`, value: 'starred', action: () => navigateTo(MAILBOX_LABEL_IDS.STARRED), shortcuts: ['G', '*'], }, { icon: 'fire', label: c('Commander action').t`Go to Spam`, value: 'spam', action: () => navigateTo(MAILBOX_LABEL_IDS.SPAM), shortcuts: ['G', 'S'], }, { icon: 'trash', label: c('Commander action').t`Go to Trash`, value: 'trash', action: () => navigateTo(MAILBOX_LABEL_IDS.TRASH), shortcuts: ['G', 'T'], }, ], [] ); const canShowDrawer = drawerSidebarButtons.length > 0; return ( <MailboxContainerContextProvider isResizing={isResizing} containerRef={messageContainerRef} elementID={elementID} > <div ref={elementRef} tabIndex={-1} className="flex-item-fluid flex flex-column flex-nowrap outline-none" data-testid="mailbox" > <MailHeader breakpoints={breakpoints} elementID={elementID} selectedIDs={selectedIDs} labelID={labelID} toolbar={toolbar(true)} settingsButton={ <SpotlightEmailForwarding> <QuickSettingsAppButton /> </SpotlightEmailForwarding> } /> <PrivateMainArea className="flex" hasToolbar hasRowMode={!showContentPanel} ref={mainAreaRef} drawerSidebar={<DrawerSidebar buttons={drawerSidebarButtons} />} drawerVisibilityButton={canShowDrawer ? <DrawerVisibilityButton /> : undefined} mainBordered={canShowDrawer && !!showDrawerSidebar} > <List ref={listRef} show={showList} conversationMode={conversationMode} labelID={labelID} loading={loading} placeholderCount={placeholderCount} columnLayout={columnLayout} elementID={elementIDForList} elements={elements} checkedIDs={checkedIDs} onCheck={handleCheck} onClick={handleElement} isSearch={isSearch} breakpoints={breakpoints} page={page} total={total} onPage={handlePage} onFocus={handleFocus} onCheckOne={handleCheckOne} filter={filter} resizeAreaRef={resizeAreaRef} enableResize={enableResize} resetWidth={resetWidth} showContentPanel={showContentPanel} scrollBarWidth={scrollBarWidth} onMarkAs={handleMarkAs} onDelete={handleDelete} onMove={handleMove} onBack={handleBack} userSettings={userSettings} toolbar={toolbar()} /> <ErrorBoundary> <section className={clsx([ 'view-column-detail flex flex-column flex-item-fluid flex-nowrap relative', !showContentPanel && 'hidden', showContentView ? 'no-scroll' : 'scroll-if-needed', ])} > {showPlaceholder && ( <MailboxContainerPlaceholder showPlaceholder={showContentPanel} welcomeFlag={welcomeFlag} labelID={labelID} checkedIDs={checkedIDs} handleCheckAll={handleCheckAll} /> )} {showContentView && (isConversationContentView ? ( <ConversationView hidden={showPlaceholder} labelID={labelID} messageID={messageID} mailSettings={mailSettings} conversationID={elementID as string} onBack={handleBack} breakpoints={breakpoints} onMessageReady={onMessageReady} columnLayout={columnLayout} isComposerOpened={isComposerOpened} containerRef={messageContainerRef} elementIDs={elementIDs} loadingElements={loading} conversationMode={conversationMode} /> ) : ( <MessageOnlyView hidden={showPlaceholder} labelID={labelID} elementIDs={elementIDs} loadingElements={loading} mailSettings={mailSettings} messageID={elementID as string} onBack={handleBack} breakpoints={breakpoints} onMessageReady={onMessageReady} columnLayout={columnLayout} isComposerOpened={isComposerOpened} /> ))} </section> </ErrorBoundary> </PrivateMainArea> </div> {commanderRender ? <Commander list={commanderList} {...commanderModalProps} /> : null} {permanentDeleteModal} {moveScheduledModal} {moveSnoozedModal} {moveAllModal} {moveToSpamModal} {deleteModal} </MailboxContainerContextProvider> ); }; export default memo(MailboxContainer);
3,770
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox/MailboxContainerPlaceholder.tsx
import { Cancellable } from '@proton/components/hooks/useHandler'; import { CHECKLIST_DISPLAY_TYPE } from '@proton/shared/lib/interfaces'; import UsersOnboardingChecklist from '../../components/checklist/UsersOnboardingChecklist'; import PlaceholderView from '../../components/view/PlaceholderView'; import { useGetStartedChecklist } from '../onboardingChecklist/provider/GetStartedChecklistProvider'; interface Props { showPlaceholder: boolean; welcomeFlag: boolean; labelID: string; checkedIDs: string[]; handleCheckAll: ((check: boolean) => void) & Cancellable; } const MailboxContainerPlaceholder = ({ showPlaceholder, welcomeFlag, labelID, checkedIDs, handleCheckAll }: Props) => { const { loading: loadingChecklist, displayState } = useGetStartedChecklist(); if (loadingChecklist) { return null; } if (showPlaceholder && displayState === CHECKLIST_DISPLAY_TYPE.FULL) { return <UsersOnboardingChecklist />; } if (showPlaceholder) { return ( <PlaceholderView welcomeFlag={welcomeFlag} labelID={labelID} checkedIDs={checkedIDs} onCheckAll={handleCheckAll} /> ); } return null; }; export default MailboxContainerPlaceholder;
3,771
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox/MailboxContainerProvider.tsx
import { RefObject, createContext, useContext, useEffect, useState } from 'react'; import debounce from '@proton/utils/debounce'; interface ContextProps { /** * Related to column layout when user is resizing MessageView. */ isResizing: boolean; /** * MessageView VerticalScroll offsetTop */ containerScrollTop: number; } interface ProviderProps { children: React.ReactNode; /** * Related to column layout when user is resizing MessageView. */ isResizing: boolean; /** * MessageView VerticalScroll offsetTop * Pass null value for tests */ containerRef: RefObject<HTMLElement> | null; elementID: string | undefined; } const MailboxContainerContext = createContext<ContextProps | undefined>(undefined); export const MailboxContainerContextProvider = ({ children, isResizing, containerRef, elementID }: ProviderProps) => { /** * This value is set in order to trigger a rerender after containerRef scroll. * This helps the tooltip to keep up to date x/y coords related to the iframe */ const [containerScrollTop, setContainerScrollTop] = useState(0); useEffect(() => { const containerEl = containerRef && containerRef?.current; if (!containerEl) { return; } const onScroll = debounce(() => { setContainerScrollTop(containerEl.scrollTop); }, 100); containerEl.addEventListener('scroll', onScroll); return () => { containerEl.removeEventListener('scroll', onScroll); setContainerScrollTop(0); }; }, [elementID]); return ( <MailboxContainerContext.Provider value={{ isResizing, containerScrollTop }}> {children} </MailboxContainerContext.Provider> ); }; export const useMailboxContainerContext = (): ContextProps => { const context = useContext(MailboxContainerContext); if (context === undefined) { throw new Error('useResizeMessageViewContext hook should be used inside MailboxContainerContextProvider'); } return { isResizing: context.isResizing, containerScrollTop: context.containerScrollTop, }; };
3,772
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox/tests/Mailbox.elements.test.tsx
import { fireEvent } from '@testing-library/react'; import { queryConversations } from '@proton/shared/lib/api/conversations'; import { MESSAGE_FLAGS } from '@proton/shared/lib/mail/constants'; import { ELEMENTS_CACHE_REQUEST_SIZE, PAGE_SIZE } from '../../../constants'; import { addApiMock, api, apiMocks, clearAll, getHistory, tick, waitForSpyCall } from '../../../helpers/test/helper'; import { Element } from '../../../models/element'; import { Sort } from '../../../models/tools'; import { getElements, props, sendEvent, setup } from './Mailbox.test.helpers'; describe('Mailbox element list', () => { const { labelID } = props; const element1 = { ID: 'id1', Labels: [{ ID: labelID, ContextTime: 1 }], LabelIDs: [labelID], Size: 20, NumUnread: 1, NumMessages: 1, } as Element; const element2 = { ID: 'id2', Labels: [{ ID: labelID, ContextTime: 2 }], LabelIDs: [labelID], Size: 10, NumUnread: 1, NumMessages: 1, } as Element; const element3 = { ID: 'id3', Labels: [{ ID: 'otherLabelID', ContextTime: 3 }], LabelIDs: ['otherLabelID'], NumUnread: 0, NumMessages: 1, } as Element; beforeEach(clearAll); describe('elements memo', () => { it('should order by label context time', async () => { const conversations = [element1, element2]; const { getItems } = await setup({ conversations }); const items = getItems(); expect(items.length).toBe(2); expect(items[0].getAttribute('data-element-id')).toBe(conversations[1].ID); expect(items[1].getAttribute('data-element-id')).toBe(conversations[0].ID); }); it('should filter message with the right label', async () => { const { getItems } = await setup({ page: 0, totalConversations: 2, conversations: [element1, element2, element3], }); const items = getItems(); expect(items.length).toBe(2); }); it('should limit to the page size', async () => { const total = PAGE_SIZE + 5; const { getItems } = await setup({ conversations: getElements(total), page: 0, totalConversations: total, }); const items = getItems(); expect(items.length).toBe(PAGE_SIZE); }); it('should returns the current page', async () => { const page1 = 0; const page2 = 1; const total = PAGE_SIZE + 2; const conversations = getElements(total); const { rerender, getItems } = await setup({ conversations, totalConversations: total, page: page1 }); let items = getItems(); expect(items.length).toBe(PAGE_SIZE); await rerender({ page: page2 }); items = getItems(); expect(items.length).toBe(2); }); it('should returns elements sorted', async () => { const conversations = [element1, element2]; const sort1: Sort = { sort: 'Size', desc: false }; const sort2: Sort = { sort: 'Size', desc: true }; const { rerender, getItems } = await setup({ conversations, sort: sort1 }); let items = getItems(); expect(items.length).toBe(2); expect(items[0].getAttribute('data-element-id')).toBe(conversations[1].ID); expect(items[1].getAttribute('data-element-id')).toBe(conversations[0].ID); await rerender({ sort: sort2 }); items = getItems(); expect(items.length).toBe(2); expect(items[0].getAttribute('data-element-id')).toBe(conversations[0].ID); expect(items[1].getAttribute('data-element-id')).toBe(conversations[1].ID); }); it('should fallback sorting on Order field', async () => { const conversations = [ { ID: 'id1', Labels: [{ ID: labelID, ContextTime: 1 }], LabelIDs: [labelID], Size: 20, Order: 3 }, { ID: 'id2', Labels: [{ ID: labelID, ContextTime: 1 }], LabelIDs: [labelID], Size: 20, Order: 2 }, { ID: 'id3', Labels: [{ ID: labelID, ContextTime: 1 }], LabelIDs: [labelID], Size: 20, Order: 4 }, { ID: 'id4', Labels: [{ ID: labelID, ContextTime: 1 }], LabelIDs: [labelID], Size: 20, Order: 1 }, ]; const expectOrder = (items: HTMLElement[], order: number[]) => { expect(items.length).toBe(order.length); for (const [i, pos] of order.entries()) { expect(items[i].getAttribute('data-element-id')).toBe(conversations[pos].ID); } }; const { rerender, getItems } = await setup({ conversations }); expectOrder(getItems(), [2, 0, 1, 3]); await rerender({ sort: { sort: 'Time', desc: false } }); expectOrder(getItems(), [3, 1, 0, 2]); await rerender({ sort: { sort: 'Size', desc: true } }); expectOrder(getItems(), [0, 1, 2, 3]); await rerender({ sort: { sort: 'Size', desc: false } }); expectOrder(getItems(), [0, 1, 2, 3]); }); }); describe('request effect', () => { it('should send request for conversations current page', async () => { const page = 0; const total = PAGE_SIZE + 3; const expectedRequest = { ...queryConversations({ LabelID: labelID, Sort: 'Time', Limit: ELEMENTS_CACHE_REQUEST_SIZE, PageSize: PAGE_SIZE, } as any), signal: new AbortController().signal, }; const { getItems } = await setup({ conversations: getElements(PAGE_SIZE), page, totalConversations: total, }); expect(api).toHaveBeenCalledWith(expectedRequest); const items = getItems(); expect(items.length).toBe(PAGE_SIZE); }); }); describe('filter unread', () => { it('should only show unread conversations if filter is on', async () => { const conversations = [element1, element2, element3]; const { getItems } = await setup({ conversations, filter: { Unread: 1 }, totalConversations: 2 }); const items = getItems(); expect(items.length).toBe(2); }); it('should keep in view the conversations when opened while filter is on', async () => { const conversations = [element1, element2, element3]; const message = { ID: 'messageID1', AddressID: 'AddressID', Sender: {}, ConversationID: element1.ID, Flag: MESSAGE_FLAGS.FLAG_RECEIVED, LabelIDs: [labelID], Attachments: [], }; const { rerender, getItems } = await setup({ conversations, filter: { Unread: 1 }, totalConversations: 2, }); // A bit complex but the point is to simulate opening the conversation addApiMock(`mail/v4/conversations/${element1.ID}`, () => ({ Conversation: element1, Messages: [message], })); addApiMock(`mail/v4/messages/messageID1`, () => ({ Message: message })); addApiMock(`mail/v4/messages/read`, () => ({ UndoToken: { Token: 'Token' } })); await rerender({ elementID: element1.ID }); const items = getItems(); expect(items.length).toBe(2); expect(items[1].classList.contains('read')).toBe(true); expect(items[0].classList.contains('read')).toBe(false); // Needed because of the message images double render await tick(); }); }); describe('page navigation', () => { it('should navigate on the last page when the one asked is too big', async () => { const conversations = getElements(PAGE_SIZE * 1.5); apiMocks['mail/v4/conversations'] = [ { method: 'get', handler: (args: any) => { const page = args.params.Page; if (page === 10) { return { Total: conversations.length, Conversations: [] }; } if (page <= 1) { return { Total: conversations.length, Conversations: conversations.slice(PAGE_SIZE) }; } }, }, ]; // Initialize on page 1 const { rerender, getItems } = await setup({ conversations, page: 0, mockConversations: false }); // Then ask for page 11 await rerender({ page: 10 }); expect(getHistory().location.hash).toBe('#page=2'); await rerender({ page: 1 }); const items = getItems(); expect(items.length).toBe(conversations.length % PAGE_SIZE); }); it('should navigate on the previous one when the current one is emptied', async () => { const conversations = getElements(PAGE_SIZE * 1.5); apiMocks['mail/v4/conversations'] = [ { method: 'get', handler: (args: any) => { const page = args.params.Page; if (page === 0) { return { Total: conversations.length, Conversations: conversations.slice(0, PAGE_SIZE) }; } if (page === 1) { return { Total: conversations.length, Conversations: conversations.slice(PAGE_SIZE) }; } }, }, ]; const labelRequestSpy = jest.fn(() => ({ UndoToken: { Token: 'Token' } })); addApiMock(`mail/v4/conversations/label`, labelRequestSpy, 'put'); const { getByTestId } = await setup({ conversations, page: 1, mockConversations: false }); const selectAll = getByTestId('toolbar:select-all-checkbox'); fireEvent.click(selectAll); const archive = getByTestId('toolbar:movetoarchive'); fireEvent.click(archive); await sendEvent({ ConversationCounts: [{ LabelID: labelID, Total: PAGE_SIZE, Unread: 0 }] }); await waitForSpyCall(labelRequestSpy); expect(getHistory().location.hash).toBe(''); }); it('should show correct number of placeholder navigating on last page', async () => { const conversations = getElements(PAGE_SIZE * 1.5); apiMocks['mail/v4/conversations'] = [ { method: 'get', handler: (args: any) => { const page = args.params.Page; if (page === 0) { return { Total: conversations.length, Conversations: conversations.slice(0, PAGE_SIZE) }; } if (page === 1) { return new Promise(() => {}); } }, }, ]; const { rerender, getItems } = await setup({ conversations, mockConversations: false }); await rerender({ page: 1 }); const items = getItems(); expect(items.length).toBe(conversations.length % PAGE_SIZE); }); }); });
3,773
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox/tests/Mailbox.events.test.tsx
import { act } from '@testing-library/react'; import { EVENT_ACTIONS } from '@proton/shared/lib/constants'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { DEFAULT_PLACEHOLDERS_COUNT, PAGE_SIZE } from '../../../constants'; import { addApiResolver, addToCache, api, clearAll, render } from '../../../helpers/test/helper'; import { Conversation } from '../../../models/conversation'; import { MessageEvent } from '../../../models/event'; import MailboxContainer from '../MailboxContainer'; import { baseApiMocks, expectElements, getElements, getProps, props, sendEvent, setup } from './Mailbox.test.helpers'; jest.setTimeout(20000); describe('Mailbox elements list reacting to events', () => { const { labelID } = props; beforeEach(clearAll); it('should add to the cache a message which is not existing yet', async () => { // Usefull to receive incoming mail or draft without having to reload the list const total = 3; const { getItems } = await setup({ conversations: getElements(total) }); const element = { ID: 'id3', Labels: [{ ID: labelID }], LabelIDs: [labelID] }; await sendEvent({ ConversationCounts: [{ LabelID: labelID, Total: total + 1, Unread: 0 }], Conversations: [{ ID: element.ID, Action: EVENT_ACTIONS.CREATE, Conversation: element as Conversation }], }); expectElements(getItems, total + 1, false); }); it('should not add to the cache a message which is not existing when a search is active', async () => { // When a search is active, all the cache will be shown, we can't accept any updated message // But we will refresh the request each time const total = 3; const search = { keyword: 'test' }; const { getItems } = await setup({ messages: getElements(total), search }); const message = { ID: 'id3', Labels: [{ ID: labelID }], LabelIDs: [labelID] } as any as Message; await sendEvent({ Messages: [{ ID: message.ID, Action: EVENT_ACTIONS.CREATE, Message: message }], }); expectElements(getItems, total, false); expect(api.mock.calls.length).toBe(5); }); it('should not reload the list on an update event if a filter is active', async () => { const total = 3; const filter = { Unread: 1 }; const conversations = getElements(total, labelID, { NumUnread: 1 }); const { getItems } = await setup({ conversations, filter }); const ID = 'id0'; await sendEvent({ Conversations: [{ ID, Action: EVENT_ACTIONS.UPDATE, Conversation: { ID } as Conversation }], }); expectElements(getItems, total, false); expect(api.mock.calls.length).toBe(4); }); it('should not reload the list on an update event if has list from start', async () => { const total = 3; const { getItems } = await setup({ conversations: getElements(total) }); const ID = 'id0'; await sendEvent({ Conversations: [{ ID, Action: EVENT_ACTIONS.UPDATE, Conversation: { ID } as Conversation }], }); expectElements(getItems, total, false); expect(api.mock.calls.length).toBe(4); }); it('should reload the list on an update event if has not list from start', async () => { const page = 2; const total = PAGE_SIZE * 6 + 2; const { getItems } = await setup({ conversations: getElements(PAGE_SIZE), page, totalConversations: total, }); const ID = 'id0'; await sendEvent({ Conversations: [{ ID, Action: EVENT_ACTIONS.UPDATE, Conversation: { ID } as Conversation }], }); expectElements(getItems, PAGE_SIZE, false); expect(api.mock.calls.length).toBe(5); }); it('should reload the list on an delete event if a search is active', async () => { const total = 3; const search = { keyword: 'test' }; const { getItems } = await setup({ messages: getElements(total), search }); const ID = 'id10'; await sendEvent({ Messages: [{ ID, Action: EVENT_ACTIONS.DELETE, Message: { ID } as Message }], }); expectElements(getItems, total, false); expect(api.mock.calls.length).toBe(5); }); it('should not reload the list on count event when a search is active', async () => { // If a search is active, the expected length computation has no meaning const total = 3; const search = { keyword: 'test' }; const messages = getElements(total); await setup({ messages, search }); await sendEvent({ MessageCounts: [{ LabelID: labelID, Total: 10, Unread: 10 }], }); expect(api.mock.calls.length).toBe(4); }); it('should not show the loader if not live cache but params has not changed', async () => { const total = PAGE_SIZE; const search = { keyword: 'test' }; const messages = getElements(total); baseApiMocks(); addToCache('ConversationCounts', []); addToCache('MessageCounts', [{ LabelID: labelID, Total: total }]); addToCache('Calendars', []); const { resolve } = addApiResolver('mail/v4/messages'); const { getAllByTestId } = await render(<MailboxContainer {...getProps({ search })} />); const getItems = () => getAllByTestId('message-item', { exact: false }); // First load pending expectElements(getItems, DEFAULT_PLACEHOLDERS_COUNT, true); await act(async () => { resolve({ Total: total, Messages: messages }); }); // First load finished expectElements(getItems, total, false); const message = messages[0] as Message; await sendEvent({ Messages: [{ ID: message.ID || '', Action: EVENT_ACTIONS.DELETE } as MessageEvent], }); // Event triggered a reload, load is pending but it's hidded to the user expectElements(getItems, total, false); await act(async () => { resolve({ Total: total, Messages: messages }); }); // Load finished expectElements(getItems, total, false); }); it('should show the loader if not live cache and params has changed', async () => { const total = PAGE_SIZE; const search = { keyword: 'test' }; const messages = getElements(total); baseApiMocks(); addToCache('ConversationCounts', []); addToCache('MessageCounts', [{ LabelID: labelID, Total: total }]); let { resolve } = addApiResolver('mail/v4/messages'); const { rerender, getAllByTestId } = await render(<MailboxContainer {...getProps({ search })} />); const getItems = () => getAllByTestId('message-item', { exact: false }); // First load pending expectElements(getItems, DEFAULT_PLACEHOLDERS_COUNT, true); await act(async () => { resolve({ Total: total, Messages: messages }); }); // First load finished expectElements(getItems, total, false); resolve = addApiResolver('mail/v4/messages').resolve; await rerender(<MailboxContainer {...getProps({ search: { keyword: 'changed' } })} />); // Params has changed, cache is reset expectElements(getItems, DEFAULT_PLACEHOLDERS_COUNT, true); await act(async () => { resolve({ Total: total, Messages: messages }); }); // Load finished expectElements(getItems, total, false); }); });
3,774
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox/tests/Mailbox.hotkeys.test.tsx
import { fireEvent } from '@testing-library/react'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { addApiMock, assertCheck, assertFocus, clearAll, getHistory, tick } from '../../../helpers/test/helper'; import MailboxContainer from '../MailboxContainer'; import { SetupArgs, setup as generalSetup, getElements, props } from './Mailbox.test.helpers'; describe('Mailbox hotkeys', () => { const conversations = getElements(4); beforeEach(clearAll); const setup = async ({ conversations: inputConversation, ...rest }: SetupArgs = {}) => { const usedConversations = inputConversation || conversations; const result = await generalSetup({ conversations: usedConversations, ...rest }); const mailbox = result.getByTestId('mailbox'); return { ...result, down: () => fireEvent.keyDown(mailbox, { key: 'ArrowDown' }), up: () => fireEvent.keyDown(mailbox, { key: 'ArrowUp' }), ctrlDown: () => fireEvent.keyDown(mailbox, { key: 'ArrowDown', ctrlKey: true }), ctrlUp: () => fireEvent.keyDown(mailbox, { key: 'ArrowUp', ctrlKey: true }), left: () => fireEvent.keyDown(mailbox, { key: 'ArrowLeft' }), right: () => fireEvent.keyDown(mailbox, { key: 'ArrowRight' }), enter: () => fireEvent.keyDown(mailbox, { key: 'Enter' }), escape: () => fireEvent.keyDown(mailbox, { key: 'Escape' }), j: () => fireEvent.keyDown(mailbox, { key: 'J' }), k: () => fireEvent.keyDown(mailbox, { key: 'K' }), space: () => fireEvent.keyDown(mailbox, { key: ' ' }), shftSpace: () => fireEvent.keyDown(mailbox, { key: ' ', shiftKey: true }), ctrlA: () => fireEvent.keyDown(mailbox, { key: 'A', ctrlKey: true }), x: () => fireEvent.keyDown(mailbox, { key: 'X' }), shftX: () => fireEvent.keyDown(mailbox, { key: 'X', shiftKey: true }), a: () => fireEvent.keyDown(mailbox, { key: 'A' }), i: () => fireEvent.keyDown(mailbox, { key: 'I' }), s: () => fireEvent.keyDown(mailbox, { key: 'S' }), star: () => fireEvent.keyDown(mailbox, { key: '*' }), t: () => fireEvent.keyDown(mailbox, { key: 'T' }), ctrlBackspace: () => fireEvent.keyDown(mailbox, { key: 'Backspace', ctrlKey: true }), }; }; it('should navigate through items with arrows', async () => { const { getItems, down, up, ctrlDown, ctrlUp } = await setup(); const items = getItems(); down(); assertFocus(items[0]); down(); assertFocus(items[1]); ctrlDown(); assertFocus(items[3]); up(); assertFocus(items[2]); ctrlUp(); assertFocus(items[0]); }); it('should navigate left and right', async () => { const TestComponent = (props: any) => { return ( <> <div data-shortcut-target="navigation-link" aria-current="page" tabIndex={-1}> nav test </div> <MailboxContainer {...props} /> <div data-shortcut-target="message-container" tabIndex={-1}> message test </div> </> ); }; const { left, right } = await setup({ Component: TestComponent as any }); const sidebar = document.querySelector('[data-shortcut-target="navigation-link"]'); const message = document.querySelector('[data-shortcut-target="message-container"]'); left(); assertFocus(sidebar); right(); assertFocus(message); }); it('should enter a message and leave', async () => { const { down, enter, escape } = await setup(); const history = getHistory(); down(); enter(); expect(history.length).toBe(3); expect(history.location.pathname).toBe(`/${props.labelID}/${conversations[3].ID}`); escape(); expect(history.length).toBe(4); expect(history.location.pathname).toBe(`/${props.labelID}`); }); it('should navigate no next message with J', async () => { const conversation = conversations[2]; const message = { ID: 'MessageID', Subject: 'test', Body: 'test', Flags: 0 } as Message; addApiMock(`mail/v4/conversations/${conversation.ID}`, () => ({ Conversation: conversation, Messages: [message], })); const { j } = await setup({ conversations, elementID: conversation.ID }); j(); const history = getHistory(); expect(history.length).toBe(3); expect(history.location.pathname).toBe(`/${props.labelID}/${conversations[1].ID}`); }); it('should navigate to previous message with K', async () => { const conversation = conversations[2]; const message = { ID: 'MessageID', Subject: 'test', Body: 'test', Flags: 0 } as Message; addApiMock(`mail/v4/conversations/${conversation.ID}`, () => ({ Conversation: conversation, Messages: [message], })); const { k } = await setup({ conversations, elementID: conversation.ID }); k(); const history = getHistory(); expect(history.length).toBe(3); expect(history.location.pathname).toBe(`/${props.labelID}/${conversations[3].ID}`); }); it('should allow to select elements with keyboard', async () => { const { getItems, down, space, x, shftSpace, shftX, ctrlA, ctrlUp } = await setup(); const assertChecks = (array: boolean[]) => { const items = getItems(); for (let i = 0; i < array.length; i++) { assertCheck(items[i], array[i]); } }; down(); space(); assertChecks([true, false, false, false]); down(); down(); shftSpace(); assertChecks([true, true, true, false]); ctrlA(); assertChecks([true, true, true, true]); ctrlA(); assertChecks([false, false, false, false]); ctrlUp(); x(); assertChecks([true, false, false, false]); down(); down(); shftX(); assertChecks([true, true, true, false]); }); it('should allow to move elements with keyboard', async () => { const labelSpy = jest.fn<any, any>(() => ({ UndoToken: 'token' })); addApiMock('mail/v4/conversations/label', labelSpy, 'put'); const deleteSpy = jest.fn(); addApiMock('mail/v4/conversations/delete', deleteSpy, 'put'); const conversations = getElements(20, MAILBOX_LABEL_IDS.TRASH); const { down, space, a, i, s, star, t, ctrlBackspace, getByTestId } = await setup({ labelID: MAILBOX_LABEL_IDS.TRASH, conversations, }); let callTimes = 0; const expectLabelCall = (LabelID: string) => { callTimes++; expect(labelSpy).toHaveBeenCalledTimes(callTimes); expect(labelSpy.mock.calls[callTimes - 1][0].data).toEqual({ LabelID, IDs: [conversations[conversations.length - (callTimes * 2 - 1)].ID], }); }; down(); space(); a(); await tick(); expectLabelCall(MAILBOX_LABEL_IDS.ARCHIVE); down(); space(); i(); await tick(); expectLabelCall(MAILBOX_LABEL_IDS.INBOX); down(); space(); s(); await tick(); expectLabelCall(MAILBOX_LABEL_IDS.SPAM); down(); space(); star(); await tick(); expectLabelCall(MAILBOX_LABEL_IDS.STARRED); // T should do nothing as we already are in trash folder t(); expect(labelSpy).toHaveBeenCalledTimes(callTimes); await tick(); ctrlBackspace(); const button = getByTestId('permanent-delete-modal:submit'); fireEvent.click(button as HTMLButtonElement); await tick(); expect(deleteSpy).toHaveBeenCalled(); }); });
3,775
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox/tests/Mailbox.labels.test.tsx
import { Matcher, fireEvent } from '@testing-library/react'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { MailSettings } from '@proton/shared/lib/interfaces'; import { VIEW_MODE } from '@proton/shared/lib/mail/mailSettings'; import { addApiMock, clearAll, waitForSpyCall } from '../../../helpers/test/helper'; import { Element } from '../../../models/element'; import { folders, labels, sendEvent, setup } from './Mailbox.test.helpers'; const [label1, label2, label3, label4] = labels; const [folder1, folder2] = folders; describe('Mailbox labels actions', () => { const conversation1 = { ID: 'id1', Labels: [ { ID: folder1.ID, ContextTime: 3, ContextNumMessages: 1 }, { ID: label1.ID, ContextTime: 3, ContextNumMessages: 1 }, { ID: label2.ID, ContextTime: 3, ContextNumMessages: 1 }, ], NumUnread: 1, NumMessages: 1, } as Element; const conversation2 = { ID: 'id2', Labels: [ { ID: folder1.ID, ContextTime: 2, ContextNumMessages: 1 }, { ID: label1.ID, ContextTime: 2, ContextNumMessages: 1 }, { ID: label2.ID, ContextTime: 2, ContextNumMessages: 1 }, ], NumUnread: 1, NumMessages: 1, } as Element; const conversation3 = { ID: 'id3', Labels: [ { ID: folder1.ID, ContextTime: 2, ContextNumMessages: 1 }, { ID: label1.ID, ContextTime: 1, ContextNumMessages: 1 }, { ID: label2.ID, ContextTime: 1, ContextNumMessages: 1 }, ], NumUnread: 0, NumMessages: 1, } as Element; const conversations = [conversation1, conversation2, conversation3]; beforeEach(clearAll); describe('labels action', () => { const useLabelDropdown = (getByTestId: (text: Matcher) => HTMLElement, labelsToClick: string[]) => { const labelDropdownButton = getByTestId('toolbar:labelas'); fireEvent.click(labelDropdownButton); const labelDropdownList = getByTestId('label-dropdown-list'); labelsToClick.forEach((labelToClick) => { const labelCheckbox = labelDropdownList.querySelector(`[id$=${labelToClick}]`); if (labelCheckbox) { fireEvent.click(labelCheckbox); } }); const labelDropdownApply = getByTestId('label-dropdown:apply'); fireEvent.click(labelDropdownApply); }; const expectLabels = ( getItems: () => HTMLElement[], itemLabels: { [itemID: string]: { [labelName: string]: boolean } } ) => { const items = getItems(); const itemByID = Object.fromEntries( items.map((item) => [item.getAttribute('data-element-id') || '', item]) ); Object.entries(itemLabels).forEach(([itemID, labels]) => { Object.entries(labels).forEach(([labelName, action]) => { if (action) { expect(itemByID[itemID].textContent).toContain(labelName); } else { expect(itemByID[itemID].textContent).not.toContain(labelName); } }); }); }; it('should add a label to two conversations', async () => { const labelRequestSpy = jest.fn(() => ({ UndoToken: { Token: 'Token' } })); addApiMock(`mail/v4/conversations/label`, labelRequestSpy, 'put'); const { getByTestId, getAllByTestId, getItems } = await setup({ conversations, labelID: label1.ID }); const checkboxes = getAllByTestId('item-checkbox'); fireEvent.click(checkboxes[0]); fireEvent.click(checkboxes[1]); useLabelDropdown(getByTestId, [label3.ID]); await waitForSpyCall(labelRequestSpy); expectLabels(getItems, { [conversation1.ID as string]: { [label1.Name]: true, [label3.Name]: true }, [conversation2.ID as string]: { [label1.Name]: true, [label3.Name]: true }, [conversation3.ID as string]: { [label1.Name]: true, [label3.Name]: false }, }); expect(labelRequestSpy).toHaveBeenCalled(); // @ts-ignore const { url, method, data } = labelRequestSpy.mock.calls[0][0]; expect({ url, method, data }).toEqual({ url: 'mail/v4/conversations/label', method: 'put', data: { IDs: [conversation1.ID, conversation2.ID], LabelID: label3.ID }, }); }); it('should remove a label to two conversations', async () => { const labelRequestSpy = jest.fn(() => ({ UndoToken: { Token: 'Token' } })); addApiMock(`mail/v4/conversations/unlabel`, labelRequestSpy, 'put'); const { getByTestId, getAllByTestId, getItems } = await setup({ conversations, labelID: label1.ID }); const checkboxes = getAllByTestId('item-checkbox'); fireEvent.click(checkboxes[1]); fireEvent.click(checkboxes[2]); useLabelDropdown(getByTestId, [label2.ID]); await waitForSpyCall(labelRequestSpy); expectLabels(getItems, { [conversation1.ID as string]: { [label2.Name]: true }, [conversation2.ID as string]: { [label2.Name]: false }, [conversation3.ID as string]: { [label2.Name]: false }, }); expect(labelRequestSpy).toHaveBeenCalled(); // @ts-ignore const { url, method, data } = labelRequestSpy.mock.calls[0][0]; expect({ url, method, data }).toEqual({ url: 'mail/v4/conversations/unlabel', method: 'put', data: { IDs: [conversation2.ID, conversation3.ID], LabelID: label2.ID }, }); }); it('should add and remove a label of a conversation', async () => { const labelRequestSpy = jest.fn(() => ({ UndoToken: { Token: 'Token' } })); const unlabelRequestSpy = jest.fn(() => ({ UndoToken: { Token: 'Token' } })); addApiMock(`mail/v4/conversations/label`, labelRequestSpy, 'put'); addApiMock(`mail/v4/conversations/unlabel`, unlabelRequestSpy, 'put'); const { getByTestId, getAllByTestId, getItems } = await setup({ conversations, labelID: label1.ID }); const checkboxes = getAllByTestId('item-checkbox'); fireEvent.click(checkboxes[0]); useLabelDropdown(getByTestId, [label2.ID, label3.ID]); await waitForSpyCall(labelRequestSpy); await waitForSpyCall(unlabelRequestSpy); expectLabels(getItems, { [conversation1.ID as string]: { [label1.Name]: true, [label2.Name]: false, [label3.Name]: true, [label4.Name]: false, }, [conversation2.ID as string]: { [label1.Name]: true, [label2.Name]: true, [label3.Name]: false, [label4.Name]: false, }, }); }); }); describe('folders action', () => { const useMoveDropdown = (getByTestId: (text: Matcher) => HTMLElement, folderID: string) => { const moveDropdownButton = getByTestId('toolbar:moveto'); fireEvent.click(moveDropdownButton); const moveDropdownList = getByTestId('move-dropdown-list'); const folderButton = moveDropdownList.querySelector(`[id$=${folderID}]`); if (folderButton) { fireEvent.click(folderButton); } const moveDropdownApply = getByTestId('move-dropdown:apply'); fireEvent.click(moveDropdownApply); }; it('should move two conversations in a another folder', async () => { const labelRequestSpy = jest.fn(() => ({ UndoToken: { Token: 'Token' } })); addApiMock(`mail/v4/conversations/label`, labelRequestSpy, 'put'); const { getByTestId, getAllByTestId, getItems } = await setup({ conversations, labelID: folder1.ID }); const checkboxes = getAllByTestId('item-checkbox'); fireEvent.click(checkboxes[0]); fireEvent.click(checkboxes[1]); addApiMock('mail/v4/conversations', () => ({ Total: 1, Conversations: [conversation3] })); useMoveDropdown(getByTestId, folder2.ID); await sendEvent({ ConversationCounts: [{ LabelID: folder1.ID, Total: 1, Unread: 0 }] }); await waitForSpyCall(labelRequestSpy); const items = getItems(); expect(items.length).toBe(1); }); }); describe('empty folder', () => { it('should empty a folder', async () => { const emptyRequestSpy = jest.fn(); addApiMock(`mail/v4/messages/empty`, emptyRequestSpy, 'delete'); const { getByTestId, getItems, findByTestId, queryAllByTestId } = await setup({ conversations, labelID: folder1.ID, }); let items = getItems(); expect(items.length).toBe(3); const moreDropdown = getByTestId('toolbar:more-dropdown'); fireEvent.click(moreDropdown); const emptyButton = await findByTestId('toolbar:more-empty'); fireEvent.click(emptyButton); const confirmButton = await findByTestId('confirm-empty-folder'); fireEvent.click(confirmButton); await waitForSpyCall(emptyRequestSpy); items = queryAllByTestId('message-item', { exact: false }); expect(items.length).toBe(0); }); }); describe('delete elements', () => { const deleteFirstTwo = async ({ getAllByTestId, getByTestId, deleteRequestSpy, }: { getAllByTestId: (text: Matcher) => HTMLElement[]; getByTestId: (text: Matcher) => HTMLElement; deleteRequestSpy: jest.Mock; }) => { const checkboxes = getAllByTestId('item-checkbox'); fireEvent.click(checkboxes[0]); fireEvent.click(checkboxes[1]); const deleteButton = getByTestId('toolbar:deletepermanently'); fireEvent.click(deleteButton); const submitButton = getByTestId('permanent-delete-modal:submit'); fireEvent.click(submitButton); await waitForSpyCall(deleteRequestSpy); }; it('should delete permamently conversations', async () => { const deleteRequestSpy = jest.fn(() => {}); addApiMock(`mail/v4/conversations/delete`, deleteRequestSpy, 'put'); const trashedConversations = conversations.map((conversation) => { return { ...conversation, Labels: [{ ID: MAILBOX_LABEL_IDS.TRASH, ContextTime: 0, ContextNumMessages: 0 }], }; }); const { getAllByTestId, getByTestId, getItems } = await setup({ conversations: trashedConversations, labelID: MAILBOX_LABEL_IDS.TRASH, }); await deleteFirstTwo({ getAllByTestId, getByTestId, deleteRequestSpy }); const items = getItems(); expect(items.length).toBe(1); }); it('should delete permamently messages', async () => { const deleteRequestSpy = jest.fn(() => {}); addApiMock(`mail/v4/messages/delete`, deleteRequestSpy, 'put'); const trashedMessages = conversations.map((conversation) => { return { ...conversation, ConversationID: 'id', LabelIDs: [MAILBOX_LABEL_IDS.TRASH] }; }); const { getByTestId, getAllByTestId, getItems } = await setup({ mailSettings: { ViewMode: VIEW_MODE.SINGLE } as MailSettings, messages: trashedMessages, labelID: MAILBOX_LABEL_IDS.TRASH, }); await deleteFirstTwo({ getAllByTestId, getByTestId, deleteRequestSpy }); const items = getItems(); expect(items.length).toBe(1); }); it('should delete permamently conversations and rollback', async () => { const deleteRequestSpy = jest.fn(() => { throw new Error('failed'); }); addApiMock(`mail/v4/conversations/delete`, deleteRequestSpy, 'put'); const trashedConversations = conversations.map((conversation) => { return { ...conversation, Labels: [{ ID: MAILBOX_LABEL_IDS.TRASH, ContextTime: 0, ContextNumMessages: 0 }], }; }); const { getByTestId, getAllByTestId, getItems } = await setup({ conversations: trashedConversations, labelID: MAILBOX_LABEL_IDS.TRASH, }); await deleteFirstTwo({ getAllByTestId, getByTestId, deleteRequestSpy }); const items = getItems(); expect(items.length).toBe(3); }); }); });
3,776
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox/tests/Mailbox.perf.test.tsx
import { EVENT_ACTIONS } from '@proton/shared/lib/constants'; import { clearAll, getHistory } from '../../../helpers/test/helper'; import * as useStarModule from '../../../hooks/actions/useStar'; import { getElements, sendEvent, setup } from './Mailbox.test.helpers'; jest.spyOn(useStarModule, 'useStar'); // Spying useStar is a trick to count the number of renders on the component ItemStar // Beware, useStar is also used on the hotkeys management const useStar = useStarModule.useStar as jest.Mock; describe('Mailbox performance loss check', () => { beforeEach(clearAll); /** * ItemStar is a pretext to detect item re-rendering * The point of this test is to trigger some common event on the app like an element update event and a location change * Count the number of render of the ItemStar component which is present inside each line of the element list * And verify that this low level component has never been re-rerendered * We're spying on the useStar hook to count the number of render */ it('should not render ItemStar on a conversation events nor a location change', async () => { const total = 3; const SomeNonMatchingID = 'SomeNonMatchingID'; const conversations = getElements(total); const { getItems } = await setup({ conversations }); const items = getItems(); expect(items.length).toBe(total); const callsAfterInitialization = useStar.mock.calls.length; // Send event though the event manager + change location to trigger common app change await sendEvent({ Conversations: [ { ID: SomeNonMatchingID, Action: EVENT_ACTIONS.CREATE, Conversation: { ID: SomeNonMatchingID } }, ], }); getHistory().push('/elsewhere'); // There will be a few more call but it has to be in limited amount expect(useStar.mock.calls.length).toBeLessThan(callsAfterInitialization + 6); }); });
3,777
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox/tests/Mailbox.retries.test.tsx
import { act, fireEvent } from '@testing-library/react'; import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { wait } from '@proton/shared/lib/helpers/promise'; import { PAGE_SIZE } from '../../../constants'; import { addApiMock, clearAll, tick } from '../../../helpers/test/helper'; import { expectElements, getElements, setup } from './Mailbox.test.helpers'; jest.setTimeout(20000); describe('Mailbox retries and waitings', () => { beforeEach(clearAll); it('should retry when API call fails', async () => { const conversations = getElements(3); let callNumber = 0; const conversationRequestSpy = jest.fn(() => { callNumber++; if (callNumber === 1) { throw new Error('Test error'); } return { Total: conversations.length, Conversations: conversations }; }); addApiMock(`mail/v4/conversations`, conversationRequestSpy, 'get'); const { getItems } = await setup({ totalConversations: conversations.length }); expect(conversationRequestSpy).toHaveBeenCalledTimes(1); expectElements(getItems, conversations.length, true); await act(async () => { await wait(2000); }); expect(conversationRequestSpy).toHaveBeenCalledTimes(2); expectElements(getItems, conversations.length, false); }); it('should retry when API respond with stale flag', async () => { const conversations = getElements(3); let callNumber = 0; const conversationRequestSpy = jest.fn(() => { callNumber++; return { Total: conversations.length, Conversations: conversations, Stale: callNumber === 1 ? 1 : 0 }; }); addApiMock(`mail/v4/conversations`, conversationRequestSpy, 'get'); const { getItems } = await setup({ totalConversations: conversations.length }); expect(conversationRequestSpy).toHaveBeenCalledTimes(1); expectElements(getItems, conversations.length, false); await act(async () => { await wait(10000); }); expect(conversationRequestSpy).toHaveBeenCalledTimes(2); expectElements(getItems, conversations.length, false); }); it('should wait for all API actions to be finished before loading elements', async () => { const conversations = getElements(PAGE_SIZE * 2, MAILBOX_LABEL_IDS.INBOX); const totalConversations = PAGE_SIZE * 3; const conversationRequestSpy = jest.fn(() => { return { Total: totalConversations, Conversations: conversations }; }); addApiMock(`mail/v4/conversations`, conversationRequestSpy, 'get'); let resolvers: ((value: any) => void)[] = []; const labelRequestSpy = jest.fn(() => { return new Promise((resolver) => { resolvers.push(resolver as any); }); }); addApiMock('mail/v4/conversations/label', labelRequestSpy, 'put'); const { getItems, getByTestId } = await setup({ labelID: MAILBOX_LABEL_IDS.INBOX, totalConversations, mockConversations: false, }); const checkAll = getByTestId('toolbar:select-all-checkbox'); await act(async () => { fireEvent.click(checkAll); await tick(); let trash = getByTestId('toolbar:movetotrash'); fireEvent.click(trash); await tick(); fireEvent.click(checkAll); await tick(); trash = getByTestId('toolbar:movetotrash'); fireEvent.click(trash); await tick(); }); expect(conversationRequestSpy).toHaveBeenCalledTimes(1); expectElements(getItems, PAGE_SIZE, true); await act(async () => { resolvers[0]({ UndoToken: 'fake' }); }); expect(conversationRequestSpy).toHaveBeenCalledTimes(1); expectElements(getItems, PAGE_SIZE, true); await act(async () => { resolvers[1]({ UndoToken: 'fake' }); }); expect(conversationRequestSpy).toHaveBeenCalledTimes(2); expectElements(getItems, PAGE_SIZE, false); }); });
3,778
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox/tests/Mailbox.selection.test.tsx
import { fireEvent } from '@testing-library/react'; import { clearAll } from '../../../helpers/test/helper'; import { props, setup } from './Mailbox.test.helpers'; describe('Mailbox elements selection', () => { const conversations = [ { ID: '1', Labels: [{ ID: props.labelID }] }, { ID: '2', Labels: [{ ID: props.labelID }] }, ]; beforeEach(clearAll); it('should show list when elements finish loading', async () => { const { getItems } = await setup({ conversations }); const items = getItems(); expect(items.length === conversations.length).toBe(true); }); it('should select all', async () => { const { getByTestId, getAllByTestId } = await setup({ conversations }); const checkAll = getByTestId('toolbar:select-all-checkbox'); fireEvent.click(checkAll); const allChecks = getAllByTestId('item-checkbox') as HTMLInputElement[]; expect(allChecks.length > 0).toBe(true); const checked = [...allChecks].every((oneCheck) => oneCheck.checked); expect(checked).toBe(true); }); });
3,779
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox/tests/Mailbox.test.helpers.tsx
import { MutableRefObject, ReactElement, ReactNode } from 'react'; import { act } from '@testing-library/react'; import loudRejection from 'loud-rejection'; import { LABEL_TYPE } from '@proton/shared/lib/constants'; import { wait } from '@proton/shared/lib/helpers/promise'; import { MailSettings, UserSettings } from '@proton/shared/lib/interfaces'; import { Folder } from '@proton/shared/lib/interfaces/Folder'; import { Label } from '@proton/shared/lib/interfaces/Label'; import { VIEW_MODE } from '@proton/shared/lib/mail/mailSettings'; import range from '@proton/utils/range'; import { filterToString, keywordToString, sortToString } from '../../../helpers/mailboxUrl'; import { addApiMock, addToCache, getHistory, minimalCache, render, triggerEvent } from '../../../helpers/test/helper'; import { ConversationLabel } from '../../../models/conversation'; import { Element } from '../../../models/element'; import { Event } from '../../../models/event'; import { Filter, SearchParameters, Sort } from '../../../models/tools'; import { Breakpoints } from '../../../models/utils'; import MailboxContainer from '../MailboxContainer'; loudRejection(); interface PropsArgs { labelID?: string; elementID?: string; page?: number; sort?: Sort; filter?: Filter; search?: SearchParameters; mailSettings?: MailSettings; } export interface SetupArgs extends PropsArgs { messages?: Element[]; conversations?: Element[]; inputLabelID?: string; page?: number; totalMessages?: number; totalConversations?: number; mockMessages?: boolean; mockConversations?: boolean; Component?: typeof MailboxContainer; mailSettings?: MailSettings; } export const props = { labelID: 'labelID', userSettings: {} as UserSettings, breakpoints: { isDesktop: true } as Breakpoints, elementID: undefined, onCompose: jest.fn(), isComposerOpened: false, drawerSidebarButtons: [] as ReactElement[], drawerSettingsButton: null as ReactNode, drawerSpotlightSeenRef: { current: false } as MutableRefObject<boolean>, }; const defaultSort = { sort: 'Time', desc: true } as Sort; const defaultFilter = {}; const defaultSearch = {}; const defaultMailSettings = { ViewMode: VIEW_MODE.GROUP, Shortcuts: 1 } as MailSettings; export const labels: Label[] = [ { ID: 'labelID', Type: LABEL_TYPE.MESSAGE_LABEL, Name: 'label' }, { ID: 'label1', Type: LABEL_TYPE.MESSAGE_LABEL, Name: 'label1' }, { ID: 'label2', Type: LABEL_TYPE.MESSAGE_LABEL, Name: 'label2' }, { ID: 'label3', Type: LABEL_TYPE.MESSAGE_LABEL, Name: 'label3' }, { ID: 'label4', Type: LABEL_TYPE.MESSAGE_LABEL, Name: 'label4' }, ] as Label[]; export const folders: Folder[] = [ { ID: 'folder1', Type: LABEL_TYPE.MESSAGE_FOLDER, Name: 'folder1' }, { ID: 'folder2', Type: LABEL_TYPE.MESSAGE_FOLDER, Name: 'folder2' }, { ID: 'folder3', Type: LABEL_TYPE.MESSAGE_FOLDER, Name: 'folder3' }, { ID: 'folder4', Type: LABEL_TYPE.MESSAGE_FOLDER, Name: 'folder4' }, ] as Folder[]; export const getElements = (count: number, label = props.labelID, elementProps: any = {}): Element[] => range(0, count).map((i) => ({ ID: `id${i}`, Labels: [{ ID: label, ContextTime: i }] as ConversationLabel[], LabelIDs: [label], NumMessages: 1, ...elementProps, })); export const getProps = ({ labelID = props.labelID, elementID, page = 0, sort = defaultSort, filter = defaultFilter, search = defaultSearch, mailSettings = defaultMailSettings, }: PropsArgs) => { const urlSearchParams = new URLSearchParams(); if (page !== 0) { urlSearchParams.set('page', String(page + 1)); } if (sort !== defaultSort) { urlSearchParams.set('sort', sortToString(sort) || ''); } if (filter !== defaultFilter) { urlSearchParams.set('filter', filterToString(filter) || ''); } if (search !== defaultSearch) { urlSearchParams.set('keyword', keywordToString(search.keyword || '') || ''); } getHistory().push(`#${urlSearchParams.toString()}`); return { ...props, labelID, elementID, mailSettings }; }; export const baseApiMocks = () => { addApiMock('importer/v1/importers', () => ({ Importers: [] })); addApiMock('settings/calendar', () => ({})); addApiMock('calendar/v1', () => ({})); addApiMock('payments/v4/plans', () => ({})); }; export const setup = async ({ messages = [], conversations = [], totalMessages = messages.length, totalConversations = conversations.length, mockMessages = true, mockConversations = true, Component = MailboxContainer, ...propsArgs }: SetupArgs = {}) => { minimalCache(); baseApiMocks(); const props = getProps(propsArgs); addToCache('Labels', [{ ID: props.labelID }]); if (mockMessages) { addApiMock('mail/v4/messages', () => ({ Total: totalMessages, Messages: messages })); } if (mockConversations) { addApiMock('mail/v4/conversations', () => ({ Total: totalConversations, Conversations: conversations })); } addToCache('Labels', [...labels, ...folders]); addToCache('MessageCounts', [{ LabelID: props.labelID, Total: totalMessages, Unread: totalMessages }]); addToCache('ConversationCounts', [ { LabelID: props.labelID, Total: totalConversations, Unread: totalConversations }, ]); addToCache('MailSettings', props.mailSettings); addToCache('Calendars', []); const result = await render(<Component {...props} />, false); const rerender = (propsArgs: PropsArgs) => result.rerender(<Component {...getProps(propsArgs)} />); const getItems = () => result.getAllByTestId('message-item', { exact: false }); return { ...result, rerender, getItems }; }; export const sendEvent = async (event: Event) => { await act(async () => { triggerEvent(event); await wait(0); }); }; export const expectElements = (getItems: () => HTMLElement[], total: number, isPlaceholder: boolean) => { const items = getItems(); expect(items.length).toBe(total); items.forEach((item) => { if (isPlaceholder) { expect(item.getAttribute('data-element-id')).toContain('placeholder'); } else { expect(item.getAttribute('data-element-id')).not.toContain('placeholder'); } }); };
3,780
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/mailbox/tests/MailboxContainerPlaceholder.test.tsx
import { screen } from '@testing-library/react'; import { CHECKLIST_DISPLAY_TYPE } from '@proton/shared/lib/interfaces'; import { ContextState, useGetStartedChecklist, } from '../../../containers/onboardingChecklist/provider/GetStartedChecklistProvider'; import { render } from '../../../helpers/test/helper'; import MailboxContainerPlaceholder from '../MailboxContainerPlaceholder'; jest.mock('../../../containers/onboardingChecklist/provider/GetStartedChecklistProvider', () => ({ __esModule: true, useGetStartedChecklist: jest.fn(), default: ({ children }: { children: any }) => <>{children}</>, })); jest.mock('../../../containers/onboardingChecklist/provider/GetStartedChecklistProvider'); const mockedReturn = useGetStartedChecklist as jest.MockedFunction<typeof useGetStartedChecklist>; describe('MailboxContainerPlaceholder', () => { it('Should display checklist when no mails are present', async () => { mockedReturn.mockReturnValue({ displayState: CHECKLIST_DISPLAY_TYPE.FULL, items: new Set() } as ContextState); await render( <MailboxContainerPlaceholder showPlaceholder={true} welcomeFlag={false} labelID="labelID" checkedIDs={[]} handleCheckAll={jest.fn()} /> ); screen.getByTestId('onboarding-checklist'); }); it('Should display section pane when checklist is reduced', async () => { mockedReturn.mockReturnValue({ displayState: CHECKLIST_DISPLAY_TYPE.REDUCED, items: new Set(), } as ContextState); await render( <MailboxContainerPlaceholder showPlaceholder={true} welcomeFlag={false} labelID="labelID" checkedIDs={[]} handleCheckAll={jest.fn()} /> ); screen.getByTestId('section-pane--wrapper'); }); it('Should display section pane when checklist is hidden', async () => { mockedReturn.mockReturnValue({ displayState: CHECKLIST_DISPLAY_TYPE.HIDDEN, items: new Set(), } as ContextState); await render( <MailboxContainerPlaceholder showPlaceholder={true} welcomeFlag={false} labelID="labelID" checkedIDs={[]} handleCheckAll={jest.fn()} /> ); screen.getByTestId('section-pane--wrapper'); }); });
3,781
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/onboardingChecklist
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/onboardingChecklist/hooks/useChecklist.test.ts
import { useUserSettings } from '@proton/components/hooks'; import { addApiMock, renderHook } from 'proton-mail/helpers/test/helper'; import useChecklist from './useChecklist'; const getChecklist = jest.fn(() => { return { Code: 10, Items: [], }; }); const paidChecklist = jest.fn(() => { return { Code: 20, Items: [], }; }); const defaultReturnValue = { Code: 0, Items: [], CreatedAt: 0, ExpiresAt: 0, UserWasRewarded: false, Display: 'Hidden', }; jest.mock('@proton/components/hooks/useUserSettings'); const mockedUserSettings = useUserSettings as jest.MockedFunction<any>; describe('useChecklist', () => { beforeAll(() => { addApiMock(`core/v4/checklist/get-started`, getChecklist); addApiMock(`core/v4/checklist/paying-user`, paidChecklist); }); afterEach(() => { getChecklist.mockClear(); paidChecklist.mockClear(); }); it('Should fetch the get-started checklist', async () => { mockedUserSettings.mockReturnValue([{ Checklists: ['get-started'] }]); const { result } = await renderHook(() => useChecklist('get-started')); expect(getChecklist).toHaveBeenCalled(); expect(paidChecklist).not.toHaveBeenCalled(); expect(result.current[0]).toEqual({ Code: 10, Items: [] }); }); it('Should fetch the paying-user checklist', async () => { mockedUserSettings.mockReturnValue([{ Checklists: ['paying-user'] }]); const { result } = await renderHook(() => useChecklist('paying-user')); expect(getChecklist).not.toHaveBeenCalled(); expect(paidChecklist).toHaveBeenCalled(); expect(result.current[0]).toEqual({ Code: 20, Items: [] }); }); it('Should not fetch get started when checklist not present', async () => { mockedUserSettings.mockReturnValue([{}]); const { result } = await renderHook(() => useChecklist('get-started')); expect(getChecklist).not.toHaveBeenCalled(); expect(paidChecklist).not.toHaveBeenCalled(); expect(result.current[0]).toEqual(defaultReturnValue); }); it('Should not fetch paying user when checklist not present', async () => { mockedUserSettings.mockReturnValue([{}]); const { result } = await renderHook(() => useChecklist('paying-user')); expect(getChecklist).not.toHaveBeenCalled(); expect(paidChecklist).not.toHaveBeenCalled(); expect(result.current[0]).toEqual(defaultReturnValue); }); it('Should not fetch get started when checklist empty', async () => { mockedUserSettings.mockReturnValue([{ Checklists: [] }]); const { result } = await renderHook(() => useChecklist('get-started')); expect(getChecklist).not.toHaveBeenCalled(); expect(paidChecklist).not.toHaveBeenCalled(); expect(result.current[0]).toEqual(defaultReturnValue); }); it('Should not fetch paying user when checklist empty', async () => { mockedUserSettings.mockReturnValue([{ Checklists: [] }]); const { result } = await renderHook(() => useChecklist('paying-user')); expect(getChecklist).not.toHaveBeenCalled(); expect(paidChecklist).not.toHaveBeenCalled(); expect(result.current[0]).toEqual(defaultReturnValue); }); });
3,782
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/onboardingChecklist
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/onboardingChecklist/hooks/useChecklist.ts
import { useEffect, useState } from 'react'; import { useApi, useEventManager, useUserSettings } from '@proton/components'; import { useLoading } from '@proton/hooks'; import { getChecklist } from '@proton/shared/lib/api/checklist'; import { CHECKLIST_DISPLAY_TYPE, ChecklistId, ChecklistKey } from '@proton/shared/lib/interfaces'; import { Event } from '../../../models/event'; interface ChecklistApiResponse { Code: number; Items: ChecklistKey[]; CreatedAt: number; ExpiresAt: number; UserWasRewarded: boolean; Display: CHECKLIST_DISPLAY_TYPE; } export interface GetStartedChecklistApiResponse extends ChecklistApiResponse { RewardInGB: number; } export type Checklist = ChecklistApiResponse | GetStartedChecklistApiResponse; const useChecklist = (id: ChecklistId) => { const [checklist, setChecklist] = useState<Checklist>({ Code: 0, Items: [] as ChecklistKey[], CreatedAt: 0, ExpiresAt: 0, UserWasRewarded: false, Display: CHECKLIST_DISPLAY_TYPE.HIDDEN, }); const [userSettings] = useUserSettings(); const [loading, withLoading] = useLoading(); const { subscribe } = useEventManager(); const api = useApi(); useEffect(() => { if (userSettings.Checklists?.includes(id)) { void withLoading(api<Checklist>(getChecklist(id)).then(setChecklist)); } const unsubscribe = subscribe(({ Checklist }: Event) => { Checklist?.forEach(({ CompletedItem, Display }) => { setChecklist((current) => ({ ...current, Items: [...current.Items, CompletedItem], Display: Display || current.Display, })); }); }); return () => { if (unsubscribe) { unsubscribe(); } }; }, [userSettings]); return [checklist, loading] as const; }; export default useChecklist;
3,783
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/onboardingChecklist
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/onboardingChecklist/provider/ChecklistsProvider.tsx
import { ReactNode } from 'react'; import GetStartedChecklistProvider from './GetStartedChecklistProvider'; interface Props { children: ReactNode; } const ChecklistsProvider = ({ children }: Props) => { return <GetStartedChecklistProvider>{children}</GetStartedChecklistProvider>; }; export default ChecklistsProvider;
3,784
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/onboardingChecklist
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/onboardingChecklist/provider/GetStartedChecklistProvider.test.tsx
import useLoading from '@proton/hooks/useLoading'; import { CHECKLIST_DISPLAY_TYPE, ChecklistId, ChecklistKey } from '@proton/shared/lib/interfaces'; import { renderHook } from 'proton-mail/helpers/test/render'; import useChecklist from '../hooks/useChecklist'; import { useGetStartedChecklist } from './GetStartedChecklistProvider'; jest.mock('@proton/hooks/useLoading'); const mockLoading = useLoading as jest.MockedFunction<any>; jest.mock('../hooks/useChecklist'); const mockChecklist = useChecklist as jest.MockedFunction<any>; interface ChecklistBuilderProps { checklistId: ChecklistId; isPaid: boolean; items?: ChecklistKey[]; createdAt?: number; expiresAt?: number; userWasRewarded?: boolean; display?: CHECKLIST_DISPLAY_TYPE; } const nonAvailableChecklist = { Code: 0, Items: [] as ChecklistKey[], CreatedAt: 0, ExpiresAt: 0, RewardInGB: 0, UserWasRewarded: false, Display: CHECKLIST_DISPLAY_TYPE.HIDDEN, }; const checklistBuilder = ({ checklistId, isPaid, items, createdAt, expiresAt, userWasRewarded, display, }: ChecklistBuilderProps) => { if (checklistId === 'paying-user' && isPaid) { return { paidChecklist: [ { Code: 1000, Items: [...(items || [])], CreatedAt: createdAt || 0, ExpiresAt: expiresAt || 0, RewardInGB: 0, UserWasRewarded: userWasRewarded || false, Display: display || CHECKLIST_DISPLAY_TYPE.HIDDEN, }, false, ], freeChecklist: [nonAvailableChecklist, false], }; } return { freeChecklist: [ { Code: 1000, Items: [...(items || [])], CreatedAt: createdAt || 0, ExpiresAt: expiresAt || 0, RewardInGB: 0, UserWasRewarded: userWasRewarded || false, Display: display || CHECKLIST_DISPLAY_TYPE.HIDDEN, }, false, ], paidChecklist: [nonAvailableChecklist, false], }; }; describe('GetStartedChecklistProvider', () => { it('Very basic test to see if default return values are correct for free users', async () => { const itemsList = [ ChecklistKey.MobileApp, ChecklistKey.SendMessage, ChecklistKey.Import, ChecklistKey.AccountLogin, ]; mockLoading.mockReturnValue([false, jest.fn()]); const { freeChecklist, paidChecklist } = checklistBuilder({ checklistId: 'get-started', isPaid: false, items: itemsList, }); mockChecklist.mockImplementation((checklistId: any) => { if (checklistId === 'get-started') { return freeChecklist; } else { return paidChecklist; } }); const { result } = await renderHook(() => useGetStartedChecklist()); const { isUserPaid, loading, isChecklistFinished, userWasRewarded, items, displayState } = result.current; expect({ isUserPaid, loading, isChecklistFinished, userWasRewarded, items, displayState }).toStrictEqual({ isUserPaid: false, loading: false, isChecklistFinished: false, userWasRewarded: false, items: new Set([...itemsList]), displayState: 'Hidden', }); }); it('Very basic test to see if default return values are correct for free users', async () => { const itemsList = [ ChecklistKey.MobileApp, ChecklistKey.MobileApp, ChecklistKey.MobileApp, ChecklistKey.SendMessage, ChecklistKey.Import, ChecklistKey.AccountLogin, ]; mockLoading.mockReturnValue([false, jest.fn()]); const { freeChecklist, paidChecklist } = checklistBuilder({ checklistId: 'paying-user', isPaid: true, items: itemsList, }); mockChecklist.mockImplementation((checklistId: any) => { if (checklistId === 'get-started') { return freeChecklist; } else { return paidChecklist; } }); const { result } = await renderHook(() => useGetStartedChecklist()); const { isUserPaid, loading, isChecklistFinished, userWasRewarded, items, displayState } = result.current; expect({ isUserPaid, loading, isChecklistFinished, userWasRewarded, items, displayState }).toStrictEqual({ isUserPaid: true, loading: false, isChecklistFinished: false, userWasRewarded: false, items: new Set([...itemsList]), displayState: 'Hidden', }); }); it('Test if checklist is marked as finished if all the items are present', async () => { const itemsList = [ ChecklistKey.MobileApp, ChecklistKey.Import, ChecklistKey.AccountLogin, ChecklistKey.ProtectInbox, ]; mockLoading.mockReturnValue([false, jest.fn()]); const { freeChecklist, paidChecklist } = checklistBuilder({ checklistId: 'get-started', isPaid: false, items: itemsList, }); mockChecklist.mockImplementation((checklistId: any) => { if (checklistId === 'get-started') { return freeChecklist; } else { return paidChecklist; } }); const { result } = await renderHook(() => useGetStartedChecklist()); const { isUserPaid, loading, isChecklistFinished, userWasRewarded, items, displayState } = result.current; expect({ isUserPaid, loading, isChecklistFinished, userWasRewarded, items, displayState, }).toStrictEqual({ isUserPaid: false, loading: false, isChecklistFinished: true, userWasRewarded: false, items: new Set([...itemsList]), displayState: 'Hidden', }); }); });
3,785
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/onboardingChecklist
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/containers/onboardingChecklist/provider/GetStartedChecklistProvider.tsx
import { ReactNode, createContext, useContext, useEffect, useState } from 'react'; import { fromUnixTime } from 'date-fns'; import { useApi, useEventManager } from '@proton/components/hooks'; import useLoading from '@proton/hooks/useLoading'; import { hidePaidUserChecklist, seenCompletedChecklist, updateChecklistDisplay, updateChecklistItem, } from '@proton/shared/lib/api/checklist'; import { getSilentApi } from '@proton/shared/lib/api/helpers/customConfig'; import { CHECKLIST_DISPLAY_TYPE, ChecklistApiResponse, ChecklistKey, ChecklistKeyType, } from '@proton/shared/lib/interfaces'; import useChecklist, { GetStartedChecklistApiResponse } from '../hooks/useChecklist'; const { REDUCED, HIDDEN } = CHECKLIST_DISPLAY_TYPE; const completedChecklist = [ ChecklistKey.AccountLogin, ChecklistKey.Import, ChecklistKey.ProtectInbox, ChecklistKey.MobileApp, ]; export interface ContextState { expiresAt: Date; loading: boolean; isUserPaid: boolean; isChecklistFinished: boolean; items: Set<ChecklistKeyType>; displayState: ChecklistApiResponse['Display']; userWasRewarded: GetStartedChecklistApiResponse['UserWasRewarded']; changeChecklistDisplay: (display: CHECKLIST_DISPLAY_TYPE) => void; markItemsAsDone: (item: ChecklistKeyType) => void; } const GetStartedChecklistContext = createContext<ContextState>({} as ContextState); const GetStartedChecklistProvider = ({ children }: { children: ReactNode }) => { const api = useApi(); const silentApi = getSilentApi(api); const { call } = useEventManager(); const [submitting, withSubmitting] = useLoading(); // This is used in the checklist to make optimistic UI updates. It marks the checklist item as done or store the display state const [doneItems, setDoneItems] = useState<ChecklistKeyType[]>([]); const [displayState, setDisplayState] = useState<CHECKLIST_DISPLAY_TYPE>(HIDDEN); const [freeUserChecklist, loadingFreeChecklist] = useChecklist('get-started') as [ GetStartedChecklistApiResponse, boolean ]; const [paidUserChecklist, loadingPaidChecklist] = useChecklist('paying-user') as [ GetStartedChecklistApiResponse, boolean ]; const isLoading = loadingFreeChecklist || loadingPaidChecklist; const isUserPaid = paidUserChecklist.Code === 1000; const items = isUserPaid ? paidUserChecklist.Items : freeUserChecklist.Items; const isChecklistFinished = completedChecklist.every((item) => items.includes(item)); useEffect(() => { if (submitting) { return; } if (isUserPaid) { setDoneItems(paidUserChecklist.Items); setDisplayState(paidUserChecklist.Display); } else { setDoneItems(freeUserChecklist.Items); setDisplayState(freeUserChecklist.Display); } }, [freeUserChecklist, paidUserChecklist, submitting]); const markItemsAsDone = async (item: ChecklistKeyType) => { setDoneItems([...doneItems, item]); await silentApi(updateChecklistItem(item)); await call(); }; const changeChecklistDisplay = (newState: CHECKLIST_DISPLAY_TYPE) => { setDisplayState(newState); withSubmitting(async () => { // Reduce the checklist and mark first checklist item as done if (newState === REDUCED) { const items = isUserPaid ? paidUserChecklist.Items : freeUserChecklist.Items; if (!items.includes(ChecklistKey.ProtectInbox)) { setDoneItems([...doneItems, ChecklistKey.ProtectInbox]); await silentApi(updateChecklistItem('ProtectInbox')); } } // Send information to the backend when paid user hide the checklist if (newState === HIDDEN && isUserPaid) { await silentApi(hidePaidUserChecklist()); } if (isChecklistFinished && (newState === REDUCED || newState === HIDDEN)) { const checklist = isUserPaid ? 'paying-user' : 'get-started'; await silentApi(seenCompletedChecklist(checklist)); } await api(updateChecklistDisplay(newState)); await call(); }); }; const getExpiredAt = (): Date => isUserPaid ? fromUnixTime(paidUserChecklist.ExpiresAt) : fromUnixTime(freeUserChecklist.ExpiresAt); const context: ContextState = { isUserPaid, loading: isLoading, isChecklistFinished, changeChecklistDisplay, userWasRewarded: isUserPaid ? paidUserChecklist.UserWasRewarded : freeUserChecklist.UserWasRewarded, items: new Set([...doneItems]), displayState, expiresAt: getExpiredAt(), markItemsAsDone, }; return <GetStartedChecklistContext.Provider value={context}>{children}</GetStartedChecklistContext.Provider>; }; export const useGetStartedChecklist = () => useContext(GetStartedChecklistContext) as ContextState; export default GetStartedChecklistProvider;
3,786
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/addresses.ts
import { ADDRESS_STATUS } from '@proton/shared/lib/constants'; import { canonicalizeInternalEmail } from '@proton/shared/lib/helpers/email'; import { Address, Key } from '@proton/shared/lib/interfaces'; import { getAddressFromPlusAlias, getByEmail } from '@proton/shared/lib/mail/addresses'; /** * Check if the address is fallback (Can't receive but has keys) */ export const isFallbackAddress = (address?: Address, keys: Key[] = []) => !!address && !address.Receive && !!keys.length; export const isDirtyAddress = ({ Keys, Status }: Address) => !Keys.length || Status === ADDRESS_STATUS.STATUS_DISABLED; export const isOwnAddress = (address?: Address, keys: Key[] = []) => !!address && !isFallbackAddress(address, keys); export const isSelfAddress = (email: string | undefined, addresses: Address[]) => !!addresses.find(({ Email }) => canonicalizeInternalEmail(Email) === canonicalizeInternalEmail(email || '')); /** * Get matching address for the email in the list dealing with potential plus aliases */ export const getAddressFromEmail = (addresses: Address[], email = '') => { const addressForPlusAlias = getAddressFromPlusAlias(addresses, email); if (addressForPlusAlias) { return addressForPlusAlias; } return getByEmail(addresses, email); }; /** * Return list of addresses available in the FROM select * Reference: Angular/src/app/composer/factories/composerFromModel.js */ export const getFromAddresses = (addresses: Address[], originalAddress = '') => { const result = addresses .filter(({ Status, Receive, Send }) => Status === 1 && Receive === 1 && Send === 1) .sort((a1, a2) => (a1.Order || 0) - (a2.Order || 0)); const plusAddress = getAddressFromPlusAlias(addresses, originalAddress); if (plusAddress) { // It's important to unshift the plus address to be found first with find() result.unshift(plusAddress); } return result; }; /** * Get address to use as sender for a new draft */ export const getFromAddress = (addresses: Address[], originalTo = '', addressID: string | undefined) => { const fromAddresses = getFromAddresses(addresses, originalTo); return fromAddresses.find((address) => address.ID === addressID) || fromAddresses[0]; };
3,787
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/autoDelete.ts
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; const { SPAM, TRASH } = MAILBOX_LABEL_IDS; export function isAllowedAutoDeleteLabelID(labelID: string): labelID is typeof SPAM | typeof TRASH { if ([SPAM, TRASH].some((systemFolderId) => systemFolderId === labelID)) { return true; } return false; }
3,788
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/base64.ts
import { base64StringToUint8Array, uint8ArrayToBase64String } from '@proton/shared/lib/helpers/encoding'; export const arrayToBase64 = (data: Uint8Array): string => uint8ArrayToBase64String(data) || ''; export const base64ToArray = (data: string): Uint8Array => base64StringToUint8Array(data);
3,789
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/composerPositioning.ts
import { getCustomSizingClasses } from '@proton/components'; import { rootFontSize } from '@proton/shared/lib/helpers/dom'; export const MAX_ACTIVE_COMPOSER_DESKTOP = 3; export const MAX_ACTIVE_COMPOSER_MOBILE = 1; export const getComposerDimension = () => { const root = rootFontSize(); return { width: 40 * root, // 640 height: 40 * root, // 640 gutter: root, // 16 verticalGutter: 0.625 * root, // 10 switchMode: 6.25 * root, // 100 headerHeight: 5 * root, // 80 appBarWidth: 2.8125 * root, // 45 }; }; export type ComposerDimension = ReturnType<typeof getComposerDimension>; const COMPOSER_NARROW_STYLES = { position: 'fixed', '--top-custom': 0, '--bottom-custom': 0, '--left-custom': 0, '--right-custom': 0, '--h-custom': 'auto', '--w-custom': 'auto', }; export const computeLeftPosition = ( { width, gutter }: ComposerDimension, index: number, count: number, windowWidth: number ) => { const neededWidth = width * count + gutter * (count + 1); let rightPosition: number; if (neededWidth < windowWidth) { rightPosition = width * index + gutter * (index + 1); } else { const widthToDivide = windowWidth - gutter * 2 - width; const share = widthToDivide / (count - 1); rightPosition = gutter + share * index; } // Prevent negative value if (rightPosition < 0) { rightPosition = gutter; } return windowWidth - width - rightPosition; }; const computeHeight = ({ height, verticalGutter, headerHeight }: ComposerDimension, windowHeight: number) => { const maxHeight = windowHeight - verticalGutter - headerHeight; return maxHeight > height ? height : maxHeight; }; interface ComputeComposerStyleOptions { composerDimension: ReturnType<typeof getComposerDimension>; // Composer index index: number; // Number of composer opened count: number; minimized: boolean; maximized: boolean; isNarrow: boolean; drawerOffset: number; } interface ComputeComposerStyleReturns { style: Record<string, string | number>; customClasses?: string; } export const computeComposerStyle = ({ composerDimension, index, count, minimized, maximized, isNarrow, drawerOffset, }: ComputeComposerStyleOptions): ComputeComposerStyleReturns => { // Use window.innerWidth and innerHeight instead of useWindowSize to avoid composer cut off issue (CLIENT-4854) const windowHeight = window.innerHeight; const windowWidth = window.innerWidth - drawerOffset; let style: Record<string, string | number> = { '--left-custom': `${computeLeftPosition(composerDimension, index, count, windowWidth)}px`, computeHeight: `${computeHeight(composerDimension, windowHeight)}px`, }; if (isNarrow) { style = COMPOSER_NARROW_STYLES; } else if (minimized) { style['--h-custom'] = '2.5em'; } else if (maximized) { const composerWidth = windowWidth - composerDimension.gutter - composerDimension.appBarWidth; style['--left-custom'] = `${windowWidth - composerWidth - composerDimension.gutter}px`; style['--w-custom'] = `${composerWidth}px`; style['--h-custom'] = `${windowHeight - composerDimension.verticalGutter * 2}px`; } return { style, customClasses: getCustomSizingClasses(style) }; }; export const shouldBeMaximized = (composerDimension: ComposerDimension, windowHeight: number) => { const { height, switchMode } = getComposerDimension(); return windowHeight < height - switchMode; };
3,790
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/conversation.ts
import { ConversationState } from '../logic/conversations/conversationsTypes'; import { Conversation } from '../models/conversation'; type LabelValue = 'NumMessages' | 'NumUnread' | 'Time' | 'Size' | 'NumAttachments'; type LabelContextValue = | 'ContextNumMessages' | 'ContextNumUnread' | 'ContextTime' | 'ContextSize' | 'ContextNumAttachments'; export const getSenders = ({ Senders = [] }: Conversation) => Senders; export const getRecipients = ({ Recipients = [] }: Conversation) => Recipients; export const getConversationContextValue = ( conversation: Conversation | undefined, value: LabelValue, labelID: string | undefined ) => { const matchingLabel = conversation?.Labels?.find((label) => label.ID === labelID); const matchingValue = matchingLabel?.[`Context${value}` as LabelContextValue]; if (matchingValue !== undefined) { return matchingValue; } if (conversation?.[value] !== undefined) { return conversation[value] as number; } return 0; }; export const getNumAttachments = (conversation: Conversation | undefined) => conversation?.NumAttachments || 0; export const hasAttachments = (conversation: Conversation | undefined) => getNumAttachments(conversation) > 0; export const getNumUnread = (conversation: Conversation | undefined, labelID: string | undefined) => getConversationContextValue(conversation, 'NumUnread', labelID); export const isUnread = (conversation: Conversation | undefined, labelID: string | undefined) => getNumUnread(conversation, labelID) !== 0; export const getNumMessages = (conversation: Conversation | undefined, labelID: string | undefined) => getConversationContextValue(conversation, 'NumMessages', labelID); export const getTime = (conversation: Conversation | undefined, labelID: string | undefined) => getConversationContextValue(conversation, 'Time', labelID); export const getSize = (conversation: Conversation | undefined, labelID: string | undefined) => getConversationContextValue(conversation, 'Size', labelID); /** * Returns a map of boolean with all labels on the conversation and for each true if all messages have the label and false if not */ export const getLabelIDs = (conversation: Conversation | undefined, contextLabelID: string | undefined) => { const contextNumMessages = getNumMessages(conversation, contextLabelID); return ( conversation?.Labels?.reduce<{ [labelID: string]: boolean | undefined }>((acc, label) => { acc[label.ID] = label.ContextNumMessages === contextNumMessages; return acc; }, {}) || {} ); }; export const mergeConversations = ( reference: ConversationState | undefined, data: Partial<ConversationState> ): ConversationState => { return { ...reference, ...data, Conversation: !!reference?.Conversation || !!data.Conversation ? ({ ...reference?.Conversation, ...data.Conversation } as Conversation) : undefined, errors: { ...reference?.errors, ...data.errors }, } as ConversationState; };
3,791
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/counter.test.ts
import { MAILBOX_LABEL_IDS } from '@proton/shared/lib/constants'; import { LabelCount } from '@proton/shared/lib/interfaces/Label'; import { Message } from '@proton/shared/lib/interfaces/mail/Message'; import { getCountersByLabelId, updateCounters, updateCountersForMarkAs } from './counter'; describe('counters', () => { describe('updateCounters', () => { it('should update counters', () => { const message = { Unread: 1, ConversationID: 'ConversationID' } as Message; const counters = [ { LabelID: MAILBOX_LABEL_IDS.INBOX, Total: 1, Unread: 1 }, { LabelID: MAILBOX_LABEL_IDS.ARCHIVE, Total: 0, Unread: 0 }, ] as LabelCount[]; const changes = { [MAILBOX_LABEL_IDS.ARCHIVE]: true, [MAILBOX_LABEL_IDS.INBOX]: false }; const newCounters = updateCounters(message, counters, changes); const inboxCounter = newCounters.find(({ LabelID }) => LabelID === MAILBOX_LABEL_IDS.INBOX); const archiveCounter = newCounters.find(({ LabelID }) => LabelID === MAILBOX_LABEL_IDS.ARCHIVE); expect(inboxCounter?.Total).toEqual(0); expect(inboxCounter?.Unread).toEqual(0); expect(archiveCounter?.Total).toEqual(1); expect(archiveCounter?.Unread).toEqual(1); }); it('should not change unmodifiable label', () => { const message = { ConversationID: 'ConversationID' } as Message; const counters = [] as LabelCount[]; const changes = { [MAILBOX_LABEL_IDS.ALL_DRAFTS]: false, [MAILBOX_LABEL_IDS.ALL_SENT]: false, [MAILBOX_LABEL_IDS.ALL_MAIL]: false, }; const newCounters = updateCounters(message, counters, changes); const allDraftsCounter = newCounters.some(({ LabelID }) => LabelID === MAILBOX_LABEL_IDS.ALL_DRAFTS); const allSentCounter = newCounters.some(({ LabelID }) => LabelID === MAILBOX_LABEL_IDS.ALL_SENT); const allMailCounter = newCounters.some(({ LabelID }) => LabelID === MAILBOX_LABEL_IDS.ALL_MAIL); expect(allDraftsCounter).toEqual(false); expect(allSentCounter).toEqual(false); expect(allMailCounter).toEqual(false); }); it('should not change unread counter for trash location', () => { const message = { Unread: 1, ConversationID: 'ConversationID' } as Message; const counters = [] as LabelCount[]; const changes = { [MAILBOX_LABEL_IDS.TRASH]: true }; const newCounters = updateCounters(message, counters, changes); const trashCounter = newCounters.find(({ LabelID }) => LabelID === MAILBOX_LABEL_IDS.TRASH); expect(trashCounter?.Total).toEqual(1); expect(trashCounter?.Unread).toEqual(0); }); }); describe('updateCountersForMarkAs', () => { const LabelIDs = [MAILBOX_LABEL_IDS.INBOX, MAILBOX_LABEL_IDS.ARCHIVE]; it('should update counters for read an unread message', () => { const before = { Unread: 1, ConversationID: 'ConversationID', LabelIDs } as Message; const after = { Unread: 0, ConversationID: 'ConversationID', LabelIDs } as Message; const counters = [ { LabelID: MAILBOX_LABEL_IDS.INBOX, Total: 1, Unread: 1 }, { LabelID: MAILBOX_LABEL_IDS.ARCHIVE, Total: 1, Unread: 1 }, ] as LabelCount[]; const newCounters = updateCountersForMarkAs(before, after, counters); const inboxCounter = newCounters.find(({ LabelID }) => LabelID === MAILBOX_LABEL_IDS.INBOX); const archiveCounter = newCounters.find(({ LabelID }) => LabelID === MAILBOX_LABEL_IDS.ARCHIVE); expect(inboxCounter?.Total).toEqual(1); expect(inboxCounter?.Unread).toEqual(0); expect(archiveCounter?.Total).toEqual(1); expect(archiveCounter?.Unread).toEqual(0); }); it('should not update counters for read an read message', () => { const before = { Unread: 0, ConversationID: 'ConversationID', LabelIDs } as Message; const after = { Unread: 0, ConversationID: 'ConversationID', LabelIDs } as Message; const counters = [ { LabelID: MAILBOX_LABEL_IDS.INBOX, Total: 1, Unread: 0 }, { LabelID: MAILBOX_LABEL_IDS.ARCHIVE, Total: 1, Unread: 0 }, ] as LabelCount[]; const newCounters = updateCountersForMarkAs(before, after, counters); const inboxCounter = newCounters.find(({ LabelID }) => LabelID === MAILBOX_LABEL_IDS.INBOX); const archiveCounter = newCounters.find(({ LabelID }) => LabelID === MAILBOX_LABEL_IDS.ARCHIVE); expect(inboxCounter?.Total).toEqual(1); expect(inboxCounter?.Unread).toEqual(0); expect(archiveCounter?.Total).toEqual(1); expect(archiveCounter?.Unread).toEqual(0); }); it('should update counters for unread an read message', () => { const before = { Unread: 0, ConversationID: 'ConversationID', LabelIDs } as Message; const after = { Unread: 1, ConversationID: 'ConversationID', LabelIDs } as Message; const counters = [ { LabelID: MAILBOX_LABEL_IDS.INBOX, Total: 1, Unread: 0 }, { LabelID: MAILBOX_LABEL_IDS.ARCHIVE, Total: 1, Unread: 0 }, ] as LabelCount[]; const newCounters = updateCountersForMarkAs(before, after, counters); const inboxCounter = newCounters.find(({ LabelID }) => LabelID === MAILBOX_LABEL_IDS.INBOX); const archiveCounter = newCounters.find(({ LabelID }) => LabelID === MAILBOX_LABEL_IDS.ARCHIVE); expect(inboxCounter?.Total).toEqual(1); expect(inboxCounter?.Unread).toEqual(1); expect(archiveCounter?.Total).toEqual(1); expect(archiveCounter?.Unread).toEqual(1); }); it('should not update counters for unread an unread message', () => { const before = { Unread: 1, ConversationID: 'ConversationID', LabelIDs } as Message; const after = { Unread: 1, ConversationID: 'ConversationID', LabelIDs } as Message; const counters = [ { LabelID: MAILBOX_LABEL_IDS.INBOX, Total: 1, Unread: 1 }, { LabelID: MAILBOX_LABEL_IDS.ARCHIVE, Total: 1, Unread: 1 }, ] as LabelCount[]; const newCounters = updateCountersForMarkAs(before, after, counters); const inboxCounter = newCounters.find(({ LabelID }) => LabelID === MAILBOX_LABEL_IDS.INBOX); const archiveCounter = newCounters.find(({ LabelID }) => LabelID === MAILBOX_LABEL_IDS.ARCHIVE); expect(inboxCounter?.Total).toEqual(1); expect(inboxCounter?.Unread).toEqual(1); expect(archiveCounter?.Total).toEqual(1); expect(archiveCounter?.Unread).toEqual(1); }); it('should not update counters where the message is not', () => { const before = { Unread: 1, ConversationID: 'ConversationID', LabelIDs: ['anyID'] } as Message; const after = { Unread: 0, ConversationID: 'ConversationID', LabelIDs: ['anyID'] } as Message; const counters = [ { LabelID: MAILBOX_LABEL_IDS.INBOX, Total: 1, Unread: 1 }, { LabelID: MAILBOX_LABEL_IDS.ARCHIVE, Total: 1, Unread: 1 }, ] as LabelCount[]; const newCounters = updateCountersForMarkAs(before, after, counters); const inboxCounter = newCounters.find(({ LabelID }) => LabelID === MAILBOX_LABEL_IDS.INBOX); const archiveCounter = newCounters.find(({ LabelID }) => LabelID === MAILBOX_LABEL_IDS.ARCHIVE); expect(inboxCounter?.Total).toEqual(1); expect(inboxCounter?.Unread).toEqual(1); expect(archiveCounter?.Total).toEqual(1); expect(archiveCounter?.Unread).toEqual(1); }); }); describe('getCountersByLabelId', () => { it('should return a map of counters by labelId', () => { const counters: LabelCount[] = [ { LabelID: MAILBOX_LABEL_IDS.INBOX, Total: 1, Unread: 1 }, { LabelID: MAILBOX_LABEL_IDS.OUTBOX, Total: 3, Unread: 0 }, { LabelID: MAILBOX_LABEL_IDS.SPAM, Total: 12, Unread: 0 }, { LabelID: MAILBOX_LABEL_IDS.ARCHIVE, Total: 0, Unread: 0 }, ]; expect(getCountersByLabelId(counters)).toEqual({ [MAILBOX_LABEL_IDS.INBOX]: { LabelID: MAILBOX_LABEL_IDS.INBOX, Total: 1, Unread: 1 }, [MAILBOX_LABEL_IDS.OUTBOX]: { LabelID: MAILBOX_LABEL_IDS.OUTBOX, Total: 3, Unread: 0 }, [MAILBOX_LABEL_IDS.SPAM]: { LabelID: MAILBOX_LABEL_IDS.SPAM, Total: 12, Unread: 0 }, [MAILBOX_LABEL_IDS.ARCHIVE]: { LabelID: MAILBOX_LABEL_IDS.ARCHIVE, Total: 0, Unread: 0 }, }); }); }); });
3,792
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/counter.ts
import { toMap } from '@proton/shared/lib/helpers/object'; import { LabelCount } from '@proton/shared/lib/interfaces'; import { Element } from '../models/element'; import { hasLabel, isUnread as testIsUnread } from './elements'; import { LabelChanges, isAutoRead, isUnmodifiableByUser } from './labels'; export const replaceCounter = (counters: LabelCount[], counter: LabelCount) => counters.map((existingCounter: any) => { if (existingCounter.LabelID === counter.LabelID) { return counter; } return existingCounter; }); const fromMapToArray = (countersMap: { [labelID: string]: LabelCount }) => Object.entries(countersMap).map(([, counter]) => counter); export const updateCounters = (element: Element, counters: LabelCount[], changes: LabelChanges) => { const countersMap = Object.entries(changes).reduce((acc, [labelID, action]) => { if (isUnmodifiableByUser(labelID)) { return acc; } acc[labelID] = acc[labelID] || { Total: 0, Unread: 0, LabelID: labelID }; const isUnread = testIsUnread(element, labelID); if (action) { acc[labelID].Total = (acc[labelID].Total || 0) + 1; if (isUnread && !isAutoRead(labelID)) { acc[labelID].Unread = (acc[labelID].Unread || 0) + 1; } } else { acc[labelID].Total = (acc[labelID].Total || 0) - 1; if ( isUnread && // Should not exists on paper but some optimistic inconsistency can lead to this point !isAutoRead(labelID) ) { acc[labelID].Unread = (acc[labelID].Unread || 0) - 1; } } return acc; }, toMap(counters, 'LabelID')); return fromMapToArray(countersMap); }; export const updateCountersForMarkAs = (elementBefore: Element, elementAfter: Element, counters: LabelCount[]) => { return counters.map((counter) => { if (!hasLabel(elementBefore, counter.LabelID || '')) { return counter; } const unreadBefore = testIsUnread(elementBefore, counter.LabelID); const unreadAfter = testIsUnread(elementAfter, counter.LabelID); let Unread = counter.Unread || 0; if (unreadBefore && !unreadAfter) { Unread -= 1; } if (!unreadBefore && unreadAfter) { Unread += 1; } return { ...counter, Unread }; }); }; export const getCountersByLabelId = (counters: LabelCount[] = []) => counters.reduce( (acc: { [labelID: string]: LabelCount }, current) => ({ ...acc, ...(current.LabelID && { [current.LabelID]: current }), }), {} );
3,793
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/date.test.ts
import { formatDateToHuman, formatDistanceToNow, formatFileNameDate, formatFullDate, formatScheduledTimeString, formatSimpleDate, } from './date'; describe('formatSimpleDate', () => { afterEach(() => { jest.useRealTimers(); }); it('should return today date correctly formatted', function () { // Sunday 1 2023 const fakeNow = new Date(2023, 0, 1, 10, 0, 0); jest.useFakeTimers().setSystemTime(fakeNow.getTime()); const expected = '10:00 AM'; expect(formatSimpleDate(fakeNow)).toEqual(expected); }); it('should return yesterday date correctly formatted', () => { // Monday 2 2023 const fakeNow = new Date(2023, 0, 2, 10, 0, 0); // Sunday 1 2023 const yesterday = new Date(2023, 0, 1, 10, 0, 0); jest.useFakeTimers().setSystemTime(fakeNow.getTime()); const expected = 'Yesterday'; expect(formatSimpleDate(yesterday)).toEqual(expected); }); it('should return is this week date correctly formatted', function () { // Monday 2 2023 const fakeNow = new Date(2023, 0, 2, 10, 0, 0); // Wednesday 4 2023 const inTheWeek = new Date(2023, 0, 4, 10, 0, 0); jest.useFakeTimers().setSystemTime(fakeNow.getTime()); const expected = 'Wednesday'; expect(formatSimpleDate(inTheWeek)).toEqual(expected); }); it('should return a normal date correctly formatted', () => { // Sunday 1 2023 const fakeNow = new Date(2023, 0, 1, 10, 0, 0); // Tuesday 10 2023 const inTheWeek = new Date(2023, 0, 10, 10, 0, 0); jest.useFakeTimers().setSystemTime(fakeNow.getTime()); const expected = 'Jan 10, 2023'; expect(formatSimpleDate(inTheWeek)).toEqual(expected); }); }); describe('formatFullDate', () => { it('should format the date with the correct format', () => { // Sunday 1 2023 const date = new Date(2023, 0, 1, 10, 0, 0); const expected = 'Sunday, January 1st, 2023 at 10:00 AM'; expect(formatFullDate(date)).toEqual(expected); }); }); describe('formatDistanceToNow', () => { afterEach(() => { jest.useRealTimers(); }); it('should format distance date', () => { // Sunday 1 2023 const fakeNow = new Date(2023, 0, 1, 10, 0, 0); // Saturday 1 2022 const lastyear = new Date(2022, 0, 1, 10, 0, 0); jest.useFakeTimers().setSystemTime(fakeNow.getTime()); const expected = 'about 1 year ago'; expect(formatDistanceToNow(lastyear)).toEqual(expected); }); }); describe('formatFileNameDate', () => { it('should format the date in a filename format', () => { // Sunday 1 2023 const date = new Date(2023, 0, 1, 10, 0, 0); const expected = '2023-01-01T'; expect(formatFileNameDate(date)).toMatch(expected); }); }); describe('formatScheduledTimeString', () => { it('should format scheduled time string', () => { // Sunday 1 2023 const date = new Date(2023, 0, 1, 10, 0, 0); const expected = '10:00 AM'; expect(formatScheduledTimeString(date)).toEqual(expected); }); }); describe('formatDateToHuman', () => { it('should format date to human format', function () { // Sunday 1 2023 const date = new Date(2023, 0, 1, 10, 0, 0); const expected = { dateString: 'Sunday, January 1st, 2023', formattedTime: '10:00 AM', }; expect(formatDateToHuman(date)).toEqual(expected); }); });
3,794
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/date.ts
import { formatDistanceToNow as dateFnsFormatDistanceToNow, format, isThisWeek, isToday, isYesterday } from 'date-fns'; import { c } from 'ttag'; import { dateLocale } from '@proton/shared/lib/i18n'; export const formatSimpleDate = (date: Date) => { if (isToday(date)) { return format(date, 'p', { locale: dateLocale }); } if (isYesterday(date)) { return c('Time').t`Yesterday`; } if (isThisWeek(date)) { return format(date, 'EEEE', { locale: dateLocale }); } return format(date, 'PP', { locale: dateLocale }); }; export const formatFullDate = (date: Date) => format(date, 'PPPPp', { locale: dateLocale }); export const formatDistanceToNow = (date: Date) => dateFnsFormatDistanceToNow(date, { locale: dateLocale, addSuffix: true }); export const formatFileNameDate = (date: Date) => format(date, "yyyy-MM-dd'T'HH_mm_ssxxx", { locale: dateLocale }); export const formatScheduledTimeString = (date: Date | number) => { return format(date, 'p', { locale: dateLocale }); }; export const formatDateToHuman = (date: Date | number) => { return { dateString: format(date, 'PPPP', { locale: dateLocale }), formattedTime: formatScheduledTimeString(date), }; };
3,795
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/dedent.ts
/** * Clean template * @link {https://gist.github.com/dhoko/4b0c20e66c8a3f1aa431} */ export const dedentTpl = (callSite: TemplateStringsArray, ...args: string[]) => { function format(str = '') { let size = -1; return str.replace(/\n(\s+)/g, (m, m1) => { if (size < 0) { size = m1.replace(/\t/g, ' ').length; } return `\n${m1.slice(Math.min(m1.length, size))}`; }); } // TODO: Could this append with TS? // if (typeof callSite === 'string') { // return format(callSite); // } // if (typeof callSite === 'function') { // return (...args: string[]) => format(callSite(...args)); // } const output = callSite .slice(0, args.length + 1) .map((text, i) => (i === 0 ? '' : args[i - 1]) + text) .join(''); return format(output); };
3,796
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/displaySignature.js
import { VERIFICATION_STATUS } from '@proton/shared/lib/mail/constants'; import { inSigningPeriod, isAuto, isImported } from '@proton/shared/lib/mail/messages'; const { SIGNED_AND_INVALID, SIGNED_AND_VALID, NOT_SIGNED } = VERIFICATION_STATUS; /** * Some complicated logic after internal discussions. * This function returns whether we should display a lock with check / warning (indicating the signature status) * or we just display a lock. * The following logic is applied: * 1. Old SENT messages (not imported, not autoresponse) are not signed * 2. If a SENT message has been correctly verified, a lonesome lock is displayed, unaccompanied by its check * (because we don't consciously do key pinning here) * 3. If a SENT message doesn't have a signature, but should have, we display a warning. A SENT message should have a signature if: * - it is not an autoreply AND * - it is not an import AND * - it is send after the time when we started signing all messages * 4. If a message fails the signature check, we display a warning * 5. If a (non-sent) message has been correctly verified, we display a check. * 6. Else we just display the appropriate lock. * - this happens when there is no signature or it hasn't been verified (meaning unverified SENT message fall in this case). * This logic is caused by sent message's signatures always being verified without requiring the user to enable key pinning * (key pinning for your own keys happens as a consequence of our authentication method). * Thus we don't want to display this check for people that don't understand key pinning, but still keep the * same security. * @return {() => boolean} whether to display the signature status */ export const displaySignatureStatus = ({ data: message = {}, verified = 0 }) => { // TODO: const isSentByMe = message.isSentByMe(); const isSentByMe = false; // Rule 4 + 5 + 6 for non-SENT messages if (!isSentByMe) { return verified === SIGNED_AND_INVALID || verified === SIGNED_AND_VALID; } // SENT messages const imported = isImported(message.data); const auto = isAuto(message.data); const period = inSigningPeriod(message.data.Time); // Rule 1: if (!auto && !imported && !period) { return false; } // Rule 2: if (verified === SIGNED_AND_VALID) { return false; } // Rule 3: if (verified === NOT_SIGNED && !auto && !imported && period) { // warning return true; } // Rule 4 + 6: return verified === SIGNED_AND_INVALID; };
3,797
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/dom.test.ts
import { isElement, isHTMLEmpty, matches, parseInDiv } from './dom'; describe('isElement', () => { it('should be an element', () => { const el = document.createElement('p'); expect(isElement(el)).toBeTruthy(); }); it('should not be an element', () => { const el = null; expect(isElement(el)).toBeFalsy(); }); }); describe('matches', () => { it('should match a selector', () => { const link = document.createElement('a'); link.setAttribute('href', '#link'); expect(matches(link, '[href^="#"]')).toBeTruthy(); }); }); describe('parseInDiv', () => { it('should add the content in a div', () => { const content = 'This is some content'; const result = parseInDiv(content); expect(result.innerHTML).toEqual(content); }); }); describe('isHTMLEmpty', () => { it('should be an empty element', () => { const html1 = ''; const html2 = ' '; expect(isHTMLEmpty(html1)).toBeTruthy(); expect(isHTMLEmpty(html2)).toBeTruthy(); }); it('should not be an empty element', () => { const html1 = 'hello'; const html2 = ' hello'; expect(isHTMLEmpty(html1)).toBeFalsy(); expect(isHTMLEmpty(html2)).toBeFalsy(); }); }); describe('createErrorHandler', () => {});
3,798
0
petrpan-code/ProtonMail/WebClients/applications/mail/src/app
petrpan-code/ProtonMail/WebClients/applications/mail/src/app/helpers/dom.ts
/** * Returns whether the element is a node. * See {@link https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType} */ export const isElement = (node: Node | null) => node && node.nodeType === 1; export const matches = (element: Element, selector: string) => (element.matches || (element as any).msMatchesSelector).call(element, selector); export const parseInDiv = (content: string) => { const div = document.createElement('div'); div.innerHTML = content; return div; }; /** * Check if a HTML content is considered empty */ export const isHTMLEmpty = (html: string) => { if (!html) { return true; } const div = document.createElement('div'); div.innerHTML = html; return div.textContent?.trim() === '' && div.querySelectorAll('img').length === 0; }; // https://github.com/chimurai/http-proxy-middleware/issues/237#issue-294034608 export const createErrorHandler = (reject: (error: Error) => void) => { return (event: any) => { const error = new Error(`Failed to load ${event?.target?.src}`); (error as any).event = event; reject(error); }; }; export const preloadImage = async (url: string) => new Promise((resolve, reject) => { const img = document.createElement('img'); img.src = url; img.onload = resolve; img.onerror = createErrorHandler(reject); });
3,799