index
int64
0
0
repo_id
stringlengths
16
181
file_path
stringlengths
28
270
content
stringlengths
1
11.6M
__index_level_0__
int64
0
10k
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/modals/SelectEmailsModal.tsx
import { ChangeEvent, useEffect, useState } from 'react'; import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms'; import { Contact, ContactEmail } from '@proton/shared/lib/interfaces/contacts'; import isTruthy from '@proton/utils/isTruthy'; import { Alert, Checkbox, Field, Label, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, Row, } from '../../../components'; import { useContactGroups } from '../../../hooks'; import useContactEmails from '../../../hooks/useContactEmails'; export interface SelectEmailsProps { groupIDs: string[]; // contacts selected contacts: Contact[]; onLock?: (lock: boolean) => void; } interface SelectEmailsResolver { // only submit checked contactEmails (Array<Object>) onResolve: (value: ContactEmail[]) => void; onReject: () => void; } type Props = SelectEmailsProps & SelectEmailsResolver & ModalProps; type CheckableContact = ContactEmail & { isChecked?: boolean }; /** * Modal to select contact emails and add them to a contact group */ const SelectEmailsModal = ({ contacts, groupIDs, onSubmit, onLock, onResolve, onReject, ...rest }: Props) => { const [contactGroups] = useContactGroups(); const [allContactEmails = []] = useContactEmails(); const groups = groupIDs.map((groupID) => contactGroups?.find((group) => group.ID === groupID)).filter(isTruthy); useEffect(() => { onLock?.(true); return () => onLock?.(false); }, []); const [model, setModel] = useState( contacts.map((contact) => { const contactEmails: CheckableContact[] = allContactEmails .filter(({ ContactID }) => ContactID === contact.ID) .map((contactEmail) => ({ ...contactEmail, // isChecked by default if the email has already all groups isChecked: groups.every((group) => contactEmail.LabelIDs.includes(group.ID)), })); // If none are checked, check the first one by default const noneChecked = contactEmails.every((contactEmail) => contactEmail.isChecked === false); if (noneChecked && contactEmails.length > 0) { contactEmails[0].isChecked = true; } return { ...contact, contactEmails }; }) ); const handleSubmit = () => { const toSubmit = model.reduce((acc, contact) => { contact.contactEmails.forEach(({ isChecked, ...contactEmail }: CheckableContact) => { if (isChecked) { acc.push(contactEmail); } }); return acc; }, [] as CheckableContact[]); onResolve(toSubmit); rest.onClose?.(); }; const handleCheck = (contactID: string, contactEmailID: string) => ({ target }: ChangeEvent<HTMLInputElement>) => { const copy = [...model]; const contactIndex = model.findIndex(({ ID }) => ID === contactID); const contactEmailIndex = model[contactIndex].contactEmails.findIndex( ({ ID }: ContactEmail) => ID === contactEmailID ); copy[contactIndex].contactEmails[contactEmailIndex].isChecked = target.checked; setModel(copy); }; const isSingleContact = contacts.length === 1; const isSingleGroup = groups.length === 1; const contactName = contacts[0].Name; const contactCount = contacts.length; const groupName = groups[0].Name; const groupCount = groups.length; const title = isSingleGroup ? c('Title').t`Add to ${groupName}` : c('Title').ngettext(msgid`Add to ${groupCount} group`, `Add to ${groupCount} groups`, groupCount); const contactText = isSingleContact ? c('Info').t`${contactName} contains multiple email addresses.` : // "<number> contacts contain..." The singular will not be used, the contact name will be used instead c('Info').ngettext( msgid`${contactCount} contact contains multiple email addresses.`, `${contactCount} contacts contain multiple email addresses.`, contactCount ); const groupText = isSingleGroup ? c('Info').t`Please select which email address or addresses to add to ${groupName}.` : // "... to add to <number> groups" The singular will not be used, the group name will be used instead c('Info').ngettext( msgid`Please select which email address or addresses to add to ${groupCount} group.`, `Please select which email address or addresses to add to ${groupCount} groups.`, groupCount ); return ( <ModalTwo size="large" {...rest}> <ModalTwoHeader title={title} /> <ModalTwoContent> <Alert className="mb-4"> {contactText} <br /> {groupText} </Alert> {model .filter(({ contactEmails = [] }) => contactEmails.length > 1) // Only display contact with multiple emails .map(({ ID: contactID, Name, contactEmails = [] }) => { return ( <Row key={contactID} className="border-bottom"> {!isSingleContact && <Label className="text-semibold pt-0">{Name}</Label>} <Field className="flex flex-column w-full"> {contactEmails.map(({ ID: contactEmailID, Email, isChecked }: CheckableContact) => { return ( <label key={contactEmailID} className="mb-4" htmlFor={contactEmailID}> <Checkbox id={contactEmailID} checked={isChecked} className="mr-2" onChange={handleCheck(contactID, contactEmailID)} /> <span>{Email}</span> </label> ); })} </Field> </Row> ); })} </ModalTwoContent> <ModalTwoFooter> <Button onClick={onReject}>{c('Action').t`Cancel`}</Button> <Button color="norm" onClick={handleSubmit}>{c('Action').t`Apply`}</Button> </ModalTwoFooter> </ModalTwo> ); }; export default SelectEmailsModal;
6,100
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/selector/ContactSelectorEmptyContacts.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import noContactsImg from '@proton/styles/assets/img/illustrations/no-contacts.svg'; import noop from '@proton/utils/noop'; import { ContactEditProps } from '../edit/ContactEditModal'; interface Props { onClose?: () => void; onEdit: (props: ContactEditProps) => void; } const ContactSelectorEmptyContacts = ({ onEdit, onClose = noop }: Props) => { const title = c('Error message').t`No results found`; const handleClick = () => { onEdit({}); onClose(); }; return ( <div className="flex flex-column flex-align-items-center flex-item-fluid p-2"> <span className="mb-4">{c('Error message') .t`You do not have any contact yet. Start by creating a new contact`}</span> <img src={noContactsImg} alt={title} className="p-4 mb-4" /> <Button color="norm" onClick={handleClick}>{c('Action').t`Create new contact`}</Button> </div> ); }; export default ContactSelectorEmptyContacts;
6,101
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/selector/ContactSelectorEmptyResults.tsx
import { c } from 'ttag'; import noResultsImg from '@proton/styles/assets/img/illustrations/empty-search.svg'; import { UnderlineButton } from '../../../components'; interface Props { query?: string; onClearSearch: () => void; } const ContactSelectorEmptyResults = ({ query = '', onClearSearch }: Props) => { const title = c('Error message').t`No results found for "${query}"`; const button = ( <UnderlineButton key="button" className="text-bold p-0" onClick={onClearSearch}> {c('Action').t`clear it`} </UnderlineButton> ); return ( <div className="flex flex-column flex-align-items-center flex-item-fluid p-2"> <h2>{title}</h2> <img src={noResultsImg} alt={title} className="px-4 pb-4 mb-4" /> <span>{c('Info').jt`You can either update your search query or ${button}`}</span> </div> ); }; export default ContactSelectorEmptyResults;
6,102
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/selector/ContactSelectorList.tsx
import { CSSProperties, ReactNode, useRef } from 'react'; import { AutoSizer, List } from 'react-virtualized'; import { DENSITY } from '@proton/shared/lib/constants'; import { UserSettings } from '@proton/shared/lib/interfaces/UserSettings'; import clsx from '@proton/utils/clsx'; interface Props { rowCount: number; userSettings: UserSettings; contactRowHeightComfort?: number; contactRowHeightCompact?: number; rowRenderer: ({ index, style, key }: { index: number; style: CSSProperties; key: string }) => ReactNode; className?: string; } const ContactSelectorList = ({ rowCount, contactRowHeightComfort = 54, contactRowHeightCompact = 46, rowRenderer, className = '', userSettings, }: Props) => { const listRef = useRef(null); const containerRef = useRef(null); const isCompactView = userSettings.Density === DENSITY.COMPACT; return ( <div ref={containerRef} className={clsx(['h-custom', className])} style={{ '--h-custom': `18.75rem` }}> <AutoSizer> {({ height, width }) => ( <List className="contact-list outline-none" ref={listRef} rowRenderer={rowRenderer} rowCount={rowCount} height={height} width={width - 1} rowHeight={isCompactView ? contactRowHeightCompact : contactRowHeightComfort} /> )} </AutoSizer> </div> ); }; export default ContactSelectorList;
6,103
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/selector/ContactSelectorModal.scss
.contact-list { .ReactVirtualized__Grid__innerScrollContainer { border-inline-end: 0; } } .contact-list-row { user-select: none; border-block-end: 1px solid var(--border-norm); &--selected { background: var(--background-strong); } }
6,104
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/selector/ContactSelectorModal.tsx
import { ChangeEvent, FormEvent, useEffect, useMemo, useRef, useState } from 'react'; import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms'; import { toMap } from '@proton/shared/lib/helpers/object'; import { normalize } from '@proton/shared/lib/helpers/string'; import { Recipient } from '@proton/shared/lib/interfaces/Address'; import { ContactEmail, ContactGroup } from '@proton/shared/lib/interfaces/contacts/Contact'; import clsx from '@proton/utils/clsx'; import { Checkbox, Form, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, Option, SearchInput, SelectTwo, } from '../../../components'; import { useActiveBreakpoint, useContactEmailsSortedByName, useUserSettings } from '../../../hooks'; import { useContactGroups } from '../../../hooks/useCategories'; import { ContactEditProps } from '../edit/ContactEditModal'; import ContactSelectorEmptyContacts from './ContactSelectorEmptyContacts'; import ContactSelectorEmptyResults from './ContactSelectorEmptyResults'; import ContactSelectorList from './ContactSelectorList'; import ContactSelectorRow from './ContactSelectorRow'; import './ContactSelectorModal.scss'; const convertContactToRecipient = ({ Name, ContactID, Email }: ContactEmail) => ({ Name, ContactID, Address: Email, }); export interface ContactSelectorProps { inputValue: any; onGroupDetails: (contactGroupID: string) => void; onEdit: (props: ContactEditProps) => void; } interface ContactSelectorResolver { onResolve: (recipients: Recipient[]) => void; onReject: () => void; } const allContactsGroup: Pick<ContactGroup, 'Name' | 'ID'> = { ID: 'default', Name: c('Label').t`All contacts`, }; type Props = ContactSelectorProps & ContactSelectorResolver & ModalProps; const ContactSelectorModal = ({ onResolve, onReject, inputValue, onGroupDetails, onEdit, ...rest }: Props) => { const { isNarrow } = useActiveBreakpoint(); const searchInputRef = useRef<HTMLInputElement>(null); const [contactEmails, loadingContactEmails] = useContactEmailsSortedByName(); const [userSettings, loadingUserSettings] = useUserSettings(); const [contactGroups = [], loadingContactGroups] = useContactGroups(); const [selectedGroup, setSelectedGroup] = useState<string>(allContactsGroup.ID); const contactGroupsWithDefault = [allContactsGroup, ...contactGroups]; const emailsFromInput = inputValue.map((e: any) => e.Address); const contactGroupsMap = toMap(contactGroups); const initialCheckedContactEmailsMap = contactEmails.reduce( (acc: { [key: string]: boolean }, contactEmail: ContactEmail) => { acc[contactEmail.ID] = emailsFromInput.includes(contactEmail.Email); return acc; }, Object.create(null) ); const [searchValue, setSearchValue] = useState(''); const [lastCheckedID, setLastCheckedID] = useState(''); const [isAllChecked, setIsAllChecked] = useState(false); const [filteredContactEmails, setFilteredContactEmails] = useState(contactEmails); const [checkedContactEmailMap, setCheckedContactEmailMap] = useState<{ [key: string]: boolean }>( initialCheckedContactEmailsMap ); const [checkedContactEmails, setCheckedContactEmails] = useState<ContactEmail[]>([]); const totalChecked = checkedContactEmails.length; const loading = loadingContactEmails || loadingUserSettings || loadingContactGroups; const toggleCheckAll = (checked: boolean) => { const update = filteredContactEmails.reduce((acc: { [key: string]: boolean }, contactEmail: ContactEmail) => { acc[contactEmail.ID] = checked; return acc; }, Object.create(null)); setCheckedContactEmailMap({ ...checkedContactEmailMap, ...update }); }; const onCheck = (checkedIDs: string[] = [], checked = false) => { const update = checkedIDs.reduce((acc, checkedID) => { acc[checkedID] = checked; return acc; }, Object.create(null)); setCheckedContactEmailMap({ ...checkedContactEmailMap, ...update }); }; const handleCheckAll = (e: ChangeEvent<HTMLInputElement>) => toggleCheckAll(e.target.checked); const handleCheck = (e: ChangeEvent<HTMLInputElement>, checkedID: string) => { const { target, nativeEvent, }: { target: EventTarget & HTMLInputElement; nativeEvent: Event & { shiftKey?: boolean }; } = e; const checkedIDs = checkedID ? [checkedID] : []; if (lastCheckedID && nativeEvent.shiftKey) { const start = filteredContactEmails.findIndex((c: ContactEmail) => c.ID === checkedID); const end = filteredContactEmails.findIndex((c: ContactEmail) => c.ID === lastCheckedID); checkedIDs.push( ...filteredContactEmails .slice(Math.min(start, end), Math.max(start, end) + 1) .map((c: ContactEmail) => c.ID) ); } if (checkedID) { setLastCheckedID(checkedID); onCheck(checkedIDs, target.checked); } }; const handleClearSearch = () => { setSearchValue(''); searchInputRef?.current?.focus(); }; const searchFilter = (c: ContactEmail) => { const tokenizedQuery = normalize(searchValue, true).split(' '); const groupNameTokens = c.LabelIDs.reduce((acc: string[], labelId) => { const tokenized = normalize(contactGroupsMap[labelId].Name, true).split(' '); return [...acc, ...tokenized]; }, []); return ( tokenizedQuery.some((token) => normalize(c.Name, true).includes(token)) || tokenizedQuery.some((token) => normalize(c.Email, true).includes(token)) || tokenizedQuery.some((token) => groupNameTokens.some((g) => g.includes(token))) ); }; const filterContactsByGroup = useMemo(() => { const filteredContacts = contactEmails; if (selectedGroup === allContactsGroup.ID) { return filteredContacts; } return filteredContacts.filter((contact: ContactEmail) => contact.LabelIDs.includes(selectedGroup)); }, [selectedGroup]); useEffect(() => { searchInputRef?.current?.focus(); }, []); useEffect(() => { setLastCheckedID(''); setFilteredContactEmails(filterContactsByGroup.filter(searchFilter)); }, [searchValue, selectedGroup]); useEffect(() => { setCheckedContactEmails(contactEmails.filter((c: ContactEmail) => !!checkedContactEmailMap[c.ID])); }, [checkedContactEmailMap]); useEffect(() => { setIsAllChecked( !!filteredContactEmails.length && filteredContactEmails.every((c: ContactEmail) => !!checkedContactEmailMap[c.ID]) ); }, [filteredContactEmails, checkedContactEmailMap]); const handleSearchValue = (value: string) => setSearchValue(value); const handleSubmit = (event: FormEvent) => { event.stopPropagation(); event.preventDefault(); onResolve(checkedContactEmails.map(convertContactToRecipient)); rest.onClose?.(); }; const actionText = totalChecked === 1 ? c('Action').t`Insert contact` : c('Action').ngettext( msgid`Insert ${totalChecked} contact`, `Insert ${totalChecked} contacts`, totalChecked ); return ( <ModalTwo size="large" as={Form} onSubmit={handleSubmit} data-testid="modal:contactlist" {...rest}> <ModalTwoHeader title={c('Title').t`Insert contacts`} /> <ModalTwoContent> {!contactEmails.length ? ( <ContactSelectorEmptyContacts onClose={rest.onClose} onEdit={onEdit} /> ) : ( <> <div className={clsx(['mb-2 flex flex-nowrap gap-4', isNarrow && 'flex-column'])}> <div className="flex-item-grow-2"> <SearchInput ref={searchInputRef} value={searchValue} onChange={handleSearchValue} placeholder={c('Placeholder').t`Search name, email or group`} /> </div> <div className={clsx([!isNarrow && 'w-1/3'])}> <SelectTwo onChange={({ value }) => setSelectedGroup(value)} value={selectedGroup} disabled={loadingContactGroups} > {contactGroupsWithDefault.map((group) => ( <Option key={group.ID} value={group.ID} title={group.Name}> {group.Name} </Option> ))} </SelectTwo> </div> </div> {filteredContactEmails.length ? ( <> {!isNarrow && ( <div className="flex flex-nowrap flex-item-fluid contact-list-row p-4"> <div> <Checkbox className="w-full h-full" checked={isAllChecked} onChange={handleCheckAll} /> </div> <div className="flex flex-item-fluid flex-align-self-center"> <div className="w-custom pl-4" style={{ '--w-custom': '45%' }}> <strong className="text-uppercase">{c('Label').t`Name`}</strong> </div> <div className="flex-item-fluid"> <strong className="text-uppercase">{c('Label').t`Email`}</strong> </div> </div> </div> )} <ContactSelectorList rowCount={filteredContactEmails.length} userSettings={userSettings} className={clsx([isNarrow && 'mt-4'])} rowRenderer={({ index, style }) => ( <ContactSelectorRow onCheck={handleCheck} style={style} key={filteredContactEmails[index].ID} contact={filteredContactEmails[index]} checked={!!checkedContactEmailMap[filteredContactEmails[index].ID]} isNarrow={isNarrow} /> )} /> </> ) : ( <ContactSelectorEmptyResults onClearSearch={handleClearSearch} query={searchValue} /> )} </> )} </ModalTwoContent> <ModalTwoFooter> <Button type="button" onClick={rest.onClose} disabled={loading}> {c('Action').t`Cancel`} </Button> {contactEmails.length ? ( <Button color="norm" loading={loading} type="submit" disabled={!totalChecked} data-testid="modal:contactlist:submit" > {actionText} </Button> ) : null} </ModalTwoFooter> </ModalTwo> ); }; export default ContactSelectorModal;
6,105
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/selector/ContactSelectorRow.tsx
import { CSSProperties, ChangeEvent } from 'react'; import { ContactEmail } from '@proton/shared/lib/interfaces/contacts/Contact'; import clsx from '@proton/utils/clsx'; import { Checkbox } from '../../../components'; interface Props { style: CSSProperties; onCheck: (e: ChangeEvent<HTMLInputElement>, contactID: string) => void; contact: ContactEmail; checked: boolean; isNarrow: boolean; } const ContactSelectorRow = ({ style, onCheck, contact, checked, isNarrow }: Props) => { return ( <div style={style} className="flex"> <div className={clsx([ 'flex flex-nowrap flex-item-fluid h-full my-auto contact-list-row px-4', checked && 'contact-list-row--selected', ])} > <Checkbox labelProps={{ 'data-testid': `contact-checkbox-${contact.Email}` }} className="flex-nowrap w-full h-full" checked={checked} onChange={(e) => onCheck(e, contact.ID)} aria-describedby={contact.ID} id={contact.ID} > <div className={clsx([ 'flex-item-fluid flex-align-items-center max-w-full h-full', !isNarrow && 'flex', ])} > <div className={clsx(['pl-4 flex', !isNarrow && 'w-custom'])} style={!isNarrow ? { '--w-custom': '45%' } : undefined} > <span className="inline-block text-ellipsis max-w-full pr-4">{contact.Name}</span> </div> <div className="flex-item-fluid flex pl-4 md:pl-0"> <span className="inline-block text-ellipsis max-w-full pr-4">{contact.Email}</span> </div> </div> </Checkbox> </div> </div> ); }; export default ContactSelectorRow;
6,106
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/tests/render.tsx
import { ReactElement, ReactNode } from 'react'; import { Router } from 'react-router'; import { RenderResult, render as originalRender } from '@testing-library/react'; import { MemoryHistory, createMemoryHistory } from 'history'; import { CryptoApiInterface, VERIFICATION_STATUS } from '@proton/crypto'; import { APPS, CONTACT_CARD_TYPE } from '@proton/shared/lib/constants'; import { prepareVCardContact } from '@proton/shared/lib/contacts/encrypt'; import { parseToVCard } from '@proton/shared/lib/contacts/vcard'; import createCache from '@proton/shared/lib/helpers/cache'; import { ProtonConfig } from '@proton/shared/lib/interfaces'; import { STATUS } from '@proton/shared/lib/models/cache'; import { resolvedRequest } from 'proton-mail/src/app/helpers/test/cache'; import ApiContext from '../../api/apiContext'; import { CacheProvider } from '../../cache'; import { ConfigProvider } from '../../config'; import EventManagerContext from '../../eventManager/context'; import FeaturesProvider from '../../features/FeaturesProvider'; import { NotificationsContext } from '../../notifications'; import ContactProvider from '../ContactProvider'; export const mockedCryptoApi = { encryptMessage: jest.fn().mockImplementation(async ({ textData }) => ({ signature: `mocked signature over ${textData}`, message: `${textData}`, })), decryptMessage: jest.fn().mockImplementation(async ({ armoredMessage }) => ({ data: `${armoredMessage}`, verified: VERIFICATION_STATUS.SIGNED_AND_VALID, })), signMessage: jest .fn() .mockImplementation(async ({ textData }) => ({ signature: `mocked signature over ${textData}` })), verifyMessage: jest.fn().mockImplementation(async () => ({ verified: VERIFICATION_STATUS.SIGNED_AND_VALID, signatureTimestamp: new Date(), })), } as any as CryptoApiInterface; window.ResizeObserver = jest.fn(() => ({ observe: jest.fn(), unobserve: jest.fn(), disconnect: jest.fn(), })); // https://github.com/nickcolley/jest-axe/issues/147#issuecomment-758804533 const { getComputedStyle } = window; window.getComputedStyle = (elt) => getComputedStyle(elt); export const cache = createCache(); export const api = jest.fn(); export const notificationManager = { createNotification: jest.fn(), removeNotification: jest.fn(), hideNotification: jest.fn(), removeDuplicate: jest.fn(), clearNotifications: jest.fn(), setOffset: jest.fn(), }; let history: MemoryHistory; export const getHistory = () => history; export const resetHistory = () => { history = createMemoryHistory({ initialEntries: ['/inbox'] }); }; resetHistory(); export const config = { APP_NAME: APPS.PROTONMAIL, APP_VERSION: 'test-version', DATE_VERSION: 'test-date-version', } as ProtonConfig; export const eventManager = { start: jest.fn(), stop: jest.fn(), call: jest.fn(), subscribe: jest.fn(), } as any; const TestProvider = ({ children }: { children: ReactNode }) => ( <ConfigProvider config={config}> <ApiContext.Provider value={api}> <CacheProvider cache={cache}> <FeaturesProvider> <NotificationsContext.Provider value={notificationManager}> <EventManagerContext.Provider value={eventManager}> <Router history={history}> <ContactProvider>{children}</ContactProvider> </Router> </EventManagerContext.Provider> </NotificationsContext.Provider> </FeaturesProvider> </CacheProvider> </ApiContext.Provider> </ConfigProvider> ); export const addToCache = (key: string, value: any) => { cache.set(key, resolvedRequest(value)); }; export const minimalCache = () => { cache.set('User', { status: STATUS.RESOLVED, value: {} }); cache.set('MailSettings', { status: STATUS.RESOLVED, value: {} }); cache.set('Addresses', { status: STATUS.RESOLVED, value: [] }); cache.set('Labels', { status: STATUS.RESOLVED, value: [] }); cache.set('Contacts', { status: STATUS.RESOLVED, value: [] }); cache.set('ContactEmails', { status: STATUS.RESOLVED, value: [] }); cache.set('USER_KEYS', { status: STATUS.RESOLVED, value: [{ publicKey: {}, privateKey: {} }], }); }; export const render = (ui: ReactElement, useMinimalCache = true): RenderResult => { if (useMinimalCache) { minimalCache(); } const result = originalRender(<TestProvider>{ui}</TestProvider>); const rerender = async (ui: ReactElement) => { result.rerender(<TestProvider>{ui}</TestProvider>); }; return { ...result, rerender }; }; export const clearAll = () => { jest.clearAllMocks(); cache.clear(); }; export const prepareContact = async (vcard: string) => { const vCardContact = parseToVCard(vcard); const Cards = await prepareVCardContact(vCardContact, { privateKey: {} as any, publicKey: {} as any }); return Cards; }; export const getCard = (cards: any[], encrypted = false) => { return cards.find( ({ Type }: { Type: CONTACT_CARD_TYPE }) => Type === (encrypted ? CONTACT_CARD_TYPE.ENCRYPTED_AND_SIGNED : CONTACT_CARD_TYPE.SIGNED) ).Data; };
6,107
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/view/ContactDetailsModal.test.tsx
import { CryptoProxy } from '@proton/crypto'; import { SHOW_IMAGES } from '@proton/shared/lib/mail/mailSettings'; import { addToCache, api, clearAll, minimalCache, mockedCryptoApi, prepareContact, render } from '../tests/render'; import ContactDetailsModal, { ContactDetailsProps } from './ContactDetailsModal'; jest.mock('../../../hooks/useConfig', () => () => ({ API_URL: 'api' })); describe('ContactDetailsModal', () => { const props: ContactDetailsProps = { contactID: 'ContactID', onEdit: jest.fn(), onDelete: jest.fn(), onMailTo: jest.fn(), onEmailSettings: jest.fn(), onGroupDetails: jest.fn(), onGroupEdit: jest.fn(), onUpgrade: jest.fn(), onDecryptionError: jest.fn(), onSignatureError: jest.fn(), }; beforeAll(() => { CryptoProxy.setEndpoint(mockedCryptoApi); }); beforeEach(clearAll); afterAll(async () => { await CryptoProxy.releaseEndpoint(); }); it('should show basic contact informations', async () => { const vcard = `BEGIN:VCARD VERSION:4.0 UID:urn:uuid:4fbe8971-0bc3-424c-9c26-36c3e1eff6b1 FN:J. Doe FN:FN2 EMAIL:jdoe@example.com NOTE:TestNote ADR:1;2;3;4;5;6;7 ADR:;;;;;;testadr TEL:testtel PHOTO:https://example.com/myphoto.jpg END:VCARD`; const { Cards } = await prepareContact(vcard); api.mockImplementation(async (args: any): Promise<any> => { if (args.url === 'contacts/v4/contacts/ContactID') { return { Contact: { ID: 'ID', ContactID: 'ContactID', Cards } }; } }); minimalCache(); addToCache('MailSettings', { HideRemoteImages: SHOW_IMAGES.HIDE }); const { findByText } = render(<ContactDetailsModal open={true} {...props} />, false); await findByText('J. Doe'); await findByText('Load image'); await findByText('FN2'); await findByText('jdoe@example.com'); await findByText('testtel'); await findByText(/3.*2.*6, 4.*1.*5, 7/); await findByText('testadr'); await findByText('TestNote'); }); });
6,108
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/view/ContactDetailsModal.tsx
import { useEffect, useMemo, useRef } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { CRYPTO_PROCESSING_TYPES } from '@proton/shared/lib/contacts/constants'; import { singleExport } from '@proton/shared/lib/contacts/helpers/export'; import { toMap } from '@proton/shared/lib/helpers/object'; import { ContactEmail } from '@proton/shared/lib/interfaces/contacts'; import { VCardContact } from '@proton/shared/lib/interfaces/contacts/VCard'; import { Icon, Loader, Tooltip } from '../../../components'; import { ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader } from '../../../components/modalTwo'; import { useAddresses, useContactGroups, useMailSettings, useNotifications, useUserKeys } from '../../../hooks'; import { useLinkHandler } from '../../../hooks/useLinkHandler'; import ErrorBoundary from '../../app/ErrorBoundary'; import GenericError from '../../error/GenericError'; import { ContactEditProps } from '../edit/ContactEditModal'; import { ContactEmailSettingsProps } from '../email/ContactEmailSettingsModal'; import { ContactGroupEditProps } from '../group/ContactGroupEditModal'; import useContact from '../hooks/useContact'; import useContactList from '../hooks/useContactList'; import useVCardContact from '../hooks/useVCardContact'; import { ContactDeleteProps } from '../modals/ContactDeleteModal'; import ContactView from './ContactView'; export interface ContactDetailsProps { contactID: string; onMailTo?: (src: string) => void; onEdit: (props: ContactEditProps) => void; onDelete: (props: ContactDeleteProps) => void; onEmailSettings: (props: ContactEmailSettingsProps) => void; onGroupDetails: (contactGroupID: string) => void; onGroupEdit: (props: ContactGroupEditProps) => void; onUpgrade: () => void; onSignatureError: (contactID: string) => void; onDecryptionError: (contactID: string) => void; } type Props = ContactDetailsProps & ModalProps; const ContactDetailsModal = ({ contactID, onMailTo, onEdit, onDelete, onEmailSettings, onGroupDetails, onGroupEdit, onUpgrade, onSignatureError, onDecryptionError, ...rest }: Props) => { const { onClose } = rest; const [mailSettings] = useMailSettings(); const [contactGroups = [], loadingContactGroups] = useContactGroups(); const [userKeysList, loadingUserKeys] = useUserKeys(); const [addresses = [], loadingAddresses] = useAddresses(); const { loading: loadingContacts, contactEmailsMap } = useContactList({}); const [contact, loadingContact] = useContact(contactID); const modalRef = useRef<HTMLDivElement>(null); const { createNotification } = useNotifications(); const { modal: linkModal } = useLinkHandler(modalRef, mailSettings, { onMailTo }); const { vCardContact, isLoading: loadingVCard, errors, isVerified, onReload, } = useVCardContact({ contact, userKeysList }); // Close the modal on a click on a mailto, useLinkHandler will open the composer useEffect(() => { const handleClick = (event: MouseEvent) => { const link = (event.target as Element).closest('a'); const src = link?.getAttribute('href'); if (src?.startsWith('mailto:')) { onClose?.(); } }; modalRef.current?.addEventListener('click', handleClick); return () => modalRef.current?.removeEventListener('click', handleClick); }, []); const handleEdit = (newField?: string) => { onEdit({ contactID, vCardContact, newField }); }; const handleDelete = () => { onDelete({ contactIDs: [contactID] }); onClose?.(); }; const handleExport = () => { const hasError = errors?.some( (error) => error instanceof Error || error.type !== CRYPTO_PROCESSING_TYPES.SIGNATURE_NOT_VERIFIED ); if (hasError) { createNotification({ text: c('Error').t`Cannot export this contact`, type: 'error' }); return; } return singleExport(vCardContact as VCardContact); }; const ownAddresses = useMemo(() => addresses.map(({ Email }) => Email), [addresses]); const contactGroupsMap = useMemo(() => toMap(contactGroups), [contactGroups]); const isLoading = loadingContacts || loadingContactGroups || loadingUserKeys || loadingAddresses || loadingContact || loadingVCard; return ( <ModalTwo size="large" className="contacts-modal" data-testid="contact-details-modal" {...rest}> <ModalTwoHeader actions={[ <Tooltip title={c('Action').t`Edit`}> <Button color="weak" shape="ghost" icon onClick={() => handleEdit()} className="inline-flex ml-2" data-testid="contact-details:edit" > <Icon name="pen" alt={c('Action').t`Edit`} /> </Button> </Tooltip>, <Tooltip title={c('Action').t`Export`}> <Button color="weak" shape="ghost" icon onClick={handleExport} className="inline-flex ml-2" data-testid="contact-details:export" > <Icon name="arrow-up-from-square" alt={c('Action').t`Export`} /> </Button> </Tooltip>, <Tooltip title={c('Action').t`Delete`}> <Button color="weak" shape="ghost" icon onClick={handleDelete} className="inline-flex ml-2" data-testid="contact-details:delete" > <Icon name="trash" alt={c('Action').t`Delete`} /> </Button> </Tooltip>, ]} /> <ModalTwoContent> <ErrorBoundary key={contactID} component={<GenericError className="pt-7 view-column-detail flex-item-fluid" />} > <div ref={modalRef}> {isLoading ? ( <Loader /> ) : ( <ContactView vCardContact={vCardContact as VCardContact} contactID={contactID} contactEmails={contactEmailsMap[contactID] as ContactEmail[]} contactGroupsMap={contactGroupsMap} ownAddresses={ownAddresses} errors={errors} isSignatureVerified={isVerified} onReload={onReload} onEdit={handleEdit} onEmailSettings={onEmailSettings} onGroupDetails={onGroupDetails} onGroupEdit={onGroupEdit} onUpgrade={onUpgrade} onSignatureError={onSignatureError} onDecryptionError={onDecryptionError} /> )} </div> {linkModal} </ErrorBoundary> </ModalTwoContent> <ModalTwoFooter> <Button onClick={onClose}>{c('Action').t`Close`}</Button> </ModalTwoFooter> </ModalTwo> ); }; export default ContactDetailsModal;
6,109
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/view/ContactImageSummary.tsx
import { RefObject, useImperativeHandle } from 'react'; import { c } from 'ttag'; import { Tooltip } from '@proton/components/components'; import { getInitials } from '@proton/shared/lib/helpers/string'; import { Icon, Loader } from '../../../components'; import useLoadContactImage from '../../../hooks/useLoadContactImage'; interface Props { photo: string; name: string; loadImageDirectRef: RefObject<() => void>; onToggleLoadDirectBanner: (show: boolean) => void; } const ContactImageSummary = ({ photo, name, loadImageDirectRef, onToggleLoadDirectBanner }: Props) => { const { handleLoadImageDirect, image, setShowAnyway, display } = useLoadContactImage({ photo, onToggleLoadDirectBanner, needsResize: true, }); useImperativeHandle(loadImageDirectRef, () => { return handleLoadImageDirect; }); if (!photo) { return ( <div className="border bg-norm rounded ratio-container-square mb-0"> <span className="inner-ratio-container flex"> <span className="m-auto color-weak h1">{getInitials(name)}</span> </span> </div> ); } const handleClick = () => setShowAnyway(true); const style = { backgroundImage: `url(${image.src})`, backgroundPosition: 'center', backgroundRepeat: 'no-repeat', backgroundSize: 'cover', }; return ( <> {display === 'loading' && ( <div className="ratio-container-square rounded border"> <span className="inner-ratio-container flex"> <Loader /> </span> </div> )} {display === 'loadDirectFailed' && ( <div className="border rounded bg-norm ratio-container-square mb-0"> <span className="inner-ratio-container flex"> <span className="m-auto lh-rg flex flex-column flex-align-items-center"> <Tooltip title={c('Tooltip').t`The image could not be loaded`}> <Icon name="cross-circle" size={24} className="color-danger" /> </Tooltip> </span> </span> </div> )} {display === 'needsLoadDirect' && ( <div className="border rounded bg-norm ratio-container-square mb-0"> <span className="inner-ratio-container flex"> <span className="m-auto lh-rg flex flex-column flex-align-items-center"> <Tooltip title={c('Tooltip').t`The image could not be loaded using proxy`}> <Icon name="file-shapes" size={24} /> </Tooltip> </span> </span> </div> )} {/* For a small image, we have to create a smaller rounded container inside the bigger standard one, and fit the image as background inside it. As container width we must pick the smallest dimension*/} {display === 'smallImageLoaded' && ( <div className="ratio-container-square mb-0"> <span className="inner-ratio-container flex rounded border overflow-hidden"> <div className="m-auto flex w-custom" style={{ '--w-custom': `${Math.min(image.width || 0, image.height || 0)}px` }} > <div className="ratio-container-square" style={style}> <span className="inner-ratio-container" /> </div> </div> </span> </div> )} {/*fit the image in the rounded container as background image*/} {display === 'loaded' && ( <div className="ratio-container-square rounded border" style={style}> <span className="inner-ratio-container" /> </div> )} {display === 'askLoading' && ( <button type="button" className="border rounded bg-norm ratio-container-square mb-0" onClick={handleClick} > <span className="inner-ratio-container flex"> <span className="m-auto lh-rg flex flex-column flex-align-items-center"> <Icon name="file-shapes" /> <div className="m-2 color-primary">{c('Action').t`Load image`}</div> </span> </span> </button> )} </> ); }; export default ContactImageSummary;
6,110
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/view/ContactLabelProperty.tsx
import { HTMLAttributes } from 'react'; import { getAllFieldLabels } from '@proton/shared/lib/helpers/contacts'; import clsx from '@proton/utils/clsx'; interface Props extends HTMLAttributes<HTMLDivElement> { field: string; type?: string; } const ContactLabelProperty = ({ field, type, className, ...rest }: Props) => { const labels: { [key: string]: string } = getAllFieldLabels(); const label: string = ['bday', 'anniversary'].includes(field) ? labels[field] : labels[type || ''] || type || labels[field]; return ( <div className={clsx(['text-capitalize text-semibold text-ellipsis', className])} {...rest} title={label}> {label} </div> ); }; export default ContactLabelProperty;
6,111
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/view/ContactSummary.scss
@import '~@proton/styles/scss/lib'; // ????? .contactsummary-list-item { block-size: rem(25); } @include media('<=small') { .contact-modal-select { max-inline-size: calc(100% - 3.3em); } }
6,112
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/view/ContactSummary.tsx
import React, { useRef, useState } from 'react'; import { c } from 'ttag'; import { getSortedProperties } from '@proton/shared/lib/contacts/properties'; import { validateEmailAddress } from '@proton/shared/lib/helpers/email'; import { formatImage } from '@proton/shared/lib/helpers/image'; import { VCardContact, VCardProperty, VcardNValue } from '@proton/shared/lib/interfaces/contacts/VCard'; import clsx from '@proton/utils/clsx'; import useActiveBreakpoint from '../../../hooks/useActiveBreakpoint'; import LoadRemoteImageBanner from '../../banner/LoadRemoteImageBanner'; import ContactImageSummary from './ContactImageSummary'; import './ContactSummary.scss'; interface Props { vCardContact: VCardContact; leftBlockWidth?: string; style?: React.CSSProperties; } const ContactSummary = ({ vCardContact, leftBlockWidth = 'w-1/3', style }: Props) => { const { isNarrow } = useActiveBreakpoint(); const [showLoadImageBanner, setShowLoadImageBanner] = useState(false); const loadImageDirectRef = useRef<() => void>(null); const photo = formatImage(getSortedProperties(vCardContact, 'photo')[0]?.value || ''); const displayName = getSortedProperties(vCardContact, 'fn')[0]?.value || ''; const nameProperty = getSortedProperties(vCardContact, 'n')[0] as VCardProperty<VcardNValue>; const givenName = nameProperty?.value?.givenNames.join(' ').trim() || ''; const familyName = nameProperty?.value?.familyNames.join(' ').trim() || ''; const computedName = `${givenName} ${familyName}`; const nameIsEmail = validateEmailAddress(displayName); return ( <> {showLoadImageBanner && ( <LoadRemoteImageBanner onClick={() => loadImageDirectRef.current?.()} text={c('Action').t`Image could not be loaded with tracker protection.`} tooltip={c('Action').t`Image will be loaded without a proxy`} actionText={c('Action').t`Load`} /> )} <div className={clsx( 'contactsummary-container my-4', !isNarrow && 'flex flex-nowrap flex-align-items-center' )} > <div className={clsx( 'text-center contactsummary-photo-container pt-2 mb-2 md:mb-0 mx-auto md:mx-0', leftBlockWidth )} style={style} > <ContactImageSummary photo={photo} name={displayName} loadImageDirectRef={loadImageDirectRef} onToggleLoadDirectBanner={setShowLoadImageBanner} /> </div> <div className="contactsummary-contact-name-container pl-0 md:pl-7 flex-column"> <h2 className={clsx( 'contactsummary-contact-name text-center md:text-right mb-4 md:mb-0 flex-item-fluid text-bold text-ellipsis-two-lines w-full', // Several email addresses are a single word but too long, for this case, we break at any char nameIsEmail && 'text-break' )} title={displayName} > {displayName} </h2> <h3 className="color-weak text-ellipsis" style={{ whiteSpace: 'break-spaces' }}> {computedName} </h3> </div> </div> </> ); }; export default ContactSummary;
6,113
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/view/ContactView.scss
@import '~@proton/styles/scss/lib'; .contact-view { &-actions { margin-block-start: -0.5em; } .contactsummary-contact-name { font-size: em(24); line-height: 1.333; // design wanted 32px for line-height flex: 1 1 auto; margin-block-end: 0.25em; } /* * Make summary elements wrap at 1500 */ @include media('<=xlarge') { .contactsummary-contact-name-container { display: flex; flex-direction: column; } .contactsummary-action-buttons { > :first-child { margin-inline-start: 0; } } } /* * triger mobile adaptation around 1000px because... not enough space */ @include media('>medium', '<=large') { .contactsummary-container { display: block; } .contactsummary-photo-container { inline-size: auto; margin-block-end: 0.5em; margin-inline: auto; } .contactsummary-contact-name-container { padding-inline-start: 0; } .contactsummary-contact-name { margin-block-end: 1em; text-align: center; } .contactsummary-action-buttons { text-align: center; } .contact-view-contents, .contact-view-cta { padding-inline: 0; } .contact-summary-wrapper { margin-inline: 0; } .contact-view-row-left { flex-direction: column; } .contact-view-row-label { max-inline-size: 100%; } .contact-view-row-content { flex-basis: auto; padding-inline-start: 0; } } }
6,114
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/view/ContactView.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { CryptoProcessingError } from '@proton/shared/lib/contacts/decrypt'; import { ContactEmail, ContactGroup } from '@proton/shared/lib/interfaces/contacts/Contact'; import { VCardContact } from '@proton/shared/lib/interfaces/contacts/VCard'; import { ContactEmailSettingsProps } from '../email/ContactEmailSettingsModal'; import { ContactGroupEditProps } from '../group/ContactGroupEditModal'; import ContactSummary from './ContactSummary'; import ContactViewErrors from './ContactViewErrors'; import ContactViewAdrs from './properties/ContactViewAdrs'; import ContactViewBdy from './properties/ContactViewBdy'; import ContactViewEmails from './properties/ContactViewEmails'; import ContactViewFns from './properties/ContactViewFns'; import ContactViewNotes from './properties/ContactViewNotes'; import ContactViewOthers from './properties/ContactViewOthers'; import ContactViewTels from './properties/ContactViewTels'; import './ContactView.scss'; interface Props { vCardContact: VCardContact; contactID: string; contactEmails: ContactEmail[]; contactGroupsMap: { [contactGroupID: string]: ContactGroup }; ownAddresses: string[]; errors?: (CryptoProcessingError | Error)[]; isSignatureVerified?: boolean; onReload: () => void; onEdit: (newField?: string) => void; onEmailSettings: (props: ContactEmailSettingsProps) => void; onGroupDetails: (contactGroupID: string) => void; onGroupEdit: (props: ContactGroupEditProps) => void; onUpgrade: () => void; onSignatureError: (contactID: string) => void; onDecryptionError: (contactID: string) => void; isPreview?: boolean; } const ShortcutButton = ({ onClick, label }: { onClick: () => void; label: string }) => ( <div className="mb-2"> <Button shape="outline" size="small" onClick={onClick}> {label} </Button> </div> ); const ContactView = ({ vCardContact, contactID, contactEmails, contactGroupsMap, ownAddresses, errors, isSignatureVerified = false, onReload, onEdit, onEmailSettings, onGroupDetails, onGroupEdit, onUpgrade, onSignatureError, onDecryptionError, isPreview = false, }: Props) => { const hasEmail = vCardContact.email?.length || 0 > 0; const hasTel = vCardContact.tel?.length || 0 > 0; const hasAdr = vCardContact.adr?.length || 0 > 0; const hasNote = vCardContact.note?.length || 0 > 0; const hasBday = Boolean(vCardContact.bday); return ( <div> <div className="contact-summary-wrapper border-bottom pb-4 mb-4"> <ContactSummary vCardContact={vCardContact} leftBlockWidth="w-auto md:w-full max-w-custom" style={{ '--max-w-custom': '6.25rem' }} /> <ContactViewErrors errors={errors} onReload={onReload} contactID={contactID} onSignatureError={onSignatureError} onDecryptionError={onDecryptionError} isPreview={isPreview} /> </div> <div> <ContactViewFns vCardContact={vCardContact} isSignatureVerified={isSignatureVerified} /> <ContactViewEmails vCardContact={vCardContact} isSignatureVerified={isSignatureVerified} isPreview={isPreview} contactEmails={contactEmails} contactGroupsMap={contactGroupsMap} ownAddresses={ownAddresses} contactID={contactID} onEmailSettings={onEmailSettings} onGroupDetails={onGroupDetails} onUpgrade={onUpgrade} onGroupEdit={onGroupEdit} /> <ContactViewTels vCardContact={vCardContact} isSignatureVerified={isSignatureVerified} /> <ContactViewAdrs vCardContact={vCardContact} isSignatureVerified={isSignatureVerified} /> <ContactViewBdy vCardContact={vCardContact} isSignatureVerified={isSignatureVerified} /> <ContactViewNotes vCardContact={vCardContact} isSignatureVerified={isSignatureVerified} /> <ContactViewOthers vCardContact={vCardContact} isSignatureVerified={isSignatureVerified} /> </div> {!isPreview ? ( <div className="mt-6"> {hasEmail ? null : ( <ShortcutButton onClick={() => onEdit('email')} label={c('Action').t`Add email`} /> )} {hasTel ? null : ( <ShortcutButton onClick={() => onEdit('tel')} label={c('Action').t`Add phone number`} /> )} {hasAdr ? null : ( <ShortcutButton onClick={() => onEdit('adr')} label={c('Action').t`Add address`} /> )} {hasBday ? null : ( <ShortcutButton onClick={() => onEdit('bday')} label={c('Action').t`Add birthday`} /> )} {hasNote ? null : <ShortcutButton onClick={() => onEdit('note')} label={c('Action').t`Add note`} />} </div> ) : null} </div> ); }; export default ContactView;
6,115
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/view/ContactViewErrors.tsx
import { c } from 'ttag'; import { Button, Href } from '@proton/atoms'; import { CRYPTO_PROCESSING_TYPES } from '@proton/shared/lib/contacts/constants'; import { CryptoProcessingError } from '@proton/shared/lib/contacts/decrypt'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import clsx from '@proton/utils/clsx'; import Icon from '../../../components/icon/Icon'; const { SIGNATURE_NOT_VERIFIED, FAIL_TO_READ, FAIL_TO_LOAD, FAIL_TO_DECRYPT } = CRYPTO_PROCESSING_TYPES; const importanceOrder = [FAIL_TO_LOAD, FAIL_TO_READ, FAIL_TO_DECRYPT, SIGNATURE_NOT_VERIFIED]; const matchType = (errors: CryptoProcessingError[], type: CRYPTO_PROCESSING_TYPES) => errors.find((error) => error.type === type); const splitErrors = (errors: (CryptoProcessingError | Error)[]) => { return errors.reduce<{ cryptoErrors: CryptoProcessingError[]; otherErrors: Error[] }>( (acc, error) => { if (error instanceof Error) { acc.otherErrors.push(error); } else { acc.cryptoErrors.push(error); } return acc; }, { cryptoErrors: [], otherErrors: [] } ); }; const selectError = (errors: (CryptoProcessingError | Error)[]) => { const { cryptoErrors, otherErrors } = splitErrors(errors); if (otherErrors.length) { return otherErrors[0]; } return importanceOrder.map((type) => matchType(cryptoErrors, type)).filter(Boolean)[0]; }; const getText = (errorType: CRYPTO_PROCESSING_TYPES) => { switch (errorType) { case FAIL_TO_DECRYPT: return c('Warning').t`The decryption of the encrypted content failed.`; case SIGNATURE_NOT_VERIFIED: return c('Warning').t`The verification of the contact details' signature failed.`; default: return c('Warning').t`The contact failed to load.`; } }; const getButtonText = (errorType: CRYPTO_PROCESSING_TYPES) => { switch (errorType) { case FAIL_TO_DECRYPT: return c('Action').t`Recover data`; case SIGNATURE_NOT_VERIFIED: return c('Action').t`Re-sign`; default: return null; } }; interface Props { contactID: string; errors?: (CryptoProcessingError | Error)[]; onReload: () => void; onSignatureError: (contactID: string) => void; onDecryptionError: (contactID: string) => void; isPreview?: boolean; } const ContactViewErrors = ({ contactID, errors, onReload, onSignatureError, onDecryptionError, isPreview = false, }: Props) => { if (!errors?.length) { return null; } const error = selectError(errors); // Should not happen but satisfy type checking if (!error) { return null; } if (error instanceof Error) { return ( <div className="bg-danger rounded p-2 mt-4 flex flex-nowrap flex-align-items-center"> <Icon name="exclamation-circle" className="flex-item-noshrink my-auto" /> <span className="flex-item-fluid py-2"> {c('Warning').t`The contact data is corrupted and cannot be displayed.`} </span> </div> ); } const isWarning = error.type === SIGNATURE_NOT_VERIFIED; const bgColor = isWarning ? 'bg-warning' : 'bg-danger'; const text = getText(error.type); const buttonText = getButtonText(error.type); const handleDecryptionErrorAction = () => { onDecryptionError(contactID); }; const handleSignatureErrorAction = () => { onSignatureError(contactID); }; const handleAction = () => { if (error.type === FAIL_TO_DECRYPT) { return handleDecryptionErrorAction(); } if (error.type === SIGNATURE_NOT_VERIFIED) { return handleSignatureErrorAction(); } onReload(); }; return ( <div className={clsx([bgColor, 'rounded p-2 mt-4 flex flex-nowrap flex-align-items-center'])}> <Icon name="exclamation-circle" className="flex-item-noshrink my-auto" /> <span className="flex-item-fluid py-2"> <span className="mr-2">{text}</span> <Href className="underline inline-block color-inherit" href={getKnowledgeBaseUrl('/proton-contacts')} >{c('Link').t`Learn more`}</Href> </span> {!isPreview && ( <span className="flex-item-noshrink flex"> <Button size="small" shape="outline" onClick={handleAction}> {buttonText} </Button> </span> )} </div> ); }; export default ContactViewErrors;
6,116
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/view/EncryptedIcon.tsx
import { c } from 'ttag'; import { Icon, Tooltip } from '../../../components'; interface Props { isSignatureVerified: boolean; className: string; } const EncryptedIcon = ({ isSignatureVerified, className = 'flex flex-item-centered' }: Props) => { const tooltipText = isSignatureVerified ? c('Tooltip').t`Encrypted data with verified digital signature` : c('Tooltip').t`Encrypted data`; const iconName = isSignatureVerified ? 'lock-check-filled' : 'lock-filled'; return ( <Tooltip title={tooltipText}> <Icon name={iconName} className={className} /> </Tooltip> ); }; export default EncryptedIcon;
6,117
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/view/RecipientDropdownItem.tsx
import React, { MouseEvent, ReactNode } from 'react'; import { c } from 'ttag'; import { ContactImage, Copy, ProtonBadgeType, useNotifications } from '@proton/components/index'; import { getInitials } from '@proton/shared/lib/helpers/string'; import { Recipient } from '@proton/shared/lib/interfaces'; interface Props { label: string; recipient: Recipient; bimiSelector?: string; closeDropdown: () => void; displaySenderImage: boolean; simple?: boolean; additionalAction?: ReactNode; } const RecipientDropdownItem = ({ displaySenderImage, bimiSelector, label, recipient, closeDropdown, simple = false, additionalAction, }: Props) => { const { createNotification } = useNotifications(); // Label value can contain : // - Contact Name if the recipient is a contact, or Recipient Name or Recipient Address on PM // - Recipient Name or Recipient Address on EO // Recipient might not have a Name or a Contact Name, and by default we put the Address // In this case, we don't want to display the Address field twice const hasName = label !== '' && label !== recipient.Address; const handleCopyEmail = () => { createNotification({ type: 'success', text: c('Success').t`Email address copied to clipboard`, }); closeDropdown(); }; // Prevent closing dropdown if click inside the recipient info const handleClick = (e: MouseEvent) => { e.stopPropagation(); }; return ( <div className="flex flex-nowrap flex-align-items-center p-2" onClick={handleClick}> <span className="item-icon flex flex-item-noshrink rounded mx-2" aria-hidden="true"> <span className="m-auto"> {simple ? ( <>{getInitials(label)}</> ) : ( <ContactImage email={recipient.Address} name={label} className="rounded" bimiSelector={bimiSelector} displaySenderImage={displaySenderImage} /> )} </span> </span> <div className="flex flex-column flex-item-fluid px-2" data-testid="recipient:dropdown-item--contact-name"> <span className="text-ellipsis inline-block max-w-full user-select" title={label}> {label} {!simple && recipient && <ProtonBadgeType recipient={recipient} />} </span> {hasName && ( <span className="color-weak text-ellipsis inline-block max-w-full user-select">{`<${recipient.Address}>`}</span> )} </div> {additionalAction} <Copy value={recipient.Address} className="mr-2 flex-item-noshrink" onCopy={handleCopyEmail} tooltipText={c('Action').t`Copy email to clipboard`} shape="ghost" data-testid="recipient:dropdown-item--copy-address-button" /> </div> ); }; export default RecipientDropdownItem;
6,118
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/view
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/view/properties/ContactViewAdrs.tsx
import { Fragment } from 'react'; import { c } from 'ttag'; import { cleanAddressFromCommas } from '@proton/shared/lib/contacts/helpers/address'; import { getSortedProperties } from '@proton/shared/lib/contacts/properties'; import { VCardAddress, VCardContact, VCardProperty } from '@proton/shared/lib/interfaces/contacts/VCard'; import isTruthy from '@proton/utils/isTruthy'; import { Copy } from '../../../../components'; import { useNotifications } from '../../../../hooks'; import { ContactViewProperties } from './ContactViewProperties'; import ContactViewProperty from './ContactViewProperty'; interface Props { vCardContact: VCardContact; isSignatureVerified?: boolean; } const ContactViewAdrs = ({ vCardContact, isSignatureVerified = false }: Props) => { const { createNotification } = useNotifications(); const adrs: VCardProperty<VCardAddress>[] = getSortedProperties(vCardContact, 'adr'); if (adrs.length === 0) { return null; } return ( <ContactViewProperties> {adrs.map((adr, i) => { const { streetAddress, extendedAddress, postalCode, postOfficeBox, locality, region, country } = cleanAddressFromCommas(adr.value); const lines = [ streetAddress, extendedAddress, [postalCode, locality].filter(isTruthy).join(', '), postOfficeBox, [region, country].filter(isTruthy).join(', '), ].filter(isTruthy); return ( <ContactViewProperty // I have nothing better for the key there // eslint-disable-next-line react/no-array-index-key key={i} field="adr" type={adr.params?.type} isSignatureVerified={isSignatureVerified} > <span className="w-full flex"> <span className="mr-2 flex-item-fluid text-ellipsis"> {lines.map((line, index) => ( // No better key here and should not change in time anyway // eslint-disable-next-line react/no-array-index-key <Fragment key={index}> {line} {index !== lines.length - 1 && <br />} </Fragment> ))} </span> <span className="flex-item-noshrink flex py-1 contact-view-actions h-4"> <Copy className="ml-2 py-2 mt-0.5" value={lines.join(', ')} onCopy={() => { createNotification({ text: c('Success').t`Address copied to clipboard` }); }} /> </span> </span> </ContactViewProperty> ); })} </ContactViewProperties> ); }; export default ContactViewAdrs;
6,119
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/view
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/view/properties/ContactViewBdy.tsx
import { format } from 'date-fns'; import { getSortedProperties } from '@proton/shared/lib/contacts/properties'; import { isDateTextValue, isValidDateValue } from '@proton/shared/lib/contacts/vcard'; import { dateLocale } from '@proton/shared/lib/i18n'; import { VCardContact, VCardDateOrText, VCardProperty } from '@proton/shared/lib/interfaces/contacts/VCard'; import { ContactViewProperties } from './ContactViewProperties'; import ContactViewProperty from './ContactViewProperty'; interface Props { vCardContact: VCardContact; isSignatureVerified?: boolean; } const ContactViewBdy = ({ vCardContact, isSignatureVerified = false }: Props) => { const bdays: VCardProperty<VCardDateOrText>[] = getSortedProperties(vCardContact, 'bday'); if (bdays.length === 0) { return null; } return ( <ContactViewProperties> {bdays.map((bday) => { const dateOrText = bday.value as VCardDateOrText; let formattedBday = null; if (isValidDateValue(dateOrText)) { formattedBday = format(dateOrText.date, 'PP', { locale: dateLocale }); } if (isDateTextValue(dateOrText)) { formattedBday = dateOrText.text; } return ( <ContactViewProperty key={formattedBday} field="bday" type={bday.params?.type} isSignatureVerified={isSignatureVerified} > <span className="mr-2 flex-item-fluid text-ellipsis">{formattedBday}</span> </ContactViewProperty> ); })} </ContactViewProperties> ); }; export default ContactViewBdy;
6,120
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/view
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/view/properties/ContactViewEmails.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { getSortedProperties } from '@proton/shared/lib/contacts/properties'; import { ContactEmail, ContactGroup } from '@proton/shared/lib/interfaces/contacts'; import { VCardContact } from '@proton/shared/lib/interfaces/contacts/VCard'; import { Copy, Icon, Tooltip } from '../../../../components'; import { useNotifications } from '../../../../hooks'; import ContactGroupDropdown from '../../ContactGroupDropdown'; import { ContactEmailSettingsProps } from '../../email/ContactEmailSettingsModal'; import { ContactGroupEditProps } from '../../group/ContactGroupEditModal'; import ContactGroupLabels from '../../group/ContactGroupLabels'; import { ContactViewProperties } from './ContactViewProperties'; import ContactViewProperty from './ContactViewProperty'; interface Props { vCardContact: VCardContact; isSignatureVerified?: boolean; isPreview?: boolean; contactEmails: ContactEmail[]; contactGroupsMap?: { [contactGroupID: string]: ContactGroup }; ownAddresses: string[]; contactID: string; onEmailSettings: (props: ContactEmailSettingsProps) => void; onGroupDetails: (contactGroupID: string, onCloseContactDetailsModal?: () => void) => void; onUpgrade: () => void; onGroupEdit: (props: ContactGroupEditProps) => void; onCloseModal?: () => void; } const ContactViewEmails = ({ vCardContact, isSignatureVerified = false, isPreview = false, contactEmails, contactGroupsMap, ownAddresses, contactID, onEmailSettings, onGroupDetails, onUpgrade, onGroupEdit, onCloseModal, }: Props) => { const { createNotification } = useNotifications(); const emails = getSortedProperties(vCardContact, 'email'); if (emails.length === 0) { return null; } return ( <ContactViewProperties> {emails.map((email, i) => { const contactEmail = contactEmails && contactEmails[i]; const contactGroups = (contactEmail && contactGroupsMap && contactEmail.LabelIDs.map((ID) => contactGroupsMap[ID]).filter(Boolean)) || []; const isOwnAddress = [...ownAddresses].includes(email.value); const handleSettings = () => { onEmailSettings({ contactID, vCardContact, emailProperty: email }); }; return ( <ContactViewProperty // I have nothing better for the key there // eslint-disable-next-line react/no-array-index-key key={i} field="email" type={email.params?.type} isSignatureVerified={isSignatureVerified} > <span className="w-full flex"> <a className="mr-2 flex-item-fluid text-ellipsis" href={`mailto:${email.value}`} title={email.value} > {email.value} </a> <span className="flex-item-noshrink flex py-1 contact-view-actions"> {!isPreview && ( <> <Copy className="ml-2" value={email.value} onCopy={() => { createNotification({ text: c('Success').t`Email address copied to clipboard`, }); }} data-testid={`${email.value}:email-copy`} /> {!isOwnAddress && ( <Tooltip title={c('Title').t`Email settings`}> <Button icon color="weak" shape="outline" className="ml-2" onClick={handleSettings} data-testid={`${email.value}:email-settings`} > <Icon name="cog-wheel" alt={c('Action').t`Email settings`} /> </Button> </Tooltip> )} <ContactGroupDropdown icon color="weak" shape="outline" className="ml-2" contactEmails={[contactEmail]} tooltip={c('Title').t`Contact group`} onGroupEdit={onGroupEdit} onUpgrade={onUpgrade} data-testid={`${email.value}:groups-dropdown`} > <Icon name="users" alt={c('Action').t`Contact group`} /> </ContactGroupDropdown> </> )} </span> </span> {!!contactGroups.length && ( <div className="mt-4"> <ContactGroupLabels className="max-w-full" contactGroups={contactGroups} isStacked={false} onDetails={onGroupDetails} onCloseModal={onCloseModal} /> </div> )} </ContactViewProperty> ); })} </ContactViewProperties> ); }; export default ContactViewEmails;
6,121
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/view
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/view/properties/ContactViewFns.tsx
import { getSortedProperties } from '@proton/shared/lib/contacts/properties'; import { VCardContact } from '@proton/shared/lib/interfaces/contacts/VCard'; import { ContactViewProperties } from './ContactViewProperties'; import ContactViewProperty from './ContactViewProperty'; interface Props { vCardContact: VCardContact; isSignatureVerified?: boolean; } const ContactViewFns = ({ vCardContact, isSignatureVerified = false }: Props) => { const fns = getSortedProperties(vCardContact, 'fn') // First FN is in the summary .slice(1); if (fns.length === 0) { return null; } return ( <ContactViewProperties className="mb-4"> {fns.map((fn, i) => ( <ContactViewProperty // I have nothing better for the key there // eslint-disable-next-line react/no-array-index-key key={i} field="fn" isSignatureVerified={isSignatureVerified} > {fn.value} </ContactViewProperty> ))} </ContactViewProperties> ); }; export default ContactViewFns;
6,122
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/view
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/view/properties/ContactViewNotes.tsx
import { getSortedProperties } from '@proton/shared/lib/contacts/properties'; import { VCardContact, VCardDateOrText, VCardProperty } from '@proton/shared/lib/interfaces/contacts/VCard'; import { ContactViewProperties } from './ContactViewProperties'; import ContactViewProperty from './ContactViewProperty'; interface Props { vCardContact: VCardContact; isSignatureVerified?: boolean; } const ContactViewNotes = ({ vCardContact, isSignatureVerified = false }: Props) => { const notes: VCardProperty<VCardDateOrText>[] = getSortedProperties(vCardContact, 'note'); if (notes.length === 0) { return null; } return ( <ContactViewProperties> {notes.map((note, i) => { const { value } = note; return ( <ContactViewProperty // I have nothing better for the key there // eslint-disable-next-line react/no-array-index-key key={i} field="note" type={note.params?.type} isSignatureVerified={isSignatureVerified} > <span className="mr-2 flex-item-fluid">{value}</span> </ContactViewProperty> ); })} </ContactViewProperties> ); }; export default ContactViewNotes;
6,123
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/view
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/view/properties/ContactViewOthers.tsx
import { format } from 'date-fns'; import { OTHER_INFORMATION_FIELDS } from '@proton/shared/lib/contacts/constants'; import { getSortedProperties } from '@proton/shared/lib/contacts/properties'; import { isDateTextValue, isValidDateValue } from '@proton/shared/lib/contacts/vcard'; import { dateLocale } from '@proton/shared/lib/i18n'; import { VCardContact, VCardDateOrText, VCardGenderValue, VCardOrg, VCardProperty, } from '@proton/shared/lib/interfaces/contacts/VCard'; import isTruthy from '@proton/utils/isTruthy'; import { RemoteImage } from '../../../../components'; import { ContactViewProperties } from './ContactViewProperties'; import ContactViewProperty from './ContactViewProperty'; interface Props { vCardContact: VCardContact; isSignatureVerified?: boolean; } const ContactViewOthers = ({ vCardContact, isSignatureVerified = false }: Props) => { const fields = OTHER_INFORMATION_FIELDS; const properties = fields.flatMap((field) => { let properties = getSortedProperties(vCardContact, field); // First photo is used in the summary if (field === 'photo') { properties = properties.slice(1); } if (field === 'org') { // TODO: move this field to its own `ContactViewOrg` component properties = properties.map((property: VCardProperty<VCardOrg>) => ({ ...property, value: [property.value.organizationalName, ...(property.value.organizationalUnitNames ?? [])] .filter(isTruthy) .join('; '), })); } return properties; }); if (properties.length === 0) { return null; } return ( <ContactViewProperties> {properties.map(({ field, value }, i) => { const getView = () => { if (field === 'url') { // use new root address when the url does not include the protocol (HTTP or HTTPS) const href = value.startsWith('http') || value.startsWith('//') ? value : `//${value}`; return ( <a href={href} target="_blank" rel="noopener noreferrer"> {value} </a> ); } if (field === 'anniversary') { const dateOrText: VCardDateOrText = value; if (isValidDateValue(dateOrText)) { return format(dateOrText.date, 'PP', { locale: dateLocale }); } if (isDateTextValue(dateOrText)) { return dateOrText.text; } return null; } if (field === 'gender') { const genderValue = value as VCardGenderValue; return genderValue.text; } if (field === 'logo' || field === 'photo') { return <RemoteImage src={value} />; } return value; }; return ( <ContactViewProperty // I have nothing better for the key there // eslint-disable-next-line react/no-array-index-key key={i} field={field} isSignatureVerified={isSignatureVerified} > {getView()} </ContactViewProperty> ); })} </ContactViewProperties> ); }; export default ContactViewOthers;
6,124
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/view
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/view/properties/ContactViewProperties.tsx
import { ReactNode } from 'react'; import clsx from '@proton/utils/clsx'; interface Props { className?: string; children: ReactNode; } export const ContactViewProperties = ({ className, children }: Props) => { return <div className={clsx(['border-bottom mb-2 pb-1', className])}>{children}</div>; };
6,125
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/view
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/view/properties/ContactViewProperty.tsx
import { ReactNode } from 'react'; import clsx from '@proton/utils/clsx'; import ContactLabelProperty from '../ContactLabelProperty'; import EncryptedIcon from '../EncryptedIcon'; interface Props { field: string; type?: string; isSignatureVerified: boolean; children: ReactNode; } const ContactViewProperty = ({ field, type, isSignatureVerified, children }: Props) => { return ( <div className="contact-view-row flex flex-nowrap flex-align-items-start mb-4"> <div className={clsx(['contact-view-row-left flex flex-nowrap flex-item-fluid on-mobile-flex-column w-full'])} > <div className={clsx([ 'contact-view-row-label flex-no-min-children w-full md:w-1/5 flex-item-noshrink flex-align-items-start label', ])} > <div className="flex flex-item-noshrink flex-item-fluid flex-align-items-center max-w-full"> <div role="heading" aria-level={3} className="mr-2"> <ContactLabelProperty field={field} type={type} /> </div> {field && ['email', 'fn'].includes(field) ? null : ( <EncryptedIcon className="flex" isSignatureVerified={isSignatureVerified} /> )} </div> </div> <span className={clsx([ 'contact-view-row-content mr-2 flex-item-fluid pt-2 pl-0 md:pl-7', ['note'].includes(field) && 'text-pre-wrap', ])} > {children} </span> </div> </div> ); }; export default ContactViewProperty;
6,126
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/view
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/view/properties/ContactViewTels.tsx
import { c } from 'ttag'; import { getSortedProperties } from '@proton/shared/lib/contacts/properties'; import { VCardContact } from '@proton/shared/lib/interfaces/contacts/VCard'; import { Copy } from '../../../../components'; import { useNotifications } from '../../../../hooks'; import { ContactViewProperties } from './ContactViewProperties'; import ContactViewProperty from './ContactViewProperty'; interface Props { vCardContact: VCardContact; isSignatureVerified?: boolean; } const ContactViewTels = ({ vCardContact, isSignatureVerified = false }: Props) => { const { createNotification } = useNotifications(); const tels = getSortedProperties(vCardContact, 'tel'); if (tels.length === 0) { return null; } return ( <ContactViewProperties> {tels.map((tel, i) => ( <ContactViewProperty // I have nothing better for the key there // eslint-disable-next-line react/no-array-index-key key={i} field="tel" type={tel.params?.type} isSignatureVerified={isSignatureVerified} > <span className="w-full flex"> <a className="mr-2 flex-item-fluid text-ellipsis" href={`tel:${tel.value}`}> {tel.value} </a> <span className=" flex-item-noshrink flex py-1 contact-view-actions h-4"> <Copy className="ml-2 py-2 mt-0.5" value={tel.value} onCopy={() => { createNotification({ text: c('Success').t`Phone number copied to clipboard` }); }} /> </span> </span> </ContactViewProperty> ))} </ContactViewProperties> ); }; export default ContactViewTels;
6,127
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/widget/ContactsWidget.scss
@import '~@proton/styles/scss/lib'; .contacts-widget { --min-width: #{em(500)}; --min-height: #{em(550)}; &-search-container, &-toolbar, .item-container { padding-inline: var(--space-4); } &-tabs { padding-block-start: var(--space-4); margin-inline: var(--space-4); } .ReactVirtualized__Grid__innerScrollContainer { border: 0; } @include media('<=small') { &.dropdown { padding-inline: 5%; } } .item-container { border-radius: 0; margin-inline: 0; padding-block: var(--space-2); &:not(.item-in-drawer) { border-block-end: 1px solid var(--border-weak); } } } .contacts-modal { // Special case otherwise contacts are not properly displayed --size: #{rem(740)}; }
6,128
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/widget/ContactsWidgetContainer.tsx
import { RefObject, useMemo, useState } from 'react'; import { c, msgid } from 'ttag'; import { CircleLoader } from '@proton/atoms'; import { SearchInput, useMailSettings } from '@proton/components'; import { useApi, useNotifications, useUser, useUserKeys } from '@proton/components/hooks'; import { exportContacts } from '@proton/shared/lib/contacts/helpers/export'; import { extractMergeable } from '@proton/shared/lib/contacts/helpers/merge'; import { Recipient } from '@proton/shared/lib/interfaces'; import { ContactEmail } from '@proton/shared/lib/interfaces/contacts'; import { ATTACHMENT_MAX_COUNT } from '@proton/shared/lib/mail/constants'; import { DEFAULT_MAILSETTINGS } from '@proton/shared/lib/mail/mailSettings'; import clsx from '@proton/utils/clsx'; import { ContactEditProps } from '../edit/ContactEditModal'; import { ContactGroupEditProps } from '../group/ContactGroupEditModal'; import useContactList from '../hooks/useContactList'; import ContactsList from '../lists/ContactsList'; import { ContactMergeProps } from '../merge/ContactMergeModal'; import { ContactDeleteProps } from '../modals/ContactDeleteModal'; import { ContactGroupLimitReachedProps } from '../modals/ContactGroupLimitReachedModal'; import { SelectEmailsProps } from '../modals/SelectEmailsModal'; import MergeContactBanner from '../widget/MergeContactBanner'; import ContactsWidgetPlaceholder, { EmptyType } from './ContactsWidgetPlaceholder'; import ContactsWidgetToolbar from './ContactsWidgetToolbar'; import { CustomAction } from './types'; import './ContactsWidget.scss'; interface Props { onClose?: () => void; onCompose?: (recipients: Recipient[], attachments: File[]) => void; onLock?: (lock: boolean) => void; customActions: CustomAction[]; onDetails: (contactID: string) => void; onEdit: (props: ContactEditProps) => void; onDelete: (props: ContactDeleteProps) => void; onImport: () => void; onMerge: (props: ContactMergeProps) => void; onGroupDetails: (contactGroupID: string) => void; onGroupEdit: (props: ContactGroupEditProps) => void; onLimitReached: (props: ContactGroupLimitReachedProps) => void; onUpgrade: () => void; onSelectEmails: (props: SelectEmailsProps) => Promise<ContactEmail[]>; isDrawer?: boolean; searchInputRef?: RefObject<HTMLInputElement>; } const ContactsWidgetContainer = ({ onClose, onCompose, onLock, customActions, onDetails, onEdit, onDelete, onImport, onMerge, onGroupDetails, onGroupEdit, onLimitReached, onUpgrade, onSelectEmails, isDrawer = false, searchInputRef, }: Props) => { const [mailSettings] = useMailSettings(); const [user, loadingUser] = useUser(); const [userKeys] = useUserKeys(); const { createNotification } = useNotifications(); const api = useApi(); const [search, setSearch] = useState(''); const contactList = useContactList({ search, }); const { formattedContacts, checkedIDs, contacts, contactGroupsMap, handleCheck, handleCheckOne, contactEmailsMap, selectedIDs, handleCheckAll, filteredContacts, hasCheckedAllFiltered, loading: loadingContacts, } = contactList; const mergeableContacts = useMemo(() => extractMergeable(formattedContacts), [formattedContacts]); const countMergeableContacts = mergeableContacts.reduce( (acc, mergeableContact) => acc + mergeableContact.length, 0 ); const noEmailsContactIDs = selectedIDs.filter((contactID) => !contactEmailsMap[contactID]?.length); const handleClearSearch = () => { // If done synchronously, button is removed from the dom and the dropdown considers a click outside setTimeout(() => setSearch('')); }; const handleCompose = () => { const maxContacts = mailSettings?.RecipientLimit || DEFAULT_MAILSETTINGS.RecipientLimit; if (selectedIDs.length > maxContacts) { createNotification({ type: 'error', text: c('Error').ngettext( msgid`You can't send a mail to more than ${maxContacts} recipient`, `You can't send a mail to more than ${maxContacts} recipients`, maxContacts ), }); return; } const contactWithEmailIDs = selectedIDs.filter((contactID) => contactEmailsMap[contactID]?.length); if (noEmailsContactIDs.length) { const noEmailsContactNames = noEmailsContactIDs.map( // Looping in all contacts is no really performant but should happen rarely (contactID) => contacts.find((contact) => contact.ID === contactID)?.Name ); const noEmailsContactNamesCount = noEmailsContactNames.length; const noEmailsContactNamesList = noEmailsContactNames.join(', '); const text = c('Error').ngettext( msgid`One of the contacts has no email address: ${noEmailsContactNamesList}`, `Some contacts have no email addresses: ${noEmailsContactNamesList} `, noEmailsContactNamesCount ); createNotification({ type: 'warning', text }); } const contactEmailsOfContacts = contactWithEmailIDs.map( (contactID) => contactEmailsMap[contactID] ) as ContactEmail[][]; const recipients = contactEmailsOfContacts.map((contactEmails) => { const contactEmail = contactEmails[0]; return { Name: contactEmail.Name, Address: contactEmail.Email }; }); onCompose?.(recipients, []); onClose?.(); }; const handleForward = async () => { // We cannot attach more than 100 files to a message const maxAttachments = ATTACHMENT_MAX_COUNT; if (selectedIDs.length > maxAttachments) { createNotification({ type: 'error', text: c('Action').ngettext( msgid`You can't send vCard files of more than ${maxAttachments} contacts`, `You can't send vCard files of more than ${maxAttachments} contacts`, maxAttachments ), }); return; } try { const exportedContacts = await exportContacts(selectedIDs, userKeys, api); const files = exportedContacts.map( ({ name, vcard }) => new File([vcard], name, { type: 'text/plain;charset=utf-8' }) ); onCompose?.([], files); } catch { createNotification({ type: 'error', text: c('Error').t`There was an error when exporting the contacts vCards`, }); } onClose?.(); }; const handleDelete = () => { const deleteAll = selectedIDs.length === contacts.length; onDelete({ contactIDs: selectedIDs, deleteAll, onDelete: () => { if (selectedIDs.length === filteredContacts.length) { setSearch(''); } handleCheckAll(false); }, }); onClose?.(); }; const handleCreate = () => { onEdit({}); onClose?.(); }; const handleImport = () => { onImport(); onClose?.(); }; const handleMerge = (mergeContactsDetected?: boolean) => { const selectedContacts = formattedContacts.filter((contact) => selectedIDs.includes(contact.ID)); const contacts = mergeContactsDetected ? mergeableContacts : [selectedContacts]; const onMerged = () => handleCheckAll(false); onMerge({ contacts, onMerged }); onClose?.(); }; const contactsCount = formattedContacts.length; const contactsLength = contacts ? contacts.length : 0; const selectedContactsLength = selectedIDs.length; const loading = loadingContacts || loadingUser; const showPlaceholder = !loading && !contactsCount; const showList = !loading && !showPlaceholder; return ( <div className="flex flex-column flex-nowrap h-full"> <div className="contacts-widget-search-container flex-item-noshrink"> <label htmlFor="id_contact-widget-search" className="sr-only">{c('Placeholder') .t`Search for name or email`}</label> <SearchInput ref={searchInputRef} autoFocus={!isDrawer} value={search} onChange={setSearch} id="id_contact-widget-search" placeholder={c('Placeholder').t`Name or email address`} /> <span className="sr-only" aria-atomic aria-live="assertive"> {c('Info').ngettext( msgid`${contactsCount} contact found`, `${contactsCount} contacts found`, contactsCount )} </span> </div> <div className="contacts-widget-toolbar py-3 border-bottom border-weak flex-item-noshrink"> <ContactsWidgetToolbar allChecked={hasCheckedAllFiltered} selected={selectedIDs} noEmailsContactCount={noEmailsContactIDs.length} onCheckAll={handleCheckAll} onCompose={onCompose ? handleCompose : undefined} customActions={customActions} contactList={contactList} onForward={handleForward} onCreate={handleCreate} onDelete={handleDelete} onMerge={() => handleMerge(false)} onLimitReached={onLimitReached} onClose={onClose} onLock={onLock} onGroupEdit={onGroupEdit} onUpgrade={onUpgrade} onSelectEmails={onSelectEmails} isDrawer={isDrawer} /> {contactsLength ? ( <p className={clsx( 'text-sm font-semibold m-0 pt-3', selectedContactsLength ? 'color-weak' : 'color-hint' )} > {selectedContactsLength ? // translator: Number of selected contacts out of total number of contacts, e.g. "1/10 contacts selected" c('Info').ngettext( msgid`${selectedContactsLength}/${contactsLength} contact selected`, `${selectedContactsLength}/${contactsLength} contacts selected`, selectedContactsLength ) : // translator: Total number of contact when none are selected, e.g. "10 contacts" c('Info').ngettext( msgid`${contactsLength} contact`, `${contactsLength} contacts`, contactsLength )} </p> ) : null} </div> {showList && countMergeableContacts ? ( <MergeContactBanner onMerge={() => handleMerge(true)} countMergeableContacts={countMergeableContacts} /> ) : null} <div className="flex-item-fluid w-full"> {loading ? ( <div className="flex h-full"> <CircleLoader className="m-auto color-primary" size="large" /> </div> ) : null} {showPlaceholder ? ( <ContactsWidgetPlaceholder type={contactsLength ? EmptyType.Search : EmptyType.All} onClearSearch={handleClearSearch} onCreate={handleCreate} onImport={handleImport} /> ) : null} {showList ? ( <ContactsList contacts={formattedContacts} contactGroupsMap={contactGroupsMap} user={user} onCheckOne={handleCheckOne} isDesktop={false} checkedIDs={checkedIDs} onCheck={handleCheck} onClick={onDetails} activateDrag={false} onGroupDetails={onGroupDetails} isDrawer={isDrawer} onCompose={onCompose} /> ) : null} </div> </div> ); }; export default ContactsWidgetContainer;
6,129
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/widget/ContactsWidgetGroupsContainer.tsx
import { useMemo, useState } from 'react'; import { c, msgid } from 'ttag'; import { CircleLoader } from '@proton/atoms'; import { orderContactGroups } from '@proton/shared/lib/helpers/contactGroups'; import { normalize } from '@proton/shared/lib/helpers/string'; import { Recipient } from '@proton/shared/lib/interfaces'; import { ContactEmail } from '@proton/shared/lib/interfaces/contacts'; import { DEFAULT_MAILSETTINGS } from '@proton/shared/lib/mail/mailSettings'; import { SearchInput } from '../../../components'; import { useContactEmails, useContactGroups, useMailSettings, useNotifications, useUser } from '../../../hooks'; import { useItemsSelection } from '../../items'; import { ContactGroupDeleteProps } from '../group/ContactGroupDeleteModal'; import { ContactGroupEditProps } from '../group/ContactGroupEditModal'; import ContactsGroupsList from '../lists/ContactsGroupsList'; import ContactsWidgetGroupsToolbar from './ContactsWidgetGroupsToolbar'; import ContactsWidgetPlaceholder, { EmptyType } from './ContactsWidgetPlaceholder'; import { CustomAction } from './types'; interface Props { onClose?: () => void; onCompose?: (recipients: Recipient[], attachments: File[]) => void; onImport: () => void; customActions: CustomAction[]; onDetails: (contactGroupID: string) => void; onDelete: (props: ContactGroupDeleteProps) => void; onEdit: (props: ContactGroupEditProps) => void; onUpgrade: () => void; isDrawer?: boolean; } const ContactsWidgetGroupsContainer = ({ onClose, onCompose, onImport, customActions, onDetails, onDelete, onEdit, onUpgrade, isDrawer = false, }: Props) => { const [mailSettings] = useMailSettings(); const { createNotification } = useNotifications(); const [user] = useUser(); const [search, setSearch] = useState(''); const [groups = [], loadingGroups] = useContactGroups(); const orderedGroups = orderContactGroups(groups); const [contactEmails = [], loadingContactEmails] = useContactEmails(); const normalizedSearch = normalize(search); const filteredGroups = useMemo( () => orderedGroups.filter(({ Name }) => normalize(Name).includes(normalizedSearch)), [orderedGroups, normalizedSearch] ); const groupIDs = filteredGroups.map((group) => group.ID); const { checkedIDs, selectedIDs, handleCheckAll, handleCheckOne } = useItemsSelection(undefined, groupIDs, []); const allChecked = checkedIDs.length > 0 && checkedIDs.length === filteredGroups.length; const groupsEmailsMap = useMemo( () => contactEmails.reduce<{ [groupID: string]: ContactEmail[] }>((acc, contactEmail) => { contactEmail.LabelIDs.forEach((labelID) => { if (!acc[labelID]) { acc[labelID] = []; } acc[labelID].push(contactEmail); }); return acc; }, {}), [groups, contactEmails] ); const recipients = selectedIDs .map((selectedID) => { const group = groups.find((group) => group.ID === selectedID); if (groupsEmailsMap[selectedID]) { return groupsEmailsMap[selectedID].map((email) => ({ Name: email.Name, Address: email.Email, Group: group?.Path, })); } return []; }) .flat(); const handleClearSearch = () => { // If done synchronously, button is removed from the dom and the dropdown considers a click outside setTimeout(() => setSearch('')); }; const handleCompose = () => { const maxContacts = mailSettings?.RecipientLimit || DEFAULT_MAILSETTINGS.RecipientLimit; if (recipients.length > maxContacts) { createNotification({ type: 'error', text: c('Error').ngettext( msgid`You can't send a mail to more than ${maxContacts} recipient`, `You can't send a mail to more than ${maxContacts} recipients`, maxContacts ), }); return; } const noContactGroupIDs = selectedIDs.filter((groupID) => !groupsEmailsMap[groupID]?.length); if (noContactGroupIDs.length) { const noContactsGroupNames = noContactGroupIDs.map( // Looping in all groups is no really performant but should happen rarely (groupID) => groups.find((group) => group.ID === groupID)?.Name ); const noContactGroupCount = noContactsGroupNames.length; const noContactGroupList = noContactsGroupNames.join(', '); const text = c('Error').ngettext( msgid`One of the groups has no contacts: ${noContactGroupList}`, `Some groups have no contacts: ${noContactGroupList} `, noContactGroupCount ); createNotification({ type: 'warning', text }); } onCompose?.(recipients, []); onClose?.(); }; const handleDetails = (groupID: string) => { onDetails(groupID); onClose?.(); }; const handleDelete = () => { onDelete({ groupIDs: selectedIDs, onDelete: () => { if (selectedIDs.length === filteredGroups.length) { setSearch(''); } handleCheckAll(false); }, }); onClose?.(); }; const handleCreate = () => { if (!user.hasPaidMail) { onUpgrade(); onClose?.(); return; } onEdit({}); onClose?.(); }; const handleImport = () => { onImport(); onClose?.(); }; const groupCounts = filteredGroups.length; const loading = loadingGroups || loadingContactEmails; const showPlaceholder = !loading && !groupCounts; const showList = !showPlaceholder; return ( <div className="flex flex-column flex-nowrap h-full"> <div className="contacts-widget-search-container flex-item-noshrink"> <label htmlFor="id_contact-widget-search" className="sr-only">{c('Placeholder') .t`Search for group name`}</label> <SearchInput autoFocus value={search} onChange={setSearch} id="id_contact-widget-group-search" placeholder={c('Placeholder').t`Group name`} /> <span className="sr-only" aria-atomic aria-live="assertive"> {c('Info').ngettext(msgid`${groupCounts} group found`, `${groupCounts} groups found`, groupCounts)} </span> </div> <div className="contacts-widget-toolbar py-4 border-bottom border-weak flex-item-noshrink"> <ContactsWidgetGroupsToolbar allChecked={allChecked} selected={selectedIDs} numberOfRecipients={recipients.length} onCheckAll={handleCheckAll} onCompose={onCompose ? handleCompose : undefined} groupsEmailsMap={groupsEmailsMap} recipients={recipients} onClose={onClose} customActions={customActions} onCreate={handleCreate} onDelete={handleDelete} isDrawer={isDrawer} /> </div> <div className="flex-item-fluid w-full"> {loading ? ( <div className="flex h-full"> <CircleLoader className="m-auto color-primary" size="large" /> </div> ) : null} {showPlaceholder ? ( <ContactsWidgetPlaceholder type={groups.length ? EmptyType.Search : EmptyType.AllGroups} onClearSearch={handleClearSearch} onCreate={handleCreate} onImport={handleImport} /> ) : null} {showList ? ( <ContactsGroupsList groups={filteredGroups} groupsEmailsMap={groupsEmailsMap} onCheckOne={handleCheckOne} isDesktop={false} checkedIDs={checkedIDs} onClick={handleDetails} isDrawer={isDrawer} onCompose={onCompose} /> ) : null} </div> </div> ); }; export default ContactsWidgetGroupsContainer;
6,130
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/widget/ContactsWidgetGroupsToolbar.tsx
import { ChangeEvent } from 'react'; import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms'; import { Recipient, SimpleMap } from '@proton/shared/lib/interfaces'; import { ContactEmail } from '@proton/shared/lib/interfaces/contacts'; import { ButtonGroup, Checkbox, Icon, Tooltip } from '../../../components'; import { CustomAction } from './types'; interface Props { allChecked: boolean; selected: string[]; numberOfRecipients: number; onCheckAll: (checked: boolean) => void; onCompose?: () => void; onCreate: () => void; onDelete: () => void; customActions: CustomAction[]; groupsEmailsMap: SimpleMap<ContactEmail[]>; recipients: Recipient[]; onClose?: () => void; isDrawer?: boolean; } const ContactsWidgetGroupsToolbar = ({ allChecked, selected, numberOfRecipients, onCheckAll, onCompose, onCreate, onDelete, customActions, groupsEmailsMap, recipients, onClose, isDrawer = false, }: Props) => { const selectedCount = selected.length; const handleCheck = ({ target }: ChangeEvent<HTMLInputElement>) => onCheckAll(target.checked); const noContactInSelected = !selectedCount || !numberOfRecipients; const noSelection = !selectedCount; const deleteText = noSelection ? c('Action').t`Delete contact group` : // translator: the variable is a positive integer (written in digits) always greater or equal to 1 c('Action').ngettext( msgid`Delete ${selectedCount} contact group`, `Delete ${selectedCount} contact groups`, selectedCount ); return ( <div className="flex flex-items-align-center"> <Tooltip title={allChecked ? c('Action').t`Deselect all` : c('Action').t`Select all`}> <span className="mr-4 flex"> <Checkbox id="id_contact-widget-select-all" checked={allChecked} onChange={handleCheck} data-testid="contacts:select-all-contact-group" /> <label htmlFor="id_contact-widget-select-all" className="sr-only"> {allChecked ? c('Action').t`Deselect all` : c('Action').t`Select all`} </label> </span> </Tooltip> <ButtonGroup> {onCompose ? ( <Tooltip title={c('Action').t`Compose`}> <Button icon className="inline-flex" onClick={onCompose} disabled={noContactInSelected} data-testid="contacts:compose-contact-group" > <Icon name="pen-square" alt={c('Action').t`Compose`} /> </Button> </Tooltip> ) : null} {customActions.map((action) => action.render({ groupsEmailsMap, recipients, noSelection, onClose, selected }) )} <Tooltip title={deleteText}> <Button icon className="inline-flex" onClick={onDelete} disabled={noSelection} data-testid="contacts:delete-contact-group" > <Icon name="trash" /> </Button> </Tooltip> {!isDrawer && ( <Tooltip title={c('Action').t`Add new group`}> <Button icon color="norm" className="ml-auto inline-flex" onClick={onCreate} data-testid="contacts:add-contact-group" > <Icon name="users-plus" alt={c('Action').t`Add new group`} /> </Button> </Tooltip> )} </ButtonGroup> </div> ); }; export default ContactsWidgetGroupsToolbar;
6,131
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/widget/ContactsWidgetPlaceholder.tsx
import { MouseEvent, ReactNode } from 'react'; import { c } from 'ttag'; import { InlineLinkButton } from '@proton/components'; import noResultsImg from '@proton/styles/assets/img/illustrations/empty-search.svg'; import noContactsImg from '@proton/styles/assets/img/illustrations/no-contacts.svg'; import { IllustrationPlaceholder } from '../../illustration'; export enum EmptyType { All, Search, AllGroups, } interface Props { type: EmptyType | undefined; onClearSearch: (event: MouseEvent) => void; onCreate: () => void; onImport: () => void; } const ContactsWidgetPlaceholder = ({ type, onClearSearch, onImport, onCreate }: Props) => { let imgUrl: string; let actions: ReactNode; switch (type) { case EmptyType.AllGroups: { imgUrl = noContactsImg; actions = ( <div className="flex flex-column"> <p className="m-0" data-testid="groups:no-groups">{c('Actions message') .t`You don't have any groups.`}</p> <p className="m-0"> <InlineLinkButton key="add-contact" onClick={onCreate}>{c('Action') .t`Add group`}</InlineLinkButton> </p> </div> ); break; } case EmptyType.Search: { imgUrl = noResultsImg; actions = ( <div className="flex flex-column"> <p className="m-0">{c('Actions message').t`No results found.`}</p> <p className="m-0">{c('Actions message').jt`Please try another search term.`}</p> <p className="m-0"> <InlineLinkButton onClick={onClearSearch}>{c('Action').t`Clear query`}</InlineLinkButton> </p> </div> ); break; } case EmptyType.All: default: { imgUrl = noContactsImg; const addContact = ( <InlineLinkButton key="add-contact" onClick={onCreate}>{c('Action').t`Add contact`}</InlineLinkButton> ); const importContact = ( <InlineLinkButton key="import" onClick={onImport}> {c('Action').t`import`} </InlineLinkButton> ); actions = ( <div className="flex flex-column"> <p className="m-0" data-testid="contacts:no-contacts">{c('Actions message') .t`You don't have any contacts.`}</p> <p className="m-0">{c('Actions message').jt`${addContact} or ${importContact}.`}</p> </div> ); } } return ( <div className="p-7 text-center w-full"> <IllustrationPlaceholder url={imgUrl}> <div className="flex flex-align-items-center">{actions}</div> </IllustrationPlaceholder> </div> ); }; export default ContactsWidgetPlaceholder;
6,132
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/widget/ContactsWidgetSettingsContainer.tsx
import { c } from 'ttag'; import { CircleLoader } from '@proton/atoms'; import { Field, Info, Label } from '@proton/components'; import { useContacts, useMailSettings } from '@proton/components/hooks'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import AutoSaveContactsToggle from '../../general/AutoSaveContactsToggle'; import ContactsWidgetSettingsContainerExport from './ContactsWidgetSettingsContainerExport'; import ContactsWidgetSettingsContainerImport from './ContactsWidgetSettingsContainerImport'; interface Props { onImport: () => void; onExport: () => void; onClose?: () => void; } const ContactsWidgetSettingsContainer = ({ onImport, onExport, onClose }: Props) => { const [mailSettings, loadingMailSettings] = useMailSettings(); const { AutoSaveContacts } = mailSettings || {}; const [, loadingContacts] = useContacts(); const loading = loadingContacts || loadingMailSettings; const handleImport = () => { onImport(); onClose?.(); }; const handleExport = () => { onExport(); onClose?.(); }; return ( <> {loading ? ( <div className="flex h-full pb-7"> <CircleLoader className="m-auto color-primary" size="large" /> </div> ) : ( <div className="p-4 pt-0 scroll-if-needed h-full"> <div className="flex mb-4 on-mobile-flex-column"> <Label htmlFor="saveContactToggle"> <span className="mr-2 text-semibold" role="heading" aria-level={2}>{c('Label') .t`Automatically save contacts`}</span> <Info url={getKnowledgeBaseUrl('/autosave-contact-list')} /> </Label> <Field className="pt-2"> <AutoSaveContactsToggle autoSaveContacts={!!AutoSaveContacts} id="saveContactToggle" /> </Field> </div> <div className="mb-8"> <ContactsWidgetSettingsContainerImport onImport={handleImport} onClose={onClose} /> </div> <div className="mb-8"> <ContactsWidgetSettingsContainerExport onExport={handleExport} /> </div> </div> )} </> ); }; export default ContactsWidgetSettingsContainer;
6,133
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/widget/ContactsWidgetSettingsContainerExport.tsx
import { c } from 'ttag'; import { Label, PrimaryButton, Tooltip } from '@proton/components'; import { useContacts } from '@proton/components/hooks'; interface ExportButtonProps { onClick?: () => void; hasNoContacts: boolean; } const ExportButton = ({ onClick, hasNoContacts }: ExportButtonProps) => { return ( <PrimaryButton disabled={hasNoContacts} id="export-contacts-button" onClick={onClick}> {c('Action').t`Export contacts`} </PrimaryButton> ); }; interface Props { onExport?: () => void; } const ContactsWidgetSettingsContainerExport = ({ onExport }: Props) => { const [contacts] = useContacts(); const hasNoContacts = !contacts?.length; return ( <> <Label htmlFor="export-contacts-button" className="text-semibold"> <span role="heading" aria-level={2}>{c('Label').t`Export contacts`}</span> </Label> <p className="color-weak mt-2 mb-4"> {c('Info') .t`The application needs to locally decrypt your contacts before they can be exported. At the end of the process, a VCF file will be generated and you will be able to download it.`} </p> {hasNoContacts ? ( <Tooltip title={c('Tooltip').t`You do not have any contacts to export`}> <span className="inline-block"> <ExportButton onClick={onExport} hasNoContacts={hasNoContacts} /> </span> </Tooltip> ) : ( <ExportButton onClick={onExport} hasNoContacts={hasNoContacts} /> )} </> ); }; export default ContactsWidgetSettingsContainerExport;
6,134
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/widget/ContactsWidgetSettingsContainerImport.tsx
import { c } from 'ttag'; import { EASY_SWITCH_SOURCE } from '@proton/activation/src/interface'; import { Label } from '@proton/components'; import ImportCsvContactButton from './ImportCsvContactButton'; interface Props { onImport: () => void; onClose?: () => void; } const ContactsWidgetSettingsContainerImport = ({ onImport, onClose }: Props) => ( <> <Label htmlFor="import-contacts-button" className="text-semibold"> <span role="heading" aria-level={2}>{c('Label').t`Import contacts`}</span> </Label> <p className="color-weak mt-2 mb-4"> {c('Info') .t`CSV files from Outlook, Outlook Express, Yahoo! Mail, Hotmail, Eudora and some other apps as well as vCard 3.1 and 4.0 formats (UTF-8 encoding) are supported.`} </p> <ImportCsvContactButton easySwitchSource={EASY_SWITCH_SOURCE.CONTACTS_WIDGET_SETTINGS} onImport={onImport} onClose={onClose} /> </> ); export default ContactsWidgetSettingsContainerImport;
6,135
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/widget/ContactsWidgetToolbar.tsx
import { ChangeEvent, useMemo } from 'react'; import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms'; import { ContactEmail } from '@proton/shared/lib/interfaces/contacts'; import isTruthy from '@proton/utils/isTruthy'; import { ButtonGroup, Checkbox, Icon, Tooltip } from '../../../components'; import ContactGroupDropdown from '../ContactGroupDropdown'; import { ContactGroupEditProps } from '../group/ContactGroupEditModal'; import useContactList from '../hooks/useContactList'; import { ContactGroupLimitReachedProps } from '../modals/ContactGroupLimitReachedModal'; import { SelectEmailsProps } from '../modals/SelectEmailsModal'; import { CustomAction } from './types'; interface Props { allChecked: boolean; selected: string[]; noEmailsContactCount: number; onCheckAll: (checked: boolean) => void; onCompose?: () => void; onForward: () => void; onDelete: () => void; onCreate: () => void; onMerge: () => void; onClose?: () => void; onLock?: (lock: boolean) => void; customActions: CustomAction[]; contactList: ReturnType<typeof useContactList>; onGroupEdit: (props: ContactGroupEditProps) => void; onLimitReached: (props: ContactGroupLimitReachedProps) => void; onUpgrade: () => void; onSelectEmails: (props: SelectEmailsProps) => Promise<ContactEmail[]>; isDrawer?: boolean; } const ContactsWidgetToolbar = ({ allChecked, selected, noEmailsContactCount, onCheckAll, onCompose, onForward, onDelete, onCreate, onMerge, onClose, onLock, customActions, contactList, onGroupEdit, onLimitReached, onUpgrade, onSelectEmails, isDrawer = false, }: Props) => { const selectedCount = selected.length; const handleCheck = ({ target }: ChangeEvent<HTMLInputElement>) => onCheckAll(target.checked); const noEmailInSelected = noEmailsContactCount === selectedCount; const noSelection = !selectedCount; const canMerge = selectedCount > 1; const deleteText = noSelection ? c('Action').t`Delete contact` : // translator: the variable is a positive integer (written in digits) always greater or equal to 1 c('Action').ngettext( msgid`Delete ${selectedCount} contact`, `Delete ${selectedCount} contacts`, selectedCount ); const contactEmails = useMemo(() => { return selected.flatMap((contactID) => contactList.contactEmailsMap[contactID]).filter(isTruthy); }, [selected, contactList.contactEmailsMap]); return ( <div className="flex flex-items-align-center"> <Tooltip title={allChecked ? c('Action').t`Deselect all` : c('Action').t`Select all`}> <span className="mr-4 flex"> <Checkbox id="id_contact-widget-select-all" checked={allChecked} onChange={handleCheck} data-testid="contacts:select-all" /> <label htmlFor="id_contact-widget-select-all" className="sr-only"> {allChecked ? c('Action').t`Deselect all` : c('Action').t`Select all`} </label> </span> </Tooltip> <ButtonGroup> {onCompose && ( <Tooltip title={c('Action').t`Compose`}> <Button icon className="inline-flex" onClick={onCompose} disabled={noEmailInSelected} title={c('Action').t`Compose`} data-testid="contacts:compose" > <Icon name="pen-square" alt={c('Action').t`Compose`} /> </Button> </Tooltip> )} {onCompose && ( <Tooltip title={c('Action').t`Forward as attachment`}> <Button icon className="inline-flex" onClick={onForward} disabled={noSelection} title={c('Action').t`Forward as attachment`} data-testid="contacts:forward-attachment" > <Icon name="arrow-right" alt={c('Action').t`Forward as attachment`} /> </Button> </Tooltip> )} {customActions.map((action) => action.render({ contactList, noSelection, onClose, selected }))} <Tooltip title={c('Action').t`Merge contacts`}> <Button icon className="inline-flex" onClick={onMerge} disabled={!canMerge} title={c('Action').t`Merge contacts`} data-testid="contacts:merge-contacts" > <Icon name="users-merge" alt={c('Action').t`Merge contacts`} /> </Button> </Tooltip> <ContactGroupDropdown className="inline-flex" contactEmails={contactEmails} disabled={contactEmails.length === 0} forToolbar onLock={onLock} onSuccess={() => onCheckAll(false)} onGroupEdit={onGroupEdit} onLimitReached={onLimitReached} onUpgrade={onUpgrade} onSelectEmails={onSelectEmails} > <Icon name="users" /> </ContactGroupDropdown> <Tooltip title={deleteText}> <Button icon className="inline-flex" onClick={onDelete} disabled={noSelection} title={deleteText} data-testid="contacts:delete-contacts" > <Icon name="trash" /> </Button> </Tooltip> {!isDrawer && ( <Tooltip title={c('Action').t`Add new contact`}> <Button icon color="norm" className="ml-auto inline-flex" onClick={onCreate} title={c('Action').t`Add new contact`} data-testid="contacts:add-new-contact" > <Icon name="user-plus" /> </Button> </Tooltip> )} </ButtonGroup> </div> ); }; export default ContactsWidgetToolbar;
6,136
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/widget/ImportCsvContactButton.tsx
import { c } from 'ttag'; import { EasySwitchOauthImportButton } from '@proton/activation'; import { EASY_SWITCH_SOURCE, EasySwitchFeatureFlag, ImportProvider, ImportType, } from '@proton/activation/src/interface'; import { Loader, PrimaryButton } from '../../../components'; import { useFeature, useUser } from '../../../hooks'; import { FeatureCode } from '../../features'; import { useFlag } from '../../unleash'; interface Props { onImport: () => void; easySwitchSource: EASY_SWITCH_SOURCE; onClose?: () => void; } const ImportCsvContactButton = ({ easySwitchSource, onImport, onClose }: Props) => { const [user, loadingUser] = useUser(); const easySwitchFeature = useFeature<EasySwitchFeatureFlag>(FeatureCode.EasySwitch); const isImporterInMaintenance = useFlag('MaintenanceImporter'); if (loadingUser || easySwitchFeature.loading) { return <Loader />; } const disabled = !user.hasNonDelinquentScope; return ( <div className="w-5/6"> {!isImporterInMaintenance && ( <> <EasySwitchOauthImportButton className="mr-4 mb-2 w-full" defaultCheckedTypes={[ImportType.CONTACTS]} displayOn="GoogleContacts" source={easySwitchSource} onClick={onClose} provider={ImportProvider.GOOGLE} /> <EasySwitchOauthImportButton className="mr-4 mb-2 w-full" defaultCheckedTypes={[ImportType.CONTACTS]} displayOn="OutlookContacts" source={easySwitchSource} onClick={onClose} provider={ImportProvider.OUTLOOK} /> </> )} <PrimaryButton fullWidth className="mb-2" id="import-contacts-button" disabled={disabled} onClick={onImport} > {c('Action').t`Import from .csv or vCard`} </PrimaryButton> </div> ); }; export default ImportCsvContactButton;
6,137
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/widget/MergeContactBanner.tsx
import { c, msgid } from 'ttag'; import { InlineLinkButton } from '../../../components'; interface Props { onMerge: () => void; countMergeableContacts: number; } const MergeContactBanner = ({ onMerge, countMergeableContacts }: Props) => { const mergeAction = ( <InlineLinkButton className="ml-1" onClick={onMerge} key="mergeAction" data-testid="contacts:merge-contacts-button" >{c('Action').t`Merge`}</InlineLinkButton> ); const mergeText = c('Success').ngettext( msgid`${countMergeableContacts} contact look identical.`, `${countMergeableContacts} contacts look identical.`, countMergeableContacts ); return ( <div className="px-4 py-2 text-sm bg-weak border-bottom"> <span> {mergeText} {mergeAction} </span> </div> ); }; export default MergeContactBanner;
6,138
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts
petrpan-code/ProtonMail/WebClients/packages/components/containers/contacts/widget/types.ts
import { ReactNode } from 'react'; import { ContactEmail } from '@proton/shared/lib/interfaces/contacts/index'; import { Recipient, SimpleMap } from '@proton/shared/lib/interfaces/index'; import useContactList from '../hooks/useContactList'; export enum CONTACT_WIDGET_TABS { CONTACTS, GROUPS, } export interface CustomActionRenderProps { onClose?: () => void; noSelection: boolean; selected: string[]; contactList?: ReturnType<typeof useContactList>; groupsEmailsMap?: SimpleMap<ContactEmail[]>; recipients?: Recipient[]; } export interface CustomAction { render: ({ onClose, noSelection, selected, contactList, groupsEmailsMap, recipients, }: CustomActionRenderProps) => ReactNode; tabs: CONTACT_WIDGET_TABS[]; }
6,139
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/domains/AddressCatchAll.tsx
import { c } from 'ttag'; import { updateCatchAll } from '@proton/shared/lib/api/domains'; import { Domain, DomainAddress } from '@proton/shared/lib/interfaces'; import { Checkbox } from '../../components'; import { useApiWithoutResult, useNotifications } from '../../hooks'; interface Props { address: DomainAddress; domain: Domain; onChange: (ID: string, value: boolean) => void; disabled: boolean; } const AddressCatchAll = ({ address, domain, onChange, disabled }: Props) => { const { request, loading } = useApiWithoutResult(updateCatchAll); const { createNotification } = useNotifications(); return ( <Checkbox id={address.ID} disabled={loading || disabled} checked={!!address.CatchAll} onChange={async ({ target }) => { const newValue = target.checked; await request(domain.ID, newValue ? address.ID : null); onChange(address.ID, newValue); createNotification({ text: c('Success').t`Catch-all address updated` }); }} /> ); }; export default AddressCatchAll;
6,140
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/domains/AddressesSection.tsx
import { c } from 'ttag'; import { ButtonLike } from '@proton/atoms'; import { APPS } from '@proton/shared/lib/constants'; import { Alert, SettingsLink } from '../../components'; import { useOrganization } from '../../hooks'; interface Props { onClose?: () => void; } const AddressesSection = ({ onClose }: Props) => { const [organization] = useOrganization(); if (!organization?.HasKeys) { return ( <div className="mb-4"> <ButtonLike as={SettingsLink} onClick={() => onClose?.()} path="/identity-addresses#addresses" app={APPS.PROTONMAIL} >{c('Action').t`Add address`}</ButtonLike> </div> ); } if (organization?.MaxMembers > 1) { return ( <> <Alert className="mb-4">{c('Info for domain modal') .t`Add a new user to your organization and create an address for it.`}</Alert> <div className="mb-4"> <ButtonLike as={SettingsLink} color="norm" onClick={() => onClose?.()} path="/users-addresses">{c( 'Action' ).t`Add user`}</ButtonLike> </div> <Alert className="mb-4">{c('Info for domain modal') .t`Add a new address for any user of your organization.`}</Alert> <div className="mb-4"> <ButtonLike as={SettingsLink} color="norm" onClick={() => onClose?.()} path="/users-addresses">{c( 'Action' ).t`Add address`}</ButtonLike> </div> </> ); } return ( <div className="mb-4"> <ButtonLike as={SettingsLink} onClick={() => onClose?.()} path="/users-addresses">{c('Action') .t`Add address`}</ButtonLike> </div> ); }; export default AddressesSection;
6,141
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/domains/AddressesTable.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { ADDRESS_RECEIVE, ADDRESS_STATUS } from '@proton/shared/lib/constants'; import { Domain, DomainAddress } from '@proton/shared/lib/interfaces'; import clsx from '@proton/utils/clsx'; import { Table, TableBody, TableHeader, TableRow } from '../../components'; import { useEventManager } from '../../hooks'; import AddressCatchAll from './AddressCatchAll'; import DomainAddressStatus from './DomainAddressStatus'; interface Props { domain: Domain; domainAddresses: DomainAddress[]; } const AddressesTable = ({ domain, domainAddresses }: Props) => { const { call } = useEventManager(); const [addresses, setAddresses] = useState(() => domainAddresses); return ( <Table className="table-auto"> <TableHeader cells={[ <span className="sr-only">{c('Title header for addresses domain table').t`Catch-All`}</span>, c('Title header for addresses domain table').t`Address`, c('Title header for addresses domain table').t`Status`, ]} /> <TableBody> {addresses.map((address) => { const key = address.ID; const { Status, Receive } = address; const isAddressActive = Status === ADDRESS_STATUS.STATUS_ENABLED && Receive === ADDRESS_RECEIVE.RECEIVE_YES; return ( <TableRow key={key} cells={[ <AddressCatchAll key={key} disabled={!isAddressActive} address={address} domain={domain} onChange={(id, value) => { setAddresses( addresses.map((address) => { return { ...address, CatchAll: address.ID === id ? value : false, } as const; }), ); void call(); }} />, <div key={key} className={clsx('text-ellipsis', !isAddressActive && 'color-disabled')} title={address.Email} > {address.Email} </div>, <DomainAddressStatus key={key} address={address} />, ]} /> ); })} </TableBody> </Table> ); }; export default AddressesTable;
6,142
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/domains/CatchAllModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { Domain, DomainAddress } from '@proton/shared/lib/interfaces'; import { Info, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader } from '../../components'; import AddressesTable from './AddressesTable'; interface Props extends ModalProps { domain: Domain; domainAddresses: DomainAddress[]; } const CatchAllModal = ({ domain, domainAddresses, ...rest }: Props) => { return ( <ModalTwo {...rest}> <ModalTwoHeader title={ <span className="inline-flex flex-align-items-center"> {c('Title').t`Catch-All address`} <Info buttonClass="ml-2" url={getKnowledgeBaseUrl('/catch-all')} /> </span> } /> <ModalTwoContent> <AddressesTable domain={domain} domainAddresses={domainAddresses} /> </ModalTwoContent> <ModalTwoFooter> <Button onClick={rest.onClose}>{c('Action').t`Close`}</Button> </ModalTwoFooter> </ModalTwo> ); }; export default CatchAllModal;
6,143
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/domains/CatchAllSection.tsx
import { c } from 'ttag'; import { APP_UPSELL_REF_PATH, BRAND_NAME, MAIL_APP_NAME, MAIL_UPSELL_PATHS, PLANS, PLAN_NAMES, UPSELL_COMPONENT, } from '@proton/shared/lib/constants'; import { getUpsellRef } from '@proton/shared/lib/helpers/upsell'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { useUser } from '../../hooks'; import { SettingsParagraph, SettingsSectionWide, UpgradeBanner } from '../account'; const CatchAllSection = () => { const [{ isAdmin, isSubUser }] = useUser(); const hasPermission = isAdmin && !isSubUser; const plus = PLAN_NAMES[PLANS.MAIL]; const bundle = PLAN_NAMES[PLANS.BUNDLE]; const upsellRef = getUpsellRef({ app: APP_UPSELL_REF_PATH.MAIL_UPSELL_REF_PATH, component: UPSELL_COMPONENT.BANNER, feature: MAIL_UPSELL_PATHS.CATCH_ALL, isSettings: true, }); return ( <SettingsSectionWide> <SettingsParagraph learnMoreUrl={getKnowledgeBaseUrl('/catch-all')}> {c('Info') .t`If you have a custom domain with ${MAIL_APP_NAME}, you can set a catch-all email address to receive messages sent to your domain but to an invalid email address (e.g., because of typos).`} </SettingsParagraph> {!hasPermission && ( <UpgradeBanner upsellPath={upsellRef}> {c('new_plans: upgrade').t`Included with ${plus}, ${bundle}, and ${BRAND_NAME} for Business.`} </UpgradeBanner> )} </SettingsSectionWide> ); }; export default CatchAllSection;
6,144
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/domains/DKIMSection.js
import PropTypes from 'prop-types'; import { c } from 'ttag'; import { Href } from '@proton/atoms'; import { MAIL_APP_NAME } from '@proton/shared/lib/constants'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { DKIM_STATE } from '@proton/shared/lib/interfaces'; import { Alert, Copy, Table, TableBody, TableCell, TableHeader, TableRow } from '../../components'; import { useNotifications } from '../../hooks'; const DKIMSection = ({ domain }) => { const { createNotification } = useNotifications(); const handleCopy = () => createNotification({ text: c('Success').t`Value copied to clipboard` }); const { DKIM: { Config, State }, } = domain; return ( <> <Alert className="mb-4"> {c('Info') .t`${MAIL_APP_NAME} supports DKIM signing for custom domains. To use DKIM authentication, please add the following CNAME record into your DNS settings for this domain. This can typically be done in the control panel of your domain name registrar.`} <div> <Href href={getKnowledgeBaseUrl('/anti-spoofing-custom-domain')}>{c('Link').t`Learn more`}</Href> </div> </Alert> {State === DKIM_STATE.DKIM_STATE_ERROR && ( <Alert className="mb-4" type="error"> {c('Error') .t`We stopped DKIM signing due to problems with your DNS configuration. Please follow the instructions below to resume signing.`} </Alert> )} {State === DKIM_STATE.DKIM_STATE_WARNING && ( <Alert className="mb-4" type="warning"> {c('Warning') .t`We detected a problem with your DNS configuration. Please make sure your records match the instructions below. If the problem persists, we will have to switch DKIM signing off.`} </Alert> )} <p className="mb-4"> {c('Label') .t`Please add all 3 of the following CNAME records. Note, DNS records can take several hours to update.`} </p> <Table responsive="cards"> <TableHeader> <TableRow> <TableCell type="header" className="w-1/6"> {c('Header for domain modal').t`Type`} </TableCell> <TableCell type="header">{c('Header for domain modal').t`Host name`}</TableCell> <TableCell type="header" className="w-1/2"> {c('Header for domain modal').t`Value / Data`} </TableCell> </TableRow> </TableHeader> <TableBody> {Config.map((row) => ( <TableRow key={row.Hostname}> <TableCell label={c('Header for domain modal').t`Type`}> <code>CNAME</code> </TableCell> <TableCell label={c('Header for domain modal').t`Host name`}> <code>{row.Hostname}</code> </TableCell> <TableCell label={c('Header for domain modal').t`Value / Data`}> <div className="flex flex-nowrap flex-align-items-center"> <Copy onCopy={handleCopy} size="small" className="flex-item-noshrink mr-2" value={row.CNAME} />{' '} <div className="text-ellipsis"> <code title={row.CNAME}>{row.CNAME}</code> </div> </div> </TableCell> </TableRow> ))} </TableBody> </Table> <Alert className="mb-4" type="warning"> {c('Info') .t`IMPORTANT: Some registrars do not accept CNAME values with a period at the end (while others require it). If your registrar does not accept your CNAME records, please delete the period at the end of each CNAME value and try again.`} </Alert> <Alert className="mb-4" type="warning"> {c('Info').t`Keep those records in your DNS for as long as you want to use DKIM.`} </Alert> </> ); }; DKIMSection.propTypes = { domain: PropTypes.object.isRequired, }; export default DKIMSection;
6,145
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/domains/DMARCSection.js
import { useState } from 'react'; import { c } from 'ttag'; import { Href } from '@proton/atoms'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { Alert, Copy, Input, Label, Table, TableBody, TableHeader, TableRow } from '../../components'; import { useNotifications } from '../../hooks'; const DMARCSection = () => { const none = <strong key="none">p=none</strong>; const quarantine = <strong key="quarantine">p=quarantine</strong>; const { createNotification } = useNotifications(); const handleCopy = () => createNotification({ text: c('Success').t`DMARC value copied to clipboard` }); const dmarcValue = 'v=DMARC1; p=none'; const [value, setValue] = useState(dmarcValue); return ( <> <Alert className="mb-4"> {c('Info') .t`If you have set both SPF and DKIM, DMARC allows you to specify how other email services should deliver email for your domain if both SPF and DKIM checks have failed. This can make it harder for spammers pretending to be you but may also cause delivery issues if not done properly.`} <div> <Href href={getKnowledgeBaseUrl('/anti-spoofing-custom-domain')}>{c('Link').t`Learn more`}</Href> </div> </Alert> <Label>{c('Label').t`Here is a basic DMARC record that does nothing except email you reports.`}</Label> <Table responsive="cards"> <TableHeader cells={[ c('Header for domain modal').t`Type`, c('Header for domain modal').t`Host name`, c('Header for domain modal').t`Value / Data / Points to`, ]} /> <TableBody> <TableRow labels={[ c('Header for domain modal').t`Type`, c('Header for domain modal').t`Host name`, c('Header for domain modal').t`Value / Data / Points to`, ]} cells={[ <code key="txt">TXT</code>, <code key="dmarc">_dmarc</code>, <div className="flex flex-nowrap flex-align-items-center" key="value"> <Copy onCopy={handleCopy} className="flex-item-noshrink mr-2" size="small" value={value} />{' '} <Input value={value} onChange={({ target }) => setValue(target.value)} placeholder={dmarcValue} /> </div>, ]} /> </TableBody> </Table> <Alert className="mb-4"> {c('Info') .jt`${none} has no effect on email delivery, but we recommend ${quarantine} for better security.`} </Alert> </> ); }; export default DMARCSection;
6,146
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/domains/DeleteDomainModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { deleteDomain } from '@proton/shared/lib/api/domains'; import { Domain } from '@proton/shared/lib/interfaces'; import { Alert, ErrorButton, Prompt, PromptProps } from '../../components'; import { useApi, useEventManager, useNotifications } from '../../hooks'; interface Props extends Omit<PromptProps, 'title' | 'buttons' | 'children'> { domain: Domain; } const DeleteDomainModal = ({ domain, ...rest }: Props) => { const api = useApi(); const { createNotification } = useNotifications(); const { call } = useEventManager(); const [loading, withLoading] = useLoading(); const handleConfirmDelete = async () => { await api(deleteDomain(domain.ID)); await call(); rest.onClose?.(); createNotification({ text: c('Success message').t`Domain deleted` }); }; return ( <Prompt title={c('Title').t`Delete ${domain.DomainName}`} buttons={[ <ErrorButton onClick={() => { withLoading(handleConfirmDelete()); }} loading={loading} >{c('Action').t`Delete`}</ErrorButton>, <Button onClick={rest.onClose} disabled={loading}>{c('Action').t`Cancel`}</Button>, ]} {...rest} > <Alert className="mb-4" type="info">{c('Info') .t`Please note that if you delete this domain, all the addresses associated with it will be disabled.`}</Alert> <Alert className="mb-4" type="error">{c('Info').t`Are you sure you want to delete this domain?`}</Alert> </Prompt> ); }; export default DeleteDomainModal;
6,147
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/domains/DomainAddressStatus.tsx
import { c } from 'ttag'; import { ADDRESS_RECEIVE, ADDRESS_STATUS } from '@proton/shared/lib/constants'; import { DomainAddress } from '@proton/shared/lib/interfaces'; import { Badge } from '../../components'; interface Props { address: DomainAddress; } const DomainAddressStatus = ({ address }: Props) => { const { Status, Receive, HasKeys } = address; if (HasKeys === 0) { return <Badge type="warning" className="text-nowrap">{c('Badge for domain').t`Missing keys`}</Badge>; } if (Status === ADDRESS_STATUS.STATUS_ENABLED && Receive === ADDRESS_RECEIVE.RECEIVE_YES) { return <Badge type="success" className="text-nowrap">{c('Badge for domain').t`Enabled`}</Badge>; } if (Status === ADDRESS_STATUS.STATUS_DISABLED) { return <Badge type="error" className="text-nowrap">{c('Badge for domain').t`Disabled`}</Badge>; } return null; }; export default DomainAddressStatus;
6,148
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/domains/DomainModal.tsx
import { FormEvent, useEffect, useRef, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { addressType } from '@proton/shared/lib/api/addresses'; import { addDomain, getDomain } from '@proton/shared/lib/api/domains'; import { getSilentApi } from '@proton/shared/lib/api/helpers/customConfig'; import { ADDRESS_TYPE } from '@proton/shared/lib/constants'; import { Address, Api, DKIM_STATE, DMARC_STATE, DOMAIN_STATE, DecryptedKey, Domain, DomainAddress, KeyTransparencyVerify, MX_STATE, SPF_STATE, VERIFY_STATE, } from '@proton/shared/lib/interfaces'; import { clearExternalFlags, getSignedKeyListWithDeferredPublish } from '@proton/shared/lib/keys'; import { getActiveKeys, getNormalizedActiveKeys } from '@proton/shared/lib/keys/getActiveKeys'; import clsx from '@proton/utils/clsx'; import noop from '@proton/utils/noop'; import { ButtonGroup, Form, Icon, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, RoundedIcon, Tooltip, useFormErrors, } from '../../components'; import { useApi, useDomains, useEventManager, useGetAddressKeys, useGetAddresses, useGetUser, useGetUserKeys, useNotifications, useStep, } from '../../hooks'; import { useKTVerifier } from '../keyTransparency'; import AddressesSection from './AddressesSection'; import DKIMSection from './DKIMSection'; import DMARCSection from './DMARCSection'; import DomainSection from './DomainSection'; import MXSection from './MXSection'; import SPFSection from './SPFSection'; import VerifySection from './VerifySection'; const STEPS = { DOMAIN: 0, VERIFY: 1, MX: 2, SPF: 3, DKIM: 4, DMARC: 5, ADDRESSES: 6, }; const verifyDomain = (domain?: Domain) => { if (domain?.VerifyState === VERIFY_STATE.VERIFY_STATE_DEFAULT) { return c('Error').t`Verification did not succeed, please try again in an hour.`; } if (domain?.VerifyState === VERIFY_STATE.VERIFY_STATE_EXIST) { return c('Error') .t`Wrong verification code. Please make sure you copied the verification code correctly and try again. It can take up to 24 hours for changes to take effect.`; } }; interface Props extends ModalProps { domain?: Domain; domainAddresses?: DomainAddress[]; } const convertToInternalAddress = async ({ address, keys, api, keyTransparencyVerify, }: { address: Address; keys: DecryptedKey[]; api: Api; keyTransparencyVerify: KeyTransparencyVerify; }) => { const activeKeys = await getActiveKeys(address, address.SignedKeyList, address.Keys, keys); const internalAddress = { ...address, // Reset type to an internal address with a custom domain Type: ADDRESS_TYPE.TYPE_CUSTOM_DOMAIN, }; const [signedKeyList, onSKLPublishSuccess] = await getSignedKeyListWithDeferredPublish( getNormalizedActiveKeys(internalAddress, activeKeys).map((key) => { return { ...key, flags: clearExternalFlags(key.flags), }; }), address, keyTransparencyVerify ); await api( addressType(address.ID, { Type: internalAddress.Type, SignedKeyList: signedKeyList, }) ); await onSKLPublishSuccess(); }; const DomainModal = ({ domain, domainAddresses = [], ...rest }: Props) => { const [domains, loadingDomains] = useDomains(); const onceRef = useRef(false); const [domainModel, setDomain] = useState<Partial<Domain>>(() => ({ ...domain })); const getAddresses = useGetAddresses(); const getAddressKeys = useGetAddressKeys(); const { createNotification } = useNotifications(); const [loading, withLoading] = useLoading(); const [domainName, updateDomainName] = useState(domainModel.DomainName || ''); const api = useApi(); const { step, next, goTo } = useStep(); const { call } = useEventManager(); const { validator, onFormSubmit } = useFormErrors(); const getUser = useGetUser(); const getUserKeys = useGetUserKeys(); const { keyTransparencyVerify, keyTransparencyCommit } = useKTVerifier(api, getUser); useEffect(() => { const run = async () => { if (onceRef.current) { return; } const domainName = domainModel.DomainName; // Once a domain has gotten verified, and before we display the MX setup, we attempt to convert external addresess // to internal ones by changing the type by updating the SKL. if (!domainModel.ID || !domainName || domainModel.VerifyState !== VERIFY_STATE.VERIFY_STATE_GOOD) { return; } onceRef.current = true; const addresses = await getAddresses(); const externalAddresses = addresses.filter( (address) => address.Type === ADDRESS_TYPE.TYPE_EXTERNAL && address.Email.endsWith(domainName) ); if (!externalAddresses.length) { return; } await Promise.all( externalAddresses.map(async (externalAddress) => { return convertToInternalAddress({ address: externalAddress, keys: await getAddressKeys(externalAddress.ID), api: getSilentApi(api), keyTransparencyVerify, }); }) ); const userKeys = await getUserKeys(); await keyTransparencyCommit(userKeys); await call(); }; void run(); }, [domainModel?.DomainName, domainModel?.ID, domainModel?.VerifyState]); const handleClose = async () => { void call(); // Refresh domains model present in background page rest.onClose?.(); }; const renderDKIMIcon = () => { const { DKIM_STATE_ERROR, DKIM_STATE_GOOD, DKIM_STATE_WARNING } = DKIM_STATE; switch (domainModel.DKIM?.State) { case DKIM_STATE_ERROR: { return ( <Tooltip title={c('Tooltip') .t`We stopped DKIM signing due to problems with your DNS configuration. Please follow the instructions below to resume signing.`} > <RoundedIcon className="mr-1 md:mr-2 p-1 md:p-0" key="dkim-icon" type="error" name="cross" /> </Tooltip> ); } case DKIM_STATE_GOOD: { return ( <Tooltip title={c('Tooltip').t`Your DKIM signing is working.`}> <RoundedIcon className="mr-1 md:mr-2 p-1 md:p-0" key="dkim-icon" type="success" name="checkmark" /> </Tooltip> ); } case DKIM_STATE_WARNING: { return ( <Tooltip title={c('Tooltip') .t`We detected a problem with your DNS configuration. Please make sure your records match the instructions below. If the problem persists, we will have to switch DKIM signing off.`} > <Icon size={24} className="mr-1 md:mr-2 p-1 md:p-0" name="exclamation-circle-filled" /> </Tooltip> ); } default: { return null; } } }; const breadcrumbLabels = [ c('Label in domain modal').t`Domain`, c('Label in domain modal').t`Verify`, 'MX', 'SPF', 'DKIM', 'DMARC', c('Label in domain modal').t`Addresses`, ]; const breadcrumbIcons = [ domainModel.State === DOMAIN_STATE.DOMAIN_STATE_DEFAULT || !domainModel.State ? null : ( <RoundedIcon className="mr-1 md:mr-2 p-1 md:p-0" key="domain-icon" type={domainModel.State === DOMAIN_STATE.DOMAIN_STATE_VERIFIED ? 'success' : 'error'} name={domainModel.State === DOMAIN_STATE.DOMAIN_STATE_VERIFIED ? 'checkmark' : 'cross'} /> ), domainModel.VerifyState === VERIFY_STATE.VERIFY_STATE_DEFAULT || !domainModel.VerifyState ? null : ( <RoundedIcon className="mr-1 md:mr-2 p-1 md:p-0" key="verify-icon" type={domainModel.VerifyState === VERIFY_STATE.VERIFY_STATE_GOOD ? 'success' : 'error'} name={domainModel.VerifyState === VERIFY_STATE.VERIFY_STATE_GOOD ? 'checkmark' : 'cross'} /> ), domainModel.MxState === MX_STATE.MX_STATE_DEFAULT || !domainModel.MxState ? null : ( <RoundedIcon className="mr-1 md:mr-2 p-1 md:p-0" key="mx-icon" type={domainModel.MxState === MX_STATE.MX_STATE_GOOD ? 'success' : 'error'} name={domainModel.MxState === MX_STATE.MX_STATE_GOOD ? 'checkmark' : 'cross'} /> ), domainModel.SpfState === SPF_STATE.SPF_STATE_DEFAULT || !domainModel.SpfState ? null : ( <RoundedIcon className="mr-1 md:mr-2 p-1 md:p-0" key="spf-icon" type={domainModel.SpfState === SPF_STATE.SPF_STATE_GOOD ? 'success' : 'error'} name={domainModel.SpfState === SPF_STATE.SPF_STATE_GOOD ? 'checkmark' : 'cross'} /> ), [DKIM_STATE.DKIM_STATE_ERROR, DKIM_STATE.DKIM_STATE_GOOD, DKIM_STATE.DKIM_STATE_WARNING].includes( domainModel.DKIM?.State as DKIM_STATE ) ? renderDKIMIcon() : null, domainModel.DmarcState === DMARC_STATE.DMARC_STATE_DEFAULT || !domainModel.DmarcState ? null : ( <RoundedIcon className="mr-1 md:mr-2 p-1 md:p-0" key="dmarc-icon" type={domainModel.DmarcState === DMARC_STATE.DMARC_STATE_GOOD ? 'success' : 'error'} name={domainModel.DmarcState === DMARC_STATE.DMARC_STATE_GOOD ? 'checkmark' : 'cross'} /> ), domainAddresses.length ? ( <RoundedIcon className="mr-1 md:mr-2 p-1 md:p-0" key="addresses-icon" type="success" name="checkmark" /> ) : null, ]; const { section, onSubmit, submit } = (() => { if (step === STEPS.DOMAIN) { const handleSubmit = async () => { if (domainModel.ID) { return next(); } const { Domain } = await api<{ Domain: Domain }>(addDomain(domainName)); setDomain(Domain); await call(); next(); }; return { section: ( <DomainSection validator={validator} domain={domainModel} domainName={domainName} onValue={updateDomainName} /> ), submit: undefined, onSubmit: (event: FormEvent<HTMLFormElement>) => { if (!onFormSubmit(event.currentTarget)) { return; } void withLoading(handleSubmit().catch(noop)); }, }; } if (step === STEPS.VERIFY) { const handleSubmit = async () => { if (domainModel.VerifyState === VERIFY_STATE.VERIFY_STATE_GOOD) { return next(); } const { Domain } = await api<{ Domain: Domain }>(getDomain(domainModel.ID)); const error = verifyDomain(Domain); if (error) { return createNotification({ text: error, type: 'error' }); } setDomain(Domain); await call(); createNotification({ text: c('Success').t`Domain verified` }); next(); }; return { section: <VerifySection domain={domainModel} />, submit: undefined, onSubmit: () => withLoading(handleSubmit()), }; } if (step === STEPS.MX) { return { section: <MXSection />, submit: undefined, onSubmit: next, }; } if (step === STEPS.SPF) { return { section: <SPFSection />, submit: undefined, onSubmit: next, }; } if (step === STEPS.DKIM) { return { section: <DKIMSection domain={domainModel} />, submit: undefined, onSubmit: next, }; } if (step === STEPS.DMARC) { return { section: <DMARCSection />, submit: undefined, onSubmit: next, }; } if (step === STEPS.ADDRESSES) { return { section: <AddressesSection onClose={handleClose} />, submit: c('Action').t`Done`, onSubmit: rest.onClose, }; } throw new Error('Missing step'); })(); useEffect(() => { if (!loadingDomains) { const maybeDomain = domains.find(({ ID }) => ID === domainModel.ID); if (maybeDomain) { setDomain({ ...maybeDomain }); } } }, [domains]); return ( <ModalTwo className="modal--full" as={Form} onSubmit={onSubmit} {...rest}> <ModalTwoHeader title={domainModel.ID ? c('Title').t`Edit domain` : c('Title').t`Add domain`} /> <ModalTwoContent> <ButtonGroup className="mb-4"> {breadcrumbLabels.map((label, index) => ( <Button icon key={label} className={clsx([ 'flex flex-nowrap flex-align-items-center', index === step && 'is-selected', ])} disabled={ (index > STEPS.DOMAIN && !domainModel.ID) || (index > STEPS.VERIFY && domainModel.VerifyState !== VERIFY_STATE.VERIFY_STATE_GOOD) } onClick={() => goTo(index)} title={label} > {breadcrumbIcons[index]} <span className="text-ellipsis max-w-full">{label}</span> </Button> ))} </ButtonGroup> {section} </ModalTwoContent> <ModalTwoFooter> <Button onClick={rest.onClose}>{c('Action').t`Close`}</Button> <Button color="norm" type="submit" loading={loading}> {submit || c('Action').t`Next`} </Button> </ModalTwoFooter> </ModalTwo> ); }; export default DomainModal;
6,149
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/domains/DomainName.tsx
import { DOMAIN_STATE, Domain } from '@proton/shared/lib/interfaces'; import { Icon } from '../../components'; const { DOMAIN_STATE_DEFAULT, DOMAIN_STATE_VERIFIED, DOMAIN_STATE_WARN } = DOMAIN_STATE; export interface Props { domain: Domain; } const DomainName = ({ domain }: Props) => { const ICONS = { [DOMAIN_STATE_DEFAULT]: ( <Icon className="color-danger flex-item-noshrink" type="error" name="cross-circle-filled" /> ), [DOMAIN_STATE_VERIFIED]: <Icon className="color-success flex-item-noshrink" name="checkmark-circle-filled" />, [DOMAIN_STATE_WARN]: ( <Icon className="color-warning flex-item-noshrink" type="warning" name="cross-circle-filled" /> ), }; return ( <span className="flex flex-nowrap flex-align-items-center"> {ICONS[domain.State]} <span className="text-ellipsis ml-2" title={domain.DomainName}> {domain.DomainName} </span> </span> ); }; export default DomainName;
6,150
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/domains/DomainSection.tsx
import { c } from 'ttag'; import { Href } from '@proton/atoms/Href'; import { MAIL_APP_NAME } from '@proton/shared/lib/constants'; import { requiredValidator } from '@proton/shared/lib/helpers/formValidators'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { Domain } from '@proton/shared/lib/interfaces'; import { Alert, InputFieldTwo } from '../../components'; interface Props { domain: Partial<Domain>; domainName: string; onValue: (domainName: string) => void; validator: (validations: string[]) => string; } const DomainSection = ({ domain, domainName, onValue, validator }: Props) => { return ( <> <Alert className="mb-4"> {c('Label for adding a new custom domain') .t`Add a domain that you own to your ${MAIL_APP_NAME} account.`} <div> <Href href={getKnowledgeBaseUrl('/custom-domain')}>{c('Link').t`Learn more`}</Href> </div> </Alert> {domain.ID ? ( <InputFieldTwo label={c('Label').t`Domain name`} as="div"> {domainName} </InputFieldTwo> ) : ( <InputFieldTwo id="domainName" rootClassName="max-w-custom" rootStyle={{ '--max-w-custom': '18em' }} label={c('Label').t`Domain name`} error={validator([requiredValidator(domainName)])} autoFocus value={domainName} onValue={onValue} placeholder={c('Placeholder').t`yourdomain.com`} /> )} {!domain.ID && domainName.toLowerCase().startsWith('www.') ? ( <Alert className="mb-4" type="warning">{c('Domain modal') .t`'www' subdomains are typically not used for email. Are you sure you want to use this domain value?`}</Alert> ) : null} </> ); }; export default DomainSection;
6,151
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/domains/DomainStatus.js
import PropTypes from 'prop-types'; import { c, msgid } from 'ttag'; import { DKIM_STATE, DMARC_STATE, DOMAIN_STATE, MX_STATE, SPF_STATE, VERIFY_STATE, } from '@proton/shared/lib/interfaces'; import { Badge } from '../../components'; const VERIFY_TYPES = { [VERIFY_STATE.VERIFY_STATE_DEFAULT]: 'origin', [VERIFY_STATE.VERIFY_STATE_EXIST]: 'error', [VERIFY_STATE.VERIFY_STATE_GOOD]: 'success', }; const MX_TYPES = { [MX_STATE.MX_STATE_DEFAULT]: 'origin', [MX_STATE.MX_STATE_NO_US]: 'error', [MX_STATE.MX_STATE_INC_US]: 'error', [MX_STATE.MX_STATE_GOOD]: 'success', }; const SPF_TYPES = { [SPF_STATE.SPF_STATE_DEFAULT]: 'origin', [SPF_STATE.SPF_STATE_ONE]: 'error', [SPF_STATE.SPF_STATE_MULT]: 'error', [SPF_STATE.SPF_STATE_GOOD]: 'success', }; const DKIM_TYPES = { [DKIM_STATE.DKIM_STATE_DEFAULT]: 'origin', [DKIM_STATE.DKIM_STATE_ERROR]: 'error', [DKIM_STATE.DKIM_STATE_GOOD]: 'success', [DKIM_STATE.DKIM_STATE_WARNING]: 'warning', }; const DMARC_TYPES = { [DMARC_STATE.DMARC_STATE_DEFAULT]: 'origin', [DMARC_STATE.DMARC_STATE_ONE]: 'error', [DMARC_STATE.DMARC_STATE_MULT]: 'error', [DMARC_STATE.DMARC_STATE_GOOD]: 'success', }; const DomainStatus = ({ domain, domainAddresses }) => { const n = domainAddresses.length; const catchAllEnabled = domainAddresses.some((address) => address.CatchAll); const badges = [ { text: c('Domain label').t`Verified`, type: VERIFY_TYPES[domain.VerifyState] }, { text: c('Info').ngettext(msgid`${n} address`, `${n} addresses`, n), type: domain.State === DOMAIN_STATE.DOMAIN_STATE_VERIFIED && n ? 'success' : 'error', }, { text: 'MX', type: MX_TYPES[domain.MxState] }, { text: 'SPF', type: SPF_TYPES[domain.SpfState] }, { text: 'DKIM', type: DKIM_TYPES[domain.DKIM.State] }, { text: 'DMARC', type: DMARC_TYPES[domain.DmarcState] }, { text: 'CATCH-ALL', type: catchAllEnabled ? 'success' : 'origin' }, ]; return ( <> {badges.map(({ text, type }, index) => ( <Badge key={index.toString()} type={type} className="mb-1 mr-1"> {text} </Badge> ))} </> ); }; DomainStatus.propTypes = { domain: PropTypes.object.isRequired, domainAddresses: PropTypes.array.isRequired, }; export default DomainStatus;
6,152
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/domains/DomainsSection.tsx
import { useState } from 'react'; import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { APP_UPSELL_REF_PATH, BRAND_NAME, MAIL_UPSELL_PATHS, PLANS, PLAN_NAMES, UPSELL_COMPONENT, } from '@proton/shared/lib/constants'; import { getUpsellRef } from '@proton/shared/lib/helpers/upsell'; import { getDomainsSupportURL } from '@proton/shared/lib/helpers/url'; import { Domain, DomainAddress } from '@proton/shared/lib/interfaces'; import { DomainsModel } from '@proton/shared/lib/models'; import { loadModels } from '@proton/shared/lib/models/helper'; import { hasPaidMail } from '@proton/shared/lib/user/helpers'; import isTruthy from '@proton/utils/isTruthy'; import { DropdownActions, Loader, Table, TableBody, TableHeader, TableRow, useModalState } from '../../components'; import { useApi, useCache, useDomains, useDomainsAddresses, useOrganization, useUser } from '../../hooks'; import { SettingsParagraph, SettingsSectionWide, UpgradeBanner } from '../account'; import RestoreAdministratorPrivileges from '../organization/RestoreAdministratorPrivileges'; import CatchAllModal from './CatchAllModal'; import DeleteDomainModal from './DeleteDomainModal'; import DomainModal from './DomainModal'; import DomainName from './DomainName'; import DomainStatus from './DomainStatus'; const DomainsSectionText = () => { return ( <SettingsParagraph className="text-cut" learnMoreUrl={getDomainsSupportURL()}> {c('Message') .t`Connect your custom domain to ${BRAND_NAME} to set up custom email addresses (e.g., you@yourcompany.com). Our wizard will guide you through the process.`} </SettingsParagraph> ); }; const DomainsSectionInternal = () => { const api = useApi(); const cache = useCache(); const [domains, loadingDomains] = useDomains(); const [domainsAddressesMap, loadingDomainsAddressesMap] = useDomainsAddresses(domains); const [organization, loadingOrganization] = useOrganization(); const [loadingRefresh, withLoadingRefresh] = useLoading(); const [tmpDomainProps, setTmpDomainProps] = useState<{ domain: Domain; domainAddresses: DomainAddress[] } | null>( null ); const [newDomainModalProps, setNewDomainModalOpen, renderNewDomain] = useModalState(); const [editDomainModalProps, setEditDomainModalOpen, renderEditDomain] = useModalState(); const [deleteDomainModalProps, setDeleteDomainModalOpen, renderDeleteDomain] = useModalState(); const [catchAllDomainModalProps, setCatchAllDomainModalOpen, renderCatchAllDomain] = useModalState(); const allModelsArePresent = domains && domainsAddressesMap && organization; const loading = !allModelsArePresent && (loadingDomains || loadingDomainsAddressesMap || loadingOrganization); const UsedDomains = organization?.UsedDomains || 0; const MaxDomains = organization?.MaxDomains || 0; const handleRefresh = async () => { await loadModels([DomainsModel], { api, cache, useCache: false }); }; const reviewText = c('Action').t`Review`; const setCatchAllText = c('Action').t`Set catch-all`; const deleteText = c('Action').t`Delete`; return ( <SettingsSectionWide> {renderNewDomain && <DomainModal {...newDomainModalProps} />} {renderEditDomain && tmpDomainProps && ( <DomainModal domain={tmpDomainProps.domain} domainAddresses={tmpDomainProps.domainAddresses} {...editDomainModalProps} /> )} {renderDeleteDomain && tmpDomainProps && ( <DeleteDomainModal domain={tmpDomainProps.domain} {...deleteDomainModalProps} /> )} {renderCatchAllDomain && tmpDomainProps && ( <CatchAllModal domain={tmpDomainProps.domain} domainAddresses={tmpDomainProps.domainAddresses} {...catchAllDomainModalProps} /> )} {loading ? ( <Loader /> ) : ( <> <RestoreAdministratorPrivileges /> <DomainsSectionText /> <div className="mb-4"> <Button color="norm" onClick={() => setNewDomainModalOpen(true)} className="mr-4"> {c('Action').t`Add domain`} </Button> <Button loading={loadingRefresh || loadingDomainsAddressesMap} onClick={() => withLoadingRefresh(handleRefresh())} >{c('Action').t`Refresh status`}</Button> </div> {!!domains?.length && domainsAddressesMap && ( <Table hasActions responsive="cards"> <TableHeader cells={[ c('Header for addresses table').t`Domain`, c('Header for addresses table').t`Status`, c('Header for addresses table').t`Actions`, ]} /> <TableBody loading={loading} colSpan={4}> {domains.map((domain) => { const domainAddresses = domainsAddressesMap[domain.ID] || []; return ( <TableRow key={domain.ID} labels={[ c('Header for addresses table').t`Domain`, c('Header for addresses table').t`Status`, '', ]} cells={[ <DomainName domain={domain} />, <DomainStatus domain={domain} domainAddresses={domainAddresses} />, <DropdownActions size="small" list={[ { text: reviewText, 'aria-label': `${reviewText} ${domain.DomainName}`, onClick: () => { setTmpDomainProps({ domain, domainAddresses }); setEditDomainModalOpen(true); }, } as const, Array.isArray(domainAddresses) && domainAddresses.length && ({ text: setCatchAllText, 'aria-label': `${setCatchAllText} (${domain.DomainName})`, onClick: () => { setTmpDomainProps({ domain, domainAddresses }); setCatchAllDomainModalOpen(true); }, } as const), { text: deleteText, 'aria-label': `${deleteText} ${domain.DomainName}`, actionType: 'delete', onClick: () => { setTmpDomainProps({ domain, domainAddresses }); setDeleteDomainModalOpen(true); }, } as const, ].filter(isTruthy)} />, ]} /> ); })} </TableBody> </Table> )} <div className="mb-4 color-weak"> {UsedDomains} / {MaxDomains}{' '} {c('Info').ngettext(msgid`domain used`, `domains used`, MaxDomains)} </div> </> )} </SettingsSectionWide> ); }; const DomainsSectionUpgrade = () => { const plus = PLAN_NAMES[PLANS.MAIL]; const bundle = PLAN_NAMES[PLANS.BUNDLE]; const upsellRef = getUpsellRef({ app: APP_UPSELL_REF_PATH.MAIL_UPSELL_REF_PATH, component: UPSELL_COMPONENT.BANNER, feature: MAIL_UPSELL_PATHS.DOMAIN_NAMES, isSettings: true, }); return ( <SettingsSectionWide> <DomainsSectionText /> <UpgradeBanner upsellPath={upsellRef}> {c('new_plans: upgrade').t`Included with ${plus}, ${bundle}, and ${BRAND_NAME} for Business.`} </UpgradeBanner> </SettingsSectionWide> ); }; const DomainsSection = () => { const [user] = useUser(); const hasPermission = user.isAdmin && !user.isSubUser && hasPaidMail(user); return hasPermission ? <DomainsSectionInternal /> : <DomainsSectionUpgrade />; }; export default DomainsSection;
6,153
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/domains/MXSection.js
import { c } from 'ttag'; import { Href } from '@proton/atoms'; import { MAIL_APP_NAME } from '@proton/shared/lib/constants'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { Alert, Label, Table, TableBody, TableHeader, TableRow } from '../../components'; const MXSection = () => { const boldAddresses = <strong key="addresses">{c('Tab in domain modal').t`Addresses`}</strong>; const tableTitles = [ c('Header for domain modal').t`Type`, c('Header for domain modal').t`Host name`, c('Header for domain modal').t`Value / Data / Points to`, c('Header for domain modal').t`Priority`, ]; return ( <> <Alert className="mb-4"> {c('Info') .t`Before you can receive emails for your custom domain addresses at ${MAIL_APP_NAME}, you need to add the following MX records to your DNS. This can typically be done in the control panel of your domain name registrar.`} <div> <Href href={getKnowledgeBaseUrl('/custom-domain')}>{c('Link').t`Learn more`}</Href> </div> </Alert> <Label>{c('Label') .t`Please add the following MX record. Note, DNS records can take several hours to update.`}</Label> <Table responsive="cards"> <TableHeader cells={tableTitles} /> <TableBody> <TableRow labels={tableTitles} cells={['MX', '@', 'mail.protonmail.ch', '10']} /> <TableRow labels={tableTitles} cells={['MX', '@', 'mailsec.protonmail.ch', '20']} /> </TableBody> </Table> <Alert className="mb-4"> {c('Info') .t`Delete any other MX records or make sure ${MAIL_APP_NAME}'s Priority is the lowest number.`} <br /> {c('Info') .jt`If this domain is currently receiving emails, select the ${boldAddresses} tab and add all active email addresses before changing the MX record to ensure a smooth transition.`} </Alert> </> ); }; export default MXSection;
6,154
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/domains/SPFSection.js
import { c } from 'ttag'; import { Href } from '@proton/atoms'; import { MAIL_APP_NAME } from '@proton/shared/lib/constants'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { Alert, Copy, Label, Table, TableBody, TableHeader, TableRow } from '../../components'; import { useNotifications } from '../../hooks'; const SPFSection = () => { const { createNotification } = useNotifications(); const handleCopy = () => createNotification({ text: c('Success').t`SPF value copied to clipboard` }); const spf = <code>include:_spf.protonmail.ch</code>; const spfValue = <code>v=spf1</code>; const valueToCopy = 'v=spf1 include:_spf.protonmail.ch mx ~all'; return ( <> <Alert className="mb-4"> {c('Info') .t`SPF is used to specify who is allowed to send email for the domain so we strongly recommend including ${MAIL_APP_NAME} in your SPF record. Please add the following TXT record into your DNS. This can typically be done in the control panel of your domain name registrar.`} <div> <Href href={getKnowledgeBaseUrl('/anti-spoofing-custom-domain')}>{c('Link').t`Learn more`}</Href> </div> </Alert> <Label>{c('Label') .t`Please add the following TXT record. Note, DNS records can take several hours to update.`}</Label> <Table responsive="cards"> <TableHeader cells={[ c('Header for domain modal').t`Type`, c('Header for domain modal').t`Host name`, c('Header for domain modal').t`Value / Data / Points to`, ]} /> <TableBody> <TableRow labels={[ c('Header for domain modal').t`Type`, c('Header for domain modal').t`Host name`, c('Header for domain modal').t`Value / Data / Points to`, ]} cells={[ <code key="txt">TXT</code>, <code key="at">@</code>, <div className="flex flex-nowrap flex-align-items-center" key="value"> <Copy size="small" onCopy={handleCopy} className="flex-item-noshrink mr-2" value={valueToCopy} />{' '} <code className="text-ellipsis lh-rg" title={valueToCopy}> {valueToCopy} </code> </div>, ]} /> </TableBody> </Table> <Alert className="mb-4">{c('Info') .jt`If you want to keep an existing SPF record, you can just add ${spf} to it after the ${spfValue}. Do not create multiple SPF records.`}</Alert> </> ); }; export default SPFSection;
6,155
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/domains/VerifySection.js
import PropTypes from 'prop-types'; import { c } from 'ttag'; import { Href } from '@proton/atoms'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { Alert, Copy, Label, Table, TableBody, TableHeader, TableRow } from '../../components'; import { useNotifications } from '../../hooks'; const VerifySection = ({ domain }) => { const { createNotification } = useNotifications(); const handleCopy = () => createNotification({ text: c('Success').t`Verification code copied to clipboard` }); const domainName = domain.DomainName; return ( <> <Alert className="mb-4"> {c('Info for domain modal') .t`For security reasons, we need to verify that you are the owner of ${domainName}. Please add the following DNS TXT record to your domain. This can typically be done in the control panel of your domain name registrar.`} <div> <Href href={getKnowledgeBaseUrl('/custom-domain')}>{c('Link').t`Learn more`}</Href> </div> </Alert> <Alert className="mb-4" type="warning"> {c('Warning for domain modal') .t`After successful verification, do not remove this TXT record as it is needed to confirm that you continue to own the domain.`} </Alert> <Label>{c('Label for domain modal').t`Please add the following TXT record:`}</Label> <Table responsive="cards"> <TableHeader cells={[ c('Header for domain modal').t`Type`, c('Header for domain modal').t`Host name`, c('Header for domain modal').t`Value / Data / Points to`, ]} /> <TableBody> <TableRow labels={[ c('Header for domain modal').t`Type`, c('Header for domain modal').t`Host name`, c('Header for domain modal').t`Value / Data / Points to`, ]} cells={[ <code key="txt">TXT</code>, <code key="at">@</code>, <div className="flex flex-nowrap flex-align-items-center" key="value"> <Copy onCopy={handleCopy} size="small" className="flex-item-noshrink mr-2" value={domain.VerifyCode} />{' '} <code className="text-ellipsis lh-rg" title={domain.VerifyCode}> {domain.VerifyCode} </code> </div>, ]} /> </TableBody> </Table> <Alert className="mb-4" type="warning">{c('Warning for domain modal') .t`It can take up to a day for DNS changes to update.`}</Alert> </> ); }; VerifySection.propTypes = { domain: PropTypes.object.isRequired, }; export default VerifySection;
6,156
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/domains/index.ts
export { default as DKIMSection } from './DKIMSection'; export { default as DomainStatus } from './DomainStatus'; export { default as SPFSection } from './SPFSection'; export { default as VerifySection } from './VerifySection'; export { default as AddressCatchAll } from './AddressCatchAll'; export { default as MXSection } from './MXSection'; export { default as DMARCSection } from './DMARCSection'; export { default as CatchAllModal } from './CatchAllModal'; export { default as DomainName } from './DomainName'; export { default as DomainModal } from './DomainModal'; export { default as DomainsSection } from './DomainsSection'; export { default as AddressesTable } from './AddressesTable'; export { default as DomainSection } from './DomainSection'; export { default as CatchAllSection } from './CatchAllSection';
6,157
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/drawer/DrawerAppFooter.tsx
import { ReactElement, cloneElement, useEffect, useRef } from 'react'; import Footer from '@proton/components/components/footer/Footer'; import { useElementRect, useNotifications } from '@proton/components/hooks'; import { modalTwoBackdropRootClassName } from '@proton/shared/lib/busy'; import throttle from '@proton/utils/throttle'; interface Props { buttons: ReactElement[]; offsetNotifications?: boolean; } const DrawerAppFooter = ({ buttons, offsetNotifications }: Props) => { const { setOffset } = useNotifications(); const ref = useRef<HTMLDivElement>(null); const rect = useElementRect(ref); const hasFooter = buttons.length > 0; useEffect(() => { if (!offsetNotifications || !hasFooter || !rect || !ref.current) { setOffset(undefined); return; } const handler = throttle(() => { const elements = document.elementsFromPoint(rect.x, rect.y); // Ignore the modal backdrop element, assume it's from the modal animation closing out const filteredElements = [...elements].filter( (element) => !element.classList.contains(modalTwoBackdropRootClassName) ); const element = filteredElements[0]; if ( // The drawer footer itself element === ref.current || // Any element inside the drawer footer ref.current?.contains(element) ) { const padding = 4; setOffset({ y: rect.height + padding }); } else { setOffset(undefined); } }, 33); const observer = new MutationObserver(handler); // Observe any changes to the children in body. This is a heuristic to determine when // floating elements might be covering the footer. observer.observe(document.body, { childList: true }); return () => { observer.disconnect(); }; }, [offsetNotifications, hasFooter, rect?.height]); if (!hasFooter) { return null; } // Adding keys to buttons const clonedButtons = buttons.map((button, index) => cloneElement(button, { key: button.key || `footer-button-${index}` }) ); return ( <div className="relative" ref={ref}> <Footer className="p-3 flex-column gap-2">{clonedButtons}</Footer> </div> ); }; export default DrawerAppFooter;
6,158
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/drawer/DrawerAppHeader.scss
@import '~@proton/styles/scss/lib'; .drawer-app-header { &-dropdownItem { inset-block-start: 100%; background-color: var(--background-norm); z-index: $layer-floating-frames; border-end-end-radius: var(--border-radius-xl); border-end-start-radius: var(--border-radius-xl); } } // Need to shift slightly the button to the left and to lower the padding .drawer-header-button { padding-inline-start: 0.25em; padding-inline-end: 0.25em; margin-inline-start: -0.25em; }
6,159
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/drawer/DrawerAppHeader.tsx
import { ReactNode, useCallback, useEffect, useRef } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { useTheme } from '@proton/components/containers'; import { closeDrawerFromChildApp, getIsDrawerPostMessage, getIsNativeDrawerApp, postMessageFromIframe, } from '@proton/shared/lib/drawer/helpers'; import { DRAWER_EVENTS } from '@proton/shared/lib/drawer/interfaces'; import { KeyboardKey } from '@proton/shared/lib/interfaces'; import { Icon, Tooltip } from '../../components'; import Header from '../../components/header/Header'; import { useConfig, useDrawer, useEventManager, useHotkeys } from '../../hooks'; import './DrawerAppHeader.scss'; export interface PrivateIframeHeaderProps { title?: ReactNode; onCloseDropdown?: () => void; // Need to set this to true for iframes apps. When inside an iframe, the window width is really small // So, If we want to display a dropdown "correctly" (not in a modal) we need to make a special case for now customDropdown?: ReactNode; } const DrawerAppHeader = ({ title, onCloseDropdown, customDropdown }: PrivateIframeHeaderProps) => { const { call } = useEventManager(); const theme = useTheme(); const { appInView, setAppInView, parentApp } = useDrawer(); const { APP_NAME: currentApp } = useConfig(); const wrapperRef = useRef<HTMLDivElement>(null); const dropdownRef = useRef<HTMLDivElement>(null); // Listen for click events outside the header in order to close the dropdown useEffect(() => { if (!customDropdown) { return; } const handleClickOutside = ({ target }: MouseEvent) => { const targetNode = target as HTMLElement; const wrapperEl = wrapperRef.current; // Do nothing if clicking ref's element or descendent elements if (wrapperEl?.contains(targetNode)) { return; } onCloseDropdown?.(); }; document.addEventListener('click', handleClickOutside, { capture: true }); return () => { document.removeEventListener('click', handleClickOutside, { capture: true }); }; }, [customDropdown]); useHotkeys(dropdownRef, [ [ KeyboardKey.Escape, (e) => { if (customDropdown) { e.stopPropagation(); onCloseDropdown?.(); } }, ], ]); const handleToggleIFrame = (nextUrl?: string, closeDefinitely?: boolean) => { if (appInView && getIsNativeDrawerApp(appInView)) { // we have access to parent drawer methods setAppInView(undefined); } else { // Otherwise we are inside an iframed app if (!parentApp) { // just for TS safety return; } onCloseDropdown?.(); // If we receive a nextUrl, it means we want to switch to another iframed app, so we need to pass the nextUrl if (nextUrl) { postMessageFromIframe( { type: DRAWER_EVENTS.SWITCH, payload: { nextUrl }, }, parentApp ); } else { // Otherwise, we only want to close the iframed app closeDrawerFromChildApp(parentApp, currentApp, closeDefinitely); } } }; const handleTriggerToggleFromOutside = useCallback( (event: MessageEvent) => { if (!getIsDrawerPostMessage(event)) { return; } switch (event.data.type) { case DRAWER_EVENTS.CALL_EVENT_MANAGER_FROM_OUTSIDE: case DRAWER_EVENTS.SHOW: void call(); break; case DRAWER_EVENTS.UPDATE_THEME: const { themeSetting } = event.data.payload; theme.setThemeSetting(themeSetting); break; default: break; } }, [theme] ); // Listen for app closing or app switching events outside the iframe useEffect(() => { window.addEventListener('message', handleTriggerToggleFromOutside); return () => { window.removeEventListener('message', handleTriggerToggleFromOutside); }; }, [handleTriggerToggleFromOutside]); return ( <div className="relative ui-standard color-norm flex-item-noshrink" ref={wrapperRef}> <Header className="header--drawer p-3"> <div className="drawer-app-header-actions flex flex-justify-space-between flex-align-items-center w-full"> <span className="text-bold text-lg">{title}</span> <div className="flex flex-align-items-center flex-nowrap gap-2"> <Tooltip title={c('Action').t`Close`}> <Button data-testid="drawer-app-header:close" icon color="weak" shape="ghost" onClick={() => handleToggleIFrame()} > <Icon name="cross-big" size={16} /> </Button> </Tooltip> </div> </div> </Header> {customDropdown && ( <div className="drawer-app-header-dropdownItem absolute w-full border-top border-weak shadow-norm" ref={dropdownRef} > {customDropdown} </div> )} </div> ); }; export default DrawerAppHeader;
6,160
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/drawer/DrawerAppHeaderCustomTitle.tsx
import { ReactNode, useRef } from 'react'; import { Button } from '@proton/atoms'; import { KeyboardKey } from '@proton/shared/lib/interfaces'; import { Icon } from '../../components'; import { Color } from '../../components/button/ButtonGroup'; import { useHotkeys } from '../../hooks'; interface Props { onToggleDropdown: () => void; onCloseDropdown?: () => void; dropdownTitle: ReactNode; buttonColor?: Color; dropdownExpanded?: boolean; } const DrawerAppHeaderCustomTitle = ({ onToggleDropdown, onCloseDropdown, dropdownTitle, buttonColor, dropdownExpanded, }: Props) => { const buttonRef = useRef<HTMLButtonElement>(null); useHotkeys(buttonRef, [ [ KeyboardKey.Escape, (e) => { e.stopPropagation(); onCloseDropdown?.(); }, ], ]); return ( <div className="flex flex-column iframe-header"> <Button shape="ghost" size="small" color={buttonColor} ref={buttonRef} onClick={onToggleDropdown} className="drawer-header-button" aria-expanded={dropdownExpanded} > {dropdownTitle} <Icon name={dropdownExpanded ? 'chevron-up-filled' : 'chevron-down-filled'} className="ml-1" /> </Button> </div> ); }; export default DrawerAppHeaderCustomTitle;
6,161
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/drawer/MailQuickSettingsReminderContextProvider.tsx
import { ReactNode, useEffect, useMemo } from 'react'; import { ThemeColor } from '@proton/colors/types'; import { useLocalState, useUser } from '@proton/components/hooks'; import { QuickSettingsRemindersContext } from '@proton/components/hooks/drawer/useQuickSettingsReminders'; import useKeyTransparencyNotification from '@proton/components/hooks/useKeyTransparencyNotification'; import { KEY_TRANSPARENCY_REMINDER_UPDATE } from '@proton/shared/lib/drawer/interfaces'; import isTruthy from '@proton/utils/isTruthy'; interface Props { defaultReminders?: ThemeColor[]; children: ReactNode; } const MailQuickSettingsReminderContextProvider = ({ defaultReminders = [], children }: Props) => { const [user] = useUser(); const [keyTransparencyNotificationSeen, toggleKeyTransparencyNotificationSeen] = useLocalState( false, `${user.ID || 'item'}-seen-key-transparency-notification` ); const keyTransparencyNotification = useKeyTransparencyNotification(); const reminders: ThemeColor[] = useMemo(() => { const keyTransparencyReminder: ThemeColor | undefined = keyTransparencyNotification && !keyTransparencyNotificationSeen ? keyTransparencyNotification : undefined; return [keyTransparencyReminder, ...defaultReminders].filter(isTruthy); }, [keyTransparencyNotification, keyTransparencyNotificationSeen, defaultReminders]); useEffect(() => { const resetKeyTransparencyReminder = (event: CustomEvent) => { const value = event.detail.value || true; if (value) { toggleKeyTransparencyNotificationSeen(value); } }; document.addEventListener(KEY_TRANSPARENCY_REMINDER_UPDATE, resetKeyTransparencyReminder as EventListener); return () => { document.removeEventListener( KEY_TRANSPARENCY_REMINDER_UPDATE, resetKeyTransparencyReminder as EventListener ); }; }, []); return ( <QuickSettingsRemindersContext.Provider value={{ reminders, }} > {children} </QuickSettingsRemindersContext.Provider> ); }; export default MailQuickSettingsReminderContextProvider;
6,162
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/drawer/index.ts
export { default as DrawerAppFooter } from './DrawerAppFooter'; export { default as DrawerAppHeader } from './DrawerAppHeader'; export { default as DrawerAppHeaderCustomTitle } from './DrawerAppHeaderCustomTitle';
6,163
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/drive/index.ts
export * from './settings';
6,164
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/drive
petrpan-code/ProtonMail/WebClients/packages/components/containers/drive/settings/RetentionDaysSection.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { Radio, RevisionsUpgradeBanner, Tooltip, useConfirmActionModal, useRevisionRetentionDays, useUser, } from '@proton/components'; import type { RevisionRetentionDaysSetting } from '@proton/shared/lib/interfaces/drive/userSettings'; import clsx from '@proton/utils/clsx'; import { getRetentionLabel } from './retentionLabels'; const RetentionDaysSection = () => { const [{ hasPaidDrive }] = useUser(); const [confirmActionModal, showConfirmActionModal] = useConfirmActionModal(); const { revisionRetentionDays, hasValueChanged, isLoading, isSubmitLoading, handleSubmit, handleChange } = useRevisionRetentionDays(hasPaidDrive, showConfirmActionModal); const options: { value: RevisionRetentionDaysSetting; label: string; disabled?: boolean; }[] = [ { value: 0, label: c('Label').t`Don't keep versions` }, { value: 7, label: getRetentionLabel(7) }, { value: 30, label: getRetentionLabel(30) }, { value: 180, label: getRetentionLabel(180) }, { value: 365, label: getRetentionLabel(365) }, { value: 3650, label: getRetentionLabel(3650) }, ]; return ( <div className="max-w-custom" style={{ '--max-w-custom': '37em' }}> {!hasPaidDrive ? <RevisionsUpgradeBanner /> : null} <form className="flex flex-column flex-align-items-start gap-2 mt-6" onSubmit={handleSubmit}> <span className="sr-only" id="id_desc_history"> {c('Info').t`Version history`} </span> {options.map((option) => { const id = option.value.toString(); const radioProps = { onChange: () => handleChange(option.value), id: `retention${id}`, name: 'retention', // If free user revisionRetentionDays will be the default and only available value disabled: isLoading || isSubmitLoading || (option.value !== revisionRetentionDays && !hasPaidDrive), checked: !isLoading && revisionRetentionDays === option.value, className: clsx( 'w-full flex flex-nowrap border rounded p-3', !isLoading && revisionRetentionDays === option.value ? 'border-primary' : 'border-norm' ), }; if (option.value !== revisionRetentionDays && !hasPaidDrive) { return ( <Tooltip key={id} title={c('Info').t`Upgrade to unlock`} originalPlacement="right"> <div className="w-full"> <Radio aria-describedby="id_desc_history" {...radioProps}> {option.label} </Radio> </div> </Tooltip> ); } return ( <Radio aria-describedby="id_desc_history" key={id} {...radioProps}> {option.label} </Radio> ); })} <Button className="mt-6" type="submit" size="large" color="norm" loading={isSubmitLoading} disabled={!hasValueChanged} >{c('Action').t`Save changes`}</Button> </form> {confirmActionModal} </div> ); }; export default RetentionDaysSection;
6,165
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/drive
petrpan-code/ProtonMail/WebClients/packages/components/containers/drive/settings/index.ts
export { default as RetentionDaysSection } from './RetentionDaysSection'; export * from './retentionLabels';
6,166
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/drive
petrpan-code/ProtonMail/WebClients/packages/components/containers/drive/settings/retentionLabels.ts
import { c, msgid } from 'ttag'; import { RevisionRetentionDaysSetting } from '@proton/shared/lib/interfaces/drive/userSettings'; const retentionLabelForDays = (nbDay: number) => c('Label').ngettext(msgid`${nbDay} day`, `${nbDay} days`, nbDay); const retentionLabelForYears = (nbYear: number) => c('Label').ngettext(msgid`${nbYear} year`, `${nbYear} years`, nbYear); export const getRetentionLabel = (nbDay: RevisionRetentionDaysSetting) => { // 10 years if (nbDay === 3650) { return retentionLabelForYears(10); } return retentionLabelForDays(nbDay); };
6,167
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/emailPrivacy/EmailPrivacySection.tsx
import React, { useEffect, useState } from 'react'; import { c } from 'ttag'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { DEFAULT_MAILSETTINGS, IMAGE_PROXY_FLAGS } from '@proton/shared/lib/mail/mailSettings'; import { Info } from '../../components/link'; import { useFeatures, useMailSettings } from '../../hooks'; import SettingsLayout from '../account/SettingsLayout'; import SettingsLayoutLeft from '../account/SettingsLayoutLeft'; import SettingsLayoutRight from '../account/SettingsLayoutRight'; import { FeatureCode } from '../features'; import PreventTrackingToggle from './PreventTrackingToggle'; import ProtectionModeSelect from './ProtectionModeSelect'; import RemoteToggle from './RemoteToggle'; const EmailPrivacySection = () => { const [{ HideRemoteImages, ImageProxy } = DEFAULT_MAILSETTINGS] = useMailSettings(); const [hideRemoteImages, setHideRemoteImages] = useState(HideRemoteImages); const [, setImageProxy] = useState(ImageProxy); const { getFeature } = useFeatures([FeatureCode.SpyTrackerProtectionIncorporator]); const { feature: featureSpyTrackerIncorporator } = getFeature(FeatureCode.SpyTrackerProtectionIncorporator); // Handle updates from the Event Manager. useEffect(() => { setImageProxy(ImageProxy); }, [ImageProxy]); const handleChangeShowImage = (newValue: number) => setHideRemoteImages(newValue); const showProtectionMode = ImageProxy !== IMAGE_PROXY_FLAGS.NONE && featureSpyTrackerIncorporator?.Value; return ( <> <SettingsLayout> <SettingsLayoutLeft> <label htmlFor="remoteToggle" className="text-semibold"> <span className="mr-2">{c('Label').t`Auto show remote images`}</span> <Info url={getKnowledgeBaseUrl('/images-by-default')} title={c('Info') .t`Loaded content is being protected by our proxy when tracker protection is activated.`} /> </label> </SettingsLayoutLeft> <SettingsLayoutRight className="pt-2"> <RemoteToggle id="remoteToggle" hideRemoteImages={hideRemoteImages} onChange={handleChangeShowImage} data-testid="privacy:remote-content-toggle" /> </SettingsLayoutRight> </SettingsLayout> <> <SettingsLayout> <SettingsLayoutLeft> <label htmlFor="preventTrackingToggle" className="text-semibold"> <span className="mr-2">{c('Label').t`Block email tracking`}</span> <Info url={getKnowledgeBaseUrl('/email-tracker-protection')} title={c('Info').t`Blocks senders from seeing if and when you opened a message.`} /> </label> </SettingsLayoutLeft> <SettingsLayoutRight className="pt-2"> <PreventTrackingToggle id="preventTrackingToggle" preventTracking={ImageProxy} data-testid="privacy:prevent-tracking-toggle" /> </SettingsLayoutRight> </SettingsLayout> {showProtectionMode && ( <SettingsLayout> <SettingsLayoutLeft> <label htmlFor="protectiontModeToggle" className="text-semibold"> <span className="mr-2">{c('Label').t`Protection mode`}</span> <Info url={getKnowledgeBaseUrl('/email-tracker-protection')} title={c('Info') .t`Hides identifying information by loading remote content through a proxy. Option to store content as attachments.`} /> </label> </SettingsLayoutLeft> <SettingsLayoutRight className="pt-2"> <ProtectionModeSelect id="protectiontModeToggle" defaultProtectionMode={ImageProxy} data-testid="privacy:protect-mode-select" /> </SettingsLayoutRight> </SettingsLayout> )} </> </> ); }; export default EmailPrivacySection;
6,168
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/emailPrivacy/PreventTrackingToggle.tsx
import { c } from 'ttag'; import { useLoading } from '@proton/hooks'; import { updateImageProxy } from '@proton/shared/lib/api/mailSettings'; import { hasBit } from '@proton/shared/lib/helpers/bitset'; import { IMAGE_PROXY_FLAGS } from '@proton/shared/lib/mail/mailSettings'; import { Toggle } from '../../components/toggle'; import { useApi, useEventManager, useNotifications, useToggle } from '../../hooks'; interface Props { id: string; preventTracking: number; onEnable?: () => void; } const PreventTrackingToggle = ({ id, preventTracking, onEnable, ...rest }: Props) => { const [loading, withLoading] = useLoading(); const { createNotification } = useNotifications(); const { call } = useEventManager(); const api = useApi(); const { state, toggle } = useToggle(hasBit(preventTracking, IMAGE_PROXY_FLAGS.PROXY)); const handleChange = async (checked: boolean) => { if (!checked) { await api(updateImageProxy(IMAGE_PROXY_FLAGS.INCORPORATOR, 'remove')); } await api(updateImageProxy(IMAGE_PROXY_FLAGS.PROXY, checked ? 'add' : 'remove')); if (checked) { onEnable?.(); } await call(); toggle(); createNotification({ text: c('Success').t`Preference saved` }); }; return ( <Toggle id={id} checked={state} onChange={({ target }) => withLoading(handleChange(target.checked))} loading={loading} {...rest} /> ); }; export default PreventTrackingToggle;
6,169
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/emailPrivacy/ProtectionModeSelect.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { useLoading } from '@proton/hooks'; import { updateImageProxy } from '@proton/shared/lib/api/mailSettings'; import { IMAGE_PROXY_FLAGS } from '@proton/shared/lib/mail/mailSettings'; import { Select } from '../../components/select'; import { useApi, useEventManager, useNotifications } from '../../hooks'; interface Props { id: string; defaultProtectionMode: number; } const ProtectionModeSelect = ({ id, defaultProtectionMode, ...rest }: Props) => { const [protectionMode, setProtectionMode] = useState(defaultProtectionMode); const { createNotification } = useNotifications(); const [loading, withLoading] = useLoading(); const api = useApi(); const { call } = useEventManager(); const options = [ { text: c('Option protection mode').t`Load content via proxy (recommended)`, value: IMAGE_PROXY_FLAGS.PROXY }, { text: c('Option protection mode').t`Load content via proxy and store as attachments`, value: IMAGE_PROXY_FLAGS.ALL, }, ]; const handleChange = async (protectionMode: number) => { if (protectionMode === IMAGE_PROXY_FLAGS.PROXY) { await api(updateImageProxy(IMAGE_PROXY_FLAGS.INCORPORATOR, 'remove')); } else { await api(updateImageProxy(IMAGE_PROXY_FLAGS.INCORPORATOR, 'add')); } await call(); setProtectionMode(protectionMode); createNotification({ text: c('Success').t`Preference saved` }); }; return ( <Select id={id} value={protectionMode} options={options} onChange={({ target }) => withLoading(handleChange(+target.value))} loading={loading} {...rest} /> ); }; export default ProtectionModeSelect;
6,170
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/emailPrivacy/RemoteToggle.tsx
import { c } from 'ttag'; import { useLoading } from '@proton/hooks'; import { updateHideRemoteImages } from '@proton/shared/lib/api/mailSettings'; import { SHOW_IMAGES } from '@proton/shared/lib/mail/mailSettings'; import { Toggle } from '../../components'; import { useApi, useEventManager, useNotifications, useToggle } from '../../hooks'; interface Props { id: string; hideRemoteImages: number; onChange: (value: number) => void; } const RemoteToggle = ({ id, hideRemoteImages, onChange, ...rest }: Props) => { const [loading, withLoading] = useLoading(); const { createNotification } = useNotifications(); const { call } = useEventManager(); const api = useApi(); const { state, toggle } = useToggle(hideRemoteImages === SHOW_IMAGES.SHOW); const handleChange = async (checked: boolean) => { const bit = checked ? SHOW_IMAGES.SHOW : SHOW_IMAGES.HIDE; await api(updateHideRemoteImages(bit)); await call(); toggle(); onChange(bit); createNotification({ text: c('Success').t`Preference saved` }); }; return ( <Toggle id={id} checked={state} onChange={({ target }) => withLoading(handleChange(target.checked))} loading={loading} {...rest} /> ); }; export default RemoteToggle;
6,171
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/emailPrivacy/index.ts
export { default as EmailPrivacySection } from './EmailPrivacySection'; export { default as RemoteToggle } from './RemoteToggle'; export { default as ProtectionModeSelect } from './ProtectionModeSelect';
6,172
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/error/AccessDeniedError.tsx
import { c } from 'ttag'; import noAccessErrorSvg from '@proton/styles/assets/img/errors/no-access-page.svg'; import IllustrationPlaceholder from '../illustration/IllustrationPlaceholder'; const AccessDeniedError = () => { return <IllustrationPlaceholder title={c('Error message').t`Access denied`} url={noAccessErrorSvg} />; }; export default AccessDeniedError;
6,173
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/error/GenericError.tsx
import { ReactNode } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import ElectronDraggeableHeader from '@proton/components/components/electron/ElectronDraggeableHeader'; import errorImg from '@proton/styles/assets/img/errors/error-generic.svg'; import networkErrorImg from '@proton/styles/assets/img/errors/error-network.svg'; import clsx from '@proton/utils/clsx'; import Icon from '../../components/icon/Icon'; import IllustrationPlaceholder from '../illustration/IllustrationPlaceholder'; interface Props { className?: string; children?: ReactNode; big?: boolean; isNetworkError?: boolean; } const GenericError = ({ children, className, big, isNetworkError }: Props) => { const title = c('Error message').t`Something went wrong`; const line1 = c('Error message').jt`Please refresh the page or try again later.`; const display: 'default' | 'with-refresh' | 'custom' = (() => { if (children) { return 'custom'; } return big ? 'with-refresh' : 'default'; })(); return ( <div className={clsx('m-auto', big ? 'p-1' : 'p-2', className)}> {big && <ElectronDraggeableHeader />} <IllustrationPlaceholder title={title} titleSize={big ? 'big' : 'regular'} url={isNetworkError ? networkErrorImg : errorImg} > {display === 'default' && <div className="text-weak text-sm">{line1}</div>} {display === 'with-refresh' && ( <> <div className="text-weak text-rg">{line1}</div> <div className="mt-8"> <Button onClick={() => window.location.reload()}> <Icon name="arrow-rotate-right" /> <span className="ml-4">{c('Action').t`Refresh the page`}</span> </Button> </div> </> )} {display === 'custom' && children} </IllustrationPlaceholder> </div> ); }; export default GenericError;
6,174
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/error/InternalServerError.tsx
import { c } from 'ttag'; import internalServerErrorSvg from '@proton/styles/assets/img/errors/error-500.svg'; import IllustrationPlaceholder from '../illustration/IllustrationPlaceholder'; const InternalServerError = () => { return ( <IllustrationPlaceholder title={c('Error message').t`Internal server error`} url={internalServerErrorSvg}> <> <span>{c('Error message').t`Brace yourself till we get the error fixed.`}</span> <span>{c('Error message').t`You may also refresh the page or try again later.`}</span> </> </IllustrationPlaceholder> ); }; export default InternalServerError;
6,175
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/error/NotFoundError.tsx
import { c } from 'ttag'; import notFoundErrorSvg from '@proton/styles/assets/img/errors/error-404.svg'; import IllustrationPlaceholder from '../illustration/IllustrationPlaceholder'; const NotFoundError = () => { return <IllustrationPlaceholder title={c('Error message').t`Not found`} url={notFoundErrorSvg} />; }; export default NotFoundError;
6,176
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/error/index.ts
export { default as GenericError } from './GenericError'; export { default as InternalServerError } from './InternalServerError'; export { default as NotFoundError } from './NotFoundError'; export { default as AccessDeniedError } from './AccessDeniedError';
6,177
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/eventManager/EventManagerProvider.tsx
import { ReactNode, useEffect } from 'react'; import { EventManager } from '@proton/shared/lib/eventManager/eventManager'; import EventManagerContext from './context'; interface Props { eventManager: EventManager; children: ReactNode; } const EventManagerProvider = ({ eventManager, children }: Props) => { useEffect(() => { eventManager.start(); return () => { eventManager.stop(); eventManager.reset(); }; }, []); return <EventManagerContext.Provider value={eventManager}>{children}</EventManagerContext.Provider>; }; export default EventManagerProvider;
6,178
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/eventManager/EventModelListener.js
import { useEffect } from 'react'; import PropTypes from 'prop-types'; import { EVENT_ERRORS } from '@proton/shared/lib/errors'; import { hasBit } from '@proton/shared/lib/helpers/bitset'; import { ContactEmailsModel, ContactsModel, DomainsModel, HolidaysCalendarsModel, UserModel, UserSettingsModel, } from '@proton/shared/lib/models'; import { AddressesModel } from '@proton/shared/lib/models/addressesModel'; import { STATUS } from '@proton/shared/lib/models/cache'; import { MembersModel } from '@proton/shared/lib/models/membersModel'; import { OrganizationModel } from '@proton/shared/lib/models/organizationModel'; import { SubscriptionModel } from '@proton/shared/lib/models/subscriptionModel'; import { useCache, useEventManager } from '../../hooks'; import { clearAddressesKeysCache, clearUsersKeysCache } from '../app/clearKeyCache'; const EventModelListener = ({ models }) => { const { subscribe } = useEventManager(); const cache = useCache(); useEffect(() => { const modelsMap = models.reduce((acc, model) => { return { ...acc, [model.key]: model, }; }, {}); return subscribe((data) => { /** * Before updating model values */ if (data[UserSettingsModel.key]) { const oldUserSettingsRecord = cache.get(UserSettingsModel.key); if (oldUserSettingsRecord?.value.Locale !== data[UserSettingsModel.key].Locale) { // The directory of holidays calendars is fetched translated from back-end, so when the app language // is changed we need to clear the cache so that next time they're requested we fetch them in the new language cache.delete(HolidaysCalendarsModel.key); } } /** * Update model values */ for (const key of Object.keys(data)) { const model = modelsMap[key]; if (!model) { continue; } const { value: oldValue, status } = cache.get(key) || {}; if (status === STATUS.RESOLVED) { cache.set(key, { status: STATUS.RESOLVED, value: model.update(oldValue, data[key]), }); } } /** * After updating model values */ if (hasBit(data.Refresh, EVENT_ERRORS.CONTACTS)) { cache.delete(ContactsModel.key); cache.delete(ContactEmailsModel.key); } // If user model was changed. if (data[UserModel.key]) { const { value: user } = cache.get(UserModel.key); // Do not get any events for these models, so delete them. if (user.isFree) { cache.delete(SubscriptionModel.key); cache.delete(OrganizationModel.key); cache.delete(DomainsModel.key); cache.delete(MembersModel.key); } // Since the keys could have changed, clear the cached keys. clearUsersKeysCache(cache); } if (data[AddressesModel.key]) { // TODO: Be smarter and just delete the address keys that changed // Since the keys could have changed, clear the cached keys. clearAddressesKeysCache(cache); } // The API sometimes does not send the user model when used space changes... if (data.UsedSpace !== undefined) { const oldUserRecord = cache.get(UserModel.key); cache.set(UserModel.key, { ...oldUserRecord, value: { ...oldUserRecord.value, UsedSpace: data.UsedSpace, }, }); } }); }, []); return null; }; EventModelListener.propTypes = { models: PropTypes.array.isRequired, }; export default EventModelListener;
6,179
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/eventManager/EventNotices.js
import { useEffect } from 'react'; import { CryptoProxy } from '@proton/crypto'; import { arrayToHexString, binaryStringToArray, encodeUtf8 } from '@proton/crypto/lib/utils'; import { getItem, setItem } from '@proton/shared/lib/helpers/storage'; import { useEventManager, useNotifications, useUser } from '../../hooks'; const getID = async (text) => { const id = arrayToHexString( await CryptoProxy.computeHash({ algorithm: 'unsafeMD5', data: binaryStringToArray(encodeUtf8(text)), }) ); return `NOTICE-${id}`; }; const serialize = (number) => `${number}`; const deserialize = (string) => (string ? +string : 0); // Two weeks in milliseconds. const EXPIRATION = 86400 * 1000 * 14; const EventNotices = () => { const { subscribe } = useEventManager(); const { createNotification } = useNotifications(); const [user] = useUser(); useEffect(() => { const notify = (text) => { createNotification({ type: 'info', text, expiration: -1, }); }; const handleNotice = async (text) => { const id = await getID(`${user.ID}${text}`); const oldTimestamp = deserialize(getItem(id)); const now = Date.now(); if (!oldTimestamp || now > oldTimestamp) { notify(text); setItem(id, serialize(now + EXPIRATION)); } }; return subscribe(({ Notices }) => { if (!Array.isArray(Notices)) { return; } Notices.forEach((text) => { handleNotice(text); }); }); }, []); return null; }; export default EventNotices;
6,180
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/eventManager/context.ts
import { createContext } from 'react'; import createEventManager from '@proton/shared/lib/eventManager/eventManager'; export default createContext<ReturnType<typeof createEventManager> | null>(null);
6,181
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/eventManager/index.ts
export { default as EventManagerProvider } from './EventManagerProvider'; export { default as EventNotices } from './EventNotices'; export { default as EventModelListener } from './EventModelListener'; export * from './calendar';
6,182
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/eventManager
petrpan-code/ProtonMail/WebClients/packages/components/containers/eventManager/calendar/ModelEventManagerProvider.tsx
import { ReactNode, createContext, useContext, useEffect, useRef } from 'react'; import { queryLatestModelEventID, queryModelEvents } from '@proton/shared/lib/api/calendars'; import createEventManager, { EVENT_ID_KEYS, EventManager } from '@proton/shared/lib/eventManager/eventManager'; import { Api } from '@proton/shared/lib/interfaces'; import { SimpleMap } from '@proton/shared/lib/interfaces/utils'; import { useApi } from '../../../hooks'; const CalendarModelEventManagerContext = createContext<CalendarModelEventManager | null>(null); type SubscribeCallback = (data: any) => void; export interface CalendarModelEventManager { start: (calendarIDs: string[]) => void[]; stop: (calendarIDs: string[]) => void[]; reset: (calendarIDs: string[]) => void[]; call: (calendarIDs: string[]) => Promise<void[]>; subscribe: (calendarIDs: string[], cb: SubscribeCallback) => () => void; } const createCalendarEventManagerById = async (api: Api, calendarID: string) => { const { CalendarModelEventID } = await api<{ CalendarModelEventID: string }>(queryLatestModelEventID(calendarID)); const eventManager = createEventManager({ api, eventID: CalendarModelEventID, query: (eventId: string) => queryModelEvents(calendarID, eventId), eventIDKey: EVENT_ID_KEYS.CALENDAR, }); eventManager.start(); return eventManager; }; const getOrSetRecord = (calendarID: string, eventManagers: SimpleMap<EventManagerCacheRecord>, api: Api) => { const cachedValue = eventManagers[calendarID]; if (!cachedValue || (cachedValue.eventManager === undefined && cachedValue.promise === undefined)) { const promise = createCalendarEventManagerById(api, calendarID) .then((eventManager) => { eventManagers[calendarID] = { eventManager, promise: undefined, }; return eventManager; }) .catch(() => { delete eventManagers[calendarID]; return undefined; }); const record = { promise, eventManager: undefined }; eventManagers[calendarID] = record; return record; } return cachedValue; }; type EventManagerCacheRecord = | { eventManager: EventManager; promise: undefined; } | { promise: Promise<EventManager | undefined>; eventManager: undefined; }; interface Props { children: ReactNode; } const ModelEventManagerProvider = ({ children }: Props) => { const api = useApi(); const silentApi: <T>(config: object) => Promise<T> = (config) => api({ ...config, silence: true }); const eventManagersByIdRef = useRef<SimpleMap<EventManagerCacheRecord>>({}); useEffect(() => { return () => { const eventManagers = eventManagersByIdRef.current; eventManagersByIdRef.current = {}; Object.values(eventManagers).forEach((record) => { if (!record) { return; } if (record.promise) { record.promise.then((eventManager) => { if (!eventManager) { return; } eventManager.stop(); eventManager.reset(); }); } if (record.eventManager) { record.eventManager.stop(); record.eventManager.reset(); } }); }; }, []); const start = (calendarIDs: string[]) => { const eventManagers = eventManagersByIdRef.current; return calendarIDs.map((calendarID) => { return eventManagers[calendarID]?.eventManager?.start(); }); }; const stop = (calendarIDs: string[]) => { const eventManagers = eventManagersByIdRef.current; return calendarIDs.map((calendarID) => { return eventManagers[calendarID]?.eventManager?.stop(); }); }; const reset = (calendarIDs: string[]) => { const eventManagers = eventManagersByIdRef.current; return calendarIDs.map((calendarID) => { return eventManagers[calendarID]?.eventManager?.reset(); }); }; const call = (calendarIDs: string[]) => { const eventManagers = eventManagersByIdRef.current; return Promise.all( calendarIDs.map((calendarID) => { return eventManagers[calendarID]?.eventManager?.call(); }) ); }; const subscribe = (calendarIDs: string[], cb: SubscribeCallback) => { let isActive = true; const notify = (data: any) => { cb(data); }; const unsubscribes = calendarIDs.reduce<(() => void)[]>((acc, calendarID) => { const record = getOrSetRecord(calendarID, eventManagersByIdRef.current, silentApi); if (record.promise) { record.promise.then((eventManager) => { if (!isActive || !eventManager) { return; } acc.push(eventManager.subscribe(notify)); }); return acc; } acc.push(record.eventManager.subscribe(notify)); return acc; }, []); return () => { unsubscribes.forEach((unsub) => unsub?.()); isActive = false; }; }; const calendarsEventManager: CalendarModelEventManager = { start, stop, reset, call, subscribe, }; return ( <CalendarModelEventManagerContext.Provider value={calendarsEventManager}> {children} </CalendarModelEventManagerContext.Provider> ); }; export const useCalendarModelEventManager = () => { const state = useContext(CalendarModelEventManagerContext); if (!state) { throw new Error('Trying to use uninitialized ModelEventManagerProvider'); } return state; }; export default ModelEventManagerProvider;
6,183
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/eventManager
petrpan-code/ProtonMail/WebClients/packages/components/containers/eventManager/calendar/index.ts
export { default as CalendarModelEventManagerProvider, useCalendarModelEventManager, } from './ModelEventManagerProvider'; export { default as useCalendarsInfoListener } from './useCalendarsInfoListener';
6,184
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/eventManager
petrpan-code/ProtonMail/WebClients/packages/components/containers/eventManager/calendar/useCalendarsInfoListener.ts
import { useEffect } from 'react'; import { updateBootstrapKeysAndSettings, updateBootstrapMembers, } from '@proton/shared/lib/eventManager/calendar/calendarBootstrap'; import { updateCalendarsUserSettings } from '@proton/shared/lib/eventManager/calendar/calendarUserSettings'; import { updateCalendarsWithMembers } from '@proton/shared/lib/eventManager/calendar/calendarsWithMembers'; import { useAddresses, useCache, useEventManager } from '../../../hooks'; import { KEY as CALENDAR_BOOTSTRAP_CACHE } from '../../../hooks/useGetCalendarBootstrap'; import { CACHE_KEY as CALENDAR_KEYS_CACHE } from '../../../hooks/useGetDecryptedPassphraseAndCalendarKeys'; import { useCalendarModelEventManager } from './ModelEventManagerProvider'; /** * Listen to updates to calendars, calendar members and calendar user settings (via core event loop) */ export const useCalendarsInfoCoreListener = () => { const { subscribe: coreSubscribe } = useEventManager(); const { reset: calendarReset } = useCalendarModelEventManager(); const cache = useCache(); const [addresses] = useAddresses(); useEffect(() => { // subscribe via the standard event loop to updates of CalendarsModel, CalendarMembersModel and CalendarUserSettingsModel const ownAddressIDs = (addresses || []).map(({ ID }) => ID); return coreSubscribe((data) => { updateCalendarsUserSettings(cache, data); updateCalendarsWithMembers(cache, data, ownAddressIDs, calendarReset); updateBootstrapMembers(cache.get(CALENDAR_BOOTSTRAP_CACHE), data); }); }, [cache, addresses]); }; /** * Listen to updates to calendar keys and settings (via calendar event loop) */ const useCalendarsInfoCalendarListener = (calendarIDs: string[]) => { const { subscribe: calendarSubscribe } = useCalendarModelEventManager(); const cache = useCache(); useEffect(() => { // subscribe via the calendar event loop to updates of CalendarKeysModel and CalendarSettingsModel return calendarSubscribe(calendarIDs, (data) => { if (data) { updateBootstrapKeysAndSettings( data, cache.get(CALENDAR_BOOTSTRAP_CACHE), cache.get(CALENDAR_KEYS_CACHE) ); } }); }, [cache, calendarIDs]); }; export const useCalendarsInfoListener = (calendarIDs: string[]) => { useCalendarsInfoCoreListener(); useCalendarsInfoCalendarListener(calendarIDs); }; export default useCalendarsInfoListener;
6,185
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/experiments/ExperimentsContext.ts
import { createContext } from 'react'; export interface Experiment { Value: string; Name: ExperimentCode; } export enum ExperimentCode { Family2023 = 'Family2023', ReferralProgramSignup = 'ReferralProgramSignup', GmailSyncOnboarding = 'GmailSyncOnboarding', MultipleUpsell = 'MultipleUpsell', } export interface ExperimentsContextValue { experiments: { [code in ExperimentCode]?: string | undefined }; loading: boolean | undefined; initialize: () => Promise<void>; } export default createContext<ExperimentsContextValue>({} as ExperimentsContextValue);
6,186
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/experiments/ExperimentsProvider.tsx
import { ReactNode, useEffect, useRef, useState } from 'react'; import { getExperiments } from '@proton/shared/lib/api/experiments'; import { getSilentApi } from '@proton/shared/lib/api/helpers/customConfig'; import { deleteCookie, getCookie, setCookie } from '@proton/shared/lib/helpers/cookies'; import { getSecondLevelDomain } from '@proton/shared/lib/helpers/url'; import { useApi } from '../../hooks'; import ExperimentsContext, { Experiment, ExperimentCode } from './ExperimentsContext'; interface Props { children: ReactNode; } export const DEFAULT_EXPERIMENT_VALUE = 'A'; const formatExperiments = (experiments: { [key in ExperimentCode]?: string }) => { return Object.entries(experiments) .reduce<string[]>((acc, [key, code]) => { return [...acc, `${key}:${code}`]; }, []) .join(','); }; const extractExperiments = (cookieValue: string) => { return cookieValue.split(',').reduce<{ [key in ExperimentCode]?: string }>((acc, code) => { const [key, value] = code.split(':'); acc[key as ExperimentCode] = value; return acc; }, {}); }; // Purge the cache of experiments that are not in the list of codes const purgeExperiments = (cookieExperiments: { [key in ExperimentCode]?: string }, apiExperiments: Experiment[]) => { return Object.entries(cookieExperiments).reduce<{ [key in ExperimentCode]?: string }>((acc, [name, value]) => { const index = apiExperiments.findIndex((experiment) => experiment.Name === name); if (index !== -1) { acc[name as ExperimentCode] = value; } return acc; }, {}); }; const addExperiments = (apiExperiments: Experiment[]) => { return apiExperiments.reduce<{ [key in ExperimentCode]?: string }>((acc, experiment) => { if (Object.values(ExperimentCode).includes(experiment.Name)) { acc[experiment.Name] = experiment.Value; } return acc; }, {}); }; const storeExperimentsInCookie = (experiments: { [key in ExperimentCode]?: string }) => { const cookieDomain = `.${getSecondLevelDomain(window.location.hostname)}`; // proton.me const cookieValue = formatExperiments(experiments); if (!cookieValue) { if (getCookie('Features')) { deleteCookie('Features'); } return; } setCookie({ cookieName: 'Features', cookieValue, cookieDomain, path: '/', expirationDate: 'max', secure: true, }); }; const getExperimentsFromCookie = () => { const cookie = getCookie('Features'); if (cookie) { return extractExperiments(cookie); } return {}; }; const ExperimentsProvider = ({ children }: Props) => { const api = useApi(); const silentApi = getSilentApi(api); const [experiments, setExperiments] = useState<{ [key in ExperimentCode]?: string }>(getExperimentsFromCookie()); const [loading, setLoading] = useState(true); const codePromiseCacheRef = useRef<Promise<void> | undefined>(); const initialize = () => { const codePromiseCache = codePromiseCacheRef.current; if (codePromiseCache) { return codePromiseCache; } setLoading(true); const promise = silentApi<{ Experiments: Experiment[] | undefined }>(getExperiments()) .then((results) => { const experiments: Experiment[] = results.Experiments || []; setExperiments((cookieExperiments) => ({ ...purgeExperiments(cookieExperiments, experiments), // filter existing experiments stored in the cookie ...addExperiments(experiments), // add experiments based on ExperimentCode })); }) // Make sure that cookie is set // if set, send a signal to the data team that the experiment started // if not set, wait a bit more and try again .then(() => { // The timeout is here to make sure the cookie is set setTimeout(() => { const fetchUrl = new URL(window.location.href); fetchUrl.searchParams.append('load', 'experiment'); // Signal used by data to indicate that the experiment started void fetch(fetchUrl.href); }, 200); }) .finally(() => { setLoading(false); }); codePromiseCacheRef.current = promise; return promise; }; useEffect(() => { storeExperimentsInCookie(experiments); }, [experiments]); return ( <ExperimentsContext.Provider value={{ experiments, loading, initialize }}> {children} </ExperimentsContext.Provider> ); }; export default ExperimentsProvider;
6,187
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/experiments/index.ts
export { default as ExperimentsProvider } from './ExperimentsProvider'; export { default as ExperimentsContext } from './ExperimentsContext'; export * from './ExperimentsContext';
6,188
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/features/FeaturesContext.ts
import { createContext } from 'react'; import noop from '@proton/utils/noop'; export type FeatureType = 'boolean' | 'integer' | 'float' | 'string' | 'enumeration' | 'mixed'; export interface Feature<V = any> { Code: string; Type: FeatureType; DefaultValue: V; Value: V; Options?: string[]; Minimum: number; Maximum: number; Global: boolean; Writable: boolean; ExpirationTime: number; UpdateTime: number; } export enum FeatureCode { /* * In the past whether you have a certain early-access (e.g. alpha / beta) * enabled or not was purely based on a client-side cookie and this feature's * value was to indicate not what your env was but rather what options were * available to you (whether you had access to both alpha & beta or only to beta). * * However, now we are persisting the users preference on the backed on their * settings under the same name "EarlyAccess" (either 0 or 1). * * To avoid confusing these two this has been renamed to "EarlyAccessScope". * Ideally we would rename it to that on the server as well (and when that happens * we can remove this comment :)). */ AliasPromotion = 'AliasPromotion', AlmostAllMail = 'AlmostAllMail', AlmostAllMailSpotlight = 'AlmostAllMailSpotlight', AutoAddHolidaysCalendars = 'AutoAddHolidaysCalendars', AutoDelete = 'AutoDelete', BlackFridayPromoShown = 'BlackFridayPromoShown', BlockSenderInToolbar = 'BlockSenderInToolbar', BundlePromoShown = 'BundlePromoShown', CalendarFeedbackEnabled = 'CalendarFeedbackEnabled', CalendarFetchMetadataOnly = 'CalendarFetchMetadataOnly', CalendarEncryptedSearch = 'CalendarEncryptedSearch', CalendarEncryptedSearchSpotlight = 'CalendarEncryptedSearchSpotlight', CalendarSharingEnabled = 'CalendarSharingEnabled', CalendarSharingSpotlight = 'CalendarSharingSpotlight', CleanUTMTrackers = 'CleanUTMTrackers', DarkStylesInBody = 'DarkStylesInBody', DismissedRecoverDataCard = 'DismissedRecoverDataCard', DriveMyDevices = 'DriveWebMyDevices', DrivePlan = 'DrivePlan', DriveSearchSpotlight = 'DriveSearchSpotlight', DriveWindowsGAMailSpotlight = 'DriveWindowsGAMailSpotlight', DriveWindowsGAMailSpotlightShown = 'DriveWindowsGAMailSpotlightShown', ESAutomaticBackgroundIndexing = 'ESAutomaticBackgroundIndexing', ESUserInterface = 'ESUserInterface', EarlyAccessScope = 'EarlyAccess', EasySwitch = 'EasySwitch', EmailForwardingSpotlight = 'EmailForwardingSpotlight', HolidaysCalendars = 'HolidaysCalendars', HolidaysCalendarsSpotlight = 'HolidaysCalendarsSpotlight', KeyTransparencyAccount = 'KeyTransparencyWebAccount', KeyTransparencyCalendar = 'KeyTransparencyWebCalendar', KeyTransparencyDrive = 'KeyTransparencyWebDrive', KeyTransparencyMail = 'KeyTransparencyWebMail', LegacyMessageMigrationEnabled = 'LegacyMessageMigrationEnabled', MailDisableE2EE = 'MailDisableE2EE', MailFeedbackEnabled = 'MailFeedbackEnabled', MailServiceWorker = 'MailServiceWorker', NumAttachmentsWithoutEmbedded = 'NumAttachmentsWithoutEmbedded', NumberOfPreloadedConversations = 'NumberOfPreloadedConversations', OfferBlackFridayMail2022 = 'OfferBlackFridayMail2022', OfferBlackFridayMailFree2022 = 'OfferBlackFridayMailFree2022', OfferBlackFridayMailPro2022 = 'OfferBlackFridayMailPro2022', OfferBlackFridayVPN1Deal2022 = 'OfferBlackFridayVPN1Deal2022', OfferBlackFridayVPN2Deal2022 = 'OfferBlackFridayVPN2Deal2022', OfferBlackFridayVPN3Deal2022 = 'OfferBlackFridayVPN3Deal2022', OfferFamily2023 = 'OfferFamily2023', OfferGoUnlimited2022 = 'OfferGoUnlimited2022', OfferMailTrial2023 = 'OfferMailTrial2023', OfferSpecialOffer2022 = 'OfferSpecialOffer2022', OfferSummer2023 = 'OfferSummer2023', OfferBlackFriday2023InboxFree = 'OfferBlackFriday2023InboxFree', OfferBlackFriday2023InboxMail = 'OfferBlackFriday2023InboxMail', OfferBlackFriday2023InboxUnlimited = 'OfferBlackFriday2023InboxUnlimited', OfferBlackFriday2023VPNFree = 'OfferBlackFriday2023VPNFree', OfferBlackFriday2023VPNMonthly = 'OfferBlackFriday2023VPNMonthly', OfferBlackFriday2023VPNYearly = 'OfferBlackFriday2023VPNYearly', OfferBlackFriday2023VPNTwoYears = 'OfferBlackFriday2023VPNTwoYears', OfferBlackFriday2023DriveFree = 'OfferBlackFriday2023DriveFree', OfferBlackFriday2023DrivePlus = 'OfferBlackFriday2023DrivePlus', OfferBlackFriday2023DriveUnlimited = 'OfferBlackFriday2023DriveUnlimited', Offers = 'Offers', OrgSpamBlockList = 'OrgSpamBlockList', OrgTwoFactor = 'OrgTwoFactor', PassSignup = 'PassSignup', PaymentsDisabled = 'PaymentsDisabled', PrivacyDropdownOpened = 'PrivacyDropdownOpened', ProtonBadge = 'ProtonBadge', ProtonSentinel = 'ProtonSentinel', ProtonSentinelAuthLogUpsell = 'ProtonSentinelAuthLogUpsell', ProtonSentinelUpsell = 'ProtonSentinelUpsell', QuickReply = 'QuickReply', QuickSettingsSpotlight = 'QuickSettingsSpotlight', RebrandingFeedback = 'RebrandingFeedback', RebrandingFeedbackEnabled = 'RebrandingFeedbackEnabled', ReferralExplanationOpened = 'ReferralExplanationOpened', ReferralProgram = 'ReferralProgram', ReferralProgramSpotlight = 'ReferralProgramSpotlight', SLIntegration = 'SLIntegration', ScheduledSendFreemium = 'ScheduledSendFreemium', SeenReferralModal = 'SeenReferralModal', SetExpiration = 'SetExpiration', SmtpToken = 'SmtpToken', SpotlightEncryptedSearch = 'SpotlightEncryptedSearch', SpotlightGetStartedChecklist = 'SpotlightGetStartedChecklist', SpotlightLoadContent = 'SpotlightLoadContent', SpotlightScheduledSend = 'SpotlightScheduledSend', SpotlightSnooze = 'SpotlightSnooze', SpyTrackerProtectionIncorporator = 'SpyTrackerProtectionIncorporator', TrustedDeviceRecovery = 'TrustedDeviceRecovery', UnreadFavicon = 'UnreadFavicon', UsedContactsImport = 'UsedContactsImport', UsedMailMobileApp = 'UsedMailMobileApp', WelcomeImportModalShown = 'WelcomeImportModalShown', } export interface FeaturesContextValue { features: { [code in FeatureCode]?: Feature | undefined }; loading: { [code in FeatureCode]?: boolean | undefined }; enqueue: (code: FeatureCode[]) => void; get: <V = any>(code: FeatureCode[]) => Promise<Feature<V>[]>; put: <V = any>(code: FeatureCode, value: V) => Promise<Feature<V>>; } export type FeaturesLoadContextValue = Pick<FeaturesContextValue, 'get'>['get']; export interface FeatureContextValue<V = any> { feature: Feature<V> | undefined; loading: boolean | undefined; get: () => Promise<Feature<V>>; update: (value: V) => Promise<Feature<V>>; code: FeatureCode; } export const FeaturesContext = createContext<FeaturesContextValue>({ features: {}, loading: {}, enqueue: noop, get: async (): Promise<any> => null, put: async (): Promise<any> => null, }); export const FeaturesLoadContext = createContext<FeaturesLoadContextValue>(null as unknown as FeaturesLoadContextValue);
6,189
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/features/FeaturesProvider.tsx
import { ReactNode, useCallback, useRef, useState } from 'react'; import { getFeatures, updateFeatureValue } from '@proton/shared/lib/api/features'; import { getSilentApi } from '@proton/shared/lib/api/helpers/customConfig'; import unique from '@proton/utils/unique'; import { useApi } from '../../hooks'; import { Feature, FeatureCode, FeaturesContext, FeaturesLoadContext } from './FeaturesContext'; interface Props { children: ReactNode; } const FeaturesProvider = ({ children }: Props) => { const api = useApi(); const silentApi = getSilentApi(api); const [features, setFeatures] = useState<{ [key in FeatureCode]?: Feature }>({}); const [loading, setLoading] = useState<{ [key in FeatureCode]?: boolean }>({}); const codePromiseCacheRef = useRef<{ [key in FeatureCode]?: Promise<Feature> | undefined }>({}); const codeQueueRef = useRef<FeatureCode[]>([]); const get = useCallback((codes: FeatureCode[]) => { const codeQueue = codeQueueRef.current; codeQueueRef.current = []; const codePromiseCache = codePromiseCacheRef.current; const allUniqueCodesToFetch = unique(codes.concat(codeQueue)).filter((code) => { return !codePromiseCache[code]; }); if (!allUniqueCodesToFetch.length) { return Promise.all( codes.map((code) => { return codePromiseCache[code]!; }) ); } setLoading((oldLoading) => { return allUniqueCodesToFetch.reduce<{ [key in FeatureCode]?: boolean }>( (acc, code) => { acc[code] = true; return acc; }, { ...oldLoading } ); }); const promise = silentApi<{ Features: Feature[] }>(getFeatures(allUniqueCodesToFetch)) .then(({ Features }) => { const newFeatures = Features.reduce<{ [key in FeatureCode]?: Feature }>((acc, Feature) => { acc[Feature.Code as FeatureCode] = Feature; return acc; }, {}); setFeatures((currentFeatures) => ({ ...newFeatures, ...currentFeatures })); return Features; }) .finally(() => { setLoading((oldLoading) => { return allUniqueCodesToFetch.reduce<{ [key in FeatureCode]?: boolean }>( (acc, code) => { acc[code] = false; return acc; }, { ...oldLoading } ); }); }); allUniqueCodesToFetch.forEach((code) => { codePromiseCache[code] = promise .then((Features) => { const Feature = Features.find(({ Code }) => Code === code); return Feature!; }) .catch((e) => { codePromiseCache[code] = undefined; throw e; }); }); return Promise.all( codes.map((code) => { return codePromiseCache[code]!; }) ); }, []); const updateFeature = (code: FeatureCode, feature: Feature | undefined) => { setFeatures((currentFeatures) => ({ ...currentFeatures, [code]: feature })); }; const put = async (code: FeatureCode, value: any) => { const oldFeature = features[code]; const oldCopiedFeature = oldFeature ? { ...oldFeature } : undefined; try { // Optimistically apply change if (oldCopiedFeature) { updateFeature(code, { ...oldCopiedFeature, Value: value }); } const { Feature } = await silentApi<{ Feature: Feature }>(updateFeatureValue(code, value)); updateFeature(code, Feature); return Feature; } catch (e: any) { // Rollback optimistic change if it fails if (oldCopiedFeature) { updateFeature(code, oldCopiedFeature); } throw e; } }; const enqueue = (codes: FeatureCode[]) => { codeQueueRef.current = unique(codeQueueRef.current.concat(codes)); }; return ( <FeaturesLoadContext.Provider value={get}> <FeaturesContext.Provider value={{ features, loading, get, put, enqueue }}> {children} </FeaturesContext.Provider> </FeaturesLoadContext.Provider> ); }; export default FeaturesProvider;
6,190
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/features/index.ts
export { default as FeaturesProvider } from './FeaturesProvider'; export * from './FeaturesContext';
6,191
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/feedback/FeedbackModal.tsx
import { ChangeEvent, FormEvent, useEffect, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { sendFeedback } from '@proton/shared/lib/api/feedback'; import { EmojiScale, EmojiScaleProps, ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, ModalProps, TextArea, } from '../../components'; import { useApi, useNotifications } from '../../hooks'; interface FeedbackModalModel { Score?: number; Feedback: string; } type FeedbackType = 'v4_migration' | 'calendar_launch' | 'web_clients_relaunch'; export interface FeedbackModalProps extends ModalProps { onClose?: () => void; onSuccess?: () => void; onMount?: () => void; feedbackType: FeedbackType; description?: string; scaleTitle: string; scaleProps: Omit<EmojiScaleProps, 'value' | 'InputButtonProps' | 'onChange'>; } const FeedbackModal = ({ feedbackType, description, scaleTitle, scaleProps, onMount, ...rest }: FeedbackModalProps) => { const api = useApi(); const { createNotification } = useNotifications(); const [loading, withLoading] = useLoading(); const [model, setModel] = useState<FeedbackModalModel>({ Score: undefined, Feedback: '', }); useEffect(() => { onMount?.(); }, []); const handleSubmit = async () => { if (model.Score === undefined) { createNotification({ text: c('Error notification when score is missing in user feedback form modal').t`Score is required`, type: 'error', }); return; } await api( sendFeedback({ Score: model.Score, Feedback: model.Feedback, FeedbackType: feedbackType, }) ); createNotification({ text: c('Success notification when user send feedback').t`Feedback sent` }); rest.onSuccess?.(); rest.onClose?.(); }; const handleChange = (field: string) => (e: ChangeEvent<HTMLTextAreaElement>) => { setModel({ ...model, [field]: e.target.value, }); }; const handleScoreChange = (Score: number) => { setModel({ ...model, Score }); }; return ( <Modal as="form" onSubmit={(e: FormEvent) => { e.preventDefault(); withLoading(handleSubmit()); }} size="large" {...rest} > <ModalHeader title={c('Feedback Modal Title').t`Your feedback`} /> <ModalContent> {description && <p className="mb-8">{description}</p>} <div className="mb-8"> <label className="mb-4 block text-semibold" id="score-label"> {scaleTitle} </label> <div> <EmojiScale {...scaleProps} value={model.Score} InputButtonProps={{ 'aria-describedby': 'score-label' }} onChange={handleScoreChange} /> </div> </div> {model.Score !== undefined && ( <div> <label className="mb-4 block text-semibold" htmlFor="feedback-label">{c('new_plans: label') .t`Tell us about your experience. (Optional)`}</label> <TextArea id="feedback-label" value={model.Feedback} placeholder={c('new_plans: placeholder').t`Feedback`} onChange={handleChange('Feedback')} /> </div> )} </ModalContent> <ModalFooter> <Button disabled={loading} onClick={rest.onClose}>{c('Action').t`Cancel`}</Button> <Button type="submit" color="norm" loading={loading}>{c('Action').t`Send feedback`}</Button> </ModalFooter> </Modal> ); }; export default FeedbackModal;
6,192
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/feedback/RebrandingFeedbackModal.tsx
import { c } from 'ttag'; import { BRAND_NAME } from '@proton/shared/lib/constants'; import useFeature from '../../hooks/useFeature'; import { FeatureCode } from '../features/FeaturesContext'; import FeedbackModal, { FeedbackModalProps } from './FeedbackModal'; import { RebrandingFeatureValue } from './useRebrandingFeedback'; interface RebrandingModalProps extends Partial<FeedbackModalProps> { onMount?: () => void; } const RebrandingFeedbackModal = (props: RebrandingModalProps) => { const rebranding = useFeature<RebrandingFeatureValue>(FeatureCode.RebrandingFeedback); const handleSuccess = () => { if (rebranding.feature?.Value.completed !== true) { /* * The value of the rebranding feature is guaranteed to exist here * because we're disabling the Feedback Modal until it's available. */ rebranding.update({ ...rebranding.feature!.Value, completed: true, }); } }; if (!rebranding.feature?.Value) { return null; } return ( <FeedbackModal size="medium" onSuccess={handleSuccess} feedbackType="web_clients_relaunch" scaleTitle={c('Label').t`How would you describe your experience with the new ${BRAND_NAME}?`} scaleProps={{ fromLabel: c('Label').t`Awful`, toLabel: c('Label').t`Wonderful`, }} {...props} /> ); }; export default RebrandingFeedbackModal;
6,193
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/feedback/index.ts
export { default as FeedbackModal } from './FeedbackModal'; export { default as RebrandingFeedbackModal } from './RebrandingFeedbackModal'; export { default as useRebrandingFeedback } from './useRebrandingFeedback'; export { default as useHasRebrandingFeedback } from './useHasRebrandingFeedback';
6,194
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/feedback/useHasRebrandingFeedback.ts
import useFeature from '../../hooks/useFeature'; import useUserSettings from '../../hooks/useUserSettings'; import { FeatureCode } from '../features'; const useHasRebrandingFeedback = () => { const [{ Locale }] = useUserSettings(); const rebrandingFeedbackEnabled = useFeature(FeatureCode.RebrandingFeedbackEnabled); const rebrandingFeedbackFeatureIsEnabled = Boolean(rebrandingFeedbackEnabled.feature?.Value); const isEnglishUser = Locale?.startsWith('en_'); return rebrandingFeedbackFeatureIsEnabled && isEnglishUser; }; export default useHasRebrandingFeedback;
6,195
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/feedback/useRebrandingFeedback.tsx
import { useEffect, useState } from 'react'; import { DAY } from '@proton/shared/lib/constants'; import { useFeature } from '../../hooks'; import { FeatureCode } from '../features'; import useHasRebrandingFeedback from './useHasRebrandingFeedback'; export interface RebrandingFeatureValue { /* User has visited rebranding in the past */ visited: boolean; /* User has given rebranding feedback */ completed: boolean; /* User has been prompted for rebranding feedback in the past */ prompted: boolean; } /* * Need to make sure that the functionality inside of the useEffect below really only runs once per runtime of * the application independently of what happens in the react tree. After the useEffect has ran once, we don't * ever want to run it again in the same runtime. */ let logicAlreadyRanDuringCurrentRuntime = false; const useRebrandingFeedback = () => { const hasRebrandingFeedback = useHasRebrandingFeedback(); const rebranding = useFeature<RebrandingFeatureValue>(FeatureCode.RebrandingFeedback); const [handleDisplay, setHandleDisplay] = useState<undefined | (() => void)>(undefined); useEffect(() => { if ( rebranding.loading || !rebranding.feature?.Value || logicAlreadyRanDuringCurrentRuntime || !hasRebrandingFeedback ) { return; } /** * Features are assumed to be loaded at this point, as ensured by the conditions above. * This is important because this logic is only supposed to run once ever, therefore the * data it consumes needs to be guaranteed in advance. */ logicAlreadyRanDuringCurrentRuntime = true; let promptTimeoutId: undefined | number; const { Value: rebrandingValue } = rebranding.feature; const updateRebranding = (value: Partial<RebrandingFeatureValue>) => { void rebranding.update({ ...rebrandingValue, ...value }); }; const { visited, completed, prompted } = rebrandingValue; const prompt = () => { /** * User has already visited the v5 / rebranding update AND has already been * prompted for feedback previously. So we don't ask again. */ if (prompted) { return; } /* We didn't prompt the user but they already gave feedback on their own */ if (completed) { return; } /* * We want to store the "handleDisplay" callback here, not use react's * setState callback api, therefore the curry. Yum! */ setHandleDisplay(() => () => { updateRebranding({ prompted: true }); }); }; /** * User is visiting v5 / rebranding for the first time, we register this so * that we can prompt them the next time they visit again. * * Alternatively, we also schedule a timer should the user not refresh / close * his browser for a really long time, prompting him anyway after expiration of * a certain amount of time in that case. */ if (!visited) { updateRebranding({ visited: true }); promptTimeoutId = window.setTimeout(prompt, DAY); return; } prompt(); return () => { window.clearTimeout(promptTimeoutId); }; }, [rebranding.loading, rebranding, hasRebrandingFeedback]); return handleDisplay; }; export default useRebrandingFeedback;
6,196
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/filePreview/AudioPreview.tsx
import { useEffect, useState } from 'react'; import UnsupportedPreview from './UnsupportedPreview'; interface Props { mimeType: string; contents?: Uint8Array[]; onDownload?: () => void; } const AudioPreview = ({ contents, mimeType, onDownload }: Props) => { const [url, setUrl] = useState<string>(); const [error, setError] = useState(false); useEffect(() => { const newUrl = URL.createObjectURL(new Blob(contents, { type: mimeType })); setUrl(newUrl); return () => { if (newUrl) { URL.revokeObjectURL(newUrl); } }; }, [contents]); const handleBrokenAudio = () => { setError(true); }; if (error) { return ( <div className="flex flex-item-fluid-auto relative"> <UnsupportedPreview onDownload={onDownload} type="audio" /> </div> ); } return ( <div className="flex w-full h-full"> <div className="m-auto w-1/2"> <audio className="w-full" onError={handleBrokenAudio} src={url} controls /> </div> </div> ); }; export default AudioPreview;
6,197
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/filePreview/CloseModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { ModalProps, Prompt } from '../../components'; interface Props extends ModalProps { isSaving?: boolean; handleDiscard?: () => void; } const CloseModal = ({ isSaving, handleDiscard, ...rest }: Props) => { const { onClose } = rest; if (isSaving) { return ( <Prompt title={c('Title').t`Your changes are not synced yet`} buttons={[<Button onClick={onClose}>{c('Action').t`Cancel`}</Button>]} {...rest} > {c('Info').t`Please wait till your changes are synced with the server.`} </Prompt> ); } const handleClose = () => { handleDiscard?.(); onClose?.(); }; return ( <Prompt title={c('Title').t`Are you sure you want to close the preview?`} buttons={[ <Button color="danger" onClick={handleClose}>{c('Action').t`Discard`}</Button>, <Button onClick={onClose}>{c('Action').t`Cancel`}</Button>, ]} {...rest} > {c('Info').t`All your changes will be lost.`} <br /> {c('Info').t`Are you sure you want to discard your changes?`} </Prompt> ); }; export default CloseModal;
6,198
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/filePreview/FilePreview.tsx
import { ReactNode, Ref, forwardRef, useEffect, useRef, useState } from 'react'; import { c } from 'ttag'; import { useCombinedRefs } from '@proton/hooks'; import { useLoading } from '@proton/hooks'; import busy from '@proton/shared/lib/busy'; import { isMinimumSafariVersion, isSafari } from '@proton/shared/lib/helpers/browser'; import { isAudio, isPDF, isSupportedImage, isSupportedText, isVideo, isWordDocument, } from '@proton/shared/lib/helpers/mimetype'; import { isPreviewAvailable, isPreviewTooLarge } from '@proton/shared/lib/helpers/preview'; import { useFocusTrap, useModalState } from '../../components'; import { useBeforeUnload, useHotkeys } from '../../hooks'; import AudioPreview from './AudioPreview'; import CloseModal from './CloseModal'; import Header, { SharedStatus } from './Header'; import ImagePreview from './ImagePreview'; import PDFPreview from './PDFPreview'; import PreviewError from './PreviewError'; import PreviewLoader from './PreviewLoader'; import SandboxedPreview from './SandboxedPreview'; import SignatureIssue from './SignatureIssue'; import TextPreview from './TextPreview'; import UnsupportedPreview from './UnsupportedPreview'; import VideoPreview from './VideoPreview'; interface Props { isMetaLoading?: boolean; isLoading: boolean; error?: string; mimeType?: string; imgThumbnailUrl?: string; fileName?: string; fileSize?: number; contents?: Uint8Array[]; sharedStatus?: SharedStatus; onClose?: () => void; onDownload?: () => void; onSave?: (content: Uint8Array[]) => Promise<void>; onDetails?: () => void; onShare?: () => void; onRestore?: () => void; // revision's specific date?: Date | string | number; colorUi?: 'standard' | 'prominent'; navigationControls?: ReactNode; signatureStatus?: ReactNode; signatureConfirmation?: ReactNode; } export const FilePreviewContent = ({ isMetaLoading, isLoading, mimeType, error, imgThumbnailUrl, fileSize, fileName, contents, onDownload, onNewContents, signatureConfirmation, previewParams, }: { isMetaLoading?: boolean; isLoading: boolean; mimeType?: string; error?: string; imgThumbnailUrl?: string; fileName?: string; fileSize?: number; contents?: Uint8Array[]; onDownload?: () => void; onNewContents?: (content: Uint8Array[]) => void; signatureConfirmation?: ReactNode; previewParams?: { img?: { zoomControls?: boolean }; }; }) => { const [forcePreview, setForcePreview] = useState(false); const renderPreview = () => { if (error) { return <PreviewError error={error} />; } if ((mimeType && !isSupportedImage(mimeType) && isLoading) || (!imgThumbnailUrl && isLoading)) { return <PreviewLoader />; } if (signatureConfirmation && !forcePreview) { return ( <SignatureIssue signatureConfirmation={signatureConfirmation} onClick={() => setForcePreview(true)} /> ); } if ( !mimeType || (!contents && !imgThumbnailUrl && !isSupportedText(mimeType)) || !isPreviewAvailable(mimeType, fileSize) ) { return ( <div className="file-preview-container"> <UnsupportedPreview onDownload={onDownload} tooLarge={isPreviewTooLarge(mimeType, fileSize)} /> </div> ); } if (isSupportedImage(mimeType)) { return ( <ImagePreview isLoading={isLoading} isZoomEnabled={previewParams?.img?.zoomControls} placeholderSrc={imgThumbnailUrl} fileName={fileName} contents={contents} mimeType={mimeType} onDownload={onDownload} /> ); } if (isVideo(mimeType)) { return <VideoPreview contents={contents} mimeType={mimeType} onDownload={onDownload} />; } if (isAudio(mimeType)) { return <AudioPreview contents={contents} mimeType={mimeType} onDownload={onDownload} />; } if (isSupportedText(mimeType)) { return <TextPreview contents={contents} onNewContents={onNewContents} />; } if (isPDF(mimeType)) { return <PDFPreview contents={contents} filename={fileName} />; } if (isWordDocument(mimeType)) { if (isSafari() && !isMinimumSafariVersion(16)) { return ( <div className="file-preview-container"> <UnsupportedPreview onDownload={onDownload} browser /> </div> ); } return <SandboxedPreview contents={contents} mimeType={mimeType} onDownload={onDownload} />; } }; return <>{isMetaLoading ? <PreviewLoader /> : renderPreview()}</>; }; const FilePreview = ( { isMetaLoading = false, isLoading = false, error, fileName, mimeType, imgThumbnailUrl, fileSize, contents, navigationControls, sharedStatus, signatureStatus, signatureConfirmation, onClose, onDownload, onSave, onDetails, onShare, onRestore, date, colorUi = 'prominent', }: Props, ref: Ref<HTMLDivElement> ) => { const rootRef = useRef<HTMLDivElement>(null); const combinedRefs = useCombinedRefs<HTMLDivElement>(ref, rootRef); const focusTrapProps = useFocusTrap({ rootRef, }); const [isSaving, withSaving] = useLoading(false); const [isDirty, setIsDirty] = useState<boolean>(false); const [newContent, setNewContent] = useState<Uint8Array[]>([]); // Block browser from leaving and do not refresh page with unsaved document. useBeforeUnload(isDirty); useEffect(() => { if (!isDirty) { return; } const unregister = busy.register(); return () => { unregister(); }; }, [isDirty]); // Reset when another content is loaded (for example after going to the next item through navigation). useEffect(() => { setIsDirty(false); }, [contents]); const [closeModalProps, setCloseModalOpen] = useModalState(); const handleClose = () => { if (!isDirty) { onClose?.(); return; } setCloseModalOpen(true); }; // There is an issue saving empty file at this moment. Lets not allow it for now. const handleSave = onSave ? async () => { return withSaving(onSave(newContent)).then(() => { // Compare to latest changes and unset dirty flag only if the user // didn't do any extra modifications after saving the file. setNewContent((latestNewContent) => { if (latestNewContent === newContent) { setIsDirty(false); setCloseModalOpen(false); } return latestNewContent; }); }); } : undefined; useHotkeys(rootRef, [ [ 'Escape', (e) => { e.stopPropagation(); handleClose(); }, ], ]); return ( <div className={`file-preview ui-${colorUi}`} ref={combinedRefs} data-testid="file-preview" {...focusTrapProps}> <Header mimeType={mimeType} name={fileName} sharedStatus={sharedStatus} signatureStatus={signatureStatus} isDirty={ isDirty && // There is an issue saving empty file at this moment. Lets not allow it for now. newContent.some((item) => item.length > 0) } onClose={handleClose} onDownload={onDownload} onSave={handleSave} onDetails={onDetails} onShare={onShare} onRestore={onRestore} date={date} > {isDirty ? ( <div className="flex flex-align-items-center absolute-center">{c('Info').t`Unsaved changes`}</div> ) : ( navigationControls )} </Header> <FilePreviewContent isMetaLoading={isMetaLoading} isLoading={isLoading} mimeType={mimeType} error={error} imgThumbnailUrl={imgThumbnailUrl} fileSize={fileSize} fileName={fileName} contents={contents} onDownload={onDownload} onNewContents={ onSave ? (content: Uint8Array[]) => { setIsDirty(true); setNewContent(content); } : undefined } signatureConfirmation={signatureConfirmation} /> <CloseModal {...closeModalProps} handleDiscard={onClose} isSaving={isSaving} /> </div> ); }; export default forwardRef(FilePreview);
6,199