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
petrpan-code/ProtonMail/WebClients/packages/components/containers/banner/PromotionBanner.tsx
import * as React from 'react'; import { ReactNode } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import clsx from '@proton/utils/clsx'; import isTruthy from '@proton/utils/isTruthy'; import { Icon } from '../../components'; import './PromotionBanner.scss'; interface Props { className?: string; rounded?: boolean; icon?: ReactNode; description?: ReactNode; cta?: ReactNode; loading?: boolean; hasDismissAction?: boolean; contentCentered?: boolean; mode?: 'row' | 'banner'; onClose?: () => void; ['data-testid']?: string; } const PromotionBanner = ({ className, rounded = false, loading = false, contentCentered = true, mode = 'row', description, cta, icon, hasDismissAction = false, onClose, 'data-testid': dataTestId, }: Props) => { const handleClose = () => { onClose?.(); }; return ( <div className={clsx( 'flex flex-nowrap flex-item-noshrink bg-promotion relative', contentCentered && 'text-left lg:text-center p-0-5', rounded && 'rounded', className )} data-testid={dataTestId} > <div className={clsx( 'inline-flex mx-auto flex-nowrap flex-align-items-center ', (() => { if (contentCentered) { return 'm-0.5 px-2'; } if (mode === 'banner') { return 'm-3 pl-4 w-full'; } if (mode === 'row') { return 'm-2 pl-4 w-full'; } })(), loading && 'w-1/3' )} > {loading ? ( <span className={clsx('bg-promotion-loading', contentCentered ? 'w-full' : 'w-1/3')} data-testid="promotion-banner:loading" /> ) : ( <> {icon && <div className="flex-item-noshrink mr-2">{icon}</div>} {description && ( <div className={clsx('bg-promotion-text', !contentCentered && 'flex-item-fluid')}> {description} </div> )} {cta && <div className="flex-item-noshrink ml-2 max-w-1/2 text-right">{cta}</div>} </> )} </div> {isTruthy(hasDismissAction && !loading) && ( <Button onClick={handleClose} icon size="small" color="weak" shape="ghost" className="ml-2 mr-1 my-auto" title={c('Action').t`Close`} > <Icon name="cross" alt={c('Action').t`Close`} /> </Button> )} </div> ); }; export default PromotionBanner;
5,900
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/banner/index.ts
export { default as PromotionBanner } from './PromotionBanner';
5,901
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/bridge/ProtonMailBridgeSection.scss
@import '~@proton/styles/scss/lib'; .bridge-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); grid-gap: 1em; }
5,902
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/bridge/ProtonMailBridgeSection.tsx
import { ChangeEvent, useEffect, useState } from 'react'; import { c } from 'ttag'; import { ButtonLike } from '@proton/atoms'; 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 { getBridgeURL, getStaticURL } from '@proton/shared/lib/helpers/url'; import { Icon, IconName, Select } from '../../components'; import { useUser } from '../../hooks'; import { SettingsParagraph, SettingsSectionWide, UpgradeBanner } from '../account'; import './ProtonMailBridgeSection.scss'; interface BridgeClient { id: string; icon: IconName; platform: string; versionFile: string; version: string; downloads: string[]; } const initialBridgeClients: BridgeClient[] = [ { id: 'windows', icon: 'brand-windows', platform: 'Windows', versionFile: 'version_windows.json', version: 'Latest', // NOTE: These URLs don't exist on proton.me yet, and are replaced with the version.json anyway downloads: ['https://protonmail.com/download/bridge/Bridge-Installer.exe'], }, { id: 'apple', icon: 'brand-apple', platform: 'macOS', versionFile: 'version_darwin.json', version: 'Latest', downloads: ['https://protonmail.com/download/bridge/Bridge-Installer.dmg'], }, { id: 'linux', icon: 'brand-linux', platform: 'GNU/Linux', versionFile: 'version_linux.json', version: 'Latest', downloads: ['https://protonmail.com/bridge/download'], }, ]; const fetchBridgeVersion = async (bridgeClient: BridgeClient): Promise<BridgeClient> => { try { const response = await fetch(getStaticURL(`/download/bridge/${bridgeClient.versionFile}`)); if (!response.ok) { throw new Error(response.statusText); } const jsonResponse = await response.json(); return { ...bridgeClient, version: jsonResponse.stable.Version, downloads: jsonResponse.stable.Installers, }; } catch (e: any) { if (bridgeClient.id === 'linux') { return { ...bridgeClient, version: c('Bridge version load failed').t`Failed to find latest version`, }; } } return bridgeClient; }; const ProtonMailBridgeSection = () => { const [{ hasPaidMail }] = useUser(); const fileTypes = new Map([ ['.exe', c('OS compatibility').t`.exe (64-bit)`], ['.dmg', c('OS compatibility').t`.dmg (10.12 or later)`], ['.deb', c('OS compatibility').t`.deb (for Debian/Ubuntu)`], ['.rpm', c('OS compatibility').t`.rpm (for Fedora/openSUSE)`], ['PKGBUILD', c('OS compatibility').t`PKGBUILD (for other distributions)`], ]); const getFileType = (link: string): string => { for (const [ext, fileType] of fileTypes) { if (link.endsWith(ext)) { return fileType; } } return ''; }; const [bridgeClients, setBridgeClients] = useState(initialBridgeClients); const [linuxLink, setLinuxLink] = useState(bridgeClients[2].downloads[0]); useEffect(() => { async function run() { const newBridgeClients = await Promise.all(bridgeClients.map(fetchBridgeVersion)); setBridgeClients(newBridgeClients); setLinuxLink(newBridgeClients[2].downloads[0]); } void run(); }, []); const handleSelect = ({ target }: ChangeEvent<HTMLSelectElement>) => setLinuxLink(target.value); const renderBox = ({ id, icon, platform, version, downloads }: BridgeClient) => { const options = downloads.map((d) => ({ text: getFileType(d), value: d, })) || []; return ( <div key={id} className="flex"> <div className="border p-7 flex-item-fluid rounded flex flex-column flex-align-items-center"> <Icon size={48} name={icon} className="mb-4" /> <h3 className="text-bold text-xl m-0 text-center">{c('Title').t`Bridge for ${platform}`}</h3> <span className="bridge-client-version mb-4 text-center">{version}</span> {downloads.length > 1 && ( <Select value={linuxLink} options={options} onChange={handleSelect} className="mb-4" /> )} {downloads.length > 0 && ( <ButtonLike as="a" color="norm" shape="solid" className="w-full mt-auto" href={id === 'linux' ? linuxLink : downloads[0]} target="_self" > {c('Action').t`Download`} </ButtonLike> )} </div> </div> ); }; 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.BRIDGE, isSettings: true, }); return ( <SettingsSectionWide> <SettingsParagraph className="mt-0 mb-4" learnMoreUrl={hasPaidMail ? getBridgeURL() : undefined}> {c('Info') .t`You can use ${MAIL_APP_NAME} with any desktop email client that supports IMAP/SMTP, including Outlook, Apple Mail, and Thunderbird.`} </SettingsParagraph> {hasPaidMail ? ( <div className="mt-8 bridge-grid">{bridgeClients.map(renderBox)}</div> ) : ( <UpgradeBanner upsellPath={upsellRef}> {c('new_plans: upgrade').t`Included with ${plus}, ${bundle}, and ${BRAND_NAME} for Business.`} </UpgradeBanner> )} </SettingsSectionWide> ); }; export default ProtonMailBridgeSection;
5,903
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/bridge/index.ts
export { default as ProtonMailBridgeSection } from './ProtonMailBridgeSection';
5,904
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/cache/Provider.tsx
import { ReactNode, useEffect } from 'react'; import { Cache } from '@proton/shared/lib/helpers/cache'; import CacheContext from './cacheContext'; interface Props<K, V> { cache: Cache<K, V>; children: ReactNode; } const Provider = <K, V>({ cache, children }: Props<K, V>) => { useEffect(() => { return () => { cache.clear(); cache.clearListeners(); }; }, []); return <CacheContext.Provider value={cache}>{children}</CacheContext.Provider>; }; export default Provider;
5,905
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/cache/cacheContext.ts
import { createContext } from 'react'; import { Cache } from '@proton/shared/lib/helpers/cache'; export default createContext<Cache<any, any> | null>(null);
5,906
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/cache/index.ts
export { default as CacheProvider } from './Provider';
5,907
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/CalendarInviteButtons.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { ICAL_ATTENDEE_STATUS } from '@proton/shared/lib/calendar/constants'; import { PartstatActions } from '@proton/shared/lib/interfaces/calendar'; import move from '@proton/utils/move'; import noop from '@proton/utils/noop'; import { ButtonGroup, DropdownMenu, DropdownMenuButton, SimpleDropdown } from '../../components'; interface Props { actions: PartstatActions; partstat?: ICAL_ATTENDEE_STATUS; disabled?: boolean; className?: string; } const CalendarInviteButtons = ({ actions, partstat = ICAL_ATTENDEE_STATUS.NEEDS_ACTION, disabled, className = '', }: Props) => { const [loadingAccept, withLoadingAccept] = useLoading(); const [loadingTentative, withLoadingTentative] = useLoading(); const [loadingDecline, withLoadingDecline] = useLoading(); const { accept, acceptTentatively, decline } = actions; const onAccept = () => withLoadingAccept(accept()); const onTentative = () => withLoadingTentative(acceptTentatively()); const onDecline = () => withLoadingDecline(decline()); const loadingAnswer = loadingAccept || loadingTentative || loadingDecline; const acceptText = c('Action').t`Yes, I'll attend`; const tentativeText = c('Action').t`Maybe I'll attend`; const declineText = c('Action').t`No, I won't attend`; if (partstat === ICAL_ATTENDEE_STATUS.NEEDS_ACTION) { return ( <ButtonGroup className={className}> <Button onClick={onAccept} disabled={loadingAnswer || disabled} loading={loadingAccept} title={acceptText} > {c('Action').t`Yes`} </Button> <Button onClick={onTentative} disabled={loadingAnswer || disabled} loading={loadingTentative} title={tentativeText} > {c('Action').t`Maybe`} </Button> <Button onClick={onDecline} disabled={loadingAnswer || disabled} loading={loadingDecline} title={declineText} > {c('Action').t`No`} </Button> </ButtonGroup> ); } const accepted = partstat === ICAL_ATTENDEE_STATUS.ACCEPTED; const tentative = partstat === ICAL_ATTENDEE_STATUS.TENTATIVE; const declined = partstat === ICAL_ATTENDEE_STATUS.DECLINED; const list = [ { text: acceptText, onClick: accepted ? noop : onAccept, }, { text: tentativeText, onClick: tentative ? noop : onTentative, }, { text: declineText, onClick: declined ? noop : onDecline, }, ]; const answerIndex = [accepted, tentative, declined].findIndex((bool) => bool === true); const orderedList = move(list, answerIndex, 0); const [{ text }, ...restList] = orderedList; return ( <SimpleDropdown originalPlacement="top-end" disabled={disabled} loading={loadingAnswer} className={className} title={c('Title').t`Change my answer`} content={<div className="text-ellipsis">{text}</div>} data-testid="dropdown:open" > <DropdownMenu> {restList.map(({ text, ...restProps }, index) => { return ( <DropdownMenuButton className="text-left" key={index} {...restProps}> {text} </DropdownMenuButton> ); })} </DropdownMenu> </SimpleDropdown> ); }; export default CalendarInviteButtons;
5,908
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/CalendarLimitReachedModal.test.tsx
import { render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { mockUseConfig } from '@proton/testing/lib/mockUseConfig'; import { mockUseLocation } from '@proton/testing/lib/mockUseLocation'; import CalendarLimitReachedModal from './CalendarLimitReachedModal'; describe('CalendarLimitReachedModal', () => { beforeEach(() => { mockUseLocation(); mockUseConfig(); }); describe('when user is free', () => { it('should render correct prompt', async () => { const onClose = jest.fn(); render(<CalendarLimitReachedModal open onClose={onClose} isFreeUser />); expect(screen.getByRole('heading', { level: 1, name: /Cannot add more calendars/ })); expect(screen.getByText("You've reached the maximum number of calendars available in your plan.")); expect( screen.getByText( 'To add a new calendar, remove another calendar or upgrade your Proton plan to a Mail paid plan.' ) ); const link = screen.getByRole('link', { name: /Upgrade/ }); expect(link).toHaveAttribute('href', '/mail/upgrade?ref=upsell_calendar-modal-max-cal'); const button = screen.getByRole('button', { name: /Cancel/ }); await userEvent.click(button); await waitFor(() => { expect(onClose).toHaveBeenCalledTimes(1); }); }); }); describe('when user is paid', () => { it('should render correct prompt', async () => { const onClose = jest.fn(); render(<CalendarLimitReachedModal open onClose={onClose} isFreeUser={false} />); expect(screen.getByRole('heading', { level: 1, name: /Cannot add more calendars/ })); expect(screen.getByText("You've reached the maximum number of calendars available in your plan.")); expect(screen.getByText('To add a new calendar, remove an existing one.')); const link = screen.getByRole('link', { name: /Manage/ }); expect(link).toHaveAttribute('href', '/mail/calendars'); const button = screen.getByRole('button', { name: /Cancel/ }); await userEvent.click(button); await waitFor(() => { expect(onClose).toHaveBeenCalledTimes(1); }); }); }); });
5,909
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/CalendarLimitReachedModal.tsx
import { c } from 'ttag'; import { Button, ButtonLike } from '@proton/atoms'; import { getCalendarsLimitReachedText } from '@proton/shared/lib/calendar/calendarLimits'; import { getCalendarsSettingsPath } from '@proton/shared/lib/calendar/settingsRoutes'; import { APP_UPSELL_REF_PATH, CALENDAR_UPSELL_PATHS, UPSELL_COMPONENT } from '@proton/shared/lib/constants'; import { addUpsellPath, getUpsellRef } from '@proton/shared/lib/helpers/upsell'; import { SettingsLink } from '../../components/link'; import { Prompt } from '../../components/prompt'; interface Props { onClose?: () => void; open?: boolean; isFreeUser: boolean; } const CalendarLimitReachedModal = ({ open, onClose, isFreeUser }: Props) => { const { maxReachedText, addNewCalendarText } = getCalendarsLimitReachedText(isFreeUser); const upsellRef = getUpsellRef({ app: APP_UPSELL_REF_PATH.CALENDAR_UPSELL_REF_PATH, component: UPSELL_COMPONENT.MODAL, feature: CALENDAR_UPSELL_PATHS.MAX_CAL, }); const upgradeLink = addUpsellPath('/upgrade', upsellRef); const submitButtonPath = isFreeUser ? upgradeLink : getCalendarsSettingsPath(); const submitButtonText = isFreeUser ? c('Modal action').t`Upgrade` : c('Modal action').t`Manage calendars`; return ( <Prompt open={open} title={c('Modal title').t`Cannot add more calendars`} buttons={[ <ButtonLike color="norm" as={SettingsLink} path={submitButtonPath}> {submitButtonText} </ButtonLike>, <Button onClick={onClose}>{c('Modal action').t`Cancel`}</Button>, ]} onClose={onClose} > <p>{maxReachedText}</p> <p>{addNewCalendarText}</p> </Prompt> ); }; export default CalendarLimitReachedModal;
5,910
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/index.ts
export * from './notifications'; export * from './settings'; export { default as CalendarInviteButtons } from './CalendarInviteButtons'; export { default as ShareLinkSection } from './shareURL/CalendarShareUrlSection';
5,911
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/calendarModal/CalendarModal.scss
@import '~@proton/styles/scss/lib'; .calendar-modal { &-content { > * + * { margin-block-start: rem(16); } } }
5,912
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/calendarModal/CalendarModal.tsx
import { ChangeEvent, useMemo, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useContactEmailsCache } from '@proton/components/containers/contacts/ContactEmailsProvider'; import { useLoading } from '@proton/hooks'; import { dedupeNotifications, sortNotificationsByAscendingTrigger } from '@proton/shared/lib/calendar/alarms'; import { getIsCalendarWritable, getIsSubscribedCalendar, getShowDuration } from '@proton/shared/lib/calendar/calendar'; import { MAX_CHARS_API, MAX_DEFAULT_NOTIFICATIONS } from '@proton/shared/lib/calendar/constants'; import { getSharedCalendarSubHeaderText } from '@proton/shared/lib/calendar/sharing/shareProton/shareProton'; import { Nullable } from '@proton/shared/lib/interfaces'; import { NotificationModel, SubscribedCalendar, VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import { ColorPicker, Form, InputFieldTwo, Loader, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, Option, SelectTwo, TextArea, TooltipExclusive, } from '../../../components'; import { SelectChangeEvent } from '../../../components/selectTwo/select'; import { TruncatedText } from '../../../components/truncatedText'; import GenericError from '../../error/GenericError'; import useGetCalendarActions from '../hooks/useGetCalendarActions'; import useGetCalendarSetup from '../hooks/useGetCalendarSetup'; import Notifications from '../notifications/Notifications'; import { getCalendarPayload, getCalendarSettingsPayload, getDefaultModel, validate } from './calendarModalState'; import './CalendarModal.scss'; const URL_MAX_DISPLAY_LENGTH = 100; export enum CALENDAR_MODAL_TYPE { COMPLETE, SHARED, VISUAL, } const { COMPLETE, VISUAL, SHARED } = CALENDAR_MODAL_TYPE; export interface CalendarModalProps { calendar?: VisualCalendar | SubscribedCalendar; calendars?: VisualCalendar[]; defaultCalendarID?: Nullable<string>; onClose?: () => void; onExit?: () => void; onCreateCalendar?: (id: string) => void; onEditCalendar?: () => void; open?: boolean; type?: CALENDAR_MODAL_TYPE; } export const CalendarModal = ({ calendar: initialCalendar, calendars = [], defaultCalendarID = '', open, onClose, onExit, onCreateCalendar, onEditCalendar, type = COMPLETE, }: CalendarModalProps) => { const [loadingAction, withLoadingAction] = useLoading(); const { contactEmailsMap } = useContactEmailsCache() || {}; const [isSubmitted, setIsSubmitted] = useState(false); const [error, setError] = useState(false); const [calendar, setCalendar] = useState(initialCalendar); const [model, setModel] = useState(() => getDefaultModel()); const addressText = useMemo(() => { const option = model.addressOptions.find(({ value: ID }) => ID === model.addressID); return (option && option.text) || ''; }, [model.addressID, model.addressOptions]); const showDuration = initialCalendar ? getShowDuration(initialCalendar) : true; const subscribeURL = initialCalendar && getIsSubscribedCalendar(initialCalendar) ? initialCalendar.SubscriptionParameters.URL : undefined; const { error: setupError, loading: loadingSetup } = useGetCalendarSetup({ calendar: initialCalendar, setModel }); const { handleCreateCalendar, handleUpdateCalendar } = useGetCalendarActions({ type, setCalendar, setError, defaultCalendarID, onClose, onCreateCalendar, onEditCalendar, calendars, }); const formattedModel = { ...model, name: model.name.trim(), description: model.description.trim(), }; const errors = validate(formattedModel); const handleProcessCalendar = async () => { const formattedModelWithFormattedNotifications = { ...formattedModel, partDayNotifications: sortNotificationsByAscendingTrigger(dedupeNotifications(model.partDayNotifications)), fullDayNotifications: sortNotificationsByAscendingTrigger(dedupeNotifications(model.fullDayNotifications)), }; const calendarPayload = getCalendarPayload(formattedModelWithFormattedNotifications); const calendarSettingsPayload = getCalendarSettingsPayload(formattedModelWithFormattedNotifications); if (calendar) { return handleUpdateCalendar(calendar, calendarPayload, calendarSettingsPayload); } return handleCreateCalendar( formattedModelWithFormattedNotifications.addressID, calendarPayload, calendarSettingsPayload ); }; const hasError = error || setupError; const getTitle = (type: CALENDAR_MODAL_TYPE) => { const editCalendarText = c('Title; edit calendar modal').t`Edit calendar`; if (hasError) { return c('Title').t`Error`; } if (type === VISUAL) { return editCalendarText; } return initialCalendar ? editCalendarText : c('Title; create calendar modal').t`Create calendar`; }; const getSubline = () => { if (type !== CALENDAR_MODAL_TYPE.SHARED || !calendar || !contactEmailsMap) { return; } const subHeaderText = getSharedCalendarSubHeaderText(calendar, contactEmailsMap); return ( subHeaderText && ( <> <div className="text-rg text-break mb-1 color-norm">{subHeaderText}</div> {!getIsCalendarWritable(calendar) && ( <div className="text-rg text-ellipsis color-weak"> {c('Info; access rights for shared calendar').t`View only`} </div> )} </> ) ); }; const getSize = (type: CALENDAR_MODAL_TYPE) => { if (type === VISUAL) { return 'small'; } return 'large'; }; const handleSubmit = () => { if (hasError) { window.location.reload(); return; } setIsSubmitted(true); if (Object.keys(errors).length > 0) { return; } void withLoadingAction(handleProcessCalendar()); }; const getFakeLabel = (labelText: string) => ( <span className="flex field-two-label-container flex-justify-space-between flex-nowrap flex-align-items-end"> <span className="field-two-label">{labelText}</span> </span> ); const getFakeInputTwo = ({ content, label }: { content: React.ReactNode; label: string }) => { // classes taken from InputFieldTwo return ( <div className="field-two-container w-full"> {getFakeLabel(label)} <div className="field-two-field-container relative">{content}</div> </div> ); }; const calendarNameRow = ( <InputFieldTwo id="calendar-name-input" label={c('Label').t`Name`} value={model.name} error={isSubmitted && errors.name} maxLength={MAX_CHARS_API.CALENDAR_NAME} disableChange={loadingAction} placeholder={c('Placeholder').t`Add a calendar name`} onChange={({ target }: ChangeEvent<HTMLInputElement>) => setModel({ ...model, name: target.value })} autoFocus /> ); const colorRow = ( <InputFieldTwo as={ColorPicker} label={c('Label').t`Color`} id="calendar-color" color={model.color} onChange={(color: string) => setModel({ ...model, color })} /> ); const descriptionRow = ( <InputFieldTwo as={TextArea} label={c('Label').t`Description`} autoGrow id="calendar-description-textarea" value={model.description} placeholder={c('Placeholder').t`Add a calendar description`} onChange={({ target }: ChangeEvent<HTMLTextAreaElement>) => setModel({ ...model, description: target.value }) } maxLength={MAX_CHARS_API.CALENDAR_DESCRIPTION} isSubmitted={isSubmitted} error={errors.description} /> ); const addressRow = model.calendarID ? ( getFakeInputTwo({ content: addressText, label: c('Label').t`Email address` }) ) : ( <InputFieldTwo as={SelectTwo} id="calendar-address-select" value={model.addressID} // @ts-ignore onChange={({ value }: SelectChangeEvent<string>) => setModel({ ...model, addressID: value })} label={c('Label').t`Email address`} > {model.addressOptions.map(({ value, text }) => ( <Option key={value} value={value} title={text} /> ))} </InputFieldTwo> ); const defaultEventDurationRow = showDuration ? ( <InputFieldTwo as={SelectTwo} label={c('Label').t`Event duration`} id="duration-select" data-testid="create-calendar/event-settings:event-duration" value={model.duration} // @ts-ignore onChange={({ value }: SelectChangeEvent<string>) => setModel({ ...model, duration: +value })} > {[ { text: c('Duration').t`30 minutes`, value: 30 }, { text: c('Duration').t`60 minutes`, value: 60 }, { text: c('Duration').t`90 minutes`, value: 90 }, { text: c('Duration').t`120 minutes`, value: 120 }, ].map(({ value, text }) => ( <Option key={value} value={value} title={text} /> ))} </InputFieldTwo> ) : null; const defaultNotificationsRow = ( <> <InputFieldTwo id="default-notification" as={Notifications} label={c('Label').t`Event notifications`} data-testid="create-calendar/event-settings:default-notification" hasType notifications={model.partDayNotifications} canAdd={model.partDayNotifications.length < MAX_DEFAULT_NOTIFICATIONS} defaultNotification={model.defaultPartDayNotification} onChange={(notifications: NotificationModel[]) => { setModel({ ...model, partDayNotifications: notifications, }); }} /> <InputFieldTwo id="default-full-day-notification" as={Notifications} label={c('Label').t`All-day event notifications`} data-testid="create-calendar/event-settings:default-full-day-notification" hasType notifications={model.fullDayNotifications} canAdd={model.fullDayNotifications.length < MAX_DEFAULT_NOTIFICATIONS} defaultNotification={model.defaultFullDayNotification} onChange={(notifications: NotificationModel[]) => { setModel({ ...model, fullDayNotifications: notifications, }); }} /> </> ); const subscribeURLRow = subscribeURL && getFakeInputTwo({ content: ( <span className="text-break-all"> <TruncatedText maxChars={URL_MAX_DISPLAY_LENGTH}>{subscribeURL}</TruncatedText> </span> ), label: c('Label').t`URL`, }); const getContentRows = (type: CALENDAR_MODAL_TYPE) => { if (type === VISUAL) { return ( <> {calendarNameRow} {descriptionRow} {colorRow} </> ); } if (type === SHARED) { return ( <> {calendarNameRow} {colorRow} {addressRow} {descriptionRow} {defaultNotificationsRow} </> ); } return ( <> {calendarNameRow} {colorRow} {addressRow} {descriptionRow} {defaultEventDurationRow} {defaultNotificationsRow} {subscribeURLRow} </> ); }; return ( <TooltipExclusive> <ModalTwo size={getSize(type)} fullscreenOnMobile className="w-full" open={open} onClose={onClose} as={Form} dense onSubmit={() => { if (!loadingAction) { handleSubmit(); } }} onExit={onExit} > {loadingSetup ? ( <Loader /> ) : ( <> <ModalTwoHeader title={getTitle(type)} subline={getSubline()} /> <ModalTwoContent className="calendar-modal-content"> {hasError ? <GenericError /> : getContentRows(type)} </ModalTwoContent> <ModalTwoFooter> {hasError ? ( <Button onClick={() => window.location.reload()} className="ml-auto" color="norm"> {c('Action').t`Close`} </Button> ) : ( <> <Button onClick={onClose} disabled={loadingAction}> {c('Action').t`Cancel`} </Button> <Button loading={loadingAction} type="submit" color="norm"> {c('Action').t`Save`} </Button> </> )} </ModalTwoFooter> </> )} </ModalTwo> </TooltipExclusive> ); }; export default CalendarModal;
5,913
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/calendarModal/calendarModalState.ts
import { c } from 'ttag'; import { sortNotificationsByAscendingTrigger } from '@proton/shared/lib/calendar/alarms'; import { modelToNotifications } from '@proton/shared/lib/calendar/alarms/modelToNotifications'; import { DEFAULT_FULL_DAY_NOTIFICATION, DEFAULT_FULL_DAY_NOTIFICATIONS, DEFAULT_PART_DAY_NOTIFICATION, DEFAULT_PART_DAY_NOTIFICATIONS, } from '@proton/shared/lib/calendar/alarms/notificationDefaults'; import { notificationsToModel } from '@proton/shared/lib/calendar/alarms/notificationsToModel'; import { CALENDAR_TYPE, DEFAULT_EVENT_DURATION } from '@proton/shared/lib/calendar/constants'; import { getRandomAccentColor } from '@proton/shared/lib/colors'; import { Address } from '@proton/shared/lib/interfaces'; import { CalendarErrors, CalendarSettings, CalendarViewModelFull, VisualCalendar, } from '@proton/shared/lib/interfaces/calendar'; import { CalendarCreateData } from '@proton/shared/lib/interfaces/calendar/Api'; export const getCalendarEventSettingsModel = (settings: Partial<CalendarSettings>) => { const { DefaultPartDayNotifications = DEFAULT_PART_DAY_NOTIFICATIONS, DefaultFullDayNotifications = DEFAULT_FULL_DAY_NOTIFICATIONS, DefaultEventDuration = DEFAULT_EVENT_DURATION, } = settings; const partDayNotifications = sortNotificationsByAscendingTrigger( notificationsToModel(DefaultPartDayNotifications, false) ); const fullDayNotifications = sortNotificationsByAscendingTrigger( notificationsToModel(DefaultFullDayNotifications, true) ); return { duration: DefaultEventDuration, partDayNotifications, fullDayNotifications, }; }; interface GetCalendarModelArguments { Calendar: VisualCalendar; CalendarSettings: CalendarSettings; Addresses: Address[]; AddressID: string; } export const getCalendarModel = ({ Calendar, CalendarSettings, Addresses, AddressID, }: GetCalendarModelArguments): Partial<CalendarViewModelFull> => ({ calendarID: Calendar.ID, name: Calendar.Name, display: !!Calendar.Display, description: Calendar.Description, color: (Calendar.Color || '').toLowerCase(), addressID: AddressID, addressOptions: Addresses.map(({ ID, Email = '' }) => ({ value: ID, text: Email })), type: Calendar.Type, ...getCalendarEventSettingsModel(CalendarSettings), }); export const getDefaultModel = (): CalendarViewModelFull => { return { calendarID: '', name: '', members: [], description: '', color: getRandomAccentColor(), display: true, addressID: '', addressOptions: [], duration: DEFAULT_EVENT_DURATION, defaultPartDayNotification: DEFAULT_PART_DAY_NOTIFICATION, defaultFullDayNotification: DEFAULT_FULL_DAY_NOTIFICATION, partDayNotifications: notificationsToModel(DEFAULT_PART_DAY_NOTIFICATIONS, false), fullDayNotifications: notificationsToModel(DEFAULT_FULL_DAY_NOTIFICATIONS, true), type: CALENDAR_TYPE.PERSONAL, }; }; export const validate = ({ name }: CalendarViewModelFull): CalendarErrors => { const errors = {} as { [key: string]: string }; if (!name) { errors.name = c('Error').t`Name required`; } return errors; }; export const getCalendarPayload = (model: CalendarViewModelFull): CalendarCreateData => { return { Name: model.name, Color: model.color, Display: model.display ? 1 : 0, Description: model.description, URL: model.url, }; }; export const getCalendarSettingsPayload = (model: CalendarViewModelFull) => { const { duration, fullDayNotifications, partDayNotifications } = model; return { DefaultEventDuration: +duration, DefaultFullDayNotifications: modelToNotifications(fullDayNotifications), DefaultPartDayNotifications: modelToNotifications(partDayNotifications), }; };
5,914
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/calendarModal/index.ts
export * from './CalendarModal';
5,915
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/exportModal/ExportModal.tsx
import { useState } from 'react'; import { format } from 'date-fns'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { createExportIcs } from '@proton/shared/lib/calendar/export/createExportIcs'; import { getProdIdFromNameAndVersion } from '@proton/shared/lib/calendar/vcalConfig'; import { getUniqueVtimezones } from '@proton/shared/lib/calendar/vtimezoneHelper'; import downloadFile from '@proton/shared/lib/helpers/downloadFile'; import { EXPORT_ERRORS, EXPORT_STEPS, ExportCalendarModel, ExportError, VcalVeventComponent, VisualCalendar, } from '@proton/shared/lib/interfaces/calendar'; import { getWeekStartsOn } from '@proton/shared/lib/settings/helper'; import { getAppVersion } from '../../..'; import { BasicModal } from '../../../components'; import { useConfig, useGetCalendarUserSettings, useUserSettings } from '../../../hooks'; import { useGetVtimezonesMap } from '../../../hooks/useGetVtimezonesMap'; import ExportSummaryModalContent from './ExportSummaryModalContent'; import ExportingModalContent from './ExportingModalContent'; interface Props { calendar: VisualCalendar; onClose?: () => void; onExit?: () => void; isOpen?: boolean; } export const ExportModal = ({ calendar, onClose, onExit, isOpen = false }: Props) => { const getVTimezonesMap = useGetVtimezonesMap(); const getCalendarUserSettings = useGetCalendarUserSettings(); const [userSettings] = useUserSettings(); const weekStartsOn = getWeekStartsOn(userSettings); const { APP_VERSION } = useConfig(); const appVersion = getAppVersion(APP_VERSION); const [model, setModel] = useState<ExportCalendarModel>({ step: EXPORT_STEPS.EXPORTING, totalFetched: 0, totalProcessed: 0, exportErrors: [], totalToProcess: 0, weekStartsOn, calendar, }); const updateModel = (changes: Partial<ExportCalendarModel>) => setModel((currentModel: ExportCalendarModel) => ({ ...currentModel, ...changes })); const [calendarBlob, setCalendarBlob] = useState<Blob>(); const { content, onSubmit } = (() => { if (model.step === EXPORT_STEPS.EXPORTING) { const handleFinish = async ( exportedEvents: VcalVeventComponent[], exportErrors: ExportError[], keepError?: boolean ) => { // we don't catch errors here as they're caught into a NETWORK error on ExportingModalContent const { PrimaryTimezone: defaultTzid } = await getCalendarUserSettings(); const uniqueTimezones = await getUniqueVtimezones({ vevents: exportedEvents, tzids: [defaultTzid], getVTimezonesMap, }).catch(() => { return []; }); const ics = createExportIcs({ calendar, // We use the ProtonAccount version here, // but we do not want to display 'Web Account' in this public PRODID // As a compromise between a "marketing display" and traceability, // we add a '.a' suffix to indicate that the version refers to Proton Account prodId: getProdIdFromNameAndVersion('WebCalendar', `${appVersion}.a`), eventsWithSummary: exportedEvents, defaultTzid, vtimezones: uniqueTimezones, }); updateModel({ step: EXPORT_STEPS.FINISHED, exportErrors, ...(!keepError && { error: undefined }), }); setCalendarBlob(new Blob([ics], { type: 'text/plain;charset=utf-8' })); }; return { content: <ExportingModalContent model={model} setModel={setModel} onFinish={handleFinish} />, onSubmit: null, }; } return { content: <ExportSummaryModalContent model={model} />, onSubmit: () => { if (model.error === EXPORT_ERRORS.NETWORK_ERROR) { updateModel({ step: EXPORT_STEPS.EXPORTING }); return; } downloadFile(calendarBlob, `${calendar.Name}-${format(Date.now(), 'yyyy-MM-dd')}.ics`); onClose?.(); }, }; })(); return ( <BasicModal title={c('Title').t`Export calendar`} footer={ <> <Button onClick={onClose}>{c('Action').t`Cancel`}</Button> {!!onSubmit && ( <Button color="norm" onClick={onSubmit} type="submit"> {model.error === EXPORT_ERRORS.NETWORK_ERROR ? c('Action').t`Try again` : c('Action').t`Save ICS file`} </Button> )} </> } isOpen={isOpen} size="large" fullscreenOnMobile onClose={onClose} onExit={onExit} > {content} </BasicModal> ); }; export default ExportModal;
5,916
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/exportModal/ExportSummaryModalContent.tsx
import { c, msgid } from 'ttag'; import { Href } from '@proton/atoms'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { EXPORT_ERRORS, EXPORT_EVENT_ERROR_TYPES, ExportCalendarModel, ExportError, } from '@proton/shared/lib/interfaces/calendar'; import partition from '@proton/utils/partition'; import { Alert, Bordered, Details, DynamicProgress, Summary } from '../../../components'; const getErrorMessage = (hasMultiplePasswordResetErrors: boolean) => (type: EXPORT_EVENT_ERROR_TYPES) => { const errorMessagesMap: { [key in EXPORT_EVENT_ERROR_TYPES]: string } = { [EXPORT_EVENT_ERROR_TYPES.DECRYPTION_ERROR]: c('Export calendar').t`Error decrypting event`, [EXPORT_EVENT_ERROR_TYPES.PASSWORD_RESET]: hasMultiplePasswordResetErrors ? c('Export calendar').t`Password reset - multiple events cannot be decrypted` : c('Export calendar').t`Password reset - event cannot be decrypted`, }; return errorMessagesMap[type]; }; interface Props { model: ExportCalendarModel; } const ExportSummaryModalContent = ({ model }: Props) => { const { totalFetched, totalProcessed, totalToProcess, exportErrors, error } = model; const isSuccess = totalProcessed === totalToProcess && error === undefined; const isPartialSuccess = totalProcessed > 0 && !isSuccess; const totalErrors = exportErrors.length; const displayMessage = isPartialSuccess || isSuccess ? c('Export calendar').ngettext( msgid`${totalProcessed}/${totalToProcess} event exported`, `${totalProcessed}/${totalToProcess} events exported`, totalToProcess ) : ''; const [passwordResetErrors, otherErrors] = partition<ExportError>( exportErrors, (item): item is ExportError => item[1] === EXPORT_EVENT_ERROR_TYPES.PASSWORD_RESET ); const hasMultiplePasswordResetErrors = passwordResetErrors.length > 1; const filteredErrors: ExportError[] = hasMultiplePasswordResetErrors ? [...otherErrors, ['', EXPORT_EVENT_ERROR_TYPES.PASSWORD_RESET]] : exportErrors; const hasOnlyPasswordResetErrors = passwordResetErrors.length === exportErrors.length; const kbLink = getKnowledgeBaseUrl('/restoring-encrypted-calendar'); const getAlertMessage = () => { if (isSuccess) { return c('Export calendar').t`Calendar successfully exported. You can now save the ICS file.`; } if (isPartialSuccess) { if (hasOnlyPasswordResetErrors) { return ( <> <div> {c('Export calendar') .t`Due to a password reset, some of your events could not be decrypted and exported.`} </div> <div> {c('Export calendar') .t`You can save an ICS file of the events that were successfully exported.`} </div> <div> <Href href={kbLink}>{c('Export calendar') .t`Learn how to restore encrypted events with old password`}</Href> </div> </> ); } return ( <> <div>{c('Export calendar').t`Some of your events could not be exported.`}</div> <div>{c('Export calendar') .t`You can save an ICS file of the events that were successfully exported.`}</div> </> ); } if (model.error === EXPORT_ERRORS.NETWORK_ERROR) { return c('Export calendar') .t`The internet connection was interrupted, causing the export process to fail. Please try again.`; } if (hasOnlyPasswordResetErrors) { return ( <> <div> {c('Export calendar') .t`Due to a password reset, none of your events could be decrypted and exported.`} </div> <div> <Href href={kbLink}>{c('Export calendar') .t`Learn how to restore encrypted events with old password`}</Href> </div> </> ); } return c('Export calendar').t`None of the events could be exported.`; }; const shouldShowErrorDetails = !!filteredErrors.length && !hasOnlyPasswordResetErrors; const getError = getErrorMessage(hasMultiplePasswordResetErrors); const getMessage = () => { const message = getAlertMessage(); if (isSuccess) { return <div className="mb-4">{message}</div>; } return ( <Alert className="mb-4" type={isPartialSuccess ? 'warning' : 'error'}> {message} </Alert> ); }; return ( <> {getMessage()} <DynamicProgress id="progress-export-calendar" value={totalFetched + totalProcessed + totalErrors} display={displayMessage} max={2 * totalToProcess} loading={false} success={isSuccess} partialSuccess={isPartialSuccess} /> {shouldShowErrorDetails && ( <Details> <Summary>{c('Summary of errors during export calendar') .t`Details about events that couldn't be exported`}</Summary> <Bordered> {filteredErrors.map(([details, error], index) => ( <div key={index}> {details && <span>{details}: </span>} <span className="color-danger">{getError(error)}</span> </div> ))} </Bordered> </Details> )} </> ); }; export default ExportSummaryModalContent;
5,917
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/exportModal/ExportingModalContent.tsx
import { Dispatch, SetStateAction, useEffect } from 'react'; import { c } from 'ttag'; import { getEventsCount } from '@proton/shared/lib/api/calendars'; import { getApiWithAbort } from '@proton/shared/lib/api/helpers/customConfig'; import { processInBatches } from '@proton/shared/lib/calendar/export/export'; import { EXPORT_ERRORS, EXPORT_STEPS, ExportCalendarModel, ExportError, VcalVeventComponent, } from '@proton/shared/lib/interfaces/calendar'; import { DynamicProgress } from '../../../components'; import { useApi, useGetAddressKeys, useGetAddresses, useGetCalendarInfo, useGetCalendarKeys, useGetCalendarUserSettings, } from '../../../hooks'; interface Props { model: ExportCalendarModel; setModel: Dispatch<SetStateAction<ExportCalendarModel>>; onFinish: (vevents: VcalVeventComponent[], exportErrors: ExportError[], keepError?: boolean) => void; } const ExportingModalContent = ({ model, setModel, onFinish }: Props) => { const api = useApi(); const getAddresses = useGetAddresses(); const getCalendarInfo = useGetCalendarInfo(); const getAddressKeys = useGetAddressKeys(); const getCalendarKeys = useGetCalendarKeys(); const getCalendarUserSettings = useGetCalendarUserSettings(); const { totalFetched, totalToProcess, totalProcessed, exportErrors } = model; const totalErrors = exportErrors.length; useEffect(() => { // Prepare api for allowing cancellation in the middle of the export const abortController = new AbortController(); const { signal } = abortController; const setModelWithAbort = (set: (currentModel: ExportCalendarModel) => ExportCalendarModel) => { if (signal.aborted) { return; } setModel(set); }; const handleExportProgress = ( eventIDs: string[], veventComponents: VcalVeventComponent[], exportErrors: ExportError[] ) => { setModelWithAbort((currentModel) => ({ ...currentModel, totalFetched: currentModel.totalFetched + eventIDs.length, totalProcessed: currentModel.totalProcessed + veventComponents.length, exportErrors: [...currentModel.exportErrors, ...exportErrors], })); }; const process = async () => { try { const [addresses, { calendarSettings }, calendarUserSettings] = await Promise.all([ getAddresses(), getCalendarInfo(model.calendar.ID), getCalendarUserSettings(), ]); if (!addresses) { throw new Error('No addresses'); } const { Total: totalToProcess } = await api<{ Total: number }>(getEventsCount(model.calendar.ID)); setModelWithAbort((currentModel) => ({ ...currentModel, totalToProcess, })); const [exportedEvents, exportErrors, totalEventsFetched] = await processInBatches({ calendar: model.calendar, addresses, api: getApiWithAbort(api, signal), signal, onProgress: handleExportProgress, getAddressKeys, getCalendarKeys, totalToProcess, weekStartsOn: model.weekStartsOn, calendarSettings, defaultTzid: calendarUserSettings.PrimaryTimezone, }); if (totalToProcess !== totalEventsFetched) { setModelWithAbort((currentModel) => ({ ...currentModel, totalToProcess: totalEventsFetched, })); } if (signal.aborted) { return; } onFinish(exportedEvents, exportErrors); } catch (error: any) { setModelWithAbort((currentModel) => ({ ...currentModel, step: EXPORT_STEPS.FINISHED, totalProcessed: 0, totalToProcess: 0, exportErrors: [], error: EXPORT_ERRORS.NETWORK_ERROR, })); if (signal.aborted) { return; } onFinish([], [], true); } }; void process(); return () => { abortController.abort(); }; }, []); const display = !totalProcessed ? c('Export calendar').t`Loading events` : c('Export calendar').t`Decrypting events from your calendar: ${totalProcessed}/${totalToProcess}`; return ( <> <div className="mb-4"> {c('Export calendar').t`Please don't close the tab before the exporting process is finished.`} </div> <DynamicProgress id="progress-export-calendar" value={totalFetched + totalProcessed + totalErrors} display={display} max={2 * totalToProcess} loading /> </> ); }; export default ExportingModalContent;
5,918
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/exportModal/index.ts
export * from './ExportModal';
5,919
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/holidaysCalendarModal/HolidaysCalendarModal.tsx
import { useEffect, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { CalendarBootstrap, HolidaysDirectoryCalendar, VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import { Form, Loader, ModalTwo as Modal, ModalProps, ModalTwoContent, ModalTwoFooter } from '../../../components'; import { useGetCalendarBootstrap } from '../../../hooks'; import GenericError from '../../error/GenericError'; import { CALENDAR_MODAL_TYPE } from '../calendarModal'; import { useGetHolidaysDirectory } from '../hooks/useHolidaysDirectory'; import HolidaysCalendarModalWithDirectory from './HolidaysCalendarModalWithDirectory'; interface Props extends ModalProps { /** * Calendar the user wants to update */ calendar?: VisualCalendar; /** * Holidays calendars the user has already joined */ holidaysCalendars: VisualCalendar[]; type?: CALENDAR_MODAL_TYPE; onEditCalendar?: () => void; } const HolidaysCalendarModal = ({ calendar, holidaysCalendars, type = CALENDAR_MODAL_TYPE.COMPLETE, onEditCalendar, ...rest }: Props) => { const getCalendarBootstrap = useGetCalendarBootstrap(); const getHolidaysDirectory = useGetHolidaysDirectory(); const [directory, setDirectory] = useState<HolidaysDirectoryCalendar[] | undefined>(); const [bootstrap, setBootstrap] = useState<CalendarBootstrap | undefined>(); const [error, setError] = useState<Error | undefined>(); useEffect(() => { const run = async () => { try { const getHolidaysDirectoryPromise = getHolidaysDirectory().then((directory) => { setDirectory(directory); }); const promises = [getHolidaysDirectoryPromise]; if (calendar) { const getCalendarBootstrapPromise = getCalendarBootstrap(calendar.ID).then( (bootstrap: CalendarBootstrap) => { setBootstrap(bootstrap); } ); promises.push(getCalendarBootstrapPromise); } void (await Promise.all(promises)); } catch (e: any) { const error = e instanceof Error ? e : new Error('Unknown error loading holidays directory'); setError(error); } }; void run(); }, []); if (error) { return ( <Modal as={Form} fullscreenOnMobile size="large" {...rest}> <ModalTwoContent className="calendar-modal-content"> <GenericError /> </ModalTwoContent> <ModalTwoFooter> <Button onClick={() => window.location.reload()} className="ml-auto" color="norm"> {c('Action').t`Close`} </Button> </ModalTwoFooter> </Modal> ); } if (!directory || (calendar && !bootstrap)) { return ( <Modal as={Form} fullscreenOnMobile size="large" {...rest}> <Loader /> </Modal> ); } return ( <HolidaysCalendarModalWithDirectory calendar={calendar} calendarBootstrap={bootstrap} holidaysCalendars={holidaysCalendars} directory={directory} type={type} onEditCalendar={onEditCalendar} {...rest} /> ); }; export default HolidaysCalendarModal;
5,920
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/holidaysCalendarModal/HolidaysCalendarModalWithDirectory.tsx
import { useCallback, useMemo, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { useLoading } from '@proton/hooks'; import { removeMember } from '@proton/shared/lib/api/calendars'; import { dedupeNotifications, sortNotificationsByAscendingTrigger } from '@proton/shared/lib/calendar/alarms'; import { modelToNotifications } from '@proton/shared/lib/calendar/alarms/modelToNotifications'; import { notificationsToModel } from '@proton/shared/lib/calendar/alarms/notificationsToModel'; import { updateCalendar } from '@proton/shared/lib/calendar/calendar'; import { DEFAULT_EVENT_DURATION, MAX_DEFAULT_NOTIFICATIONS } from '@proton/shared/lib/calendar/constants'; import setupHolidaysCalendarHelper from '@proton/shared/lib/calendar/crypto/keys/setupHolidaysCalendarHelper'; import { findHolidaysCalendarByCountryCodeAndLanguageTag, getHolidaysCalendarsFromCountryCode, getSuggestedHolidaysCalendar, } from '@proton/shared/lib/calendar/holidaysCalendar/holidaysCalendar'; import { getRandomAccentColor } from '@proton/shared/lib/colors'; import { languageCode } from '@proton/shared/lib/i18n'; import { getBrowserLanguageTags } from '@proton/shared/lib/i18n/helper'; import { CalendarBootstrap, CalendarCreateData, CalendarSettings, HolidaysDirectoryCalendar, NotificationModel, VisualCalendar, } from '@proton/shared/lib/interfaces/calendar'; import uniqueBy from '@proton/utils/uniqueBy'; import { ColorPicker, Form, InputFieldTwo as InputField, ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, ModalProps, Option, SelectTwo as Select, useFormErrors, } from '../../../components'; import CountrySelect from '../../../components/country/CountrySelect'; import { useAddresses, useApi, useCalendarUserSettings, useEventManager, useGetAddressKeys, useGetAddresses, useNotifications, useReadCalendarBootstrap, } from '../../../hooks'; import { useCalendarModelEventManager } from '../../eventManager'; import { CALENDAR_MODAL_TYPE } from '../calendarModal'; import { getDefaultModel } from '../calendarModal/calendarModalState'; import Notifications from '../notifications/Notifications'; const getInitialCalendarNotifications = (bootstrap?: CalendarBootstrap) => { if (!bootstrap) { return []; } const { CalendarSettings } = bootstrap; return notificationsToModel(CalendarSettings.DefaultFullDayNotifications, true); }; const getHasAlreadyJoinedCalendar = ( holidaysCalendars: VisualCalendar[], calendar?: HolidaysDirectoryCalendar, inputCalendar?: VisualCalendar ) => { if (!calendar) { return false; } const { CalendarID } = calendar; const holidaysCalendar = holidaysCalendars.find(({ ID }) => ID === CalendarID); return !!holidaysCalendar && holidaysCalendar.ID !== inputCalendar?.ID; }; const getModalTitle = (isEdit: boolean) => { if (isEdit) { return c('Modal title').t`Edit calendar`; } // translator: A holidays calendar includes bank holidays and observances return c('Modal title').t`Add public holidays`; }; const getModalSubline = (isEdit: boolean) => { if (isEdit) { return; } // translator: A holidays calendar includes bank holidays and observances return c('Modal title').t`Get a country's official public holidays calendar.`; }; interface Props extends ModalProps { /** * Calendar the user wants to update */ calendar?: VisualCalendar; calendarBootstrap?: CalendarBootstrap; directory: HolidaysDirectoryCalendar[]; /** * Holidays calendars the user has already joined */ holidaysCalendars: VisualCalendar[]; type: CALENDAR_MODAL_TYPE; onEditCalendar?: () => void; } const HolidaysCalendarModalWithDirectory = ({ calendar: inputHolidaysCalendar, calendarBootstrap, directory, holidaysCalendars, type, onEditCalendar, ...rest }: Props) => { const [addresses] = useAddresses(); const getAddresses = useGetAddresses(); const [{ PrimaryTimezone }] = useCalendarUserSettings(); const { call } = useEventManager(); const { call: calendarCall } = useCalendarModelEventManager(); const api = useApi(); const getAddressKeys = useGetAddressKeys(); const { validator, onFormSubmit } = useFormErrors(); const [loading, withLoading] = useLoading(); const { createNotification } = useNotifications(); const readCalendarBootstrap = useReadCalendarBootstrap(); const memoizedHolidaysCalendars = useMemo(() => { // Prevent the list of user holidays calendars from changing (via event loop) once the modal opened. // This avoids possible UI jumps and glitches return holidaysCalendars; }, []); const visibleDirectory = useMemo(() => { const inputHolidaysCalendarID = inputHolidaysCalendar?.ID; return directory.filter((calendar) => { // a directory calendar is displayed if it's not hidden, or we're editing it return !calendar.Hidden || calendar.CalendarID === inputHolidaysCalendarID; }); }, [directory]); const { directoryCalendarFromInput, suggestedCalendar } = useMemo(() => { // Directory calendar that we want to edit (when we get an input calendar) const directoryCalendarFromInput = visibleDirectory.find( ({ CalendarID }) => CalendarID === inputHolidaysCalendar?.ID ); // Default holidays calendar found based on the user time zone and language const suggestedCalendar = getSuggestedHolidaysCalendar( visibleDirectory, PrimaryTimezone, languageCode, getBrowserLanguageTags() ); return { directoryCalendarFromInput, suggestedCalendar }; }, [inputHolidaysCalendar, visibleDirectory, PrimaryTimezone, languageCode]); // Check if the user has already joined the default holidays directory calendar. // If so, we don't want to pre-select that default calendar const hasAlreadyJoinedSuggestedCalendar = getHasAlreadyJoinedCalendar( memoizedHolidaysCalendars, suggestedCalendar, inputHolidaysCalendar ); /** * We won't have preselection if we are in one of the following cases * - user is editing an existing holidays calendar * - user doesn't have a suggested calendar * - user has already added the suggested calendar */ const canPreselect = !directoryCalendarFromInput && !!suggestedCalendar && !hasAlreadyJoinedSuggestedCalendar; const isEdit = !!inputHolidaysCalendar; // Currently selected option in the modal const [selectedCalendar, setSelectedCalendar] = useState<HolidaysDirectoryCalendar | undefined>( directoryCalendarFromInput ); // Calendar that is either the selected one or the default one if preselect possible // Because in some case, we do have a default calendar (suggested one) to use, but we want to act CountrySelect as if we don't (focus on suggested option) // we need to separate calendar that has been explicitly selected by user from the one that is being used (selected OR suggested) const computedCalendar = selectedCalendar || (canPreselect ? suggestedCalendar : undefined); // Check if currently selected holidays calendar has already been joined by the user // If already joined, we don't want the user to be able to "save" again, or he will get an error const hasAlreadyJoinedSelectedCalendar = getHasAlreadyJoinedCalendar( memoizedHolidaysCalendars, computedCalendar, inputHolidaysCalendar ); const [color, setColor] = useState(inputHolidaysCalendar?.Color || getRandomAccentColor()); const [notifications, setNotifications] = useState<NotificationModel[]>( getInitialCalendarNotifications(calendarBootstrap) ); // Note that we don't need to fill this state on holidays calendar edition since this field will not be displayed // Preselection hint is needed only if // - user can have a preselected calendar // - suggested calendar matches computed one const canShowHint = canPreselect && suggestedCalendar === computedCalendar; const countries: Pick<HolidaysDirectoryCalendar, 'Country' | 'CountryCode'>[] = useMemo(() => { return uniqueBy(visibleDirectory, ({ CountryCode }) => CountryCode) .map(({ Country, CountryCode }) => ({ Country, CountryCode })) .sort((a, b) => a.Country.localeCompare(b.Country)); }, [visibleDirectory]); // We might have several calendars for a specific country, with different languages const filteredLanguageOptions: HolidaysDirectoryCalendar[] = useMemo(() => { return getHolidaysCalendarsFromCountryCode(visibleDirectory, computedCalendar?.CountryCode || ''); }, [computedCalendar, visibleDirectory]); const preselectedOption = useMemo(() => { return canPreselect ? { countryName: suggestedCalendar.Country, countryCode: suggestedCalendar.CountryCode, } : undefined; }, [canPreselect, suggestedCalendar]); const value = useMemo(() => { return selectedCalendar ? { countryName: selectedCalendar.Country, countryCode: selectedCalendar.CountryCode, } : undefined; }, [selectedCalendar]); const handleSubmit = async () => { try { if (!onFormSubmit() || hasAlreadyJoinedSelectedCalendar) { return; } if (computedCalendar) { const formattedNotifications = modelToNotifications( sortNotificationsByAscendingTrigger(dedupeNotifications(notifications)) ); /** * Based on the inputHolidaysCalendar, we have several cases to cover: * 1 - The user is updating colors or notifications of his holidays calendar * => We perform a classic calendar update * 2 - The user is updating the country or the language of his holidays calendar * => We need to leave the old holidays calendar and then join a new one * 3 - The user is joining a holidays calendar * => We just want to join a holidays calendar */ if (inputHolidaysCalendar) { // 1 - Classic update: staying in the same holidays calendar if (computedCalendar.CalendarID === directoryCalendarFromInput?.CalendarID) { const calendarPayload: CalendarCreateData = { Name: inputHolidaysCalendar.Name, Description: inputHolidaysCalendar.Description, Color: color, Display: inputHolidaysCalendar.Display, }; const calendarSettingsPayload: Required< Pick< CalendarSettings, 'DefaultEventDuration' | 'DefaultPartDayNotifications' | 'DefaultFullDayNotifications' > > = { DefaultEventDuration: DEFAULT_EVENT_DURATION, DefaultFullDayNotifications: formattedNotifications, DefaultPartDayNotifications: [], }; await updateCalendar( inputHolidaysCalendar, calendarPayload, calendarSettingsPayload, readCalendarBootstrap, getAddresses, api ); await call(); await calendarCall([directoryCalendarFromInput.CalendarID]); onEditCalendar?.(); } else { // 2 - Leave old holidays calendar and join a new one // 2bis - If input holidays calendar doesn't exist anymore, we remove it and join new one await api(removeMember(inputHolidaysCalendar.ID, inputHolidaysCalendar.Members[0].ID)); await setupHolidaysCalendarHelper({ holidaysCalendar: computedCalendar, addresses, getAddressKeys, color, notifications: formattedNotifications, api, }).catch(() => { createNotification({ type: 'error', // translator: A holidays calendar includes bank holidays and observances text: c('Notification in holidays calendar modal').t`Adding holidays calendar failed`, }); }); await call(); } createNotification({ type: 'success', text: c('Notification in holidays calendar modal').t`Calendar updated`, }); } else { // 3 - Joining a holidays calendar await setupHolidaysCalendarHelper({ holidaysCalendar: computedCalendar, addresses, getAddressKeys, color, notifications: formattedNotifications, api, }); await call(); createNotification({ type: 'success', text: c('Notification in holidays calendar modal').t`Calendar added`, }); } rest.onClose?.(); } } catch (error) { console.error(error); rest.onClose?.(); } }; const handleSelectCountry = useCallback( (countryCode: string) => { const newSelected = findHolidaysCalendarByCountryCodeAndLanguageTag(visibleDirectory, countryCode, [ languageCode, ...getBrowserLanguageTags(), ]); if (newSelected) { setSelectedCalendar(newSelected); } }, [visibleDirectory, setSelectedCalendar] ); const handleSelectLanguage = ({ value }: { value: any }) => { const calendarsFromCountry = filteredLanguageOptions.find((calendar) => calendar.Language === value); setSelectedCalendar(calendarsFromCountry); }; const getErrorText = () => { if (!rest.open) { // Avoid displaying the error during the exit animation return ''; } if (hasAlreadyJoinedSelectedCalendar) { // translator: A holidays calendar includes bank holidays and observances return c('Error').t`You already added this holidays calendar`; } return ''; }; // translator: Hint text about the pre-selected country option in the holidays calendar modal const hintText = c('Info').t`Based on your time zone`; const isComplete = type === CALENDAR_MODAL_TYPE.COMPLETE; const countryOptions = useMemo( () => countries.map((calendar) => ({ countryName: calendar.Country, countryCode: calendar.CountryCode, })), [countries] ); return ( <Modal as={Form} fullscreenOnMobile onSubmit={() => withLoading(handleSubmit())} size="large" {...rest}> <ModalHeader title={getModalTitle(isEdit)} subline={getModalSubline(isEdit)} /> <ModalContent className="holidays-calendar-modal-content"> {isComplete && ( <CountrySelect options={countryOptions} preSelectedOption={preselectedOption} value={value} preSelectedOptionDivider={hintText} onSelectCountry={handleSelectCountry} error={validator([getErrorText()])} hint={canShowHint ? hintText : undefined} /> )} {computedCalendar && filteredLanguageOptions.length > 1 && isComplete && ( <InputField id="languageSelect" as={Select} label={c('Label').t`Language`} value={computedCalendar.Language} onChange={handleSelectLanguage} aria-describedby="label-languageSelect" data-testid="holidays-calendar-modal:language-select" > {filteredLanguageOptions.map((option) => ( <Option key={option.Language} value={option.Language} title={option.Language} /> ))} </InputField> )} <InputField id="colorSelect" as={ColorPicker} label={c('Label').t`Color`} color={color} onChange={(color: string) => setColor(color)} data-testid="holidays-calendar-modal:color-select" /> {isComplete && ( <InputField id="default-full-day-notification" as={Notifications} label={c('Label').t`Notifications`} hasType notifications={notifications} defaultNotification={getDefaultModel().defaultFullDayNotification} canAdd={notifications.length < MAX_DEFAULT_NOTIFICATIONS} onChange={(notifications: NotificationModel[]) => { setNotifications(notifications); }} /> )} </ModalContent> <ModalFooter> <> <Button onClick={rest.onClose}>{c('Action').t`Cancel`}</Button> <Button loading={loading} disabled={!computedCalendar} type="submit" color="norm" data-testid="holidays-calendar-modal:submit" > {isEdit ? c('Action').t`Save` : c('Action').t`Add`} </Button> </> </ModalFooter> </Modal> ); }; export default HolidaysCalendarModalWithDirectory;
5,921
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/holidaysCalendarModal
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/holidaysCalendarModal/tests/HolidaysCalendarModalWithDirectory.test.tsx
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'; import { mocked } from 'jest-mock'; import { useCalendarUserSettings, useNotifications } from '@proton/components/hooks'; import { ACCENT_COLORS_MAP } from '@proton/shared/lib/colors'; import { localeCode, setLocales } from '@proton/shared/lib/i18n'; import { HolidaysDirectoryCalendar, VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import { generateHolidaysCalendars } from '@proton/testing/lib/builders'; import { mockNotifications } from '@proton/testing/lib/mockNotifications'; import { CALENDAR_MODAL_TYPE } from '../../calendarModal'; import HolidaysCalendarModalWithDirectory from '../HolidaysCalendarModalWithDirectory'; jest.mock('@proton/components/hooks/useAddresses', () => ({ __esModule: true, default: jest.fn(() => []), useGetAddresses: jest.fn(), })); jest.mock('@proton/components/hooks/useGetCalendarBootstrap', () => ({ __esModule: true, default: jest.fn(() => () => Promise.resolve({ CalendarSettings: { DefaultFullDayNotifications: [] } })), useReadCalendarBootstrap: jest.fn(), })); jest.mock('@proton/components/hooks/useEventManager', () => () => ({})); jest.mock('@proton/components/containers/eventManager/calendar/ModelEventManagerProvider', () => ({ useCalendarModelEventManager: jest.fn(() => ({})), })); jest.mock('@proton/components/hooks/useGetAddressKeys', () => () => ({})); jest.mock('@proton/components/hooks/useNotifications'); jest.mock('@proton/components/hooks/useCalendarUserSettings', () => ({ ...jest.requireActual('@proton/components/hooks/useCalendarUserSettings'), useCalendarUserSettings: jest.fn(), })); const mockedColor = '#273EB2'; jest.mock('@proton/shared/lib/colors', () => ({ ...jest.requireActual('@proton/shared/lib/colors'), getRandomAccentColor: jest.fn(() => mockedColor), // return cobalt })); // Holidays calendars mocks const frCalendar = { CalendarID: 'calendarID1', Country: 'France', CountryCode: 'fr', Hidden: false, LanguageCode: 'fr', Language: 'Français', Timezones: ['Europe/Paris'], Passphrase: 'dummyPassphrase', SessionKey: { Key: 'dummyKey', Algorithm: 'dummyAlgorithm', }, }; const chEnCalendar = { CalendarID: 'calendarID2', Country: 'Switzerland', CountryCode: 'ch', Hidden: false, LanguageCode: 'en', Language: 'English', Timezones: ['Europe/Zurich'], Passphrase: 'dummyPassphrase', SessionKey: { Key: 'dummyKey', Algorithm: 'dummyAlgorithm', }, }; const chDeCalendar = { CalendarID: 'calendarID3', Country: 'Switzerland', CountryCode: 'ch', Hidden: false, LanguageCode: 'de', Language: 'Deutsch', Timezones: ['Europe/Zurich'], Passphrase: 'dummyPassphrase', SessionKey: { Key: 'dummyKey', Algorithm: 'dummyAlgorithm', }, }; const beFrCalendar = { CalendarID: 'calendarID4', Country: 'Belgium', CountryCode: 'be', Hidden: false, LanguageCode: 'fr', Language: 'Français', Timezones: ['Europe/Brussels'], Passphrase: 'dummyPassphrase', SessionKey: { Key: 'dummyKey', Algorithm: 'dummyAlgorithm', }, }; const beNlCalendar = { CalendarID: 'calendarID5', Country: 'Belgium', CountryCode: 'be', Hidden: false, LanguageCode: 'nl', Language: 'Dutch', Timezones: ['Europe/Brussels'], Passphrase: 'dummyPassphrase', SessionKey: { Key: 'dummyKey', Algorithm: 'dummyAlgorithm', }, }; const nlCalendar = { CalendarID: 'calendarID6', Country: 'Netherlands', CountryCode: 'nl', Hidden: false, LanguageCode: 'nl', Language: 'Dutch', Timezones: ['Europe/Brussels'], Passphrase: 'dummyPassphrase', SessionKey: { Key: 'dummyKey', Algorithm: 'dummyAlgorithm', }, }; const esCalendar = { CalendarID: 'calendarID7', Country: 'Spain', CountryCode: 'es', Hidden: false, LanguageCode: 'es', Language: 'Español', Timezones: ['Europe/Madrid'], Passphrase: 'dummyPassphrase', SessionKey: { Key: 'dummyKey', Algorithm: 'dummyAlgorithm', }, }; const esBaCalendar = { CalendarID: 'calendarID8', Country: 'Spain', CountryCode: 'es', Hidden: false, LanguageCode: 'eu', Language: 'Euskera', Timezones: ['Europe/Madrid'], Passphrase: 'dummyPassphrase', SessionKey: { Key: 'dummyKey', Algorithm: 'dummyAlgorithm', }, }; const esCaCalendar = { CalendarID: 'calendarID9', Country: 'Spain', CountryCode: 'es', Hidden: false, LanguageCode: 'ca', Language: 'Català', Timezones: ['Europe/Madrid'], Passphrase: 'dummyPassphrase', SessionKey: { Key: 'dummyKey', Algorithm: 'dummyAlgorithm', }, }; const esGlCalendar = { CalendarID: 'calendarID10', Country: 'Spain', CountryCode: 'es', Hidden: false, LanguageCode: 'gl', Language: 'Galego', Timezones: ['Europe/Madrid'], Passphrase: 'dummyPassphrase', SessionKey: { Key: 'dummyKey', Algorithm: 'dummyAlgorithm', }, }; const itItCalendar = { CalendarID: 'calendarID11', Country: 'Italy', CountryCode: 'it', Hidden: true, LanguageCode: 'it', Language: 'Italiano', Timezones: ['Europe/Rome'], Passphrase: 'dummyPassphrase', SessionKey: { Key: 'dummyKey', Algorithm: 'dummyAlgorithm', }, }; const directory: HolidaysDirectoryCalendar[] = [ frCalendar, chEnCalendar, chDeCalendar, beNlCalendar, beFrCalendar, nlCalendar, esCalendar, esBaCalendar, esCaCalendar, esGlCalendar, itItCalendar, ]; const holidaysCalendars: VisualCalendar[] = generateHolidaysCalendars(2, [ { id: frCalendar.CalendarID, name: 'Holidays in France', color: ACCENT_COLORS_MAP.cerise.color }, { id: chEnCalendar.CalendarID, name: 'Holidays in Switzerland', color: ACCENT_COLORS_MAP.carrot.color }, ]); describe('HolidaysCalendarModal - Subscribe to a holidays calendar', () => { const mockedUseNotifications = mocked(useNotifications); beforeEach(async () => { mockedUseNotifications.mockImplementation(() => mockNotifications); }); afterEach(async () => { setLocales({ localeCode: 'en_US', languageCode: 'en' }); }); const setup = ({ inputCalendar, holidaysCalendars = [], type = CALENDAR_MODAL_TYPE.COMPLETE, }: { inputCalendar?: VisualCalendar; holidaysCalendars?: VisualCalendar[]; type?: CALENDAR_MODAL_TYPE; }) => { render( <HolidaysCalendarModalWithDirectory calendar={inputCalendar} directory={directory} holidaysCalendars={holidaysCalendars} open type={type} /> ); }; describe('Add a holidays calendar', () => { describe('List of calendars', () => { it('should only offer non-hidden calendars', () => { // @ts-ignore useCalendarUserSettings.mockReturnValue([{ PrimaryTimezone: 'Something else' }, false]); setup({}); const countrySelect = screen.getByText('Please select a country'); fireEvent.click(countrySelect); // expected countries expect(screen.getByText('France')).toBeInTheDocument(); expect(screen.getByText('Switzerland')).toBeInTheDocument(); expect(screen.getByText('Belgium')).toBeInTheDocument(); expect(screen.getByText('Netherlands')).toBeInTheDocument(); expect(screen.getByText('Spain')).toBeInTheDocument(); // hidden countries expect(screen.queryByText('Italy')).not.toBeInTheDocument(); }); }); describe('Pre-selected fields', () => { it('should pre-select the suggested holidays calendar based on time zone', async () => { // Mock user's time zone to Paris // @ts-ignore useCalendarUserSettings.mockReturnValue([{ PrimaryTimezone: 'Europe/Paris' }, false]); setup({}); // Modal title and subtitle are displayed screen.getByText('Add public holidays'); screen.getByText("Get a country's official public holidays calendar."); // Country is pre-selected screen.getByText('France'); // Hint is displayed before country select focus screen.getByText('Based on your time zone'); const countrySelect = screen.getByTestId('country-select'); fireEvent.click(countrySelect); // Hint is displayed within country select within(screen.getByTestId('select-list')).getByText('Based on your time zone'); // Preselected option is focused const preselectedOption = await waitFor(() => screen.getByTestId('preselected-country-select-option')); expect(preselectedOption).toHaveTextContent('France'); expect(preselectedOption).toHaveClass('dropdown-item--is-selected'); // Language is NOT shown because there's only one available for this country const languageInput = screen.queryByTestId('holidays-calendar-modal:language-select'); expect(languageInput).toBeNull(); // Random color has been selected (we mock the result to be cobalt) screen.getByText('cobalt'); // No notification set const notificationInput = screen.queryByTestId('notification-time-input'); expect(notificationInput).toBeNull(); // Add notification button is visible screen.getByTestId('add-notification'); }); it('should pre-select the suggested holidays calendar based on time zone and user language', async () => { // Mock user's time zone to Zurich // @ts-ignore useCalendarUserSettings.mockReturnValue([{ PrimaryTimezone: 'Europe/Zurich' }, false]); setup({}); // Modal title and subtitle are displayed screen.getByText('Add public holidays'); screen.getByText("Get a country's official public holidays calendar."); // Country is pre-selected screen.getByText('Switzerland'); // Hint is displayed before country select focus screen.getByText('Based on your time zone'); const countrySelect = screen.getByTestId('country-select'); fireEvent.click(countrySelect); // Hint is displayed within country select within(screen.getByTestId('select-list')).getByText('Based on your time zone'); // Preselected option is focused const preselectedOption = await waitFor(() => screen.getByTestId('preselected-country-select-option')); expect(preselectedOption).toHaveTextContent('Switzerland'); expect(preselectedOption).toHaveClass('dropdown-item--is-selected'); // Language is shown because there's several languages for this country screen.getByText('English'); // Random color has been selected (we mock the result to be cobalt) screen.getByText('cobalt'); // No notification set const notificationInput = screen.queryByTestId('notification-time-input'); expect(notificationInput).toBeNull(); // Add notification button is visible screen.getByTestId('add-notification'); }); it('should pre-select the suggested holidays calendar based on time zone and first language', async () => { setLocales({ localeCode, languageCode: 'something' }); // Mock user's time zone to Spain // @ts-ignore useCalendarUserSettings.mockReturnValue([{ PrimaryTimezone: 'Europe/Madrid' }, false]); setup({}); // Modal title and subtitle are displayed screen.getByText('Add public holidays'); screen.getByText("Get a country's official public holidays calendar."); // Country is pre-selected screen.getByText('Spain'); // Hint is displayed before country select focus screen.getByText('Based on your time zone'); const countrySelect = screen.getByTestId('country-select'); fireEvent.click(countrySelect); // Hint is displayed within country select within(screen.getByTestId('select-list')).getByText('Based on your time zone'); // Preselected option is focused const preselectedOption = await waitFor(() => screen.getByTestId('preselected-country-select-option')); expect(preselectedOption).toHaveTextContent('Spain'); expect(preselectedOption).toHaveClass('dropdown-item--is-selected'); // Language is shown because there's several languages for this country screen.getByText('Català'); // Random color has been selected (we mock the result to be cobalt) screen.getByText('cobalt'); // No notification set const notificationInput = screen.queryByTestId('notification-time-input'); expect(notificationInput).toBeNull(); // Add notification button is visible screen.getByTestId('add-notification'); }); it('should not pre-select a suggested holidays calendar when no corresponding time zone is found', () => { // Mock user's time zone to something which does not exist in holidays calendars list we get // @ts-ignore useCalendarUserSettings.mockReturnValue([{ PrimaryTimezone: 'Something else' }, false]); setup({}); // Modal title and subtitle are displayed screen.getByText('Add public holidays'); screen.getByText("Get a country's official public holidays calendar."); // Country is NOT pre-selected screen.getByText('Please select a country'); // Hint is NOT displayed const hint = screen.queryByText('Based on your time zone'); expect(hint).toBeNull(); // Language is NOT shown because no default country is found const languageInput = screen.queryByTestId('holidays-calendar-modal:language-select'); expect(languageInput).toBeNull(); // Random color has been selected (we mock the result to be cobalt) screen.getByText('cobalt'); // No notification set const notificationInput = screen.queryByTestId('notification-time-input'); expect(notificationInput).toBeNull(); // Add notification button is visible screen.getByTestId('add-notification'); }); it('should not pre-select a suggested holidays calendar that is not visible', () => { // @ts-ignore useCalendarUserSettings.mockReturnValue([{ PrimaryTimezone: 'Europe/Rome' }, false]); setLocales({ localeCode: 'it_IT', languageCode: 'it' }); setup({}); // Modal title and subtitle are displayed screen.getByText('Add public holidays'); screen.getByText("Get a country's official public holidays calendar."); // Italy is NOT pre-selected and NOT offered screen.getByText('Please select a country'); }); }); describe('Already added holidays calendar', () => { it('should not pre-select the suggested calendar if the user already added it', () => { // Mock user's time zone to Paris // @ts-ignore useCalendarUserSettings.mockReturnValue([{ PrimaryTimezone: 'Europe/Paris' }, false]); setup({ holidaysCalendars }); // Modal title and subtitle are displayed screen.getByText('Add public holidays'); screen.getByText("Get a country's official public holidays calendar."); // Country is NOT pre-selected screen.getByText('Please select a country'); // Hint is NOT displayed const hint = screen.queryByText('Based on your time zone'); expect(hint).toBeNull(); // Language is NOT shown because there's only one available for this country const languageInput = screen.queryByTestId('holidays-calendar-modal:language-select'); expect(languageInput).toBeNull(); // Random color has been selected (we mock the result to be cobalt) screen.getByText('cobalt'); // No notification set const notificationInput = screen.queryByTestId('notification-time-input'); expect(notificationInput).toBeNull(); // Add notification button is visible screen.getByTestId('add-notification'); }); it('should display an error message when selecting a country of an already added holidays calendar', () => { // Mock user's time zone to Paris // @ts-ignore useCalendarUserSettings.mockReturnValue([{ PrimaryTimezone: 'Europe/Paris' }, false]); setup({ holidaysCalendars }); // Modal title and subtitle are displayed screen.getByText('Add public holidays'); screen.getByText("Get a country's official public holidays calendar."); // Country is NOT pre-selected const countryInput = screen.getByText('Please select a country'); // Open dropdown fireEvent.click(countryInput); // Select France const franceDropdownOption = screen.getByText('France'); fireEvent.click(franceDropdownOption); // Click "Add" const submitButton = screen.getByText('Add'); fireEvent.click(submitButton); // An error is displayed under the country input screen.getByText('You already added this holidays calendar'); }); }); }); describe('Edit a holidays calendar', () => { it('should pre-select all fields in modal', async () => { // Mock user's time zone to Paris // @ts-ignore useCalendarUserSettings.mockReturnValue([{ PrimaryTimezone: 'Europe/Paris' }, false]); setup({ holidaysCalendars, inputCalendar: holidaysCalendars[0], type: CALENDAR_MODAL_TYPE.COMPLETE, }); await waitFor(() => { expect(screen.getByText('Edit calendar')); }); // Modal title is displayed screen.getByText('Edit calendar'); // No modal subtitle is displayed const subtitle = screen.queryByText("Get a country's official public holidays calendar."); expect(subtitle).toBeNull(); // Edited country is selected screen.getByText('France'); // Hint should not be displayed on edition const hint = screen.queryByText('Based on your time zone'); expect(hint).toBeNull(); // Language is NOT shown because there's only one available for this country const languageInput = screen.queryByTestId('holidays-calendar-modal:language-select'); expect(languageInput).toBeNull(); // Random color has been selected (we mock the result to be cobalt) screen.getByText('cerise'); // Add notification button is NOT visible in edit mode const notificationButton = screen.queryByTestId('add-notification'); expect(notificationButton).toBeInTheDocument(); }); it('should display a message when user wants to change country to an already added holidays calendar', async () => { // Mock user's time zone to Zurich // @ts-ignore useCalendarUserSettings.mockReturnValue([{ PrimaryTimezone: 'Europe/Zurich' }, false]); setup({ holidaysCalendars, inputCalendar: holidaysCalendars[1], type: CALENDAR_MODAL_TYPE.COMPLETE, }); await waitFor(() => { expect(screen.getByText('Edit calendar')); }); // No modal subtitle is displayed const subtitle = screen.queryByText("Get a country's official public holidays calendar."); expect(subtitle).toBeNull(); // Country is pre-selected const countryInput = screen.getByText('Switzerland'); // Random color has been selected (we mock the result to be cobalt) screen.getByText('carrot'); // Add notification button is NOT visible in edit mode const notificationButton = screen.queryByTestId('add-notification'); expect(notificationButton).toBeInTheDocument(); // Open dropdown fireEvent.click(countryInput); // Select France const frDropdownOption = screen.getByText('France'); fireEvent.click(frDropdownOption); // An error is displayed under the country input after trying to save const submitButton = screen.getByText('Save'); fireEvent.click(submitButton); screen.getByText('You already added this holidays calendar'); }); it('should allow to edit a hidden calendar', async () => { // Mock user's time zone to Paris // @ts-ignore useCalendarUserSettings.mockReturnValue([{ PrimaryTimezone: 'Europe/Paris' }, false]); const holidaysCalendars = generateHolidaysCalendars(1, [ { id: itItCalendar.CalendarID, name: 'Giorni festivi e ricorrenze in Italia', color: ACCENT_COLORS_MAP.cerise.color, }, ]); setup({ holidaysCalendars, inputCalendar: holidaysCalendars[0], type: CALENDAR_MODAL_TYPE.COMPLETE, }); await waitFor(() => { expect(screen.getByText('Edit calendar')); }); // No modal subtitle is displayed const subtitle = screen.queryByText("Get a country's official public holidays calendar."); expect(subtitle).toBeNull(); // Edited country is selected screen.getByText('Italy'); }); }); });
5,922
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/hooks/index.ts
export { default as useAddEvents } from './useAddEvents'; export { default as useAddAttendees } from './useAddAttendees'; export { default as useHolidaysDirectory } from './useHolidaysDirectory';
5,923
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/hooks/useAddAttendees.tsx
import { useCallback } from 'react'; import { serverTime } from '@proton/crypto'; import { syncMultipleEvents as syncMultipleEventsRoute } from '@proton/shared/lib/api/calendars'; import { getHasDefaultNotifications, getHasSharedEventContent } from '@proton/shared/lib/calendar/apiModels'; import { getAttendeeEmail, withPmAttendees } from '@proton/shared/lib/calendar/attendees'; import { DEFAULT_ATTENDEE_PERMISSIONS, ICAL_METHOD, MAX_ATTENDEES } from '@proton/shared/lib/calendar/constants'; import { getBase64SharedSessionKey, getCreationKeys } from '@proton/shared/lib/calendar/crypto/keys/helpers'; import { getInviteLocale } from '@proton/shared/lib/calendar/getSettings'; import { ADD_EVENT_ERROR_TYPE, AddAttendeeError } from '@proton/shared/lib/calendar/mailIntegration/AddAttendeeError'; import { createInviteIcs, generateEmailBody, generateEmailSubject, generateVtimezonesComponents, getIcsMessageWithPreferences, } from '@proton/shared/lib/calendar/mailIntegration/invite'; import { createCalendarEvent } from '@proton/shared/lib/calendar/serialize'; import { prodId } from '@proton/shared/lib/calendar/vcalConfig'; import { withDtstamp } from '@proton/shared/lib/calendar/veventHelper'; import { omit } from '@proton/shared/lib/helpers/object'; import { SimpleMap } from '@proton/shared/lib/interfaces'; import { CalendarEvent, SyncMultipleApiResponse, VcalAttendeeProperty, VcalVeventComponent, } from '@proton/shared/lib/interfaces/calendar'; import { ContactEmail } from '@proton/shared/lib/interfaces/contacts'; import { SendPreferences } from '@proton/shared/lib/interfaces/mail/crypto'; import getSendPreferences from '@proton/shared/lib/mail/send/getSendPreferences'; import { useAddresses, useApi, useGetAddressKeys, useGetCalendarInfo, useGetCalendarUserSettings, useGetEncryptionPreferences, useGetMailSettings, useMailSettings, useRelocalizeText, } from '../../../hooks'; import { useGetCanonicalEmailsMap } from '../../../hooks/useGetCanonicalEmailsMap'; import { useGetVtimezonesMap } from '../../../hooks/useGetVtimezonesMap'; import useSendIcs from '../../../hooks/useSendIcs'; const useAddAttendees = () => { const [mailSettings] = useMailSettings(); const api = useApi(); const [addresses] = useAddresses(); const getAddressKeys = useGetAddressKeys(); const getMailSettings = useGetMailSettings(); const getCalendarUserSettings = useGetCalendarUserSettings(); const getEncryptionPreferences = useGetEncryptionPreferences(); const getCalendarInfo = useGetCalendarInfo(); const sendIcs = useSendIcs(); const relocalizeText = useRelocalizeText(); const getVTimezonesMap = useGetVtimezonesMap(); const getCanonicalEmailsMap = useGetCanonicalEmailsMap(); return useCallback( async ({ eventComponent, calendarEvent, addedAttendees, sendInvitation, contactEmailsMap, }: { eventComponent: VcalVeventComponent; calendarEvent: CalendarEvent; addedAttendees: VcalAttendeeProperty[]; sendInvitation: boolean; contactEmailsMap?: SimpleMap<ContactEmail>; }) => { const maxAttendees = mailSettings?.RecipientLimit || MAX_ATTENDEES; if ((eventComponent.attendee?.length || 0) > maxAttendees) { throw new AddAttendeeError(ADD_EVENT_ERROR_TYPE.TOO_MANY_PARTICIPANTS, undefined, maxAttendees); } const { addressID, memberID, calendarKeys, addressKeys } = await getCalendarInfo(calendarEvent.CalendarID); const selfAddress = addresses.find(({ ID }) => ID === addressID); if (!selfAddress) { throw new Error("Cannot add attendees to events you don't organize"); } const formattedAddedAttendees = addedAttendees.map((attendee) => ({ attendee, email: getAttendeeEmail(attendee), cn: attendee.parameters?.cn, })); const pmVevent = await withPmAttendees(eventComponent, getCanonicalEmailsMap); if (sendInvitation) { // get send preferences for the added attendee email const { Sign } = await getMailSettings(); const sendPreferencesMap: SimpleMap<SendPreferences> = {}; await Promise.all( formattedAddedAttendees.map(async ({ email }) => { const encryptionPreferences = await getEncryptionPreferences({ email, lifetime: 0, contactEmailsMap, }); const sendPreferences = getSendPreferences( encryptionPreferences, getIcsMessageWithPreferences(Sign) ); if (sendPreferences.error) { // abort operation if we cannot send the email throw sendPreferences.error; } }) ); // create ICS to send const currentTimestamp = +serverTime(); const veventWithDtstamp = withDtstamp(omit(pmVevent, ['dtstamp']), currentTimestamp); const vtimezones = await generateVtimezonesComponents(pmVevent, getVTimezonesMap); const sharedSessionKey = await getBase64SharedSessionKey({ calendarEvent, calendarKeys, getAddressKeys, }); if (!sharedSessionKey) { throw new Error('Failed to retrieve shared session key'); } const inviteVevent = { ...veventWithDtstamp, 'x-pm-shared-event-id': { value: calendarEvent.SharedEventID }, 'x-pm-session-key': { value: sharedSessionKey }, }; const inviteIcs = createInviteIcs({ method: ICAL_METHOD.REQUEST, prodId, vevent: inviteVevent, vtimezones, keepDtstamp: true, }); const inviteLocale = getInviteLocale(await getCalendarUserSettings()); const params = { method: ICAL_METHOD.REQUEST, vevent: inviteVevent, isCreateEvent: true }; // send email with ICS attached await sendIcs({ method: ICAL_METHOD.REQUEST, ics: inviteIcs, addressID: selfAddress.ID, from: { Address: selfAddress.Email, Name: selfAddress.DisplayName || selfAddress.Email }, to: formattedAddedAttendees.map(({ email, cn }) => ({ Address: email, Name: cn || email })), subject: await relocalizeText({ getLocalizedText: () => generateEmailSubject(params), newLocaleCode: inviteLocale, relocalizeDateFormat: true, }), plainTextBody: await relocalizeText({ getLocalizedText: () => generateEmailBody(params), newLocaleCode: inviteLocale, relocalizeDateFormat: true, }), sendPreferencesMap, contactEmailsMap, }); } const data = await createCalendarEvent({ eventComponent: pmVevent, isCreateEvent: false, isSwitchCalendar: false, hasDefaultNotifications: getHasDefaultNotifications(calendarEvent), ...(await getCreationKeys({ calendarEvent, newAddressKeys: addressKeys, newCalendarKeys: calendarKeys, })), }); if (!getHasSharedEventContent(data)) { throw new Error('Missing shared data'); } const result = await api<SyncMultipleApiResponse>({ ...syncMultipleEventsRoute(calendarEvent.CalendarID, { MemberID: memberID, Events: [ { ID: calendarEvent.ID, Event: { Permissions: DEFAULT_ATTENDEE_PERMISSIONS, IsOrganizer: 1, ...data, }, }, ], }), silence: true, }); return result.Responses[0]; }, [] ); }; export default useAddAttendees;
5,924
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/hooks/useAddEvents.tsx
import { useCallback } from 'react'; import { processInBatches } from '@proton/shared/lib/calendar/import/encryptAndSubmit'; import { VcalVeventComponent } from '@proton/shared/lib/interfaces/calendar'; import { useApi, useGetCalendarInfo } from '../../../hooks'; const useAddEvents = () => { const api = useApi(); const getCalendarInfo = useGetCalendarInfo(); return useCallback( async ({ calendarID, events, }: { calendarID: string; events: { eventComponent: VcalVeventComponent; hasDefaultNotifications: boolean }[]; }) => { const { addressKeys, memberID, calendarKeys } = await getCalendarInfo(calendarID); return processInBatches({ events, api, memberID, addressKeys, calendarID, calendarKeys, }); }, [] ); }; export default useAddEvents;
5,925
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/hooks/useGetCalendarActions.ts
import { Dispatch, SetStateAction } from 'react'; import { c } from 'ttag'; import { CALENDAR_MODAL_TYPE } from '@proton/components/containers/calendar/calendarModal'; import { createCalendar, updateCalendarSettings, updateCalendarUserSettings } from '@proton/shared/lib/api/calendars'; import { getOwnedPersonalCalendars, getProbablyActiveCalendars, getVisualCalendar, updateCalendar, } from '@proton/shared/lib/calendar/calendar'; import { setupCalendarKey } from '@proton/shared/lib/calendar/crypto/keys/setupCalendarKeys'; import { CalendarSettings, CalendarWithOwnMembers, VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import { CalendarCreateData } from '@proton/shared/lib/interfaces/calendar/Api'; import { getPrimaryKey } from '@proton/shared/lib/keys'; import { useApi, useEventManager, useGetAddressKeys, useGetAddresses, useNotifications, useReadCalendarBootstrap, } from '../../../hooks'; import { useCalendarModelEventManager } from '../../eventManager/calendar'; interface Props { type?: CALENDAR_MODAL_TYPE; setCalendar: Dispatch<SetStateAction<VisualCalendar | undefined>>; setError: Dispatch<SetStateAction<boolean>>; defaultCalendarID?: string | null; onClose?: () => void; onCreateCalendar?: (id: string) => void; onEditCalendar?: () => void; calendars?: VisualCalendar[]; isSubscribedCalendar?: boolean; } const useGetCalendarActions = ({ type = CALENDAR_MODAL_TYPE.COMPLETE, setCalendar, setError, defaultCalendarID, onClose, onCreateCalendar, onEditCalendar, calendars, isSubscribedCalendar = false, }: Props) => { const api = useApi(); const getAddresses = useGetAddresses(); const { call } = useEventManager(); const { call: calendarCall } = useCalendarModelEventManager(); const getAddressKeys = useGetAddressKeys(); const readCalendarBootstrap = useReadCalendarBootstrap(); const { createNotification } = useNotifications(); const handleCreateCalendar = async ( addressID: string, calendarPayload: CalendarCreateData, calendarSettingsPayload: Partial<CalendarSettings> ) => { const addressKeys = await getAddressKeys(addressID); const { privateKey: primaryAddressKey } = getPrimaryKey(addressKeys) || {}; if (!primaryAddressKey) { createNotification({ text: c('Error').t`Primary address key is not decrypted`, type: 'error' }); setError(true); throw new Error('Missing primary key'); } const { Calendar, Calendar: { ID: newCalendarID }, } = await api<{ Calendar: CalendarWithOwnMembers }>( createCalendar({ ...calendarPayload, AddressID: addressID, }) ); const visualCalendar = getVisualCalendar(Calendar); await setupCalendarKey({ api, calendarID: newCalendarID, addressID, getAddressKeys, }).catch((e: Error) => { // Hard failure if the keys fail to setup. Force the user to reload. setError(true); throw e; }); onCreateCalendar?.(newCalendarID); // Set the calendar in case one of the following calls fails so that it ends up in the update function after this. setCalendar(visualCalendar); if (!isSubscribedCalendar) { await Promise.all([ api(updateCalendarSettings(newCalendarID, calendarSettingsPayload)), (() => { if (defaultCalendarID) { return; } const ownedActiveCalendars = getProbablyActiveCalendars(getOwnedPersonalCalendars(calendars)); const newDefaultCalendarID = ownedActiveCalendars?.length ? ownedActiveCalendars[0].ID : newCalendarID; return api(updateCalendarUserSettings({ DefaultCalendarID: newDefaultCalendarID })); })(), ]).catch(() => { createNotification({ type: 'warning', text: c('Settings update growler warning').t`Failed to update settings`, }); }); } await call(); onClose?.(); createNotification({ text: isSubscribedCalendar ? c('Success').t`Calendar added. It might take a few minutes to sync.` : c('Success').t`Calendar created`, }); }; const handleUpdateCalendar = async ( calendar: VisualCalendar, calendarPayload: CalendarCreateData, calendarSettingsPayload: Required< Pick< CalendarSettings, 'DefaultEventDuration' | 'DefaultPartDayNotifications' | 'DefaultFullDayNotifications' > > ) => { const calendarID = calendar.ID; await updateCalendar( calendar, calendarPayload, calendarSettingsPayload, readCalendarBootstrap, getAddresses, api ); await call(); await calendarCall([calendarID]); onEditCalendar?.(); onClose?.(); createNotification({ text: type === CALENDAR_MODAL_TYPE.COMPLETE ? c('Success').t`Calendar updated` : c('Success').t`Calendar information updated`, }); }; return { handleCreateCalendar, handleUpdateCalendar }; }; export default useGetCalendarActions;
5,926
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/hooks/useGetCalendarSetup.ts
import { Dispatch, SetStateAction, useEffect, useState } from 'react'; import { c } from 'ttag'; import { useLoading } from '@proton/hooks'; import { getActiveAddresses } from '@proton/shared/lib/helpers/address'; import { CalendarViewModelFull, SubscribedCalendar, VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import { useGetAddresses, useGetCalendarBootstrap, useNotifications } from '../../../hooks'; import { getCalendarModel } from '../calendarModal/calendarModalState'; interface Props { calendar?: VisualCalendar | SubscribedCalendar; setModel: Dispatch<SetStateAction<CalendarViewModelFull>>; } const useGetCalendarSetup = ({ calendar: initialCalendar, setModel }: Props) => { const getAddresses = useGetAddresses(); const getCalendarBootstrap = useGetCalendarBootstrap(); const [loading, withLoading] = useLoading(true); const { createNotification } = useNotifications(); const [error, setError] = useState(false); useEffect(() => { const initializeEmptyCalendar = async () => { const activeAdresses = getActiveAddresses(await getAddresses()); if (!activeAdresses.length) { setError(true); return createNotification({ text: c('Error').t`No valid address found`, type: 'error' }); } setModel((prev) => ({ ...prev, addressID: activeAdresses[0].ID, addressOptions: activeAdresses.map(({ ID, Email = '' }) => ({ value: ID, text: Email })), })); }; const initializeCalendar = async () => { if (!initialCalendar) { throw new Error('No initial calendar'); } const [{ Members, CalendarSettings }, Addresses] = await Promise.all([ getCalendarBootstrap(initialCalendar.ID), getAddresses(), ]); const [{ Email: memberEmail } = { Email: '' }] = Members; const { ID: AddressID } = Addresses.find(({ Email }) => memberEmail === Email) || {}; if (!AddressID) { setError(true); return createNotification({ text: c('Error').t`No valid address found`, type: 'error' }); } setModel((prev) => ({ ...prev, ...getCalendarModel({ Calendar: initialCalendar, CalendarSettings, Addresses, AddressID, }), })); }; const promise = initialCalendar ? initializeCalendar() : initializeEmptyCalendar(); void withLoading( promise.catch(() => { setError(true); }) ); }, []); return { loading, error }; }; export default useGetCalendarSetup;
5,927
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/hooks/useHolidaysDirectory.ts
import { useCallback } from 'react'; import { useApi, useCache, useCachedModelResult } from '@proton/components/hooks'; import { getPromiseValue } from '@proton/components/hooks/useCachedModelResult'; import { Api } from '@proton/shared/lib/interfaces'; import { HolidaysDirectoryCalendar } from '@proton/shared/lib/interfaces/calendar'; import { GetHolidaysDirectory } from '@proton/shared/lib/interfaces/hooks/GetHolidaysDirectory'; import { HolidaysCalendarsModel } from '@proton/shared/lib/models'; export const useGetHolidaysDirectory = (inputApi?: Api): GetHolidaysDirectory => { const normalApi = useApi(); const api = inputApi || normalApi; const cache = useCache(); return useCallback(() => { return getPromiseValue(cache, HolidaysCalendarsModel.key, () => HolidaysCalendarsModel.get(api)); }, [cache, api]); }; const useHolidaysDirectory = (api?: Api): [HolidaysDirectoryCalendar[] | undefined, boolean, any] => { const cache = useCache(); const miss = useGetHolidaysDirectory(api); return useCachedModelResult(cache, HolidaysCalendarsModel.key, miss); }; export default useHolidaysDirectory;
5,928
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/importModal/AttachingModalContent.tsx
import { ChangeEvent } from 'react'; import { c } from 'ttag'; import { IMPORT_CALENDAR_FAQ_URL, MAX_IMPORT_EVENTS_STRING, MAX_IMPORT_FILE_SIZE_STRING, } from '@proton/shared/lib/calendar/constants'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import { ImportCalendarModel } from '@proton/shared/lib/interfaces/calendar/Import'; import { Alert, AttachedFile, Dropzone, Field, FileInput, Label, LearnMore, Row } from '../../../components'; import CalendarSelect from '../../../components/calendarSelect/CalendarSelect'; interface Props { model: ImportCalendarModel; calendars: VisualCalendar[]; onSelectCalendar: (calendar: VisualCalendar) => void; onAttach: (event: ChangeEvent<HTMLInputElement>) => void; onClear: () => void; onDrop: (Files: File[]) => void; } const AttachingModalContent = ({ model, calendars, onSelectCalendar, onAttach, onClear, onDrop }: Props) => { const options = calendars.map(({ Name, ID, Color }) => ({ name: Name, id: ID, color: Color })); const handleChange = ({ value }: { value: string }) => { const calendar = calendars.find(({ ID }) => ID === value); if (calendar) { onSelectCalendar(calendar); } }; const alert = model.failure ? ( <Alert className="mb-4" type="error"> {model.failure?.message} </Alert> ) : ( <div className="mb-4"> {c('Description') .t`You can import events in iCal format (ICS file). The file should have a maximum size of ${MAX_IMPORT_FILE_SIZE_STRING} and have up to ${MAX_IMPORT_EVENTS_STRING} events. If your file is bigger, please split it into smaller files.`} <div> <LearnMore url={getKnowledgeBaseUrl(IMPORT_CALENDAR_FAQ_URL)} /> </div> </div> ); return ( <> {alert} <Dropzone onDrop={onDrop} size="small" shape="flashy"> <div className="flex flex-align-items-center flex-justify-center border p-4 rounded-xl mb-4"> {model.fileAttached ? ( <AttachedFile file={model.fileAttached} iconName="calendar-grid" clear={c('Action').t`Delete`} onClear={onClear} /> ) : ( <FileInput className="mx-auto" accept=".ics" id="import-calendar" onChange={onAttach}> {c('Action').t`Choose a file or drag it here`} </FileInput> )} </div> </Dropzone> {calendars.length > 1 && ( <Row> <Label style={{ '--label-width': 'auto' }} htmlFor="import-calendar-select"> {c('Label').t`Import to:`} </Label> <Field> <CalendarSelect id="import-calendar-select" calendarID={model.calendar.ID} options={options} onChange={handleChange} /> </Field> </Row> )} </> ); }; export default AttachingModalContent;
5,929
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/importModal/ErrorDetails.tsx
import { c } from 'ttag'; import { MAX_UID_CHARS_DISPLAY } from '@proton/shared/lib/calendar/constants'; import { ImportEventError } from '@proton/shared/lib/calendar/icsSurgery/ImportEventError'; import { truncateMore } from '@proton/shared/lib/helpers/string'; import { Bordered, Details, Summary } from '../../../components'; const getComponentText = (component: string) => { if (component === 'vevent') { return c('Error importing event').t`Event`; } if (component === 'vcalendar') { return c('Error importing event').t`Calendar`; } if (component === 'vtimezone') { return c('Error importing event').t`Time zone`; } if (component === 'vtodo') { return c('Error importing event').t`Element`; } if (component === 'vjournal') { return c('Error importing event').t`Element`; } if (component === 'vfreebusy') { return c('Error importing event').t`Element`; } if (component === '') { return c('Error importing event').t`Bad format. Component cannot be read.`; } return c('Error importing event').t`Unknown`; }; const getErrorIdentifierText = (error: ImportEventError) => { const shortUID = truncateMore({ string: error.componentId, charsToDisplay: MAX_UID_CHARS_DISPLAY, }); return `${getComponentText(error.component)} ${shortUID}`; }; const ErrorDetail = ({ error, ...rest }: { error: ImportEventError }) => { return ( <div {...rest}> <span>{`${getErrorIdentifierText(error)}: `}</span> <span className="color-danger">{error.message}</span> </div> ); }; interface Props { summary?: string; errors: ImportEventError[]; } const ErrorDetails = ({ errors, summary = c('Info on errors').t`Click for details` }: Props) => { if (!errors.length) { return null; } return ( <Details> <Summary>{summary}</Summary> <Bordered className="rounded"> {errors.map((error, i) => ( <ErrorDetail error={error} key={error.componentId + i.toString()} /> ))} </Bordered> </Details> ); }; export default ErrorDetails;
5,930
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/importModal/ImportInvitationModalContent.tsx
import { c, msgid } from 'ttag'; import { ICAL_METHODS_ATTENDEE } from '@proton/shared/lib/calendar/constants'; import { extractTotals } from '@proton/shared/lib/calendar/import/import'; import { BRAND_NAME, CALENDAR_APP_NAME } from '@proton/shared/lib/constants'; import { ImportCalendarModel } from '@proton/shared/lib/interfaces/calendar/Import'; import { AttachedFile } from '../../../components'; interface Props { model: ImportCalendarModel; } const ImportInvitationModalContent = ({ model }: Props) => { const { method, fileAttached } = model; const { totalToImport } = extractTotals(model); const isResponse = method && ICAL_METHODS_ATTENDEE.includes(method); return ( <> <div> {isResponse ? c('Import calendar; import invitation').ngettext( msgid`This file contains an invitation response:`, `This file contains invitation responses:`, totalToImport ) : c('Import calendar; import invitation').ngettext( msgid`This file contains an event invitation:`, `This file contains event invitations:`, totalToImport )} </div> {fileAttached && <AttachedFile file={fileAttached} iconName="calendar-grid" className="my-4" />} <div> {c('Import calendar; import invitation') .t`Imported invitations appear in ${CALENDAR_APP_NAME} as simple events without organizer and participant details. To get event updates and see participants, ask organizers to invite you using your ${BRAND_NAME} email address.`} </div> </> ); }; export default ImportInvitationModalContent;
5,931
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/importModal/ImportModal.tsx
import { ChangeEvent, useEffect, useState } from 'react'; import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms'; import { updateMember } from '@proton/shared/lib/api/calendars'; import { getProbablyActiveCalendars, getWritableCalendars } from '@proton/shared/lib/calendar/calendar'; import { ICAL_METHOD, IMPORT_ERROR_TYPE, MAX_IMPORT_FILE_SIZE } from '@proton/shared/lib/calendar/constants'; import { ImportFatalError } from '@proton/shared/lib/calendar/import/ImportFatalError'; import { ImportFileError } from '@proton/shared/lib/calendar/import/ImportFileError'; import { extractTotals, getSupportedEvents, parseIcs, splitErrors, splitHiddenErrors, } from '@proton/shared/lib/calendar/import/import'; import { getMemberAndAddress } from '@proton/shared/lib/calendar/members'; import { APPS } from '@proton/shared/lib/constants'; import { splitExtension } from '@proton/shared/lib/helpers/file'; import { IMPORT_STEPS, ImportCalendarModel, ImportedEvent, VisualCalendar, } from '@proton/shared/lib/interfaces/calendar'; import noop from '@proton/utils/noop'; import { BasicModal } from '../../../components'; import { useAddresses, useApi, useConfig, useEventManager, useGetCalendarUserSettings } from '../../../hooks'; import { useCalendarModelEventManager } from '../../eventManager/calendar'; import AttachingModalContent from './AttachingModalContent'; import ImportInvitationModalContent from './ImportInvitationModalContent'; import ImportSummaryModalContent from './ImportSummaryModalContent'; import ImportingModalContent from './ImportingModalContent'; import PartialImportModalContent from './PartialImportModalContent'; interface Props { initialCalendar: VisualCalendar; calendars: VisualCalendar[]; onClose?: () => void; onExit?: () => void; files?: File[]; isOpen?: boolean; } const getInitialState = (calendar: VisualCalendar): ImportCalendarModel => ({ step: IMPORT_STEPS.ATTACHING, calendar, eventsParsed: [], totalEncrypted: 0, totalImported: 0, visibleErrors: [], hiddenErrors: [], loading: false, }); const ImportModal = ({ calendars, initialCalendar, files, isOpen = false, onClose, onExit }: Props) => { const [addresses] = useAddresses(); const api = useApi(); const { APP_NAME } = useConfig(); const { call: coreCall } = useEventManager(); const getCalendarUserSettings = useGetCalendarUserSettings(); const { call: calendarCall } = useCalendarModelEventManager(); const [model, setModel] = useState<ImportCalendarModel>(getInitialState(initialCalendar)); const isCalendar = APP_NAME === APPS.PROTONCALENDAR; const activeWritableCalendars = getWritableCalendars(getProbablyActiveCalendars(calendars)); const handleFiles = (files: File[]) => { const [file] = files; const filename = file.name; const [, extension] = splitExtension(filename); const fileAttached = extension.toLowerCase() === 'ics' ? file : null; if (!fileAttached) { throw new ImportFileError(IMPORT_ERROR_TYPE.NO_ICS_FILE, filename); } if (fileAttached.size > MAX_IMPORT_FILE_SIZE) { throw new ImportFileError(IMPORT_ERROR_TYPE.FILE_TOO_BIG, filename); } setModel({ ...model, step: IMPORT_STEPS.ATTACHED, fileAttached, failure: undefined }); }; const onAddFiles = (files: File[]) => { try { if (!files) { throw new ImportFileError(IMPORT_ERROR_TYPE.NO_FILE_SELECTED); } handleFiles(files); } catch (e: any) { setModel({ ...model, failure: e }); } }; const { content, close = <Button onClick={onClose}>{c('Action').t`Cancel`}</Button>, submit, title = c('Title').t`Import events`, ...modalProps } = (() => { if (model.step <= IMPORT_STEPS.ATTACHED) { const handleClear = () => { setModel(getInitialState(model.calendar)); }; const handleAttach = ({ target }: ChangeEvent<HTMLInputElement>) => { try { if (!target.files) { throw new ImportFileError(IMPORT_ERROR_TYPE.NO_FILE_SELECTED); } handleFiles([...target.files]); } catch (e: any) { setModel({ ...model, failure: e }); } }; const handleSelectCalendar = (calendar: VisualCalendar) => { setModel({ ...model, calendar }); }; const handleSubmit = async () => { const { fileAttached } = model; if (!fileAttached) { throw new Error('No file'); } try { setModel({ ...model, loading: true }); const [{ PrimaryTimezone: primaryTimezone }, { components, calscale, xWrTimezone, method }] = await Promise.all([getCalendarUserSettings(), parseIcs(fileAttached)]); const { errors, rest: parsed } = splitErrors( await getSupportedEvents({ components, method, calscale, xWrTimezone, primaryTimezone, }) ); const { hidden: hiddenErrors, visible: visibleErrors } = splitHiddenErrors(errors); const totalToImport = parsed.length + hiddenErrors.length; const totalErrors = visibleErrors.length; if (!totalToImport && !totalErrors) { throw new ImportFileError(IMPORT_ERROR_TYPE.NO_EVENTS, fileAttached.name); } const step = (() => { if (method !== ICAL_METHOD.PUBLISH) { return IMPORT_STEPS.WARNING_IMPORT_INVITATION; } return totalErrors ? IMPORT_STEPS.WARNING_PARTIAL_IMPORT : IMPORT_STEPS.IMPORTING; })(); setModel({ ...model, method, step, eventsParsed: parsed, visibleErrors, hiddenErrors, failure: undefined, loading: false, }); } catch (e: any) { const failure = e instanceof ImportFileError ? e : new ImportFatalError(e); setModel({ ...getInitialState(model.calendar), failure, }); } }; const submit = ( <Button color="norm" disabled={model.step === IMPORT_STEPS.ATTACHING} loading={model.loading} type="submit" onClick={handleSubmit} > {c('Action').t`Import`} </Button> ); return { content: ( <AttachingModalContent model={model} calendars={activeWritableCalendars} onSelectCalendar={handleSelectCalendar} onAttach={handleAttach} onClear={handleClear} onDrop={onAddFiles} /> ), submit, onSubmit: handleSubmit, }; } if (model.step <= IMPORT_STEPS.WARNING_IMPORT_INVITATION) { const totalEvents = model.eventsParsed.length + model.visibleErrors.length + model.hiddenErrors.length; const handleSubmit = () => { setModel({ ...model, step: model.visibleErrors.length ? IMPORT_STEPS.WARNING_PARTIAL_IMPORT : IMPORT_STEPS.IMPORTING, }); }; const submit = <Button onClick={handleSubmit} color="norm" type="submit">{c('Action').t`Import`}</Button>; return { title: c('Title').ngettext(msgid`Import as simple event?`, `Import as simple events?`, totalEvents), content: <ImportInvitationModalContent model={model} />, submit, onSubmit: handleSubmit, }; } if (model.step <= IMPORT_STEPS.WARNING_PARTIAL_IMPORT) { const handleSubmit = () => { setModel({ ...model, step: IMPORT_STEPS.IMPORTING, visibleErrors: [] }); }; const { totalToImport } = extractTotals(model); const submit = ( <Button onClick={handleSubmit} color="norm" type="submit">{c('Action').t`Continue import`}</Button> ); return { title: !totalToImport ? c('Title').t`Import failed` : c('Title').t`Continue with partial import?`, content: <PartialImportModalContent model={model} />, submit: totalToImport ? submit : null, onSubmit: handleSubmit, }; } if (model.step === IMPORT_STEPS.IMPORTING) { const submit = ( <Button color="norm" disabled type="submit"> {c('Action').t`Continue`} </Button> ); const handleFinish = async (importedEvents: ImportedEvent[]) => { setModel((model) => ({ ...model, step: IMPORT_STEPS.FINISHED })); if (!importedEvents.length) { return; } const { Display, ID: calendarID } = model.calendar; const calls: Promise<void | void[]>[] = []; if (!Display) { const [{ ID: memberID }] = getMemberAndAddress(addresses, model.calendar.Members); await api(updateMember(calendarID, memberID, { Display: 1 })); calls.push(coreCall()); } if (isCalendar) { calls.push(calendarCall([calendarID])); } await Promise.all(calls); }; return { content: <ImportingModalContent model={model} setModel={setModel} onFinish={handleFinish} />, submit, onSubmit: noop, }; } // model.step === IMPORT_STEPS.FINISHED at this stage const submit = ( <Button className="ml-auto" onClick={onClose} color="norm" type="submit">{c('Action').t`Close`}</Button> ); return { content: <ImportSummaryModalContent model={model} />, close: null, submit, onSubmit: onClose, }; })(); useEffect(() => { if (files?.length) { onAddFiles(files); } }, []); return ( <BasicModal title={title} footer={ <> {close} {submit} </> } isOpen={isOpen} size="large" className="w-full" fullscreenOnMobile onClose={onClose} onExit={onExit} {...modalProps} > {content} </BasicModal> ); }; export default ImportModal;
5,932
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/importModal/ImportSummaryModalContent.tsx
import { c, msgid } from 'ttag'; import { extractTotals } from '@proton/shared/lib/calendar/import/import'; import { ImportCalendarModel } from '@proton/shared/lib/interfaces/calendar'; import { Alert, DynamicProgress } from '../../../components'; import ErrorDetails from './ErrorDetails'; interface GetMessageParams { isSuccess: boolean; isPartialSuccess: boolean; totalImported: number; totalToImport: number; } const getAlertMessage = ({ isSuccess, isPartialSuccess, totalImported, totalToImport }: GetMessageParams) => { if (isSuccess) { return totalImported === 1 ? c('Import calendar').t`Event successfully imported. The imported event will now appear in your calendar.` : // translator: "Events" below is meant as multiple (more than one) events generically. The exact number of events imported is mentioned elsewhere c('Import calendar') .t`Events successfully imported. The imported events will now appear in your calendar.`; } if (isPartialSuccess) { return c('Import calendar').ngettext( msgid`An error occurred while encrypting and adding your event. ${totalImported} out of ${totalToImport} event successfully imported.`, `An error occurred while encrypting and adding your events. ${totalImported} out of ${totalToImport} events successfully imported.`, totalToImport ); } return totalImported === 1 ? c('Import calendar').t`An error occurred while encrypting and adding your event. No event could be imported.` : // translator: "Events" below is meant as multiple (more than one) events generically. The exact number of events we tried to import is mentioned elsewhere c('Import calendar') .t`An error occurred while encrypting and adding your events. No event could be imported.`; }; const getDisplayMessage = ({ isSuccess, isPartialSuccess, totalImported, totalToImport }: GetMessageParams) => { if (!isSuccess && !isPartialSuccess) { return ''; } return c('Import calendar').ngettext( msgid`${totalImported}/${totalToImport} event encrypted and added to your calendar`, `${totalImported}/${totalToImport} events encrypted and added to your calendar`, totalToImport ); }; interface Props { model: ImportCalendarModel; } const ImportSummaryModalContent = ({ model }: Props) => { const { totalToImport, totalToProcess, totalImported, totalProcessed } = extractTotals(model); const isSuccess = totalImported === totalToImport; const isPartialSuccess = totalImported > 0 && !isSuccess; const alertMessage = getAlertMessage({ isSuccess, isPartialSuccess, totalImported, totalToImport }); const displayMessage = getDisplayMessage({ isSuccess, isPartialSuccess, totalImported, totalToImport }); const getAlert = () => { if (isSuccess) { return <div className="mb-4">{alertMessage}</div>; } return ( <Alert className="mb-4" type={isPartialSuccess ? 'warning' : 'error'}> {alertMessage} </Alert> ); }; return ( <> {getAlert()} <DynamicProgress id="progress-import-calendar" value={totalProcessed} display={displayMessage} max={totalToProcess} loading={false} success={isSuccess} partialSuccess={isPartialSuccess} /> <ErrorDetails errors={model.visibleErrors} /> </> ); }; export default ImportSummaryModalContent;
5,933
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/importModal/ImportingModalContent.tsx
import { Dispatch, SetStateAction, useEffect } from 'react'; import { c } from 'ttag'; import { getApiWithAbort } from '@proton/shared/lib/api/helpers/customConfig'; import { ICAL_METHOD } from '@proton/shared/lib/calendar/constants'; import { ImportEventError } from '@proton/shared/lib/calendar/icsSurgery/ImportEventError'; import { ImportFatalError } from '@proton/shared/lib/calendar/import/ImportFatalError'; import { processWithJails } from '@proton/shared/lib/calendar/import/encryptAndSubmit'; import { extractTotals, getSupportedEventsWithRecurrenceId, splitByRecurrenceId, splitErrors, splitHiddenErrors, } from '@proton/shared/lib/calendar/import/import'; import { getVeventWithDefaultCalendarAlarms } from '@proton/shared/lib/calendar/mailIntegration/invite'; import { EncryptedEvent, IMPORT_STEPS, ImportCalendarModel, ImportedEvent, VcalVeventComponent, } from '@proton/shared/lib/interfaces/calendar'; import { DynamicProgress } from '../../../components'; import { useApi, useBeforeUnload, useGetCalendarInfo } from '../../../hooks'; const getEventsWithoutDefaultNotifications = (events: VcalVeventComponent[]) => { return events.map((eventComponent) => ({ eventComponent, hasDefaultNotifications: false })); }; interface Props { model: ImportCalendarModel; setModel: Dispatch<SetStateAction<ImportCalendarModel>>; onFinish: (result: ImportedEvent[]) => void; } const ImportingModalContent = ({ model, setModel, onFinish }: Props) => { const api = useApi(); const getCalendarInfo = useGetCalendarInfo(); useBeforeUnload(c('Alert').t`By leaving now, some events may not be imported`); useEffect(() => { // Prepare api for allowing cancellation in the middle of the import const abortController = new AbortController(); const { signal } = abortController; const apiWithAbort = getApiWithAbort(api, signal); const setModelWithAbort = (set: (model: ImportCalendarModel) => ImportCalendarModel) => { if (signal.aborted) { return; } setModel(set); }; const handleImportProgress = ( encrypted: EncryptedEvent[], imported: EncryptedEvent[], errors: ImportEventError[] ) => { const { hidden: hiddenErrors, visible: visibleErrors } = splitHiddenErrors(errors); setModelWithAbort((model) => ({ ...model, totalEncrypted: model.totalEncrypted + encrypted.length, totalImported: model.totalImported + imported.length, visibleErrors: [...model.visibleErrors, ...visibleErrors], hiddenErrors: [...model.hiddenErrors, ...hiddenErrors], })); }; const process = async () => { try { const { memberID, addressKeys, calendarKeys, calendarSettings } = await getCalendarInfo( model.calendar.ID ); // add calendar alarms to invitations const vevents = model.method !== ICAL_METHOD.PUBLISH ? model.eventsParsed.map((vevent) => getVeventWithDefaultCalendarAlarms(vevent, calendarSettings) ) : [...model.eventsParsed]; const { withoutRecurrenceId, withRecurrenceId } = splitByRecurrenceId(vevents); const processData = { events: getEventsWithoutDefaultNotifications(withoutRecurrenceId), calendarID: model.calendar.ID, memberID, addressKeys, calendarKeys, api: apiWithAbort, signal, onProgress: handleImportProgress, }; const { importedEvents } = await processWithJails(processData); const formattedEventsWithRecurrenceId = await getSupportedEventsWithRecurrenceId({ eventsWithRecurrenceId: withRecurrenceId, parentEvents: importedEvents, calendarId: model.calendar.ID, api: apiWithAbort, }); const { errors, rest: supportedEventsWithRecurrenceID } = splitErrors(formattedEventsWithRecurrenceId); handleImportProgress([], [], errors); const { importedEvents: recurrenceImportedEvents } = await processWithJails({ ...processData, events: getEventsWithoutDefaultNotifications(supportedEventsWithRecurrenceID), }); if (signal.aborted) { return; } onFinish([...importedEvents, ...recurrenceImportedEvents]); } catch (error: any) { setModelWithAbort((model) => ({ step: IMPORT_STEPS.ATTACHING, calendar: model.calendar, eventsParsed: [], totalEncrypted: 0, totalImported: 0, visibleErrors: [], hiddenErrors: [], failure: new ImportFatalError(error), loading: false, })); if (signal.aborted) { return; } onFinish([]); } }; void process(); return () => { abortController.abort(); }; }, []); const { totalToImport, totalToProcess, totalImported, totalProcessed } = extractTotals(model); return ( <> <div className="mb-4"> {c('Import calendar').t`Please don't close the tab before the importing process is finished.`} </div> <DynamicProgress id="progress-import-calendar" value={totalProcessed} display={c('Import calendar') .t`Encrypting and adding events to your calendar: ${totalImported}/${totalToImport}`} max={totalToProcess} loading /> </> ); }; export default ImportingModalContent;
5,934
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/importModal/PartialImportModalContent.tsx
import { c, msgid } from 'ttag'; import { Href } from '@proton/atoms'; import { IMPORT_CALENDAR_UNSUPPORTED_FAQ_URL } from '@proton/shared/lib/calendar/constants'; import { extractTotals } from '@proton/shared/lib/calendar/import/import'; import { CALENDAR_APP_NAME } from '@proton/shared/lib/constants'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { ImportCalendarModel } from '@proton/shared/lib/interfaces/calendar/Import'; import { Alert, AttachedFile } from '../../../components'; import ErrorDetails from './ErrorDetails'; interface Props { model: ImportCalendarModel; } const PartialImportModalContent = ({ model }: Props) => { const { fileAttached, visibleErrors, failure } = model; const { totalToImport } = extractTotals(model); const totalEventsDiscarded = visibleErrors.filter((e) => e.component === 'vevent').length; const totalEvents = totalToImport + totalEventsDiscarded; const learnMore = failure ? undefined : getKnowledgeBaseUrl(IMPORT_CALENDAR_UNSUPPORTED_FAQ_URL); const summary = (() => { if (totalEventsDiscarded === totalEvents) { return c('Import warning').t`No event can be imported. Expand for details.`; } if (totalEventsDiscarded === 0) { return c('Import warning').t`Part of your calendar content is not supported and will not be imported.`; } return c('Import warning').ngettext( msgid`${totalEventsDiscarded} out of ${totalEvents} event will not be imported. Expand for details.`, `${totalEventsDiscarded} out of ${totalEvents} events will not be imported. Expand for details.`, totalEvents ); })(); return ( <> <div>{c('Import calendar; import invitation').t`This file contains some data that we cannot import:`}</div> {fileAttached && <AttachedFile file={fileAttached} iconName="calendar-grid" className="my-4" />} <Alert className="mb-4" type="warning"> {c('Import calendar warning') .t`${CALENDAR_APP_NAME} currently does not support certain event types, details and formats.`} {learnMore && ( <div> <Href href={learnMore}>{c('Link').t`Learn more`}</Href> </div> )} </Alert> <ErrorDetails summary={summary} errors={visibleErrors} /> </> ); }; export default PartialImportModalContent;
5,935
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/importModal/index.ts
export { default as ImportModal } from './ImportModal';
5,936
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/notifications/Notifications.tsx
import { Button, ButtonLike } from '@proton/atoms'; import getNotificationsTexts from '@proton/components/containers/calendar/notifications/getNotificationsTexts'; import { NotificationModel } from '@proton/shared/lib/interfaces/calendar/Notification'; import addItem from '@proton/utils/addItem'; import clsx from '@proton/utils/clsx'; import removeItem from '@proton/utils/removeIndex'; import updateItem from '@proton/utils/updateItem'; import { Icon, IconName, Tooltip } from '../../../components'; import { generateUID } from '../../../helpers'; import NotificationInput from './inputs/NotificationInput'; export const NOTIFICATION_ID = 'notifications'; interface Props { id: string; notifications: NotificationModel[]; hasWhen?: boolean; hasType?: boolean; fullWidth?: boolean; canAdd?: boolean; addIcon?: IconName; defaultNotification: NotificationModel; disabled?: boolean; onChange: (value: NotificationModel[]) => void; } const Notifications = ({ id, notifications, hasWhen, hasType, fullWidth = true, canAdd = true, addIcon, defaultNotification, disabled, onChange, }: Props) => { const { addNotificationText, addNotificationTitle, removeNotificationText } = getNotificationsTexts(); const noNotificationsButtonClassName = fullWidth ? 'mt-4 md:mt-2' : 'mt-4 lg:mt-0'; return ( <> {notifications.map((notification, index) => { const uniqueId = index === 0 ? id : `${id}-${index}`; return ( <div className="mb-2 flex flex-nowrap flex-align-items-center" key={notification.id}> <NotificationInput id={uniqueId} hasWhen={hasWhen} hasType={hasType} fullWidth={fullWidth} notification={notification} disabled={disabled} onEdit={(newNotification) => onChange(updateItem(notifications, index, newNotification))} /> <Tooltip title={removeNotificationText}> <ButtonLike data-testid="delete-notification" className="flex flex-item-noshrink ml-2" disabled={disabled} onClick={() => onChange(removeItem(notifications, index))} icon type="button" shape="ghost" color="norm" > <Icon name="trash" className="flex-item-noshrink" /> <span className="sr-only">{removeNotificationText}</span> </ButtonLike> </Tooltip> </div> ); })} {canAdd && ( <Button className={clsx([ fullWidth ? 'p-0' : 'p-2', notifications.length === 0 && noNotificationsButtonClassName, ])} shape={addIcon ? 'ghost' : 'underline'} color={addIcon ? 'weak' : 'norm'} data-testid="add-notification" title={addNotificationTitle} disabled={disabled} onClick={() => onChange(addItem(notifications, { ...defaultNotification, id: generateUID('notification') })) } > {addIcon ? ( <span className="flex flex-nowrap w-full flex-align-items-center"> <Icon name={addIcon} className="mr-2 flex-item-centered-vert" /> {addNotificationText} </span> ) : ( addNotificationText )} </Button> )} </> ); }; export default Notifications;
5,937
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/notifications/NotificationsInDrawer.tsx
import { Button } from '@proton/atoms'; import getNotificationsTexts from '@proton/components/containers/calendar/notifications/getNotificationsTexts'; import NotificationInputInDrawer from '@proton/components/containers/calendar/notifications/inputs/NotificationInputInDrawer'; import { NotificationModel } from '@proton/shared/lib/interfaces/calendar/Notification'; import addItem from '@proton/utils/addItem'; import clsx from '@proton/utils/clsx'; import removeItem from '@proton/utils/removeIndex'; import updateItem from '@proton/utils/updateItem'; import { Icon, IconName } from '../../../components'; import { generateUID } from '../../../helpers'; export const NOTIFICATION_ID = 'notifications'; interface Props { id: string; notifications: NotificationModel[]; hasWhen?: boolean; hasType?: boolean; fullWidth?: boolean; canAdd?: boolean; addIcon?: IconName; defaultNotification: NotificationModel; disabled?: boolean; onChange: (value: NotificationModel[]) => void; } const NotificationsInDrawer = ({ id, notifications, hasWhen, hasType, fullWidth = true, canAdd = true, addIcon, defaultNotification, disabled, onChange, }: Props) => { const { addNotificationText, addNotificationTitle } = getNotificationsTexts(); return ( <> {notifications.map((notification, index) => { const uniqueId = index === 0 ? id : `${id}-${index}`; return ( <NotificationInputInDrawer id={uniqueId} hasWhen={hasWhen} hasType={hasType} fullWidth={fullWidth} notification={notification} disabled={disabled} onEdit={(newNotification) => onChange(updateItem(notifications, index, newNotification))} onDelete={() => onChange(removeItem(notifications, index))} /> ); })} {canAdd && ( <div className={clsx(['mb-2', notifications.length === 0 && 'mt-2'])}> <Button className="p-0" shape={addIcon ? 'ghost' : 'underline'} color={addIcon ? 'weak' : 'norm'} data-testid="add-notification" title={addNotificationTitle} disabled={disabled} onClick={() => onChange( addItem(notifications, { ...defaultNotification, id: generateUID('notification') }) ) } > {addIcon ? ( <span className="flex flex-nowrap w-full flex-align-items-center"> <Icon name={addIcon} className="mr-2 flex-item-centered-vert" /> {addNotificationText} </span> ) : ( addNotificationText )} </Button> </div> )} </> ); }; export default NotificationsInDrawer;
5,938
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/notifications/getNotificationsTexts.ts
import { c } from 'ttag'; const getNotificationsTexts = () => { return { addNotificationText: c('Action').t`Add notification`, addNotificationTitle: c('Title').t`Add another notification to remind you of this event`, removeNotificationText: c('Action').t`Remove this notification`, notificationTypeText: c('Notification type').t`notification`, emailTypeText: c('Notification type').t`email`, howToSendText: c('Title').t`Select the way to send this notification`, whenToSendText: c('Title').t`Select when you want this notification to be sent`, timeToSendText: c('Title').t`Select the time to send this notification`, atText: c('Notification time input').t`at`, chooseANumberText: c('Title (number of minutes/hours/days/weeks)').t`Choose a number`, }; }; export default getNotificationsTexts;
5,939
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/notifications/index.ts
export { default as Notifications } from './Notifications';
5,940
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/notifications
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/notifications/inputs/NotificationInput.tsx
import getNotificationsTexts from '@proton/components/containers/calendar/notifications/getNotificationsTexts'; import { NOTIFICATION_INPUT_ID, NOTIFICATION_TYPE_API, NOTIFICATION_UNITS_MAX, } from '@proton/shared/lib/calendar/constants'; import { NotificationModel } from '@proton/shared/lib/interfaces/calendar/Notification'; import clsx from '@proton/utils/clsx'; import { DropdownSizeUnit, IntegerInput, Option, SelectTwo, TimeInput } from '../../../../components'; import { getDaysBefore, getHoursBefore, getMinutesBefore, getSameDay, getSameTime, getWeeksBefore, } from './notificationOptions'; const { EMAIL, DEVICE /* BOTH */ } = NOTIFICATION_TYPE_API; interface Props { id: string; className?: string; notification: NotificationModel; hasWhen?: boolean; hasType?: boolean; fullWidth?: boolean; disabled?: boolean; onEdit: (model: NotificationModel) => void; error?: string; } const getWhenOptions = (isAllDay: boolean, value = 0) => { if (isAllDay) { return [getSameDay(), getDaysBefore(value), getWeeksBefore(value)]; } return [getSameTime(), getMinutesBefore(value), getHoursBefore(value), getDaysBefore(value), getWeeksBefore(value)]; }; const NotificationInput = ({ id, className, notification, notification: { isAllDay, type, when, value, at, unit }, hasType = false, fullWidth = true, disabled = false, onEdit, error, }: Props) => { const { notificationTypeText, emailTypeText, howToSendText, whenToSendText, timeToSendText, atText, chooseANumberText, } = getNotificationsTexts(); const safeValue = value === undefined ? 1 : value; const options = getWhenOptions(isAllDay, safeValue); const textOptions = options.map((option, i) => ({ text: option.text, value: i })); const closestOption = options.findIndex((option) => { return option.value === safeValue && option.unit === unit && option.when === when; }); const optionsValue = closestOption === -1 ? 0 : closestOption; const hasValueInput = value === undefined || value > 0; const errorProps = typeof error === 'string' ? { 'aria-invalid': true } : {}; return ( <div className={clsx( 'flex flex-nowrap flex-item-fluid', className, fullWidth ? 'on-mobile-flex-column' : 'on-tablet-flex-column' )} > {hasType && ( <span className={clsx( 'flex flex-nowrap mr-2 my-2', fullWidth ? 'md:my-0' : 'lg:my-0', !(isAllDay && at) && 'w-custom' )} style={!(isAllDay && at) ? { '--w-custom': '10em' } : undefined} > <SelectTwo id={id} value={type} disabled={disabled} onChange={({ value }) => onEdit({ ...notification, type: +value })} title={howToSendText} {...errorProps} > {[ { text: notificationTypeText, value: DEVICE }, { text: emailTypeText, value: EMAIL }, // { text: c('Notification type').t`both notification and email`, value: BOTH }, ].map(({ value, text }) => ( <Option key={value} value={value} title={text} /> ))} </SelectTwo> </span> )} <span className="flex flex-nowrap flex-item-fluid"> {hasValueInput && ( <span className="flex-item-noshrink mr-2 w-custom" style={{ '--w-custom': '5em' }}> <IntegerInput id={NOTIFICATION_INPUT_ID} data-testid="notification-time-input" step={1} min={0} max={NOTIFICATION_UNITS_MAX[unit]} value={value} disabled={disabled} onChange={(newValue) => { if (newValue !== undefined && newValue === 0) { return; } onEdit({ ...notification, value: newValue }); }} onBlur={() => { if (!value) { onEdit({ ...notification, value: 1 }); } }} title={chooseANumberText} {...errorProps} /> </span> )} <SelectTwo data-testid="notification-time-dropdown" className="flex-item-fluid" size={{ width: DropdownSizeUnit.Dynamic }} value={optionsValue} disabled={disabled} onChange={({ value }) => { const optionIndex = +value; const option = options[optionIndex]; if (!option) { return; } onEdit({ ...notification, ...option, }); }} title={whenToSendText} {...errorProps} > {textOptions.map(({ value, text }) => ( <Option key={value} value={value} title={text} truncate /> ))} </SelectTwo> </span> {isAllDay && at && ( <span className="flex on-tiny-mobile-flex-column flex-nowrap"> {isAllDay && at && ( <span className={clsx( 'flex flex-nowrap flex-item-fluid flex-align-items-center mt-2', fullWidth ? 'md:mt-0' : 'lg:mt-0' )} > <span className={clsx('flex-item-noshrink ml-0 mr-2', fullWidth ? 'md:ml-2' : 'lg:ml-2')}> {atText} </span> <span className="w-custom" style={{ '--w-custom': '8em' }}> <TimeInput data-testid="notification-time-at" value={at} disabled={disabled} onChange={(at) => onEdit({ ...notification, at })} title={timeToSendText} {...errorProps} /> </span> </span> )} </span> )} </div> ); }; export default NotificationInput;
5,941
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/notifications
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/notifications/inputs/NotificationInputInDrawer.tsx
import { ButtonLike } from '@proton/atoms/Button'; import getNotificationsTexts from '@proton/components/containers/calendar/notifications/getNotificationsTexts'; import { NOTIFICATION_INPUT_ID, NOTIFICATION_TYPE_API, NOTIFICATION_UNITS_MAX, } from '@proton/shared/lib/calendar/constants'; import { NotificationModel } from '@proton/shared/lib/interfaces/calendar/Notification'; import clsx from '@proton/utils/clsx'; import { Icon, IntegerInput, Option, SelectTwo, TimeInput, Tooltip } from '../../../../components'; import { getDaysBefore, getHoursBefore, getMinutesBefore, getSameDay, getSameTime, getWeeksBefore, } from './notificationOptions'; const { EMAIL, DEVICE } = NOTIFICATION_TYPE_API; interface Props { id: string; className?: string; notification: NotificationModel; hasWhen?: boolean; hasType?: boolean; fullWidth?: boolean; disabled?: boolean; onEdit: (model: NotificationModel) => void; error?: string; onDelete: () => void; } const getWhenOptions = (isAllDay: boolean, value = 0) => { if (isAllDay) { return [getSameDay(), getDaysBefore(value), getWeeksBefore(value)]; } return [getSameTime(), getMinutesBefore(value), getHoursBefore(value), getDaysBefore(value), getWeeksBefore(value)]; }; const NotificationInputInDrawer = ({ id, className, notification, notification: { isAllDay, type, when, value, at, unit }, hasType = false, fullWidth = true, disabled = false, onEdit, error, onDelete, }: Props) => { const { removeNotificationText, notificationTypeText, emailTypeText, howToSendText, whenToSendText, timeToSendText, atText, chooseANumberText, } = getNotificationsTexts(); const safeValue = value === undefined ? 1 : value; const options = getWhenOptions(isAllDay, safeValue); const textOptions = options.map((option, i) => ({ text: option.text, value: i })); const closestOption = options.findIndex((option) => { return option.value === safeValue && option.unit === unit && option.when === when; }); const optionsValue = closestOption === -1 ? 0 : closestOption; const hasValueInput = value === undefined || value > 0; const errorProps = typeof error === 'string' ? { 'aria-invalid': true } : {}; return ( <div key={notification.id} className={clsx('flex flex-column flex-align-items-stretch flex-item-fluid gap-2 mb-4', className)} > {hasType && ( <span className="flex flex-nowrap gap-2"> <SelectTwo id={id} value={type} disabled={disabled} onChange={({ value }) => onEdit({ ...notification, type: +value })} title={howToSendText} className="flex-item-fluid" {...errorProps} > {[ { text: notificationTypeText, value: DEVICE }, { text: emailTypeText, value: EMAIL }, // { text: c('Notification type').t`both notification and email`, value: BOTH }, ].map(({ value, text }) => ( <Option key={value} value={value} title={text} /> ))} </SelectTwo> <span className="flex-item-noshrink"> <Tooltip title={removeNotificationText}> <ButtonLike data-testid="delete-notification" className="flex flex-item-noshrink" disabled={disabled} onClick={onDelete} icon type="button" shape="ghost" color="norm" > <Icon name="trash" className="flex-item-noshrink" /> <span className="sr-only">{removeNotificationText}</span> </ButtonLike> </Tooltip> </span> </span> )} <span className={clsx('flex gap-2', fullWidth ? 'on-mobile-flex-column' : 'on-tablet-flex-column')}> <span className="flex flex-nowrap gap-2 flex-item-grow-custom flex-item-fluid" style={{ '--grow-custom': '1.5' }} > {hasValueInput && ( <span className="flex-item-noshrink w-custom" style={{ '--w-custom': '4.5em' }}> <IntegerInput id={NOTIFICATION_INPUT_ID} data-testid="notification-time-input" step={1} min={0} max={NOTIFICATION_UNITS_MAX[unit]} value={value} disabled={disabled} onChange={(newValue) => { if (newValue !== undefined && newValue === 0) { return; } onEdit({ ...notification, value: newValue }); }} onBlur={() => { if (!value) { onEdit({ ...notification, value: 1 }); } }} title={chooseANumberText} {...errorProps} /> </span> )} <span className="flex-item-fluid"> <SelectTwo data-testid="notification-time-dropdown" value={optionsValue} disabled={disabled} onChange={({ value }) => { const optionIndex = +value; const option = options[optionIndex]; if (!option) { return; } onEdit({ ...notification, ...option, }); }} title={whenToSendText} {...errorProps} > {textOptions.map(({ value, text }) => ( <Option key={value} value={value} title={text} /> ))} </SelectTwo> </span> </span> {isAllDay && at && ( <span className="flex-item-fluid"> <TimeInput data-testid="notification-time-at" value={at} prefix={atText} disabled={disabled} onChange={(at) => onEdit({ ...notification, at })} title={timeToSendText} {...errorProps} /> </span> )} </span> </div> ); }; export default NotificationInputInDrawer;
5,942
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/notifications
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/notifications/inputs/notificationOptions.ts
import { c, msgid } from 'ttag'; import { NOTIFICATION_UNITS, NOTIFICATION_UNITS_MAX, NOTIFICATION_WHEN } from '@proton/shared/lib/calendar/constants'; import clamp from '@proton/utils/clamp'; export const getDaysBefore = (value: number) => ({ text: c('Notification when').ngettext(msgid`day before`, `days before`, value), value: clamp(value, 1, NOTIFICATION_UNITS_MAX[NOTIFICATION_UNITS.DAY]), unit: NOTIFICATION_UNITS.DAY, when: NOTIFICATION_WHEN.BEFORE, }); export const getSameDay = () => ({ text: c('Notification when').t`on the same day`, value: 0, unit: NOTIFICATION_UNITS.DAY, when: NOTIFICATION_WHEN.AFTER, }); export const getSameTime = () => ({ text: c('Notification when').t`at time of event`, value: 0, unit: NOTIFICATION_UNITS.MINUTE, when: NOTIFICATION_WHEN.AFTER, }); export const getWeeksBefore = (value: number) => ({ text: c('Notification when').ngettext(msgid`week before`, `weeks before`, value), value: clamp(value, 1, NOTIFICATION_UNITS_MAX[NOTIFICATION_UNITS.WEEK]), unit: NOTIFICATION_UNITS.WEEK, when: NOTIFICATION_WHEN.BEFORE, }); export const getMinutesBefore = (value: number) => ({ text: c('Notification when').ngettext(msgid`minute before`, `minutes before`, value), value: clamp(value, 1, NOTIFICATION_UNITS_MAX[NOTIFICATION_UNITS.MINUTE]), unit: NOTIFICATION_UNITS.MINUTE, when: NOTIFICATION_WHEN.BEFORE, }); export const getHoursBefore = (value: number) => ({ text: c('Notification when').ngettext(msgid`hour before`, `hours before`, value), value: clamp(value, 1, NOTIFICATION_UNITS_MAX[NOTIFICATION_UNITS.HOUR]), unit: NOTIFICATION_UNITS.HOUR, when: NOTIFICATION_WHEN.BEFORE, });
5,943
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/AutoDetectPrimaryTimezoneSection.tsx
import { c } from 'ttag'; import { useApi, useEventManager, useNotifications } from '@proton/components/hooks'; import { useLoading } from '@proton/hooks'; import { updateCalendarUserSettings } from '@proton/shared/lib/api/calendars'; import { CalendarUserSettings } from '@proton/shared/lib/interfaces/calendar'; import { Info, Toggle } from '../../../components'; import SettingsLayout from '../../account/SettingsLayout'; import SettingsLayoutLeft from '../../account/SettingsLayoutLeft'; import SettingsLayoutRight from '../../account/SettingsLayoutRight'; interface Props { calendarUserSettings: CalendarUserSettings; } const AutoDetectPrimaryTimezoneSection = ({ calendarUserSettings }: Props) => { const api = useApi(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const [loadingAutoDetect, withLoadingAutoDetect] = useLoading(); const checked = !!calendarUserSettings.AutoDetectPrimaryTimezone; const handleChange = async (data: Partial<CalendarUserSettings>) => { await api(updateCalendarUserSettings(data)); await call(); createNotification({ text: c('Success').t`Preference saved` }); }; return ( <SettingsLayout> <SettingsLayoutLeft> <label className="text-semibold" htmlFor="autodetect-primary-timezone" id="label-autodetect-primary-timezone" > <span className="mr-2">{c('Label').t`Auto-detect primary time zone`}</span> <Info title={c('Info') .t`If the system time zone does not match the current time zone preference, you will be asked to update it (at most once per day).`} /> </label> </SettingsLayoutLeft> <SettingsLayoutRight className="pt-2 flex flex-align-items-center"> <Toggle id="autodetect-primary-timezone" aria-describedby="autodetect-primary-timezone" loading={loadingAutoDetect} checked={checked} onChange={({ target }) => withLoadingAutoDetect( handleChange({ AutoDetectPrimaryTimezone: +target.checked, }) ) } /> </SettingsLayoutRight> </SettingsLayout> ); }; export default AutoDetectPrimaryTimezoneSection;
5,944
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/CalendarBadge.tsx
import { Badge, Tooltip } from '@proton/components/components'; import { CalendarStatusBadge } from '@proton/shared/lib/calendar/badges'; const CalendarBadge = ({ badgeType, text, tooltipText, className }: Omit<CalendarStatusBadge, 'statusType'>) => { return tooltipText ? ( <Tooltip title={tooltipText}> <span className={className}> <Badge type={badgeType}>{text}</Badge> </span> </Tooltip> ) : ( <Badge className={className} type={badgeType}> {text} </Badge> ); }; export default CalendarBadge;
5,945
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/CalendarDeleteSection.tsx
import { useHistory } from 'react-router'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Alert, ErrorButton, Prompt, useModalState } from '@proton/components/components'; import { SettingsParagraph } from '@proton/components/containers'; import { useApi, useEventManager, useNotifications } from '@proton/components/hooks'; import { useLoading } from '@proton/hooks'; import { removeCalendar, removeMember, updateCalendarUserSettings } from '@proton/shared/lib/api/calendars'; import { getIsHolidaysCalendar, getIsOwnedCalendar, getIsPersonalCalendar, getIsSubscribedCalendar, getOwnedPersonalCalendars, getProbablyActiveCalendars, } from '@proton/shared/lib/calendar/calendar'; import { getCalendarsSettingsPath } from '@proton/shared/lib/calendar/settingsRoutes'; import { VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import noop from '@proton/utils/noop'; import SettingsSection from '../../account/SettingsSection'; const getTexts = ({ isSubscribedCalendar, isHolidaysCalendar, isSharedAsMember, isSharedAsOwner, }: { isSubscribedCalendar: boolean; isHolidaysCalendar: boolean; isSharedAsMember: boolean; isSharedAsOwner: boolean; }) => { if (isSubscribedCalendar) { return { modalTitle: c('Remove calendar section title').t`Unsubscribe?`, modalText: c('Remove calendar section text').t`This calendar will be removed from your account.`, description: c('Remove calendar section description') .t`By unsubscribing, you will no longer have access to this calendar. All events in this calendar will be deleted from your account, but they'll remain in the original public link.`, deleteText: c('Action').t`Unsubscribe`, }; } if (isHolidaysCalendar) { return { modalTitle: c('Remove calendar section title').t`Delete calendar?`, // translator: A holidays calendar includes bank holidays and observances modalText: c('Info') .t`Are you sure you want to delete this calendar? You can add the holidays calendar back later.`, description: c('Delete calendar section description').t`You will no longer have access to this calendar.`, deleteText: c('Action').t`Delete`, }; } if (isSharedAsMember) { return { modalTitle: c('Remove calendar section title').t`Leave calendar?`, modalText: c('Remove calendar section text') .t`If you leave this calendar, you'll have to ask the owner to join again.`, description: c('Remove calendar section description').t`You will no longer have access to this calendar.`, deleteText: c('Action').t`Leave`, }; } return { modalTitle: c('Remove calendar section title').t`Delete calendar?`, modalText: isSharedAsOwner ? c('Info') .t`Are you sure you want to delete this calendar? All addresses you shared this calendar with will lose access to it.` : c('Info').t`Are you sure you want to delete this calendar? All events in it will be deleted.`, description: c('Delete calendar section description').t`All events in this calendar will be deleted.`, deleteText: c('Action').t`Delete`, }; }; interface Props { calendars: VisualCalendar[]; calendar: VisualCalendar; defaultCalendar?: VisualCalendar; isShared: boolean; } const CalendarDeleteSection = ({ calendars, calendar, defaultCalendar, isShared }: Props) => { const history = useHistory(); const api = useApi(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const [loading, withLoading] = useLoading(false); const [deleteModal, setIsDeleteModalOpen, renderDeleteModal] = useModalState(); const isSubscribedCalendar = getIsSubscribedCalendar(calendar); const isHolidaysCalendar = getIsHolidaysCalendar(calendar); const isOwner = getIsOwnedCalendar(calendar); const isSharedAsOwner = getIsPersonalCalendar(calendar) && isOwner && isShared; const isSharedAsMember = getIsPersonalCalendar(calendar) && !isOwner; const isDeleteDefaultCalendar = calendar.ID === defaultCalendar?.ID; const firstRemainingCalendar = getProbablyActiveCalendars(getOwnedPersonalCalendars(calendars)).find( ({ ID: calendarID }) => calendarID !== calendar.ID ); const { modalTitle, modalText, description, deleteText } = getTexts({ isSubscribedCalendar, isHolidaysCalendar, isSharedAsOwner, isSharedAsMember, }); const firstRemainingCalendarName = firstRemainingCalendar ? ( <span className="text-strong text-break" key="calendar-name"> {firstRemainingCalendar.Name} </span> ) : null; const deleteDefaultAlertText = isDeleteDefaultCalendar && firstRemainingCalendarName ? c('Info').jt`${firstRemainingCalendarName} will be set as default calendar.` : ''; const handleDelete = async () => { // If deleting the default calendar, the new calendar to make default is either the first active calendar or null if there is none. const newDefaultCalendarID = isDeleteDefaultCalendar ? firstRemainingCalendar?.ID || null : undefined; await withLoading( (async () => { if (getIsOwnedCalendar(calendar)) { await api(removeCalendar(calendar.ID)); // null is a valid default calendar id if (newDefaultCalendarID !== undefined) { // do not make this operation blocking, but growl about it await api(updateCalendarUserSettings({ DefaultCalendarID: newDefaultCalendarID })).catch(noop); } } else { await api(removeMember(calendar.ID, calendar.Members[0].ID)); } await call(); })() ); createNotification({ text: c('Success').t`Calendar removed` }); deleteModal.onClose(); history.replace(getCalendarsSettingsPath({ fullPath: true })); }; return ( <> {renderDeleteModal && ( <Prompt {...deleteModal} title={modalTitle} buttons={[ <Button color="danger" onClick={handleDelete} loading={loading} type="submit"> {deleteText} </Button>, <Button disabled={loading} onClick={deleteModal.onClose}>{c('Action').t`Cancel`}</Button>, ]} > <div className="mb-4">{modalText}</div> {deleteDefaultAlertText} </Prompt> )} <SettingsSection className="container-section-sticky-section"> <div className="h2 mb-1 text-bold">{c('Remove calendar section title').t`Remove calendar`}</div> <SettingsParagraph large>{description}</SettingsParagraph> {deleteDefaultAlertText && <Alert className="mb-4">{deleteDefaultAlertText}</Alert>} <ErrorButton onClick={() => setIsDeleteModalOpen(true)}>{deleteText}</ErrorButton> </SettingsSection> </> ); }; export default CalendarDeleteSection;
5,946
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/CalendarEventDefaultsSection.tsx
import { useEffect, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { InputFieldTwo, Option, SelectTwo } from '@proton/components/components'; import { SelectChangeEvent } from '@proton/components/components/selectTwo/select'; import { SettingsLayoutLeft, SettingsSectionWide, useCalendarModelEventManager } from '@proton/components/containers'; import { getCalendarEventSettingsModel, getDefaultModel, } from '@proton/components/containers/calendar/calendarModal/calendarModalState'; import { useApi, useNotifications } from '@proton/components/hooks'; import { useLoading } from '@proton/hooks'; import { updateCalendarSettings } from '@proton/shared/lib/api/calendars'; import { dedupeNotifications, sortNotificationsByAscendingTrigger } from '@proton/shared/lib/calendar/alarms'; import { modelToNotifications } from '@proton/shared/lib/calendar/alarms/modelToNotifications'; import { getIsHolidaysCalendar, getShowDuration } from '@proton/shared/lib/calendar/calendar'; import { MAX_DEFAULT_NOTIFICATIONS } from '@proton/shared/lib/calendar/constants'; import { CalendarBootstrap, NotificationModel, SubscribedCalendar, VisualCalendar, } from '@proton/shared/lib/interfaces/calendar'; import SettingsLayout from '../../account/SettingsLayout'; import SettingsLayoutRight from '../../account/SettingsLayoutRight'; import Notifications from '../notifications/Notifications'; interface Props { calendar: VisualCalendar | SubscribedCalendar; bootstrap: CalendarBootstrap; canEdit: boolean; } const CalendarEventDefaultsSection = ({ calendar, bootstrap, canEdit }: Props) => { const api = useApi(); const { call } = useCalendarModelEventManager(); const { createNotification } = useNotifications(); const [model, setModel] = useState<ReturnType<typeof getCalendarEventSettingsModel>>(() => getCalendarEventSettingsModel(bootstrap.CalendarSettings) ); const [loadingDuration, withLoadingDuration] = useLoading(); const [hasTouchedPartDayNotifications, setHasTouchedPartDayNotifications] = useState(false); const [hasTouchedFullDayNotifications, setHasTouchedFullDayNotifications] = useState(false); const [loadingSavePartDayNotifications, withLoadingSavePartDayNotifications] = useLoading(); const [loadingSaveFullDayNotifications, withLoadingSaveFullDayNotifications] = useLoading(); const showDuration = getShowDuration(calendar); const cannotEdit = !canEdit; const isHolidaysCalendar = getIsHolidaysCalendar(calendar); const displaySuccessNotification = () => { createNotification({ type: 'success', text: c('Notification success').t`Event defaults updated` }); }; const handleChangeDuration = async ({ value }: SelectChangeEvent<string>) => { return withLoadingDuration( (async () => { setModel((model) => ({ ...model, duration: +value, })); await api(updateCalendarSettings(calendar.ID, { DefaultEventDuration: +value })); await call([calendar.ID]); displaySuccessNotification(); })() ); }; const handleSaveNotifications = (fullDay = false) => { const key = fullDay ? 'fullDayNotifications' : 'partDayNotifications'; const dedupedNotifications = sortNotificationsByAscendingTrigger(dedupeNotifications(model[key])); const withLoading = fullDay ? withLoadingSaveFullDayNotifications : withLoadingSavePartDayNotifications; return withLoading( (async () => { await api( updateCalendarSettings(calendar.ID, { [fullDay ? 'DefaultFullDayNotifications' : 'DefaultPartDayNotifications']: modelToNotifications(dedupedNotifications), }) ); await call([calendar.ID]); setModel((model) => ({ ...model, [key]: dedupedNotifications, })); const setHasTouchedNotifications = fullDay ? setHasTouchedFullDayNotifications : setHasTouchedPartDayNotifications; setHasTouchedNotifications(false); displaySuccessNotification(); })() ); }; useEffect(() => { setModel(getCalendarEventSettingsModel(bootstrap.CalendarSettings)); setHasTouchedPartDayNotifications(false); setHasTouchedFullDayNotifications(false); }, [bootstrap]); return ( <SettingsSectionWide className="container-section-sticky-section"> <div className="h2 mb-1 text-bold">{c('Default calendar event settings section title') .t`Default event settings`}</div> {showDuration && ( <SettingsLayout stackEarlier className="mt-8"> <SettingsLayoutLeft> <label htmlFor="event-duration" className="text-semibold"> {c('Label for default event settings').t`Duration`} </label> </SettingsLayoutLeft> <SettingsLayoutRight> <InputFieldTwo disabled={loadingDuration || cannotEdit} as={SelectTwo} id="event-duration" data-testid="create-calendar/event-settings:event-duration" value={model.duration} // @ts-ignore onChange={handleChangeDuration} > {[ { text: c('Duration').t`30 minutes`, value: 30 }, { text: c('Duration').t`60 minutes`, value: 60 }, { text: c('Duration').t`90 minutes`, value: 90 }, { text: c('Duration').t`120 minutes`, value: 120 }, ].map(({ value, text }) => ( <Option key={value} value={value} title={text} /> ))} </InputFieldTwo> </SettingsLayoutRight> </SettingsLayout> )} <SettingsLayout stackEarlier> {!isHolidaysCalendar && ( <> <SettingsLayoutLeft> <label htmlFor="default-part-day-notifications" className="text-semibold"> {c('Label for default event notifications').t`Notifications`} </label> </SettingsLayoutLeft> <SettingsLayoutRight className="w-full"> <Notifications id="default-part-day-notifications" data-testid="create-calendar/event-settings:default-notification" hasType fullWidth={false} notifications={model.partDayNotifications} canAdd={model.partDayNotifications.length < MAX_DEFAULT_NOTIFICATIONS} disabled={loadingSavePartDayNotifications || cannotEdit} addIcon="plus" defaultNotification={getDefaultModel().defaultPartDayNotification} onChange={(notifications: NotificationModel[]) => { setModel({ ...model, partDayNotifications: notifications, }); setHasTouchedPartDayNotifications(true); }} /> <div className="mt-1"> <Button color="norm" onClick={() => handleSaveNotifications(false)} loading={loadingSavePartDayNotifications} disabled={!hasTouchedPartDayNotifications || cannotEdit} > {c('Action').t`Save`} </Button> </div> </SettingsLayoutRight> </> )} </SettingsLayout> <SettingsLayout stackEarlier> <SettingsLayoutLeft> <label htmlFor="default-full-day-notifications" className="text-semibold"> {isHolidaysCalendar ? c('Label for default event notifications').t`Notifications` : c('Label for default event notifications').t`All-day event notifications`} </label> </SettingsLayoutLeft> <SettingsLayoutRight className="w-full"> <Notifications id="default-full-day-notifications" data-testid="create-calendar/event-settings:default-full-day-notification" hasType fullWidth={false} notifications={model.fullDayNotifications} canAdd={model.fullDayNotifications.length < MAX_DEFAULT_NOTIFICATIONS} disabled={loadingSaveFullDayNotifications || cannotEdit} addIcon="plus" defaultNotification={getDefaultModel().defaultFullDayNotification} onChange={(notifications: NotificationModel[]) => { setModel({ ...model, fullDayNotifications: notifications, }); setHasTouchedFullDayNotifications(true); }} /> <div className="mt-1"> <Button color="norm" onClick={() => handleSaveNotifications(true)} loading={loadingSaveFullDayNotifications} disabled={!hasTouchedFullDayNotifications || cannotEdit} > {c('Action').t`Save`} </Button> </div> </SettingsLayoutRight> </SettingsLayout> </SettingsSectionWide> ); }; export default CalendarEventDefaultsSection;
5,947
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/CalendarExportSection.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Href } from '@proton/atoms'; import CalendarSelect from '@proton/components/components/calendarSelect/CalendarSelect'; import { SelectChangeEvent } from '@proton/components/components/selectTwo/select'; import { ExportModal } from '@proton/components/containers/calendar/exportModal'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import { Alert, PrimaryButton, useModalState } from '../../../components'; import { SettingsParagraph, SettingsSection } from '../../account'; interface Props { fallbackCalendar?: VisualCalendar; personalCalendars: VisualCalendar[]; } const CalendarExportSection = ({ personalCalendars, fallbackCalendar }: Props) => { const [calendar, setCalendar] = useState(fallbackCalendar); const [exportModal, setIsExportModalOpen, renderExportModal] = useModalState(); const calendarOptions = personalCalendars.map(({ ID: id, Name: name, Color: color }) => ({ id, name, color })); const handleSelectCalendar = ({ value: id }: SelectChangeEvent<string>) => { const selectedCalendar = personalCalendars.find(({ ID }) => ID === id); setCalendar(selectedCalendar || fallbackCalendar); }; const handleExport = () => { setIsExportModalOpen(true); }; const selectedCalendar = calendar || fallbackCalendar; return ( <SettingsSection> {renderExportModal && selectedCalendar && ( <ExportModal isOpen={exportModal.open} calendar={selectedCalendar} {...exportModal} /> )} {!selectedCalendar && ( <Alert className="mb-4" type="warning"> {c('Info').t`You have no calendars to export.`} </Alert> )} <SettingsParagraph> {c('Calendar export section description') .t`Download an ICS file with all the events from the selected calendar.`} <br /> <Href href={getKnowledgeBaseUrl('/protoncalendar-calendars')}>{c('Knowledge base link label') .t`Here's how`}</Href> </SettingsParagraph> <div className="flex"> {selectedCalendar && ( <span className="flex-item-fluid mr-4"> <CalendarSelect calendarID={selectedCalendar.ID} options={calendarOptions} onChange={handleSelectCalendar} freeze={false} /> </span> )} <span className="flex-item-noshrink"> <PrimaryButton onClick={handleExport} disabled={!selectedCalendar}>{c('Action') .t`Download ICS`}</PrimaryButton> </span> </div> </SettingsSection> ); }; export default CalendarExportSection;
5,948
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/CalendarImportSection.tsx
import { c } from 'ttag'; import { EasySwitchOauthImportButton, EasySwitchProvider } from '@proton/activation'; import { EASY_SWITCH_SOURCE, ImportProvider, ImportType } from '@proton/activation/src/interface'; import { Href } from '@proton/atoms'; import { getProbablyActiveCalendars, getWritableCalendars } from '@proton/shared/lib/calendar/calendar'; import { IMPORT_CALENDAR_FAQ_URL } from '@proton/shared/lib/calendar/constants'; import { CALENDAR_APP_NAME } from '@proton/shared/lib/constants'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { UserModel } from '@proton/shared/lib/interfaces'; import { VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import { Alert, PrimaryButton, useModalState } from '../../../components'; import { SettingsParagraph, SettingsSection } from '../../account'; import { useFlag } from '../../unleash'; import { ImportModal } from '../importModal'; interface Props { calendars: VisualCalendar[]; initialCalendar?: VisualCalendar; user: UserModel; } const CalendarImportSection = ({ calendars, initialCalendar, user }: Props) => { const { hasNonDelinquentScope } = user; const isImporterInMaintenance = useFlag('MaintenanceImporter'); const activeWritableCalendars = getWritableCalendars(getProbablyActiveCalendars(calendars)); const hasActiveCalendars = !!activeWritableCalendars.length; const [importModal, setIsImportModalOpen, renderImportModal] = useModalState(); const handleManualImport = () => setIsImportModalOpen(true); return ( <SettingsSection> {renderImportModal && initialCalendar && ( <ImportModal isOpen={importModal.open} initialCalendar={initialCalendar} calendars={calendars} {...importModal} /> )} {hasNonDelinquentScope && !hasActiveCalendars ? ( <Alert className="mb-4" type="warning"> {c('Info').t`You need to have an active personal calendar to import your events from ICS.`} </Alert> ) : null} <SettingsParagraph> {c('Calendar import section description') .t`You can import ICS files from another calendar to ${CALENDAR_APP_NAME}. This lets you quickly import one event or your entire agenda.`} <br /> <Href href={getKnowledgeBaseUrl(IMPORT_CALENDAR_FAQ_URL)}>{c('Knowledge base link label') .t`Here's how`}</Href> </SettingsParagraph> {!isImporterInMaintenance && ( <EasySwitchProvider> <EasySwitchOauthImportButton className="mr-4" source={EASY_SWITCH_SOURCE.IMPORT_CALENDAR_SETTINGS} defaultCheckedTypes={[ImportType.CALENDAR]} displayOn={'GoogleCalendar'} provider={ImportProvider.GOOGLE} /> </EasySwitchProvider> )} <PrimaryButton onClick={handleManualImport} disabled={!hasNonDelinquentScope || !hasActiveCalendars}> {c('Action').t`Import from ICS`} </PrimaryButton> </SettingsSection> ); }; export default CalendarImportSection;
5,949
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/CalendarInvitationsSection.tsx
import { c } from 'ttag'; import { useLoading } from '@proton/hooks'; import { updateCalendarUserSettings } from '@proton/shared/lib/api/calendars'; import { getClosestLocaleCode } from '@proton/shared/lib/i18n/helper'; import { TtagLocaleMap } from '@proton/shared/lib/interfaces/Locale'; import { CalendarUserSettings } from '@proton/shared/lib/interfaces/calendar'; import { Info, Toggle } from '../../../components'; import { useApi, useEventManager, useNotifications } from '../../../hooks'; import { SettingsSection } from '../../account'; import SettingsLayout from '../../account/SettingsLayout'; import SettingsLayoutLeft from '../../account/SettingsLayoutLeft'; import SettingsLayoutRight from '../../account/SettingsLayoutRight'; import InviteLocaleSelector from './InviteLocaleSelector'; interface Props { calendarUserSettings: CalendarUserSettings; locales: TtagLocaleMap; } const CalendarInvitationsSection = ({ calendarUserSettings: { InviteLocale, AutoImportInvite }, locales }: Props) => { const api = useApi(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const [loadingInviteLocale, withLoadingInviteLocale] = useLoading(); const [loadingAutoImportInvite, withLoadingAutoImportInvite] = useLoading(); const handleChange = async (data: Partial<CalendarUserSettings>) => { await api(updateCalendarUserSettings(data)); await call(); createNotification({ text: c('Success').t`Preference saved` }); }; const displayedLocale = InviteLocale === null ? null : getClosestLocaleCode(InviteLocale, locales); return ( <SettingsSection> <SettingsLayout> <SettingsLayoutLeft> <label className="text-semibold" htmlFor="invite-locale"> { // translator: the full sentence will be "Send invites in [LANGUAGE]", where [LANGUAGE] is a dropdown with language options. E.g. "Send invites in [ENGLISH]" c('Label').t`Send in` }{' '} <Info buttonClass="ml-2 inline-flex" title={c('Info').t`Event invitations and RSVPs will be sent in this language.`} /> </label> </SettingsLayoutLeft> <SettingsLayoutRight> <InviteLocaleSelector id="invite-locale" locale={displayedLocale} locales={locales} loading={loadingInviteLocale} onChange={(InviteLocale) => withLoadingInviteLocale(handleChange({ InviteLocale }))} /> </SettingsLayoutRight> </SettingsLayout> <SettingsLayout> <SettingsLayoutLeft> <label className="text-semibold inline-block" htmlFor="auto-import-invitations"> <span>{c('Auto import invitations setting').jt`Add to calendar and mark as pending`}</span> <Info buttonClass="ml-2 inline-flex" title={c('Info') .t`You still need to reply to invitations for the host to see your response.`} /> </label> </SettingsLayoutLeft> <SettingsLayoutRight className="pt-2 flex flex-align-items-center"> <Toggle id="auto-import-invitations" aria-describedby="auto-import-invitations" loading={loadingAutoImportInvite} checked={!!AutoImportInvite} onChange={({ target }) => withLoadingAutoImportInvite( handleChange({ AutoImportInvite: +target.checked, }) ) } /> </SettingsLayoutRight> </SettingsLayout> </SettingsSection> ); }; export default CalendarInvitationsSection;
5,950
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/CalendarLayoutSection.tsx
import { c } from 'ttag'; import { useLoading } from '@proton/hooks'; import { updateCalendarUserSettings } from '@proton/shared/lib/api/calendars'; import { CalendarUserSettings } from '@proton/shared/lib/interfaces/calendar'; import { Info, Toggle } from '../../../components'; import { useApi, useEventManager, useNotifications } from '../../../hooks'; import { SettingsSection } from '../../account'; import SettingsLayout from '../../account/SettingsLayout'; import SettingsLayoutLeft from '../../account/SettingsLayoutLeft'; import SettingsLayoutRight from '../../account/SettingsLayoutRight'; import WeekStartSection from '../../general/WeekStartSection'; import ViewPreferenceSelector from './ViewPreferenceSelector'; interface Props { calendarUserSettings: CalendarUserSettings; } const CalendarLayoutSection = ({ calendarUserSettings: { ViewPreference, DisplayWeekNumber } }: Props) => { const api = useApi(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const [loadingView, withLoadingView] = useLoading(); const [loadingWeekNumberDisplay, withLoadingWeekNumberDisplay] = useLoading(); const handleChange = async (data: Partial<CalendarUserSettings>) => { await api(updateCalendarUserSettings(data)); await call(); createNotification({ text: c('Success').t`Preference saved` }); }; return ( <SettingsSection> <SettingsLayout> <SettingsLayoutLeft> <label className="text-semibold" htmlFor="view-select"> {c('Label').t`Default view`}{' '} <Info buttonClass="ml-2 inline-flex" title={c('Info').t`Week and month views only apply to desktop.`} /> </label> </SettingsLayoutLeft> <SettingsLayoutRight> <ViewPreferenceSelector id="view-select" view={ViewPreference} loading={loadingView} onChange={(ViewPreference) => withLoadingView(handleChange({ ViewPreference }))} /> </SettingsLayoutRight> </SettingsLayout> <WeekStartSection/> <SettingsLayout> <SettingsLayoutLeft> <label className="text-semibold" htmlFor="week-numbers-display" id="label-week-numbers-display"> <span className="mr-2">{c('Label').t`Show week numbers`}</span> </label> </SettingsLayoutLeft> <SettingsLayoutRight className="pt-2 flex flex-align-items-center"> <Toggle id="week-numbers-display" aria-describedby="week-numbers-display" checked={!!DisplayWeekNumber} loading={loadingWeekNumberDisplay} onChange={({ target: { checked } }) => withLoadingWeekNumberDisplay(handleChange({ DisplayWeekNumber: +checked })) } /> </SettingsLayoutRight> </SettingsLayout> </SettingsSection> ); }; export default CalendarLayoutSection;
5,951
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/CalendarMemberAndInvitationList.test.tsx
import { render, screen } from '@testing-library/react'; import { mocked } from 'jest-mock'; import { useNotifications } from '@proton/components/hooks'; import { CalendarMember, CalendarMemberInvitation, MEMBER_INVITATION_STATUS, } from '@proton/shared/lib/interfaces/calendar'; import { mockNotifications } from '@proton/testing'; import CalendarMemberAndInvitationList from './CalendarMemberAndInvitationList'; jest.mock('@proton/components/hooks/useGetEncryptionPreferences'); jest.mock('@proton/components/hooks/useNotifications'); jest.mock('@proton/components/hooks/useAddresses'); jest.mock('../../contacts/ContactEmailsProvider', () => ({ useContactEmailsCache: () => ({ contactEmails: [], contactGroups: [], contactEmailsMap: { 'member1@pm.gg': { Name: 'Abraham Trump', Email: 'member1@pm.gg', }, 'invitation1@pm.gg': { Name: 'Unknown Person', Email: 'invitation1@pm.gg', }, }, groupsWithContactsMap: {}, }), })); const mockedUseNotifications = mocked(useNotifications); describe('CalendarMemberAndInvitationList', () => { beforeEach(() => { mockedUseNotifications.mockImplementation(() => mockNotifications); }); it(`doesn't display anything if there are no members or invitations`, () => { const { container } = render( <CalendarMemberAndInvitationList members={[]} invitations={[]} canEdit onDeleteInvitation={() => Promise.resolve()} onDeleteMember={() => Promise.resolve()} calendarID="1" /> ); expect(container).toBeEmptyDOMElement(); }); it('displays a members and invitations with available data', () => { const members = [ { ID: 'member1', Email: 'member1+oops@pm.gg', Permissions: 96, }, ] as CalendarMember[]; const invitations = [ { CalendarInvitationID: 'invitation1', Email: 'invitation1@pm.gg', // TODO: change when free/busy becomes available // Permissions: 64, Permissions: 96, Status: MEMBER_INVITATION_STATUS.PENDING, }, { CalendarInvitationID: 'invitation2', Email: 'invitation2@pm.gg', Permissions: 112, Status: MEMBER_INVITATION_STATUS.REJECTED, }, ] as CalendarMemberInvitation[]; const { rerender } = render( <CalendarMemberAndInvitationList members={members} invitations={invitations} canEdit onDeleteInvitation={() => Promise.resolve()} onDeleteMember={() => Promise.resolve()} calendarID="1" /> ); expect(screen.getByText(/^AT$/)).toBeInTheDocument(); expect(screen.getByText(/member1@pm.gg/)).toBeInTheDocument(); expect(screen.queryByText(/member1+oops@pm.gg/)).not.toBeInTheDocument(); // Temporary until free/busy becomes available // expect(screen.getByText(/See all event details/)).toBeInTheDocument(); expect(screen.getAllByText(/See all event details/).length).toBeTruthy(); // String is found 2 times due to responsive behaviour. // We need two buttons, each with the label "Remove this member" const removeMemberLabel = screen.getAllByText(/Remove this member/); expect(removeMemberLabel).toHaveLength(2); expect(screen.getByText(/^UP$/)).toBeInTheDocument(); expect(screen.getByText(/invitation1@pm.gg/)).toBeInTheDocument(); // expect(screen.getByText(/See only free\/busy/)).toBeInTheDocument(); expect(screen.getByText(/Invite sent/)).toBeInTheDocument(); expect(screen.getByText(/^I$/)).toBeInTheDocument(); expect(screen.getByText(/invitation2@pm.gg/)).toBeInTheDocument(); expect(screen.getByText(/Declined/)).toBeInTheDocument(); expect(screen.getAllByText(/Revoke this invitation/).length).toBe(2); expect(screen.getAllByText(/Delete/).length).toBe(2); /* * Check cannot edit case * * It should be possible to remove members * * It shouldn't be possible to edit permissions */ rerender( <CalendarMemberAndInvitationList members={members} invitations={invitations} canEdit={false} onDeleteInvitation={() => Promise.resolve()} onDeleteMember={() => Promise.resolve()} calendarID="1" /> ); const changePermissionsButtons = screen.getAllByRole('button', { name: /See all event details|Edit/ }); changePermissionsButtons.forEach((button) => { expect(button).toBeDisabled(); }); const removeThisMemberButtons = screen.getAllByRole('button', { name: /Remove this member/ }); removeThisMemberButtons.forEach((button) => { expect(button).not.toBeDisabled(); }); }); });
5,952
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/CalendarMemberAndInvitationList.tsx
import { c, msgid } from 'ttag'; import { Alert } from '@proton/components/components'; import { useApi, useNotifications } from '@proton/components/hooks'; import { updateInvitation, updateMemberPermission } from '@proton/shared/lib/api/calendars'; import { MAX_CALENDAR_MEMBERS } from '@proton/shared/lib/calendar/constants'; import { canonicalizeInternalEmail } from '@proton/shared/lib/helpers/email'; import { CalendarMember, CalendarMemberInvitation, MEMBER_INVITATION_STATUS, } from '@proton/shared/lib/interfaces/calendar'; import { Table, TableBody, TableHeader, TableHeaderCell, TableRow } from '../../../components'; import { useContactEmailsCache } from '../../contacts/ContactEmailsProvider'; import CalendarMemberRow from './CalendarMemberRow'; interface MemberAndInvitationListProps { members: CalendarMember[]; invitations: CalendarMemberInvitation[]; calendarID: string; canEdit: boolean; onDeleteMember: (id: string) => Promise<void>; onDeleteInvitation: (id: string, isDeclined: boolean) => Promise<void>; } const CalendarMemberAndInvitationList = ({ members, invitations, calendarID, canEdit, onDeleteMember, onDeleteInvitation, }: MemberAndInvitationListProps) => { const { contactEmailsMap } = useContactEmailsCache(); const { createNotification } = useNotifications(); const api = useApi(); if (!members.length && !invitations.length) { return null; } const showPermissionChangeSuccessNotification = (email: string) => { createNotification({ type: 'info', text: c('Calendar sharing permission change notification').t`Permissions changed for ${email}`, }); }; const displayStatus = invitations.some(({ Status }) => [MEMBER_INVITATION_STATUS.REJECTED, MEMBER_INVITATION_STATUS.PENDING].includes(Status) ); // do not display permissions if there are only declined invitations const displayPermissions = !!members.length || invitations.some(({ Status }) => Status !== MEMBER_INVITATION_STATUS.REJECTED); return ( <> {members.length + invitations.length >= MAX_CALENDAR_MEMBERS && ( <Alert type="info" className="mb-3"> {c('Maximum shared calendar members reached alert').ngettext( msgid`You have reached the maximum of ${MAX_CALENDAR_MEMBERS} member.`, `You have reached the maximum of ${MAX_CALENDAR_MEMBERS} members.`, MAX_CALENDAR_MEMBERS )} </Alert> )} <Table hasActions responsive="cards"> <TableHeader> <TableRow> <TableHeaderCell>{c('Header').t`User`}</TableHeaderCell> {displayPermissions && <TableHeaderCell>{c('Header').t`Permissions`}</TableHeaderCell>} {displayStatus && <TableHeaderCell>{c('Header').t`Status`}</TableHeaderCell>} <TableHeaderCell className="w-1/6">{c('Header').t`Action`}</TableHeaderCell> </TableRow> </TableHeader> <TableBody> {members.map(({ ID, Email, Permissions }) => { const { Name: contactName, Email: contactEmail } = contactEmailsMap[ canonicalizeInternalEmail(Email) ] || { Name: Email, Email, }; return ( <CalendarMemberRow key={ID} name={contactName} email={contactEmail} deleteLabel={c('Action').t`Remove this member`} status={MEMBER_INVITATION_STATUS.ACCEPTED} permissions={Permissions} displayPermissions={displayPermissions} displayStatus={displayStatus} canEdit={canEdit} onDelete={() => onDeleteMember(ID)} onPermissionsUpdate={async (newPermissions) => { await api(updateMemberPermission(calendarID, ID, { Permissions: newPermissions })); showPermissionChangeSuccessNotification(contactEmail); }} /> ); })} {invitations.map(({ CalendarInvitationID, Email, Permissions, Status }) => { if (Status === MEMBER_INVITATION_STATUS.ACCEPTED) { return null; } const { Name: contactName, Email: contactEmail } = contactEmailsMap[ canonicalizeInternalEmail(Email) ] || { Name: Email, Email, }; const isDeclined = Status === MEMBER_INVITATION_STATUS.REJECTED; const deleteLabel = isDeclined ? c('Action').t`Delete` : c('Action').t`Revoke this invitation`; return ( <CalendarMemberRow key={CalendarInvitationID} name={contactName} email={contactEmail} deleteLabel={deleteLabel} permissions={Permissions} status={Status} displayPermissions={displayPermissions} displayStatus={displayStatus} canEdit={canEdit} onDelete={() => onDeleteInvitation(CalendarInvitationID, isDeclined)} onPermissionsUpdate={async (newPermissions) => { await api( updateInvitation(calendarID, CalendarInvitationID, { Permissions: newPermissions, }) ); showPermissionChangeSuccessNotification(contactEmail); }} /> ); })} </TableBody> </Table> </> ); }; export default CalendarMemberAndInvitationList;
5,953
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/CalendarMemberGrid.scss
@import '~@proton/styles/scss/lib'; @import '~@proton/styles/scss/specifics/placeholder-loading'; .calendar-member-status { padding-block: rem(1); padding-inline: rem(6); } .calendar-member-skeleton { &-container { display: flex; border-block-end: 1px solid var(--border-weak); padding: rem(8); } &-user { display: flex; flex-direction: column; > * { block-size: rem(14); &:first-child { margin-block-end: rem(4); } } } &::before { inline-size: 100%; block-size: 100%; @extend %item-loading-pseudo; @extend %placeholder-loading; } &--avatar { inline-size: rem(32); block-size: rem(32); margin-inline-end: rem(8); } &--user-name { inline-size: 174px; } &--user-email { block-size: 109px; } }
5,954
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/CalendarMemberRow.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Avatar, Button } from '@proton/atoms'; import { Icon, Option, SelectTwo, Tooltip } from '@proton/components/components'; import { SelectChangeEvent } from '@proton/components/components/selectTwo/select'; import { useLoading } from '@proton/hooks'; import { MEMBER_PERMISSIONS } from '@proton/shared/lib/calendar/permissions'; import { getInitials } from '@proton/shared/lib/helpers/string'; import { MEMBER_INVITATION_STATUS } from '@proton/shared/lib/interfaces/calendar'; import { TableCell, TableRow } from '../../../components'; import './CalendarMemberGrid.scss'; const permissionLabelMap = { [MEMBER_PERMISSIONS.EDIT]: c('Calendar share permission label').t`Edit event details`, [MEMBER_PERMISSIONS.FULL_VIEW]: c('Calendar share permission label').t`See all event details`, // [CalendarMemberPermissions.LIMITED]: c('Calendar share permission label').t`See only free/busy`, }; const getStatusText = (status: MEMBER_INVITATION_STATUS) => { if (status === MEMBER_INVITATION_STATUS.PENDING) { return c('Calendar invite status label').t`Invite sent`; } if (status === MEMBER_INVITATION_STATUS.REJECTED) { return c('Calendar invite status label').t`Declined`; } return ''; }; export const MemberStatus = ({ status }: { status: MEMBER_INVITATION_STATUS }) => { if (status === MEMBER_INVITATION_STATUS.ACCEPTED) { return null; } const text = getStatusText(status); return ( <span title={text} className="calendar-member-status inline-block text-ellipsis text-sm text-semibold color-weak bg-strong text-uppercase rounded text-no-wrap" > {text} </span> ); }; interface CalendarMemberRowProps { email: string; name: string; deleteLabel: string; permissions: number; status: MEMBER_INVITATION_STATUS; displayPermissions: boolean; displayStatus: boolean; canEdit: boolean; onPermissionsUpdate: (newPermissions: number) => Promise<void>; onDelete: () => Promise<void>; } const CalendarMemberRow = ({ email, name, deleteLabel, permissions, status, displayPermissions, displayStatus, canEdit, onPermissionsUpdate, onDelete, }: CalendarMemberRowProps) => { const [isLoadingDelete, withLoadingDelete] = useLoading(); const [isLoadingPermissionsUpdate, withLoadingPermissionsUpdate] = useLoading(); const [perms, setPerms] = useState(permissions); const handleDelete = () => withLoadingDelete(onDelete()); const handleChangePermissions = async ({ value: newPermissions }: SelectChangeEvent<number>) => { await withLoadingPermissionsUpdate(onPermissionsUpdate(newPermissions)); setPerms(newPermissions); }; const availablePermissions = Object.entries(permissionLabelMap); const isStatusRejected = status === MEMBER_INVITATION_STATUS.REJECTED; const permissionsSelect = ( <SelectTwo loading={isLoadingPermissionsUpdate} value={perms} disabled={!canEdit} onChange={handleChangePermissions} > {availablePermissions.map(([value, label]) => ( <Option key={value} value={+value} title={label} /> ))} </SelectTwo> ); return ( <TableRow> <TableCell> <div className="flex flex-nowrap flex-align-items-center gap-2 w-full md:w-auto"> <Avatar color="weak" className="flex-item-noshrink"> {getInitials(name)} </Avatar> <div> <div className="text-ellipsis" title={name}> {name} </div> {email !== name && ( <div className="text-ellipsis text-sm m-0 color-weak" title={email}> {email} </div> )} </div> </div> </TableCell> {displayPermissions && ( <TableCell label={c('Header').t`Permissions`}>{!isStatusRejected && permissionsSelect}</TableCell> )} {displayStatus && ( <TableCell> <MemberStatus status={status} /> </TableCell> )} <TableCell> <Tooltip title={deleteLabel}> <Button icon shape="ghost" color="norm" loading={isLoadingDelete} onClick={handleDelete} className="ml-auto hidden lg:inline-block" > <Icon name="trash" alt={deleteLabel} /> </Button> </Tooltip> <div className="lg:hidden"> <Button shape="outline" color="norm" size="small" loading={isLoadingDelete} onClick={handleDelete} className="inline-flex flex-align-items-center flex-nowrap" > <Icon name="trash" alt="" className="mr-1 flex-item-noshrink" /> <span>{deleteLabel}</span> </Button> </div> </TableCell> </TableRow> ); }; export default CalendarMemberRow;
5,955
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/CalendarSettingsBreadcrumbs.tsx
import { useHistory } from 'react-router'; import { c } from 'ttag'; import { ButtonLike } from '@proton/atoms'; import { CollapsingBreadcrumbs, Icon, Option, SimpleDropdown } from '@proton/components/components'; import CalendarSelectIcon from '@proton/components/components/calendarSelect/CalendarSelectIcon'; import SelectOptions from '@proton/components/components/selectTwo/SelectOptions'; import { getCalendarSubpagePath, getCalendarsSettingsPath } from '@proton/shared/lib/calendar/settingsRoutes'; import { VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; interface Props { calendar: VisualCalendar; calendars: VisualCalendar[]; } const CalendarSettingsBreadcrumbs = ({ calendar, calendars }: Props) => { const history = useHistory(); if (calendars.length === 1) { return null; } return ( <div className="flex flex-nowrap flex-align-items-center md:hidden"> <CollapsingBreadcrumbs breadcrumbs={[ { text: c('breadcrumb').t`Calendars`, key: 'calendars-main-route', onClick: () => history.replace(getCalendarsSettingsPath({ fullPath: true })), }, { text: calendar.Name, key: calendar.ID, className: 'flex-item-fluid', }, ]} /> {calendars && ( <SimpleDropdown as={ButtonLike} shape="ghost" color="weak" icon type="button" className="flex-item-noshrink" content={<Icon name="chevron-down" className="caret-like" />} hasCaret={false} > <SelectOptions<string> selected={calendars.findIndex(({ ID }) => ID === calendar.ID) || 0} onChange={({ value: calendarID }) => history.replace(getCalendarSubpagePath(calendarID, { fullPath: true })) } > {calendars.map(({ ID, Name, Color }) => ( <Option key={ID} value={ID} title={Name}> <div className="flex flex-nowrap flex-align-items-center"> <CalendarSelectIcon color={Color} className="flex-item-noshrink mr-3" /> <div className="text-ellipsis">{Name}</div> </div> </Option> ))} </SelectOptions> </SimpleDropdown> )} </div> ); }; export default CalendarSettingsBreadcrumbs;
5,956
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/CalendarShareSection.tsx
import { Dispatch, SetStateAction } from 'react'; import { c } from 'ttag'; import { Button, ButtonLike, Card } from '@proton/atoms'; import { SettingsLink, useModalState } from '@proton/components/components'; import { FeatureCode, SettingsParagraph, SettingsSectionWide } from '@proton/components/containers'; import { useApi, useFeature, useNotifications } from '@proton/components/hooks'; import { removeInvitation, removeMember } from '@proton/shared/lib/api/calendars'; import { CALENDAR_SETTINGS_SECTION_ID, MAX_CALENDAR_MEMBERS } from '@proton/shared/lib/calendar/constants'; import { filterOutAcceptedInvitations } from '@proton/shared/lib/calendar/sharing/shareProton/shareProton'; import { APP_UPSELL_REF_PATH, BRAND_NAME, CALENDAR_UPSELL_PATHS, MAIL_SHORT_APP_NAME, UPSELL_COMPONENT, } from '@proton/shared/lib/constants'; import { addUpsellPath, getUpsellRef } from '@proton/shared/lib/helpers/upsell'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { Address, UserModel } from '@proton/shared/lib/interfaces'; import { CalendarMember, CalendarMemberInvitation, VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import SubSettingsSection from '../../layout/SubSettingsSection'; import ShareCalendarModal from '../shareProton/ShareCalendarModal'; import CalendarShareUrlSection from '../shareURL/CalendarShareUrlSection'; import CalendarMemberAndInvitationList from './CalendarMemberAndInvitationList'; import './CalendarMemberGrid.scss'; const MembersAndInvitationsLoadingSkeleton = () => ( <> <div className="calendar-member-skeleton-container"> <div className="calendar-member-skeleton calendar-member-skeleton--avatar rounded" /> <div className="calendar-member-skeleton-user"> <div className="calendar-member-skeleton calendar-member-skeleton--user-name" /> <div className="calendar-member-skeleton calendar-member-skeleton--user-email" /> </div> </div> <div className="calendar-member-skeleton-container"> <div className="calendar-member-skeleton calendar-member-skeleton--avatar rounded" /> <div className="calendar-member-skeleton-user"> <div className="calendar-member-skeleton calendar-member-skeleton--user-name" /> <div className="calendar-member-skeleton calendar-member-skeleton--user-email" /> </div> </div> </> ); interface CalendarShareSectionProps { calendar: VisualCalendar; addresses: Address[]; user: UserModel; isLoading: boolean; canShare: boolean; invitations: CalendarMemberInvitation[]; members: CalendarMember[]; setMembers: Dispatch<SetStateAction<CalendarMember[]>>; setInvitations: Dispatch<SetStateAction<CalendarMemberInvitation[]>>; } const CalendarShareSection = ({ calendar, addresses, user, isLoading, canShare, invitations, members, setInvitations, setMembers, }: CalendarShareSectionProps) => { const api = useApi(); const { createNotification } = useNotifications(); const isCalendarSharingEnabled = !!useFeature(FeatureCode.CalendarSharingEnabled).feature?.Value; const [shareCalendarModal, setIsShareModalOpen, renderShareCalendarModal] = useModalState(); const { hasPaidMail } = user; const handleShare = () => { setIsShareModalOpen(true); }; const handleDeleteMember = async (id: string) => { await api(removeMember(calendar.ID, id)); setMembers((members) => members.filter(({ ID }) => ID !== id)); createNotification({ type: 'success', text: c('Notification in share calendar modal').t`Member deleted`, }); }; const handleDeleteInvitation = async (id: string, isDeclined: boolean) => { await api(removeInvitation(calendar.ID, id)); setInvitations((prevState) => prevState.filter(({ CalendarInvitationID: ID }) => ID !== id)); const text = isDeclined ? c('Notification in share calendar modal').t`Invitation deleted` : c('Notification in share calendar modal').t`Invitation revoked`; createNotification({ type: 'success', text }); }; const title = isCalendarSharingEnabled ? c('Calendar settings section title').t`Share calendar` : c('Calendar settings section title').t`Share outside ${BRAND_NAME}`; const pendingInvitations = filterOutAcceptedInvitations(invitations); const isMaximumMembersReached = members.length + pendingInvitations.length >= MAX_CALENDAR_MEMBERS; const upsellRef = getUpsellRef({ app: APP_UPSELL_REF_PATH.CALENDAR_UPSELL_REF_PATH, component: UPSELL_COMPONENT.BANNER, feature: CALENDAR_UPSELL_PATHS.SHARE_CAL, isSettings: true, }); const sectionTitle = c('Calendar settings section title').t`Share with ${BRAND_NAME} users`; return ( <SettingsSectionWide className="container-section-sticky-section"> {renderShareCalendarModal && ( <ShareCalendarModal addresses={addresses} members={members} invitations={invitations} calendar={calendar} {...shareCalendarModal} onFinish={(invitations) => setInvitations((prevState) => [...prevState, ...invitations])} /> )} <SubSettingsSection title={title} id={CALENDAR_SETTINGS_SECTION_ID.SHARE}> {hasPaidMail && (isCalendarSharingEnabled ? ( <> <div className="mb-11 mt-6"> <div className="mb-6"> <h3 className="text-bold mb-2" id={CALENDAR_SETTINGS_SECTION_ID.SHARE_PRIVATELY}> {sectionTitle} </h3> <SettingsParagraph learnMoreUrl={getKnowledgeBaseUrl('/share-calendar-with-proton-users')} > {c('Calendar settings private share description') .t`Share your calendar with other ${BRAND_NAME} users. Enable collaboration by allowing them to add and edit events in your calendar. You can modify the user permissions anytime.`} </SettingsParagraph> {!isMaximumMembersReached && ( <Button onClick={handleShare} disabled={isLoading || !canShare || isMaximumMembersReached} color="norm" aria-label={sectionTitle} > {c('Action').t`Share`} </Button> )} </div> {isLoading && <MembersAndInvitationsLoadingSkeleton />} <CalendarMemberAndInvitationList members={members} invitations={invitations} calendarID={calendar.ID} canEdit={canShare} onDeleteInvitation={handleDeleteInvitation} onDeleteMember={handleDeleteMember} /> </div> <CalendarShareUrlSection calendar={calendar} user={user} canShare={canShare} /> </> ) : ( <CalendarShareUrlSection calendar={calendar} noTitle={!isCalendarSharingEnabled} user={user} canShare={canShare} /> ))} {!hasPaidMail && ( <Card rounded className="mt-4" data-testid="card:upgrade"> <div className="flex flex-nowrap flex-align-items-center"> <p className="flex-item-fluid my-0 pr-7"> {c('Upgrade notice') .t`Upgrade to a ${MAIL_SHORT_APP_NAME} paid plan to share your calendar.`} </p> <ButtonLike as={SettingsLink} path={addUpsellPath('/upgrade', upsellRef)} color="norm" shape="solid" size="small" > {c('Action').t`Upgrade`} </ButtonLike> </div> </Card> )} </SubSettingsSection> </SettingsSectionWide> ); }; export default CalendarShareSection;
5,957
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/CalendarSubpage.tsx
import { useEffect, useLayoutEffect, useState } from 'react'; import { useHistory, useParams } from 'react-router'; import { c } from 'ttag'; import { PrivateMainArea, SettingsPageTitle, SettingsParagraph, SettingsSection, SettingsSectionTitle, } from '@proton/components/containers'; import CalendarSettingsBreadcrumbs from '@proton/components/containers/calendar/settings/CalendarSettingsBreadcrumbs'; import { useApi, useGetCalendarBootstrap, useNotifications } from '@proton/components/hooks'; import { getAllMembers, getCalendarInvitations } from '@proton/shared/lib/api/calendars'; import { getIsOwnedCalendar, getIsPersonalCalendar } from '@proton/shared/lib/calendar/calendar'; import { MEMBER_PERMISSIONS } from '@proton/shared/lib/calendar/permissions'; import { getCalendarsSettingsPath } from '@proton/shared/lib/calendar/settingsRoutes'; import { Address, UserModel } from '@proton/shared/lib/interfaces'; import { CalendarMember, CalendarMemberInvitation, GetAllMembersApiResponse, GetCalendarInvitationsResponse, MEMBER_INVITATION_STATUS, SubscribedCalendar, VisualCalendar, } from '@proton/shared/lib/interfaces/calendar'; import { PrivateMainSettingsAreaBase } from '../../layout/PrivateMainSettingsArea'; import CalendarDeleteSection from './CalendarDeleteSection'; import CalendarEventDefaultsSection from './CalendarEventDefaultsSection'; import CalendarShareSection from './CalendarShareSection'; import CalendarSubpageHeaderSection from './CalendarSubpageHeaderSection'; interface Props { calendars: VisualCalendar[]; subscribedCalendars: SubscribedCalendar[]; holidaysCalendars: VisualCalendar[]; defaultCalendar?: VisualCalendar; addresses: Address[]; user: UserModel; } const CalendarSubpage = ({ calendars, subscribedCalendars, holidaysCalendars, defaultCalendar, addresses, user, }: Props) => { const { calendarId } = useParams<{ calendarId: string }>(); const history = useHistory(); const getCalendarBootstrap = useGetCalendarBootstrap(); const { createNotification } = useNotifications(); const api = useApi(); const [renderCount, setRenderCount] = useState(0); const [calendar, setCalendar] = useState<SubscribedCalendar | VisualCalendar>(); const [bootstrap, setBootstrap] = useState(); const [invitations, setInvitations] = useState<CalendarMemberInvitation[]>([]); const [members, setMembers] = useState<CalendarMember[]>([]); const [loadingShareData, setLoadingShareData] = useState(true); useLayoutEffect(() => { const calendar = subscribedCalendars.find(({ ID }) => ID === calendarId) || calendars.find(({ ID }) => ID === calendarId); if (!calendar) { createNotification({ type: 'error', text: c('Error').t`Calendar cannot be found`, }); history.replace(getCalendarsSettingsPath({ fullPath: true })); } else { setCalendar(calendar); } }, [calendarId, renderCount]); useEffect( () => { if (!calendar) { return; } else { setBootstrap(undefined); } const loadBootstrap = async () => { try { setBootstrap(await getCalendarBootstrap(calendar.ID)); } catch (e: any) { const text = e?.message || 'Failed to retrieve calendar details'; createNotification({ type: 'error', text, }); // we leave the user stuck with a loader screen } }; const loadMembersAndInvitations = async () => { // set loading state to true in case the component did not get unmounted setLoadingShareData(true); if (!getIsOwnedCalendar(calendar)) { return; } const [{ Members }, { Invitations }] = await Promise.all([ api<GetAllMembersApiResponse>(getAllMembers(calendar.ID)), api<GetCalendarInvitationsResponse>(getCalendarInvitations(calendar.ID)), ]); // if failing here, leave user with loader in the section // filter out owner and accepted invitations setMembers(Members.filter(({ Permissions }) => Permissions !== MEMBER_PERMISSIONS.OWNS)); setInvitations(Invitations.filter(({ Status }) => Status !== MEMBER_INVITATION_STATUS.ACCEPTED)); setLoadingShareData(false); }; Promise.all([loadBootstrap(), loadMembersAndInvitations()]); }, // re-load bootstrap only if calendar changes. Do not listen to dynamic changes [calendar] ); if (!calendar) { return null; } if (!bootstrap) { return ( <PrivateMainArea> <div className="container-section-sticky"> <SettingsPageTitle className="my-14 settings-loading-page-title" /> <section className="container-section-sticky-section"> <SettingsSectionTitle className="settings-loading-section-title" /> <SettingsSection> <SettingsParagraph className="mb-4"> <span className="block settings-loading-paragraph-line" /> <span className="block settings-loading-paragraph-line" /> <span className="block settings-loading-paragraph-line" /> </SettingsParagraph> </SettingsSection> </section> </div> </PrivateMainArea> ); } const hasMembersOrInvitations = !!(members.length || invitations.length); const isOwner = getIsOwnedCalendar(calendar); const isPersonalCalendar = getIsPersonalCalendar(calendar); const reRender = () => setRenderCount((count) => count + 1); return ( <PrivateMainSettingsAreaBase title={calendar.Name} noTitle breadcrumbs={<CalendarSettingsBreadcrumbs calendar={calendar} calendars={calendars} />} > <div className="container-section-sticky-section container-section-sticky-section--single-calendar-section"> <CalendarSubpageHeaderSection calendar={calendar} holidaysCalendars={holidaysCalendars} defaultCalendar={defaultCalendar} onEdit={reRender} canEdit={user.hasNonDelinquentScope} /> <CalendarEventDefaultsSection calendar={calendar} bootstrap={bootstrap} canEdit={user.hasNonDelinquentScope} /> {isOwner && isPersonalCalendar && ( <CalendarShareSection calendar={calendar} addresses={addresses} user={user} isLoading={loadingShareData} canShare={user.hasNonDelinquentScope} members={members} invitations={invitations} setInvitations={setInvitations} setMembers={setMembers} /> )} <CalendarDeleteSection calendars={calendars} calendar={calendar} defaultCalendar={defaultCalendar} isShared={hasMembersOrInvitations} /> </div> </PrivateMainSettingsAreaBase> ); }; export default CalendarSubpage;
5,958
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/CalendarSubpageHeaderSection.spec.tsx
import { ComponentProps } from 'react'; import { render, screen } from '@testing-library/react'; import { mockUseContactEmailsCache } from '@proton/testing/index'; import CalendarSubpageHeaderSection from './CalendarSubpageHeaderSection'; const defaultCalendar = { ID: 'FV6FNtAc6lgP6R7dM7YB5N3LzHuoBMyivBSqjPcDfIbuMf5MdvXlCmMMcBY57-wdG-hQk4qhFb5lDEJyxjySpQ==', }; const ownedCalendar = { ID: 'FV6FNtAc6lgP6R7dM7YB5N3LzHuoBMyivBSqjPcDfIbuMf5MdvXlCmMMcBY57-wdG-hQk4qhFb5lDEJyxjySpQ==', Name: 'My calendar', Description: '', Type: 0, Owner: { Email: 'joshua@yomail.com', }, CreateTime: 1688650068, Members: [ { ID: 'FV6FNtAc6lgP6R7dM7YB5N3LzHuoBMyivBSqjPcDfIbuMf5MdvXlCmMMcBY57-wdG-hQk4qhFb5lDEJyxjySpQ==', Permissions: 127, Email: 'joshua@yomail.com', AddressID: 'p5DPgsgSOQhwxfZmy4A-vVIxHd40lH8xRVg_4ulz69pz7Ox7ibSa2QXEbMg151clLRB-CQQTCRNteaIBHL_iUg==', CalendarID: 'FV6FNtAc6lgP6R7dM7YB5N3LzHuoBMyivBSqjPcDfIbuMf5MdvXlCmMMcBY57-wdG-hQk4qhFb5lDEJyxjySpQ==', Name: 'My calendar', Description: '', Color: '#DB60D6', Display: 1, Priority: 1, Flags: 1, }, ], Color: '#DB60D6', Display: 1, Email: 'joshua@yomail.com', Flags: 1, Permissions: 127, Priority: 1, }; const readonlySharedCalendar = { ID: 'W6E2R1LyNeueUxuR_1VjbM3M2UoGKPqPrRhGwrqRlLyoweZNyLx4xGKqw6f6hUXPDdaBUzoDUQpmC689IaZccw==', Name: 'Test read only', Description: '', Type: 0, Owner: { Email: 'plus@steno.proton.black', }, CreateTime: 1688992242, Members: [ { ID: 'IlnTbqicN-2HfUGIn-ki8bqZfLqNj5ErUB0z24Qx5g-4NvrrIc6GLvEpj2EPfwGDv28aKYVRRrSgEFhR_zhlkA==', Permissions: 96, Email: 'joshua@yomail.com', AddressID: 'p5DPgsgSOQhwxfZmy4A-vVIxHd40lH8xRVg_4ulz69pz7Ox7ibSa2QXEbMg151clLRB-CQQTCRNteaIBHL_iUg==', CalendarID: 'W6E2R1LyNeueUxuR_1VjbM3M2UoGKPqPrRhGwrqRlLyoweZNyLx4xGKqw6f6hUXPDdaBUzoDUQpmC689IaZccw==', Name: 'Test read only', Description: '', Color: '#0F735A', Display: 1, Priority: 3, Flags: 1, }, ], Color: '#0F735A', Display: 1, Email: 'joshua@yomail.com', Flags: 1, Permissions: 96, Priority: 1, }; const writeSharedCalendar = { ID: 'BvbqbySUPo9uWW_eR8tLA13NUsQMz3P4Zhw4UnpvrKqURnrHlE6L2Au0nplHfHlVXFgGz4L4hJ9-BYllOL-L5g==', Name: 'Test Write', Description: '', Type: 0, Owner: { Email: 'plus@steno.proton.black', }, CreateTime: 1688992227, Members: [ { ID: 'QVcbf04GzTJosFX36v47-82MiZqyItZKjbWdo5O8O5WAJQHPKlnGBfmf290e2jpbWRL3U5415dWDUSwXoWJJHQ==', Permissions: 112, Email: 'joshua@yomail.com', AddressID: 'p5DPgsgSOQhwxfZmy4A-vVIxHd40lH8xRVg_4ulz69pz7Ox7ibSa2QXEbMg151clLRB-CQQTCRNteaIBHL_iUg==', CalendarID: 'BvbqbySUPo9uWW_eR8tLA13NUsQMz3P4Zhw4UnpvrKqURnrHlE6L2Au0nplHfHlVXFgGz4L4hJ9-BYllOL-L5g==', Name: 'Test Write', Description: '', Color: '#807304', Display: 1, Priority: 2, Flags: 1, }, ], Color: '#807304', Display: 1, Email: 'joshua@yomail.com', Flags: 1, Permissions: 112, Priority: 1, }; const baseArgs = { calendar: ownedCalendar, defaultCalendar, holidaysCalendars: [], canEdit: true, } as unknown as ComponentProps<typeof CalendarSubpageHeaderSection>; describe('CalendarSubpageHeaderSection', () => { describe('when calendar is owned', () => { it('should display user calendar address', () => { mockUseContactEmailsCache(); render(<CalendarSubpageHeaderSection {...baseArgs} />); expect(screen.getByText('joshua@yomail.com')); }); }); describe('when calendar is default one', () => { it('should display a badge', () => { mockUseContactEmailsCache(); render(<CalendarSubpageHeaderSection {...baseArgs} />); expect(screen.getByText('Default')); }); }); describe('when calendar is shared', () => { describe('when user has only read access', () => { it('should display `View only` and owner address', () => { mockUseContactEmailsCache(); const props = { ...baseArgs, calendar: readonlySharedCalendar }; render(<CalendarSubpageHeaderSection {...props} />); expect(screen.getByText('Shared by plus@steno.proton.black')); expect(screen.getByText('View only • joshua@yomail.com')); }); }); describe('when user has write access', () => { it('should display owner address', () => { mockUseContactEmailsCache(); const props = { ...baseArgs, calendar: writeSharedCalendar }; render(<CalendarSubpageHeaderSection {...props} />); expect(screen.getByText('Shared by plus@steno.proton.black')); expect(screen.queryByText('View only')).not.toBeInTheDocument(); }); }); }); });
5,959
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/CalendarSubpageHeaderSection.tsx
import { c } from 'ttag'; import { ButtonLike, Href } from '@proton/atoms'; import { Alert, Icon, Tooltip, useModalState } from '@proton/components/components'; import CalendarSelectIcon from '@proton/components/components/calendarSelect/CalendarSelectIcon'; import { SettingsSectionWide } from '@proton/components/containers'; import { useContactEmailsCache } from '@proton/components/containers/contacts/ContactEmailsProvider'; import { CALENDAR_STATUS_TYPE, getCalendarStatusBadges } from '@proton/shared/lib/calendar/badges'; import { getIsHolidaysCalendar } from '@proton/shared/lib/calendar/calendar'; import { getCalendarNameSubline, getSharedCalendarSubHeaderText, } from '@proton/shared/lib/calendar/sharing/shareProton/shareProton'; import { getCalendarHasSubscriptionParameters } from '@proton/shared/lib/calendar/subscribe/helpers'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { SubscribedCalendar, VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import clsx from '@proton/utils/clsx'; import { CALENDAR_MODAL_TYPE, CalendarModal } from '../calendarModal/CalendarModal'; import HolidaysCalendarModal from '../holidaysCalendarModal/HolidaysCalendarModal'; import CalendarBadge from './CalendarBadge'; interface Props { calendar: VisualCalendar | SubscribedCalendar; defaultCalendar?: VisualCalendar; holidaysCalendars: VisualCalendar[]; onEdit?: () => void; canEdit: boolean; } const CalendarSubpageHeaderSection = ({ calendar, defaultCalendar, holidaysCalendars, onEdit, canEdit }: Props) => { const { contactEmailsMap } = useContactEmailsCache(); const { Name, Description, Color, Email: memberEmail, Type: calendarType, Permissions: memberPermissions, } = calendar; const { isSubscribed, badges, isNotSyncedInfo } = getCalendarStatusBadges(calendar, defaultCalendar?.ID); const url = getCalendarHasSubscriptionParameters(calendar) ? calendar.SubscriptionParameters.URL : undefined; const subHeaderText = getSharedCalendarSubHeaderText(calendar, contactEmailsMap); const subline = getCalendarNameSubline({ calendarType, displayEmail: true, memberEmail, memberPermissions }); const editCalendarText = c('Calendar edit button tooltip').t`Edit calendar`; const [calendarModal, setIsCalendarModalOpen, renderCalendarModal] = useModalState(); const [holidaysCalendarModal, setHolidaysCalendarModalOpen, renderHolidaysCalendarModal] = useModalState(); const handleEdit = () => { if (getIsHolidaysCalendar(calendar)) { setHolidaysCalendarModalOpen(true); } else { setIsCalendarModalOpen(true); } }; return ( <SettingsSectionWide className="container-section-sticky-section"> {renderCalendarModal && ( <CalendarModal calendar={calendar} type={CALENDAR_MODAL_TYPE.VISUAL} onEditCalendar={onEdit} {...calendarModal} /> )} {renderHolidaysCalendarModal && ( <HolidaysCalendarModal {...holidaysCalendarModal} calendar={calendar} holidaysCalendars={holidaysCalendars} type={CALENDAR_MODAL_TYPE.VISUAL} onEditCalendar={onEdit} /> )} <div className="my-6 flex flex-justify-space-between flex-nowrap"> <div className="grid-align-icon"> <CalendarSelectIcon large color={Color} className="mr-3 mt-4 flex-item-noshrink keep-left" /> <h1 className="h1 mb-2 text-bold text-break" title={Name}> {Name} </h1> {Description && <div className="mb-1 text-break">{Description}</div>} {subHeaderText && ( <div className="text-rg text-break mb-1 color-norm" title={subHeaderText}> {subHeaderText} </div> )} <div className="text-ellipsis color-weak" title={subline}> {subline} </div> {isSubscribed && ( <div className={clsx(['text-break text-sm mt-1 color-weak', !url && 'calendar-email'])} title={url || ''} > {url} </div> )} <div className="mt-1"> {badges .filter(({ statusType }) => statusType !== CALENDAR_STATUS_TYPE.ACTIVE) .map(({ statusType, badgeType, text, tooltipText }) => ( <CalendarBadge key={statusType} badgeType={badgeType} text={text} tooltipText={isNotSyncedInfo ? undefined : tooltipText} /> ))} </div> {isNotSyncedInfo && ( <Alert className="my-4" type="warning"> {isNotSyncedInfo.longText} {isNotSyncedInfo.isSyncing ? null : ( <div> <Href href={getKnowledgeBaseUrl('/subscribe-to-external-calendar#troubleshooting')}> {c('Link').t`Learn more`} </Href> </div> )} </Alert> )} </div> <span className="ml-4 pt-2 flex-item-noshrink"> <Tooltip title={editCalendarText}> <ButtonLike shape="outline" onClick={handleEdit} icon disabled={!canEdit}> <Icon name="pen" alt={editCalendarText} /> </ButtonLike> </Tooltip> </span> </div> </SettingsSectionWide> ); }; export default CalendarSubpageHeaderSection;
5,960
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/CalendarTimeSection.tsx
import { CalendarUserSettings } from '@proton/shared/lib/interfaces/calendar'; import { SettingsSection } from '../../account'; import AutoDetectPrimaryTimezoneSection from './AutoDetectPrimaryTimezoneSection'; import PrimaryTimezoneSection from './PrimaryTimezoneSection'; import SecondaryTimezoneSection from './SecondaryTimezoneSection'; import ShowSecondaryTimezoneToggleSection from './ShowSecondaryTimezoneToggleSection'; interface Props { calendarUserSettings: CalendarUserSettings; } const CalendarTimeSection = ({ calendarUserSettings }: Props) => { return ( <SettingsSection> <AutoDetectPrimaryTimezoneSection calendarUserSettings={calendarUserSettings} /> <PrimaryTimezoneSection calendarUserSettings={calendarUserSettings} /> <ShowSecondaryTimezoneToggleSection calendarUserSettings={calendarUserSettings} /> <SecondaryTimezoneSection calendarUserSettings={calendarUserSettings} /> </SettingsSection> ); }; export default CalendarTimeSection;
5,961
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/CalendarsSection.test.tsx
import { Router } from 'react-router-dom'; import { render, screen } from '@testing-library/react'; import { createMemoryHistory } from 'history'; import createCache from '@proton/shared/lib/helpers/cache'; import { UserModel } from '@proton/shared/lib/interfaces'; import { generateSimpleCalendar } from '@proton/testing/lib/builders'; import { CacheProvider } from '../../cache'; import ModalsProvider from '../../modals/Provider'; import CalendarsSection, { CalendarsSectionProps } from './CalendarsSection'; jest.mock('../../../hooks/useAddresses', () => ({ __esModule: true, default: jest.fn(() => [ [ { Email: 'test@pm.gg', Status: 1, Receive: 1, Send: 1, }, ], ]), useGetAddresses: jest.fn(), })); jest.mock('../../../hooks/useEventManager', () => () => ({})); jest.mock('../../eventManager/calendar/useCalendarsInfoListener', () => () => ({})); jest.mock('../../eventManager/calendar/ModelEventManagerProvider', () => ({ useCalendarModelEventManager: jest.fn(), })); jest.mock('@proton/components/hooks/useConfig', () => () => ({ APP_NAME: 'proton-calendar', APP_VERSION: 'test' })); jest.mock('@proton/components/hooks/useAddresses', () => ({ __esModule: true, default: jest.fn(() => [ [ { Email: 'test@pm.gg', Status: 1, Receive: 1, Send: 1, }, ], ]), useGetAddresses: jest.fn(), })); function renderComponent(props?: Partial<CalendarsSectionProps>) { const defaultProps: CalendarsSectionProps = { addresses: [], calendars: [], children: null, // defaultCalendarID?: string, user: { hasPaidMail: false } as UserModel, // loading?: boolean, // onSetDefault?: (id: string) => Promise<void>, onEdit: jest.fn(), onDelete: jest.fn(), // onExport?: (calendar: Calendar) => void, }; return ( <ModalsProvider> <Router history={createMemoryHistory()}> <CacheProvider cache={createCache()}> <CalendarsSection {...defaultProps} {...props} /> </CacheProvider> </Router> </ModalsProvider> ); } describe('CalendarsSection', () => { it('renders properly', () => { render( renderComponent({ calendars: [generateSimpleCalendar(1, { name: 'calendar1' })], }) ); expect(screen.getByText('calendar1')).toBeInTheDocument(); }); it('does not render a table when no calendars are provided', () => { render(renderComponent()); expect(screen.queryByRole('table')).not.toBeInTheDocument(); }); });
5,962
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/CalendarsSection.tsx
import { ReactNode } from 'react'; import { Address, UserModel } from '@proton/shared/lib/interfaces'; import { SubscribedCalendar, VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import { SettingsSectionWide } from '../../account'; import CalendarsTable from './CalendarsTable'; export interface CalendarsSectionProps { calendars: (VisualCalendar | SubscribedCalendar)[]; defaultCalendarID?: string; addresses: Address[]; user: UserModel; children?: ReactNode; onSetDefault?: (id: string) => Promise<void>; onEdit?: (calendar: VisualCalendar) => void; onDelete?: (id: string) => Promise<void>; onExport?: (calendar: VisualCalendar) => void; nameHeader?: string; } const CalendarsSection = ({ calendars, defaultCalendarID, addresses, user, children, onEdit, onSetDefault, onDelete, onExport, nameHeader, ...rest }: CalendarsSectionProps) => { return ( <SettingsSectionWide {...rest}> {children} {!!calendars.length && ( <CalendarsTable nameHeader={nameHeader} calendars={calendars} defaultCalendarID={defaultCalendarID} addresses={addresses} user={user} onSetDefault={onSetDefault} /> )} </SettingsSectionWide> ); }; export default CalendarsSection;
5,963
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/CalendarsSettingsSection.test.tsx
import { Router } from 'react-router'; import { render, screen, within } from '@testing-library/react'; import { createMemoryHistory } from 'history'; import { MAX_CALENDARS_FREE, MAX_CALENDARS_PAID } from '@proton/shared/lib/calendar/constants'; import { ADDRESS_RECEIVE, ADDRESS_SEND, ADDRESS_STATUS, BRAND_NAME, MAIL_SHORT_APP_NAME, } from '@proton/shared/lib/constants'; import { RequireOnly, UserModel } from '@proton/shared/lib/interfaces'; import { SubscribedCalendar, VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import { addressBuilder, generateHolidaysCalendars, generateOwnedPersonalCalendars, generateSharedCalendars, generateSubscribedCalendars, } from '@proton/testing/lib/builders'; import { IconName } from '../../../components'; import CalendarsSettingsSection, { CalendarsSettingsSectionProps } from './CalendarsSettingsSection'; jest.mock('../../../hooks/useCalendarShareInvitations', () => jest.fn().mockReturnValue({ loading: false, invitations: [], }) ); jest.mock('../../../hooks/useCalendarShareInvitationActions', () => jest.fn().mockReturnValue({ accept: () => {}, reject: () => {}, }) ); jest.mock('../../../hooks/useConfig', () => () => ({ CLIENT_TYPE: 1, CLIENT_SECRET: 'not_so_secret', APP_VERSION: 'test', APP_NAME: 'proton-calendar', API_URL: 'api', LOCALES: {}, DATE_VERSION: 'test', COMMIT: 'test', BRANCH: 'test', SENTRY_DSN: 'test', VERSION_PATH: 'test', })); jest.mock('../../../hooks/useAppTitle', () => jest.fn().mockReturnValue(undefined)); jest.mock('../../../hooks/useApi', () => jest.fn(() => jest.fn().mockResolvedValue({}))); jest.mock('../../../hooks/useEventManager', () => () => ({})); jest.mock('../../eventManager/calendar/useCalendarsInfoListener', () => () => ({})); jest.mock('../../eventManager/calendar/ModelEventManagerProvider', () => ({ useCalendarModelEventManager: jest.fn(() => ({ call: jest.fn() })), })); jest.mock('@proton/components/hooks/useNotifications', () => () => ({})); jest.mock('@proton/components/hooks/useFeature', () => jest.fn(() => ({ feature: { Value: true } }))); jest.mock('@proton/components/hooks/useEarlyAccess', () => () => ({})); jest.mock('@proton/components/containers/calendar/hooks/useHolidaysDirectory', () => ({ __esModule: true, default: jest.fn(() => []), })); let memoryHistory = createMemoryHistory(); const renderComponent = ({ user, addresses = [addressBuilder()], calendars, myCalendars, subscribedCalendars, sharedCalendars, unknownCalendars = [], holidaysCalendars = [], }: RequireOnly< CalendarsSettingsSectionProps, 'user' | 'calendars' | 'myCalendars' | 'sharedCalendars' | 'subscribedCalendars' >) => { const config = { icon: 'calendar' as IconName, to: '/calendars', text: 'Calendars', subsections: [ { text: 'My calendars', id: 'my-calendars' }, { text: 'Other calendars', id: 'other-calendars' }, ], }; render( <Router history={memoryHistory}> <CalendarsSettingsSection config={config} user={user} addresses={addresses} calendars={calendars} myCalendars={myCalendars} subscribedCalendars={subscribedCalendars} sharedCalendars={sharedCalendars} holidaysCalendars={holidaysCalendars} unknownCalendars={unknownCalendars} /> </Router> ); }; describe('My calendars section', () => { const createCalendarText = `Create calendar`; const addCalendarText = `Add calendar from URL`; const addHolidaysCalendarText = `Add public holidays`; const limitReachedFreeText = `You've reached the maximum number of calendars available in your plan. To add a new calendar, remove another calendar or upgrade your ${BRAND_NAME} plan to a ${MAIL_SHORT_APP_NAME} paid plan.`; const limitReachedPaidText = `You've reached the maximum number of calendars available in your plan. To add a new calendar, remove an existing one.`; describe('for a Mail free user', () => { it('allows the user to create both personal and other calendars if under the limit', () => { const user = { isFree: false, hasPaidMail: false, hasNonDelinquentScope: true } as UserModel; const myCalendars: VisualCalendar[] = []; const sharedCalendars: VisualCalendar[] = []; const subscribedCalendars = generateSubscribedCalendars(1); const calendars = [...myCalendars, ...sharedCalendars, ...subscribedCalendars]; renderComponent({ user, calendars, myCalendars, sharedCalendars, subscribedCalendars, }); expect(screen.queryAllByText(limitReachedFreeText)).toHaveLength(0); expect(screen.queryAllByText(createCalendarText)).toHaveLength(1); expect(screen.queryAllByText(addCalendarText)).toHaveLength(1); expect(screen.queryAllByText(addHolidaysCalendarText)).toHaveLength(1); }); it('displays the limit reached message in both "My calendars" and "Other calendars" section when the user reaches the calendar limit with personal owned calendars', () => { const user = { isFree: false, hasPaidMail: false, hasNonDelinquentScope: true } as UserModel; const myCalendars = generateOwnedPersonalCalendars(MAX_CALENDARS_FREE); const sharedCalendars: VisualCalendar[] = []; const subscribedCalendars: SubscribedCalendar[] = []; const calendars = [...myCalendars, ...sharedCalendars, ...subscribedCalendars]; renderComponent({ user, calendars, myCalendars, sharedCalendars, subscribedCalendars, }); expect(screen.queryAllByText(limitReachedFreeText)).toHaveLength(2); expect(screen.queryAllByText(createCalendarText)).toHaveLength(0); expect(screen.queryAllByText(addCalendarText)).toHaveLength(0); }); it('displays the limit reached message only in "Other calendars" section when the user reached the calendar limit with shared and subscribed calendars (only possible for pre-plans-migration users), and allows creation of owned personal calendars', () => { const user = { isFree: false, hasPaidMail: false, hasNonDelinquentScope: true } as UserModel; const myCalendars: VisualCalendar[] = []; const sharedCalendars = generateSharedCalendars(MAX_CALENDARS_FREE - 2); const subscribedCalendars = generateSubscribedCalendars(2); const calendars = [...myCalendars, ...sharedCalendars, ...subscribedCalendars]; renderComponent({ user, calendars, myCalendars, sharedCalendars, subscribedCalendars, }); expect(screen.queryAllByText(limitReachedFreeText)).toHaveLength(1); expect(screen.queryAllByText(createCalendarText)).toHaveLength(1); }); it('prevents user from creating MAX_CALENDARS_FREE other calendars by displaying limit reached message', () => { const user = { isFree: false, hasPaidMail: false, hasNonDelinquentScope: true } as UserModel; const myCalendars: VisualCalendar[] = []; const sharedCalendars = generateSharedCalendars(1); const subscribedCalendars = generateSubscribedCalendars(MAX_CALENDARS_FREE - 2); const calendars = [...myCalendars, ...sharedCalendars, ...subscribedCalendars]; renderComponent({ user, calendars, myCalendars, sharedCalendars, subscribedCalendars, }); expect(screen.queryAllByText(limitReachedFreeText)).toHaveLength(1); expect(screen.queryAllByText(createCalendarText)).toHaveLength(1); expect(screen.queryAllByText(addCalendarText)).toHaveLength(0); expect(screen.queryAllByText(addHolidaysCalendarText)).toHaveLength(0); }); it('prevents user without active addresses from creating personal or other calendars', () => { const user = { isFree: true, hasPaidMail: false, hasNonDelinquentScope: true } as UserModel; const addresses = [ { ...addressBuilder(), Receive: ADDRESS_RECEIVE.RECEIVE_NO, Send: ADDRESS_SEND.SEND_NO, Status: ADDRESS_STATUS.STATUS_DISABLED, }, ]; const myCalendars = generateOwnedPersonalCalendars(0); const sharedCalendars = generateSharedCalendars(0); const subscribedCalendars = generateSubscribedCalendars(0); const calendars = [...myCalendars, ...sharedCalendars, ...subscribedCalendars]; renderComponent({ user, addresses, calendars, myCalendars, sharedCalendars, subscribedCalendars, }); const createCalendarButton = screen.getByText(createCalendarText); const addCalendarButton = screen.getByText(addCalendarText); const addHolidaysCalendarButton = screen.getByText(addHolidaysCalendarText); expect(screen.queryAllByText(limitReachedPaidText)).toHaveLength(0); expect(createCalendarButton).toBeInTheDocument(); expect(createCalendarButton).toBeDisabled(); expect(addCalendarButton).toBeInTheDocument(); expect(addCalendarButton).toBeDisabled(); expect(addHolidaysCalendarButton).toBeInTheDocument(); expect(addHolidaysCalendarButton).toBeDisabled(); }); it('prevents delinquent user from creating personal or other calendars', () => { const user = { isFree: true, hasPaidMail: false, hasNonDelinquentScope: false } as UserModel; const myCalendars = generateOwnedPersonalCalendars(0); const sharedCalendars = generateSharedCalendars(0); const subscribedCalendars = generateSubscribedCalendars(0); const calendars = [...myCalendars, ...sharedCalendars, ...subscribedCalendars]; renderComponent({ user, calendars, myCalendars, sharedCalendars, subscribedCalendars, }); const createCalendarButton = screen.getByText(createCalendarText); const addCalendarButton = screen.getByText(addCalendarText); const addHolidaysCalendarButton = screen.getByText(addHolidaysCalendarText); expect(screen.queryAllByText(limitReachedPaidText)).toHaveLength(0); expect(createCalendarButton).toBeInTheDocument(); expect(createCalendarButton).toBeDisabled(); expect(addCalendarButton).toBeInTheDocument(); expect(addCalendarButton).toBeDisabled(); expect(addHolidaysCalendarButton).toBeInTheDocument(); expect(addHolidaysCalendarButton).toBeDisabled(); }); }); describe('for a Mail paid user', () => { it('allows the user to create both personal and other calendars if under the limit', () => { const user = { isFree: false, hasPaidMail: true, hasNonDelinquentScope: true } as UserModel; const myCalendars = generateOwnedPersonalCalendars(7); const sharedCalendars = generateSharedCalendars(4); const subscribedCalendars = generateSubscribedCalendars(5); const calendars = [...myCalendars, ...sharedCalendars, ...subscribedCalendars]; renderComponent({ user, calendars, myCalendars, sharedCalendars, subscribedCalendars, }); expect(screen.queryAllByText(limitReachedFreeText)).toHaveLength(0); expect(screen.queryAllByText(createCalendarText)).toHaveLength(1); expect(screen.queryAllByText(addCalendarText)).toHaveLength(1); expect(screen.queryAllByText(addHolidaysCalendarText)).toHaveLength(1); }); it('displays the limit reached message in both "My calendars" and "Other calendars" section when the user reaches the calendar limit with personal owned calendars', () => { const user = { isFree: false, hasPaidMail: true, hasNonDelinquentScope: true } as UserModel; const myCalendars = generateOwnedPersonalCalendars(MAX_CALENDARS_PAID); const sharedCalendars: VisualCalendar[] = []; const subscribedCalendars: SubscribedCalendar[] = []; const calendars = [...myCalendars, ...sharedCalendars, ...subscribedCalendars]; renderComponent({ user, calendars, myCalendars, sharedCalendars, subscribedCalendars, }); expect(screen.queryAllByText(limitReachedPaidText)).toHaveLength(2); expect(screen.queryAllByText(createCalendarText)).toHaveLength(0); expect(screen.queryAllByText(addCalendarText)).toHaveLength(0); expect(screen.queryAllByText(addHolidaysCalendarText)).toHaveLength(0); }); it('prevents user from creating MAX_CALENDARS_PAID other calendars by display limit reached message', () => { const user = { isFree: false, hasPaidMail: true, hasNonDelinquentScope: true } as UserModel; const myCalendars: VisualCalendar[] = []; const sharedCalendars = generateSharedCalendars(MAX_CALENDARS_PAID - 2); const subscribedCalendars = generateSubscribedCalendars(1); const calendars = [...myCalendars, ...sharedCalendars, ...subscribedCalendars]; renderComponent({ user, calendars, myCalendars, sharedCalendars, subscribedCalendars, }); expect(screen.queryAllByText(limitReachedPaidText)).toHaveLength(1); expect(screen.queryAllByText(createCalendarText)).toHaveLength(1); expect(screen.queryAllByText(addCalendarText)).toHaveLength(0); expect(screen.queryAllByText(addHolidaysCalendarText)).toHaveLength(0); }); it('prevents user without active addresses from creating personal or other calendars', () => { const user = { isFree: false, hasPaidMail: true, hasNonDelinquentScope: true } as UserModel; const addresses = [ { ...addressBuilder(), Receive: ADDRESS_RECEIVE.RECEIVE_NO, Send: ADDRESS_SEND.SEND_NO, Status: ADDRESS_STATUS.STATUS_DISABLED, }, ]; const myCalendars = generateOwnedPersonalCalendars(2); const sharedCalendars = generateSharedCalendars(0); const subscribedCalendars = generateSubscribedCalendars(0); const calendars = [...myCalendars, ...sharedCalendars, ...subscribedCalendars]; renderComponent({ user, addresses, calendars, myCalendars, sharedCalendars, subscribedCalendars, }); const createCalendarButton = screen.getByText(createCalendarText); const addCalendarButton = screen.getByText(addCalendarText); const addHolidaysCalendarButton = screen.getByText(addHolidaysCalendarText); expect(screen.queryAllByText(limitReachedPaidText)).toHaveLength(0); expect(createCalendarButton).toBeInTheDocument(); expect(createCalendarButton).toBeDisabled(); expect(addCalendarButton).toBeInTheDocument(); expect(addCalendarButton).toBeDisabled(); expect(addHolidaysCalendarButton).toBeInTheDocument(); expect(addHolidaysCalendarButton).toBeDisabled(); }); it('prevents delinquent user from creating personal or other calendars', () => { const user = { isFree: false, hasPaidMail: true, hasNonDelinquentScope: false } as UserModel; const myCalendars = generateOwnedPersonalCalendars(1); const sharedCalendars = generateSharedCalendars(1); const subscribedCalendars = generateSubscribedCalendars(1); const calendars = [...myCalendars, ...sharedCalendars, ...subscribedCalendars]; renderComponent({ user, calendars, myCalendars, sharedCalendars, subscribedCalendars, }); const createCalendarButton = screen.getByText(createCalendarText); const addCalendarButton = screen.getByText(addCalendarText); const addHolidaysCalendarButton = screen.getByText(addHolidaysCalendarText); expect(screen.queryAllByText(limitReachedPaidText)).toHaveLength(0); expect(createCalendarButton).toBeInTheDocument(); expect(createCalendarButton).toBeDisabled(); expect(addCalendarButton).toBeInTheDocument(); expect(addCalendarButton).toBeDisabled(); expect(addHolidaysCalendarButton).toBeInTheDocument(); expect(addHolidaysCalendarButton).toBeDisabled(); }); }); describe("displays user's calendars", () => { it('in their respective sections', async () => { const user = { isFree: false, hasPaidMail: true, hasNonDelinquentScope: true } as UserModel; const myCalendars = generateOwnedPersonalCalendars(2, [{ name: 'Calendar 1' }, { name: 'Calendar 2' }]); const subscribedCalendars = generateSubscribedCalendars(2, [ { name: 'Calendar 3' }, { name: 'Calendar 4' }, ]); const sharedCalendars = generateSharedCalendars(2, [{ name: 'Calendar 5' }, { name: 'Calendar 6' }]); const holidaysCalendars = generateHolidaysCalendars(2, [{ name: 'Calendar 7' }, { name: 'Calendar 8' }]); const calendars = [...myCalendars, ...sharedCalendars, ...holidaysCalendars, ...subscribedCalendars]; renderComponent({ user, calendars, myCalendars, sharedCalendars, holidaysCalendars, subscribedCalendars, }); const myCalendarsSection = await screen.findByTestId('my-calendars-section'); const susbcribedCalendarsSection = await screen.findByTestId('subscribed-calendars-section'); const sharedCalendarsSection = await screen.findByTestId('shared-calendars-section'); const holidaysCalendarsSection = await screen.findByTestId('holidays-calendars-section'); within(myCalendarsSection).getByText(myCalendars[0].Name); within(myCalendarsSection).getByText(myCalendars[1].Name); within(susbcribedCalendarsSection).getByText(subscribedCalendars[0].Name); within(susbcribedCalendarsSection).getByText(subscribedCalendars[1].Name); within(sharedCalendarsSection).getByText(`${sharedCalendars[0].Name} (${sharedCalendars[0].Owner.Email})`); within(sharedCalendarsSection).getByText(`${sharedCalendars[1].Name} (${sharedCalendars[1].Owner.Email})`); within(holidaysCalendarsSection).getByText(holidaysCalendars[0].Name); within(holidaysCalendarsSection).getByText(holidaysCalendars[1].Name); }); }); });
5,964
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/CalendarsSettingsSection.tsx
import { getHasUserReachedCalendarsLimit } from '@proton/shared/lib/calendar/calendarLimits'; import { filterOutExpiredInvitations, getPendingInvitations, } from '@proton/shared/lib/calendar/sharing/shareProton/shareProton'; import { getActiveAddresses } from '@proton/shared/lib/helpers/address'; import { Address, UserModel } from '@proton/shared/lib/interfaces'; import { HolidaysDirectoryCalendar, SubscribedCalendar, VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import { MyCalendarsSection, PrivateMainAreaLoading, PrivateMainSettingsArea, SectionConfig } from '../..'; import { useCalendarShareInvitations } from '../../../hooks'; import OtherCalendarsSection from '../settings/OtherCalendarsSection'; export interface CalendarsSettingsSectionProps { config: SectionConfig; user: UserModel; addresses: Address[]; calendars: VisualCalendar[]; myCalendars: VisualCalendar[]; subscribedCalendars: SubscribedCalendar[]; sharedCalendars: VisualCalendar[]; holidaysCalendars: VisualCalendar[]; holidaysDirectory?: HolidaysDirectoryCalendar[]; unknownCalendars: VisualCalendar[]; defaultCalendar?: VisualCalendar; } const CalendarsSettingsSection = ({ config, user, addresses, calendars, myCalendars, subscribedCalendars, sharedCalendars, holidaysCalendars, holidaysDirectory, unknownCalendars, defaultCalendar, }: CalendarsSettingsSectionProps) => { const { invitations: calendarInvitations, loading: loadingCalendarInvitations } = useCalendarShareInvitations(); const { isCalendarsLimitReached, isOtherCalendarsLimitReached } = getHasUserReachedCalendarsLimit( calendars, !user.hasPaidMail ); const canAddCalendar = user.hasNonDelinquentScope && getActiveAddresses(addresses).length > 0; if (loadingCalendarInvitations) { return <PrivateMainAreaLoading />; } return ( <PrivateMainSettingsArea config={config}> <MyCalendarsSection myCalendars={myCalendars} defaultCalendar={defaultCalendar} addresses={addresses} user={user} canAdd={canAddCalendar} isCalendarsLimitReached={isCalendarsLimitReached} /> <OtherCalendarsSection subscribedCalendars={subscribedCalendars} sharedCalendars={sharedCalendars} calendarInvitations={filterOutExpiredInvitations(getPendingInvitations(calendarInvitations))} holidaysCalendars={holidaysCalendars} holidaysDirectory={holidaysDirectory} unknownCalendars={unknownCalendars} addresses={addresses} user={user} canAdd={canAddCalendar} isCalendarsLimitReached={isOtherCalendarsLimitReached} /> </PrivateMainSettingsArea> ); }; export default CalendarsSettingsSection;
5,965
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/CalendarsTable.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Button, ButtonLike } from '@proton/atoms'; import { getCalendarStatusBadges } from '@proton/shared/lib/calendar/badges'; import { getCalendarSubpagePath } from '@proton/shared/lib/calendar/settingsRoutes'; import { APPS } from '@proton/shared/lib/constants'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { Address, UserModel } from '@proton/shared/lib/interfaces'; import { SubscribedCalendar, VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import clsx from '@proton/utils/clsx'; import { Icon, Info, SettingsLink, Table, TableBody, TableCell, TableHeader, TableHeaderCell, TableRow, Tooltip, } from '../../../components'; import CalendarSelectIcon from '../../../components/calendarSelect/CalendarSelectIcon'; import CalendarBadge from './CalendarBadge'; interface Props { calendars: (VisualCalendar | SubscribedCalendar)[]; defaultCalendarID?: string; addresses: Address[]; user: UserModel; onSetDefault?: (id: string) => Promise<void>; nameHeader?: string; } const CalendarsTable = ({ calendars, defaultCalendarID, addresses, user, onSetDefault, nameHeader: inputNameHeader, }: Props) => { const { hasNonDelinquentScope } = user; const [isLoading, setIsLoading] = useState<string>(); const hasSingleAddress = addresses.length === 1; if (!calendars.length) { return null; } const nameHeader = inputNameHeader || c('Header').t`Name`; const statusHeader = ( <div className="flex flex-align-items-center"> <span className="mr-2">{c('Header').t`Status`}</span> <Info url={getKnowledgeBaseUrl('/calendar-status')} /> </div> ); return ( <Table hasActions responsive="cards"> <TableHeader> <TableRow> <TableHeaderCell className="text-left w-1/2">{nameHeader}</TableHeaderCell> <TableHeaderCell className="w-1/5">{statusHeader}</TableHeaderCell> <TableHeaderCell>{c('Header').t`Actions`}</TableHeaderCell> </TableRow> </TableHeader> <TableBody> {calendars.map((calendar, index) => { const { ID, Name, Color, Email } = calendar; const { isDisabled, isDefault, isSubscribed, badges } = getCalendarStatusBadges( calendar, defaultCalendarID ); return ( <TableRow key={ID}> <TableCell label={nameHeader}> <div key="id"> <div className="grid-align-icon-center"> <CalendarSelectIcon color={Color} className="mr-3 flex-item-noshrink keep-left" /> <div className="text-ellipsis" title={Name}> {Name} </div> {!hasSingleAddress && ( <div className={clsx(['text-ellipsis text-sm m-0 color-weak'])} style={{ '--index': index }} title={Email} > {Email} </div> )} </div> </div> </TableCell> <TableCell label={statusHeader}> <div data-testid="calendar-settings-page:calendar-status" key="status"> {badges.map(({ statusType, badgeType, text, tooltipText }) => ( <CalendarBadge key={statusType} badgeType={badgeType} text={text} tooltipText={tooltipText} className="mb-1 mr-2" /> ))} </div> </TableCell> <TableCell> <div className="inline-flex"> {!isSubscribed && !isDisabled && !isDefault && hasNonDelinquentScope && onSetDefault && ( <Button disabled={!!isLoading} loading={isLoading === ID} onClick={async () => { setIsLoading(ID); await onSetDefault(ID); setIsLoading(undefined); }} size="small" shape="outline" className="mr-2" >{c('Action').t`Set as default`}</Button> )} <Tooltip title={c('Calendar table settings button tooltip').t`Open settings`}> <ButtonLike as={SettingsLink} app={APPS.PROTONCALENDAR} path={getCalendarSubpagePath(ID)} shape="outline" size="small" icon disabled={!!isLoading} className="flex-item-noshrink" > <Icon name="cog-wheel" alt={c('Calendar table settings button tooltip').t`Open settings`} /> </ButtonLike> </Tooltip> </div> </TableCell> </TableRow> ); })} </TableBody> </Table> ); }; export default CalendarsTable;
5,966
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/InviteLocaleSelector.tsx
import { c } from 'ttag'; import { getClosestLocaleCode } from '@proton/shared/lib/i18n/helper'; import { Nullable } from '@proton/shared/lib/interfaces'; import { TtagLocaleMap } from '@proton/shared/lib/interfaces/Locale'; import { Option, SelectTwo } from '../../../components'; import { useConfig, useUserSettings } from '../../../hooks'; interface Props { id: string; className?: string; loading: boolean; disabled?: boolean; locale: Nullable<string>; locales: TtagLocaleMap; onChange: (locale: Nullable<string>) => void; } const InviteLocaleSelector = ({ className = 'field w-full', loading = false, disabled = false, locale, locales, onChange, ...rest }: Props) => { const { LOCALES = {} } = useConfig(); const [userSettings] = useUserSettings(); const defaultLanguage = LOCALES[getClosestLocaleCode(userSettings?.Locale, locales)]; const options: { text: string; value: Nullable<string> }[] = Object.keys(LOCALES).map((value) => ({ text: LOCALES[value], value, })); options.unshift({ text: c('Label').t`Default language (${defaultLanguage})`, value: null, }); const handleChange = async (locale: Nullable<string>) => { const localeCode = locale === null ? null : getClosestLocaleCode(locale, locales); onChange(localeCode); }; return ( <SelectTwo disabled={loading || disabled} className={className} title={c('Action').t`Select language for invitation emails`} value={locale} onChange={({ value }) => handleChange(value)} {...rest} > {options.map(({ text, value }) => ( <Option key={value} value={value} title={text} /> ))} </SelectTwo> ); }; export default InviteLocaleSelector;
5,967
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/MyCalendarsSection.tsx
import { ReactNode } from 'react'; import { c } from 'ttag'; import { Button, ButtonLike, Card, Href } from '@proton/atoms'; import { SettingsParagraph } from '@proton/components/containers'; import { removeCalendar, updateCalendarUserSettings } from '@proton/shared/lib/api/calendars'; import { getProbablyActiveCalendars } from '@proton/shared/lib/calendar/calendar'; import { getCalendarsLimitReachedText } from '@proton/shared/lib/calendar/calendarLimits'; import { APP_UPSELL_REF_PATH, CALENDAR_UPSELL_PATHS, UPSELL_COMPONENT } from '@proton/shared/lib/constants'; import { addUpsellPath, getUpsellRef } from '@proton/shared/lib/helpers/upsell'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { Address, UserModel } from '@proton/shared/lib/interfaces'; import { ModalWithProps } from '@proton/shared/lib/interfaces/Modal'; import { VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import { Alert, PrimaryButton, Prompt, SettingsLink, useModalState } from '../../../components'; import { useApi, useEventManager, useNotifications } from '../../../hooks'; import { useModalsMap } from '../../../hooks/useModalsMap'; import { CalendarModal } from '../calendarModal/CalendarModal'; import { ExportModal } from '../exportModal/ExportModal'; import CalendarsSection from './CalendarsSection'; type ModalsMap = { calendarModal: ModalWithProps<{ calendars?: VisualCalendar[]; defaultCalendarID?: string; calendar?: VisualCalendar; }>; exportCalendarModal: ModalWithProps<{ exportCalendar?: VisualCalendar; }>; deleteCalendarModal: ModalWithProps<{ defaultCalendarWarning?: ReactNode; onClose: () => void; onConfirm: () => void; }>; }; interface Props { addresses: Address[]; user: UserModel; myCalendars: VisualCalendar[]; defaultCalendar?: VisualCalendar; isCalendarsLimitReached: boolean; canAdd: boolean; } const MyCalendarsSection = ({ addresses, user, myCalendars, defaultCalendar, isCalendarsLimitReached, canAdd, }: Props) => { const api = useApi(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const { modalsMap, updateModal, closeModal } = useModalsMap<ModalsMap>({ calendarModal: { isOpen: false }, exportCalendarModal: { isOpen: false }, deleteCalendarModal: { isOpen: false }, }); const [{ onExit: onExitCalendarModal, ...calendarModalProps }, setIsCalendarModalOpen] = useModalState(); const [{ open: isExportModalOpen, onExit: onExitExportModal, ...exportModalProps }, setIsExportModalOpen] = useModalState(); const defaultCalendarID = defaultCalendar?.ID; const isFreeUser = !user.hasPaidMail; const calendarsLimitReachedText = getCalendarsLimitReachedText(isFreeUser).combinedText; const handleCreateCalendar = () => { setIsCalendarModalOpen(true); updateModal('calendarModal', { isOpen: true, props: { calendars: myCalendars, defaultCalendarID }, }); }; const handleEditCalendar = (calendar: VisualCalendar) => { setIsCalendarModalOpen(true); updateModal('calendarModal', { isOpen: true, props: { calendar }, }); }; const handleSetDefaultCalendar = async (calendarID: string) => { await api(updateCalendarUserSettings({ DefaultCalendarID: calendarID })); await call(); createNotification({ text: c('Success').t`Default calendar updated` }); }; const handleDeleteCalendar = async (id: string) => { const isDeleteDefaultCalendar = id === defaultCalendarID; const firstRemainingCalendar = getProbablyActiveCalendars(myCalendars).find( ({ ID: calendarID }) => calendarID !== id ); // If deleting the default calendar, the new calendar to make default is either the first active calendar or null if there is none. const newDefaultCalendarID = isDeleteDefaultCalendar ? (firstRemainingCalendar && firstRemainingCalendar.ID) || null : undefined; await new Promise<void>((resolve, reject) => { const calendarName = firstRemainingCalendar ? ( <span key="bold-calendar-name" className="text-bold text-break"> {firstRemainingCalendar.Name} </span> ) : ( '' ); const defaultCalendarWarning = isDeleteDefaultCalendar && firstRemainingCalendar ? ( <div className="mb-4">{c('Info').jt`${calendarName} will be set as default calendar.`}</div> ) : null; updateModal('deleteCalendarModal', { isOpen: true, props: { onClose: () => { reject(); closeModal('deleteCalendarModal'); }, onConfirm: () => { resolve(); closeModal('deleteCalendarModal'); }, defaultCalendarWarning, }, }); }); await api(removeCalendar(id)); // null is a valid default calendar id if (newDefaultCalendarID !== undefined) { await api(updateCalendarUserSettings({ DefaultCalendarID: newDefaultCalendarID })); } await call(); createNotification({ text: c('Success').t`Calendar removed` }); }; const handleExportCalendar = (exportCalendar: VisualCalendar) => { setIsExportModalOpen(true); updateModal('exportCalendarModal', { isOpen: true, props: { exportCalendar }, }); }; const { calendarModal, exportCalendarModal, deleteCalendarModal } = modalsMap; const upsellRef = getUpsellRef({ app: APP_UPSELL_REF_PATH.CALENDAR_UPSELL_REF_PATH, component: UPSELL_COMPONENT.BANNER, feature: CALENDAR_UPSELL_PATHS.MULTI_CAL, isSettings: true, }); const createCalendarButton = ( <div className="mb-4"> <PrimaryButton data-testid="calendar-setting-page:add-calendar" disabled={!canAdd} onClick={handleCreateCalendar} > {c('Action').t`Create calendar`} </PrimaryButton> </div> ); const isCalendarsLimitReachedNode = isFreeUser ? ( <Card rounded className="mb-4"> <div className="flex flex-nowrap flex-align-items-center"> <p className="flex-item-fluid my-0 pr-7">{calendarsLimitReachedText}</p> <ButtonLike as={SettingsLink} path={addUpsellPath('/upgrade', upsellRef)} color="norm" shape="solid" size="small" > {c('Action').t`Upgrade`} </ButtonLike> </div> </Card> ) : ( <Alert className="mb-4" type="info"> {calendarsLimitReachedText} </Alert> ); return ( <> <Prompt open={deleteCalendarModal.isOpen} title={c('Title').t`Delete calendar`} buttons={[ <Button color="danger" onClick={deleteCalendarModal.props?.onConfirm} type="submit">{c('Action') .t`Delete`}</Button>, <Button onClick={deleteCalendarModal.props?.onClose} type="submit">{c('Action').t`Cancel`}</Button>, ]} onClose={deleteCalendarModal.props?.onClose} > <div className="mb-4">{c('Info').t`Are you sure you want to delete this calendar?`}</div> {deleteCalendarModal.props?.defaultCalendarWarning} </Prompt> {!!exportCalendarModal.props?.exportCalendar && ( <ExportModal {...exportCalendarModal} {...exportModalProps} calendar={exportCalendarModal.props.exportCalendar} isOpen={isExportModalOpen} onExit={() => { onExitCalendarModal?.(); updateModal('exportCalendarModal', { isOpen: false, props: undefined, }); }} /> )} {!!calendarModal.props && ( <CalendarModal {...calendarModal.props} {...calendarModalProps} onExit={() => { onExitCalendarModal?.(); updateModal('calendarModal', { isOpen: false, props: undefined, }); }} /> )} <CalendarsSection calendars={myCalendars} addresses={addresses} user={user} defaultCalendarID={defaultCalendar?.ID} onSetDefault={handleSetDefaultCalendar} onEdit={handleEditCalendar} onDelete={handleDeleteCalendar} onExport={handleExportCalendar} data-testid="my-calendars-section" > <SettingsParagraph> {c('Personal calendar section description') .t`Create a calendar to stay on top of your schedule while keeping your data secure.`} <br /> <Href href={getKnowledgeBaseUrl('/protoncalendar-calendars')}>{c('Knowledge base link label') .t`Learn more`}</Href> </SettingsParagraph> {isCalendarsLimitReached ? isCalendarsLimitReachedNode : createCalendarButton} </CalendarsSection> </> ); }; export default MyCalendarsSection;
5,968
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/OtherCalendarsSection.tsx
import React, { ComponentPropsWithoutRef, useRef } from 'react'; import { c } from 'ttag'; import { Button, ButtonLike, Card, Href } from '@proton/atoms'; import { FeatureCode, SharedCalendarsSection } from '@proton/components/containers'; import { removeCalendar } from '@proton/shared/lib/api/calendars'; import { getCalendarsLimitReachedText } from '@proton/shared/lib/calendar/calendarLimits'; import { APP_UPSELL_REF_PATH, CALENDAR_UPSELL_PATHS, UPSELL_COMPONENT } from '@proton/shared/lib/constants'; import { addUpsellPath, getUpsellRef } from '@proton/shared/lib/helpers/upsell'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { Address, UserModel } from '@proton/shared/lib/interfaces'; import { ModalWithProps } from '@proton/shared/lib/interfaces/Modal'; import { CalendarMemberInvitation, HolidaysDirectoryCalendar, SubscribedCalendar, VisualCalendar, } from '@proton/shared/lib/interfaces/calendar'; import { Alert, PrimaryButton, Prompt, SettingsLink, useModalState } from '../../../components'; import { useApi, useEventManager, useFeature, useNotifications } from '../../../hooks'; import { useModalsMap } from '../../../hooks/useModalsMap'; import { SettingsParagraph } from '../../account'; import { CalendarModal } from '../calendarModal/CalendarModal'; import HolidaysCalendarModal from '../holidaysCalendarModal/HolidaysCalendarModal'; import SubscribedCalendarModal from '../subscribedCalendarModal/SubscribedCalendarModal'; import CalendarsSection from './CalendarsSection'; type ModalsMap = { calendarModal: ModalWithProps<{ editCalendar?: VisualCalendar; }>; deleteCalendarModal: ModalWithProps; }; export interface OtherCalendarsSectionProps extends ComponentPropsWithoutRef<'div'> { subscribedCalendars: SubscribedCalendar[]; sharedCalendars: VisualCalendar[]; calendarInvitations: CalendarMemberInvitation[]; holidaysCalendars: VisualCalendar[]; holidaysDirectory?: HolidaysDirectoryCalendar[]; unknownCalendars: VisualCalendar[]; addresses: Address[]; user: UserModel; canAdd: boolean; isCalendarsLimitReached: boolean; } const OtherCalendarsSection = ({ subscribedCalendars, sharedCalendars, calendarInvitations, holidaysCalendars, holidaysDirectory, unknownCalendars, addresses, user, canAdd, isCalendarsLimitReached, ...rest }: OtherCalendarsSectionProps) => { const api = useApi(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const calendarSharingEnabled = !!useFeature(FeatureCode.CalendarSharingEnabled).feature?.Value; const holidaysCalendarsEnabled = !!useFeature(FeatureCode.HolidaysCalendars)?.feature?.Value; const [{ onExit: onExitCalendarModal, ...calendarModalProps }, setIsCalendarModalOpen] = useModalState(); const [subscribedCalendarModal, setIsSubscribedCalendarModalOpen, renderSubscribedCalendarModal] = useModalState(); const [holidaysCalendarModal, setHolidaysCalendarModalOpen, renderHolidaysCalendarModal] = useModalState(); const confirm = useRef<{ resolve: (param?: any) => any; reject: () => any }>(); const { modalsMap, updateModal, closeModal } = useModalsMap<ModalsMap>({ calendarModal: { isOpen: false }, deleteCalendarModal: { isOpen: false }, }); const handleCreate = () => { setIsSubscribedCalendarModalOpen(true); }; const handleCreateHolidaysCalendar = () => { setHolidaysCalendarModalOpen(true); }; const handleEdit = (editCalendar: VisualCalendar) => { setIsCalendarModalOpen(true); updateModal('calendarModal', { isOpen: true, props: { editCalendar } }); }; const handleDelete = async (id: string) => { await new Promise<void>((resolve, reject) => { updateModal('deleteCalendarModal', { isOpen: true }); confirm.current = { resolve, reject }; }); await api(removeCalendar(id)); await call(); createNotification({ text: c('Success').t`Calendar removed` }); }; const { deleteCalendarModal, calendarModal } = modalsMap; const isFreeUser = !user.hasPaidMail; const calendarsLimitReachedText = getCalendarsLimitReachedText(isFreeUser).combinedText; const descriptionText = calendarSharingEnabled ? c('Subscribed calendar section description').t`Add public, external, or shared calendars.` : c('Subscribed calendar section description').t`Add public, external, or shared calendars using a URL.`; const addCalendarText = c('Action').t`Add calendar from URL`; const addHolidaysCalendarText = c('Action').t`Add public holidays`; const upsellRef = getUpsellRef({ app: APP_UPSELL_REF_PATH.CALENDAR_UPSELL_REF_PATH, component: UPSELL_COMPONENT.BANNER, feature: CALENDAR_UPSELL_PATHS.MULTI_CAL, isSettings: true, }); const addCalendarButtons = ( <div className="mb-4"> <> {holidaysCalendarsEnabled && ( <PrimaryButton data-testid="calendar-setting-page:add-holidays-calendar" disabled={!canAdd} onClick={handleCreateHolidaysCalendar} className="mr-4" > {addHolidaysCalendarText} </PrimaryButton> )} <PrimaryButton data-test-id="calendar-setting-page:add-calendar" disabled={!canAdd} onClick={handleCreate} > {addCalendarText} </PrimaryButton> </> </div> ); const isCalendarsLimitReachedNode = isFreeUser ? ( <Card rounded className="mb-4"> <div className="flex flex-nowrap flex-align-items-center"> <p className="flex-item-fluid my-0 pr-7">{calendarsLimitReachedText}</p> <ButtonLike as={SettingsLink} path={addUpsellPath('/upgrade', upsellRef)} color="norm" shape="solid" size="small" > {c('Action').t`Upgrade`} </ButtonLike> </div> </Card> ) : ( <Alert className="mb-4" type="info"> {calendarsLimitReachedText} </Alert> ); return ( <> <Prompt open={deleteCalendarModal.isOpen} title={c('Title').t`Remove calendar`} buttons={[ <Button color="danger" onClick={() => { confirm.current?.resolve(); closeModal('deleteCalendarModal'); }} >{c('Action').t`Remove calendar`}</Button>, <Button onClick={() => { confirm.current?.reject(); closeModal('deleteCalendarModal'); }} >{c('Action').t`Cancel`}</Button>, ]} onClose={() => confirm.current?.reject()} > {c('Info').t`The calendar will be removed from your account.`} </Prompt> {renderSubscribedCalendarModal && <SubscribedCalendarModal {...subscribedCalendarModal} />} {renderHolidaysCalendarModal && ( <HolidaysCalendarModal {...holidaysCalendarModal} holidaysCalendars={holidaysCalendars} /> )} {calendarModal.props?.editCalendar && ( <CalendarModal {...calendarModalProps} calendar={calendarModal.props.editCalendar} onExit={() => { onExitCalendarModal?.(); updateModal('calendarModal', { isOpen: true, props: undefined }); }} /> )} <CalendarsSection calendars={subscribedCalendars} addresses={addresses} user={user} nameHeader={c('Header; Table with list of calendars arranged by type').t`Subscribed`} onEdit={handleEdit} onDelete={handleDelete} data-testid="subscribed-calendars-section" {...rest} > <SettingsParagraph> {descriptionText} <br /> <Href href={getKnowledgeBaseUrl('/subscribe-to-external-calendar')}> {c('Knowledge base link label').t`Here's how`} </Href> </SettingsParagraph> {isCalendarsLimitReached ? isCalendarsLimitReachedNode : addCalendarButtons} </CalendarsSection> <CalendarsSection nameHeader={c('Header; Table with list of calendars arranged by type').t`Holidays`} calendars={holidaysCalendars} addresses={addresses} user={user} data-testid="holidays-calendars-section" /> <SharedCalendarsSection user={user} addresses={addresses} calendars={sharedCalendars} calendarInvitations={calendarInvitations} canAddCalendars={canAdd && !isCalendarsLimitReached} /> <CalendarsSection calendars={unknownCalendars} addresses={addresses} user={user} nameHeader={c('Header; Table with list of calendars arranged by type').t`Other`} onEdit={handleEdit} onDelete={handleDelete} data-testid="unknown-calendars-section" /> </> ); }; export default OtherCalendarsSection;
5,969
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/PrimaryTimezoneSection.tsx
import { c } from 'ttag'; import { CalendarUserSettings } from '@proton/shared/lib/interfaces/calendar'; import SettingsLayout from '../../account/SettingsLayout'; import SettingsLayoutLeft from '../../account/SettingsLayoutLeft'; import SettingsLayoutRight from '../../account/SettingsLayoutRight'; import PrimaryTimezoneSelector from './PrimaryTimezoneSelector'; interface Props { calendarUserSettings: CalendarUserSettings; } const PrimaryTimezoneSection = ({ calendarUserSettings }: Props) => { const timeZoneSelectorId = 'primary-timezone'; return ( <SettingsLayout> <SettingsLayoutLeft> <label className="text-semibold" htmlFor={timeZoneSelectorId} id="label-primary-timezone"> <span className="mr-2">{c('Primary timezone').t`Primary time zone`}</span> </label> </SettingsLayoutLeft> <SettingsLayoutRight> <PrimaryTimezoneSelector id={timeZoneSelectorId} calendarUserSettings={calendarUserSettings} data-testid="settings/primary-time-zone:dropdown" /> </SettingsLayoutRight> </SettingsLayout> ); }; export default PrimaryTimezoneSection;
5,970
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/PrimaryTimezoneSelector.tsx
import { c } from 'ttag'; import { DropdownSizeUnit, TimeZoneSelector } from '@proton/components/components'; import { Unit } from '@proton/components/components/dropdown/utils'; import { useApi, useEventManager, useNotifications } from '@proton/components/hooks'; import { useLoading } from '@proton/hooks/index'; import { updateCalendarUserSettings } from '@proton/shared/lib/api/calendars'; import { AbbreviatedTimezone } from '@proton/shared/lib/date/timezone'; import { CalendarUserSettings } from '@proton/shared/lib/interfaces/calendar'; interface Props { id: string; calendarUserSettings: CalendarUserSettings; className?: string; abbreviatedTimezone?: AbbreviatedTimezone; unstyledSelect?: boolean; selectMaxHeight?: DropdownSizeUnit.Viewport | Unit; tooltip?: boolean; ['data-testid']?: string; } const PrimaryTimezoneSelector = ({ id, calendarUserSettings: { PrimaryTimezone }, className, abbreviatedTimezone, unstyledSelect, selectMaxHeight, tooltip, 'data-testid': dataTestId, }: Props) => { const api = useApi(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const [loadingPrimaryTimeZone, withLoadingPrimaryTimeZone] = useLoading(); const handleChange = async (data: Partial<CalendarUserSettings>) => { await api(updateCalendarUserSettings(data)); await call(); createNotification({ text: c('Success').t`Preference saved` }); }; return ( <TimeZoneSelector id={id} data-testid={dataTestId} loading={loadingPrimaryTimeZone} timezone={PrimaryTimezone} onChange={(PrimaryTimezone) => withLoadingPrimaryTimeZone(handleChange({ PrimaryTimezone }))} telemetrySource="primary_timezone" className={className} abbreviatedTimezone={abbreviatedTimezone} unstyledSelect={unstyledSelect} selectMaxHeight={selectMaxHeight} tooltip={tooltip} /> ); }; export default PrimaryTimezoneSelector;
5,971
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/SecondaryTimezoneSection.tsx
import { c } from 'ttag'; import { CalendarUserSettings } from '@proton/shared/lib/interfaces/calendar'; import SettingsLayout from '../../account/SettingsLayout'; import SettingsLayoutLeft from '../../account/SettingsLayoutLeft'; import SettingsLayoutRight from '../../account/SettingsLayoutRight'; import SecondaryTimezoneSelector from './SecondaryTimezoneSelector'; interface Props { calendarUserSettings: CalendarUserSettings; } const SecondaryTimezoneSection = ({ calendarUserSettings }: Props) => { const timeZoneSelectorId = 'secondary-timezone'; return ( <SettingsLayout> <SettingsLayoutLeft> <label className="text-semibold" htmlFor={timeZoneSelectorId} id="label-secondary-timezone"> <span className="mr-2">{c('Primary timezone').t`Secondary time zone`}</span> </label> </SettingsLayoutLeft> <SettingsLayoutRight> <SecondaryTimezoneSelector id={timeZoneSelectorId} calendarUserSettings={calendarUserSettings} data-testid="settings/secondary-time-zone:dropdown" /> </SettingsLayoutRight> </SettingsLayout> ); }; export default SecondaryTimezoneSection;
5,972
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/SecondaryTimezoneSelector.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { DropdownSizeUnit, TimeZoneSelector } from '@proton/components/components'; import { Unit } from '@proton/components/components/dropdown/utils'; import { useApi, useEventManager, useNotifications } from '@proton/components/hooks'; import { useLoading } from '@proton/hooks/index'; import { updateCalendarUserSettings } from '@proton/shared/lib/api/calendars'; import { AbbreviatedTimezone, getTimezone } from '@proton/shared/lib/date/timezone'; import { CalendarUserSettings } from '@proton/shared/lib/interfaces/calendar'; interface Props { id: string; calendarUserSettings: CalendarUserSettings; className?: string; abbreviatedTimezone?: AbbreviatedTimezone; unstyledSelect?: boolean; selectMaxHeight?: DropdownSizeUnit.Viewport | Unit; tooltip?: boolean; ['data-testid']?: string; } const SecondaryTimezoneSelector = ({ id, calendarUserSettings: { DisplaySecondaryTimezone, SecondaryTimezone }, className, abbreviatedTimezone, unstyledSelect, selectMaxHeight, tooltip, 'data-testid': dataTestId, }: Props) => { const api = useApi(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const [loadingSecondaryTimeZone, withLoadingSecondaryTimeZone] = useLoading(); const [timezone] = useState(() => getTimezone()); const handleChange = async (data: Partial<CalendarUserSettings>) => { await api(updateCalendarUserSettings(data)); await call(); createNotification({ text: c('Success').t`Preference saved` }); }; return ( <TimeZoneSelector id={id} data-testid={dataTestId} loading={loadingSecondaryTimeZone} disabled={!DisplaySecondaryTimezone} timezone={SecondaryTimezone || timezone} onChange={(SecondaryTimezone) => withLoadingSecondaryTimeZone(handleChange({ SecondaryTimezone }))} telemetrySource="secondary_timezone" className={className} abbreviatedTimezone={abbreviatedTimezone} unstyledSelect={unstyledSelect} selectMaxHeight={selectMaxHeight} tooltip={tooltip} /> ); }; export default SecondaryTimezoneSelector;
5,973
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/SharedCalendarsSection.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Button, ButtonLike } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { getApiErrorMessage } from '@proton/shared/lib/api/helpers/apiErrorHelper'; import { CALENDAR_STATUS_TYPE, getCalendarStatusBadges, getDisabledCalendarBadge, } from '@proton/shared/lib/calendar/badges'; import { CALENDAR_TYPE } from '@proton/shared/lib/calendar/constants'; import { getCalendarSubpagePath } from '@proton/shared/lib/calendar/settingsRoutes'; import { ShareCalendarSignatureVerificationError } from '@proton/shared/lib/calendar/sharing/shareProton/ShareCalendarSignatureVerificationError'; import { getCalendarNameSubline, getCalendarNameWithOwner, } from '@proton/shared/lib/calendar/sharing/shareProton/shareProton'; import { APPS } from '@proton/shared/lib/constants'; import { ApiError } from '@proton/shared/lib/fetch/ApiError'; import { getIsAddressDisabled } from '@proton/shared/lib/helpers/address'; import { canonicalizeInternalEmail } from '@proton/shared/lib/helpers/email'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { Address, UserModel } from '@proton/shared/lib/interfaces'; import { CalendarMemberInvitation, VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import { ButtonGroup, Icon, Info, SettingsLink, Table, TableBody, TableCell, TableHeader, TableHeaderCell, TableRow, Tooltip, useModalState, } from '../../../components'; import CalendarSelectIcon from '../../../components/calendarSelect/CalendarSelectIcon'; import { FeatureCode, SettingsSectionWide } from '../../../containers'; import CalendarBadge from '../../../containers/calendar/settings/CalendarBadge'; import { useCalendarShareInvitationActions, useEventManager, useFeature, useNotifications } from '../../../hooks'; import ShareCalendarWithSignatureVerificationErrorModal from '../../calendar/shareProton/ShareCalendarWithSignatureVerificationErrorModal'; const SharedCalendarRow = ({ calendar, displayEmail }: { calendar: VisualCalendar; displayEmail: boolean }) => { const { ID, Color, Name: calendarName, Owner: { Email: ownerEmail }, Email: memberEmail, Permissions: memberPermissions, Type: calendarType, } = calendar; const calendarNameWithOwner = getCalendarNameWithOwner({ calendarName, ownerEmail }); const { badges } = getCalendarStatusBadges(calendar); const filteredBadges = badges.filter(({ statusType }) => statusType === CALENDAR_STATUS_TYPE.DISABLED); const subline = getCalendarNameSubline({ calendarType, displayEmail, memberEmail, memberPermissions }); const statusHeader = ( <div className="flex flex-align-items-center"> <span className="mr-2">{c('Header').t`Status`}</span> <Info url={getKnowledgeBaseUrl('/calendar-status')} /> </div> ); return ( <TableRow> <TableCell label={c('Header').t`Name`}> <div className="grid-align-icon-center"> <CalendarSelectIcon color={Color} className="mr-3 flex-item-noshrink keep-left" /> <div className="flex flex-align-items-center flex-nowrap overflow-hidden"> <div className="text-ellipsis" title={calendarNameWithOwner}> {calendarNameWithOwner} </div> </div> {subline && <div className="text-ellipsis text-sm m-0 color-weak">{subline}</div>} </div> </TableCell> <TableCell label={filteredBadges.length > 0 && statusHeader}> <div data-testid="calendar-settings-page:calendar-status" key="status"> {filteredBadges.map(({ statusType, badgeType, text, tooltipText }) => ( <CalendarBadge key={statusType} badgeType={badgeType} text={text} tooltipText={tooltipText} /> ))} </div> </TableCell> <TableCell> <Tooltip title={c('Calendar table settings button tooltip').t`Open settings`}> <ButtonLike as={SettingsLink} app={APPS.PROTONCALENDAR} path={getCalendarSubpagePath(ID)} shape="outline" size="small" icon > <Icon name="cog-wheel" className="flex-item-noshrink" alt={c('Calendar table settings button tooltip').t`Open settings`} /> </ButtonLike> </Tooltip> </TableCell> </TableRow> ); }; const InvitationRow = ({ user, invitation, onAccept, onDecline, isInvitedAddressDisabled, canAddCalendars, displayEmail, }: { user: UserModel; invitation: CalendarMemberInvitation; onAccept: (invitation: CalendarMemberInvitation) => Promise<void>; onDecline: (invitationID: CalendarMemberInvitation) => Promise<void>; isInvitedAddressDisabled: boolean; canAddCalendars: boolean; displayEmail: boolean; }) => { const [loadingAccept, withLoadingAccept] = useLoading(); const [loadingDecline, withLoadingDecline] = useLoading(); const { Email: memberEmail, Calendar, Permissions: memberPermissions } = invitation; const calendarNameWithOwner = getCalendarNameWithOwner({ calendarName: Calendar.Name, ownerEmail: Calendar.SenderEmail, }); const subline = getCalendarNameSubline({ calendarType: CALENDAR_TYPE.PERSONAL, displayEmail, memberEmail, memberPermissions, }); const handleAccept = () => withLoadingAccept(onAccept(invitation)); const handleDecline = () => withLoadingDecline(onDecline(invitation)); const isAcceptButtonDisabled = isInvitedAddressDisabled || !canAddCalendars || !user.hasNonDelinquentScope; const isDeclineButtonDisabled = !user.hasNonDelinquentScope; // TODO: Unify table styles with CalendarsTable.tsx return ( <TableRow> <TableCell> <div className="grid-align-icon-center"> <CalendarSelectIcon border color={Calendar.Color} className="mr-3 flex-item-noshrink keep-left" /> <div className="flex flex-align-items-center flex-nowrap overflow-hidden"> <div className="text-ellipsis" title={calendarNameWithOwner}> {calendarNameWithOwner} </div> </div> {subline && <div className="text-ellipsis text-sm m-0 color-weak">{subline}</div>} </div> </TableCell> <TableCell> <div key="status">{isInvitedAddressDisabled && <CalendarBadge {...getDisabledCalendarBadge()} />}</div> </TableCell> <TableCell> <div className="flex flex-nowrap on-tablet-flex-justify-start flex-justify-end flex-align-items-center gap-2"> {isAcceptButtonDisabled && ( <Info title={ isInvitedAddressDisabled ? c('Info').t`Enable this address to join this calendar` : c('Info').t`Remove one of your calendars to join this one` } buttonClass="flex-item-noshrink" /> )} <ButtonGroup size="small" className="flex-item-noshrink"> <Button loading={loadingAccept} disabled={isAcceptButtonDisabled} onClick={handleAccept}> {c('Action; accept invitation to share calendar').t`Accept`} </Button> <Button loading={loadingDecline} disabled={isDeclineButtonDisabled} onClick={handleDecline}> {c('Action; decline invitation to share calendar').t`Decline`} </Button> </ButtonGroup> </div> </TableCell> </TableRow> ); }; interface Props { user: UserModel; addresses: Address[]; calendars: VisualCalendar[]; calendarInvitations: CalendarMemberInvitation[]; canAddCalendars: boolean; } const SharedCalendarsSection = ({ user, addresses, calendars = [], calendarInvitations, canAddCalendars }: Props) => { const { call } = useEventManager(); const { createNotification } = useNotifications(); const [ signatureVerificationErrorModal, setIsSignatureVerificationErrorModalOpen, renderSignatureVerificationErrorModal, ] = useModalState(); const { accept, reject } = useCalendarShareInvitationActions(); const hasSingleAddress = addresses.length === 1; const isCalendarSharingEnabled = !!useFeature(FeatureCode.CalendarSharingEnabled).feature?.Value; const [invitations, setInvitations] = useState([...calendarInvitations]); const [calendarOwnerEmail, setCalendarOwnerEmail] = useState(''); const removeInvitation = (ID: string) => setInvitations((invitations) => invitations.filter(({ CalendarInvitationID }) => CalendarInvitationID !== ID)); const handleAcceptError = (e: Error) => { if (e instanceof ShareCalendarSignatureVerificationError) { const { senderEmail, errors } = e; setCalendarOwnerEmail(senderEmail); errors?.forEach((error) => { console.error(error); }); setIsSignatureVerificationErrorModalOpen(true); } else { const text = e instanceof ApiError ? getApiErrorMessage(e) : e.message; createNotification({ type: 'error', text, }); } }; const handleAccept = async (invitation: CalendarMemberInvitation) => { const accepted = await accept({ invitation, onError: handleAcceptError }); if (accepted) { removeInvitation(invitation.CalendarInvitationID); await call(); } }; const handleRejectError = (e: Error) => { const text = e instanceof ApiError ? getApiErrorMessage(e) : e.message; createNotification({ type: 'error', text, }); }; const handleDecline = async (invitation: CalendarMemberInvitation) => { await reject({ invitation, onError: handleRejectError }); removeInvitation(invitation.CalendarInvitationID); }; if (!(calendars.length || (isCalendarSharingEnabled && invitations.length))) { return null; } const sharedWithMeTitle = c('Table header; invitations to share calendar').t`Shared with me`; return ( <> {renderSignatureVerificationErrorModal && ( <ShareCalendarWithSignatureVerificationErrorModal {...signatureVerificationErrorModal} senderEmail={calendarOwnerEmail} onCancel={signatureVerificationErrorModal.onClose} /> )} <SettingsSectionWide> <h4 className="lg:hidden text-bold text-rg mb-2">{sharedWithMeTitle}</h4> <Table hasActions responsive="cards" data-testid="shared-calendars-section"> <TableHeader> <TableRow> <TableHeaderCell className="text-left w-1/2">{sharedWithMeTitle}</TableHeaderCell> <TableHeaderCell className="w-1/5">{''}</TableHeaderCell> <TableHeaderCell>{''}</TableHeaderCell> </TableRow> </TableHeader> <TableBody> {calendars.map((calendar) => ( <SharedCalendarRow key={calendar.ID} calendar={calendar} displayEmail={!hasSingleAddress} /> ))} {isCalendarSharingEnabled && invitations.map((invitation) => { const disabledCanonicalizedEmails = addresses .filter((address) => getIsAddressDisabled(address)) .map((address) => canonicalizeInternalEmail(address.Email)); const isInvitedAddressDisabled = disabledCanonicalizedEmails.includes( canonicalizeInternalEmail(invitation.Email) ); return ( <InvitationRow key={invitation.CalendarInvitationID} user={user} invitation={invitation} onAccept={handleAccept} onDecline={handleDecline} isInvitedAddressDisabled={isInvitedAddressDisabled} canAddCalendars={canAddCalendars} displayEmail={!hasSingleAddress} /> ); })} </TableBody> </Table> </SettingsSectionWide> </> ); }; export default SharedCalendarsSection;
5,974
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/ShowSecondaryTimezoneToggle.tsx
import {useState} from "react"; import {c} from "ttag"; import { useLoading } from '@proton/hooks'; import {Toggle} from "@proton/components/components"; import {useApi, useEventManager, useNotifications} from "@proton/components/hooks"; import {getTimezone} from "@proton/shared/lib/date/timezone"; import {CalendarUserSettings} from "@proton/shared/lib/interfaces/calendar"; import {updateCalendarUserSettings} from "@proton/shared/lib/api/calendars"; interface Props { calendarUserSettings: CalendarUserSettings } const ShowSecondaryTimezoneToggle = ({ calendarUserSettings: { DisplaySecondaryTimezone, SecondaryTimezone }, }: Props) => { const api = useApi(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const [loadingDisplaySecondaryTimezone, withLoadingDisplaySecondaryTimezone] = useLoading(); const [timezone] = useState(() => getTimezone()); const handleChange = async (data: Partial<CalendarUserSettings>) => { await api(updateCalendarUserSettings(data)); await call(); createNotification({ text: c('Success').t`Preference saved` }); }; const secondaryTimezoneValue = SecondaryTimezone || timezone; return ( <Toggle id="show-secondary-timezone" aria-describedby="show-secondary-timezone" loading={loadingDisplaySecondaryTimezone} checked={!!DisplaySecondaryTimezone} onChange={({ target }) => withLoadingDisplaySecondaryTimezone( handleChange({ DisplaySecondaryTimezone: +target.checked, // Set a timezone if it's the first time SecondaryTimezone: !SecondaryTimezone ? secondaryTimezoneValue : undefined, }) ) } /> ); }; export default ShowSecondaryTimezoneToggle;
5,975
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/ShowSecondaryTimezoneToggleSection.tsx
import { c } from 'ttag'; import { CalendarUserSettings } from '@proton/shared/lib/interfaces/calendar'; import SettingsLayout from '../../account/SettingsLayout'; import SettingsLayoutLeft from '../../account/SettingsLayoutLeft'; import SettingsLayoutRight from '../../account/SettingsLayoutRight'; import ShowSecondaryTimezoneToggle from "./ShowSecondaryTimezoneToggle"; interface Props { calendarUserSettings: CalendarUserSettings; } const ShowSecondaryTimezoneToggleSection = ({ calendarUserSettings, }: Props) => { return ( <SettingsLayout> <SettingsLayoutLeft> <label className="text-semibold" htmlFor="show-secondary-timezone" id="label-show-secondary-timezone"> <span className="mr-2">{c('Label').t`Show secondary time zone`}</span> </label> </SettingsLayoutLeft> <SettingsLayoutRight className="pt-2 flex flex-align-items-center"> <ShowSecondaryTimezoneToggle calendarUserSettings={calendarUserSettings}/> </SettingsLayoutRight> </SettingsLayout> ); }; export default ShowSecondaryTimezoneToggleSection;
5,976
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/ViewPreferenceSelector.tsx
import { c } from 'ttag'; import { SETTINGS_VIEW } from '@proton/shared/lib/calendar/constants'; import { Option, SelectTwo } from '../../../components'; interface Props { id: string; className?: string; loading: boolean; disabled?: boolean; view: SETTINGS_VIEW; onChange: (view: SETTINGS_VIEW) => void; unstyledSelect?: boolean; } const ViewPreferenceSelector = ({ className = 'field w-full', loading = false, disabled = false, view, unstyledSelect, onChange, ...rest }: Props) => { const options = [ { text: c('Calendar view').t`Day`, value: SETTINGS_VIEW.DAY }, { text: c('Calendar view').t`Week`, value: SETTINGS_VIEW.WEEK }, { text: c('Calendar view').t`Month`, value: SETTINGS_VIEW.MONTH }, // not activated for beta // { text: c('Calendar view').t`Year`, value: YEAR }, // { text: c('Calendar view').t`Agenda`, value: PLANNING }, ].filter(Boolean); return ( <SelectTwo disabled={loading || disabled} className={className} title={c('Action').t`Select calendar view`} value={view} onChange={({ value }) => onChange(+value)} unstyled={unstyledSelect} {...rest} > {options.map(({ text, value }) => ( <Option key={value} value={value} title={text} /> ))} </SelectTwo> ); }; export default ViewPreferenceSelector;
5,977
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/WeekStartSelector.tsx
import { c } from 'ttag'; import { DropdownSizeUnit, Option, SelectTwo } from '@proton/components/components'; import { useApi, useEventManager, useNotifications, useUserSettings } from '@proton/components/hooks'; import { useLoading } from '@proton/hooks'; import { updateWeekStart } from '@proton/shared/lib/api/settings'; import { dateLocaleCode } from '@proton/shared/lib/i18n'; import { getBrowserLocale } from '@proton/shared/lib/i18n/helper'; import { loadDateLocale } from '@proton/shared/lib/i18n/loadLocale'; import { SETTINGS_WEEK_START } from '@proton/shared/lib/interfaces'; import { getDefaultWeekStartsOn } from '@proton/shared/lib/settings/helper'; interface Props { className?: string; unstyledSelect?: boolean; shortText?: boolean; } const WeekStartSelector = ({ className, unstyledSelect, shortText = false }: Props) => { const api = useApi(); const [userSettings] = useUserSettings(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const [loading, withLoading] = useLoading(); const handleWeekStart = async (value: SETTINGS_WEEK_START) => { await loadDateLocale(dateLocaleCode, getBrowserLocale(), { ...userSettings, WeekStart: value }); await api(updateWeekStart(value)); await call(); createNotification({ text: c('Success').t`Preference saved` }); }; const days = [ { text: c('Day').t`Sunday`, value: SETTINGS_WEEK_START.SUNDAY }, { text: c('Day').t`Monday`, value: SETTINGS_WEEK_START.MONDAY }, { text: c('Day').t`Tuesday`, value: SETTINGS_WEEK_START.TUESDAY }, { text: c('Day').t`Wednesday`, value: SETTINGS_WEEK_START.WEDNESDAY }, { text: c('Day').t`Thursday`, value: SETTINGS_WEEK_START.THURSDAY }, { text: c('Day').t`Friday`, value: SETTINGS_WEEK_START.FRIDAY }, { text: c('Day').t`Saturday`, value: SETTINGS_WEEK_START.SATURDAY }, ]; const defaultDay = days[getDefaultWeekStartsOn()].text; const selectOptions = [ { text: c('Option').t`Automatic (${defaultDay})`, value: SETTINGS_WEEK_START.LOCALE_DEFAULT }, ...days.filter(({ value }) => [SETTINGS_WEEK_START.SUNDAY, SETTINGS_WEEK_START.MONDAY, SETTINGS_WEEK_START.SATURDAY].includes(value) ), ]; return ( <SelectTwo className={className} id="week-start-select" value={userSettings.WeekStart} loading={loading} disabled={loading} onChange={({ value }) => withLoading(handleWeekStart(value))} aria-describedby="label-week-start-select" unstyled={unstyledSelect} size={{ width: DropdownSizeUnit.Dynamic }} renderSelected={ shortText ? (selected) => { if (selected === SETTINGS_WEEK_START.LOCALE_DEFAULT) { // translater: as in "Automatic" return <>{c('Option').t`Auto`}</>; } const selectedDay = days.find((day) => day.value === selected); return <>{selectedDay?.text}</>; } : undefined } > {selectOptions.map((option) => { return <Option title={option.text} value={option.value} key={option.value} />; })} </SelectTwo> ); }; export default WeekStartSelector;
5,978
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/settings/index.ts
export { default as CalendarImportSection } from './CalendarImportSection'; export { default as CalendarExportSection } from './CalendarExportSection'; export { default as MyCalendarsSection } from './MyCalendarsSection'; export { default as OtherCalendarsSection } from './OtherCalendarsSection'; export { default as CalendarTimeSection } from './CalendarTimeSection'; export { default as SecondaryTimezoneSection } from './SecondaryTimezoneSection'; export { default as CalendarLayoutSection } from './CalendarLayoutSection'; export { default as CalendarSubpage } from './CalendarSubpage'; export { default as CalendarSubpageHeaderSection } from './CalendarSubpageHeaderSection'; export { default as CalendarDeleteSection } from './CalendarDeleteSection'; export { default as CalendarEventDefaultsSection } from './CalendarEventDefaultsSection'; export { default as SharedCalendarsSection } from './SharedCalendarsSection'; export { default as WeekStartSelector } from './WeekStartSelector'; export { default as PrimaryTimezoneSelector } from './PrimaryTimezoneSelector'; export { default as SecondaryTimezoneSelector } from './SecondaryTimezoneSelector'; export { default as ShowSecondaryTimezoneToggle } from './ShowSecondaryTimezoneToggle';
5,979
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/shareProton/ShareCalendarModal.test.tsx
import { act, render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { mocked } from 'jest-mock'; import { useApi, useGetEncryptionPreferences, useNotifications } from '@proton/components/hooks'; import { PublicKeyReference } from '@proton/crypto'; import { MIME_TYPES, PGP_SCHEMES } from '@proton/shared/lib/constants'; import createCache from '@proton/shared/lib/helpers/cache'; import { EncryptionPreferences } from '@proton/shared/lib/mail/encryptionPreferences'; import { addressBuilder, calendarBuilder, mockApiWithServer, mockNotifications, server } from '@proton/testing'; import { CacheProvider } from '../../cache'; import ShareCalendarModal from './ShareCalendarModal'; jest.mock('@proton/components/hooks/useGetEncryptionPreferences'); jest.mock('@proton/components/hooks/useNotifications'); jest.mock('@proton/components/hooks/useApi'); jest.mock('@proton/components/hooks/useAddresses'); jest.mock('../../contacts/ContactEmailsProvider', () => ({ useContactEmailsCache: () => ({ contactEmails: [], contactGroups: [], contactEmailsMap: {}, groupsWithContactsMap: {}, }), })); const mockedUseApi = mocked(useApi); const mockedUseNotifications = mocked(useNotifications); const mockedUseGetEncryptionPreferences = mocked(useGetEncryptionPreferences); const mockedEncryptionPreferences: EncryptionPreferences = { encrypt: true, sign: true, scheme: PGP_SCHEMES.PGP_INLINE, mimeType: MIME_TYPES.PLAINTEXT, isInternalWithDisabledE2EEForMail: false, sendKey: 'anything' as unknown as PublicKeyReference, apiKeys: [], pinnedKeys: [], verifyingPinnedKeys: [], isInternal: true, hasApiKeys: true, hasPinnedKeys: true, isContact: true, // error: new EncryptionPreferencesError(ENCRYPTION_PREFERENCES_ERROR_TYPES.EMAIL_ADDRESS_ERROR, 'EMAIL_ADDRESS_ERROR'), }; function renderComponent({ members = [], invitations = [] } = {}) { const Wrapper = ({ children }: any) => <CacheProvider cache={createCache()}>{children}</CacheProvider>; return render( <ShareCalendarModal members={members} invitations={invitations} calendar={calendarBuilder()} addresses={[addressBuilder()]} onFinish={() => {}} open />, { wrapper: Wrapper } ); } function addRecipients(emails: string[]) { const emailInput = screen.getByTitle('Email address'); screen.debug(emailInput, 10000000); act(() => { emails.forEach(async (email) => { // FIXME: same issue as in MainContainer.spec.tsx, it doesn't enter recipients await userEvent.type(emailInput, `${email}{enter}`); }); }); } xdescribe('ShareCalendarModal', () => { beforeAll(() => server.listen()); afterAll(() => server.close()); beforeEach(() => { mockedUseApi.mockImplementation(() => mockApiWithServer); mockedUseNotifications.mockImplementation(() => mockNotifications); mockedUseGetEncryptionPreferences.mockImplementation(() => () => Promise.resolve(mockedEncryptionPreferences)); }); afterEach(() => { server.resetHandlers(); }); it(`removes duplicate recipients and self addresses when added and displays a notification`, async () => { renderComponent(); addRecipients(['legit@pm.me']); await waitFor(() => { expect(screen.getByText(/legit@pm.me/)).toBeInTheDocument(); }); expect(screen.getByText(/decent.one@proton.me/)).toBeInTheDocument(); expect(screen.queryByText(/legit\+dog@pm.me/)).not.toBeInTheDocument(); expect(screen.queryByText(/stest1@proton.black/)).not.toBeInTheDocument(); expect(mockedUseNotifications().createNotification).toHaveBeenCalledTimes(2); }); it(`displays errors for existing members, invalid emails and exceeding the limit before submitting`, () => { renderComponent(); }); it(`displays errors for non-proton, non-existing and other errors after submitting`, () => { // assistive text when non-proton renderComponent(); }); it(`disables the share button if there are no recipients or there are errors`, () => { renderComponent(); expect(screen.getByText(/Share/, { selector: 'button' })).toBeDisabled(); }); it(`shows a loading state when submitting and a notification once done`, () => { renderComponent(); }); });
5,980
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/shareProton/ShareCalendarModal.tsx
import { Dispatch, SetStateAction, useEffect, useRef, useState } from 'react'; import { c, msgid } from 'ttag'; import { Button, Href } from '@proton/atoms'; import InputField from '@proton/components/components/v2/field/InputField'; import { useApi, useGetAddressKeys, useGetDecryptedPassphraseAndCalendarKeys, useGetEncryptionPreferences, useNotifications, } from '@proton/components/hooks'; import { PublicKeyReference } from '@proton/crypto'; import { useLoading } from '@proton/hooks'; import { addMember } from '@proton/shared/lib/api/calendars'; import { reformatApiErrorMessage } from '@proton/shared/lib/calendar/api'; import { MAX_CALENDAR_MEMBERS } from '@proton/shared/lib/calendar/constants'; import { encryptPassphraseSessionKey } from '@proton/shared/lib/calendar/crypto/keys/calendarKeys'; import { MEMBER_PERMISSIONS } from '@proton/shared/lib/calendar/permissions'; import { filterOutAcceptedInvitations } from '@proton/shared/lib/calendar/sharing/shareProton/shareProton'; import { BRAND_NAME } from '@proton/shared/lib/constants'; import { getSelfSendAddresses } from '@proton/shared/lib/helpers/address'; import { canonicalizeInternalEmail, validateEmailAddress } from '@proton/shared/lib/helpers/email'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { Address, KeyTransparencyActivation, Recipient, RequireSome, SimpleMap } from '@proton/shared/lib/interfaces'; import { CalendarMember, CalendarMemberInvitation, VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import { ContactEmail } from '@proton/shared/lib/interfaces/contacts'; import { GetEncryptionPreferences } from '@proton/shared/lib/interfaces/hooks/GetEncryptionPreferences'; import { getPrimaryKey } from '@proton/shared/lib/keys'; import { EncryptionPreferencesError } from '@proton/shared/lib/mail/encryptionPreferences'; import clsx from '@proton/utils/clsx'; import isTruthy from '@proton/utils/isTruthy'; import noop from '@proton/utils/noop'; import { AddressesAutocompleteTwo, AddressesInput, AddressesInputItem, Icon, Loader, ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, ModalProps, RadioGroup, } from '../../../components'; import { useContactEmailsCache } from '../../contacts/ContactEmailsProvider'; import { useKeyTransparencyContext } from '../../keyTransparency'; export enum VALIDATION_ERROR_TYPES { INVALID_EMAIL, NOT_PROTON_ACCOUNT, SHARING_UNSUPPORTED, DOES_NOT_EXIST, EXISTING_MEMBER, } const { INVALID_EMAIL, NOT_PROTON_ACCOUNT, SHARING_UNSUPPORTED, DOES_NOT_EXIST, EXISTING_MEMBER } = VALIDATION_ERROR_TYPES; const getValidationErrorMessage = (type: VALIDATION_ERROR_TYPES) => { if (type === INVALID_EMAIL) { return c('Error').t`The address might be misspelled`; } if (type === NOT_PROTON_ACCOUNT) { return c('Error').t`Not a ${BRAND_NAME} account`; } if (type === SHARING_UNSUPPORTED) { return c('Error').t`Intended recipient does not support calendar sharing`; } if (type === DOES_NOT_EXIST) { return c('Error').t`Account does not exist`; } if (type === EXISTING_MEMBER) { return c('Error').t`Already a member of this calendar`; } return c('Error').t`Validation error`; }; class ShareCalendarValdidationError extends Error { type: VALIDATION_ERROR_TYPES; constructor(type: VALIDATION_ERROR_TYPES) { const message = getValidationErrorMessage(type); super(message); this.type = type; Object.setPrototypeOf(this, ShareCalendarValdidationError.prototype); } } type RecipientError = ShareCalendarValdidationError | EncryptionPreferencesError; interface RecipientWithAddedTime extends Recipient { addedTime: number; } interface ExtendedRecipient extends RecipientWithAddedTime { loading?: boolean; error?: RecipientError; publicKey?: PublicKeyReference; isKeyPinned?: boolean; } const getRecipientHasError = (recipient: ExtendedRecipient): recipient is RequireSome<ExtendedRecipient, 'error'> => { return !!recipient.error; }; const getPublicKeysForCalendarSharing = async ({ email, getEncryptionPreferences, contactEmailsMap, ktActivation, }: { email: string; ktActivation: KeyTransparencyActivation; getEncryptionPreferences: GetEncryptionPreferences; contactEmailsMap: SimpleMap<ContactEmail>; }): Promise<{ publicKey?: PublicKeyReference; isKeyPinned?: boolean; error?: EncryptionPreferencesError | ShareCalendarValdidationError; }> => { // potential errors thrown in the code below are handled in a custom way by loadRecipient const { sendKey, isSendKeyPinned, error, isInternal } = await getEncryptionPreferences({ email, lifetime: 0, contactEmailsMap, intendedForEmail: false, }); if (error) { return { error, }; } if (!isInternal) { return { error: new ShareCalendarValdidationError(NOT_PROTON_ACCOUNT), }; } if (!sendKey) { return { error: new ShareCalendarValdidationError(SHARING_UNSUPPORTED), }; } if (ktActivation === KeyTransparencyActivation.SHOW_UI) { // TODO: Decide what we want to do when there are KT errors } return { publicKey: sendKey, isKeyPinned: isSendKeyPinned, }; }; const loadRecipient = async ({ recipient, setRecipientsMap, getEncryptionPreferences, contactEmailsMap, ktActivation, onError, }: { recipient: RecipientWithAddedTime; setRecipientsMap: Dispatch<SetStateAction<SimpleMap<ExtendedRecipient>>>; getEncryptionPreferences: GetEncryptionPreferences; contactEmailsMap: SimpleMap<ContactEmail>; ktActivation: KeyTransparencyActivation; onError: (error: any) => void; }) => { const { Address: email } = recipient; setRecipientsMap((map) => ({ ...map, [email]: { ...recipient, loading: true, }, })); try { const { publicKey, isKeyPinned, error } = await getPublicKeysForCalendarSharing({ email, getEncryptionPreferences, contactEmailsMap, ktActivation, }); if (error) { const customError = error instanceof EncryptionPreferencesError ? new EncryptionPreferencesError(error.type, reformatApiErrorMessage(error.message)) : error; setRecipientsMap((map) => ({ ...map, [email]: { ...recipient, loading: false, error: customError, }, })); } else { setRecipientsMap((map) => ({ ...map, [email]: { ...recipient, loading: false, publicKey, isKeyPinned, }, })); } } catch (error: any) { onError(error); setRecipientsMap((map) => { const result = { ...map }; delete result[email]; return result; }); } }; const getAddressInputItemAttributes = ({ loading, error, Address, isKeyPinned }: ExtendedRecipient) => { if (loading) { return { icon: <Loader className="icon-16p pl-2 m-auto flex flex-item-noshrink" />, }; } if (error) { return { icon: ( <div className="flex flex-align-items-center flex-item-noshrink ml-2"> <Icon name="exclamation-circle" /> </div> ), iconTooltip: error.message, labelTooltip: Address, }; } return { icon: ( <span className="inline-flex pl-2 flex-item-noshrink my-auto"> <Icon size={16} name={isKeyPinned ? 'lock-check-filled' : 'lock-filled'} className={'color-info'} /> </span> ), iconTooltip: isKeyPinned ? c('Tooltip; share calendar modal ').t`Shared end-to-end encrypted with verified contact` : c('Tooltip; share calendar modal ').t`Shared end-to-end encrypted`, labelTooltip: Address, }; }; interface Props extends ModalProps { calendar: VisualCalendar; addresses: Address[]; onFinish?: (invitations: CalendarMemberInvitation[]) => void; members: CalendarMember[]; invitations: CalendarMemberInvitation[]; } const ShareCalendarModal = ({ calendar, addresses, onFinish, members, invitations, ...rest }: Props) => { const api = useApi(); const { createNotification } = useNotifications(); const { contactEmails, contactGroups, contactEmailsMap, groupsWithContactsMap } = useContactEmailsCache(); const getEncryptionPreferences = useGetEncryptionPreferences(); const getAddressKeys = useGetAddressKeys(); const getDecryptedPassphraseAndCalendarKeys = useGetDecryptedPassphraseAndCalendarKeys(); const { ktActivation } = useKeyTransparencyContext(); const addressesAutocompleteRef = useRef<HTMLInputElement>(null); const [permissions, setPermissions] = useState<number>(MEMBER_PERMISSIONS.FULL_VIEW); const [recipientsMap, setRecipientsMap] = useState<SimpleMap<ExtendedRecipient>>({}); const [loadingShare, withLoadingShare] = useLoading(false); const recipients = Object.values(recipientsMap) .filter(isTruthy) .sort(({ addedTime: a }, { addedTime: b }) => a - b); const invalidRecipients = recipients.filter(getRecipientHasError); const hasExternalRecipients = invalidRecipients.some(({ error }) => error.type === NOT_PROTON_ACCOUNT); const currentEmails = recipients.map(({ Address }) => canonicalizeInternalEmail(Address)); const pendingInvitations = filterOutAcceptedInvitations(invitations); const existingEmails = [...pendingInvitations, ...members].map(({ Email }) => canonicalizeInternalEmail(Email)); const totalRecipients = recipients.length; const maxRecipients = Math.max(MAX_CALENDAR_MEMBERS - existingEmails.length, 0); const isLoadingRecipients = recipients.some(({ loading }) => loading); const ownNormalizedEmails = getSelfSendAddresses(addresses).map(({ Email }) => canonicalizeInternalEmail(Email)); useEffect(() => { if (!rest.open) { setRecipientsMap({}); setPermissions(MEMBER_PERMISSIONS.FULL_VIEW); } }, [rest.open]); const showDuplicateNotification = (recipients: Recipient[]) => { const joinedRecipients = recipients.map((recipient) => recipient.Address).join(', '); // translator: "joinedRecipients" is the recipient list joined by a comma, e.g. "John, Jane, Joe" const text = c('Error').ngettext( msgid`Removed duplicate recipient: ${joinedRecipients}`, `Removed duplicate recipients: ${joinedRecipients}`, recipients.length ); createNotification({ text, type: 'warning', }); }; const handleAddRecipients = (recipients: Recipient[]) => { const { duplicateRecipients, existingRecipients } = recipients.reduce<{ newRecipients: Recipient[]; addedCanonicalizedAddresses: string[]; duplicateRecipients: RecipientWithAddedTime[]; existingRecipients: RecipientWithAddedTime[]; }>( (acc, recipient) => { const address = recipient.Address; const canonicalizedAddress = canonicalizeInternalEmail(address); const recipientWithAddedTime = { ...recipient, addedTime: Date.now(), }; if (ownNormalizedEmails.includes(canonicalizedAddress)) { createNotification({ type: 'error', text: c('Calendar self sharing error').t`You already have access to this calendar`, }); return acc; } if (!validateEmailAddress(address)) { setRecipientsMap((map) => ({ ...map, [address]: { ...recipientWithAddedTime, error: new ShareCalendarValdidationError(INVALID_EMAIL), }, })); } if (existingEmails.includes(canonicalizedAddress)) { acc.existingRecipients.push(recipientWithAddedTime); } else if ([...currentEmails, ...acc.addedCanonicalizedAddresses].includes(canonicalizedAddress)) { acc.duplicateRecipients.push(recipientWithAddedTime); } else { const onError = (error: any) => { const { data = {} } = error; if (typeof data.Error === 'string') { console.error(data.Error); createNotification({ type: 'error', text: data.Error, }); } else { console.error(error); createNotification({ type: 'error', // translator: The variable ${address} is an email here. E.g.: Failed to retrieve contact information for eric.norbert@proton.me text: c('Calendar sharing error') .t`Failed to retrieve contact information for ${address}`, }); } }; void loadRecipient({ recipient: recipientWithAddedTime, setRecipientsMap, getEncryptionPreferences, ktActivation, contactEmailsMap, onError, }); acc.newRecipients.push(recipientWithAddedTime); acc.addedCanonicalizedAddresses.push(canonicalizedAddress); } return acc; }, { newRecipients: [], addedCanonicalizedAddresses: [], duplicateRecipients: [], existingRecipients: [] } ); if (existingRecipients.length) { setRecipientsMap((map) => ({ ...map, ...existingRecipients.reduce<SimpleMap<ExtendedRecipient>>((acc, recipient) => { acc[recipient.Address] = { ...recipient, loading: false, error: new ShareCalendarValdidationError(EXISTING_MEMBER), }; return acc; }, {}), })); } if (duplicateRecipients.length) { showDuplicateNotification(duplicateRecipients); } }; const handleShare = async () => { const memberPublicKeys = recipients.reduce<{ [email: string]: PublicKeyReference }>( (acc, { Address, publicKey }) => { if (!publicKey) { throw new Error('No public key for member'); } acc[Address] = publicKey; return acc; }, {} ); const addressID = addresses.find(({ Email }) => Email === calendar.Email)?.ID; if (!addressID) { throw new Error('Could not find address ID for calendar owner'); } const [{ decryptedPassphraseSessionKey: sessionKey }, addressKeys] = await Promise.all([ getDecryptedPassphraseAndCalendarKeys(calendar.ID), getAddressKeys(addressID), ]); const primaryAddressKey = getPrimaryKey(addressKeys)?.privateKey; if (!primaryAddressKey) { throw new Error('Could not find primary address key for calendar owner'); } const { armoredSignature, encryptedSessionKeyMap } = await encryptPassphraseSessionKey({ sessionKey, memberPublicKeys, signingKey: primaryAddressKey, }); return api<{ Code: number; Invitations: CalendarMemberInvitation[] }>( addMember(calendar.ID, { AddressID: addressID, Signature: armoredSignature, Members: Object.keys(memberPublicKeys).map((email) => { const keyPacket = encryptedSessionKeyMap[email]; if (!keyPacket) { throw new Error('No passphrase key packet for member'); } return { Email: email, PassphraseKeyPacket: keyPacket, Permissions: permissions, }; }), }) ); }; const handleAddMembers = async () => { try { const { Invitations: newInvitations } = await handleShare(); createNotification({ type: 'success', text: c('Notification in share calendar modal').ngettext( msgid`Member added`, `Members added`, newInvitations.length ), }); onFinish?.(newInvitations); rest.onClose?.(); } catch (error) { noop(); } }; const remainingSpots = maxRecipients - totalRecipients; const maxReachedError = remainingSpots < 0 ? c('Share calendar max shares reached error').ngettext( msgid`You have exceeded the maximum of ${MAX_CALENDAR_MEMBERS} member per calendar`, `You have exceeded the maximum of ${MAX_CALENDAR_MEMBERS} members per calendar`, MAX_CALENDAR_MEMBERS ) : null; const hint = ( <span className={clsx([remainingSpots < 0 && 'color-danger'])}> {totalRecipients}/{maxRecipients} </span> ); const assistiveText = ( <span className="cursor-default"> {c('Share calendar assistive text').t`To invite non-${BRAND_NAME} users, share your calendar with a link.`}{' '} <Href href={getKnowledgeBaseUrl('/share-calendar-via-link')}> {c('Knowledge base link label').t`Here's how`} </Href> </span> ); const addressesInputText = c('Calendar access select label').t`Add people or groups`; const items = recipients.map((recipient) => { const { Name, Address, error } = recipient; const { icon, iconTooltip, labelTooltip } = getAddressInputItemAttributes(recipient); return ( <AddressesInputItem key={Address} labelTooltipTitle={labelTooltip} label={Name} labelProps={{ className: clsx(['py-1', error && 'pl-1']), }} icon={icon} iconTooltipTitle={iconTooltip} className={clsx([error && 'invalid'])} onClick={(event) => event.stopPropagation()} onRemove={() => { setRecipientsMap((map) => { const result = { ...map }; delete result[Address]; return result; }); }} /> ); }); const onAutocompleteKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => { if (event.key === 'Backspace' && event.currentTarget.value.length === 0 && totalRecipients > 0) { setRecipientsMap((map) => Object.fromEntries(Object.entries(map).slice(0, -1))); } }; const isSubmitDisabled = !totalRecipients || isLoadingRecipients || Object.values(invalidRecipients).some(isTruthy) || remainingSpots < 0; const inputId = 'input-share-privately'; const calendarName = ( <span key="bold-calendar-name" className="text-bold text-break"> {calendar.Name} </span> ); return ( <Modal size="large" {...rest} data-testid="share-calendar-privately"> <ModalHeader title={c('Share calendar modal title').t`Share with ${BRAND_NAME} users`} /> <ModalContent> <div className="mb-4"> {c('Share calendar modal description') .jt`Add the ${BRAND_NAME} accounts with whom you want to share ${calendarName}. We’ll send them an invite.`} </div> <div className="mb-4"> <InputField as={AddressesInput} ref={addressesAutocompleteRef} hint={maxReachedError ? hint : null} id={inputId} assistiveText={hasExternalRecipients ? assistiveText : null} onClick={() => { document.getElementById(inputId)?.focus(); }} autocomplete={ <AddressesAutocompleteTwo hasAddOnBlur id={inputId} compact anchorRef={addressesAutocompleteRef} contactEmails={contactEmails} excludedEmails={existingEmails} contactGroups={contactGroups} contactEmailsMap={contactEmailsMap} groupsWithContactsMap={groupsWithContactsMap} recipients={recipients} onAddRecipients={handleAddRecipients} className="min-w-custom unstyled" style={{ '--min-w-custom': '5em' }} inputClassName={clsx([ !totalRecipients && 'my-0.5', !!totalRecipients && 'p-0 rounded-none', ])} title={addressesInputText} onKeyDown={onAutocompleteKeyDown} placeholder={ recipients.length ? '' : c('Share calendar modal input placeholder') .t`Enter an email address or group name` } /> } items={items} error={maxReachedError} className={clsx(['multi-select-container', !!totalRecipients && 'px-2 py-0.5'])} label={addressesInputText} /> </div> <div> <div className=" flex flex-nowrap flex-column"> <span className="field-two-label-container" id="desc-label-permission">{c( 'Calendar permissions label' ).t`Permissions`}</span> <div> <RadioGroup name="calendar-sharing-access" options={[ { label: ( <span className="flex-item-fluid"> {c('Calendar sharing access option label') .t`View (see all event details)`} </span> ), value: MEMBER_PERMISSIONS.FULL_VIEW, }, { label: ( <span className="flex-item-fluid"> {c('Calendar sharing access option label') .t`Edit (view, create and edit event details)`} </span> ), value: MEMBER_PERMISSIONS.EDIT, }, ]} onChange={(value) => setPermissions(value)} value={permissions} aria-describedby="desc-label-permission" /> </div> <div className="color-weak"> {c('Calendar permissions hint').t`You can change or remove permissions at any time.`} </div> </div> </div> </ModalContent> <ModalFooter> <Button onClick={rest.onClose}>{c('Action').t`Cancel`}</Button> <Button loading={loadingShare} color="norm" disabled={isSubmitDisabled} type="submit" onClick={() => withLoadingShare(handleAddMembers())} > {c('Action').t`Share`} </Button> </ModalFooter> </Modal> ); }; export default ShareCalendarModal;
5,981
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/shareProton/ShareCalendarWithSignatureVerificationErrorModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { LearnMore, ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, ModalProps, } from '../../../components'; interface Props extends ModalProps { senderEmail: string; onCancel: () => void; } const ShareCalendarWithSignatureVerificationErrors = ({ senderEmail, onCancel, ...rest }: Props) => { const boldSenderEmail = ( <span key="bold-sender-email" className="text-bold text-break"> {senderEmail} </span> ); const handleCancel = () => { onCancel(); rest.onClose?.(); }; return ( <Modal {...rest} size="medium"> <ModalHeader title={c('Signature verification error when joining calendar').t`Signature verification error`} hasClose={false} /> <ModalContent> <p> {c('Signature verification error when joining calendar') .jt`You have enabled address verification for ${boldSenderEmail}. We couldn't verify the authenticity of this calendar invite. This may be due to changes in the encryption keys of this contact. Please review its advanced PGP settings, or your can ask ${boldSenderEmail} for a new invite.`} </p> <LearnMore url={getKnowledgeBaseUrl('/key-pinning')} /> </ModalContent> <ModalFooter className="flex-justify-end"> <Button onClick={handleCancel}>{c('Action').t`Cancel`}</Button> </ModalFooter> </Modal> ); }; export default ShareCalendarWithSignatureVerificationErrors;
5,982
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/shareURL/CalendarShareUrlSection.tsx
import { ComponentPropsWithoutRef, MouseEvent, useEffect, useState } from 'react'; import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms'; import { SettingsParagraph } from '@proton/components/containers'; import { useLoading } from '@proton/hooks'; import useIsMounted from '@proton/hooks/useIsMounted'; import { deletePublicLink, editPublicLink, getPublicLinks } from '@proton/shared/lib/api/calendars'; import { CALENDAR_SETTINGS_SECTION_ID, MAX_LINKS_PER_CALENDAR } from '@proton/shared/lib/calendar/constants'; import { getPrimaryCalendarKey } from '@proton/shared/lib/calendar/crypto/keys/helpers'; import { generateEncryptedPurpose, transformLinksFromAPI } from '@proton/shared/lib/calendar/sharing/shareUrl/shareUrl'; import { BRAND_NAME } from '@proton/shared/lib/constants'; import { textToClipboard } from '@proton/shared/lib/helpers/browser'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { SimpleMap, UserModel } from '@proton/shared/lib/interfaces'; import { ModalWithProps } from '@proton/shared/lib/interfaces/Modal'; import { ACCESS_LEVEL, CalendarLink, CalendarUrl, VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import { Nullable } from '@proton/shared/lib/interfaces/utils'; import { splitKeys } from '@proton/shared/lib/keys'; import { Alert, Loader } from '../../../components'; import { useApi, useGetCalendarInfo, useNotifications } from '../../../hooks'; import { useModalsMap } from '../../../hooks/useModalsMap'; import DeleteLinkConfirmationModal from './DeleteLinkConfirmationModal'; import EditLinkModal from './EditLinkModal'; import LinkTable from './LinkTable'; import ShareLinkModal from './ShareLinkModal'; import ShareLinkSuccessModal from './ShareLinkSuccessModal'; const sortLinks = (links: CalendarLink[]) => [...links].sort((a, b) => a.CreateTime - b.CreateTime); type ModalsMap = { shareLinkSuccessModal: ModalWithProps<{ onSubmit: (e: MouseEvent<HTMLButtonElement>) => void; accessLevel: ACCESS_LEVEL; link: string; }>; deleteLinkConfirmationModal: ModalWithProps<{ calendarID: string; urlID: string }>; editLinkModal: ModalWithProps<{ calendarID: string; urlID: string; purpose: Nullable<string> }>; shareLinkModal: ModalWithProps<{ calendarID: string; onSubmit: () => void }>; }; interface Props extends ComponentPropsWithoutRef<'div'> { calendar: VisualCalendar; user: UserModel; canShare: boolean; noTitle?: boolean; } const CalendarShareUrlSection = ({ calendar, user, canShare, noTitle }: Props) => { const [links, setLinks] = useState<CalendarLink[]>([]); const [isLoadingLinks, withLoadingLinks] = useLoading(); const [isLoadingMap, setIsLoadingMap] = useState<Partial<SimpleMap<boolean>>>({}); const api = useApi(); const { createNotification } = useNotifications(); const getCalendarInfo = useGetCalendarInfo(); const isMounted = useIsMounted(); const notifyLinkCopied = () => { createNotification({ type: 'info', text: c('Info').t`Link copied to clipboard` }); }; const handleError = ({ message }: Error) => createNotification({ type: 'error', text: message }); const calendarID = calendar.ID; const { modalsMap, closeModal, updateModal } = useModalsMap<ModalsMap>({ shareLinkSuccessModal: { isOpen: false }, deleteLinkConfirmationModal: { isOpen: false }, editLinkModal: { isOpen: false }, shareLinkModal: { isOpen: false }, }); const handleCreateLink = async ({ link, transformedLink, accessLevel, }: { link: string; transformedLink: CalendarLink[]; accessLevel: ACCESS_LEVEL; }) => { setLinks((prevState) => [...prevState, ...transformedLink]); updateModal('shareLinkSuccessModal', { isOpen: true, props: { onSubmit: (e: MouseEvent<HTMLButtonElement>) => { textToClipboard(link, e.currentTarget); closeModal('shareLinkSuccessModal'); notifyLinkCopied(); }, accessLevel, link, }, }); }; const toggleLinkLoading = (urlID: string, value: boolean) => { setIsLoadingMap((prevIsLoadingMap) => ({ ...prevIsLoadingMap, [urlID]: value })); }; const tryLoadingAction = async (urlID: string, fn: () => Promise<void>) => { try { toggleLinkLoading(urlID, true); await fn(); } catch (error: any) { createNotification({ type: 'error', text: error.message }); } finally { toggleLinkLoading(urlID, false); } }; const handleCopyLink = (link: string, e: MouseEvent<HTMLButtonElement>) => { textToClipboard(link, e.currentTarget); notifyLinkCopied(); }; const handleEdit = ({ urlID, purpose }: { urlID: string; purpose: Nullable<string> }) => { updateModal('editLinkModal', { isOpen: true, props: { calendarID: calendarID, urlID, purpose }, }); }; const handleDelete = ({ calendarID, urlID }: { calendarID: string; urlID: string }) => { updateModal('deleteLinkConfirmationModal', { isOpen: true, props: { calendarID, urlID }, }); }; const { editLinkModal, shareLinkSuccessModal, deleteLinkConfirmationModal, shareLinkModal } = modalsMap; const editLinkModalProps = editLinkModal.props; useEffect(() => { const getAllLinks = async () => { const { calendarKeys, passphrase } = await getCalendarInfo(calendarID); const { privateKeys } = splitKeys(calendarKeys); try { if (!isMounted()) { return; } const { CalendarUrls } = await api<{ CalendarUrls: CalendarUrl[] }>(getPublicLinks(calendarID)); const links = await transformLinksFromAPI({ calendarUrls: CalendarUrls, privateKeys, calendarPassphrase: passphrase, onError: handleError, }); const sortedLinks = sortLinks(links); if (!isMounted()) { return; } setLinks(sortedLinks); } catch (e: any) { handleError(e); } }; void withLoadingLinks(getAllLinks()); }, []); const maxLinksReached = links.length === MAX_LINKS_PER_CALENDAR; const content = ( <> <SettingsParagraph learnMoreUrl={getKnowledgeBaseUrl('/share-calendar-via-link')}> {c('Calendar settings link share description') .t`Create a link to your calendar and share it with anyone outside ${BRAND_NAME}. Only you can add or remove events.`} </SettingsParagraph> {!maxLinksReached && ( <Button onClick={() => updateModal('shareLinkModal', { isOpen: true })} color="norm" disabled={!canShare} aria-label={c('Action').t`Create a link to share with anyone outside ${BRAND_NAME}`} > {c('Action').t`Create link`} </Button> )} </> ); return ( <> <ShareLinkModal calendarID={calendarID} calendarName={calendar.Name} isOpen={shareLinkModal.isOpen} onSubmit={handleCreateLink} onClose={() => { closeModal('shareLinkModal'); }} /> {!!editLinkModalProps && ( <EditLinkModal isOpen={editLinkModal.isOpen} onSubmit={async (untrimmedPurpose) => { const { calendarID, urlID } = editLinkModalProps; return tryLoadingAction(urlID, async () => { const { calendarKeys } = await getCalendarInfo(calendarID); const { publicKey } = getPrimaryCalendarKey(calendarKeys); const purpose = untrimmedPurpose.trim(); const encryptedPurpose = purpose ? await generateEncryptedPurpose({ purpose, publicKey }) : null; await api<void>(editPublicLink({ calendarID, urlID, encryptedPurpose })); setLinks((prevState) => prevState.map((item) => { if (item.CalendarUrlID === urlID) { item.purpose = untrimmedPurpose; item.EncryptedPurpose = encryptedPurpose; } return item; }) ); closeModal('editLinkModal'); }); }} decryptedPurpose={editLinkModalProps.purpose} onClose={() => { closeModal('editLinkModal'); }} subline={calendar.Name} /> )} {!!shareLinkSuccessModal.props && ( <ShareLinkSuccessModal isOpen={shareLinkSuccessModal.isOpen} onClose={() => closeModal('shareLinkSuccessModal')} {...shareLinkSuccessModal.props} /> )} {!!deleteLinkConfirmationModal.props && ( <DeleteLinkConfirmationModal isOpen={deleteLinkConfirmationModal.isOpen} onConfirm={() => { const { calendarID, urlID } = deleteLinkConfirmationModal.props!; return tryLoadingAction(urlID, async () => { await api<void>(deletePublicLink({ calendarID, urlID })); setLinks((prevState) => prevState.filter((link) => link.CalendarUrlID !== urlID)); closeModal('deleteLinkConfirmationModal'); createNotification({ type: 'success', text: c('Info').t`Link deleted` }); }); }} onClose={() => closeModal('deleteLinkConfirmationModal')} /> )} <div className="mb-6"> {noTitle ? ( content ) : ( <> <h3 className="text-bold mb-2" id={CALENDAR_SETTINGS_SECTION_ID.SHARE_PUBLICLY}> {c('Calendar settings section title').t`Share with anyone`} </h3> {content} </> )} </div> {maxLinksReached && ( <Alert className="mb-3" type="info"> {c('Maximum calendar links reached warning').ngettext( msgid`You can create up to ${MAX_LINKS_PER_CALENDAR} link per calendar. To create a new link to this calendar, delete one from the list below.`, `You can create up to ${MAX_LINKS_PER_CALENDAR} links per calendar. To create a new link to this calendar, delete one from the list below.`, MAX_LINKS_PER_CALENDAR )} </Alert> )} {isLoadingLinks ? ( <div className="text-center"> <Loader /> </div> ) : ( <LinkTable isLoadingMap={isLoadingMap} links={links} onCopyLink={handleCopyLink} onEdit={handleEdit} onDelete={handleDelete} user={user} /> )} </> ); }; export default CalendarShareUrlSection;
5,983
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/shareURL/DeleteLinkConfirmationModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Prompt } from '../../../components'; interface DeleteLinkConfirmationModalProps { onClose: () => void; onConfirm: () => void; isOpen: boolean; } const DeleteLinkConfirmationModal = ({ onClose, onConfirm, isOpen }: DeleteLinkConfirmationModalProps) => ( <Prompt open={isOpen} onClose={onClose} buttons={[ <Button color="danger" type="submit" onClick={onConfirm}>{c('Action').t`Delete link`}</Button>, <Button onClick={onClose}>{c('Action').t`Cancel`}</Button>, ]} title={c('Info').t`Delete link?`} > {c('Info') .t`Anyone with this link won't be able to sync or get future updates for your calendar. If you want to give them access again, you will have to create a new link.`} </Prompt> ); export default DeleteLinkConfirmationModal;
5,984
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/shareURL/EditLinkModal.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { BasicModalProps } from '@proton/components/components/modalTwo/BasicModal'; import { useLoading } from '@proton/hooks'; import { MAX_CHARS_CLEARTEXT } from '@proton/shared/lib/calendar/constants'; import { Nullable } from '@proton/shared/lib/interfaces/utils'; import { BasicModal, Form, InputFieldTwo } from '../../../components'; import { useNotifications } from '../../../hooks'; interface EditLinkModalProps extends Omit<BasicModalProps, 'children' | 'footer'> { decryptedPurpose: Nullable<string>; onClose: () => void; onSubmit: (purpose: string) => Promise<void>; isOpen: boolean; } const EditLinkModal = ({ decryptedPurpose, onClose, onSubmit, ...rest }: EditLinkModalProps) => { const [purpose, setPurpose] = useState(decryptedPurpose || ''); const [isLoading, withLoading] = useLoading(); const { createNotification } = useNotifications(); const handleSubmit = async () => { const text = (() => { if (!decryptedPurpose && purpose) { return c('Calendar link purpose update success message').t`Label added`; } if (decryptedPurpose && purpose) { return c('Calendar link purpose update success message').t`Label edited`; } if (decryptedPurpose && !purpose) { return c('Calendar link purpose update success message').t`Label deleted`; } return null; })(); if (text) { await onSubmit(purpose); createNotification({ text }); } onClose(); }; return ( <BasicModal {...rest} title={decryptedPurpose ? c('Info').t`Edit label` : c('Info').t`Add label`} footer={ <> <Button onClick={onClose}>{c('Action').t`Cancel`}</Button> <Button color="norm" type="submit" loading={isLoading}>{c('Action').t`Save`}</Button> </> } size="medium" onSubmit={() => { if (!isLoading) { withLoading(handleSubmit()); } }} onClose={onClose} as={Form} > <InputFieldTwo label={c('Label').t`Link label`} assistiveText={c('Info').t`Only you can see the labels.`} placeholder={c('Shared calendar label input placeholder').t`Add label`} id="your-calendar-url-label" maxLength={MAX_CHARS_CLEARTEXT.PURPOSE} autoFocus value={purpose} // @ts-ignore onValue={(value) => setPurpose(value)} /> </BasicModal> ); }; export default EditLinkModal;
5,985
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/shareURL/LinkTable.tsx
import { MouseEvent } from 'react'; import { format, fromUnixTime } from 'date-fns'; import { c } from 'ttag'; import { dateLocale } from '@proton/shared/lib/i18n'; import { UserModel } from '@proton/shared/lib/interfaces'; import { ACCESS_LEVEL, CalendarLink } from '@proton/shared/lib/interfaces/calendar'; import { Nullable, SimpleMap } from '@proton/shared/lib/interfaces/utils'; import clsx from '@proton/utils/clsx'; import isTruthy from '@proton/utils/isTruthy'; import { DropdownActions, Icon, Info, Table, TableBody, TableHeader, TableRow } from '../../../components'; interface Props { links: CalendarLink[]; onEdit: ({ calendarID, urlID, purpose }: { calendarID: string; urlID: string; purpose: Nullable<string> }) => void; onCopyLink: (link: string, e: MouseEvent<HTMLButtonElement>) => void; onDelete: ({ calendarID, urlID }: { calendarID: string; urlID: string }) => void; isLoadingMap: SimpleMap<boolean>; user: UserModel; } const LinkTable = ({ links, onCopyLink, onDelete, onEdit, isLoadingMap, user }: Props) => { if (!links.length) { return null; } const accessHeader = c('Header').t`Access`; const labelHeader = ( <span className="flex flex-align-items-center"> <span className="mr-2">{c('Header').t`Label`}</span> <Info title={c('Info').t`Only you can see the labels.`} /> </span> ); return ( <> <Table hasActions responsive="cards"> <TableHeader cells={[accessHeader, labelHeader, c('Header').t`Actions`]} /> <TableBody> {links.map(({ CalendarID, CalendarUrlID, AccessLevel: accessLevel, link, purpose, CreateTime }) => { const list = [ user.hasNonDelinquentScope && { text: c('Action').t`Copy link`, onClick: (e: MouseEvent<HTMLButtonElement>) => onCopyLink(link, e), }, user.hasNonDelinquentScope && { text: purpose ? c('Action').t`Edit label` : c('Action').t`Add label`, onClick: () => onEdit({ calendarID: CalendarID, urlID: CalendarUrlID, purpose }), }, { text: c('Action').t`Delete link`, actionType: 'delete', onClick: () => onDelete({ calendarID: CalendarID, urlID: CalendarUrlID }), } as const, ].filter(isTruthy); const purposeOrCreatedDate = purpose || `${c('A label for unlabeled shared calendar links').t`Unlabeled`} (${format( fromUnixTime(CreateTime), 'P', { locale: dateLocale, } )})`; return ( <TableRow key={CalendarUrlID} labels={[accessHeader, labelHeader, '']} cells={[ <div key="calendar"> <div className="flex flex-align-items-center"> <Icon name="link" className="mr-2" /> {accessLevel === ACCESS_LEVEL.FULL ? c('Access level').t`Full view` : c('Access level').t`Limited view`} </div> </div>, <div key="label" className={clsx(['text-ellipsis', !purpose && 'color-weak'])} title={purposeOrCreatedDate} > {purposeOrCreatedDate} </div>, <DropdownActions loading={isLoadingMap[CalendarUrlID]} size="small" key="actions" list={list} />, ]} /> ); })} </TableBody> </Table> </> ); }; export default LinkTable;
5,986
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/shareURL/ShareLinkModal.tsx
import { useEffect, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { BasicModalProps } from '@proton/components/components/modalTwo/BasicModal'; import { useApi, useGetCalendarInfo, useNotifications } from '@proton/components/hooks'; import { createPublicLink } from '@proton/shared/lib/api/calendars'; import { MAX_CHARS_CLEARTEXT } from '@proton/shared/lib/calendar/constants'; import { getPrimaryCalendarKey } from '@proton/shared/lib/calendar/crypto/keys/helpers'; import { buildLink, generateEncryptedPurpose, getCreatePublicLinkPayload, transformLinksFromAPI, } from '@proton/shared/lib/calendar/sharing/shareUrl/shareUrl'; import { ACCESS_LEVEL, CalendarLink, CalendarUrlResponse } from '@proton/shared/lib/interfaces/calendar'; import { splitKeys } from '@proton/shared/lib/keys'; import { BasicModal, Form, InputFieldTwo, Option, SelectTwo } from '../../../components'; interface Props extends Omit<BasicModalProps, 'children' | 'footer'> { calendarID: string; calendarName: string; onSubmit: ({ link, transformedLink, accessLevel, }: { link: string; transformedLink: CalendarLink[]; accessLevel: ACCESS_LEVEL; }) => Promise<void>; onClose: () => void; isOpen: boolean; } const defaultAccessLevel = ACCESS_LEVEL.LIMITED; const ShareLinkModal = ({ calendarID, calendarName, onSubmit, onClose, isOpen, ...rest }: Props) => { const getCalendarInfo = useGetCalendarInfo(); const api = useApi(); const { createNotification } = useNotifications(); const [isLoading, setIsLoading] = useState(false); const [accessLevel, setAccessLevel] = useState<ACCESS_LEVEL>(defaultAccessLevel); const [purpose, setPurpose] = useState(''); const handleError = ({ message }: Error) => createNotification({ type: 'error', text: message }); const handleSubmit = async () => { try { setIsLoading(true); const { calendarKeys, passphrase, passphraseID } = await getCalendarInfo(calendarID); const { publicKey } = getPrimaryCalendarKey(calendarKeys); const { publicKeys } = splitKeys(calendarKeys); const encryptedPurpose = purpose ? await generateEncryptedPurpose({ purpose, publicKey }) : null; const { payload, passphraseKey, cacheKey } = await getCreatePublicLinkPayload({ accessLevel, publicKeys, passphrase, passphraseID, encryptedPurpose, }); const { CalendarUrl } = await api<CalendarUrlResponse>(createPublicLink(calendarID, payload)); const { CalendarUrlID } = CalendarUrl; const link = buildLink({ urlID: CalendarUrlID, accessLevel, passphraseKey, cacheKey, }); const { privateKeys } = splitKeys(calendarKeys); const transformedLink = await transformLinksFromAPI({ calendarUrls: [CalendarUrl], privateKeys, calendarPassphrase: passphrase, onError: handleError, }); createNotification({ type: 'success', text: c('Info').t`Link created` }); setIsLoading(false); await onSubmit({ link, transformedLink, accessLevel }); onClose(); } catch (e: any) { setIsLoading(false); const error = e instanceof Error ? e : new Error('Failed to generate link'); throw error; } }; useEffect(() => { if (!isOpen) { setPurpose(''); setAccessLevel(defaultAccessLevel); } }, [isOpen]); return ( <BasicModal {...rest} isOpen={isOpen} title={c('Title').t`Create public link`} subline={calendarName} footer={ <> <Button onClick={onClose}>{c('Action').t`Cancel`}</Button> <Button type="submit" loading={isLoading} className="ml-auto" onClick={handleSubmit} color="norm">{c( 'Action' ).t`Create`}</Button> </> } onClose={onClose} size="medium" as={Form} > <InputFieldTwo label={c('Input label').t`Access`} as={SelectTwo} value={accessLevel} onValue={(value: any) => setAccessLevel(value)} > <Option value={0} title={c('Access level').t`Limited view (see only free/busy)`} /> <Option value={1} title={c('Access level').t`Full view (see all event details)`} /> </InputFieldTwo> <InputFieldTwo value={purpose} onValue={setPurpose} maxLength={MAX_CHARS_CLEARTEXT.PURPOSE} label={c('Input label').t`Label (optional)`} assistiveText={c('Calendar link sharing label input assistive text').t`Only you can see the label`} placeholder={c('Input placeholder').t`Add label`} /> </BasicModal> ); }; export default ShareLinkModal;
5,987
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/shareURL/ShareLinkSuccessModal.tsx
import { MouseEvent } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { BRAND_NAME } from '@proton/shared/lib/constants'; import { ACCESS_LEVEL } from '@proton/shared/lib/interfaces/calendar'; import { BasicModal } from '../../../components'; interface Props { link: string; onSubmit: (e: MouseEvent<HTMLButtonElement>) => void; onClose: () => void; accessLevel: ACCESS_LEVEL; isOpen: boolean; } const ShareLinkSuccessModal = ({ link, onSubmit, onClose, accessLevel, isOpen }: Props) => { return ( <BasicModal title={c('Title').t`Your calendar link`} footer={ <> <Button onClick={onClose}>{c('Action').t`Cancel`}</Button> <Button className="ml-auto" onClick={onSubmit} color="norm">{c('Action').t`Copy link`}</Button> </> } size="medium" onClose={onClose} isOpen={isOpen} > <div className="color-weak"> {accessLevel === ACCESS_LEVEL.FULL ? ( <> <p className="mt-0">{c('Info') .t`By sharing the full event details of this calendar, you accept to grant ${BRAND_NAME} access to this calendar's encrypted information.`}</p> <p>{c('Info') .t`Anyone with this link can see all the event details of this calendar such as title, location or participants.`}</p> </> ) : ( <p className="mt-0"> {c('Info') .t`Anyone with this link can see whether you’re free or busy on your calendar. They can’t see event details, such as title, location, or participants.`} </p> )} </div> <label htmlFor="your-calendar-url" className="sr-only"> {c('Label').t`Your calendar URL`} </label> <div className="border p-4 rounded text-break-all">{link}</div> </BasicModal> ); }; export default ShareLinkSuccessModal;
5,988
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/shareURL/useCalendarShareUrls.ts
import { useEffect, useMemo, useState } from 'react'; import { useLoading } from '@proton/hooks'; import { getIsCalendarUrlEventManagerCreate, getIsCalendarUrlEventManagerDelete, getIsCalendarUrlEventManagerUpdate, transformLinkFromAPI, transformLinksFromAPI, } from '@proton/shared/lib/calendar/sharing/shareUrl/shareUrl'; import { getIsCalendarEventManagerDelete } from '@proton/shared/lib/eventManager/calendar/helpers'; import { SimpleMap } from '@proton/shared/lib/interfaces'; import { CalendarLink, CalendarUrl, VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import { CalendarEventManager, CalendarUrlEventManager, CalendarUrlEventManagerDelete, } from '@proton/shared/lib/interfaces/calendar/EventManager'; import { splitKeys } from '@proton/shared/lib/keys'; import updateItem from '@proton/utils/updateItem'; import { useEventManager, useGetCalendarInfo, useNotifications } from '../../../hooks'; import { useGetCalendarPublicLinks } from '../../../hooks/useGetCalendarPublicLinks'; import { useCalendarModelEventManager } from '../../eventManager/calendar'; const useCalendarShareUrls = (calendars: VisualCalendar[]) => { const { createNotification } = useNotifications(); const getCalendarInfo = useGetCalendarInfo(); const getPublicLinks = useGetCalendarPublicLinks(); const { subscribe: coreSubscribe } = useEventManager(); const { subscribe: calendarSubscribe } = useCalendarModelEventManager(); const [linksMap, setLinksMap] = useState<SimpleMap<CalendarLink[]>>({}); const [loading, withLoading] = useLoading(true); const calendarIDs = useMemo(() => calendars.map(({ ID }) => ID), [calendars]); const handleError = ({ message }: Error) => createNotification({ type: 'error', text: message }); const handleDeleteCalendar = (calendarID: string) => { setLinksMap((linksMap) => { const newMap = { ...linksMap }; delete newMap[calendarID]; return newMap; }); }; const handleDeleteLink = ({ ID }: CalendarUrlEventManagerDelete) => { setLinksMap((linksMap) => { return Object.fromEntries( Object.entries(linksMap).map(([calendarID, links]) => { const newLinks = links?.filter(({ CalendarUrlID }) => CalendarUrlID !== ID); return [calendarID, newLinks]; }) ); }); }; const handleAddOrUpdateLink = async (calendarUrl: CalendarUrl) => { const { CalendarID } = calendarUrl; const calendar = calendars.find(({ ID }) => ID === CalendarID); if (!calendar) { return; } const { calendarKeys, passphrase } = await getCalendarInfo(CalendarID); const { privateKeys } = splitKeys(calendarKeys); const link = await transformLinkFromAPI({ calendarUrl, privateKeys, calendarPassphrase: passphrase, onError: handleError, }); setLinksMap((linksMap) => { const previousLinks = linksMap[CalendarID] || []; const linkIndex = previousLinks.findIndex( ({ CalendarUrlID }) => CalendarUrlID === calendarUrl.CalendarUrlID ); const newLinks = linkIndex === -1 ? [...previousLinks, link] : updateItem(previousLinks, linkIndex, link); return { ...linksMap, [CalendarID]: newLinks, }; }); }; // load links useEffect(() => { const getAllLinks = async () => { const map: SimpleMap<CalendarLink[]> = {}; await Promise.all( calendars.map(async (calendar) => { const calendarID = calendar.ID; const { calendarKeys, passphrase } = await getCalendarInfo(calendarID); const { privateKeys } = splitKeys(calendarKeys); try { const { CalendarUrls } = await getPublicLinks(calendarID); map[calendarID] = await transformLinksFromAPI({ calendarUrls: CalendarUrls, privateKeys, calendarPassphrase: passphrase, onError: handleError, }); } catch (e: any) { handleError(e); } }) ); setLinksMap(map); }; void withLoading(getAllLinks()); }, []); // subscribe to general event loop useEffect(() => { return coreSubscribe(({ Calendars = [] }: { Calendars?: CalendarEventManager[] }) => { Calendars.forEach((event) => { if (getIsCalendarEventManagerDelete(event)) { handleDeleteCalendar(event.ID); } }); }); }, []); // subscribe to calendar event loop useEffect(() => { return calendarSubscribe( calendarIDs, ({ CalendarURL: CalendarURLEvents = [] }: { CalendarURL?: CalendarUrlEventManager[] }) => { CalendarURLEvents.forEach((event) => { if (getIsCalendarUrlEventManagerDelete(event)) { handleDeleteLink(event); } if (getIsCalendarUrlEventManagerCreate(event) || getIsCalendarUrlEventManagerUpdate(event)) { // TODO: The code below is prone to race conditions. Namely if a new event manager update // comes before this promise is resolved. void handleAddOrUpdateLink(event.CalendarUrl); } }); } ); }, [calendarIDs]); return { linksMap, isLoadingLinks: loading, }; }; export default useCalendarShareUrls;
5,989
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/subscribedCalendarModal/SubscribedCalendarModal.test.tsx
import { render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import createCache from '@proton/shared/lib/helpers/cache'; import { CALENDAR_SUBSCRIPTION_STATUS } from '@proton/shared/lib/interfaces/calendar'; import { CacheProvider } from '../../cache'; import SubscribedCalendarModal from './SubscribedCalendarModal'; jest.mock('../hooks/useGetCalendarSetup', () => () => ({})); jest.mock('@proton/components/hooks/useNotifications', () => () => ({})); jest.mock('../calendarModal/calendarModalState', () => ({ ...jest.requireActual('../calendarModal/calendarModalState'), getDefaultModel: jest.fn(() => ({ calendarID: '7824929ac66f483ba12ee051c056b9e5', name: 'A fake calendar', members: [], description: 'a fake description', color: '#8080FF', display: true, addressID: 'fa4ea8f5e6ac4df494f8190a6c9d9bd9', addressOptions: [], duration: 30, type: 0, })), })); const mockApi = jest.fn(); jest.mock('@proton/components/hooks/useApi', () => ({ __esModule: true, default: jest.fn(() => mockApi), })); const mockHandleCreateCalendar = jest.fn(); jest.mock('../hooks/useGetCalendarActions', () => ({ __esModule: true, default: jest.fn(() => ({ handleCreateCalendar: mockHandleCreateCalendar, })), })); jest.mock('@proton/components/hooks/useEventManager', () => ({ __esModule: true, default: jest.fn(() => ({ call: jest.fn(), subscribe: jest.fn(), })), })); jest.mock('@proton/components/containers/eventManager/calendar/ModelEventManagerProvider', () => ({ useCalendarModelEventManager: jest.fn(() => ({ subscribe: jest.fn(), })), })); function renderComponent() { const Wrapper = ({ children }: { children: any }) => ( <CacheProvider cache={createCache()}>{children}</CacheProvider> ); return render(<SubscribedCalendarModal open />, { wrapper: Wrapper }); } describe('SubscribedCalendarModal', () => { afterEach(() => { mockApi.mockReset(); mockHandleCreateCalendar.mockReset(); }); describe('when validation API returns a validation error', () => { it('should display an error message and not call mockUseGetCalendarActions', async () => { renderComponent(); mockApi.mockResolvedValue({ ValidationResult: { Result: CALENDAR_SUBSCRIPTION_STATUS.INVALID_URL } }); const submitButton = screen.getByText('Add calendar', { selector: 'button' }); const input = screen.getByLabelText('Calendar URL'); const invalidGoogleCalendarLink = `https://calendar.google.com/public/a.ics`; expect(submitButton).toBeDisabled(); input.focus(); await userEvent.paste(invalidGoogleCalendarLink); expect(submitButton).toBeEnabled(); await userEvent.click(submitButton); await screen.findByText('Invalid URL'); expect(mockApi).toHaveBeenCalledTimes(1); expect(mockApi).toHaveBeenCalledWith({ data: { Mode: 1, URL: 'https://calendar.google.com/public/a.ics' }, method: 'post', silence: true, url: 'calendar/v1/subscription/validate', }); expect(mockHandleCreateCalendar).not.toHaveBeenCalled(); }); }); describe('when validation returns OK', () => { it('should call `handleCreateCalendar`', async () => { renderComponent(); mockApi.mockResolvedValue({ ValidationResult: { Result: CALENDAR_SUBSCRIPTION_STATUS.OK } }); mockHandleCreateCalendar.mockImplementation(() => Promise.resolve()); const submitButton = screen.getByText('Add calendar', { selector: 'button' }); const input = screen.getByLabelText('Calendar URL'); const invalidGoogleCalendarLink = `https://calendar.google.com/public/a.ics`; expect(submitButton).toBeDisabled(); input.focus(); await userEvent.paste(invalidGoogleCalendarLink); expect(submitButton).toBeEnabled(); await userEvent.click(submitButton); // wait for the last api call to be made await waitFor(() => expect(mockHandleCreateCalendar).toHaveBeenCalledTimes(1)); expect(mockApi).toHaveBeenCalledTimes(1); expect(mockApi).toHaveBeenCalledWith({ data: { Mode: 1, URL: 'https://calendar.google.com/public/a.ics' }, method: 'post', silence: true, url: 'calendar/v1/subscription/validate', }); expect(mockHandleCreateCalendar).toHaveBeenCalledWith( 'fa4ea8f5e6ac4df494f8190a6c9d9bd9', { Color: '#8080FF', Description: 'a fake description', Display: 1, Name: 'https://calendar.google.com/public/a.ics', URL: 'https://calendar.google.com/public/a.ics', }, { DefaultEventDuration: 30, DefaultFullDayNotifications: [], DefaultPartDayNotifications: [] } ); }); }); });
5,990
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar
petrpan-code/ProtonMail/WebClients/packages/components/containers/calendar/subscribedCalendarModal/SubscribedCalendarModal.tsx
import { ChangeEvent, useState } from 'react'; import { c } from 'ttag'; import { Button, Href } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { validateSubscription } from '@proton/shared/lib/api/calendars'; import { MAX_CHARS_API } from '@proton/shared/lib/calendar/constants'; import { getCalendarStatusInfo } from '@proton/shared/lib/calendar/subscribe/helpers'; import { HTTP_STATUS_CODE } from '@proton/shared/lib/constants'; import { truncateMore } from '@proton/shared/lib/helpers/string'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { CALENDAR_SUBSCRIPTION_STATUS, VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import { BasicModal, Form, InputFieldTwo, Loader } from '../../../components'; import { useApi } from '../../../hooks'; import { GenericError } from '../../error'; import { getCalendarPayload, getCalendarSettingsPayload, getDefaultModel } from '../calendarModal/calendarModalState'; import useGetCalendarActions from '../hooks/useGetCalendarActions'; import useGetCalendarSetup from '../hooks/useGetCalendarSetup'; interface Props { open: boolean; onClose?: () => void; onExit?: () => void; onCreateCalendar?: (id: string) => void; } const SubscribedCalendarModal = ({ open, onClose, onExit, onCreateCalendar }: Props) => { const [, setCalendar] = useState<VisualCalendar | undefined>(); const [calendarURL, setCalendarURL] = useState(''); const [model, setModel] = useState(() => getDefaultModel()); const [error, setError] = useState(false); const [validationError, setValidationError] = useState<CALENDAR_SUBSCRIPTION_STATUS>(); const [loadingAction, withLoadingAction] = useLoading(); const api = useApi(); const { error: setupError, loading: loadingSetup } = useGetCalendarSetup({ setModel }); const handleClose = () => { setValidationError(undefined); setCalendarURL(''); onClose?.(); }; const { handleCreateCalendar } = useGetCalendarActions({ setCalendar, setError, onClose: handleClose, onCreateCalendar, isSubscribedCalendar: true, }); const handleProcessCalendar = async () => { const formattedModel = { ...model, name: truncateMore({ string: calendarURL, charsToDisplay: MAX_CHARS_API.CALENDAR_NAME }), url: calendarURL, }; const calendarPayload = getCalendarPayload(formattedModel); const calendarSettingsPayload = getCalendarSettingsPayload(formattedModel); const { ValidationResult: { Result: result }, } = await api<{ ValidationResult: { Result: CALENDAR_SUBSCRIPTION_STATUS } }>({ ...validateSubscription({ url: calendarURL }), silence: true, }).catch((error) => { if (error?.status === HTTP_STATUS_CODE.UNPROCESSABLE_ENTITY) { return { ValidationResult: { Result: CALENDAR_SUBSCRIPTION_STATUS.INVALID_URL } }; } return { ValidationResult: { Result: CALENDAR_SUBSCRIPTION_STATUS.OK } }; }); if (result === CALENDAR_SUBSCRIPTION_STATUS.OK) { return handleCreateCalendar(formattedModel.addressID, calendarPayload, calendarSettingsPayload); } setValidationError(result); }; const { title, submitProps, errorContent = null, onSubmit, } = (() => { const disabled = !calendarURL || !!validationError; if (error || setupError) { const onSubmitError = () => window.location.reload(); return { title: c('Title').t`Error`, errorContent: <GenericError />, onSubmit: onSubmitError, submitProps: { children: c('Action').t`Close`, disabled, }, }; } const loading = loadingSetup || loadingAction; const onSubmit = () => withLoadingAction(handleProcessCalendar()); const titleAndSubmitCopy = c('Modal title and action').t`Add calendar`; return { title: titleAndSubmitCopy, onSubmit, submitProps: { loading, children: titleAndSubmitCopy, disabled, }, }; })(); const kbLink = ( <Href key="kbLink" href={getKnowledgeBaseUrl('/subscribe-to-external-calendar')}>{c( 'Subscribe to calendar modal description' ).t`Learn how to get a private calendar link.`}</Href> ); const getError = () => { if (validationError === CALENDAR_SUBSCRIPTION_STATUS.INVALID_URL) { return c('Error message').t`Invalid URL`; } if (validationError) { return getCalendarStatusInfo(validationError)?.text; } return null; }; return ( <BasicModal title={title} footer={ <> <Button onClick={handleClose}>{c('Action').t`Cancel`}</Button> <Button type="submit" color="norm" {...submitProps} /> </> } isOpen={open} className="modal--shorter-labels w-full" onClose={handleClose} as={Form} dense onSubmit={() => { if (!submitProps.loading) { void onSubmit(); } }} onExit={onExit} > {loadingSetup ? ( <Loader /> ) : ( errorContent || ( <> <p className="mt-0 text-pre-wrap">{c('Subscribe to calendar modal') .jt`To subscribe to an external or public calendar and its updates, enter the URL. A read-only version of the calendar will be added to your Other calendars. ${kbLink} `}</p> <InputFieldTwo autoFocus error={getError()} label={c('Subscribe to calendar modal').t`Calendar URL`} value={calendarURL} onChange={(e: ChangeEvent<HTMLInputElement>) => { setValidationError(undefined); setCalendarURL(e.target.value.trim()); }} data-testid="input:calendar-subscription" /> </> ) )} </BasicModal> ); }; export default SubscribedCalendarModal;
5,991
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/challenge/Challenge.tsx
import { useRef, useState } from 'react'; import { getApiSubdomainUrl } from '@proton/shared/lib/helpers/url'; import randomIntFromInterval from '@proton/utils/randomIntFromInterval'; import ChallengeError from './ChallengeError'; import ChallengeFrame, { Props as ChallengeProps } from './ChallengeFrame'; import { ChallengeLog } from './interface'; interface Props extends Omit<ChallengeProps, 'src' | 'onError' | 'onSuccess'> { type: number; name: string; iframeClassName?: string; onSuccess: (challengeLog: ChallengeLog[]) => void; onError: (challengeLog: ChallengeLog[]) => void; } const Challenge = ({ children, style, onSuccess, onError, bodyClassName, iframeClassName, name, type, ...rest }: Props) => { const [error, setError] = useState(false); const [errorRetry, setErrorRetry] = useState(0); const challengeLogRef = useRef<ChallengeLog[]>([]); const challengeSrc = (() => { const url = getApiSubdomainUrl('/challenge/v4/html'); url.searchParams.set('Type', `${type}`); url.searchParams.set('Name', name); if (errorRetry) { url.searchParams.set('Retry', `${errorRetry}`); } return url.toString(); })(); // Loading error timeouts in intervals of [12, 15], [17, 20], [22, 25] const jitter = randomIntFromInterval(0, 3); const errorTimeout = (15 + errorRetry * 5 - jitter) * 1000; if (error) { if (rest.empty) { return null; } return <ChallengeError />; } return ( <ChallengeFrame key={errorRetry} src={challengeSrc} errorTimeout={errorTimeout} className={iframeClassName ? iframeClassName : 'w-full'} bodyClassName={bodyClassName} style={style} onSuccess={() => { onSuccess?.(challengeLogRef.current); }} onError={(challengeLog) => { challengeLogRef.current = challengeLogRef.current.concat(challengeLog); if (errorRetry < 2) { setErrorRetry(errorRetry + 1); return; } setError(true); onError?.(challengeLogRef.current); }} {...rest} > {children} </ChallengeFrame> ); }; export default Challenge;
5,992
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/challenge/ChallengeError.tsx
import { c } from 'ttag'; import { Alert } from '../../components/alert'; import { InlineLinkButton } from '../../components/button'; import { useModalState } from '../../components/modalTwo'; import { BugModal } from '../support'; const ChallengeError = () => { const [bugReportModal, setBugReportModal, render] = useModalState(); const refresh = ( <InlineLinkButton key="refresh" onClick={() => window.location.reload()}>{c('Action') .t`refresh the page`}</InlineLinkButton> ); const supportTeam = ( <InlineLinkButton key="support" title="Contact the support team." onClick={() => { setBugReportModal(true); }} > {c('Info').t`support team`} </InlineLinkButton> ); return ( <> {render && <BugModal {...bugReportModal} />} <Alert className="mb-4" type="error"> {c('Error') .jt`Something went wrong, please ${refresh} in order to proceed. If you still see this error message please contact our ${supportTeam}.`} </Alert> </> ); }; export default ChallengeError;
5,993
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/challenge/ChallengeFrame.tsx
import { DetailedHTMLProps, IframeHTMLAttributes, MutableRefObject, ReactNode, useLayoutEffect, useMemo, useRef, useState, } from 'react'; import { ICONS_ID } from '../../components/icon/Icons'; import { useActiveBreakpoint } from '../../hooks'; import { THEME_ID } from '../themes/ThemeProvider'; import { getStyleSrcUrls, getStyleSrcsData, handleEvent } from './challengeHelper'; import { ChallengeLog, ChallengeLogType, ChallengeRef, ChallengeResult } from './interface'; export const ERROR_TIMEOUT_MS = 15000; export const CHALLENGE_TIMEOUT_MS = 9000; type Stage = 'initialize' | 'initialized' | 'load' | 'loaded' | 'error'; export interface Props extends Omit<DetailedHTMLProps<IframeHTMLAttributes<HTMLIFrameElement>, HTMLIFrameElement>, 'onClick' | 'onError'> { challengeRef: MutableRefObject<ChallengeRef | undefined>; children?: ReactNode; src: string; className?: string; empty?: boolean; bodyClassName?: string; hasSizeObserver?: boolean; title?: string; onError?: (logs: ChallengeLog[]) => void; onSuccess?: () => void; errorTimeout?: number; challengeTimeout?: number; } const ChallengeFrame = ({ onSuccess, onError, title, children, className, empty, bodyClassName = '', challengeRef, src, hasSizeObserver, errorTimeout = ERROR_TIMEOUT_MS, challengeTimeout = CHALLENGE_TIMEOUT_MS, ...rest }: Props) => { const iframeRef = useRef<HTMLIFrameElement>(null); const [isLoaded, setIsLoaded] = useState(false); const renderDivRef = useRef<HTMLDivElement>(null); const activeBreakpoint = useActiveBreakpoint(); const targetOrigin = useMemo(() => { return new URL(src).origin; }, [src]); useLayoutEffect(() => { let isMounted = true; let stage: Stage = 'initialize'; const setStage = (newStage: Stage) => { stage = newStage; }; const logs: ChallengeLog[] = []; const tmpUrl = new URL(src); const addLog = (text: string, data: unknown, type: ChallengeLogType) => { // To keep it somewhat limited if (logs.length > 20) { return; } const log: ChallengeLog = { type, text: `${new Date().toISOString()} ${text} ${tmpUrl.searchParams.toString()}`, }; // The sentry serializer doesn't like undefined values if (data) { log.data = data; } logs.push(log); }; let error = false; const handleError = () => { // If already notified if (error) { return; } error = true; setStage('error'); if (!isMounted) { return; } onError?.(logs); }; let errorTimeoutHandle = window.setTimeout(() => { addLog('Initial iframe timeout', undefined, 'error'); handleError(); }, errorTimeout); let challengeResolve: (data: { [key: string]: string }) => void; const handleLoaded = () => { if (!isMounted) { return; } setIsLoaded(true); onSuccess?.(); }; const stylesPromise = empty ? Promise.resolve('') : getStyleSrcsData(getStyleSrcUrls()); const cb = (event: MessageEvent) => { const iframe = iframeRef.current; const contentWindow = iframe?.contentWindow; if ( error || !iframe || !contentWindow || event.origin !== targetOrigin || event.source !== contentWindow || !isMounted ) { return; } const eventData = event.data; const eventDataType = eventData?.type; const eventDataPayload = eventData?.payload; if (eventDataType === 'init' && stage === 'initialize') { clearTimeout(errorTimeoutHandle); setStage('initialized'); addLog('Initialized', undefined, 'step'); stylesPromise .then((styles) => { if (!isMounted) { return; } clearTimeout(errorTimeoutHandle); errorTimeoutHandle = window.setTimeout(() => { addLog('Load iframe error', undefined, 'error'); handleError(); }, errorTimeout); const themeNodeData = empty ? '' : document.querySelector(`#${THEME_ID}`)?.innerHTML ?? ''; const iconsNodeData = empty ? '' : document.querySelector(`#${ICONS_ID}`)?.innerHTML ?? ''; setStage('load'); addLog( 'Sending data', [themeNodeData, styles, iconsNodeData].map((x) => x.slice(0, 30)).join(' - '), 'step' ); contentWindow.postMessage( { type: 'load', payload: { iconsRoot: `${iconsNodeData}`, stylesRoot: `${styles}\n${themeNodeData}`, hasSizeObserver, bodyClassName, }, }, targetOrigin ); }) .catch((error) => { addLog('CSS load error', { error }, 'error'); handleError(); }); } if (eventDataType === 'onload' && stage === 'load') { clearTimeout(errorTimeoutHandle); setStage('loaded'); addLog('Fully loaded', undefined, 'step'); handleLoaded(); } if (eventDataType === 'onerror') { addLog('Script error', { error: eventDataPayload }, 'message'); } if (eventDataType === 'event' && stage === 'loaded' && renderDivRef.current) { handleEvent(renderDivRef.current, eventDataPayload); } if (eventDataType === 'rect' && stage === 'loaded' && eventDataPayload?.height !== undefined) { iframe.classList.add('h-custom'); iframe.style.setProperty('--h-custom', `${eventDataPayload.height}px`); } if (eventDataType === 'child.message.data' && stage === 'loaded') { const messageData = eventData.data; if (!messageData) { return; } challengeResolve?.({ [messageData.id]: messageData.fingerprint, }); } }; challengeRef.current = { focus: (selector: string) => { const contentWindow = iframeRef.current?.contentWindow; if (!contentWindow || stage !== 'loaded') { return; } contentWindow.postMessage( { type: 'focus', payload: { selector, }, }, targetOrigin ); }, getChallenge: () => { return new Promise<ChallengeResult | undefined>((resolve, reject) => { const contentWindow = iframeRef.current?.contentWindow; if (!contentWindow || stage !== 'loaded') { return reject(new Error('No iframe available')); } challengeResolve = resolve; contentWindow.postMessage( { type: 'env.loaded', data: { targetOrigin: window.location.origin, }, }, targetOrigin ); contentWindow.postMessage( { type: 'submit.broadcast', }, targetOrigin ); errorTimeoutHandle = window.setTimeout(() => { reject(new Error('Challenge timeout')); }, challengeTimeout); }); }, }; addLog('Added listener', undefined, 'step'); window.addEventListener('message', cb); return () => { window.removeEventListener('message', cb); clearTimeout(errorTimeoutHandle); isMounted = false; }; }, []); useLayoutEffect(() => { const contentWindow = iframeRef.current?.contentWindow; const renderDivEl = renderDivRef.current; const iframe = iframeRef.current; if (iframe && renderDivEl && (!hasSizeObserver || !isLoaded)) { const rect = renderDivEl.getBoundingClientRect(); iframe.classList.add('h-custom'); iframe.style.setProperty('--h-custom', `${rect.height}px`); } if (!renderDivEl || !contentWindow || !isLoaded) { return; } contentWindow.postMessage( { type: 'html', payload: `<div class='${activeBreakpoint.breakpoint}'>${renderDivEl.innerHTML}</div>`, }, targetOrigin ); }, [isLoaded, activeBreakpoint.breakpoint, children, iframeRef.current, renderDivRef.current]); return ( <> <div ref={renderDivRef} style={{ position: 'absolute', '--left-custom': '-1000px', '--top-custom': '-1000px' }} aria-hidden="true" className="visibility-hidden top-custom left-custom" > {children} </div> <iframe {...rest} src={src} ref={iframeRef} title={title} className={className} sandbox="allow-scripts allow-same-origin allow-popups" /> </> ); }; export default ChallengeFrame;
5,994
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/challenge/challengeHelper.ts
import ReactTestUtils from 'react-dom/test-utils'; import { getTimezone } from '@proton/shared/lib/date/timezone'; import { captureMessage } from '@proton/shared/lib/helpers/sentry'; import { getBrowserLocale } from '@proton/shared/lib/i18n/helper'; import { ChallengeLog } from './interface'; // Select option is broken on react. Correct the HTML here. export const normalizeSelectOptions = (el: HTMLElement) => { el.querySelectorAll('select').forEach((selectEl) => { for (let i = 0; i < selectEl.children.length; ++i) { const liEl = selectEl.children[i]; if (i === selectEl.selectedIndex) { liEl.setAttribute('selected', 'true'); } else { liEl.removeAttribute('selected'); } } }); }; interface EventPayload { type: string; id?: string; value?: string; key?: string; } export const handleEvent = (renderEl: HTMLElement | undefined, eventPayload: EventPayload) => { if (!renderEl) { return; } const { type, id } = eventPayload; if (type === 'keydown' && id) { const inputEl = renderEl.querySelector<HTMLInputElement>(`#${id}`); if (inputEl) { ReactTestUtils.Simulate.keyDown(inputEl, { key: eventPayload.key }); } } if (type === 'input' && id) { const inputEl = renderEl.querySelector<HTMLInputElement>(`#${id}`); if (inputEl) { inputEl.value = eventPayload.value || ''; ReactTestUtils.Simulate.change(inputEl); } } if (type === 'click' && id) { const targetEl = renderEl.querySelector(`#${id}`); if (targetEl) { ReactTestUtils.Simulate.click(targetEl); } } }; export const getStyleSrcUrls = () => { return [...document.querySelectorAll<HTMLLinkElement>('link[rel=stylesheet]')].reduce<string[]>((acc, link) => { const url = new URL(link.href, window.location.origin); if (url.origin.startsWith(window.location.origin) && url.pathname.endsWith('.css')) { acc.push(url.toString()); } return acc; }, []); }; export const getStyleSrcsData = (styleSrcUrls: string[]) => { return Promise.all( styleSrcUrls.map(async (styleSrcUrls) => { const response = await fetch(styleSrcUrls); const text = await response.text(); const trimmedText = text.replace(/^\s+/, ''); if (!(response.status >= 200 && response.status < 300) || trimmedText[0] === '<') { throw new Error('Invalid asset loading'); } return [...trimmedText.matchAll(/url\(\/(assets\/[^)]+)\)/g)] .map((matchArray) => { const [all, match] = matchArray; const newUrl = new URL(match, window.location.origin); // Chrome uses the cached font response making CORS fail. // Cache bust it by adding a query parameter. newUrl.searchParams.set('t', `${Date.now()}`); return { all, newUrl: newUrl.toString(), }; }) .reduce((acc, cur) => { return acc.replace(cur.all, `url(${cur.newUrl})`); }, trimmedText); }) ).then((results) => { return results.join(''); }); }; export const captureChallengeMessage = (message: string, logs: ChallengeLog[]) => { if ( !logs.some(({ type }) => { return type === 'error'; }) ) { return; } captureMessage(message, { level: 'error', extra: { logs, locale: getBrowserLocale(), timezone: getTimezone(), time: new Date().toString(), }, }); };
5,995
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/challenge/index.ts
export { default as Challenge } from './Challenge'; export { default as ChallengeError } from './ChallengeError'; export { default as ChallengeFrame } from './ChallengeFrame'; export { captureChallengeMessage } from './challengeHelper'; export * from './interface';
5,996
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/challenge/interface.ts
export type ChallengeLogType = 'message' | 'error' | 'step'; export interface ChallengeLog { type: ChallengeLogType; text: string; data?: unknown; } export type ChallengeResult = { [key: string]: string } | undefined; export interface ChallengeRef { focus: (selector: string) => void; getChallenge: () => Promise<ChallengeResult>; }
5,997
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/compatibilityCheck/CompatibilityCheck.tsx
import { ReactNode, useEffect, useState } from 'react'; import { decryptData, encryptData, getKey } from '@proton/shared/lib/authentication/cryptoHelper'; import { useConfig } from '../../hooks'; import CompatibilityCheckView from './CompatibilityCheckView'; import { getCompatibilityList } from './compatibilityCheckHelper'; interface Props { children: ReactNode; } const CompatibilityCheck = ({ children }: Props) => { const { APP_NAME } = useConfig(); const [incompatibilities, setIncompatibilities] = useState(() => { return getCompatibilityList().filter(({ valid }) => !valid); }); useEffect(() => { const run = async () => { const key = await getKey(new Uint8Array(16)); const data = await encryptData(key, new Uint8Array(16)); return decryptData(key, data); }; run().catch(() => { setIncompatibilities([ ...incompatibilities, { name: 'WebCrypto', valid: false, text: 'Please update to a browser compatible with AES-GCM encryption.', }, ]); }); }, []); if (!incompatibilities.length) { return <>{children}</>; } return <CompatibilityCheckView appName={APP_NAME} incompatibilities={incompatibilities} />; }; export default CompatibilityCheck;
5,998
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/compatibilityCheck/CompatibilityCheckView.tsx
import { Href } from '@proton/atoms'; import { getAppName } from '@proton/shared/lib/apps/helper'; import { APPS, APP_NAMES } from '@proton/shared/lib/constants'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import unsupportedBrowserSettings from '@proton/styles/assets/img/errors/unsupported-browser.svg'; import { useAppTitle } from '../../hooks'; interface Props { appName: APP_NAMES; incompatibilities: { name: string; text: string }[]; } // Note: This is not translated because locales are not loaded at this point const CompatibilityCheckView = ({ appName = APPS.PROTONMAIL, incompatibilities }: Props) => { const isVPN = appName === APPS.PROTONVPN_SETTINGS; const kbUrl = isVPN ? 'https://protonvpn.com/support/browsers-supported/' : getKnowledgeBaseUrl('/recommended-browsers'); useAppTitle('Compatibility check'); const app = getAppName(appName); return ( <div className="w-full md:w-1/2 p-7 mt-8 mx-auto text-lg"> <div className="text-center"> <h1>Compatibility check</h1> <p> {app} requires a modern web browser with cutting edge support for{' '} <Href className="primary-link" href="http://caniuse.com/#feat=cryptography"> WebCrypto (PRNG) </Href>{' '} and{' '} <Href className="primary-link" href="http://caniuse.com/#feat=namevalue-storage"> Web Storage </Href> . </p> <Href className="primary-link text-bold" href={kbUrl} target="_self"> More info </Href> </div> <div className="mt-8 text-center"> <img src={unsupportedBrowserSettings} alt="Compatibility check" /> </div> <ul> {incompatibilities.map(({ name, text }, i) => { return ( <li key={i}> {name}: {text} </li> ); })} </ul> </div> ); }; export default CompatibilityCheckView;
5,999