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/mnemonic/index.ts
export { default as DisableMnemonicModal } from './DisableMnemonicModal'; export { default as GenerateMnemonicModal } from './GenerateMnemonicModal'; export * from './helper';
6,500
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/modals/Children.tsx
import { useContext } from 'react'; import ModalsContainer from './Container'; import ModalsChildrenContext from './childrenContext'; import ModalsContext from './modalsContext'; const ModalsChildren = () => { const manager = useContext(ModalsContext); const children = useContext(ModalsChildrenContext); return <ModalsContainer removeModal={manager.removeModal} hideModal={manager.hideModal} modals={children} />; }; export default ModalsChildren;
6,501
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/modals/Container.tsx
import { cloneElement } from 'react'; import BackdropContainer from '../../components/modalTwo/BackdropContainer'; import ModalErrorBoundary from '../app/ModalErrorBoundary'; import { Modal } from './interface'; export interface ModalPropsInjection { key: string; onClose: () => void; onExit: () => void; open: boolean; isClosing: Modal['isClosing']; } interface Props { modals: Modal[]; removeModal: (id: string) => void; hideModal: (id: string) => void; } const ModalsContainer = ({ modals, removeModal, hideModal }: Props) => ( <> <BackdropContainer /> {modals.map(({ id, content, isClosing }) => { if (!content) { return null; } const handleModalExit: ModalPropsInjection['onExit'] = () => { content.props.onExit?.(); removeModal(id); }; const handleModalClose: ModalPropsInjection['onClose'] = () => { content.props.onClose?.(); hideModal(id); }; const props: ModalPropsInjection = { onClose: handleModalClose, onExit: handleModalExit, open: !isClosing, isClosing, key: id, }; return <ModalErrorBoundary {...props}>{cloneElement(content, props)}</ModalErrorBoundary>; })} </> ); export default ModalsContainer;
6,502
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/modals/Provider.tsx
import { ReactNode, useMemo, useState } from 'react'; import { ModalPositionsProvider } from '../../components/modalTwo/modalPositions'; import ModalsChildrenContext from './childrenContext'; import { Modal } from './interface'; import createManager from './manager'; import ModalsContext from './modalsContext'; interface Props { children: ReactNode; } const ModalsProvider = ({ children }: Props) => { const [modals, setModals] = useState<Modal[]>([]); const manager = useMemo(() => { return { ...createManager(modals, setModals), modals }; }, [modals, setModals]); return ( <ModalPositionsProvider> <ModalsContext.Provider value={manager}> <ModalsChildrenContext.Provider value={modals}>{children}</ModalsChildrenContext.Provider> </ModalsContext.Provider> </ModalPositionsProvider> ); }; export default ModalsProvider;
6,503
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/modals/childrenContext.ts
import { createContext } from 'react'; import { Modal } from './interface'; export default createContext<Modal[]>([]);
6,504
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/modals/index.ts
export { default as ModalsContainer } from './Container'; export * from './Container'; export { default as ModalsChildren } from './Children'; export { default as ModalsProvider } from './Provider';
6,505
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/modals/interface.ts
export interface Modal { id: string; content: JSX.Element | undefined; isClosing: boolean; } export interface ModalManager { createModal: (content?: JSX.Element, id?: string) => string; hideModal: (id: string) => void; removeModal: (id: string) => void; getModal: (id: string) => Modal | undefined; modals: Modal[]; }
6,506
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/modals/manager.tsx
import { Dispatch, SetStateAction } from 'react'; import { Modal, ModalManager } from './interface'; export default (modals: Modal[], setModals: Dispatch<SetStateAction<Modal[]>>): ModalManager => { const hideModal = (id: string) => { return setModals((oldModals: Modal[]) => { return oldModals.map((old) => { if (old.id !== id) { return old; } return { ...old, isClosing: true, }; }); }); }; const removeModal = (id: string) => { return setModals((oldModals) => { return oldModals.filter(({ id: otherId }) => id !== otherId); }); }; const createModal = (content: JSX.Element | undefined, id = Math.random().toString(36).slice(2, 11)) => { setModals((oldModals) => { return oldModals.find(({ id: otherId }) => id === otherId) ? oldModals : [ ...oldModals, { id, content, isClosing: false, }, ]; }); return id; }; const getModal = (id: string) => { return modals.find(({ id: otherId }) => id === otherId); }; return { createModal, hideModal, removeModal, getModal, modals, }; };
6,507
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/modals/modalsContext.ts
import { createContext } from 'react'; import { ModalManager } from './interface'; export default createContext<ModalManager>(null as unknown as ModalManager);
6,508
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/notification/DesktopNotificationPanel.tsx
import { useState } from 'react'; import { PushNotification } from 'push.js'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Status, create, getStatus, request } from '@proton/shared/lib/helpers/desktopNotification'; import { Badge, Field } from '../../components'; const testDefaultNotification = () => { return create(c('Info').t`You have a new email`, { body: 'Quarterly operations update', icon: '/assets/img/notification-badge.gif', onClick() { window.focus(); }, }); }; export interface Props { onTest?: () => Promise<PushNotification | undefined>; infoURL?: string; } const DesktopNotificationPanel = ({ onTest = testDefaultNotification }: Props) => { const [status, setStatus] = useState<Status>(getStatus()); const handleEnable = () => { request( () => setStatus(getStatus()), () => setStatus(getStatus()) ); }; return ( <> <Field className="pt-2"> <div className="mb-4"> <span className="mr-2">{c('Info').t`Desktop notifications are currently`}</span> {status === Status.GRANTED ? ( <Badge type="success" className="m-0">{c('Desktop notification status').t`Enabled`}</Badge> ) : ( <Badge type="error" className="m-0">{c('Desktop notification status').t`Disabled`}</Badge> )} </div> <div> {status === Status.GRANTED ? ( <Button size="small" onClick={onTest}>{c('Action').t`Send test notification`}</Button> ) : status === Status.DEFAULT ? ( <Button size="small" onClick={handleEnable}>{c('Action') .t`Enable desktop notification`}</Button> ) : null} </div> </Field> </> ); }; export default DesktopNotificationPanel;
6,509
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/notification/DesktopNotificationSection.tsx
import { c } from 'ttag'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { Info, Label, Row } from '../../components'; import DesktopNotificationPanel, { Props } from './DesktopNotificationPanel'; const DesktopNotificationSection = ({ onTest, infoURL = getKnowledgeBaseUrl('/desktop-notifications') }: Props) => { return ( <Row> <Label> <span className="mr-2">{c('Label').t`Desktop notification`}</span> <Info url={infoURL} /> </Label> <DesktopNotificationPanel onTest={onTest} /> </Row> ); }; export default DesktopNotificationSection;
6,510
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/notification/index.ts
export { default as DesktopNotificationSection } from './DesktopNotificationSection';
6,511
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/notifications/Children.tsx
import React, { useContext } from 'react'; import NotificationsContainer from './Container'; import NotificationsChildrenContext from './childrenContext'; import NotificationsContext from './notificationsContext'; const NotificationsChildren = () => { const manager = useContext(NotificationsContext); const { notifications, offset } = useContext(NotificationsChildrenContext); return ( <NotificationsContainer notifications={notifications} offset={offset} removeDuplicate={manager.removeDuplicate} removeNotification={manager.removeNotification} hideNotification={manager.hideNotification} /> ); }; export default NotificationsChildren;
6,512
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/notifications/Container.tsx
import React, { Fragment, Key, useEffect, useRef, useState } from 'react'; import clsx from '@proton/utils/clsx'; import noop from '@proton/utils/noop'; import Notification from './Notification'; import { NotificationOffset, Notification as NotificationType } from './interfaces'; const notificationGap = 4; const getRects = (notifications: { [key: Key]: HTMLDivElement }) => { return Object.entries(notifications).reduce<{ [key: Key]: DOMRect }>((acc, [key, el]) => { if (!el) { return acc; } acc[key] = el.getBoundingClientRect(); return acc; }, {}); }; type Position = number; const getPositions = (notifications: NotificationType[], rects: ReturnType<typeof getRects>) => { let top = 0; return notifications.reduce<{ [key: Key]: Position }>((acc, notification) => { acc[notification.key] = top; const height = rects[notification.key]?.height; if (height === undefined) { return acc; } top += height + notificationGap; return acc; }, {}); }; interface Props { notifications: NotificationType[]; removeNotification: (id: number) => void; hideNotification: (id: number) => void; removeDuplicate: (id: number) => void; offset?: NotificationOffset; } const NotificationsContainer = ({ notifications, removeNotification, hideNotification, removeDuplicate, offset, }: Props) => { const containerRef = useRef<HTMLDivElement>(null); const notificationRefs = useRef<{ [key: Key]: HTMLDivElement }>({}); const [rects, setRects] = useState<{ [key: Key]: DOMRect }>({}); const resizeObserverRef = useRef<ResizeObserver | null>(null); const callbackRefs = useRef<{ [key: Key]: (el: HTMLDivElement | null) => void }>({}); useEffect(() => { const observer = new ResizeObserver(() => { setRects(getRects(notificationRefs.current)); }); resizeObserverRef.current = observer; Object.values(notificationRefs.current).forEach((el) => { observer.observe(el); }); return () => { observer.disconnect(); resizeObserverRef.current = null; }; }, []); useEffect(() => { const notificationIds = Object.fromEntries(notifications.map((notification) => [notification.key, true])); const callbackKeys = Object.keys(callbackRefs.current); callbackKeys.forEach((callbackKey) => { if (!notificationIds[callbackKey]) { delete callbackRefs.current[callbackKey]; } }); }, [notifications]); const positions = getPositions(notifications, rects); const list = notifications.map(({ id, key, type, text, isClosing, showCloseButton, icon, duplicate }) => { if (!callbackRefs.current[key]) { callbackRefs.current[key] = (el: HTMLDivElement | null) => { if (el === null) { const oldEl = notificationRefs.current[key]; if (oldEl) { resizeObserverRef.current?.unobserve(oldEl); } delete notificationRefs.current[key]; } else { resizeObserverRef.current?.observe(el); notificationRefs.current[key] = el; } }; } return ( <Fragment key={key}> {duplicate.old && ( <Notification top={positions[key]} isClosing={true} isDuplicate={true} icon={duplicate.old.icon} type={duplicate.old.type} onClose={noop} onEnter={noop} onExit={noop} showCloseButton={duplicate.old.showCloseButton} > {text} </Notification> )} <Notification key={duplicate.key} onEnter={() => removeDuplicate(id)} top={positions[key]} ref={callbackRefs.current[key]} isClosing={isClosing} icon={icon} type={type} onClose={() => hideNotification(id)} onExit={() => removeNotification(id)} showCloseButton={showCloseButton} > {text} </Notification> </Fragment> ); }); return ( <div ref={containerRef} className={clsx( 'notifications-container flex flex-column flex-align-items-center no-print', offset?.y || offset?.x || 0 > 0 ? 'notifications-container--shifted' : undefined )} style={{ ...(offset?.y && { '--shift-custom-y': `${offset.y}px` }), ...(offset?.x && { '--shift-custom-x': `${offset.x}px` }), }} > {list} </div> ); }; export default NotificationsContainer;
6,513
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/notifications/Notification.tsx
import { AnimationEvent, MouseEvent, ReactNode, Ref, cloneElement, forwardRef, isValidElement } from 'react'; import clsx from '@proton/utils/clsx'; import { Icon, IconName } from '../../components/icon'; import { NotificationCloseButton } from './NotificationButton'; import { CustomNotificationProps, NotificationType } from './interfaces'; import NotificationContext from './notificationContext'; const TYPES_CLASS = { error: 'notification--error', warning: 'notification--warning', info: 'notification--info', success: 'notification--success', }; const CLASSES = { NOTIFICATION: 'notification', NOTIFICATION_IN: 'notification--in', NOTIFICATION_OUT: 'notification--out', NOTIFICATION_OUT_DUPLICATE: 'notification--out-duplicate', }; const ANIMATIONS = { NOTIFICATION_IN: 'anime-notification-in', NOTIFICATION_OUT: 'anime-notification-out', }; interface Props { children: ReactNode; type: NotificationType; isClosing: boolean; isDuplicate?: boolean; onExit: () => void; onClick?: (e: MouseEvent<HTMLElement>) => void; onClose?: () => void; onEnter: () => void; showCloseButton?: boolean; icon?: IconName; top: number | undefined; } const NotificationBase = ( { children, type, top, isClosing, isDuplicate, onClick, showCloseButton, onClose, onExit, onEnter, icon }: Props, ref: Ref<HTMLDivElement> ) => { const handleAnimationEnd = ({ animationName }: AnimationEvent<HTMLDivElement>) => { if (animationName === ANIMATIONS.NOTIFICATION_IN) { onEnter(); } if (animationName === ANIMATIONS.NOTIFICATION_OUT && isClosing) { onExit(); } }; return ( <div ref={ref} aria-atomic="true" role="alert" className={clsx([ CLASSES.NOTIFICATION, CLASSES.NOTIFICATION_IN, TYPES_CLASS[type] || TYPES_CLASS.success, isClosing && (isDuplicate ? CLASSES.NOTIFICATION_OUT_DUPLICATE : CLASSES.NOTIFICATION_OUT), icon && 'notification--has-icon', onClose && 'notification--has-close-button', ])} onClick={onClick} onAnimationEnd={handleAnimationEnd} style={{ '--top-custom': top === undefined ? '-999px' : `${top}px`, }} > <NotificationContext.Provider value={{ type }}> {icon && <Icon name={icon} className="notification__icon" />} <span className="notification__content"> {isValidElement<CustomNotificationProps>(children) ? cloneElement(children, { onClose }) : children} </span> {showCloseButton && <NotificationCloseButton onClick={onClose} />} </NotificationContext.Provider> </div> ); }; const Notification = forwardRef<HTMLDivElement, Props>(NotificationBase); export default Notification;
6,514
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/notifications/NotificationButton.tsx
import { ElementType, ForwardedRef, ReactElement, forwardRef, useContext } from 'react'; import { ButtonLike, ButtonLikeProps } from '@proton/atoms'; import NotificationContext from '@proton/components/containers/notifications/notificationContext'; import clsx from '@proton/utils/clsx'; import Icon from '../../components/icon/Icon'; interface NotificationOwnProps { close?: boolean; } export type NotificationButtonProps<E extends ElementType> = Omit<ButtonLikeProps<E>, 'shape' | 'color' | 'size'> & NotificationOwnProps; const defaultElement = 'button'; const NotificationButtonBase = <E extends ElementType = typeof defaultElement>( { close, className = '', as, ...rest }: NotificationButtonProps<E>, ref: ForwardedRef<Element> ) => { const { type } = useContext(NotificationContext); const positive = type == 'info' || type == 'success'; const Element: ElementType = as || defaultElement; return ( <ButtonLike as={Element} {...(Element === 'button' ? { type: 'button' } : undefined)} ref={ref} {...rest} shape={positive ? 'ghost' : 'solid'} color={positive ? 'weak' : 'danger'} size="small" className={clsx(['notification__button text-bold', close && 'notification__close-button', className])} data-testid="notification:undo-button" /> ); }; const NotificationButton: <E extends ElementType = typeof defaultElement>( props: NotificationButtonProps<E> ) => ReactElement | null = forwardRef(NotificationButtonBase); export const NotificationCloseButton = ({ onClick }: { onClick?: () => void }) => { return ( <NotificationButton icon onClick={onClick} close> <Icon name="cross-big" /> </NotificationButton> ); }; export default NotificationButton;
6,515
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/notifications/NotificationsHijack.tsx
import { FC } from 'react'; import { CreateNotificationOptions, NotificationsContext, NotificationsContextValue } from '@proton/components'; import noop from '@proton/utils/noop'; interface NotificationsHijackProps { onCreate: ((options: CreateNotificationOptions) => void) | undefined; } const NotificationsHijack: FC<NotificationsHijackProps> = ({ children, onCreate }) => { if (!onCreate) { return <>{children}</>; } const hijackedCreateNotification = (options: CreateNotificationOptions) => { onCreate(options); /* createNotification has to return a number */ return 42; }; const context: NotificationsContextValue = { createNotification: hijackedCreateNotification, removeNotification: noop, hideNotification: noop, removeDuplicate: noop, clearNotifications: noop, setOffset: noop, }; return <NotificationsContext.Provider value={context}>{children}</NotificationsContext.Provider>; }; export default NotificationsHijack;
6,516
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/notifications/Provider.tsx
import { ReactNode, Reducer, useEffect, useReducer, useState } from 'react'; import useInstance from '@proton/hooks/useInstance'; import isDeepEqual from '@proton/shared/lib/helpers/isDeepEqual'; import NotificationsChildrenContext from './childrenContext'; import { Notification, NotificationOffset } from './interfaces'; import createManager from './manager'; import NotificationsContext from './notificationsContext'; interface Props { children: ReactNode; } const offsetReducer = (oldState: NotificationOffset | undefined, newState: NotificationOffset | undefined) => { if (oldState === newState || isDeepEqual(oldState, newState)) { return oldState; } return newState; }; const NotificationsProvider = ({ children }: Props) => { const [notifications, setNotifications] = useState<Notification[]>([]); const [offset, setNotificationOffset] = useReducer< Reducer<NotificationOffset | undefined, NotificationOffset | undefined> >(offsetReducer, undefined); const manager = useInstance(() => { return createManager(setNotifications, setNotificationOffset); }); useEffect(() => { return () => { manager.clearNotifications(); }; }, []); return ( <NotificationsContext.Provider value={manager}> <NotificationsChildrenContext.Provider value={{ notifications, offset }}> {children} </NotificationsChildrenContext.Provider> </NotificationsContext.Provider> ); }; export default NotificationsProvider;
6,517
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/notifications/childrenContext.ts
import { createContext } from 'react'; import { Notification, NotificationOffset } from './interfaces'; export default createContext<{ notifications: Notification[]; offset: NotificationOffset | undefined }>({ notifications: [], offset: undefined, });
6,518
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/notifications/index.ts
export { default as NotificationsContainer } from './Container'; export { default as NotificationsChildren } from './Children'; export { default as NotificationsProvider } from './Provider'; export { default as NotificationsContext } from './notificationsContext'; export { default as NotificationContext } from './notificationContext'; export { default as NotificationsHijack } from './NotificationsHijack'; export { default as NotificationButton } from './NotificationButton'; export * from './NotificationButton'; export * from './notificationsContext'; export * from './interfaces';
6,519
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/notifications/interfaces.ts
import { Key, ReactNode } from 'react'; import { IconName } from '@proton/components/components'; export type NotificationType = 'error' | 'warning' | 'info' | 'success'; export interface NotificationOffset { y?: number; x?: number; } export interface Notification { id: number; key: Key; text: ReactNode; type: NotificationType; isClosing: boolean; showCloseButton?: boolean; icon?: IconName; deduplicate?: boolean; duplicate: { old: Notification | undefined; state: 'init' | 'removed'; key: number }; } export interface CreateNotificationOptions extends Pick<Notification, 'text' | 'icon' | 'showCloseButton' | 'deduplicate'> { id?: number; key?: Key; type?: NotificationType; isClosing?: boolean; expiration?: number; } export interface CustomNotificationProps { onClose?: () => void; } export interface NotificationContextProps { type: NotificationType; }
6,520
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/notifications/manager.test.tsx
import { useState } from 'react'; import { act, renderHook } from '@testing-library/react-hooks'; import noop from '@proton/utils/noop'; import { Notification } from './interfaces'; import createNotificationManager from './manager'; describe('notification manager', () => { it('should create a notification', () => { const { result } = renderHook(() => useState<Notification[]>([])); const [, setState] = result.current; const manager = createNotificationManager(setState, noop); expect(result.current[0]).toStrictEqual([]); act(() => { manager.createNotification({ text: 'hello', }); }); expect(result.current[0]).toStrictEqual([expect.objectContaining({ text: 'hello' })]); }); describe('deduplication', () => { describe('when deduplicate true', () => { it('should remove duplicate notifications', () => { const { result } = renderHook(() => useState<Notification[]>([])); const [, setState] = result.current; const manager = createNotificationManager(setState, noop); act(() => { manager.createNotification({ text: 'foo', type: 'success', deduplicate: true, }); manager.createNotification({ text: 'foo', type: 'success', deduplicate: true, }); manager.createNotification({ text: 'bar', type: 'success', }); }); expect(result.current[0]).toStrictEqual([ expect.objectContaining({ text: 'bar' }), expect.objectContaining({ text: 'foo' }), ]); }); }); describe('when deduplicate false', () => { it('should not remove duplicate notifications', () => { const { result } = renderHook(() => useState<Notification[]>([])); const [, setState] = result.current; const manager = createNotificationManager(setState, noop); act(() => { manager.createNotification({ text: 'foo', type: 'error', deduplicate: false, }); manager.createNotification({ text: 'foo', type: 'error', }); manager.createNotification({ text: 'bar', type: 'error', }); }); expect(result.current[0]).toStrictEqual([ expect.objectContaining({ text: 'bar' }), expect.objectContaining({ text: 'foo' }), expect.objectContaining({ text: 'foo' }), ]); }); }); describe('when deduplicate is undefined', () => { it('should deduplicate a success notification', () => { const { result } = renderHook(() => useState<Notification[]>([])); const [, setState] = result.current; const manager = createNotificationManager(setState, noop); act(() => { manager.createNotification({ text: 'foo', type: 'success', }); manager.createNotification({ text: 'foo', type: 'success', }); manager.createNotification({ text: 'bar', type: 'success', }); }); expect(result.current[0]).toStrictEqual([ expect.objectContaining({ text: 'bar' }), expect.objectContaining({ text: 'foo' }), ]); }); it('should deduplicate a warning notification', () => { const { result } = renderHook(() => useState<Notification[]>([])); const [, setState] = result.current; const manager = createNotificationManager(setState, noop); act(() => { manager.createNotification({ text: 'foo', type: 'warning', }); manager.createNotification({ text: 'foo', type: 'warning', }); manager.createNotification({ text: 'bar', type: 'warning', }); }); expect(result.current[0]).toStrictEqual([ expect.objectContaining({ text: 'bar' }), expect.objectContaining({ text: 'foo' }), ]); }); it('should deduplicate a info notification', () => { const { result } = renderHook(() => useState<Notification[]>([])); const [, setState] = result.current; const manager = createNotificationManager(setState, noop); act(() => { manager.createNotification({ text: 'foo', type: 'info', }); manager.createNotification({ text: 'foo', type: 'info', }); manager.createNotification({ text: 'bar', type: 'info', }); }); expect(result.current[0]).toStrictEqual([ expect.objectContaining({ text: 'bar' }), expect.objectContaining({ text: 'foo' }), ]); }); it('should deduplicate an error notification', () => { const { result } = renderHook(() => useState<Notification[]>([])); const [, setState] = result.current; const manager = createNotificationManager(setState, noop); act(() => { manager.createNotification({ text: 'foo', type: 'error', }); manager.createNotification({ text: 'foo', type: 'error', }); manager.createNotification({ text: 'bar', type: 'error', }); }); expect(result.current[0]).toStrictEqual([ expect.objectContaining({ text: 'bar' }), expect.objectContaining({ text: 'foo' }), ]); }); }); it('should deduplicate react elements using the provided key', () => { const { result } = renderHook(() => useState<Notification[]>([])); const [, setState] = result.current; const manager = createNotificationManager(setState, noop); act(() => { manager.createNotification({ text: <div>text</div>, key: 'item1', type: 'error', }); manager.createNotification({ text: <div>text</div>, key: 'item1', type: 'error', }); manager.createNotification({ text: 'bar', key: 'item2', type: 'error', }); // Do not deduplicate if key is not provided manager.createNotification({ text: <div>text</div>, type: 'error', }); }); expect(result.current[0]).toStrictEqual([ expect.objectContaining({ text: <div>text</div> }), expect.objectContaining({ text: 'bar', key: 'item2' }), expect.objectContaining({ text: <div>text</div>, key: 'item1' }), ]); }); }); it('should allow to create notifications with raw html text and deduplicate it', () => { const { result } = renderHook(() => useState<Notification[]>([])); const [, setState] = result.current; const manager = createNotificationManager(setState, noop); act(() => { manager.createNotification({ text: 'Foo <a href="https://foo.bar">text</a>', type: 'error', }); manager.createNotification({ text: 'Foo <a href="https://foo.bar">text</a>', type: 'error', }); }); expect(result.current[0]).toStrictEqual([ expect.objectContaining({ text: ( <div dangerouslySetInnerHTML={{ __html: 'Foo <a href="https://foo.bar" rel="noopener noreferrer" target="_blank" class="color-inherit">text</a>', }} /> ), key: 'Foo <a href="https://foo.bar">text</a>', }), ]); }); });
6,521
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/notifications/manager.tsx
import { Dispatch, SetStateAction } from 'react'; import DOMPurify from 'dompurify'; import { isElement } from '@proton/shared/lib/helpers/dom'; import { CreateNotificationOptions, Notification, NotificationOffset } from './interfaces'; function createNotificationManager( setNotifications: Dispatch<SetStateAction<Notification[]>>, setNotificationOffset: Dispatch<NotificationOffset | undefined> ) { let idx = 1; const intervalIds = new Map<number, any>(); const removeInterval = (id: number) => { const intervalId = intervalIds.get(id); if (!intervalId) { return; } if (intervalId !== -1) { clearTimeout(intervalId); } intervalIds.delete(id); }; const removeNotification = (id: number) => { const intervalId = intervalIds.get(id); if (!intervalId) { return; } removeInterval(id); return setNotifications((oldNotifications) => { return oldNotifications.filter(({ id: otherId }) => id !== otherId); }); }; const hideNotification = (id: number) => { // If the page is hidden, don't hide the notification with an animation because they get stacked. // This is to solve e.g. offline notifications appearing when the page is hidden, and when you focus // the tab again, they would be visible for the animation out even if they happened a while ago. if (document.hidden) { return removeNotification(id); } return setNotifications((oldNotifications) => { return oldNotifications.map((oldNotification) => { if (oldNotification.id !== id) { return oldNotification; } return { ...oldNotification, isClosing: true, }; }); }); }; const createNotification = ({ id = idx++, key, expiration = 5000, type = 'success', text, showCloseButton = true, icon = type === 'warning' || type === 'error' ? 'exclamation-triangle-filled' : undefined, deduplicate = true, ...rest }: CreateNotificationOptions) => { if (intervalIds.has(id)) { throw new Error('notification already exists'); } if (idx >= 1000) { idx = 0; } if (key === undefined) { key = typeof text === 'string' && deduplicate ? text : id; } if (typeof text === 'string') { const sanitizedElement = DOMPurify.sanitize(text, { RETURN_DOM: true, ALLOWED_TAGS: ['b', 'a', 'i', 'em', 'strong', 'br', 'p', 'span'], }); const containsHTML = sanitizedElement?.childNodes && Array.from(sanitizedElement.childNodes).some(isElement); if (containsHTML) { sanitizedElement.querySelectorAll('A').forEach((node) => { if (node.tagName === 'A') { node.setAttribute('rel', 'noopener noreferrer'); node.setAttribute('target', '_blank'); node.setAttribute('class', 'color-inherit'); } }); expiration = Math.max(5000, expiration); text = <div dangerouslySetInnerHTML={{ __html: sanitizedElement.innerHTML }} />; } } setNotifications((oldNotifications) => { const newNotification: Notification = { id, key: key!, type, text, ...rest, isClosing: false, showCloseButton, icon, duplicate: { key: 1, state: 'init', old: undefined, }, }; if (deduplicate) { const duplicateOldNotification = oldNotifications.find( (oldNotification) => oldNotification.key === key ); if (duplicateOldNotification) { removeInterval(duplicateOldNotification.id); return oldNotifications.map((oldNotification) => { if (oldNotification === duplicateOldNotification) { const hasOldDuplicate = !!oldNotification.duplicate.old || oldNotification.duplicate.state === 'init'; return { ...newNotification, duplicate: { old: hasOldDuplicate ? oldNotification.duplicate.old : oldNotification, state: oldNotification.duplicate.state, key: hasOldDuplicate ? oldNotification.duplicate.key : oldNotification.duplicate.key + 1, }, key: duplicateOldNotification.key, }; } return oldNotification; }); } } return [newNotification, ...oldNotifications]; }); intervalIds.set(id, expiration === -1 ? -1 : setTimeout(() => hideNotification(id), expiration)); return id; }; const removeDuplicate = (id: number) => { return setNotifications((oldNotifications) => { return oldNotifications.map((oldNotification) => { if (oldNotification.id !== id) { return oldNotification; } return { ...oldNotification, duplicate: { old: undefined, state: 'removed', key: oldNotification.duplicate.key, }, }; }); }); }; const clearNotifications = () => { intervalIds.forEach((intervalId) => { clearTimeout(intervalId); }); intervalIds.clear(); return setNotifications([]); }; return { setOffset: setNotificationOffset, removeDuplicate, createNotification, removeNotification, hideNotification, clearNotifications, }; } export type NotificationsManager = ReturnType<typeof createNotificationManager>; export default createNotificationManager;
6,522
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/notifications/notificationContext.ts
import { createContext } from 'react'; import { NotificationContextProps } from './interfaces'; export default createContext<NotificationContextProps>({ type: 'success' });
6,523
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/notifications/notificationsContext.ts
import { createContext } from 'react'; import { NotificationsManager } from './manager'; export type NotificationsContextValue = NotificationsManager; export default createContext<NotificationsManager>(null as unknown as NotificationsManager);
6,524
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/Offer.scss
@import '~@proton/styles/scss/lib'; $amount-size: 34; // should be 36, but don't increase more than 34, otherwise we'll have some display issues. .offer { &-modal { &.modal-two-dialog--large { // only increasing size for large case = when 3 plans --size: #{em(1050)}; // 992 before, but increase to have feature copy on one line... } &.offer-modal--four-deals { // larger case = when 4 plans --size: #{em(1200)}; } &.offer-modal--one-deal { --size: #{em(820)}; // half image & content .modal-two-content { margin-block-end: 0; @include media('>small') { display: flex; inline-size: 100%; } } // kill scroll only for desktop @include media('>small') { .scroll-outer-vertical .scroll-inner, .scroll-child { overflow: hidden; display: flex; block-size: 100%; inline-size: 100%; } .offer-main-wrapper { inline-size: calc(100% + 4rem); } .offer-main-content-container { overflow-y: auto; } } } .scroll-inner { overflow: overlay; // trick for Chrome Mac layout rendering for scrollbar } } // for some promotions &-proton-logo { @include media('<=small') { inline-size: em(30); // just to avoid having images going to another next line on mobile } } @include media('<=small') { &-proton-logo { inline-size: em(30); // just to avoid having images going to another next line on mobile } } // top banner offer // need to compensate modal paddings &-modal &-main-wrapper { margin-inline: -2rem; margin-block-start: -0.5em; @include media('<=small') { margin-inline: 0; } } &-modal:not(.offer-modal--one-deal) { .offer-main-content { margin-inline: 2rem; @include media('<=small') { margin-inline: 0; } } @include media('>small') { .offer-close-button--dark { color: white; // always above a banner, so hardcoded to white } } } // side banner offer &-side-image-container, &-side-image { min-inline-size: 400px; @include media('<=#{em(1100, 16)}') { min-inline-size: 300px; } @include media('<=#{em(900, 16)}') { min-inline-size: 250px; } } &-main-wrapper--left-banner &-wrapper { flex-direction: column; align-items: center; .offer-plan-container:not(:first-child) { margin-inline-start: 0; } } // special 2x2 stacking for four plan case &-main-wrapper--four-plans &-wrapper { // special 2x2 stacking for four plan case @include media('<=#{em(1200, 16)}') { flex-wrap: wrap; .offer-plan-container { min-inline-size: calc(50% - 2em); &--mostPopular { order: -4; } &--secondMostPopular { order: -3; } &--thirdMostPopular { order: -2; } &:not(:first-child) { margin-inline-start: 0; } } } } // contents of offers &-countdown { &-number { font-variant: tabular-nums; min-inline-size: 2em; } } &-plan-container { flex: 1; max-inline-size: 26em; &:not(:first-child) { margin-inline-start: 1em; @include media('<=small') { margin-inline-start: 0; } } @include media('<=small') { max-inline-size: none; &--mostPopularOnMobile { order: -4; } &--secondMostPopularOnMobile { order: -3; } &--thirdMostPopularOnMobile { order: -2; } &--fourthMostPopularOnMobile { order: -1; } } } &-plan { padding-inline: em(20); @include media('<=#{em(850, 16)}') { padding-inline: em(18); } @include media('<=small') { padding-inline: em(24); } &.is-focused { border-color: var(--focus-outline); box-shadow: 0 0 0 #{$focus-ring-size} var(--focus-ring); } } &-percentage { inset-inline-start: 50%; transform: translateX(-50%) translateY(-50%); [dir='rtl'] & { transform: translateX(50%) translateY(-50%); } white-space: nowrap; border-radius: 1em; z-index: 1; } &-most-popular { min-block-size: 1.5em; // no need to keep space for 1 plan case .offer-modal--one-deal &:empty { display: none; } // hidden when empty on mobile @include media('<=small') { &:empty { display: none; } } } &-plan-namePeriod { .offer-modal:not(.offer-modal--one-deal) & { @include media('<=#{em(850, 16)}') { min-block-size: 6em; // proton unlimited on 2 lines } @include media('<=small') { min-block-size: 0; } } } &-monthly-price { display: block; .amount, .currency { font-size: em($amount-size); font-weight: var(--font-weight-bold); @include media('<=#{em(1050, 16)}') { font-size: em(28); } @include media('<=#{em(770, 16)}') { // fix for medium viewports font-size: em(24); } @include media('<=small') { font-size: em($amount-size); } } .suffix { margin-inline-start: 0.5em; color: var(--text-weak); display: inline-block; .offer-modal:not(.offer-modal--one-deal) & { @include media('<=#{em(960, 16)}') { min-inline-size: 100%; position: relative; inset-block-start: -0.5em; } @include media('<=small') { min-inline-size: 0; position: static; } } } } &-regular-price { inset-block-start: -0.2em; // magic number to be a bit closer to real price and not CTA } &-features:empty { display: none; } &-features { .info-button { position: relative; inset-block-start: em(-2); } } }
6,525
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/Offers.test.helpers.tsx
import React from 'react'; import { Route, Router } from 'react-router'; import { createMemoryHistory } from 'history'; import { CacheProvider, ConfigProvider, FeaturesProvider, ModalsProvider, NotificationsProvider, } from '@proton/components/'; import ApiContext from '@proton/components/containers/api/apiContext'; import { APPS } from '@proton/shared/lib/constants'; import createCache from '@proton/shared/lib/helpers/cache'; import { ProtonConfig } from '@proton/shared/lib/interfaces'; import { STATUS } from '@proton/shared/lib/models/cache'; import { mockApiWithServer } from '@proton/testing'; export const DEFAULT_CONFIG = { APP_NAME: APPS.PROTONMAIL, APP_VERSION: 'test-version', DATE_VERSION: 'test-date-version', } as ProtonConfig; let routeHistory = createMemoryHistory({ initialEntries: ['/inbox'] }); const MAIL_MAIN_ROUTE_PATH = '/:labelID?/:elementID?/:messageID?'; let cache = createCache(); export const offersCache = { cache, add: (key: string, value: any) => { cache.set(key, { status: STATUS.RESOLVED, value }); }, clear: () => { cache.clear(); }, }; export const OffersTestProvider = ({ children, config = DEFAULT_CONFIG, }: { children: React.ReactNode; config?: ProtonConfig; }) => ( <ConfigProvider config={config}> <ApiContext.Provider value={mockApiWithServer}> <NotificationsProvider> <ModalsProvider> <CacheProvider cache={cache}> <FeaturesProvider> <Router history={routeHistory}> <Route path={MAIL_MAIN_ROUTE_PATH}>{children}</Route> </Router> </FeaturesProvider> </CacheProvider> </ModalsProvider> </NotificationsProvider> </ApiContext.Provider> </ConfigProvider> );
6,526
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/Offers.test.tsx
import { fireEvent, render, screen } from '@testing-library/react'; import { FeatureCode, TopNavbarUpsell } from '@proton/components'; import { UserModel } from '@proton/shared/lib/models'; import { OffersTestProvider, offersCache } from './Offers.test.helpers'; import { OfferConfig } from './interface'; const OFFER_CONTENT = 'deal deal deal deal deal'; const offerConfig: OfferConfig = { deals: [], featureCode: 'testOffer2022' as FeatureCode, layout: () => <div>{OFFER_CONTENT}</div>, ID: 'test-offer-2022' as OfferConfig['ID'], canBeDisabled: true, }; const offerConfigAutopopup: OfferConfig = { deals: [], featureCode: 'testOffer2022' as FeatureCode, layout: () => <div>{OFFER_CONTENT}</div>, ID: 'test-offer-2022' as OfferConfig['ID'], canBeDisabled: true, autoPopUp: 'one-time', }; jest.mock('./hooks/useOfferConfig', function () { return { __esModule: true, default: jest .fn() .mockReturnValueOnce([undefined, false]) .mockReturnValueOnce([undefined, false]) .mockReturnValueOnce([offerConfig, false]) .mockReturnValueOnce([offerConfig, false]) .mockReturnValue([offerConfigAutopopup, false]), }; }); jest.mock('./hooks/useFetchOffer', function () { return { __esModule: true, default: jest.fn(({ offerConfig }) => [offerConfig, false]), }; }); jest.mock('./hooks/useOfferFlags', function () { return { __esModule: true, default: jest.fn(() => ({ isVisited: false, loading: false, isActive: true, handleVisit: () => {}, handleHide: () => {}, })), }; }); afterEach(() => { offersCache.clear(); }); const TopNavbarComponent = () => ( <OffersTestProvider> <TopNavbarUpsell /> </OffersTestProvider> ); describe('Offers', () => { describe('Offers display', () => { it('Should display upgrade button for free users', () => { offersCache.add(UserModel.key, { isFree: true }); render(<TopNavbarComponent />); const link = screen.getByTestId('cta:upgrade-plan'); expect(link.textContent).toContain('Upgrade'); expect(link.tagName).toBe('A'); }); it('Should display nothing for paid users with offers', () => { offersCache.add(UserModel.key, { isFree: false }); render(<TopNavbarComponent />); expect(screen.queryByTestId('cta:upgrade-plan')).toBeNull(); }); describe('Non free user with valid offer', () => { it('Should display an offer button', () => { offersCache.add(UserModel.key, { isFree: false }); render(<TopNavbarComponent />); expect(screen.getByTestId('cta:special-offer')?.textContent).toBe('Special offer'); }); it('Should open a modal with offer content', () => { offersCache.add(UserModel.key, { isFree: false }); render(<TopNavbarComponent />); const specialOfferCta = screen.getByTestId('cta:special-offer'); fireEvent.click(specialOfferCta); screen.getByText(OFFER_CONTENT); }); it.skip('Should open a modal when autopopup', () => { offersCache.add(UserModel.key, { isFree: false }); render(<TopNavbarComponent />); screen.getByText(OFFER_CONTENT); }); }); }); });
6,527
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/README.md
# Offers The goal was to give developer a platform allowing them to create offers operations with a single, well typed, config file. And if customisation is needed, components are modular enough to give the needed flexibility to make it in a fast and reusable way. ## Create a new offer In order to create a new offer, few steps are needed. ### Create FeatureCode In `FeaturesContext.ts`, insert a new FeatureCode for the offer. **FeatureCode name must respect naming conventions**: - PascalCase - Prefixed by `Offer` - Suffixed by year - Ex: `OfferBlackFriday2022` ### Add an offer-id Add an offer ID (for frontend purpose only) in `interface.ts` `OfferId` union type. ### Create operation folder Create a new folder inside `operations`. Name should be same as featureFlag without the prefix and camelCased. Ex: If FF is `OfferBlackFriday2022` folder name will be `blackFriday2022`. Then create and fill `configuration.ts`, `useOffer.ts`, `Layout.tsx` and `index.ts` files. Be carefull with naming exports in `index.ts`. Ex: ```ts export { default as blackFriday2022Config } from './configuration'; export { default as useBlackFriday2022 } from './useOffer'; ``` ### Add operation to main hook Import the config and the hook in `useOfferConfig`.
6,528
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/index.ts
export { default as useOfferConfig } from './hooks/useOfferConfig'; export { default as OfferModal } from './components/OfferModal'; export { default as useFetchOffer } from './hooks/useFetchOffer'; export { default as useOfferModal } from './hooks/useOfferModal';
6,529
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/interface.ts
import { JSXElementConstructor, ReactNode } from 'react'; import { ButtonLikeShape } from '@proton/atoms/Button'; import type { FeatureCode, IconName } from '@proton/components'; import type { COUPON_CODES, CYCLE } from '@proton/shared/lib/constants'; import type { Currency, Optional, PlanIDs } from '@proton/shared/lib/interfaces'; export type OfferId = | 'go-unlimited-2022' | 'mail-trial-2023' | 'black-friday-2023-inbox-free' | 'black-friday-2023-inbox-mail' | 'black-friday-2023-inbox-unlimited' | 'black-friday-2023-vpn-free' | 'black-friday-2023-vpn-monthly' | 'black-friday-2023-vpn-yearly' | 'black-friday-2023-vpn-two-years' | 'black-friday-2023-drive-free' | 'black-friday-2023-drive-plus' | 'black-friday-2023-drive-unlimited'; export type OfferGlobalFeatureCodeValue = Record<OfferId, boolean>; export enum OfferUserFeatureCodeValue { Default = 0, Visited = 1, Hide = 2, } export interface OfferProps { currency: Currency; offer: Offer; onChangeCurrency: (currency: Currency) => void; onSelectDeal: (offer: Offer, deal: Deal, current: Currency) => void; onCloseModal: () => void; } export type OfferLayoutProps = Optional<OfferProps, 'offer'>; export interface Operation { config: OfferConfig; isValid: boolean; isLoading: boolean; isEligible: boolean; } export interface OfferImages { sideImage?: string; sideImage2x?: string; bannerImage?: string; bannerImage2x?: string; } export interface OfferConfig { ID: OfferId; icon?: IconName; featureCode: FeatureCode; autoPopUp?: 'each-time' | 'one-time'; canBeDisabled?: boolean; deals: Deal[]; layout: JSXElementConstructor<OfferLayoutProps>; /** Displays countdown if present */ periodEnd?: Date; getCTAContent?: () => string; shapeButton?: ButtonLikeShape; images?: OfferImages; darkBackground?: boolean; // Will use a light close button if true (ghost button with white text) enableCycleSelector?: boolean; // Allow the selection of cycles if true in the checkout process } interface Feature { badge?: string; disabled?: boolean; icon?: IconName; name: string; tooltip?: string; } export interface Deal { couponCode?: COUPON_CODES; ref: string; cycle: CYCLE; features?: () => Feature[]; getCTAContent?: () => string; planIDs: PlanIDs; // planIDs used to subscribe dealName: string; // most of the time we show the plan name of the deal popular?: number; // 1 = most popular, 2 = second most popular, etc. mobileOrder?: number; // 1 = most popular, 2 = second most popular, etc. if using this, please specify it for all plans to avoid issues header?: () => string | ReactNode; star?: string; isGuaranteed?: boolean; } export interface Prices { withCoupon: number; withoutCoupon: number; withoutCouponMonthly: number; } export type DealWithPrices = Deal & { prices: Prices }; export interface Offer extends OfferConfig { deals: DealWithPrices[]; } export interface DealProps extends Required<OfferProps> { deal: Offer['deals'][number]; }
6,530
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/OfferModal.tsx
import { Currency } from '@proton/shared/lib/interfaces'; import clsx from '@proton/utils/clsx'; import noop from '@proton/utils/noop'; import { ModalProps, ModalTwo, ModalTwoContent } from '../../../components/modalTwo'; import useOnSelectDeal from '../hooks/useOnSelectDeal'; import useVisitedOffer from '../hooks/useVisitedOffer'; import { Offer, OfferConfig, OfferProps } from '../interface'; import OfferCloseButton from './shared/OfferCloseButton'; import '../Offer.scss'; interface Props { offerConfig: OfferConfig; offer: Offer; modalProps: ModalProps; currency: Currency; onChangeCurrency: (currency: Currency) => void; onSelectDeal?: OfferProps['onSelectDeal']; } const OfferModal = ({ offer, offerConfig, modalProps, currency, onChangeCurrency, onSelectDeal }: Props) => { useVisitedOffer(offerConfig); const { onClose: handleCloseModal } = modalProps; const handleOnSelectDeal = useOnSelectDeal(handleCloseModal); return ( <ModalTwo className={clsx( 'offer-modal', `offer-${offerConfig.ID}`, offerConfig.deals.length < 2 && 'offer-modal--one-deal', offerConfig.deals.length > 3 && 'offer-modal--four-deals' )} {...modalProps} size="large" > <ModalTwoContent> {modalProps.onClose && ( <OfferCloseButton onClose={modalProps.onClose} darkBackground={offer.darkBackground} /> )} <offerConfig.layout offer={offer} currency={currency} onChangeCurrency={onChangeCurrency} onSelectDeal={onSelectDeal || handleOnSelectDeal} onCloseModal={handleCloseModal || noop} /> </ModalTwoContent> </ModalTwo> ); }; export default OfferModal;
6,531
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/blackFriday/BlackFridayFooter.tsx
import { c } from 'ttag'; import { Price } from '@proton/components/components'; import { getDiscount } from '../../helpers/dealPrices'; import { getRenewDescription } from '../../helpers/offerCopies'; import { OfferProps } from '../../interface'; const BlackFridayFooter = ({ offer, currency }: OfferProps) => { return ( <div className="mb-4"> {offer.deals.map((deal) => { const { prices, cycle, dealName, star } = deal; const { withoutCoupon = 0, withoutCouponMonthly = 0 } = prices || {}; const discount = getDiscount(deal); const discountedAmount = ( <Price key="discounted-amount" currency={currency} isDisplayedInSentence> {withoutCoupon} </Price> ); const regularAmount = ( <Price key="regular-amount" currency={currency} isDisplayedInSentence> {withoutCouponMonthly * cycle} </Price> ); const description = getRenewDescription(cycle, discountedAmount, regularAmount, discount); if (!description || !star) { return null; } const key = `${dealName}-${cycle}`; return ( <p key={key} className="text-sm text-center color-weak"> <sup className="mr-2">{star}</sup> {description} </p> ); })} <p className="text-sm text-center color-weak"> <div>{c('bf2023: Footer').t`Discounts are based on standard monthly pricing.`}</div> <div>{c('bf2023: Footer') .t`Your subscription will automatically renew at the standard discounted rate and duration at the end of your billing cycle.`}</div> </p> </div> ); }; export default BlackFridayFooter;
6,532
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/blackFriday/BlackFridayTitle.tsx
import { c } from 'ttag'; import { isBlackFridayPeriod, isCyberWeekPeriod } from '../../helpers/offerPeriods'; import OfferTitle from '../shared/OfferTitle'; const BlackFridayTitle = () => { if (isBlackFridayPeriod()) { return <OfferTitle>{c('specialoffer: Title').t`Black Friday Sale`}</OfferTitle>; } if (isCyberWeekPeriod()) { return <OfferTitle>{c('specialoffer: Title').t`Cyber Week Sale`}</OfferTitle>; } return <OfferTitle>{c('specialoffer: Title').t`End of Year Sale`}</OfferTitle>; }; export default BlackFridayTitle;
6,533
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/familyPlan/FamilyPlanFooter.tsx
import { c } from 'ttag'; import { OfferProps } from '../../interface'; import OfferDisableButton from '../shared/OfferDisableButton'; const FamilyPlanFooter = (props: OfferProps) => { return ( <div className="mb-4"> <div className="text-center"> <OfferDisableButton {...props} /> </div> <p className="text-sm text-center color-weak"> {c('familyOffer_2023:Footer').t`Discounts are based on the standard monthly pricing.`} <br /> {c('familyOffer_2023:Footer') .t`*Your subscription will automatically renew at the same rate at the end of your billing cycle.`} </p> </div> ); }; export default FamilyPlanFooter;
6,534
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/familyPlan/FamilyPlanTitle.tsx
import { c } from 'ttag'; import { PLANS, PLAN_NAMES } from '@proton/shared/lib/constants'; import OfferTitle from '../shared/OfferTitle'; const FamilyPlanTitle = () => { const planName = PLAN_NAMES[PLANS.FAMILY]; return ( <> <OfferTitle>{c('familyOffer_2023:Title').t`Introducing ${planName}`}</OfferTitle> <p className="text-center">{c('familyOffer_2023:Info').t`Online privacy, for your whole family`}</p> </> ); }; export default FamilyPlanTitle;
6,535
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/shared/OfferCloseButton.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Icon, Tooltip } from '@proton/components/components'; import clsx from '@proton/utils/clsx'; interface Props { onClose?: () => void; darkBackground?: boolean; } const OfferCloseButton = ({ onClose, darkBackground = false }: Props) => { return ( <Tooltip title={c('specialoffer: Action').t`Close`}> <Button className={clsx( 'flex-item-noshrink offer-close-button absolute right mr-2 top-custom', darkBackground && 'offer-close-button--dark' )} icon shape="ghost" onClick={onClose} style={{ '--top-custom': '8px', }} > <Icon className="modal-close-icon" size={12} name="cross-big" alt={c('specialoffer: Action').t`Close`} /> </Button> </Tooltip> ); }; export default OfferCloseButton;
6,536
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/shared/OfferCountdown.tsx
import { c, msgid } from 'ttag'; import useDateCountdown from '@proton/hooks/useDateCountdown'; import isTruthy from '@proton/utils/isTruthy'; interface Props { periodEnd: Date; } const Countdown = ({ periodEnd }: Props) => { const countdownProps = useDateCountdown(periodEnd); const { expired, seconds, minutes, hours, days } = countdownProps; if (expired) { return null; } return ( <div className="mt-4 text-center"> {[ days > 0 ? c('specialoffer: Countdown unit').ngettext(msgid`${days} day`, `${days} days`, days) : undefined, c('specialoffer: Countdown unit').ngettext(msgid`${hours} hour`, `${hours} hours`, hours), c('specialoffer: Countdown unit').ngettext(msgid`${minutes} minute`, `${minutes} minutes`, minutes), c('specialoffer: Countdown unit').ngettext(msgid`${seconds} second`, `${seconds} seconds`, seconds), ] .filter(isTruthy) .map((value) => { const [number, unit] = value.split(' '); return ( <span className="inline-flex flex-column flex-nowrap flex-align-items-center mr-4" key={unit}> <span className="bg-weak text-bold w-custom offer-countdown-number py-1 rounded" style={{ '--w-custom': '2em' }} > {number} </span> <span className="text-nowrap color-weak">{unit}</span> </span> ); })} </div> ); }; export default Countdown;
6,537
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/shared/OfferDisableButton.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import useOfferFlags from '../../hooks/useOfferFlags'; import { OfferProps } from '../../interface'; const OfferDisableButton = (props: OfferProps) => { const { handleHide } = useOfferFlags(props.offer); const [loading, withLoading] = useLoading(); return ( <Button shape="underline" size="small" color="norm" loading={loading} data-testid="cta:hide-offer" onClick={async () => { await withLoading(handleHide()); props.onCloseModal?.(); }} >{c('specialoffer: Action').t`Don't show this offer again`}</Button> ); }; export default OfferDisableButton;
6,538
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/shared/OfferFooter.tsx
import { forwardRef } from 'react'; import { CurrencySelector, useUser } from '@proton/components'; import { OfferProps } from '../../interface'; import OfferDisableButton from './OfferDisableButton'; interface Props extends OfferProps { children?: React.ReactNode; } const OfferFooter = forwardRef<HTMLDivElement, Props>((props, ref) => { const { children, currency, onChangeCurrency } = props; const [user] = useUser(); return ( <footer ref={ref}> {user.isFree ? ( <div className="my-4 text-center offers-currency-selector"> <CurrencySelector id="offers-currency-selector" mode="buttons" currency={currency} onSelect={onChangeCurrency} /> </div> ) : null} {props.offer.canBeDisabled ? ( <div className="mb-4 text-center"> <OfferDisableButton {...props} /> </div> ) : null} {children} </footer> ); }); OfferFooter.displayName = 'OfferFooter'; export default OfferFooter;
6,539
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/shared/OfferHeader.tsx
import { forwardRef } from 'react'; import { OfferProps } from '../../interface'; import OfferCountdown from './OfferCountdown'; interface Props extends OfferProps { children: React.ReactNode; } const OfferHeader = forwardRef<HTMLDivElement, Props>(({ children, offer }, ref) => ( <header ref={ref}> {children} {offer.periodEnd !== undefined && <OfferCountdown periodEnd={offer.periodEnd} />} </header> )); OfferHeader.displayName = 'OfferHeader'; export default OfferHeader;
6,540
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/shared/OfferLayout.tsx
import { ReactNode } from 'react'; import clsx from '@proton/utils/clsx'; import { OfferProps } from '../../interface'; interface Props extends OfferProps { children: ReactNode; } const OfferLayout = ({ children, offer }: Props) => { const hasMultipleDeals = offer?.deals?.length > 1; const hasFourDeals = offer?.deals?.length > 3; const { sideImage, sideImage2x, bannerImage, bannerImage2x } = offer?.images || {}; return ( <div className={clsx( 'offer-main-wrapper', !hasMultipleDeals && 'offer-main-wrapper--left-banner flex flex-row flex-nowrap', hasFourDeals && 'offer-main-wrapper--four-plans' )} > {hasMultipleDeals ? null : ( <div className="offer-side-image-container hidden md:flex no-scroll relative"> <picture> <source media="(-webkit-min-device-pixel-ratio: 1.25), min-resolution: 1.25dppx" srcSet={`${sideImage2x}`} /> <img className="offer-side-image absolute absolute-center-y" src={sideImage} srcSet={`${sideImage}, ${sideImage2x} 2x`} alt="" /> </picture> </div> )} <div className={clsx( 'offer-main-content-container', !hasMultipleDeals && 'flex-item-fluid px-0 sm:px-4 md:px-6' )} > {hasMultipleDeals ? ( <div className="offer-top-banner-container text-center mb-4 hidden md:flex"> {/* if viewport is higher than 990 px (image size), we'll use the 2x version for a proper display */} <picture> <source media="(min-width: 61.875em)" srcSet={`${bannerImage2x}`} /> <img className="offer-top-banner w-full" src={bannerImage} srcSet={`${bannerImage}, ${bannerImage2x} 2x`} alt="" /> </picture> </div> ) : null} <div className={clsx('offer-main-content', hasMultipleDeals ? 'pt-6 md:pt-0' : 'pt-6')}>{children}</div> </div> </div> ); }; export default OfferLayout;
6,541
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/shared/OfferLoader.tsx
import { CircleLoader } from '@proton/atoms'; const OfferLoader = () => ( <div className="text-center"> <CircleLoader size="large" className="mx-auto flex mb-8" /> </div> ); export default OfferLoader;
6,542
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/shared/OfferTitle.tsx
import { ReactNode } from 'react'; const OfferTitle = ({ children }: { children: ReactNode }) => <h1 className="h3 text-center text-bold">{children}</h1>; export default OfferTitle;
6,543
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/shared/ProtonLogos.tsx
import { CalendarLogo, DriveLogo, MailLogo, VpnLogo } from '@proton/components/components'; const ProtonLogos = () => ( <div className="text-center"> <MailLogo variant="glyph-only" className="offer-proton-logo" size={40} /> <CalendarLogo variant="glyph-only" className="offer-proton-logo" size={40} /> <DriveLogo variant="glyph-only" className="offer-proton-logo" size={40} /> <VpnLogo variant="glyph-only" className="offer-proton-logo" size={40} /> </div> ); export default ProtonLogos;
6,544
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/shared
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/shared/deal/Deal.tsx
import { ReactNode, forwardRef } from 'react'; import { c } from 'ttag'; import clsx from '@proton/utils/clsx'; import { getDiscountWithCoupon } from '../../../helpers/dealPrices'; import type { Offer, OfferProps } from '../../../interface'; import { DealProvider } from './DealContext'; interface Props extends OfferProps { deal: Offer['deals'][number]; children: ReactNode; } const Deal = forwardRef<HTMLDivElement, Props>(({ children, ...props }: Props, ref) => { const { popular, mobileOrder } = props.deal; const discount = getDiscountWithCoupon(props.deal); const isMostPopular = popular === 1; const isSecondMostPopular = popular === 2; const isThirdMostPopular = popular === 3; const isMostPopularOnMobile = mobileOrder === 1; const isSecondMostPopularOnMobile = mobileOrder === 2; const isThirdMostPopularOnMobile = mobileOrder === 3; const isFourthMostPopularOnMobile = mobileOrder === 4; return ( <DealProvider {...props}> <div ref={ref} className={clsx([ 'relative flex flex-item-fluid offer-plan-container mt-4 md:mt-0', isMostPopular && 'offer-plan-container--mostPopular', isSecondMostPopular && 'offer-plan-container--secondMostPopular', isThirdMostPopular && 'offer-plan-container--thirdMostPopular', isMostPopularOnMobile && 'offer-plan-container--mostPopularOnMobile', isSecondMostPopularOnMobile && 'offer-plan-container--secondMostPopularOnMobile', isThirdMostPopularOnMobile && 'offer-plan-container--thirdMostPopularOnMobile', isFourthMostPopularOnMobile && 'offer-plan-container--fourthMostPopularOnMobile', ])} > {discount ? ( <span className={clsx([ 'text-semibold absolute text-center offer-percentage py-1 px-4', isMostPopular ? 'bg-primary' : 'bg-weak color-weak border border-norm', ])} > {c('specialoffer: Offers').t`Save ${discount}%`} </span> ) : null} <div className={clsx([ 'offer-plan w-full border rounded p-4 mb-4 flex flex-column flex-align-items-center flex-justify-end', isMostPopular && 'border-primary is-focused', ])} > {children} </div> </div> </DealProvider> ); }); Deal.displayName = 'Deal'; export default Deal;
6,545
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/shared
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/shared/deal/DealCTA.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useDealContext } from './DealContext'; const DealCTA = () => { const { deal, onSelectDeal, offer, currency } = useDealContext(); const { popular } = deal; return ( <Button color="norm" shape={popular === 1 ? 'solid' : 'outline'} className="mb-4" fullWidth onClick={() => { onSelectDeal(offer, deal, currency); }} > {deal.getCTAContent?.() || c('specialoffer: Offers').t`Get the deal`} </Button> ); }; export default DealCTA;
6,546
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/shared
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/shared/deal/DealContext.tsx
import { createContext, useContext } from 'react'; import { DealProps } from '../../../interface'; const DealContext = createContext<DealProps | undefined>(undefined); interface ProviderProps extends DealProps { children: React.ReactNode; } export const DealProvider = ({ children, ...props }: ProviderProps) => ( <DealContext.Provider value={{ ...props }}>{children}</DealContext.Provider> ); export const useDealContext = () => { const context = useContext(DealContext); if (context === undefined) { throw new Error('Deal context is not set'); } return context; };
6,547
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/shared
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/shared/deal/DealFeatures.tsx
import { useMemo } from 'react'; import { c } from 'ttag'; import { Badge, Icon, Info, InlineLinkButton, StripedItem, StripedList } from '@proton/components/'; import clsx from '@proton/utils/clsx'; import { useDealContext } from './DealContext'; interface Props { isExpanded?: boolean; expand: () => void; } const DealFeatures = ({ isExpanded, expand }: Props) => { const { deal } = useDealContext(); const features = useMemo(() => deal.features?.(), [deal.features]); if (!features?.length) { return null; } return ( <div className="flex-item-fluid-auto w-full"> {isExpanded && ( <StripedList alternate="odd"> {features.map((feature) => ( <StripedItem key={`${feature.name}-${feature.icon}`} left={ !!feature.icon ? ( <Icon className="color-success" name={feature.icon} size={20} /> ) : ( <Icon className="color-success" name="checkmark" size={20} /> ) } > {feature.badge && <Badge type="primary">{feature.badge}</Badge>} <span className={clsx(['text-left', feature.disabled && 'color-disabled'])}> {feature.name} </span> {!!feature.tooltip && <Info buttonClass="ml-1" title={feature.tooltip} />} </StripedItem> ))} </StripedList> )} {!isExpanded && ( <div className="w-full text-center flex"> <InlineLinkButton className="mx-auto" onClick={() => expand()}> <span>{c('Action').t`See plan features`}</span> <Icon name="chevron-down" className="ml-2" /> </InlineLinkButton> </div> )} </div> ); }; export default DealFeatures;
6,548
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/shared
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/shared/deal/DealGuarantee.tsx
import { c } from 'ttag'; import { Icon } from '@proton/components/components'; import { useDealContext } from './DealContext'; const DealGuarantee = () => { const { deal } = useDealContext(); if (deal?.isGuaranteed === true) { return ( <p className="flex mx-auto flex-items-align-center text-sm m-0 max-w-full flex-nowrap color-success"> <span className="flex-item-noshrink flex mr-1"> <Icon name="shield" /> </span> <span className="flex-item-fluid">{c('bf2023: Offers').t`30-day money-back guarantee`}</span> </p> ); } return null; }; export default DealGuarantee;
6,549
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/shared
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/shared/deal/DealMostPopular.tsx
import { useDealContext } from './DealContext'; const DealMostPopular = () => { const { deal: { header }, } = useDealContext(); return ( <div className="text-center offer-most-popular mt-4 text-sm text-semibold"> {header && <span className="text-uppercase color-primary">{header()}</span>} </div> ); }; export default DealMostPopular;
6,550
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/shared
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/shared/deal/DealPrice.tsx
import { c } from 'ttag'; import { Price } from '@proton/components/components'; import { useDealContext } from '../deal/DealContext'; const DealPrice = () => { const { deal: { prices, cycle }, currency, } = useDealContext(); const { withCoupon = 0, withoutCouponMonthly = 0 } = prices || {}; return ( <div className="my-4 text-center"> <Price currency={currency} className="offer-monthly-price color-norm" suffix={c('specialoffer: Offers').t`/ month`} isDisplayedInSentence > {withCoupon / cycle} </Price> <Price className="text-strike color-weak offer-regular-price relative" currency={currency} suffix={c('specialoffer: Offers').t`/ month`} > {withoutCouponMonthly} </Price> </div> ); }; export default DealPrice;
6,551
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/shared
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/shared/deal/DealPriceInfos.tsx
import { Price } from '@proton/components/components'; import { getDealBilledDescription } from '../../../helpers/offerCopies'; import { useDealContext } from './DealContext'; const DealPriceInfos = () => { const { deal: { cycle, prices, star }, currency, } = useDealContext(); const { withCoupon = 0 } = prices || {}; const amountDue = ( <Price key="deal-amount" currency={currency} isDisplayedInSentence> {withCoupon} </Price> ); // const regularPrice = ( // <span key="deal-regular-price"> // <Price currency={currency}>{withoutCouponMonthly * cycle}</Price> // </span> // ); return ( <div className="w-full"> <small className="w-full color-weak text-left"> <span className="block"> {getDealBilledDescription(cycle, amountDue)} {star ? <sup>{star}</sup> : null} </span> {/* <span className="block">{getStandardPriceDescription(cycle, regularPrice)}</span> */} </small> </div> ); }; export default DealPriceInfos;
6,552
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/shared
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/shared/deal/DealTitle.tsx
import { getDealDuration } from '../../../helpers/offerCopies'; import { useDealContext } from './DealContext'; const DealTitle = () => { const { deal: { dealName, cycle }, } = useDealContext(); return ( <div className="offer-plan-namePeriod"> <strong className="offer-plan-name block text-center text-2xl mt-1 mb-0">{dealName}</strong> <span className="color-weak block text-center">{getDealDuration(cycle)}</span> </div> ); }; export default DealTitle;
6,553
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/shared
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/shared/deal/Deals.tsx
import { useEffect, useState } from 'react'; import { useActiveBreakpoint } from '@proton/components/hooks'; import { OfferProps } from '../../../interface'; import Deal from './Deal'; import DealCTA from './DealCTA'; import DealFeatures from './DealFeatures'; import DealGuarantee from './DealGuarantee'; import DealMostPopular from './DealMostPopular'; import DealPrice from './DealPrice'; import DealPriceInfos from './DealPriceInfos'; import DealTitle from './DealTitle'; const Deals = (props: OfferProps) => { const { deals } = props.offer; const [isExpanded, setIsExpanded] = useState(true); const { isNarrow, isMediumDesktop } = useActiveBreakpoint(); useEffect(() => { if (isNarrow) { setIsExpanded(false); } if (isMediumDesktop && deals.length > 3) { setIsExpanded(false); } }, [isNarrow, isMediumDesktop]); return ( <div className="offer-wrapper gap-4 flex flex-nowrap flex-justify-center on-mobile-flex-column mt-11"> {deals.map((deal) => ( <Deal key={deal.ref} {...props} deal={deal}> <DealMostPopular /> <DealTitle /> <DealPrice /> <DealCTA /> <DealGuarantee /> <div className="offer-features flex-item-fluid-auto w-full mb-4"> <DealFeatures isExpanded={isExpanded} expand={() => setIsExpanded(true)} /> </div> <DealPriceInfos /> </Deal> ))} </div> ); }; export default Deals;
6,554
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/shared
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/components/shared/deal/DealsWithCycleSelector.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { CycleSelector } from '@proton/components/containers/payments'; import { CYCLE } from '@proton/shared/lib/constants'; import { OfferProps } from '../../../interface'; import Deal from './Deal'; import DealCTA from './DealCTA'; import DealFeatures from './DealFeatures'; import DealMostPopular from './DealMostPopular'; import DealPrice from './DealPrice'; import DealPriceInfos from './DealPriceInfos'; import DealTitle from './DealTitle'; const DealsWithCycleSelector = (props: OfferProps) => { const [isExpanded, setIsExpanded] = useState(false); const [cycle, setCycle] = useState(CYCLE.TWO_YEARS); const filteredDeals = props.offer.deals.filter((deal) => deal.cycle === cycle); if (!filteredDeals.length) { return null; } return ( <> <div className="text-center"> <CycleSelector mode="buttons" cycle={cycle} onSelect={setCycle} options={[ { text: c('summer2023: Billing cycle option').t`1 year`, value: CYCLE.YEARLY }, { text: c('summer2023: Billing cycle option').t`2 years`, value: CYCLE.TWO_YEARS }, ]} /> </div> <div className="offer-wrapper gap-4 flex flex-nowrap flex-justify-center on-mobile-flex-column mt-11"> {filteredDeals.map((deal) => ( <Deal key={deal.ref} {...props} deal={deal}> <DealMostPopular /> <DealTitle /> <DealPrice /> <DealCTA /> <div className="offer-features flex-item-fluid-auto w-full mb-4"> <DealFeatures isExpanded={isExpanded} expand={() => setIsExpanded(true)} /> </div> <DealPriceInfos /> </Deal> ))} </div> </> ); }; export default DealsWithCycleSelector;
6,555
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/helpers/dealPrices.test.ts
import { CYCLE } from '@proton/shared/lib/constants'; import { DealWithPrices } from '../interface'; import { getDiscount, getDiscountWithCoupon } from './dealPrices'; describe('getDiscountWithCoupon', () => { it('should return discount', () => { expect( getDiscountWithCoupon({ cycle: CYCLE.YEARLY, prices: { withCoupon: 44, withoutCouponMonthly: 77, }, } as DealWithPrices) ).toBe(95); }); it('should return custom discount for 15 months', () => { expect( getDiscountWithCoupon({ cycle: CYCLE.FIFTEEN, prices: { withCoupon: 7188, withoutCoupon: 14985, withoutCouponMonthly: 999, }, } as DealWithPrices) ).toBe(52); }); it('should return custom discount for 30 months', () => { expect( getDiscountWithCoupon({ cycle: CYCLE.THIRTY, prices: { withCoupon: 11976, withoutCoupon: 29970, withoutCouponMonthly: 999, }, } as DealWithPrices) ).toBe(60); }); }); describe('getDiscount', () => { it('should return discount', () => { expect( getDiscount({ cycle: CYCLE.YEARLY, prices: { withoutCoupon: 44, withoutCouponMonthly: 77, }, } as DealWithPrices) ).toBe(95); }); });
6,556
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/helpers/dealPrices.ts
import { checkSubscription } from '@proton/shared/lib/api/payments'; import { CYCLE } from '@proton/shared/lib/constants'; import { Api, Currency, SubscriptionCheckResponse } from '@proton/shared/lib/interfaces'; import { DealWithPrices, OfferConfig } from '../interface'; export const fetchDealPrices = async (api: Api, offerConfig: OfferConfig, currency: Currency) => Promise.all( offerConfig.deals.map(({ planIDs, cycle, couponCode }) => { return Promise.all([ api<SubscriptionCheckResponse>( checkSubscription({ Plans: planIDs, CouponCode: couponCode, Currency: currency, Cycle: cycle, }) ), api<SubscriptionCheckResponse>( checkSubscription({ Plans: planIDs, Currency: currency, Cycle: cycle, }) ), api<SubscriptionCheckResponse>( checkSubscription({ Plans: planIDs, Currency: currency, Cycle: CYCLE.MONTHLY, }) ), ]); }) ); export const getDiscountWithCoupon = (deal: DealWithPrices) => { const { withCoupon = 0, withoutCouponMonthly = 0 } = deal.prices || {}; const withCouponMonthly = withCoupon / deal.cycle; return 100 - Math.round((withCouponMonthly * 100) / withoutCouponMonthly); }; export const getDiscount = (deal: DealWithPrices) => { const { withoutCoupon = 0, withoutCouponMonthly = 0 } = deal.prices || {}; return 100 - Math.round((withoutCoupon * 100) / (withoutCouponMonthly * deal.cycle)); };
6,557
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/helpers/getOfferRedirectionParams.ts
import { Currency } from '@proton/shared/lib/interfaces'; import { Deal, Offer } from '../interface'; interface Props { offer: Offer; deal: Deal; currency: Currency; } const getOfferRedirectionParams = ({ offer, deal, currency }: Props): URLSearchParams => { const { cycle, couponCode, ref, planIDs } = deal; const { ID, enableCycleSelector } = offer; const [planName] = Object.keys(planIDs); const params = new URLSearchParams(); params.set('cycle', `${cycle}`); params.set('currency', currency); if (couponCode) { params.set('coupon', couponCode); } params.set('plan', planName); params.set('type', 'offer'); params.set('edit', enableCycleSelector ? 'enable' : 'disable' || 'disable'); // Allow to choose to enable or disable the cycle selector in the subscription modal params.set('offer', ID); params.set('ref', ref); // Used by data team return params; }; export default getOfferRedirectionParams;
6,558
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/helpers/hasOffer.ts
import { OfferLayoutProps, OfferProps } from '../interface'; const hasOffer = (props: OfferLayoutProps): props is OfferProps => { return !!props.offer; }; export default hasOffer;
6,559
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/helpers/offerCopies.tsx
import { ReactElement } from 'react'; import { c, msgid } from 'ttag'; import { BRAND_NAME, CALENDAR_APP_NAME, CALENDAR_SHORT_APP_NAME, CYCLE, DRIVE_APP_NAME, DRIVE_SHORT_APP_NAME, MAIL_APP_NAME, MAIL_SHORT_APP_NAME, PLANS, PLAN_NAMES, VPN_SHORT_APP_NAME, } from '@proton/shared/lib/constants'; import { getPremiumPasswordManagerText } from '@proton/shared/lib/helpers/checkout'; import humanSize from '@proton/shared/lib/helpers/humanSize'; export const getMonthFreeText = (n: number) => { return c('specialoffer: Deal').ngettext(msgid`${n} month FREE`, `${n} months FREE`, n); }; export const getMonthsFree = (cycle: CYCLE) => { if (cycle === CYCLE.THIRTY) { return 6; } if (cycle === CYCLE.FIFTEEN) { return 3; } return 0; }; const getStorageSizeFeature = (storageSize: string, vpn?: boolean) => { return { name: c('bf2023: Deal details').t`${storageSize} storage`, tooltip: vpn ? undefined : c('bf2023: Tooltip').t`Storage space is shared across all ${BRAND_NAME} apps.`, }; }; export const getUnlimitedFeatures = () => { return [ getStorageSizeFeature(humanSize(500 * 1024 ** 3, undefined, undefined, 0)), { name: c('specialoffer: Deal details').t`All paid Mail and Calendar features`, tooltip: c('specialoffer: Tooltip') .t`Includes support for 3 custom email domains, 15 email addresses, unlimited hide-my-email aliases, calendar sharing, and more.`, }, { name: c('specialoffer: Deal details').t`High speed VPN`, tooltip: c('specialoffer: Tooltip') .t`Access blocked content and browse privately. Includes 1700 servers in 60+ countries, highest VPN speed, 10 VPN connections, worldwide streaming services, malware and ad-blocker, and more.`, }, { name: c('specialoffer: Deal details').t`Secure cloud storage`, tooltip: c('specialoffer: Tooltip') .t`Secure your files with encrypted cloud storage. Includes automatic sync, encrypted file sharing, and more.`, }, ]; }; export const getMailDealFeatures = () => { return [ getStorageSizeFeature(humanSize(15 * 1024 ** 3, undefined, undefined, 0)), { name: c('summer2023: Deal details').t`Premium ${MAIL_SHORT_APP_NAME} & ${CALENDAR_SHORT_APP_NAME}`, tooltip: c('summer2023: Tooltip') .t`Includes support for 1 custom email domain, 10 email addresses, 10 hide-my-email aliases, calendar sharing, and more.`, }, ]; }; export const getUnlimitedDealFeatures = () => { return [ getStorageSizeFeature(humanSize(500 * 1024 ** 3, undefined, undefined, 0)), { name: c('specialoffer: Deal details').t`Premium ${MAIL_SHORT_APP_NAME} & ${CALENDAR_SHORT_APP_NAME}`, tooltip: c('specialoffer: Tooltip') .t`Includes support for 3 custom email domains, 15 email addresses, unlimited hide-my-email aliases, calendar sharing, and more.`, }, { name: c('summer2023: Deal details').t`Premium ${DRIVE_SHORT_APP_NAME}`, tooltip: c('summer2023: Tooltip') .t`Secure your files with encrypted cloud storage. Includes version history, encrypted file sharing, and more.`, }, { name: c('specialoffer: Deal details').t`Premium ${VPN_SHORT_APP_NAME}`, tooltip: c('summer2023: Tooltip') .t`Includes 2950+ servers in 65+ countries, connect up to 10 devices, access worldwide streaming services, malware and ad-blocker, and more.`, }, { name: getPremiumPasswordManagerText(), tooltip: c('summer2023: Tooltip') .t`Create secure login details on all your devices. Includes unlimited aliases, 20 vaults, integrated 2FA, credit card auto-fill and more.`, }, ]; }; const getPremiumVPNFeature = () => ({ name: PLAN_NAMES[PLANS.VPN], tooltip: c('bf2023: Tooltip') .t`Access blocked content and browse privately. Includes 3,000+ servers across 65+ countries, highest VPN speeds, access to worldwide streaming services, malware and ad-blocker, fast BitTorrent downloads, and more.`, }); const getPremiumPasswordManagerFeature = () => ({ name: PLAN_NAMES[PLANS.PASS_PLUS], tooltip: c('bf2023: Tooltip') .t`Secure logins on all your devices. Includes unlimited aliases, sharing, integrated 2FA, and more.`, }); const getPremiumDriveFeature = () => ({ name: PLAN_NAMES[PLANS.DRIVE], tooltip: c('bf2023: Tooltip') .t`Secure your files with encrypted cloud storage. Includes version history, encrypted file sharing, and more.`, }); const getPremiumInboxFeature = (domains?: number, addresses?: number) => { const name = c('bf2023: Deal details').t`${MAIL_SHORT_APP_NAME} Plus and ${CALENDAR_SHORT_APP_NAME}`; if (domains && addresses) { if (domains === 1) { return { name: c('bf2023: Deal details').t`All paid ${MAIL_SHORT_APP_NAME} and ${CALENDAR_APP_NAME} features`, tooltip: c('bf2023: Tooltip') .t`Includes support for 1 custom email domain, 10 email addresses, 10 hide-my-email aliases, calendar sharing, and more.`, }; } return { name, tooltip: c('bf2023: Tooltip').ngettext( msgid`Includes support for 3 custom email domains, ${addresses} email address, unlimited hide-my-email aliases, calendar sharing, and more.`, `Includes support for 3 custom email domains, ${addresses} email addresses, unlimited hide-my-email aliases, calendar sharing, and more.`, addresses ), }; } return { name, tooltip: c('bf2023: Tooltip') .t`Secure your emails and schedule with end-to-end encryption. Includes support for custom email domains, 15 email addresses, unlimited hide-my-email aliases, calendar sharing, and more.`, }; }; export const getMailPlusInboxFeatures = () => { return [ getStorageSizeFeature(humanSize(15 * 1024 ** 3, undefined, undefined, 0)), { name: c('specialoffer: Deal details').t`1 user`, }, getPremiumInboxFeature(1, 10), ]; }; export const getUnlimitedVPNFeatures = () => [ getPremiumVPNFeature(), getPremiumPasswordManagerFeature(), getPremiumDriveFeature(), getPremiumInboxFeature(), ]; export const getUnlimitedInboxFeatures = () => [ getStorageSizeFeature(humanSize(500 * 1024 ** 3, undefined, undefined, 0)), { name: c('bf2023: Deal details').t`1 user` }, getPremiumInboxFeature(3, 15), getPremiumDriveFeature(), getPremiumVPNFeature(), getPremiumPasswordManagerFeature(), ]; export const getFamilyInboxFeatures = () => [ // humanSize doesn't support TB and we don't want to add it yet because of "nice numbers" rounding issues. getStorageSizeFeature(c('bf2023: Deal details').t`3 TB`), { name: c('bf2023: Deal details').t`6 users` }, getPremiumInboxFeature(3, 90), getPremiumDriveFeature(), getPremiumVPNFeature(), getPremiumPasswordManagerFeature(), ]; export const getDriveFeatures = () => [ getStorageSizeFeature(humanSize(200 * 1024 ** 3, undefined, undefined, 0)), { name: c('bf2023: Deal details').t`1 user` }, { name: c('bf2023: Deal details').t`Extended version history`, tooltip: c('bf2023: Tooltip').t`Store up to 200 versions of each file for up to 10 years.`, }, ]; export const getUnlimitedDriveFeatures = () => [ getStorageSizeFeature(humanSize(500 * 1024 ** 3, undefined, undefined, 0)), { name: c('bf2023: Deal details').t`1 user` }, getPremiumDriveFeature(), getPremiumInboxFeature(3, 15), getPremiumVPNFeature(), getPremiumPasswordManagerFeature(), ]; export const getFamilyDriveFeatures = () => [ // humanSize doesn't support TB and we don't want to add it yet because of "nice numbers" rounding issues. getStorageSizeFeature(c('bf2023: Deal details').t`3 TB`), { name: c('bf2023: Deal details').t`6 users` }, getPremiumDriveFeature(), getPremiumInboxFeature(3, 90), getPremiumVPNFeature(), getPremiumPasswordManagerFeature(), ]; export const getVPNFeatures = () => [ { name: c('bf2023: Deal details').t`3,000+ servers across 65+ countries`, }, { name: c('bf2023: Deal details').t`High speed streaming`, tooltip: c('bf2023: Tooltip') .t`Access content on streaming services including Netflix, Disney+, Prime Video, and more, from anywhere.`, }, { name: c('bf2023: Deal details').t`Ad-blocker and malware protection`, tooltip: c('bf2023: Tooltip') .t`Specially designed NetShield protects your devices and speeds up your browsing by blocking ads, trackers, and malware.`, }, { name: c('bf2023: Deal details').t`Access content worldwide`, tooltip: c('bf2023: Tooltip') .t`Bypass local internet blocks and censorship with our global network of servers.`, }, ]; export const getVisionaryFeatures = () => [ // humanSize doesn't support TB and we don't want to add it yet because of "nice numbers" rounding issues. getStorageSizeFeature(c('specialoffer: Deal details').t`3 TB`), { name: c('specialoffer: Deal details').t`6 users`, tooltip: c('specialoffer: Tooltip') .t`Perfect for families or small teams, each can have their own inbox and aliases. Requires a custom domain.`, }, { name: c('specialoffer: Deal details') .t`Premium ${MAIL_SHORT_APP_NAME}, ${CALENDAR_SHORT_APP_NAME} & ${DRIVE_SHORT_APP_NAME}`, tooltip: c('specialoffer: Tooltip') .t`All our premium services with their highest limits: 100 email addresses, support for 10 custom domains, unlimited hide-my-email aliases, calendar sharing, encrypted cloud storage and file sharing, and more.`, }, { name: c('specialoffer: Deal details').t`Premium ${VPN_SHORT_APP_NAME}`, tooltip: c('specialoffer: Tooltip') .t`Access blocked content and browse privately. Includes 1700 servers in 60+ countries, highest VPN speed, 10 VPN connections per user, worldwide streaming services, malware and ad-blocker, and more.`, }, { name: c('specialoffer: Deal details').t`Premium early access`, tooltip: c('specialoffer: Tooltip') .t`Receive at no extra cost the paid versions of all new privacy services we release in the future, along with early access to all future features and products.`, }, { name: c('specialoffer: Deal details').t`Support online privacy`, }, ]; export const getFamilyFeatures = () => [ { name: c('familyOffer_2023:Deal details').t`Up to 6 users`, }, { name: c('familyOffer_2023: Deal details').t`3 TB total storage`, tooltip: c('familyOffer_2023: Tooltip') .t`Storage space is shared between family members across ${MAIL_APP_NAME}, ${CALENDAR_APP_NAME}, and ${DRIVE_APP_NAME}.`, }, { name: c('familyOffer_2023:Deal details').t`Premium ${MAIL_SHORT_APP_NAME} & ${CALENDAR_SHORT_APP_NAME}`, tooltip: c('familyOffer_2023:Tooltip') .t`Includes support for 3 custom email domains, 90 email addresses, unlimited hide-my-email aliases, calendar sharing and more.`, }, { name: c('familyOffer_2023:Deal details').t`Premium ${DRIVE_SHORT_APP_NAME}`, tooltip: c('familyOffer_2023:Tooltip') .t`Secure your files with encrypted cloud storage. Includes automatic sync, encrypted file sharing, and more.`, }, { name: c('familyOffer_2023:Deal details').t`Premium ${VPN_SHORT_APP_NAME}`, tooltip: c('familyOffer_2023:Tooltip') .t`Includes 2700 servers in 65+ countries, connect up to 10 devices, access worldwide streaming services, malware and ad-blocker, and more.`, }, { name: getPremiumPasswordManagerText(), tooltip: c('summer2023: Tooltip') .t`Create secure login details on all your devices. Includes unlimited aliases, 20 vaults, integrated 2FA, credit card auto-fill and more.`, }, ]; export const getVPNPlusFeatures = () => [ { name: c('specialoffer: Deal details').t`64 countries`, }, { name: c('specialoffer: Deal details').t`Highest VPN speed`, }, { name: c('specialoffer: Deal details').t`Secure streaming`, tooltip: c('specialoffer: Tooltip') .t`Access content on streaming services, including Netflix, Disney+, and Prime Video, from anywhere.`, }, ]; export const getDealBilledDescription = (cycle: CYCLE, amount: ReactElement): string | string[] | null => { switch (cycle) { case CYCLE.MONTHLY: return c('specialoffer: Offers').jt`Billed at ${amount} for 1 month`; case CYCLE.YEARLY: return c('specialoffer: Offers').jt`Billed at ${amount} for 12 months`; case CYCLE.TWO_YEARS: return c('specialoffer: Offers').jt`Billed at ${amount} for 24 months`; case CYCLE.FIFTEEN: return c('specialoffer: Offers').jt`Billed at ${amount} for 15 months`; case CYCLE.THIRTY: return c('specialoffer: Offers').jt`Billed at ${amount} for 30 months`; default: return null; } }; export const getStandardPriceDescription = (cycle: CYCLE, amount: ReactElement): string | string[] | null => { switch (cycle) { case CYCLE.MONTHLY: return c('specialoffer: Offers').jt`Standard price ${amount} for 1 month`; case CYCLE.YEARLY: return c('specialoffer: Offers').jt`Standard price ${amount} for 12 months`; case CYCLE.TWO_YEARS: return c('specialoffer: Offers').jt`Standard price ${amount} for 24 months`; case CYCLE.FIFTEEN: return c('specialoffer: Offers').jt`Standard price ${amount} for 15 months`; case CYCLE.THIRTY: return c('specialoffer: Offers').jt`Standard price ${amount} for 30 months`; default: return null; } }; export const getDealDurationText = (cycle: CYCLE | undefined) => { const n = Number(cycle); if (n === 12) { return c('specialoffer: Offers').t`1 year`; } if (n === 24) { return c('specialoffer: Offers').t`2 years`; } if (n === 15) { return c('specialoffer: Offers').t`15 months`; } if (n === 30) { return c('specialoffer: Offers').t`30 months`; } return c('specialoffer: Offers').ngettext(msgid`${n} month`, `${n} months`, n); }; export const getDealDuration = (cycle: CYCLE): ReactElement | null => { return <>{getDealDurationText(cycle)}</>; }; export const getRenewDescription = ( cycle: CYCLE, discountedAmount: ReactElement, regularAmount: ReactElement, discount: number ): string | string[] | null => { switch (cycle) { case CYCLE.YEARLY: return c('specialoffer: Offers') .jt`Renews after 1 year at a discounted price of ${discountedAmount} instead of ${regularAmount} (${discount}% discount)`; case CYCLE.TWO_YEARS: return c('specialoffer: Offers') .jt`Renews after 2 years at a discounted price of ${discountedAmount} instead of ${regularAmount} (${discount}% discount)`; default: return null; } };
6,560
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/helpers/offerPeriods.ts
import { isBefore, isWithinInterval } from 'date-fns'; export const CYBER_WEEK_START = new Date(Date.UTC(2023, 10, 27, 9, 0, 0)); // November 27 09:00:00 UTC export const CYBER_WEEK_END = new Date(Date.UTC(2023, 11, 4, 9, 0, 0)); // December 4 09:00:00 UTC export const END_OF_THE_YEAR_START = new Date(Date.UTC(2023, 11, 23, 9, 0, 0)); // December 23 09:00:00 UTC export const END_OF_THE_YEAR_END = new Date(Date.UTC(2024, 0, 3, 9, 0, 0)); // January 3 09:00:00 UTC export const FREE_DOWNGRADER_LIMIT = new Date(Date.UTC(2023, 9, 1, 0, 0, 0)); // October 1 2023 00:00:00 UTC /** * After Nov 28 2022 6:00 AM UTC and before Dec 5 2022 6:00 AM UTC * @returns {boolean} true if the offer is available for the current date */ export const isCyberWeekPeriod = () => { const now = new Date(); return isWithinInterval(now, { start: CYBER_WEEK_START, end: CYBER_WEEK_END }); }; /** * After Dec 5 2022 6:00 AM UTC and before Jan 2 2023 6:00 AM UTC * @returns {boolean} true if the offer is available for the current date */ export const isEndOfYearPeriod = () => { const now = new Date(); return isWithinInterval(now, { start: END_OF_THE_YEAR_START, end: END_OF_THE_YEAR_END }); }; export const isBlackFridayPeriod = () => { const now = new Date(); return isBefore(now, CYBER_WEEK_START); };
6,561
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/hooks/useFetchOffer.ts
import { useEffect, useState } from 'react'; import { useLoading } from '@proton/hooks'; import { Currency } from '@proton/shared/lib/interfaces'; import { useApi } from '../../../hooks'; import { fetchDealPrices } from '../helpers/dealPrices'; import { Offer, OfferConfig } from '../interface'; interface Props { offerConfig: OfferConfig | undefined; currency: Currency; onSuccess?: () => void; onError?: () => void; } function useFetchOffer({ offerConfig, currency, onSuccess, onError }: Props): [Offer | undefined, boolean] { const api = useApi(); const [loading, withLoading] = useLoading(); const [state, setState] = useState<Partial<{ offer: Offer; offerConfig: OfferConfig }>>(); useEffect(() => { if (!offerConfig) { return; } const updateOfferPrices = async () => { try { // Reset previous offer prices in case the offer config has changed from what was previously cached if (state?.offerConfig !== offerConfig) { setState(undefined); } const result = await fetchDealPrices(api, offerConfig, currency); // We make an offer based on offerConfig + fetched results above const offer: Offer = { ...offerConfig, deals: offerConfig.deals.map((deal, index) => { const [withCoupon, withoutCoupon, withoutCouponMonthly] = result[index]; return { ...deal, prices: { withCoupon: withCoupon.Amount + (withCoupon.CouponDiscount || 0), withoutCoupon: withoutCoupon.Amount + (withoutCoupon.CouponDiscount || 0), // BUNDLE discount can be applied withoutCouponMonthly: withoutCouponMonthly.Amount, }, }; }), }; setState({ offer, offerConfig }); onSuccess?.(); } catch (error) { onError?.(); } }; void withLoading(updateOfferPrices()); }, [offerConfig, currency]); return [state?.offer, loading]; } export default useFetchOffer;
6,562
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/hooks/useOfferConfig.ts
import { useFeatures } from '@proton/components/hooks'; import { FeatureCode } from '../../features'; import { OfferConfig, OfferId, Operation } from '../interface'; import { blackFriday2023DriveFreeConfig, useBlackFriday2023DriveFree } from '../operations/blackFridayDrive2023Free'; import { blackFriday2023DrivePlusConfig, useBlackFriday2023DrivePlus } from '../operations/blackFridayDrive2023Plus'; import { blackFriday2023DriveUnlimitedConfig, useBlackFriday2023DriveUnlimited, } from '../operations/blackFridayDrive2023Unlimited'; import { blackFriday2023InboxFreeConfig, useBlackFriday2023InboxFree } from '../operations/blackFridayInbox2023Free'; import { blackFriday2023InboxMailConfig, useBlackFriday2023InboxMail } from '../operations/blackFridayInbox2023Plus'; import { blackFriday2023InboxUnlimitedConfig, useBlackFriday2023InboxUnlimited, } from '../operations/blackFridayInbox2023Unlimited'; import { blackFriday2023VPNFreeConfig, useBlackFriday2023VPNFree } from '../operations/blackFridayVPN2023Free'; import { blackFriday2023VPNMonthlyConfig, useBlackFriday2023VPNMonthly } from '../operations/blackFridayVPN2023Monthly'; import { blackFriday2023VPNTwoYearsConfig, useBlackFriday2023VPNTwoYears, } from '../operations/blackFridayVPN2023TwoYears'; import { blackFriday2023VPNYearlyConfig, useBlackFriday2023VPNYearly } from '../operations/blackFridayVPN2023Yearly'; import { goUnlimited2022Config, useGoUnlimited2022 } from '../operations/goUnlimited2022'; import { mailTrial2023Config, useMailTrial2023 } from '../operations/mailTrial2023'; const configs: Record<OfferId, OfferConfig> = { 'go-unlimited-2022': goUnlimited2022Config, 'mail-trial-2023': mailTrial2023Config, 'black-friday-2023-inbox-free': blackFriday2023InboxFreeConfig, 'black-friday-2023-inbox-mail': blackFriday2023InboxMailConfig, 'black-friday-2023-inbox-unlimited': blackFriday2023InboxUnlimitedConfig, 'black-friday-2023-vpn-free': blackFriday2023VPNFreeConfig, 'black-friday-2023-vpn-monthly': blackFriday2023VPNMonthlyConfig, 'black-friday-2023-vpn-yearly': blackFriday2023VPNYearlyConfig, 'black-friday-2023-vpn-two-years': blackFriday2023VPNTwoYearsConfig, 'black-friday-2023-drive-free': blackFriday2023DriveFreeConfig, 'black-friday-2023-drive-plus': blackFriday2023DrivePlusConfig, 'black-friday-2023-drive-unlimited': blackFriday2023DriveUnlimitedConfig, }; const OFFERS_FEATURE_FLAGS = Object.values(configs).map(({ featureCode }) => featureCode); const useOfferConfig = (): [OfferConfig | undefined, boolean] => { // Preload FF to avoid single API requests useFeatures([FeatureCode.Offers, ...OFFERS_FEATURE_FLAGS]); const goUnlimited2022 = useGoUnlimited2022(); const mailTrial2023 = useMailTrial2023(); const blackFriday2023InboxFree = useBlackFriday2023InboxFree(); const blackFriday2023InboxMail = useBlackFriday2023InboxMail(); const blackFriday2023InboxUnlimited = useBlackFriday2023InboxUnlimited(); const blackFriday2023VPNFree = useBlackFriday2023VPNFree(); const blackFriday2023VPNMonthly = useBlackFriday2023VPNMonthly(); const blackFriday2023VPNYearly = useBlackFriday2023VPNYearly(); const blackFriday2023VPNTwoYears = useBlackFriday2023VPNTwoYears(); const blackFriday2023DriveFree = useBlackFriday2023DriveFree(); const blackFriday2023DrivePlus = useBlackFriday2023DrivePlus(); const blackFriday2023DriveUnlimited = useBlackFriday2023DriveUnlimited(); // Offer order matters const allOffers: Operation[] = [ blackFriday2023InboxFree, blackFriday2023InboxMail, blackFriday2023InboxUnlimited, blackFriday2023VPNFree, blackFriday2023VPNMonthly, blackFriday2023VPNYearly, blackFriday2023VPNTwoYears, blackFriday2023DriveFree, blackFriday2023DrivePlus, blackFriday2023DriveUnlimited, goUnlimited2022, mailTrial2023, ]; const validOffer: Operation | undefined = allOffers.find((offer) => !offer.isLoading && offer.isValid); const isLoading = allOffers.some((offer) => offer.isLoading); return [validOffer?.config, isLoading]; }; export default useOfferConfig;
6,563
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/hooks/useOfferFlags.ts
import { useFeature } from '@proton/components/hooks'; import { hasBit, setBit } from '@proton/shared/lib/helpers/bitset'; import { FeatureCode } from '../../features'; import { OfferConfig, OfferGlobalFeatureCodeValue, OfferUserFeatureCodeValue } from '../interface'; const { Default, Visited, Hide } = OfferUserFeatureCodeValue; const useOfferFlags = (config: OfferConfig) => { const { feature: globalFlag, loading: globalFlagLoading } = useFeature<OfferGlobalFeatureCodeValue>( FeatureCode.Offers ); const { feature: userFlag, loading: userFlagLoading, update: userFlagUpdate, } = useFeature<OfferUserFeatureCodeValue>(config.featureCode); const userFlagValue = userFlag?.Value || Default; return { loading: globalFlagLoading || userFlagLoading, isActive: globalFlag?.Value?.[config.ID] === true && !hasBit(userFlagValue, Hide), isVisited: hasBit(userFlagValue, Visited), handleHide: () => { const nextValue = setBit(userFlagValue, Hide); if (nextValue === userFlagValue) { return; } return userFlagUpdate(nextValue); }, handleVisit: () => { const nextValue = setBit(userFlagValue, Visited); if (nextValue === userFlagValue) { return; } return userFlagUpdate(nextValue); }, }; }; export default useOfferFlags;
6,564
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/hooks/useOfferModal.ts
import { useState } from 'react'; import { useModalState } from '@proton/components/components'; import { useUser } from '@proton/components/hooks'; import { DEFAULT_CURRENCY } from '@proton/shared/lib/constants'; import { Currency } from '@proton/shared/lib/interfaces'; import { OfferConfig } from '../interface'; import useFetchOffer from './useFetchOffer'; const useOfferModal = (offerConfig: OfferConfig) => { const [user] = useUser(); const [offerModalProps, setOfferModalOpen, renderOfferModal] = useModalState(); const [fetchOffer, setFetchOffer] = useState(false); const defaultCurrency = user?.Currency || DEFAULT_CURRENCY; const [currency, setCurrency] = useState<Currency>(defaultCurrency); const [offer, loadingOffer] = useFetchOffer({ offerConfig: fetchOffer ? offerConfig : undefined, currency, onError: () => { // This is like a retry. Resetting the offer config so that the calls get retried if the user clicks the button again. setFetchOffer(false); }, }); return { offer, currency, loadingOffer, renderOfferModal, offerModalProps, onChangeCurrency: setCurrency, setOfferModalOpen, setFetchOffer, }; }; export default useOfferModal;
6,565
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/hooks/useOnSelectDeal.ts
import { useCallback } from 'react'; import { useSettingsLink } from '@proton/components/components'; import { Currency } from '@proton/shared/lib/interfaces'; import getOfferRedirectionParams from '../helpers/getOfferRedirectionParams'; import { Deal, Offer } from '../interface'; const useSelectDeal = (callback?: () => void) => { const goToSettingsLink = useSettingsLink(); const handleOnSelectDeal = useCallback( (offer: Offer, deal: Deal, currency: Currency) => { const urlSearchParams = getOfferRedirectionParams({ offer, deal, currency }); callback?.(); goToSettingsLink(`/dashboard?${urlSearchParams.toString()}`); }, [callback] ); return handleOnSelectDeal; }; export default useSelectDeal;
6,566
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/hooks/useVisitedOffer.ts
import { useEffect } from 'react'; import { OfferConfig } from '../interface'; import useOfferFlags from './useOfferFlags'; /** * Mark the offer as visited */ const useVisitedOffer = (offerConfig: OfferConfig) => { const { handleVisit, isVisited, loading } = useOfferFlags(offerConfig); useEffect(() => { if (!loading && !isVisited && offerConfig.autoPopUp === 'one-time') { // Only mark offer as visited for one-time offers to not show it again // if autoPopUp === 'each-time', it will still show the offer each time because the offer is not marked as visited void handleVisit(); } }, [loading]); }; export default useVisitedOffer;
6,567
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayDrive2023Free/Layout.tsx
import BlackFridayFooter from '../../components/blackFriday/BlackFridayFooter'; import BlackFridayTitle from '../../components/blackFriday/BlackFridayTitle'; import OfferFooter from '../../components/shared/OfferFooter'; import OfferHeader from '../../components/shared/OfferHeader'; import OfferLayout from '../../components/shared/OfferLayout'; import OfferLoader from '../../components/shared/OfferLoader'; import Deals from '../../components/shared/deal/Deals'; import hasOffer from '../../helpers/hasOffer'; import { OfferLayoutProps } from '../../interface'; const Layout = (props: OfferLayoutProps) => { return hasOffer(props) ? ( <OfferLayout {...props}> <OfferHeader {...props}> <BlackFridayTitle /> </OfferHeader> <Deals {...props} /> <OfferFooter {...props}> <BlackFridayFooter {...props} /> </OfferFooter> </OfferLayout> ) : ( <OfferLoader /> ); }; export default Layout;
6,568
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayDrive2023Free/configuration.ts
import { FeatureCode } from '@proton/components/containers/features'; import { COUPON_CODES, CYCLE, PLANS, PLAN_NAMES } from '@proton/shared/lib/constants'; import { getDriveFeatures, getFamilyDriveFeatures, getUnlimitedDriveFeatures } from '../../helpers/offerCopies'; import { OfferConfig } from '../../interface'; import bannerImage from './BF-Drive-App-Modal-996x176.png'; import bannerImage2x from './BF-Drive-App-Modal-1992x352.png'; import Layout from './Layout'; const config: OfferConfig = { ID: 'black-friday-2023-drive-free', autoPopUp: 'one-time', featureCode: FeatureCode.OfferBlackFriday2023DriveFree, images: { bannerImage, bannerImage2x, }, darkBackground: true, deals: [ { ref: 'bf_23_drive_free-modal-d12', dealName: `${PLAN_NAMES[PLANS.DRIVE]} - 200 GB`, planIDs: { [PLANS.DRIVE]: 1, }, cycle: CYCLE.YEARLY, couponCode: COUPON_CODES.BLACK_FRIDAY_2023, features: getDriveFeatures, }, { ref: 'bf_23_drive_free-modal-u12', dealName: `${PLAN_NAMES[PLANS.BUNDLE]} - 500 GB`, planIDs: { [PLANS.BUNDLE]: 1, }, cycle: CYCLE.YEARLY, couponCode: COUPON_CODES.BLACK_FRIDAY_2023, features: getUnlimitedDriveFeatures, popular: 1, }, { ref: 'bf_23_drive_free-modal-f12', dealName: `${PLAN_NAMES[PLANS.FAMILY]} - 3 TB`, planIDs: { [PLANS.FAMILY]: 1, }, cycle: CYCLE.YEARLY, couponCode: COUPON_CODES.BLACK_FRIDAY_2023, features: getFamilyDriveFeatures, }, ], layout: Layout, }; export default config;
6,569
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayDrive2023Free/eligibility.ts
import { fromUnixTime, isBefore } from 'date-fns'; import { getAppFromPathnameSafe } from '@proton/shared/lib/apps/slugHelper'; import { APPS } from '@proton/shared/lib/constants'; import { isManagedExternally } from '@proton/shared/lib/helpers/subscription'; import { ProtonConfig, Subscription, UserModel } from '@proton/shared/lib/interfaces'; import { FREE_DOWNGRADER_LIMIT } from '../../helpers/offerPeriods'; interface Props { subscription?: Subscription; protonConfig: ProtonConfig; user: UserModel; lastSubscriptionEnd?: number; } const isEligible = ({ subscription, protonConfig, user, lastSubscriptionEnd = 0 }: Props) => { const parentApp = getAppFromPathnameSafe(window.location.pathname); const hasValidApp = protonConfig?.APP_NAME === APPS.PROTONDRIVE || (protonConfig?.APP_NAME === APPS.PROTONACCOUNT && parentApp === APPS.PROTONDRIVE); const { canPay, isDelinquent, isFree } = user; const notDelinquent = !isDelinquent; const isNotExternal = !isManagedExternally(subscription); return ( hasValidApp && isNotExternal && canPay && notDelinquent && isFree && isBefore(fromUnixTime(lastSubscriptionEnd), FREE_DOWNGRADER_LIMIT) ); }; export default isEligible;
6,570
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayDrive2023Free/index.ts
export { default as blackFriday2023DriveFreeConfig } from './configuration'; export { default as useBlackFriday2023DriveFree } from './useOffer'; export { default as blackFriday2023DriveFreeEligibility } from './eligibility';
6,571
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayDrive2023Free/useOffer.ts
import { useConfig, useLastSubscriptionEnd, useSubscription, useUser } from '@proton/components/hooks'; import useOfferFlags from '../../hooks/useOfferFlags'; import { Operation } from '../../interface'; import config from './configuration'; import getIsEligible from './eligibility'; const useOffer = (): Operation => { const [user, userLoading] = useUser(); const [subscription, subscriptionLoading] = useSubscription(); const { isActive, loading: flagsLoading } = useOfferFlags(config); const [lastSubscriptionEnd, lastSubscriptionEndLoading] = useLastSubscriptionEnd(); const protonConfig = useConfig(); const isLoading = flagsLoading || userLoading || subscriptionLoading || lastSubscriptionEndLoading; const isEligible = getIsEligible({ subscription, protonConfig, user, lastSubscriptionEnd }); const isValid = isEligible && isActive; return { isValid, config, isLoading, isEligible }; }; export default useOffer;
6,572
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayDrive2023Plus/Layout.tsx
import BlackFridayFooter from '../../components/blackFriday/BlackFridayFooter'; import BlackFridayTitle from '../../components/blackFriday/BlackFridayTitle'; import OfferFooter from '../../components/shared/OfferFooter'; import OfferHeader from '../../components/shared/OfferHeader'; import OfferLayout from '../../components/shared/OfferLayout'; import OfferLoader from '../../components/shared/OfferLoader'; import Deals from '../../components/shared/deal/Deals'; import hasOffer from '../../helpers/hasOffer'; import { OfferLayoutProps } from '../../interface'; const Layout = (props: OfferLayoutProps) => { return hasOffer(props) ? ( <OfferLayout {...props}> <OfferHeader {...props}> <BlackFridayTitle /> </OfferHeader> <Deals {...props} /> <OfferFooter {...props}> <BlackFridayFooter {...props} /> </OfferFooter> </OfferLayout> ) : ( <OfferLoader /> ); }; export default Layout;
6,573
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayDrive2023Plus/configuration.ts
import { FeatureCode } from '@proton/components/containers/features'; import { COUPON_CODES, CYCLE, PLANS, PLAN_NAMES } from '@proton/shared/lib/constants'; import { getFamilyDriveFeatures, getUnlimitedDriveFeatures } from '../../helpers/offerCopies'; import { OfferConfig } from '../../interface'; import bannerImage from './BF-Drive-App-Modal-996x176.png'; import bannerImage2x from './BF-Drive-App-Modal-1992x352.png'; import Layout from './Layout'; const config: OfferConfig = { ID: 'black-friday-2023-drive-plus', autoPopUp: 'one-time', featureCode: FeatureCode.OfferBlackFriday2023DrivePlus, images: { bannerImage, bannerImage2x, }, darkBackground: true, canBeDisabled: true, deals: [ { ref: 'bf_23_drive_plus-modal-u12', dealName: `${PLAN_NAMES[PLANS.BUNDLE]} - 500 GB`, planIDs: { [PLANS.BUNDLE]: 1, }, cycle: CYCLE.YEARLY, couponCode: COUPON_CODES.BLACK_FRIDAY_2023, features: getUnlimitedDriveFeatures, popular: 1, }, { ref: 'bf_23_drive_plus-modal-f12', dealName: `${PLAN_NAMES[PLANS.FAMILY]} - 3 TB`, planIDs: { [PLANS.FAMILY]: 1, }, cycle: CYCLE.YEARLY, couponCode: COUPON_CODES.BLACK_FRIDAY_2023, features: getFamilyDriveFeatures, }, ], layout: Layout, }; export default config;
6,574
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayDrive2023Plus/eligibility.ts
import { getAppFromPathnameSafe } from '@proton/shared/lib/apps/slugHelper'; import { APPS, PLANS } from '@proton/shared/lib/constants'; import { getPlan, isManagedExternally } from '@proton/shared/lib/helpers/subscription'; import { ProtonConfig, Subscription, UserModel } from '@proton/shared/lib/interfaces'; interface Props { subscription: Subscription; protonConfig: ProtonConfig; user: UserModel; } const isEligible = ({ subscription, protonConfig, user }: Props) => { const parentApp = getAppFromPathnameSafe(window.location.pathname); const plan = getPlan(subscription); const hasDrive = plan?.Name === PLANS.DRIVE; const hasValidApp = protonConfig?.APP_NAME === APPS.PROTONDRIVE || (protonConfig?.APP_NAME === APPS.PROTONACCOUNT && parentApp === APPS.PROTONDRIVE); const { canPay, isDelinquent } = user; const notDelinquent = !isDelinquent; const isNotExternal = !isManagedExternally(subscription); return hasValidApp && isNotExternal && canPay && notDelinquent && hasDrive; }; export default isEligible;
6,575
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayDrive2023Plus/index.ts
export { default as blackFriday2023DrivePlusConfig } from './configuration'; export { default as useBlackFriday2023DrivePlus } from './useOffer'; export { default as blackFriday2023DrivePlusEligibility } from './eligibility';
6,576
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayDrive2023Plus/useOffer.ts
import { useConfig, useSubscription, useUser } from '@proton/components/hooks'; import useOfferFlags from '../../hooks/useOfferFlags'; import { Operation } from '../../interface'; import config from './configuration'; import getIsEligible from './eligibility'; const useOffer = (): Operation => { const [user, userLoading] = useUser(); const [subscription, subscriptionLoading] = useSubscription(); const { isActive, loading: flagsLoading } = useOfferFlags(config); const protonConfig = useConfig(); const isLoading = flagsLoading || userLoading || subscriptionLoading; const isEligible = getIsEligible({ subscription, protonConfig, user }); const isValid = isEligible && isActive; return { isValid, config, isLoading, isEligible }; }; export default useOffer;
6,577
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayDrive2023Unlimited/Layout.tsx
import BlackFridayFooter from '../../components/blackFriday/BlackFridayFooter'; import BlackFridayTitle from '../../components/blackFriday/BlackFridayTitle'; import OfferFooter from '../../components/shared/OfferFooter'; import OfferHeader from '../../components/shared/OfferHeader'; import OfferLayout from '../../components/shared/OfferLayout'; import OfferLoader from '../../components/shared/OfferLoader'; import Deals from '../../components/shared/deal/Deals'; import hasOffer from '../../helpers/hasOffer'; import { OfferLayoutProps } from '../../interface'; const Layout = (props: OfferLayoutProps) => { return hasOffer(props) ? ( <OfferLayout {...props}> <OfferHeader {...props}> <BlackFridayTitle /> </OfferHeader> <Deals {...props} /> <OfferFooter {...props}> <BlackFridayFooter {...props} /> </OfferFooter> </OfferLayout> ) : ( <OfferLoader /> ); }; export default Layout;
6,578
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayDrive2023Unlimited/configuration.ts
import { FeatureCode } from '@proton/components/containers/features'; import { COUPON_CODES, CYCLE, PLANS, PLAN_NAMES } from '@proton/shared/lib/constants'; import { getFamilyDriveFeatures } from '../../helpers/offerCopies'; import { OfferConfig } from '../../interface'; import sideImage from './BF-Drive-App-Modal-400x1200-33.png'; import sideImage2x from './BF-Drive-App-Modal-800x2400-33.png'; import Layout from './Layout'; const config: OfferConfig = { ID: 'black-friday-2023-drive-unlimited', autoPopUp: 'one-time', featureCode: FeatureCode.OfferBlackFriday2023DriveUnlimited, images: { sideImage, sideImage2x, }, canBeDisabled: true, deals: [ { ref: 'bf_23_drive_unlimited-modal-f12', dealName: `${PLAN_NAMES[PLANS.FAMILY]} - 3 TB`, planIDs: { [PLANS.FAMILY]: 1, }, cycle: CYCLE.YEARLY, couponCode: COUPON_CODES.BLACK_FRIDAY_2023, features: getFamilyDriveFeatures, }, ], layout: Layout, }; export default config;
6,579
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayDrive2023Unlimited/eligibility.ts
import { getAppFromPathnameSafe } from '@proton/shared/lib/apps/slugHelper'; import { APPS, PLANS } from '@proton/shared/lib/constants'; import { getPlan, isManagedExternally } from '@proton/shared/lib/helpers/subscription'; import { ProtonConfig, Subscription, UserModel } from '@proton/shared/lib/interfaces'; interface Props { subscription: Subscription; protonConfig: ProtonConfig; user: UserModel; } const isEligible = ({ subscription, protonConfig, user }: Props) => { const parentApp = getAppFromPathnameSafe(window.location.pathname); const plan = getPlan(subscription); const hasUnlimited = plan?.Name === PLANS.BUNDLE; const hasValidApp = protonConfig?.APP_NAME === APPS.PROTONDRIVE || (protonConfig?.APP_NAME === APPS.PROTONACCOUNT && parentApp === APPS.PROTONDRIVE); const { canPay, isDelinquent } = user; const notDelinquent = !isDelinquent; const isNotExternal = !isManagedExternally(subscription); return hasValidApp && isNotExternal && canPay && notDelinquent && hasUnlimited; }; export default isEligible;
6,580
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayDrive2023Unlimited/index.ts
export { default as blackFriday2023DriveUnlimitedConfig } from './configuration'; export { default as useBlackFriday2023DriveUnlimited } from './useOffer'; export { default as blackFriday2023DriveUnlimitedEligibility } from './eligibility';
6,581
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayDrive2023Unlimited/useOffer.ts
import { useConfig, useSubscription, useUser } from '@proton/components/hooks'; import useOfferFlags from '../../hooks/useOfferFlags'; import { Operation } from '../../interface'; import config from './configuration'; import getIsEligible from './eligibility'; const useOffer = (): Operation => { const [user, userLoading] = useUser(); const [subscription, subscriptionLoading] = useSubscription(); const { isActive, loading: flagsLoading } = useOfferFlags(config); const protonConfig = useConfig(); const isLoading = flagsLoading || userLoading || subscriptionLoading; const isEligible = getIsEligible({ subscription, protonConfig, user }); const isValid = isEligible && isActive; return { isValid, config, isLoading, isEligible }; }; export default useOffer;
6,582
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayInbox2023Free/Layout.tsx
import BlackFridayFooter from '../../components/blackFriday/BlackFridayFooter'; import BlackFridayTitle from '../../components/blackFriday/BlackFridayTitle'; import OfferFooter from '../../components/shared/OfferFooter'; import OfferHeader from '../../components/shared/OfferHeader'; import OfferLayout from '../../components/shared/OfferLayout'; import OfferLoader from '../../components/shared/OfferLoader'; import Deals from '../../components/shared/deal/Deals'; import hasOffer from '../../helpers/hasOffer'; import { OfferLayoutProps } from '../../interface'; const Layout = (props: OfferLayoutProps) => { return hasOffer(props) ? ( <OfferLayout {...props}> <OfferHeader {...props}> <BlackFridayTitle /> </OfferHeader> <Deals {...props} /> <OfferFooter {...props}> <BlackFridayFooter {...props} /> </OfferFooter> </OfferLayout> ) : ( <OfferLoader /> ); }; export default Layout;
6,583
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayInbox2023Free/configuration.ts
import { FeatureCode } from '@proton/components/containers/features'; import { COUPON_CODES, CYCLE, PLANS, PLAN_NAMES } from '@proton/shared/lib/constants'; import { getFamilyInboxFeatures, getMailPlusInboxFeatures, getUnlimitedInboxFeatures } from '../../helpers/offerCopies'; import { OfferConfig } from '../../interface'; import bannerImage from './BF-Mail-App-Modal-996x176.png'; import bannerImage2x from './BF-Mail-App-Modal-1992x352.png'; import Layout from './Layout'; const config: OfferConfig = { ID: 'black-friday-2023-inbox-free', autoPopUp: 'one-time', featureCode: FeatureCode.OfferBlackFriday2023InboxFree, images: { bannerImage, bannerImage2x, }, darkBackground: true, deals: [ { ref: 'bf_23_mail_free-modal-m12', dealName: PLAN_NAMES[PLANS.MAIL], planIDs: { [PLANS.MAIL]: 1, }, cycle: CYCLE.YEARLY, couponCode: COUPON_CODES.BLACK_FRIDAY_2023, features: getMailPlusInboxFeatures, }, { ref: 'bf_23_mail_free-modal-u12', dealName: PLAN_NAMES[PLANS.BUNDLE], planIDs: { [PLANS.BUNDLE]: 1, }, cycle: CYCLE.YEARLY, couponCode: COUPON_CODES.BLACK_FRIDAY_2023, features: getUnlimitedInboxFeatures, popular: 1, }, { ref: 'bf_23_mail_free-modal-f12', dealName: PLAN_NAMES[PLANS.FAMILY], planIDs: { [PLANS.FAMILY]: 1, }, cycle: CYCLE.YEARLY, couponCode: COUPON_CODES.BLACK_FRIDAY_2023, features: getFamilyInboxFeatures, }, ], layout: Layout, }; export default config;
6,584
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayInbox2023Free/eligibility.test.ts
import { getUnixTime } from 'date-fns'; import { APPS, COUPON_CODES } from '@proton/shared/lib/constants'; import { ProtonConfig, Subscription, UserModel } from '@proton/shared/lib/interfaces'; import isEligible from './eligibility'; describe('BF 2023 Inbox offer for Free', () => { const protonConfig = { APP_NAME: APPS.PROTONMAIL } as ProtonConfig; const user = { isFree: true, isDelinquent: false, canPay: true } as UserModel; const pathname = '/u/1/mail/'; beforeAll(() => { Object.defineProperty(window, 'location', { value: { pathname }, writable: true, }); }); it('should be available for free account', () => { expect(isEligible({ user, protonConfig })).toBeTruthy(); expect(isEligible({ user, protonConfig: { ...protonConfig, APP_NAME: APPS.PROTONCALENDAR } })).toBeTruthy(); expect(isEligible({ user, protonConfig: { ...protonConfig, APP_NAME: APPS.PROTONACCOUNT } })).toBeTruthy(); }); it('should be available for trial account', () => { const subscription = { CouponCode: COUPON_CODES.REFERRAL } as Subscription; expect(isEligible({ user: { ...user, isPaid: true, isFree: false }, subscription, protonConfig })).toBeTruthy(); }); it('should not be available to downgrader', () => { const date = new Date(2023, 9, 2, 0, 0, 0); // October 2 2023 00:00:00 UTC const lastSubscriptionEnd = getUnixTime(date); expect(isEligible({ protonConfig, user, lastSubscriptionEnd })).toBeFalsy(); }); });
6,585
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayInbox2023Free/eligibility.ts
import { fromUnixTime, isBefore } from 'date-fns'; import { getAppFromPathnameSafe } from '@proton/shared/lib/apps/slugHelper'; import { APPS } from '@proton/shared/lib/constants'; import { isManagedExternally, isTrial } from '@proton/shared/lib/helpers/subscription'; import { ProtonConfig, Subscription, UserModel } from '@proton/shared/lib/interfaces'; import { FREE_DOWNGRADER_LIMIT } from '../../helpers/offerPeriods'; interface Props { subscription?: Subscription; protonConfig: ProtonConfig; user: UserModel; lastSubscriptionEnd?: number; } const isEligible = ({ subscription, protonConfig, user, lastSubscriptionEnd = 0 }: Props) => { const parentApp = getAppFromPathnameSafe(window.location.pathname); const hasValidApp = (protonConfig.APP_NAME === APPS.PROTONACCOUNT && parentApp === APPS.PROTONMAIL) || (protonConfig.APP_NAME === APPS.PROTONACCOUNT && parentApp === APPS.PROTONCALENDAR) || protonConfig.APP_NAME === APPS.PROTONCALENDAR || protonConfig.APP_NAME === APPS.PROTONMAIL; const { canPay, isDelinquent, isFree } = user; const notDelinquent = !isDelinquent; const isNotExternal = !isManagedExternally(subscription); const hasTrial = isTrial(subscription); return ( hasValidApp && isNotExternal && canPay && notDelinquent && (hasTrial || (isFree && isBefore(fromUnixTime(lastSubscriptionEnd), FREE_DOWNGRADER_LIMIT))) ); }; export default isEligible;
6,586
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayInbox2023Free/index.ts
export { default as blackFriday2023InboxFreeConfig } from './configuration'; export { default as useBlackFriday2023InboxFree } from './useOffer'; export { default as blackFriday2023InboxFreeEligibility } from './eligibility';
6,587
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayInbox2023Free/useOffer.ts
import { useConfig, useLastSubscriptionEnd, useSubscription, useUser } from '@proton/components/hooks'; import useOfferFlags from '../../hooks/useOfferFlags'; import { Operation } from '../../interface'; import config from './configuration'; import getIsEligible from './eligibility'; const useOffer = (): Operation => { const [user, userLoading] = useUser(); const [subscription, subscriptionLoading] = useSubscription(); const { isActive, loading: flagsLoading } = useOfferFlags(config); const [lastSubscriptionEnd, lastSubscriptionEndLoading] = useLastSubscriptionEnd(); const protonConfig = useConfig(); const isLoading = flagsLoading || userLoading || subscriptionLoading || lastSubscriptionEndLoading; const isEligible = getIsEligible({ subscription, protonConfig, user, lastSubscriptionEnd }); const isValid = isEligible && isActive; return { isValid, config, isLoading, isEligible }; }; export default useOffer;
6,588
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayInbox2023Plus/Layout.tsx
import BlackFridayFooter from '../../components/blackFriday/BlackFridayFooter'; import BlackFridayTitle from '../../components/blackFriday/BlackFridayTitle'; import OfferFooter from '../../components/shared/OfferFooter'; import OfferHeader from '../../components/shared/OfferHeader'; import OfferLayout from '../../components/shared/OfferLayout'; import OfferLoader from '../../components/shared/OfferLoader'; import Deals from '../../components/shared/deal/Deals'; import hasOffer from '../../helpers/hasOffer'; import { OfferLayoutProps } from '../../interface'; const Layout = (props: OfferLayoutProps) => { return hasOffer(props) ? ( <OfferLayout {...props}> <OfferHeader {...props}> <BlackFridayTitle /> </OfferHeader> <Deals {...props} /> <OfferFooter {...props}> <BlackFridayFooter {...props} /> </OfferFooter> </OfferLayout> ) : ( <OfferLoader /> ); }; export default Layout;
6,589
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayInbox2023Plus/configuration.ts
import { FeatureCode } from '@proton/components/containers/features'; import { COUPON_CODES, CYCLE, PLANS, PLAN_NAMES } from '@proton/shared/lib/constants'; import { getFamilyInboxFeatures, getUnlimitedInboxFeatures } from '../../helpers/offerCopies'; import { OfferConfig } from '../../interface'; import bannerImage from './BF-Mail-App-Modal-996x176.png'; import bannerImage2x from './BF-Mail-App-Modal-1992x352.png'; import Layout from './Layout'; const config: OfferConfig = { ID: 'black-friday-2023-inbox-mail', autoPopUp: 'one-time', featureCode: FeatureCode.OfferBlackFriday2023InboxMail, images: { bannerImage, bannerImage2x, }, canBeDisabled: true, darkBackground: true, deals: [ { ref: 'bf_23_mail_plus-modal-u12', dealName: PLAN_NAMES[PLANS.BUNDLE], planIDs: { [PLANS.BUNDLE]: 1, }, cycle: CYCLE.YEARLY, couponCode: COUPON_CODES.BLACK_FRIDAY_2023, features: getUnlimitedInboxFeatures, popular: 1, }, { ref: 'bf_23_mail_plus-modal-f12', dealName: PLAN_NAMES[PLANS.FAMILY], planIDs: { [PLANS.FAMILY]: 1, }, cycle: CYCLE.YEARLY, couponCode: COUPON_CODES.BLACK_FRIDAY_2023, features: getFamilyInboxFeatures, }, ], layout: Layout, }; export default config;
6,590
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayInbox2023Plus/eligibility.ts
import { getAppFromPathnameSafe } from '@proton/shared/lib/apps/slugHelper'; import { APPS, PLANS } from '@proton/shared/lib/constants'; import { getPlan, isManagedExternally, isTrial } from '@proton/shared/lib/helpers/subscription'; import { ProtonConfig, Subscription, UserModel } from '@proton/shared/lib/interfaces'; interface Props { subscription: Subscription; user: UserModel; protonConfig: ProtonConfig; } const isEligible = ({ subscription, user, protonConfig }: Props) => { const parentApp = getAppFromPathnameSafe(window.location.pathname); const plan = getPlan(subscription); const hasPlus = plan?.Name === PLANS.MAIL; const hasValidApp = (protonConfig.APP_NAME === APPS.PROTONACCOUNT && parentApp === APPS.PROTONMAIL) || (protonConfig.APP_NAME === APPS.PROTONACCOUNT && parentApp === APPS.PROTONCALENDAR) || protonConfig.APP_NAME === APPS.PROTONCALENDAR || protonConfig.APP_NAME === APPS.PROTONMAIL; const { canPay, isDelinquent } = user; const isNotExternal = !isManagedExternally(subscription); const notTrial = !isTrial(subscription); const isNotDelinquent = !isDelinquent; return hasValidApp && hasPlus && canPay && isNotExternal && notTrial && isNotDelinquent; }; export default isEligible;
6,591
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayInbox2023Plus/index.ts
export { default as blackFriday2023InboxMailConfig } from './configuration'; export { default as useBlackFriday2023InboxMail } from './useOffer'; export { default as blackFriday2023InboxMailEligibility } from './eligibility';
6,592
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayInbox2023Plus/useOffer.ts
import { useConfig, useSubscription, useUser } from '@proton/components/hooks'; import useOfferFlags from '../../hooks/useOfferFlags'; import { Operation } from '../../interface'; import config from './configuration'; import getIsEligible from './eligibility'; const useOffer = (): Operation => { const [user, userLoading] = useUser(); const [subscription, subscriptionLoading] = useSubscription(); const { isActive, loading: flagsLoading } = useOfferFlags(config); const protonConfig = useConfig(); const isLoading = flagsLoading || userLoading || subscriptionLoading; const isEligible = getIsEligible({ subscription, protonConfig, user }); const isValid = isEligible && isActive; return { isValid, config, isLoading, isEligible }; }; export default useOffer;
6,593
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayInbox2023Unlimited/Layout.tsx
import BlackFridayFooter from '../../components/blackFriday/BlackFridayFooter'; import BlackFridayTitle from '../../components/blackFriday/BlackFridayTitle'; import OfferFooter from '../../components/shared/OfferFooter'; import OfferHeader from '../../components/shared/OfferHeader'; import OfferLayout from '../../components/shared/OfferLayout'; import OfferLoader from '../../components/shared/OfferLoader'; import Deals from '../../components/shared/deal/Deals'; import hasOffer from '../../helpers/hasOffer'; import { OfferLayoutProps } from '../../interface'; const Layout = (props: OfferLayoutProps) => { return hasOffer(props) ? ( <OfferLayout {...props}> <OfferHeader {...props}> <BlackFridayTitle /> </OfferHeader> <Deals {...props} /> <OfferFooter {...props}> <BlackFridayFooter {...props} /> </OfferFooter> </OfferLayout> ) : ( <OfferLoader /> ); }; export default Layout;
6,594
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayInbox2023Unlimited/configuration.ts
import { FeatureCode } from '@proton/components/containers/features'; import { COUPON_CODES, CYCLE, PLANS, PLAN_NAMES } from '@proton/shared/lib/constants'; import { getFamilyInboxFeatures } from '../../helpers/offerCopies'; import { OfferConfig } from '../../interface'; import sideImage from './BF-Mail-App-Modal-400x1200.png'; import sideImage2x from './BF-Mail-App-Modal-800x2400.png'; import Layout from './Layout'; const config: OfferConfig = { ID: 'black-friday-2023-inbox-unlimited', autoPopUp: 'one-time', featureCode: FeatureCode.OfferBlackFriday2023InboxUnlimited, images: { sideImage, sideImage2x, }, canBeDisabled: true, deals: [ { ref: 'bf_23_mail_unlimited-modal-f12', dealName: PLAN_NAMES[PLANS.FAMILY], planIDs: { [PLANS.FAMILY]: 1, }, cycle: CYCLE.YEARLY, couponCode: COUPON_CODES.BLACK_FRIDAY_2023, features: getFamilyInboxFeatures, }, ], layout: Layout, }; export default config;
6,595
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayInbox2023Unlimited/eligibility.ts
import { getAppFromPathnameSafe } from '@proton/shared/lib/apps/slugHelper'; import { APPS, PLANS } from '@proton/shared/lib/constants'; import { getPlan, isManagedExternally } from '@proton/shared/lib/helpers/subscription'; import { ProtonConfig, Subscription, UserModel } from '@proton/shared/lib/interfaces'; interface Props { subscription: Subscription; protonConfig: ProtonConfig; user: UserModel; } const isEligible = ({ subscription, protonConfig, user }: Props) => { const parentApp = getAppFromPathnameSafe(window.location.pathname); const plan = getPlan(subscription); const hasUnlimited = plan?.Name === PLANS.BUNDLE; const hasValidApp = (protonConfig.APP_NAME === APPS.PROTONACCOUNT && parentApp === APPS.PROTONMAIL) || (protonConfig.APP_NAME === APPS.PROTONACCOUNT && parentApp === APPS.PROTONCALENDAR) || protonConfig.APP_NAME === APPS.PROTONCALENDAR || protonConfig.APP_NAME === APPS.PROTONMAIL; const { canPay, isDelinquent } = user; const isNotExternal = !isManagedExternally(subscription); const isNotDelinquent = !isDelinquent; return hasValidApp && hasUnlimited && canPay && isNotExternal && isNotDelinquent; }; export default isEligible;
6,596
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayInbox2023Unlimited/index.ts
export { default as blackFriday2023InboxUnlimitedConfig } from './configuration'; export { default as useBlackFriday2023InboxUnlimited } from './useOffer'; export { default as blackFriday2023InboxUnlimitedEligibility } from './eligibility';
6,597
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayInbox2023Unlimited/useOffer.ts
import { useConfig, useSubscription, useUser } from '@proton/components/hooks'; import useOfferFlags from '../../hooks/useOfferFlags'; import { Operation } from '../../interface'; import config from './configuration'; import getIsEligible from './eligibility'; const useOffer = (): Operation => { const [user, userLoading] = useUser(); const [subscription, subscriptionLoading] = useSubscription(); const { isActive, loading: flagsLoading } = useOfferFlags(config); const protonConfig = useConfig(); const isLoading = flagsLoading || userLoading || subscriptionLoading; const isEligible = getIsEligible({ subscription, protonConfig, user }); const isValid = isEligible && isActive; return { isValid, config, isLoading, isEligible }; }; export default useOffer;
6,598
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations
petrpan-code/ProtonMail/WebClients/packages/components/containers/offers/operations/blackFridayVPN2023Free/Layout.tsx
import BlackFridayFooter from '../../components/blackFriday/BlackFridayFooter'; import BlackFridayTitle from '../../components/blackFriday/BlackFridayTitle'; import OfferFooter from '../../components/shared/OfferFooter'; import OfferHeader from '../../components/shared/OfferHeader'; import OfferLayout from '../../components/shared/OfferLayout'; import OfferLoader from '../../components/shared/OfferLoader'; import Deals from '../../components/shared/deal/Deals'; import hasOffer from '../../helpers/hasOffer'; import { OfferLayoutProps } from '../../interface'; const Layout = (props: OfferLayoutProps) => { return hasOffer(props) ? ( <OfferLayout {...props}> <OfferHeader {...props}> <BlackFridayTitle /> </OfferHeader> <Deals {...props} /> <OfferFooter {...props}> <BlackFridayFooter {...props} /> </OfferFooter> </OfferLayout> ) : ( <OfferLoader /> ); }; export default Layout;
6,599