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/filePreview/Header.tsx
import { ReactNode, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { TimeIntl } from '../../'; import { FileIcon, FileNameDisplay, Icon } from '../../components'; const SHARED_STATUS_TO_COLOR = { '': undefined, shared: 'color-info', inactive: 'color-weak', }; export type SharedStatus = '' | 'shared' | 'inactive'; interface Props { name?: string; mimeType?: string; sharedStatus?: SharedStatus; signatureStatus?: ReactNode; isDirty?: boolean; onClose?: () => void; onDownload?: () => void; onSave?: () => Promise<void>; onDetails?: () => void; onShare?: () => void; onRestore?: () => void; // revision's specific date?: Date | string | number; children?: ReactNode; } const Header = ({ mimeType, name, sharedStatus, signatureStatus, isDirty, onClose, onDownload, onSave, onDetails, onShare, onRestore, date, children, }: Props) => { const [isSaving, withSaving] = useLoading(); const [saveError, setSaveError] = useState(); const handleSave = () => { if (!onSave) { return; } void withSaving( onSave() .then(() => { setSaveError(undefined); }) .catch((err) => { setSaveError(err?.message || err?.toString?.()); }) ); }; return ( <div className="flex flex-justify-space-between flex-align-items-center p-7 relative"> <div className="file-preview-filename flex flex-align-items-center flex-nowrap" data-testid="preview:file-name" > {mimeType && <FileIcon mimeType={mimeType} className="mr-2" />} <FileNameDisplay text={name} data-testid="file-preview:file-name" /> {signatureStatus} </div> {date && ( <TimeIntl className="flex-item-fluid text-ellipsis ml-5" data-testid="file-preview:date" options={{ year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: 'numeric', }} > {date} </TimeIntl> )} {children} <div className="flex flex-align-items-center mt-2 ml-auto sm:m-0"> {onRestore && ( <Button title={c('Action').t`Restore`} onClick={onRestore} shape="solid" className="mx-2 lg:mr-11" color="norm" data-testid="file-preview:actions:restore" > {c('Info').t`Restore`} </Button> )} {onDownload && ( <Button icon shape="ghost" title={c('Action').t`Download`} onClick={onDownload} className="ml-2" data-testid="file-preview:actions:download" > <Icon name="arrow-down-line" size={20} alt={c('Action').t`Download`} /> </Button> )} {onSave && ( <Button icon shape="ghost" title={ saveError ? c('Action').t`Try to save again. Saving failed due to: ${saveError}` : c('Action').t`Save` } onClick={handleSave} className="ml-2" data-testid="file-preview:actions:save" loading={isSaving} disabled={!isDirty} > <Icon name={saveError ? 'exclamation-circle-filled' : 'arrow-up-line'} size={20} alt={c('Action').t`Save`} /> </Button> )} {onDetails && ( <Button icon shape="ghost" title={c('Action').t`Details`} onClick={onDetails} className="ml-2 hidden md:inline-flex" data-testid="file-preview:actions:details" > <Icon name="info-circle" size={20} alt={c('Action').t`Details`} /> </Button> )} {onShare && ( <Button icon shape="ghost" title={sharedStatus === '' ? c('Action').t`Share via link` : c('Action').t`Sharing options`} onClick={onShare} className="ml-2 md:inline-flex" data-testid="file-preview:actions:share" > <Icon name="link" size={20} alt={sharedStatus === '' ? c('Action').t`Share via link` : c('Action').t`Sharing options`} className={SHARED_STATUS_TO_COLOR[sharedStatus || '']} /> </Button> )} {onClose && ( <Button icon shape="ghost" title={c('Action').t`Close`} onClick={onClose} className="ml-2" data-testid="preview:button:close" > <Icon name="cross" size={20} alt={c('Action').t`Close`} /> </Button> )} </div> </div> ); }; export default Header;
6,200
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/filePreview/ImagePreview.tsx
import { useEffect, useRef, useState } from 'react'; import DOMPurify from 'dompurify'; import { c } from 'ttag'; import { CircleLoader } from '@proton/atoms/CircleLoader'; import { useDragToScroll, useElementRect } from '@proton/components/hooks'; import { isFirefox } from '@proton/shared/lib/helpers/browser'; import { stringToUint8Array, uint8ArrayToString } from '@proton/shared/lib/helpers/encoding'; import { isSVG } from '@proton/shared/lib/helpers/mimetype'; import clsx from '@proton/utils/clsx'; import UnsupportedPreview from './UnsupportedPreview'; import ZoomControl from './ZoomControl'; interface Props { mimeType: string; fileName?: string; onDownload?: () => void; contents?: Uint8Array[]; placeholderSrc?: string; isLoading: boolean; isZoomEnabled?: boolean; } type ElementDimensions = { height: number; width: number; }; const FALLBACK_IMAGE_DIMENSION_VALUE = window.innerHeight / 2; // These are just arbitrary numbers to keep image reasonable size // on giant screens when we don't have information about image // dimensions const DEFAULT_IMAGE_DIMENSION_LIMIT_WIDTH = 2400; const DEFAULT_IMAGE_DIMENSION_LIMIT_HEIGHT = 1400; /* * Svg image dimension are 0 in Firefox. For these cases fallback values * will be used, so the image preview is visible. * https://bugzilla.mozilla.org/show_bug.cgi?id=1328124 */ function getImageDimensions(imageElement: HTMLImageElement | null): ElementDimensions { return { height: imageElement?.naturalHeight || FALLBACK_IMAGE_DIMENSION_VALUE, width: imageElement?.naturalWidth || FALLBACK_IMAGE_DIMENSION_VALUE, }; } /** * SVG can contain nasty scripts. We do have security headers set but attacker * can overcome it by asking user to open the previewed image in the new tab, * where browsers don't check headers and allow scripts from the SVG. * One option would be to render it as PNG, but zooming or rescaling the window * would mean to redraw. Better to keep SVG then. Sanitizing small SVGs takes * milliseconds, bigger ones (MBs) under second. Only super huge ones takes even * 10 seconds on slow computer as is mine, but we talk about huge SVGs as 30 MB. * Because such SVG is more edge case, we can live with that. */ function sanitizeSVG(contents: Uint8Array[]): Uint8Array[] { const contentsString = contents.map(uint8ArrayToString).join(''); const sanitzedSVG = DOMPurify.sanitize(contentsString); return [stringToUint8Array(sanitzedSVG)]; } function calcImageScaleToFitContainer(imageDimensions: ElementDimensions, containerDimensions: DOMRect) { const heightLimit = Math.min(containerDimensions.height, DEFAULT_IMAGE_DIMENSION_LIMIT_HEIGHT); const widthLimit = Math.min(containerDimensions.width, DEFAULT_IMAGE_DIMENSION_LIMIT_WIDTH); const heightRatio = heightLimit / imageDimensions.height; const widthRatio = widthLimit / imageDimensions.width; const scale = Math.min(heightRatio, widthRatio); return scale; } const scaleDimensions = (dimensions: ElementDimensions, scale: number) => { return { height: dimensions.height * scale, width: dimensions.width * scale, }; }; const ImagePreview = ({ isLoading = false, isZoomEnabled = true, mimeType, contents, onDownload, placeholderSrc, fileName, }: Props) => { const imageLowResRef = useRef<HTMLImageElement>(null); const imageHiResRef = useRef<HTMLImageElement>(null); const containerRef = useRef<HTMLDivElement>(null); const containerBounds = useElementRect(containerRef); const [imageData, setImageData] = useState({ src: '' }); const [error, setError] = useState(false); const [imageScale, setImageScale] = useState(0); const [isHiResImageRendered, setIsHiResImageRendered] = useState(false); const [isLowResImageHidden, setIsLowResImageHidden] = useState(false); const [imageStyles, setImageStyles] = useState({}); const [fullImageDimensions, setFullImageDimensions] = useState<{ width: number; height: number } | null>(null); const timeoutId = useRef<ReturnType<typeof setTimeout>>(); const handleZoomOut = () => setImageScale((zoom) => (zoom ? zoom * 0.9 : 1)); const handleZoomIn = () => setImageScale((zoom) => (zoom ? zoom * 1.1 : 1)); const { onMouseDown } = useDragToScroll(containerRef); useEffect(() => { if (!fullImageDimensions) { return; } setImageStyles(scaleDimensions(fullImageDimensions, imageScale)); }, [fullImageDimensions, imageScale]); const fitImageToContainer = (imageElement: HTMLImageElement | null) => { if (!containerBounds || !imageElement) { return; } // There is issue with svg since during zoom they change their size, so we used the original savedSize const dimensions = fullImageDimensions ? fullImageDimensions : getImageDimensions(imageElement); const scale = calcImageScaleToFitContainer(dimensions, containerBounds); if (scale) { setImageScale(scale); setImageStyles(scaleDimensions(dimensions, scale)); } }; const handleBrokenImage = () => { if (!error) { setError(true); } }; const handleFullImageLoaded = () => { if (isFirefox()) { // Setting the flag with arbitrary timeout value to hide thumbnail image with a delay. // Firefox tends to insert bigger images slowly, which lead to flickering. // Example: // 1. Data of full-size image loads // 2. We hide the thumbnail // 3. Before the full image is properly inserted into DOM, we see preview overlay background setTimeout(() => setIsHiResImageRendered(true), 200); } else { setIsHiResImageRendered(true); } fitImageToContainer(imageHiResRef.current); setFullImageDimensions(getImageDimensions(imageHiResRef.current)); }; useEffect(() => { if (error) { setError(false); } if (!contents) { setImageData({ src: '' }); return; } const data = isSVG(mimeType) ? sanitizeSVG(contents) : contents; const blob = new Blob(data, { type: mimeType }); const srcUrl = URL.createObjectURL(blob); setImageData({ src: srcUrl, }); // Load image before rendering const buffer = new Image(); buffer.src = srcUrl; return () => { if (srcUrl) { URL.revokeObjectURL(srcUrl); } }; }, [contents, mimeType]); useEffect(() => { return () => { clearTimeout(timeoutId.current); }; }, []); return ( <> <div ref={containerRef} className={'file-preview-container'} onMouseDown={onMouseDown}> {error ? ( <UnsupportedPreview onDownload={onDownload} type="image" /> ) : ( <div className="flex-no-min-children m-auto relative" style={{ ...imageStyles, overflow: !isLowResImageHidden && placeholderSrc ? 'hidden' : 'initial', }} > {!isLoading && ( <div className={clsx('file-preview-image file-preview-image-full-size')} style={{ ...imageStyles, background: 'repeating-conic-gradient(#606060 0% 25%, transparent 0% 50%)', backgroundSize: '40px 40px', transform: 'scale(0.99)', }} /> )} {!isLoading && ( <img ref={imageHiResRef} onLoad={handleFullImageLoaded} onError={handleBrokenImage} className={clsx(['file-preview-image file-preview-image-full-size'])} style={imageStyles} src={imageData.src} alt={c('Info').t`${fileName}: full-size image`} /> )} {!isLowResImageHidden && placeholderSrc && ( <img ref={imageLowResRef} onLoad={() => fitImageToContainer(imageLowResRef.current)} onError={handleBrokenImage} className={clsx([ 'file-preview-image', isHiResImageRendered && 'file-preview-image-out', ])} style={{ ...imageStyles, // Blurring an image this way leads to its edges to become transparent. // To compensate this, we apply scale transformation. filter: 'blur(3px)', transform: 'scale(1.03)', }} src={placeholderSrc} alt={c('Info').t`${fileName}: low-resolution preview`} onAnimationEnd={(e) => { if (e.animationName === 'anime-image-preview-out') { setIsLowResImageHidden(isHiResImageRendered); } }} /> )} </div> )} </div> {!isHiResImageRendered && !error && ( <div className="file-preview-loading w-full mb-8 flex flex-justify-center flex-align-items-center"> <CircleLoader /> <span className="ml-4">{c('Info').t`Loading...`}</span> </div> )} {isZoomEnabled && !error && ( <ZoomControl className={isHiResImageRendered ? '' : 'visibility-hidden'} onReset={() => fitImageToContainer(imageHiResRef.current)} scale={imageScale} onZoomIn={handleZoomIn} onZoomOut={handleZoomOut} /> )} </> ); }; export default ImagePreview;
6,201
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/filePreview/NavigationControl.tsx
import { RefObject } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import Icon from '../../components/icon/Icon'; import { useHotkeys } from '../../hooks'; interface Props { current: number; total: number; rootRef: RefObject<HTMLDivElement>; onNext: () => void; onPrev: () => void; } const NavigationControl = ({ current, total, rootRef, onNext, onPrev }: Props) => { const isPrevDisabled = current === 1; const isNextDisabled = current === total; useHotkeys(rootRef, [ [ 'ArrowLeft', (e) => { e.stopPropagation(); if (!isPrevDisabled) { onPrev(); } }, ], [ 'ArrowRight', (e) => { e.stopPropagation(); if (!isNextDisabled) { onNext(); } }, ], ]); return ( <div className="flex flex-align-items-center absolute-center"> <Button icon shape="ghost" className="on-rtl-mirror" disabled={isPrevDisabled} onClick={onPrev} title={c('Action').t`Previous`} data-testid="file-preview:navigation:prev" > <Icon name="chevron-left" size={16} alt={c('Action').t`Previous`} /> </Button> <span className="mx-2"> <span data-testid="preview:current-attachment">{current}</span> <span className="mx-1 color-weak text-sm">{c('Info').t`of`}</span> <span data-testid="preview:all-attachments">{total}</span> </span> <Button icon shape="ghost" className="on-rtl-mirror" disabled={isNextDisabled} onClick={onNext} title={c('Action').t`Next`} data-testid="file-preview:navigation:next" > <Icon name="chevron-right" size={16} alt={c('Action').t`Next`} /> </Button> </div> ); }; export default NavigationControl;
6,202
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/filePreview/PDFPreview.tsx
import { useEffect, useState } from 'react'; import { c } from 'ttag'; interface Props { filename?: string; contents?: Uint8Array[]; } const PDFPreview = ({ filename = 'preview.pdf', contents }: Props) => { const [url, setUrl] = useState<string>(); useEffect(() => { const newUrl = URL.createObjectURL(new Blob(contents, { type: 'application/pdf' })); setUrl(newUrl); return () => { if (newUrl) { URL.revokeObjectURL(newUrl); } }; }, [contents]); return ( <> {url && ( <object data={url} className="w-full flex-no-min-children flex-item-fluid-auto flex-column-reverse" type="application/pdf" title={filename} > <embed src={url} className="flex" type="application/pdf" /> <p className="m-auto">{c('Info') .t`This browser does not support previewing PDF documents. Please download the file.`}</p> </object> )} </> ); }; export default PDFPreview;
6,203
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/filePreview/PreviewError.tsx
import { c } from 'ttag'; import corruptedPreviewSvg from '@proton/styles/assets/img/errors/broken-image.svg'; import clsx from '@proton/utils/clsx'; import { useActiveBreakpoint } from '../../hooks'; type Props = { error: string; }; export default function PreviewError({ error }: Props) { const { isNarrow } = useActiveBreakpoint(); return ( <div className="absolute-center text-center w-full px-4"> <img className="mb-4 w-custom" style={{ '--w-custom': '5rem' }} src={corruptedPreviewSvg} alt={c('Info').t`Preview failed to be loaded`} /> <h2 className={clsx(['p-1 text-bold', isNarrow && 'h3'])}>{c('Info').t`Preview failed to be loaded`}</h2> <p className="color-weak">{error}</p> </div> ); }
6,204
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/filePreview/PreviewLoader.tsx
import { c } from 'ttag'; import { CircleLoader } from '@proton/atoms'; import { TextLoader } from '../../components'; const PreviewLoader = () => { return ( <div className="file-preview-container"> <div className="absolute-center text-center w-full"> <CircleLoader size="large" /> <TextLoader>{c('Info').t`Loading preview`}</TextLoader> </div> </div> ); }; export default PreviewLoader;
6,205
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/filePreview/SandboxedPreview.tsx
import { FC, useEffect, useRef, useState } from 'react'; import { c } from 'ttag'; import { traceError } from '@proton/shared/lib/helpers/sentry'; import mergeUint8Arrays from '@proton/utils/mergeUint8Arrays'; import UnsupportedPreview from './UnsupportedPreview'; interface Props { mimeType: string; contents?: Uint8Array[]; onDownload?: () => void; } export const SandboxedPreview: FC<Props> = ({ contents, mimeType, onDownload }) => { const [isError, setError] = useState(false); const ref = useRef<HTMLIFrameElement>(null); // Word document can have custom styles that can include external link. // We want to block those external request for security reasons. const csp = `style-src 'self' 'unsafe-inline'; img-src 'self' blob: data:; font-src 'self' blob: data:; default-src 'self'; script-src 'self' ${origin}`; useEffect(() => { const sandbox = ref.current; if (isError || !sandbox || !contents) { return; } const handleError = (e: any) => { traceError(e); setError(true); }; const onSandboxMessage = (event: MessageEvent) => { const contentWindow = sandbox.contentWindow; const { origin, data, source } = event; if (!contentWindow || origin !== 'null' || !data || source !== contentWindow) { return; } if (data.type === 'error') { handleError(data.error); } }; window.addEventListener('message', onSandboxMessage); const onSandboxLoad = () => { // Only '*' seems to work here sandbox.contentWindow?.postMessage({ type: 'data', mimeType, data: mergeUint8Arrays(contents) }, '*'); }; sandbox.addEventListener('load', onSandboxLoad); const origin = window.location.origin; const setSandboxUrl = async () => { const html = `<!doctype html><html> <head> <meta http-equiv="Content-Security-Policy" content="${csp}"> <style>html, body { border: 0; margin: 0; padding: 0; width: 100%; height: 100%; }</style> <script type='text/javascript' src='${origin}/assets/sandbox.js'></script> </head> <body></body> </html>`; const url = URL.createObjectURL(new Blob([html], { type: 'text/html' })); sandbox.setAttribute('src', url); }; setSandboxUrl().catch(handleError); return () => { window.removeEventListener('message', onSandboxMessage); }; }, [contents]); if (isError) { return ( <div className="flex flex-item-fluid-auto relative"> <UnsupportedPreview onDownload={onDownload} type="file" /> </div> ); } return ( <iframe title={c('Title').t`Preview`} src="about:blank" ref={ref} className="file-preview-container w-full h-full" sandbox="allow-scripts" // Attribute is still experimental: https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/csp // @ts-ignore csp={csp} /> ); }; export default SandboxedPreview;
6,206
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/filePreview/SignatureIssue.tsx
import { ReactNode } from 'react'; import { c } from 'ttag'; import { Icon, PrimaryButton } from '../../components'; import { useActiveBreakpoint } from '../../hooks'; const SignatureIssue = ({ signatureConfirmation, onClick, }: { signatureConfirmation: ReactNode; onClick: () => void; }) => { const { isNarrow } = useActiveBreakpoint(); return ( <div className="file-preview-container"> <div className="absolute-center w-full"> <div className="mx-auto w-custom" style={{ '--w-custom': isNarrow ? '18.75rem' : '31.25rem' }}> <div className="text-center"> <Icon name="lock-exclamation-filled" size={60} className="color-danger" /> </div> <div className="mt-4 mb-8">{signatureConfirmation}</div> </div> <div className="text-center"> <PrimaryButton size={!isNarrow ? 'large' : undefined} className="text-bold" onClick={onClick}> {c('Action').t`Show preview`} </PrimaryButton> </div> </div> </div> ); }; export default SignatureIssue;
6,207
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/filePreview/TextPreview.tsx
import { useState } from 'react'; import mergeUint8Arrays from '@proton/utils/mergeUint8Arrays'; interface Props { contents?: Uint8Array[]; onNewContents?: (content: Uint8Array[]) => void; } const TextPreview = ({ contents = [], onNewContents }: Props) => { const string = new TextDecoder().decode(mergeUint8Arrays(contents)); const [value, setValue] = useState(string); const handleChange = (event: any) => { const newValue = event.target.value as string; setValue(newValue); const content = Uint8Array.from(newValue.split('').map((x) => x.charCodeAt(0))); onNewContents?.([content]); }; return ( <div className="file-preview-container"> {onNewContents ? ( <textarea className="file-preview-text" value={value} onChange={handleChange} /> ) : ( <div className="file-preview-text">{value}</div> )} </div> ); }; export default TextPreview;
6,208
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/filePreview/UnsupportedPreview.tsx
import { c } from 'ttag'; import corruptedPreviewSvg from '@proton/styles/assets/img/errors/broken-image.svg'; import unsupportedPreviewSvg from '@proton/styles/assets/img/errors/preview-unavailable.svg'; import clsx from '@proton/utils/clsx'; import { PrimaryButton } from '../../components'; import { useActiveBreakpoint } from '../../hooks'; interface Props { type?: 'file' | 'image' | 'video' | 'audio'; onDownload?: () => void; browser?: boolean; tooLarge?: boolean; } const UnsupportedPreview = ({ onDownload, type = 'file', browser = false, tooLarge = false }: Props) => { const { isNarrow } = useActiveBreakpoint(); let message = c('Info').t`Preview for this file type is not supported`; if (browser) { message = c('Info').t`Preview for this file type is currently not supported on this browser.`; } else if (tooLarge) { message = c('Info').t`This file is too large to preview`; } return ( <div className="absolute-center text-center w-full px-4"> <img className="mb-4 w-custom" style={{ '--w-custom': '5rem' }} src={type === 'file' ? unsupportedPreviewSvg : corruptedPreviewSvg} alt={c('Info').t`Unsupported file`} data-testid="file-preview:unsupported-preview-image" /> <h2 className={clsx(['p-1 text-bold', isNarrow && 'h3'])} data-testid="file-preview:unsupported-preview-text" > {message} </h2> {browser && <h3 className="pb-1">{c('Info').t`Please use another browser or download the file.`}</h3>} {onDownload && ( <PrimaryButton size={!isNarrow ? 'large' : undefined} className="text-bold mt-8" onClick={onDownload} >{c('Action').t`Download`}</PrimaryButton> )} </div> ); }; export default UnsupportedPreview;
6,209
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/filePreview/VideoPreview.tsx
import { useEffect, useRef, useState } from 'react'; import useElementRect from '../../hooks/useElementRect'; import UnsupportedPreview from './UnsupportedPreview'; interface Props { mimeType: string; contents?: Uint8Array[]; onDownload?: () => void; } const VideoPreview = ({ contents, mimeType, onDownload }: Props) => { const videoRef = useRef<HTMLVideoElement>(null); const containerRef = useRef<HTMLDivElement>(null); const containerBounds = useElementRect(containerRef); const [url, setUrl] = useState<string>(); const [scale, setScale] = useState(1); const [error, setError] = useState(false); useEffect(() => { const newUrl = URL.createObjectURL(new Blob(contents, { type: mimeType })); setUrl(newUrl); return () => { if (newUrl) { URL.revokeObjectURL(newUrl); } }; }, [contents]); const fitToContainer = () => { if (!videoRef.current || !containerBounds) { return; } const heightRatio = containerBounds.height / videoRef.current.videoHeight; const widthRatio = containerBounds.width / videoRef.current.videoWidth; const scale = Math.min(1, heightRatio, widthRatio); setScale(scale); }; const handleBrokenVideo = () => { setError(true); }; const scaledDimensions = !videoRef.current?.videoHeight ? {} : { height: videoRef.current.videoHeight * scale, width: videoRef.current.videoWidth * scale, }; if (error) { return ( <div className="flex flex-item-fluid-auto relative"> <UnsupportedPreview onDownload={onDownload} type="video" /> </div> ); } return ( <div ref={containerRef} className="flex w-full h-full"> <div className="m-auto"> {/* eslint-disable-next-line */} <video ref={videoRef} onLoadedMetadata={fitToContainer} onError={handleBrokenVideo} src={url} style={scaledDimensions} controls /> </div> </div> ); }; export default VideoPreview;
6,210
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/filePreview/ZoomControl.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import clsx from '@proton/utils/clsx'; import Icon from '../../components/icon/Icon'; interface Props { className?: string; scale: number; onZoomIn: () => void; onZoomOut: () => void; onReset: () => void; } const ZoomControl = ({ className, scale, onZoomIn, onZoomOut, onReset }: Props) => { const isZoomOutDisabled = scale <= 0.005; const isZoomInDisabled = scale >= 10; const displayedZoomValueInPercent = `${Math.round(scale * 100)}%`; return ( <div className={clsx(['w-full p-7 flex', className])}> <div className="mx-auto flex flex-align-items-center"> <Button icon shape="ghost" disabled={isZoomOutDisabled} onClick={onZoomOut} title={c('Action').t`Zoom out`} > <Icon name="minus" size={12} alt={c('Action').t`Zoom out`} /> </Button> <Button shape="ghost" title={c('Action').t`Fit to window`} className="mx-2" onClick={onReset}> <span>{displayedZoomValueInPercent}</span> </Button> <Button icon shape="ghost" disabled={isZoomInDisabled} onClick={onZoomIn} title={c('Action').t`Zoom in`} > <Icon name="plus" size={12} alt={c('Action').t`Zoom in`} /> </Button> </div> </div> ); }; export default ZoomControl;
6,211
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/filePreview/index.ts
export { default as FilePreview } from './FilePreview'; export { default as NavigationControl } from './NavigationControl'; export { default as PDFPreview } from './PDFPreview'; export { default as ImagePreview } from './ImagePreview'; export { default as TextPreview } from './TextPreview'; export { default as ZoomControl } from './ZoomControl';
6,212
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/ActionsFilterToolbar.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Filter } from '@proton/components/containers/filters/interfaces'; import { useFilters } from '@proton/components/hooks'; import { hasReachedFiltersLimit } from '@proton/shared/lib/helpers/filters'; import { FiltersUpsellModal, MailUpsellButton, useModalState } from '../../components'; import useUser from '../../hooks/useUser'; import FilterModal from './modal/FilterModal'; import AdvancedFilterModal from './modal/advanced/AdvancedFilterModal'; function ActionsFilterToolbar() { const [user] = useUser(); const [filterModalProps, setFilterModalOpen] = useModalState(); const [advancedFilterModalProps, setAdvancedFilterModalOpen] = useModalState(); const [filters = []] = useFilters() as [Filter[], boolean, Error]; const canCreateFilters = !hasReachedFiltersLimit(user, filters); const [upsellModalProps, handleUpsellModalDisplay, renderUpsellModal] = useModalState(); return ( <> <div className="mb-4"> {canCreateFilters ? ( <> <Button color="norm" onClick={() => setFilterModalOpen(true)} className="mb-2 md:mb-0 mr-4"> {c('Action').t`Add filter`} </Button> <Button shape="outline" onClick={() => setAdvancedFilterModalOpen(true)} className="mb-2 md:mb-0" > {c('Action').t`Add sieve filter`} </Button> </> ) : ( <MailUpsellButton onClick={() => handleUpsellModalDisplay(true)} text={c('Action').t`Get more filters`} /> )} </div> <FilterModal {...filterModalProps} /> <AdvancedFilterModal {...advancedFilterModalProps} /> {renderUpsellModal && <FiltersUpsellModal modalProps={upsellModalProps} isSettings />} </> ); } export default ActionsFilterToolbar;
6,213
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/FilterItemRow.tsx
import React, { ChangeEvent, useState } from 'react'; import { c } from 'ttag'; import { useLoading } from '@proton/hooks'; import { deleteFilter, toggleEnable } from '@proton/shared/lib/api/filters'; import { FILTER_STATUS } from '@proton/shared/lib/constants'; import { hasReachedFiltersLimit } from '@proton/shared/lib/helpers/filters'; import { DropdownActions, FiltersUpsellModal, OrderableTableRow, Toggle, useModalState } from '../../components'; import { DropdownActionProps } from '../../components/dropdown/DropdownActions'; import { useApi, useEventManager, useNotifications, useUser } from '../../hooks'; import FilterWarningModal from './FilterWarningModal'; import { Filter } from './interfaces'; import DeleteFilterModal from './modal/DeleteFilterModal'; import FilterModal from './modal/FilterModal'; import AdvancedFilterModal from './modal/advanced/AdvancedFilterModal'; import { isSieve } from './utils'; interface Props { filter: Filter; filters: Filter[]; index: number; onApplyFilter: (filterID: string) => void; } function FilterItemRow({ filter, filters, index, onApplyFilter, ...rest }: Props) { const api = useApi(); const [user] = useUser(); const [loading, withLoading] = useLoading(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const [applyFilterModalOpen, setApplyFilterModalOpen] = useState(false); const [filterModalProps, setFilterModalOpen, renderFilterModal] = useModalState(); const [advancedFilterModalProps, setAdvancedFilterModalOpen, renderAdvancedFilterModal] = useModalState(); const [deleteFilterModalProps, setDeleteFilterModalOpen, renderDeleteFilterModal] = useModalState(); const { ID, Name, Status } = filter; const [upsellModalProps, handleUpsellModalDisplay, renderUpsellModal] = useModalState(); const handleChangeStatus = async ({ target }: ChangeEvent<HTMLInputElement>) => { await api(toggleEnable(ID, target.checked)); await call(); createNotification({ text: c('Success notification').t`Status updated`, }); }; const handleRemove = async () => { await api(deleteFilter(filter.ID)); await call(); createNotification({ text: c('Success notification').t`Filter removed` }); }; const handleEdit = (type?: 'sieve') => () => { if (type === 'sieve') { setAdvancedFilterModalOpen(true); } else { setFilterModalOpen(true); } }; const editAction: DropdownActionProps = { text: c('Action').t`Edit`, onClick: handleEdit(), }; const editSieveAction: DropdownActionProps = { text: c('Action').t`Edit sieve`, onClick: handleEdit('sieve'), }; const applyFilterAction: DropdownActionProps = { text: c('Action').t`Apply to existing messages`, onClick: () => setApplyFilterModalOpen(true), }; const deleteFilterAction: DropdownActionProps = { text: c('Action').t`Delete`, actionType: 'delete', onClick: () => setDeleteFilterModalOpen(true), }; const list: DropdownActionProps[] = isSieve(filter) ? [editSieveAction, applyFilterAction, deleteFilterAction] : [editAction, applyFilterAction, editSieveAction, deleteFilterAction]; const handleChange = (e: ChangeEvent<HTMLInputElement>) => { if (Status === FILTER_STATUS.DISABLED && hasReachedFiltersLimit(user, filters)) { handleUpsellModalDisplay(true); } else { withLoading(handleChangeStatus(e)); } }; return ( <> <OrderableTableRow index={index} cells={[ <div key="name" className="text-ellipsis max-w-full" title={Name}> {Name} </div>, <div key="toggle" className="w-1/10 flex"> <Toggle id={`item-${ID}`} loading={loading} checked={Status === FILTER_STATUS.ENABLED} onChange={handleChange} /> </div>, <DropdownActions key="dropdown" size="small" list={list} />, ]} {...rest} className="on-mobile-hide-td3" /> {renderFilterModal && <FilterModal {...filterModalProps} filter={filter} />} {renderAdvancedFilterModal && <AdvancedFilterModal {...advancedFilterModalProps} filter={filter} />} {renderDeleteFilterModal && ( <DeleteFilterModal {...deleteFilterModalProps} filterName={filter.Name} handleDelete={handleRemove} /> )} <FilterWarningModal open={applyFilterModalOpen} onClose={() => { setApplyFilterModalOpen(false); }} onConfirm={() => { setApplyFilterModalOpen(false); onApplyFilter(filter.ID); }} /> {renderUpsellModal && <FiltersUpsellModal modalProps={upsellModalProps} isSettings />} </> ); } export default FilterItemRow;
6,214
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/FilterSortableList.tsx
import { ContainerGetter, SortEndHandler } from 'react-sortable-hoc'; import { c } from 'ttag'; import { OrderableTable, OrderableTableBody, OrderableTableHeader } from '../../components'; import FilterItemRow from './FilterItemRow'; import { Filter } from './interfaces'; interface Props { items: Filter[]; getContainer: ContainerGetter; onSortEnd: SortEndHandler; onApplyFilter: (filterID: string) => void; } const FilterSortableList = ({ items, onApplyFilter, ...rest }: Props) => ( <OrderableTable className="border-none border-collapse mt-4 simple-table--has-actions" {...rest}> <caption className="sr-only">{c('Settings/filters').t`Filters`}</caption> <OrderableTableHeader> <tr> <th scope="col" className="w-custom" style={{ '--w-custom': '5%' }}> <span className="sr-only">{c('Settings/filters - table').t`Order`}</span> </th> <th scope="col">{c('Settings/filters - table').t`Name`}</th> <th scope="col" className="w-custom hidden md:table-cell" style={{ '--w-custom': '8em' }}> {c('Settings/filters - table').t`Status`} </th> <th scope="col" className="w-custom" style={{ '--w-custom': '10em' }}> {c('Settings/filters - table').t`Action`} </th> </tr> </OrderableTableHeader> <OrderableTableBody colSpan={0}> {items.map((filter, index) => ( <FilterItemRow key={`item-${index}`} index={index} filter={filter} filters={items} onApplyFilter={onApplyFilter} /> ))} </OrderableTableBody> </OrderableTable> ); export default FilterSortableList;
6,215
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/FilterWarningModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { MAIL_APP_NAME } from '@proton/shared/lib/constants'; import { Prompt } from '../../components/prompt'; interface Props { open: boolean; onClose: () => void; onConfirm: () => void; } const FilterWarningModal = ({ open, onClose, onConfirm }: Props) => ( <Prompt open={open} onClose={onClose} title={c('Title').t`Apply filter to existing messages`} buttons={[ <Button color="norm" onClick={() => { onConfirm(); }} >{c('Action').t`Confirm`}</Button>, <Button onClick={onClose}>{c('Action').t`Cancel`}</Button>, ]} > <p className="mt-0"> {c('Message') .t`All filter actions will be applied to all messages in your ${MAIL_APP_NAME} account. No auto-reply emails will be sent.`} </p> </Prompt> ); export default FilterWarningModal;
6,216
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/FiltersSection.tsx
import React, { useEffect, useState } from 'react'; import { ContainerGetter, SortEndHandler, arrayMove } from 'react-sortable-hoc'; import { c } from 'ttag'; import { Href } from '@proton/atoms/Href'; import { applyFilters, updateFilterOrder } from '@proton/shared/lib/api/filters'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { Loader } from '../../components'; import { useApi, useApiWithoutResult, useEventManager, useFilters, useNotifications } from '../../hooks'; import { SettingsParagraph, SettingsSection } from '../account'; import ActionsFilterToolbar from './ActionsFilterToolbar'; import FilterSortableList from './FilterSortableList'; import { Filter } from './interfaces'; function FiltersSection() { const { call } = useEventManager(); const [filters, loading] = useFilters(); const orderRequest = useApiWithoutResult(updateFilterOrder); const { createNotification } = useNotifications(); const api = useApi(); const handleApplyFilter = async (filterId: string) => { // Handle Filter API call await api(applyFilters([filterId])); createNotification({ text: c('Action').t`Filters are being applied. This might take a few minutes.`, type: 'success', }); }; const [list, setFilters] = useState<Filter[]>(() => filters || []); useEffect(() => { if (!Array.isArray(filters)) { return; } setFilters(filters); }, [filters]); const getScrollContainer: ContainerGetter = () => document.querySelector('.main-area') as HTMLElement; const onSortEnd: SortEndHandler = async ({ oldIndex, newIndex }) => { try { const nextFilters: Filter[] = arrayMove(list, oldIndex, newIndex); setFilters(nextFilters); const filterIds = nextFilters.map(({ ID }) => ID); await orderRequest.request(filterIds); await call(); } catch (e: any) { setFilters(filters); } }; const contentRenderer = () => { if (loading) { return <Loader />; } return list.length ? ( <FilterSortableList getContainer={getScrollContainer} items={list} onSortEnd={onSortEnd} onApplyFilter={handleApplyFilter} /> ) : null; }; return ( <SettingsSection> <SettingsParagraph> <span> {c('FilterSettings') .t`Add a custom filter to automatically perform certain actions, like labeling or archiving messages.`} </span> <br /> <Href href={getKnowledgeBaseUrl('/email-inbox-filters')}>{c('Link').t`Learn more`}</Href> </SettingsParagraph> <ActionsFilterToolbar /> {contentRenderer()} </SettingsSection> ); } export default FiltersSection;
6,217
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/SpamFiltersSection.tsx
import { c } from 'ttag'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { SettingsParagraph, SettingsSectionWide } from '../account'; import Spams from './spams/Spams'; const SpamFiltersSection = () => ( <SettingsSectionWide> <SettingsParagraph learnMoreUrl={getKnowledgeBaseUrl('/spam-filtering')}> {c('FilterSettings').t`Take control over what lands in your inbox by creating the following lists:`} <ul className="mt-2 mb-0"> <li> <strong>{c('FilterSettings').t`Spam:`}</strong>{' '} {c('FilterSettings').t`To prevent junk mail from clogging up your inbox`} </li> <li> <strong>{c('FilterSettings').t`Block:`}</strong>{' '} {c('FilterSettings').t`To stop phishing or suspicious emails from entering your email system`} </li> <li> <strong>{c('FilterSettings').t`Allow:`}</strong>{' '} {c('FilterSettings').t`To ensure critical messages don't end up in spam and getting missed`} </li> </ul> </SettingsParagraph> <Spams /> </SettingsSectionWide> ); export default SpamFiltersSection;
6,218
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/constants.ts
import { c } from 'ttag'; import { ConditionComparator, ConditionType, FilterStatement } from './interfaces'; import { SelectOption } from './modal/FilterActionsFormFolderRow'; export const FILTER_VERSION = 2; export const getConditionTypeLabels = (type: ConditionType) => { switch (type) { case ConditionType.SELECT: return c('Filter modal type').t`Select…`; case ConditionType.SUBJECT: return c('Filter modal type').t`The subject`; case ConditionType.SENDER: return c('Filter modal type').t`The sender`; case ConditionType.RECIPIENT: return c('Filter modal type').t`The recipient`; case ConditionType.ATTACHMENTS: return c('Filter modal type').t`The attachment`; default: return ''; } }; export const getComparatorLabels = (comparator: ConditionComparator) => { switch (comparator) { case ConditionComparator.CONTAINS: return c('Condition for custom filter').t`contains`; case ConditionComparator.IS: return c('Condition for custom filter').t`is exactly`; case ConditionComparator.STARTS: return c('Condition for custom filter').t`begins with`; case ConditionComparator.ENDS: return c('Condition for custom filter').t`ends with`; case ConditionComparator.MATCHES: return c('Condition for custom filter').t`matches`; case ConditionComparator.DOES_NOT_CONTAIN: return c('Condition for custom filter').t`does not contain`; case ConditionComparator.IS_NOT: return c('Condition for custom filter').t`is not`; case ConditionComparator.DOES_NOT_START: return c('Condition for custom filter').t`does not begin with`; case ConditionComparator.DOES_NOT_END: return c('Condition for custom filter').t`does not end with`; case ConditionComparator.DOES_NOT_MATCH: return c('Condition for custom filter').t`does not match`; default: return ''; } }; export const getOperatorLabels = (statement: FilterStatement) => { switch (statement) { case FilterStatement.ALL: return c('Filter modal operators').t`All conditions must be fulfilled (AND)`; case FilterStatement.ANY: return c('Filter modal operators').t`One condition must be fulfilled (OR)`; default: return ''; } }; export const TYPES = [ { label: getConditionTypeLabels(ConditionType.SELECT), value: ConditionType.SELECT, }, { label: getConditionTypeLabels(ConditionType.SUBJECT), value: ConditionType.SUBJECT, }, { label: getConditionTypeLabels(ConditionType.SENDER), value: ConditionType.SENDER, }, { label: getConditionTypeLabels(ConditionType.RECIPIENT), value: ConditionType.RECIPIENT, }, { label: getConditionTypeLabels(ConditionType.ATTACHMENTS), value: ConditionType.ATTACHMENTS, }, ]; export const COMPARATORS = [ { label: getComparatorLabels(ConditionComparator.CONTAINS), value: ConditionComparator.CONTAINS, }, { label: getComparatorLabels(ConditionComparator.IS), value: ConditionComparator.IS, }, { label: getComparatorLabels(ConditionComparator.STARTS), value: ConditionComparator.STARTS, }, { label: getComparatorLabels(ConditionComparator.ENDS), value: ConditionComparator.ENDS, }, { label: getComparatorLabels(ConditionComparator.MATCHES), value: ConditionComparator.MATCHES, }, { label: getComparatorLabels(ConditionComparator.DOES_NOT_CONTAIN), value: ConditionComparator.DOES_NOT_CONTAIN, }, { label: getComparatorLabels(ConditionComparator.IS_NOT), value: ConditionComparator.IS_NOT, }, { label: getComparatorLabels(ConditionComparator.DOES_NOT_START), value: ConditionComparator.DOES_NOT_START, }, { label: getComparatorLabels(ConditionComparator.DOES_NOT_END), value: ConditionComparator.DOES_NOT_END, }, { label: getComparatorLabels(ConditionComparator.DOES_NOT_MATCH), value: ConditionComparator.DOES_NOT_MATCH, }, ]; export const OPERATORS = [ { label: getOperatorLabels(FilterStatement.ALL), value: FilterStatement.ALL, }, { label: getOperatorLabels(FilterStatement.ANY), value: FilterStatement.ANY, }, ]; export const noFolderValue = ''; export const noFolderOption = { type: 'option', text: c('Filter Actions').t`Do not move`, value: noFolderValue, } as SelectOption; export const getDefaultFolders = () => { return [ { group: c('Option group').t`Move to...`, text: c('Filter Actions').t`Select a folder`, value: '', disabled: true, }, { group: c('Option group').t`Default folders`, text: c('Filter Actions').t`Archive`, value: 'archive', }, { group: c('Option group').t`Default folders`, text: c('Filter Actions').t`Inbox`, value: 'inbox', }, { group: c('Option group').t`Default folders`, text: c('Filter Actions').t`Spam`, value: 'spam', }, { group: c('Option group').t`Default folders`, text: c('Filter Actions').t`Trash`, value: 'trash', }, ]; }; export const getDefaultFolderOptions = () => { return [ { type: 'label', text: c('Option group').t`Default folders`, }, { type: 'option', text: c('Filter Actions').t`Archive`, value: 'archive', }, { type: 'option', text: c('Filter Actions').t`Inbox - Default`, value: 'inbox', }, { type: 'option', text: c('Filter Actions').t`Spam`, value: 'spam', }, { type: 'option', text: c('Filter Actions').t`Trash`, value: 'trash', }, ] as SelectOption[]; };
6,219
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/index.ts
export { default as SpamFiltersSection } from './SpamFiltersSection'; export { default as FiltersSection } from './FiltersSection'; export { default as AddFilterModal } from './modal/FilterModal'; export { default as FilterConditionsFormRow } from './modal/FilterConditionsFormRow'; export * as FilterUtils from './utils'; export * as FilterConstants from './constants';
6,220
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/interfaces.ts
import { Annotation } from 'codemirror/addon/lint/lint'; export enum FilterStatement { ALL = 'all', ANY = 'any', } export enum ConditionType { SELECT = 'select', SUBJECT = 'subject', SENDER = 'sender', RECIPIENT = 'recipient', ATTACHMENTS = 'attachments', } export enum ConditionComparator { CONTAINS = 'contains', IS = 'is', STARTS = 'starts', ENDS = 'ends', MATCHES = 'matches', IS_NOT = '!is', DOES_NOT_CONTAIN = '!contains', DOES_NOT_START = '!starts', DOES_NOT_END = '!ends', DOES_NOT_MATCH = '!matches', } export const ConditionComparatorMap = new Map<ConditionComparator, ConditionComparator>([ [ConditionComparator.CONTAINS, ConditionComparator.DOES_NOT_CONTAIN], [ConditionComparator.ENDS, ConditionComparator.DOES_NOT_END], [ConditionComparator.MATCHES, ConditionComparator.DOES_NOT_MATCH], [ConditionComparator.STARTS, ConditionComparator.DOES_NOT_START], [ConditionComparator.IS, ConditionComparator.IS_NOT], ]); //Map the opposite to it's positive comparator export const ConditionComparatorInvertedMap = new Map<ConditionComparator, ConditionComparator>(); ConditionComparatorMap.forEach((value, key) => ConditionComparatorInvertedMap.set(value, key)); /* Simple Modal Filter Model interfaces */ export enum Step { NAME, CONDITIONS, ACTIONS, PREVIEW, } export interface Errors { name: string; actions: string; conditions: string; } export interface Actions { labelAs: { labels: string[]; isOpen: boolean; }; moveTo: { folder?: string; isOpen: boolean; }; markAs: { read: boolean; starred: boolean; isOpen: boolean; }; autoReply: string | null; error?: string; } export interface Condition { type: ConditionType; comparator: ConditionComparator; values?: string[]; error?: string; isOpen: boolean; id: string; defaultValue?: string; } export interface FilterModalModelBase { id?: string; status?: number; version?: 1 | 2; name: string; } export interface SimpleFilterModalModel extends FilterModalModelBase { step: Step; statement: FilterStatement; actions: Actions; conditions: Condition[]; apply: boolean; } export interface ErrorsSieve { name: string; sieve: string; } export interface AdvancedSimpleFilterModalModel extends FilterModalModelBase { sieve: string; issues: Annotation[]; } /* Expected API Format */ export interface FilterOperator { label: string; value: FilterStatement; } export interface FilterRedirect { Address: string; Copy?: boolean; } export interface FilterActions { FileInto: string[]; Mark: { Read: boolean; Starred: boolean; }; Vacation?: string | null; Redirects?: FilterRedirect[]; } export interface FilterCondition { Comparator: { value: ConditionComparator; label: string; }; Type: { value: ConditionType; label: string; }; Values: string[]; } export interface SimpleObject { Operator: FilterOperator; Conditions: FilterCondition[]; Actions: FilterActions; } export interface Filter { ID: string; Name: string; Status: number; Priority?: number; Version: 1 | 2; Simple?: SimpleObject; Sieve?: string; Tree?: any; }
6,221
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/utils.ts
import isDeepEqual from '@proton/shared/lib/helpers/isDeepEqual'; import { toMap } from '@proton/shared/lib/helpers/object'; import { fromSieveTree, toSieveTree } from '@proton/sieve'; import { COMPARATORS, FILTER_VERSION, OPERATORS, TYPES, getDefaultFolders } from './constants'; import { Filter, FilterActions, FilterCondition, FilterModalModelBase, FilterOperator, SimpleFilterModalModel, } from './interfaces'; export const computeFromTree = (filter: Filter) => { const ignoreComment = ({ Type }: any) => Type !== 'Comment'; const simple = fromSieveTree(filter.Tree); if (!simple) { return null; } const fromSimple = toSieveTree(simple, filter.Version).filter(ignoreComment); const original = filter.Tree.filter(ignoreComment); return isDeepEqual(fromSimple, original) ? simple : null; }; export const computeTree = ({ Simple, Version }: Partial<Filter>) => { if (!Simple) { return []; } return toSieveTree(Simple, Version); }; export function normalize() { const SINGLE_QUOTE = "'"; const DOUBLE_QUOTE = '"'; const SINGLE_QUOTE_REGEXP = new RegExp(`[${['‹', '›', '‚', '‘', '‛', '’', '❛', '❜', '❮', '❯'].join('')}]`, 'g'); const DOUBLE_QUOTE_REGEXP = new RegExp( `[${['«', '»', '„', '“', '‟', '”', '❝', '❞', '〝', '〞', '〟', '"'].join('')}]`, 'g' ); return (value = '') => { if (SINGLE_QUOTE_REGEXP.test(value) || DOUBLE_QUOTE_REGEXP.test(value)) { return value.replace(SINGLE_QUOTE_REGEXP, SINGLE_QUOTE).replace(DOUBLE_QUOTE_REGEXP, DOUBLE_QUOTE); } return value; }; } const convertOperator = ({ statement }: SimpleFilterModalModel): FilterOperator => { const operatorsMap = toMap(OPERATORS, 'value'); return operatorsMap[statement]; }; const convertConditions = ({ conditions }: SimpleFilterModalModel): FilterCondition[] => { const comparatorsMap = toMap(COMPARATORS, 'value'); const typesMap = toMap(TYPES, 'value'); return conditions.map((cond) => ({ Comparator: comparatorsMap[cond.comparator], Type: typesMap[cond.type], Values: cond.values || [], })); }; const convertActions = ({ actions }: SimpleFilterModalModel): FilterActions => { const { labelAs: { labels }, moveTo: { folder }, markAs, autoReply, } = actions; return { FileInto: folder ? [folder, ...labels] : [...labels], Mark: { Read: markAs.read, Starred: markAs.starred, }, Vacation: autoReply || null, }; }; export const convertModel = (modalModel: FilterModalModelBase, isSieve = false): Filter => { const config = { ID: modalModel.id || '', Name: modalModel.name || '', Status: modalModel.status || 1, Version: modalModel.version || FILTER_VERSION, }; if (isSieve) { const model = modalModel as FilterModalModelBase & { sieve: string }; return { ...config, Sieve: model.sieve || '', }; } const newModel = { ...config, Simple: { Operator: convertOperator(modalModel as SimpleFilterModalModel), Conditions: convertConditions(modalModel as SimpleFilterModalModel), Actions: convertActions(modalModel as SimpleFilterModalModel), }, }; return { ...newModel, Tree: computeTree(newModel), }; }; export const isSieve = (filter: Filter) => { return !computeFromTree(filter); }; export const sieveTemplates = { 1: '', 2: `require ["include", "environment", "variables", "relational", "comparator-i;ascii-numeric", "spamtest"]; # Generated: Do not run this script on spam messages if allof (environment :matches "vnd.proton.spam-threshold" "*", spamtest :value "ge" :comparator "i;ascii-numeric" "\${1}") { return; } `, }; export const newFilter = (): Filter => { return { ID: '', Name: '', Status: 1, Version: FILTER_VERSION, Simple: { Operator: { label: OPERATORS[0].label, value: OPERATORS[0].value, }, Conditions: [ { Values: [], Type: TYPES[0], Comparator: COMPARATORS[0], }, ], Actions: { FileInto: [], Vacation: '', Mark: { Read: false, Starred: false }, }, }, }; }; /** * Return a filter name based on baseName but unique in the list of existing filters */ export const createUniqueName = (baseName: string, filters: Filter[]) => { let filterName = baseName; let counter = 1; const isAlreadyUsed = (name: string) => filters.some((filter) => filter.Name === name); while (isAlreadyUsed(filterName)) { filterName = `${filterName} ${counter++}`; } return filterName; }; export const createDefaultLabelsFilter = ( senders: string[], labels: { ID: string; Name: string; Path: string }[], filters: Filter[] ) => { return senders.map<Filter>((sender) => { const labelNames = labels.map((label) => label.Name).join(', '); const Name = createUniqueName(`${sender} - ${labelNames}`, filters); const filter: Filter = { ID: '', Name, Status: 1, Version: FILTER_VERSION, Simple: { Operator: { label: OPERATORS[0].label, value: OPERATORS[0].value, }, Conditions: [ { Values: [sender], Type: TYPES[2], Comparator: COMPARATORS[1], }, ], Actions: { FileInto: labels.map((label) => { // We need to send the label Name as action here. // In case it's a default folder, we want to make sure the folder is sent the correct way (without upper cases) const defaultFolderNames = getDefaultFolders().map((f) => f.value); if (defaultFolderNames.includes(label.Name.toLowerCase())) { return label.Name.toLowerCase(); } return label.Path; }), Vacation: '', Mark: { Read: false, Starred: false }, }, }, }; filter.Tree = computeTree(filter); return filter; }, []); }; export default newFilter;
6,222
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/modal/CloseFilterModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { ModalProps, Prompt } from '../../../components'; interface Props extends ModalProps { handleDiscard?: () => void; } const CloseFilterModal = ({ handleDiscard, ...rest }: Props) => { const { onClose } = rest; const handleClose = () => { handleDiscard?.(); onClose?.(); }; return ( <Prompt title={c('Title').t`Are you sure you want to close?`} buttons={[ <Button color="danger" onClick={handleClose}>{c('Action').t`Discard`}</Button>, <Button onClick={onClose}>{c('Action').t`Cancel`}</Button>, ]} {...rest} > {c('Info').t`All your changes will be lost.`} <br /> {c('Info').t`Are you sure you want to discard your changes?`} </Prompt> ); }; export default CloseFilterModal;
6,223
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/modal/DeleteFilterModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { ModalProps, Prompt } from '../../../components'; interface Props extends ModalProps { filterName: string; handleDelete: () => void; } const DeleteFilterModal = ({ filterName, handleDelete, ...rest }: Props) => { const { onClose } = rest; const deleteFilter = () => { onClose?.(); handleDelete(); }; return ( <Prompt title={c('Title').t`Delete ${filterName}`} buttons={[ <Button color="danger" onClick={deleteFilter}>{c('Action').t`Delete`}</Button>, <Button onClick={onClose}>{c('Action').t`Cancel`}</Button>, ]} {...rest} > {c('Info') .t`Please note that if you delete this filter, we will stop processing all the automated actions it triggers.`} <br /> {c('Info').t`Are you sure you want to delete this filter?`} </Prompt> ); }; export default DeleteFilterModal;
6,224
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/modal/FilterActionsForm.tsx
import { Folder } from '@proton/shared/lib/interfaces/Folder'; import { Label } from '@proton/shared/lib/interfaces/Label'; import { Actions, SimpleFilterModalModel } from '../interfaces'; import FilterActionsFormAutoReplyRow from './FilterActionsFormAutoReplyRow'; import FilterActionsFormFoldersRow from './FilterActionsFormFolderRow'; import FilterActionsFormLabelsRow from './FilterActionsFormLabelsRow'; import FilterActionsFormMarkAsRow from './FilterActionsFormMarkAsRow'; interface Props { labels: Label[]; folders: Folder[]; model: SimpleFilterModalModel; onChange: (newModel: SimpleFilterModalModel) => void; isEdit: boolean; } const FilterActionsForm = ({ labels, folders, model, onChange, isEdit }: Props) => { const onUpdateActions = (payload: Partial<Actions>) => { onChange({ ...model, actions: { ...model.actions, ...payload, }, }); }; return ( <> <FilterActionsFormLabelsRow actions={model.actions} handleUpdateActions={onUpdateActions} labels={labels} /> <FilterActionsFormFoldersRow actions={model.actions} handleUpdateActions={onUpdateActions} folders={folders} /> <FilterActionsFormMarkAsRow actions={model.actions} handleUpdateActions={onUpdateActions} /> <FilterActionsFormAutoReplyRow actions={model.actions} handleUpdateActions={onUpdateActions} isEdit={isEdit} /> </> ); }; export default FilterActionsForm;
6,225
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/modal/FilterActionsFormAutoReplyRow.tsx
import { useEffect, useState } from 'react'; import { c } from 'ttag'; import { useToolbar } from '@proton/components/components/editor/hooks/useToolbar'; import noop from '@proton/utils/noop'; import { Editor, EditorActions, Toggle, Tooltip } from '../../../components'; import { useUser } from '../../../hooks'; import { Actions } from '../interfaces'; interface Props { actions: Actions; handleUpdateActions: (onUpdateActions: Partial<Actions>) => void; isEdit: boolean; } const FilterActionsFormAutoReplyRow = ({ isEdit, actions, handleUpdateActions }: Props) => { const [user] = useUser(); const { autoReply } = actions; const [editorVisible, setEditorVisible] = useState(!!autoReply); const [editorValue, setEditorValue] = useState(autoReply || ''); const handleReady = (editorActions: EditorActions) => { editorActions.setContent(editorValue); if (!isEdit) { editorActions.focus(); } }; useEffect(() => { handleUpdateActions({ autoReply: editorVisible ? editorValue : '' }); }, [editorVisible]); const { openEmojiPickerRef, toolbarConfig, setToolbarConfig, modalLink, modalImage, modalDefaultFont } = useToolbar( {} ); return ( <> <div className="flex flex-nowrap flex-column md:flex-row align-items-center pt-4 gap-4" data-testid="filter-modal:auto-reply-row" > {user.hasPaidMail ? ( <> <label htmlFor="autoReply" className="w-full md:w-1/4 pt-2"> <span>{c('Label').t`Send auto-reply`}</span> </label> <div className="flex flex-column w-full pt-2"> <Toggle id="autoReply" checked={editorVisible} onChange={() => { setEditorVisible((editorVisible) => !editorVisible); }} /> </div> </> ) : ( <> <div className="w-full md:w-1/4 pt-2"> <span className="mx-2">{c('Label').t`Send auto-reply`}</span> </div> <Tooltip title={c('Tooltip').t`This feature is only available for paid users`}> <span> <Toggle disabled checked={false} onChange={noop} /> </span> </Tooltip> </> )} </div> {editorVisible && user.hasPaidMail && ( <div className="w-full mt-4"> <Editor onReady={handleReady} metadata={{ supportImages: false }} onChange={(value: string) => { setEditorValue(value); handleUpdateActions({ autoReply: value }); }} simple openEmojiPickerRef={openEmojiPickerRef} toolbarConfig={toolbarConfig} setToolbarConfig={setToolbarConfig} modalLink={modalLink} modalImage={modalImage} modalDefaultFont={modalDefaultFont} /> </div> )} </> ); }; export default FilterActionsFormAutoReplyRow;
6,226
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/modal/FilterActionsFormFolderRow.tsx
import { Fragment } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useUser } from '@proton/components/hooks'; import { buildTreeview, formatFolderName, hasReachedFolderLimit } from '@proton/shared/lib/helpers/folder'; import { Folder, FolderWithSubFolders } from '@proton/shared/lib/interfaces/Folder'; import clsx from '@proton/utils/clsx'; import { Icon, IconName, InputFieldTwo, Option, SelectTwo, useModalState } from '../../../components'; import EditLabelModal, { LabelModel } from '../../labels/modals/EditLabelModal'; import { getDefaultFolderOptions, noFolderOption, noFolderValue } from '../constants'; import { Actions } from '../interfaces'; interface Props { folders: Folder[]; actions: Actions; handleUpdateActions: (onUpdateActions: Partial<Actions>) => void; } type ChangePayload = { folder?: string; isOpen: boolean; }; export type SelectOption = { type: 'label' | 'option'; value?: string; text: string; disabled?: boolean; }; const formatOption = ({ Path, Name }: FolderWithSubFolders, level = 0) => ({ type: 'option', value: Path || '', text: formatFolderName(level, Name, ' • '), }) as SelectOption; const reducer = (acc: SelectOption[] = [], folder: FolderWithSubFolders, level = 0): SelectOption[] => { acc.push(formatOption(folder, level)); if (Array.isArray(folder.subfolders)) { folder.subfolders.forEach((folder) => reducer(acc, folder, level + 1)); } return acc; }; const FilterActionsFormFolderRow = ({ folders, actions, handleUpdateActions }: Props) => { const [user] = useUser(); const treeview = buildTreeview(folders); const canCreateLabel = !hasReachedFolderLimit(user, folders); const reducedFolders = treeview.reduce<SelectOption[]>((acc, folder) => { return reducer(acc, folder, 0); }, []); const defaultFolders = getDefaultFolderOptions(); const options = [noFolderOption, ...defaultFolders].concat([ { type: 'label', text: c('Option group').t`Custom folders` }, ...reducedFolders, ]); const { moveTo } = actions; const { isOpen } = moveTo; const [editLabelProps, setEditLabelModalOpen] = useModalState(); const folderOptions = options.map((option) => { const { type, text, value, disabled } = option; if (type === 'label') { return ( <label className="text-semibold px-2 py-1 block" key={text}> {text} </label> ); } return <Option value={value} title={text} key={value} disabled={disabled} />; }); const handleChangeModel = (payload: Partial<ChangePayload>) => { handleUpdateActions({ moveTo: { ...actions.moveTo, ...payload, }, }); }; const toggleSection = () => { handleChangeModel({ isOpen: !isOpen }); }; const handleCreateFolder = (folder: LabelModel) => { handleChangeModel({ folder: folder.Path }); }; const renderClosed = () => { if (!moveTo?.folder) { return <em className="color-weak">{c('Info').t`No folder selected`}</em>; } let selectedFolder; if (['archive', 'inbox', 'spam', 'trash'].includes(moveTo?.folder)) { selectedFolder = ( <span className="inline-flex flex-align-items-center mr-8"> <Icon name={moveTo.folder as IconName} className="mr-2" /> {options.find((o) => o.value === moveTo?.folder)?.text} </span> ); } else { selectedFolder = moveTo?.folder.split('/').map((f: string, i: number) => ( <Fragment key={f}> {i !== 0 && ( <Icon name="chevron-down" className="ml-2" style={{ transform: 'rotate(-90deg)', }} /> )} <span className={clsx([ 'max-w-full flex-nowrap inline-flex flex-align-items-center', i !== 0 && 'ml-2', ])} > <Icon name="folder" className="mr-2" /> <span className="text-ellipsis" title={f}> {f} </span> </span> </Fragment> )); } return <div className="flex flex-align-items-center max-w-full">{selectedFolder}</div>; }; return ( <div className="border-bottom flex flex-column md:flex-row flex-nowrap align-items-center py-4 gap-4" data-testid="filter-modal:folder-row" > <button type="button" className="w-full md:w-1/4 text-left" onClick={toggleSection}> <Icon name="chevron-down" className={clsx([isOpen && 'rotateX-180'])} /> <span className={clsx(['ml-2', actions.error && 'color-danger'])}>{c('Label').t`Move to`}</span> </button> <div className="flex flex-column flex-nowrap w-full"> {isOpen ? ( <div className="w-full"> <InputFieldTwo as={SelectTwo} id="memberSelect" value={moveTo.folder || noFolderValue} onValue={(value: any) => handleChangeModel({ folder: value })} > {folderOptions} </InputFieldTwo> {canCreateLabel && ( <Button shape="outline" onClick={() => setEditLabelModalOpen(true)}> {c('Action').t`Create folder`} </Button> )} <EditLabelModal {...editLabelProps} onAdd={handleCreateFolder} type="folder" /> </div> ) : ( renderClosed() )} </div> </div> ); }; export default FilterActionsFormFolderRow;
6,227
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/modal/FilterActionsFormLabelsRow.tsx
import { Fragment } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useUser } from '@proton/components/hooks'; import { hasReachedLabelLimit } from '@proton/shared/lib/helpers/folder'; import { Label } from '@proton/shared/lib/interfaces/Label'; import clsx from '@proton/utils/clsx'; import { Checkbox, Icon, LabelStack, useModalState } from '../../../components'; import EditLabelModal, { LabelModel } from '../../labels/modals/EditLabelModal'; import { Actions } from '../interfaces'; interface Props { labels: Label[]; actions: Actions; handleUpdateActions: (onUpdateActions: Partial<Actions>) => void; } type ChangePayload = { labels: string[]; isOpen: boolean; }; const FilterActionsFormLabelsRow = ({ actions, handleUpdateActions, labels }: Props) => { const [user] = useUser(); const { labelAs } = actions; const { isOpen } = labelAs; const [editLabelProps, setEditLabelModalOpen] = useModalState(); const canCreateLabel = !hasReachedLabelLimit(user, labels); const handleChangeModel = (payload: Partial<ChangePayload>) => { handleUpdateActions({ labelAs: { ...actions.labelAs, ...payload, }, }); }; const toggleSection = () => { handleChangeModel({ isOpen: !isOpen }); }; const handleCreateLabel = (label: LabelModel) => { if (label.Path) { handleChangeModel({ labels: [...labelAs.labels, label.Path] }); } }; const handleCheckLabel = (checkedLabel: Label) => { const isLabelCheck = labelAs.labels.indexOf(checkedLabel.Path) === -1; let nextLabels = [...labelAs.labels]; nextLabels = isLabelCheck ? [...nextLabels, checkedLabel.Path] : nextLabels.filter((labelPath) => checkedLabel.Path !== labelPath); handleChangeModel({ labels: nextLabels }); }; const renderClosed = () => { if (!labelAs?.labels.length) { return <em className="color-weak">{c('Info').t`No label selected`}</em>; } return ( <div> {labelAs?.labels.map((labelName: string) => { const label = labels?.find((l) => l.Name === labelName); return label ? ( <Fragment key={labelName}> <span className="mx-2 mb-2"> <LabelStack labels={[ { name: label.Name, color: label.Color, title: label.Name, }, ]} /> </span> </Fragment> ) : null; })} </div> ); }; return ( <div className="border-bottom flex flex-column md:flex-row flex-nowrap align-items-center py-4 gap-4" data-testid="filter-modal:label-row" > <button type="button" className="w-full md:w-1/4 text-left" onClick={toggleSection}> <Icon name="chevron-down" className={clsx([isOpen && 'rotateX-180'])} /> <span className={clsx(['ml-2', actions.error && 'color-danger'])}>{c('Label').t`Label as`}</span> </button> <div className="w-full"> {isOpen ? ( <> <div className="w-full"> {labels.length ? ( labels.map((label) => ( <div className="mb-2 inline-block text-ellipsis" key={label.Path}> <Checkbox title={label.Name} className="mr-4 flex-nowrap" checked={labelAs.labels.includes(label.Path)} onChange={() => handleCheckLabel(label)} labelOnClick={(e) => e.stopPropagation()} > <span className="inline-flex align-middle"> <LabelStack labels={[ { name: label.Name, color: label.Color, }, ]} /> </span> </Checkbox> </div> )) ) : ( <div className="mb-4 color-weak">{c('Label').t`No label found`}</div> )} </div> {canCreateLabel && ( <Button shape="outline" className="mt-0" onClick={() => setEditLabelModalOpen(true)}> {c('Action').t`Create label`} </Button> )} <EditLabelModal {...editLabelProps} onAdd={handleCreateLabel} type="label" /> </> ) : ( <div>{renderClosed()}</div> )} </div> </div> ); }; export default FilterActionsFormLabelsRow;
6,228
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/modal/FilterActionsFormMarkAsRow.tsx
import { c } from 'ttag'; import clsx from '@proton/utils/clsx'; import { Checkbox, Icon } from '../../../components'; import { Actions } from '../interfaces'; interface Props { actions: Actions; handleUpdateActions: (onUpdateActions: Partial<Actions>) => void; } type ChangePayload = { read: boolean; starred: boolean; isOpen: boolean; }; const FilterActionsFormMarkAsRow = ({ actions, handleUpdateActions }: Props) => { const { markAs } = actions; const { isOpen } = markAs; const handleChangeModel = (payload: Partial<ChangePayload>) => { handleUpdateActions({ markAs: { ...actions.markAs, ...payload, }, }); }; const toggleSection = () => { handleChangeModel({ isOpen: !isOpen }); }; const renderClosed = () => { if (!markAs?.read && !markAs?.starred) { return <em className="color-weak">{c('Info').t`No action selected`}</em>; } return ( <div> {markAs?.read && ( <span className="inline-flex flex-align-items-center mr-8"> <Icon name="eye" className="mr-2" /> {c('Label').t`Read`} </span> )} {markAs?.starred && ( <span className="inline-flex flex-align-items-center"> <Icon name="star" className="mr-2" /> {c('Label').t`Starred`} </span> )} </div> ); }; return ( <div className="border-bottom flex flex-column md:flex-row flex-nowrap align-items-center py-4 gap-4" data-testid="filter-modal:mark-as-row" > <button type="button" className="w-full md:w-1/4 text-left" onClick={toggleSection}> <Icon name="chevron-down" className={clsx([isOpen && 'rotateX-180'])} /> <span className={clsx(['ml-2', actions.error && 'color-danger'])}>{c('Label').t`Mark as`}</span> </button> <div className="flex flex-column w-full"> {isOpen ? ( <div className="w-full py-2"> <Checkbox checked={markAs.read} onChange={(e) => { handleChangeModel({ read: e.target.checked }); }} labelOnClick={(e) => e.stopPropagation()} > <span>{c('Label').t`Read`}</span> </Checkbox> <Checkbox className="ml-8" checked={markAs.starred} onChange={(e) => { handleChangeModel({ starred: e.target.checked, }); }} labelOnClick={(e) => e.stopPropagation()} > <span>{c('Label').t`Starred`}</span> </Checkbox> </div> ) : ( renderClosed() )} </div> </div> ); }; export default FilterActionsFormMarkAsRow;
6,229
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/modal/FilterConditionsForm.tsx
import { c } from 'ttag'; import clsx from '@proton/utils/clsx'; import { Radio, UnderlineButton } from '../../../components'; import { FilterStatement, SimpleFilterModalModel } from '../interfaces'; import FilterConditionsFormRow from './FilterConditionsFormRow'; import useFilterConditions from './useFilterConditions'; interface Props { model: SimpleFilterModalModel; onChange: (newModel: SimpleFilterModalModel) => void; isEdit: boolean; } const FilterConditionsForm = ({ isEdit, model, onChange }: Props) => { const { conditions, onDeleteCondition, onUpdateCondition, onAddCondition } = useFilterConditions( model.conditions.length ? model.conditions : undefined, (conditions) => onChange({ ...model, conditions }) ); return ( <> <div className="flex flex-nowrap flex-column md:flex-row mb-0 border-bottom gap-4"> <div className={clsx(['w-full md:w-1/4'])}>{c('Label').t`Statement`}</div> <div className={clsx(['inline-flex w-full'])}> <Radio id="statement-all" name="filterConditionStatement" className="flex flex-nowrap mb-4 radio--ontop" checked={model.statement === FilterStatement.ALL} onChange={() => onChange({ ...model, statement: FilterStatement.ALL, }) } > {c('Label').t`ALL`} <em className="ml-2">{c('Info').t`(Filter if ALL of the following conditions are met)`}</em> </Radio> <Radio id="statement-any" name="filterConditionStatement" className="flex flex-nowrap mb-4 radio--ontop" checked={model.statement === FilterStatement.ANY} onChange={() => onChange({ ...model, statement: FilterStatement.ANY, }) } > {c('Label').t`ANY`} <em className="ml-2">{c('Info').t`(Filter if ANY of the following conditions are met)`}</em> </Radio> </div> </div> <div className="mb-2"> {conditions.map((condition, i) => ( <FilterConditionsFormRow isEdit={isEdit} key={condition.id} condition={condition} conditionIndex={i} handleDelete={onDeleteCondition} handleUpdateCondition={onUpdateCondition} statement={model.statement} displayDelete={conditions.length > 1} /> ))} </div> {conditions.every((c) => !c.error) && ( <UnderlineButton onClick={onAddCondition} className="my-2"> <strong>{c('Action').t`Add condition`}</strong> </UnderlineButton> )} </> ); }; export default FilterConditionsForm;
6,230
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/modal/FilterConditionsFormRow.scss
@import '~@proton/styles/scss/lib'; .condition-token { border-radius: 1em; border: 1px solid var(--border-norm); block-size: 1.6em; padding-block: 0; padding-inline: 0.6em; align-items: center; font-size: rem(14); color: var(--text-norm); background: var(--background-weak); }
6,231
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/modal/FilterConditionsFormRow.tsx
import { ChangeEvent, Fragment, useEffect, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import clsx from '@proton/utils/clsx'; import { Icon, Input, Option, Radio, SelectTwo, Tooltip } from '../../../components'; import { COMPARATORS, TYPES, getComparatorLabels, getConditionTypeLabels } from '../constants'; import { Condition, ConditionComparator, ConditionType, FilterStatement } from '../interfaces'; import './FilterConditionsFormRow.scss'; const { SELECT, SUBJECT, SENDER, RECIPIENT } = ConditionType; interface Props { conditionIndex: number; statement: FilterStatement; condition: Condition; handleDelete: (index: number) => void; handleUpdateCondition: (index: number, condition: Condition) => void; displayDelete: boolean; isEdit: boolean; } const FilterConditionsFormRow = ({ conditionIndex, statement, condition, handleDelete, handleUpdateCondition, displayDelete, isEdit, }: Props) => { const typeOptions = TYPES.map(({ value }, i) => { return { text: getConditionTypeLabels(value), value, disabled: i === 0 }; }); const ConditionComparatorOptions = COMPARATORS.map(({ value }) => ({ text: getComparatorLabels(value), value, })); const [isOpen, setIsOpen] = useState(condition.isOpen); const [tokens, setTokens] = useState<string[]>(condition.values || []); const [inputValue, setInputValue] = useState(!isEdit && condition.defaultValue ? condition.defaultValue : ''); const { type, comparator } = condition; const statementLabel = statement === FilterStatement.ALL ? c('Label').t`AND` : c('Label').t`OR`; const label = conditionIndex === 0 ? c('Label').t`IF` : statementLabel; const onAddNewToken = () => { setTokens((tokens) => [...tokens, inputValue.trim()]); setInputValue(''); }; const onRemoveToken = (i: number) => { setTokens((tokens) => { const newTokens = tokens.filter((_, index) => index !== i); return newTokens; }); }; useEffect(() => { if (condition.type === SELECT) { condition.error = c('Error').t`Empty condition`; } else if ( [SUBJECT, SENDER, RECIPIENT].includes(condition.type) && (!condition.values || !condition.values.length) ) { condition.error = c('Error').t`Condition incomplete`; } else { condition.error = ''; } }, [condition]); useEffect(() => { handleUpdateCondition(conditionIndex, { ...condition, values: tokens, }); }, [tokens]); useEffect(() => { handleUpdateCondition(conditionIndex, { ...condition, isOpen, }); }, [isOpen]); const onChangeInputValue = (e: ChangeEvent<HTMLInputElement>) => { setInputValue(e.target.value); }; const renderAttachmentsCondition = () => { const withAttachment = condition?.comparator === ConditionComparator.CONTAINS; const toggleAttachment = () => { handleUpdateCondition(conditionIndex, { ...condition, comparator: withAttachment ? ConditionComparator.DOES_NOT_CONTAIN : ConditionComparator.CONTAINS, }); }; return ( <div className="mt-4 flex"> <Radio id={`condition-${conditionIndex}-with-attachment`} name={`attachment-condition-${conditionIndex}`} className="flex flex-nowrap radio--ontop mr-4" checked={withAttachment} onChange={toggleAttachment} > {c('Label').t`With attachment`} </Radio> <Radio id={`condition-${conditionIndex}-without-attachment`} name={`attachment-condition-${conditionIndex}`} className="flex flex-nowrap radio--ontop" checked={!withAttachment} onChange={toggleAttachment} > {c('Label').t`Without attachment`} </Radio> </div> ); }; const renderToken = (token: string, i: number) => ( <Fragment key={`Condition_${conditionIndex}_Token_${i}`}> {i > 0 && <span className="mx-2 text-sm">{c('Label').t`or`}</span>} <span key={`condition-${conditionIndex}-token-${i}`} className="inline-flex flex-row flex-align-items-center mb-2 condition-token" > <span className="text-ellipsis text-no-decoration" title={token}> {token} </span> <button type="button" className="flex flex-item-noshrink ml-2" onClick={() => onRemoveToken(i)}> <Icon name="cross" size={11} /> <span className="sr-only">{c('Action').t`Remove this label`}</span> </button> </span> </Fragment> ); const renderGenericCondition = () => { return ( <div className="mt-4 flex-item-fluid"> <div className="flex flex-nowrap"> <span className="flex-item-fluid pr-4"> <Input onChange={onChangeInputValue} type="text" value={inputValue} placeholder={c('Placeholder').t`Type text or keyword`} onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); onAddNewToken(); } }} /> </span> <Button disabled={!inputValue.trim()} onClick={onAddNewToken} className="button-blue">{c('Action') .t`Insert`}</Button> </div> {tokens.length ? <div className="mt-4">{tokens.map(renderToken)}</div> : null} </div> ); }; const renderClosed = () => { if (condition?.error) { return <em className="pt-2 color-danger">{condition?.error}</em>; } let label; let title; if (type === ConditionType.ATTACHMENTS) { const attachment = condition?.comparator === ConditionComparator.CONTAINS ? c('Label').t`with attachments` : c('Label').t`without attachment`; const attachmentStrong = <strong key="attachments">{attachment}</strong>; label = c('Label').jt`The email was sent ${attachmentStrong}`; title = c('Label').t`The email was sent ${attachment}`; } else { const typeLabel = getConditionTypeLabels(type); const comparatorLabel = getComparatorLabels(comparator); const values = condition?.values?.map((v, i) => { return i > 0 ? ( <Fragment key={`${v}${i}`}> {` `} {c('Label').t`or`} {` `} <strong>{v}</strong> </Fragment> ) : ( <strong key={`${v}${i}`}>{v}</strong> ); }); const titleValues = condition?.values?.map((v, i) => { return i > 0 ? ` or ${v}` : v; }); title = `${typeLabel} ${comparatorLabel} ${titleValues}`; label = ( <> {typeLabel} {` `} {comparatorLabel} {` `} {values} </> ); } return ( <span className="max-w-full text-ellipsis" title={title}> {label} </span> ); }; const toggleSection = () => setIsOpen((isOpen) => !isOpen); return ( <div className="border-bottom"> <div className="flex flex-nowrap flex-column md:flex-row align-items-center gap-4 py-4" data-testid={`filter-modal:condition-${conditionIndex}`} > <button type="button" className={clsx(['w-1/4 text-left'])} onClick={toggleSection}> <Icon name="chevron-down" className={clsx([isOpen && 'rotateX-180'])} /> <span className={clsx(['ml-2', condition.error && 'color-danger'])}>{label}</span> </button> <div className={clsx(['flex flex-column w-full'])}> {isOpen ? ( <div className="flex"> <span className="w-1/2 pr-4"> <SelectTwo value={type} onChange={({ value }) => { handleUpdateCondition(conditionIndex, { ...condition, type: value as ConditionType, }); }} > {typeOptions.map(({ text, value, disabled }) => ( <Option key={value} value={value} disabled={disabled} title={text} /> ))} </SelectTwo> </span> {type && [ConditionType.SUBJECT, ConditionType.SENDER, ConditionType.RECIPIENT].includes( type ) && ( <span className="w-1/2"> <SelectTwo value={comparator} onChange={({ value }) => { handleUpdateCondition(conditionIndex, { ...condition, comparator: value as ConditionComparator, }); }} > {ConditionComparatorOptions.map(({ text, value }) => ( <Option key={value} value={value} title={text} /> ))} </SelectTwo> </span> )} </div> ) : ( renderClosed() )} {isOpen && type && type !== ConditionType.SELECT && ( <div className="flex"> {type === ConditionType.ATTACHMENTS ? renderAttachmentsCondition() : renderGenericCondition()} </div> )} </div> {displayDelete && ( <div className="flex-item-noshrink"> <Tooltip title={c('Action').t`Delete`}> <Button onClick={() => handleDelete(conditionIndex)} icon> <Icon name="trash" alt={c('Action').t`Delete`} /> </Button> </Tooltip> </div> )} </div> </div> ); }; export default FilterConditionsFormRow;
6,232
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/modal/FilterModal.tsx
import React, { useEffect, useMemo, useState } from 'react'; import { c } from 'ttag'; import { useLoading } from '@proton/hooks'; import { addTreeFilter, applyFilters, updateFilter } from '@proton/shared/lib/api/filters'; import isDeepEqual from '@proton/shared/lib/helpers/isDeepEqual'; import { removeImagesFromContent } from '@proton/shared/lib/sanitize/purify'; import { Checkbox, Form, Loader, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, useModalState, } from '../../../components'; import { generateUID } from '../../../helpers'; import { useApiWithoutResult, useEventManager, useFilters, useFolders, useLabels, useNotifications, } from '../../../hooks'; import { getDefaultFolders, noFolderValue } from '../constants'; import { Actions, Condition, Errors, Filter, FilterActions, FilterCondition, FilterOperator, FilterStatement, SimpleFilterModalModel, Step, } from '../interfaces'; import { computeFromTree, convertModel } from '../utils'; import CloseFilterModal from './CloseFilterModal'; import FilterActionsForm from './FilterActionsForm'; import FilterConditionsForm from './FilterConditionsForm'; import FilterNameForm from './FilterNameForm'; import FilterPreview from './FilterPreview'; import FooterFilterModal from './FooterFilterModal'; import HeaderFilterModal from './HeaderFilterModal'; import './Filtermodal.scss'; interface Props extends ModalProps { filter?: Filter; onCloseCustomAction?: () => void; } const checkNameErrors = (filters: Filter[], name: string): string => { if (!name) { return c('Error').t`This field is required`; } const trimmedName = name.trim(); if (filters.find(({ Name }: Filter) => Name.trim() === trimmedName)) { return c('Error').t`Filter with this name already exists`; } return ''; }; const checkConditionsErrors = (conditions: Condition[]): string => { if (conditions.some((c) => !!c.error)) { return c('Error').t`Error in one of the conditions`; } if (!conditions.length) { return c('Error').t`Require at least one condition`; } return ''; }; const checkActionsErrors = (actions: Actions) => { const { labelAs, markAs, moveTo, autoReply } = actions; if (!labelAs.labels.length && !moveTo.folder && !markAs.read && !markAs.starred && !autoReply) { return c('Error').t`Require at least one action`; } return ''; }; const modelHasChanged = (a: SimpleFilterModalModel, b: SimpleFilterModalModel): boolean => { const cleanConditions = (c: Condition) => ({ type: c.type, comparator: c.comparator, values: c.values, }); if ( a.name !== b.name || a.statement !== b.statement || !isDeepEqual(a.conditions.map(cleanConditions), b.conditions.map(cleanConditions)) || !isDeepEqual(a.actions.labelAs.labels, b.actions.labelAs.labels) || a.actions.moveTo.folder !== b.actions.moveTo.folder || a.actions.markAs.read !== b.actions.markAs.read || a.actions.markAs.starred !== b.actions.markAs.starred || (a.actions.autoReply && b.actions.autoReply && a.actions.autoReply !== b.actions.autoReply) ) { return true; } return false; }; const FilterModal = ({ filter, onCloseCustomAction, ...rest }: Props) => { const [filters = []] = useFilters(); const [labels = [], loadingLabels] = useLabels(); const [folders = [], loadingFolders] = useFolders(); const { createNotification } = useNotifications(); const { call } = useEventManager(); const [loading, withLoading] = useLoading(); const isEdit = !!filter?.ID; const [closeFilterModalProps, setCloseFilterModalOpen] = useModalState(); const { onClose } = rest; const initializeModel = (filter?: Filter) => { const computedFilter = filter ? computeFromTree(filter) : {}; const { Actions, Conditions, Operator, }: { Operator?: FilterOperator; Actions?: FilterActions; Conditions?: FilterCondition[]; } = computedFilter || {}; const foldersLabelsMap = Actions?.FileInto.reduce( ( acc: { folder: string[]; labels: string[]; }, folderOrLabel: string ) => { const defaultFolderNames = getDefaultFolders().map((f) => f.value); if (defaultFolderNames.includes(folderOrLabel) || folders?.find((f) => f.Path === folderOrLabel)) { acc.folder = [folderOrLabel]; } if (labels?.find((l) => l.Path === folderOrLabel)) { acc.labels.push(folderOrLabel); } return acc; }, { folder: [], labels: [] } ); return { step: Step.NAME, id: filter?.ID, statement: Operator?.value || FilterStatement.ALL, name: filter?.Name || '', apply: false, conditions: Conditions?.map((cond) => ({ type: cond.Type.value, comparator: cond.Comparator.value, values: isEdit ? cond.Values : [], isOpen: true, defaultValue: cond.Values[0] || '', id: generateUID('condition'), })) || [], actions: { labelAs: { labels: foldersLabelsMap?.labels || [], isOpen: true, }, moveTo: { folder: foldersLabelsMap?.folder && foldersLabelsMap?.folder[0] ? foldersLabelsMap?.folder[0] : noFolderValue, isOpen: true, }, markAs: { read: Actions?.Mark.Read || false, starred: Actions?.Mark.Starred || false, isOpen: true, }, autoReply: Actions?.Vacation || null, }, }; }; const [model, setModel] = useState<SimpleFilterModalModel>(initializeModel()); const title = isEdit ? c('Title').t`Edit filter` : c('Title').t`Add filter`; const { name, conditions, actions } = model; const errors = useMemo<Errors>(() => { return { name: !model.name || filter?.Name !== name ? checkNameErrors(filters, name) : '', conditions: checkConditionsErrors(conditions), actions: checkActionsErrors(actions), }; }, [name, actions, conditions]); const reqCreate = useApiWithoutResult<{ Filter: Filter }>(addTreeFilter); const reqUpdate = useApiWithoutResult<{ Filter: Filter }>(updateFilter); const reqApply = useApiWithoutResult<{ Filter: Filter }>(applyFilters); const handleCloseModal = () => { onCloseCustomAction?.(); onClose?.(); }; const createFilter = async (filter: Filter) => { try { const { Filter } = await reqCreate.request(filter); createNotification({ text: c('Notification').t`${Filter.Name} created`, }); return Filter; } finally { // Some failed request will add the filter but in disabled mode // So we have to refresh the list in both cases await call(); handleCloseModal(); } }; const applyFilter = async (filterId: string) => { await reqApply.request([filterId]); }; const editFilter = async (filter: Filter) => { const { Filter } = await reqUpdate.request(filter.ID, filter); await call(); createNotification({ text: c('Filter notification').t`Filter ${Filter.Name} updated`, }); handleCloseModal(); return Filter; }; const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => { let newModel = model; // Remove images from the composer in autoreply if (model.actions.autoReply) { const { message, containsImages } = removeImagesFromContent(model.actions.autoReply); if (containsImages) { createNotification({ type: 'warning', text: c('Info').t`Images have been removed because they are not allowed in auto-reply`, }); } newModel = { ...model, actions: { ...actions, autoReply: message } }; setModel(newModel); } event.preventDefault(); let apiResult: Filter | undefined = undefined; if (isEdit) { apiResult = await editFilter(convertModel(newModel)); } else { apiResult = await createFilter(convertModel(newModel)); } if (newModel.apply && apiResult) { await applyFilter(apiResult.ID); } }; const handleClose = () => { if (!modelHasChanged(model, initializeModel(filter))) { return handleCloseModal(); } setCloseFilterModalOpen(true); }; const renderStep = () => { switch (model.step) { case Step.NAME: return ( <FilterNameForm model={model} onChange={(newModel) => setModel(newModel as SimpleFilterModalModel)} errors={errors} loading={loading} /> ); case Step.CONDITIONS: return <FilterConditionsForm isEdit={isEdit} model={model} onChange={setModel} />; case Step.ACTIONS: return ( <FilterActionsForm labels={labels} folders={folders} model={model} onChange={setModel} isEdit={isEdit} /> ); case Step.PREVIEW: return <FilterPreview labels={labels} folders={folders} model={model} />; default: return null; } }; useEffect(() => { if (filter && !loadingFolders && !loadingLabels) { setModel(initializeModel(filter)); } }, [loadingFolders, loadingLabels]); return ( <> <ModalTwo as={Form} className="mail-filter-modal" onSubmit={(event: React.FormEvent<HTMLFormElement>) => { withLoading(handleSubmit(event)); }} {...rest} onClose={handleClose} > <ModalTwoHeader title={title} /> <ModalTwoContent> <HeaderFilterModal model={model} errors={errors} onChange={(newModel) => setModel(newModel as SimpleFilterModalModel)} /> {loadingLabels || loadingFolders ? <Loader /> : renderStep()} {[Step.ACTIONS, Step.PREVIEW].includes(model.step) && ( <div className="mt-4"> <Checkbox id="applyfilter" onChange={(event) => setModel({ ...model, apply: !!event.target.checked })} checked={model.apply} > {c('Label').t`Apply filter to existing emails`} </Checkbox> </div> )} </ModalTwoContent> <ModalTwoFooter> <FooterFilterModal model={model} errors={errors} onChange={(newModel) => setModel(newModel as SimpleFilterModalModel)} onClose={handleClose} loading={loading} /> </ModalTwoFooter> </ModalTwo> <CloseFilterModal {...closeFilterModalProps} handleDiscard={handleCloseModal} /> </> ); }; export default FilterModal;
6,233
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/modal/FilterNameForm.tsx
import { KeyboardEvent } from 'react'; import { c } from 'ttag'; import { Input } from '@proton/atoms'; import clsx from '@proton/utils/clsx'; import { Field } from '../../../components'; import { AdvancedSimpleFilterModalModel, SimpleFilterModalModel, Step } from '../interfaces'; interface Errors { name: string; } interface Props { model: SimpleFilterModalModel | AdvancedSimpleFilterModalModel; errors: Errors; onChange: (newModel: SimpleFilterModalModel | AdvancedSimpleFilterModalModel) => void; isSieveFilter?: boolean; loading: boolean; } const FilterNameForm = ({ isSieveFilter = false, model, errors, onChange, loading }: Props) => { const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => { if (e.key === 'Enter' && !loading && !errors.name) { e.preventDefault(); e.stopPropagation(); if (isSieveFilter) { onChange({ ...model, } as AdvancedSimpleFilterModalModel); return; } onChange({ ...model, step: Step.CONDITIONS, } as SimpleFilterModalModel); } }; return ( <> {!isSieveFilter && ( <div className="mb-4"> {c('Info') .t`Filters work on all emails, including incoming as well as sent emails. Each filter must contain at least a name, a condition and an action.`} </div> )} <div className="flex flex-nowrap flex-column md:flex-row align-items-center py-4 gap-4"> <label htmlFor="name" className={clsx(['w-1/5 pt-2'])}> {c('Label').t`Filter Name`} </label> <Field> <Input id="name" placeholder={c('Placeholder').t`Name`} value={model.name} error={errors.name} onValue={(value) => onChange({ ...model, name: value })} onKeyDown={handleKeyDown} autoFocus required data-testid="filter-modal:name-input" /> </Field> </div> </> ); }; export default FilterNameForm;
6,234
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/modal/FilterPreview.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Folder } from '@proton/shared/lib/interfaces/Folder'; import { Label } from '@proton/shared/lib/interfaces/Label'; import { SimpleFilterModalModel } from '../interfaces'; import FilterPreviewActions from './FilterPreviewActions'; import FilterPreviewConditions from './FilterPreviewConditions'; interface Props { labels: Label[]; folders: Folder[]; model: SimpleFilterModalModel; } const FilterPreview = ({ labels, folders, model }: Props) => { const [conditionsOpen, setConditionsOpen] = useState(true); const [actionsOpen, setActionsOpen] = useState(true); return ( <> <div className="border-bottom"> <div className="flex flex-nowrap flex-column md:flex-row align-items-center pb-4 gap-4"> <div className="w-full md:w-1/4 pt-2 mb-2 md:mb-0"> <span className="mr-2">{c('Label').t`Filter Name`}</span> </div> <div title={model.name} className="pt-2 flex flex-column w-full"> <span className="max-w-full text-ellipsis">{model.name}</span> </div> </div> </div> <FilterPreviewConditions model={model} isOpen={conditionsOpen} toggleOpen={() => setConditionsOpen(!conditionsOpen)} /> <FilterPreviewActions labels={labels} folders={folders} model={model} isOpen={actionsOpen} toggleOpen={() => setActionsOpen(!actionsOpen)} /> </> ); }; export default FilterPreview;
6,235
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/modal/FilterPreviewActions.tsx
import { Fragment } from 'react'; import { c } from 'ttag'; import { toMap } from '@proton/shared/lib/helpers/object'; import { Folder } from '@proton/shared/lib/interfaces/Folder'; import { Label } from '@proton/shared/lib/interfaces/Label'; import clsx from '@proton/utils/clsx'; import { Icon, LabelStack } from '../../../components'; import { getDefaultFolders } from '../constants'; import { SimpleFilterModalModel } from '../interfaces'; interface Props { labels: Label[]; folders: Folder[]; model: SimpleFilterModalModel; toggleOpen: () => void; isOpen: boolean; } const FilterPreviewActions = ({ isOpen, toggleOpen, labels, folders, model }: Props) => { const LABELS_ACTION = { labelAs: c('Action').t`label emails as`, moveTo: c('Action').t`move emails to`, markAs: c('Action').t`mark emails as`, autoReply: c('Action').t`send auto-reply email`, }; const { actions } = model; const labelsMap = toMap(labels, 'Name'); const actionsRenderer = (() => { const actionsRows = []; if (actions.labelAs.labels.length) { const labelsTitles = actions.labelAs.labels.map((l, i) => { return i > 0 ? c('Label').t` and ${l}` : l; }); const labelsElements = actions.labelAs.labels.map((l, i) => { const label = labelsMap[l]; if (!label) { return null; } return ( <Fragment key={l}> {i > 0 && c('Label').t` and `} {isOpen ? ( <span className="mb-2"> <LabelStack labels={[ { name: label.Name, color: label.Color, title: label.Name, }, ]} /> </span> ) : ( <strong>{l}</strong> )} </Fragment> ); }); actionsRows.push({ element: ( <span> {LABELS_ACTION.labelAs} {` `} {labelsElements} </span> ), title: `${LABELS_ACTION.labelAs} ${labelsTitles}`, }); } if (actions.moveTo.folder) { const isDefault = ['archive', 'inbox', 'spam', 'trash'].includes(actions.moveTo.folder); const defaultFolders = getDefaultFolders(); const selectedFolder = isDefault ? defaultFolders.find((f) => f.value === actions.moveTo.folder)?.text : folders.find((f) => f.Path === actions.moveTo.folder)?.Name; const folderElement = isOpen ? ( <span className="inline-flex flex-row flex-align-items-center condition-token mb-2" role="listitem"> <span className="text-ellipsis text-no-decoration" title={selectedFolder}> {selectedFolder} </span> </span> ) : ( <strong>{selectedFolder}</strong> ); actionsRows.push({ element: ( <> {LABELS_ACTION.moveTo} {` `} {folderElement} </> ), title: `${LABELS_ACTION.moveTo} ${selectedFolder}`, }); } if (actions.markAs.read || actions.markAs.starred) { const readElement = isOpen ? ( <span className="inline-flex flex-row flex-align-items-center condition-token mb-2" role="listitem"> <span className="text-ellipsis text-no-decoration">{c('Filter preview').t`read`}</span> </span> ) : ( <strong>{c('Filter preview').t`read`}</strong> ); const starredElement = isOpen ? ( <span className="inline-flex flex-row flex-align-items-center condition-token mb-2" role="listitem"> <span className="text-ellipsis text-no-decoration">{c('Filter preview').t`starred`}</span> </span> ) : ( <strong>{c('Filter preview').t`starred`}</strong> ); const markAsTitle = `${actions.markAs.read && c('Filter preview').t`read`}${ actions.markAs.read && actions.markAs.starred && ` ${c('Label').t`and`} ` }${actions.markAs.starred && c('Filter preview').t`starred`}`; actionsRows.push({ element: ( <> {LABELS_ACTION.markAs} {` `} {actions.markAs.read && readElement} {actions.markAs.read && actions.markAs.starred && ( <> {` `} {c('Label').t`and`} {` `} </> )} {actions.markAs.starred && starredElement} </> ), title: `${LABELS_ACTION.markAs} ${markAsTitle}`, }); } if (actions.autoReply) { const label = isOpen ? ( <span className="inline-flex flex-row flex-align-items-center condition-token mb-2" role="listitem"> <span className="text-no-decoration max-w-custom" style={{ '--max-w-custom': 'inherit' }}> {LABELS_ACTION.autoReply} </span> </span> ) : ( <strong>{LABELS_ACTION.autoReply}</strong> ); actionsRows.push({ element: label, title: LABELS_ACTION.autoReply, }); } const title: string = actionsRows.reduce((acc, action, i) => { acc += i === 0 ? c('Label').t`Then` : ` ${c('Label').t`and`}`; return `${acc} ${action.title}`; }, ''); return isOpen ? ( <div className="pt-2"> {actionsRows.map((action, i) => ( <div key={`preview-action-${i}`}> {i === 0 ? c('Label').t`Then` : c('Label').t`And`} {` `} {action.element} </div> ))} </div> ) : ( <div className="max-w-full text-ellipsis" title={title}> {actionsRows.map((action, i) => ( <span key={`preview-action-${i}`}> {i === 0 ? c('Label').t`Then` : ` ${c('Label').t`and`}`} {` `} {action.element} </span> ))} </div> ); })(); return ( <div className="border-bottom mb-8"> <div className="flex flex-nowrap flex-column md:flex-row align-items-center py-4 gap-4"> <button type="button" className="w-full md:w-1/4 text-left" onClick={toggleOpen}> <Icon name="chevron-down" className={clsx([isOpen && 'rotateX-180'])} /> <span className="ml-2">{c('Label').t`Actions`}</span> </button> <div className="flex flex-column w-full">{actionsRenderer}</div> </div> </div> ); }; export default FilterPreviewActions;
6,236
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/modal/FilterPreviewConditions.tsx
import { Fragment, useMemo } from 'react'; import { c } from 'ttag'; import clsx from '@proton/utils/clsx'; import { Icon } from '../../../components'; import { getComparatorLabels, getConditionTypeLabels } from '../constants'; import { ConditionComparator, ConditionType, FilterStatement, SimpleFilterModalModel } from '../interfaces'; interface Props { model: SimpleFilterModalModel; toggleOpen: () => void; isOpen: boolean; } const FilterPreviewConditions = ({ isOpen, toggleOpen, model }: Props) => { const { conditions } = model; const conditionsRenderer = useMemo(() => { const conditionsRows = conditions?.map((cond) => { if (cond.type === ConditionType.ATTACHMENTS) { const label = cond.comparator === ConditionComparator.CONTAINS ? c('Label').t`with attachments` : c('Label').t`without attachments`; const attachment = isOpen ? ( <span key={`filter_preview_${label}`} className="inline-flex flex-row flex-align-items-center condition-token mb-2" role="listitem" > <span className="text-ellipsis text-no-decoration" title={label}> {label} </span> </span> ) : ( <strong key={`open_filter_preview_${label}`}>{label}</strong> ); return { element: c('Label').jt`the email was sent ${attachment}`, title: c('Label').t`the email was sent ${label}`, }; } const typeLabel = getConditionTypeLabels(cond.type); const comparatorLabel = getComparatorLabels(cond.comparator); const titleValues = cond?.values?.map((v, i) => { return i > 0 ? ` or ${v}` : v; }); const values = cond?.values?.map((v, i) => { const value = isOpen ? ( <span key={`${v}${i}`} className="inline-flex flex-row flex-align-items-center condition-token mb-2" role="listitem" > <span className="text-ellipsis text-no-decoration" title={v}> {v} </span> </span> ) : ( <strong key={`${v}${i}`}>{v}</strong> ); return i > 0 ? ( <Fragment key={`preview_condition_${v}${i}`}> {` `} {c('Label').t`or`} {` `} {value} </Fragment> ) : ( value ); }); return { element: ( <> {typeLabel?.toLowerCase()} {` `} {comparatorLabel} {` `} {values} </> ), title: `${typeLabel?.toLowerCase()} ${comparatorLabel} ${titleValues}`, }; }); const ifLabel = c('Label').t`If`; const operator = model.statement === FilterStatement.ALL ? c('Label').t`And` : c('Label').t`Or`; const title: string = conditionsRows.reduce((acc, cond, i) => { acc += i === 0 ? ifLabel : ` ${operator.toLowerCase()}`; return `${acc} ${cond.title}`; }, ''); return isOpen ? ( <div className="pt-2"> {conditionsRows.map((cond, i) => ( <div key={`preview-condition-${i}`}> {i === 0 ? ifLabel : operator} {` `} {cond.element} </div> ))} </div> ) : ( <div className="pt-2 max-w-full text-ellipsis" title={title}> {conditionsRows.map((cond, i) => ( <span key={`preview-condition-${i}`}> {i === 0 ? ifLabel : <span className="ml-1">{operator.toLowerCase()}</span>} {` `} {cond.element} </span> ))} </div> ); }, [isOpen]); return ( <div className="border-bottom"> <div className="flex flex-nowrap flex-column md:flex-row align-items-center py-4 gap-4"> <button type="button" className="w-full md:w-1/4 text-left" onClick={toggleOpen}> <Icon name="chevron-down" className={clsx([isOpen && 'rotateX-180'])} /> <span className="ml-2">{c('Label').t`Conditions`}</span> </button> <div className="flex flex-column w-full">{conditionsRenderer}</div> </div> </div> ); }; export default FilterPreviewConditions;
6,237
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/modal/Filtermodal.scss
@import '~@proton/styles/scss/lib'; .mail-filter-modal { // Special case otherwise shortcuts are not properly displayed --size: #{rem(700)}; }
6,238
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/modal/FooterFilterModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import clsx from '@proton/utils/clsx'; import { Errors, SimpleFilterModalModel, Step } from '../interfaces'; interface Props { model: SimpleFilterModalModel; onClose: () => void; onChange: (newModel: SimpleFilterModalModel) => void; loading: boolean; errors: Errors; } const NEXT_STEP = { [Step.NAME]: Step.CONDITIONS, [Step.CONDITIONS]: Step.ACTIONS, [Step.ACTIONS]: Step.PREVIEW, [Step.PREVIEW]: Step.PREVIEW, }; const BACK_STEP = { [Step.NAME]: Step.NAME, [Step.CONDITIONS]: Step.NAME, [Step.ACTIONS]: Step.CONDITIONS, [Step.PREVIEW]: Step.ACTIONS, }; const FooterFilterModal = ({ model, errors, onClose, onChange, loading }: Props) => { const { step } = model; const handleNext = () => { onChange({ ...model, step: NEXT_STEP[step] }); }; const handleBack = () => { onChange({ ...model, step: BACK_STEP[step] }); }; const isNextButtonDisabled = () => { if (step === Step.CONDITIONS) { return !!errors.conditions; } if ([Step.ACTIONS, Step.PREVIEW].includes(step)) { return !!errors.conditions || !!errors.actions; } return loading || !!errors.name; }; return ( <> {step === Step.NAME ? ( <div> <Button shape="outline" className="w-full sm:w-auto" disabled={loading} onClick={onClose}>{c( 'Action' ).t`Cancel`}</Button> </div> ) : ( <div> <Button shape="outline" className="w-full sm:w-auto" disabled={loading} onClick={handleBack}>{c( 'Action' ).t`Back`}</Button> </div> )} <div className="flex"> {step !== Step.PREVIEW && ( <Button shape="outline" disabled={isNextButtonDisabled()} onClick={handleNext} className={clsx(['w-full sm:w-auto mb-2 lg:mb-0', step === Step.ACTIONS && 'sm:mr-4'])} data-testid="filter-modal:next-button" > {step === Step.ACTIONS ? c('Action').t`Preview` : c('Action').t`Next`} </Button> )} {[Step.ACTIONS, Step.PREVIEW].includes(step) && ( <Button color="norm" className="w-full sm:w-auto mb-2 lg:mb-0" disabled={loading || !!errors.name || !!errors.conditions || !!errors.actions} type="submit" >{c('Action').t`Save`}</Button> )} </div> </> ); }; export default FooterFilterModal;
6,239
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/modal/HeaderFilterModal.tsx
import { c } from 'ttag'; import { Breadcrumb } from '../../../components'; import { Errors, SimpleFilterModalModel, Step } from '../interfaces'; interface Props { model: SimpleFilterModalModel; onChange: (newModel: SimpleFilterModalModel) => void; errors: Errors; } const HeaderFilterModal = ({ model, errors, onChange }: Props) => { const list = [ { step: Step.NAME, content: c('Step in filter modal').t`Name` }, { step: Step.CONDITIONS, content: c('Step in filter modal').t`Conditions` }, { step: Step.ACTIONS, content: c('Step in filter modal').t`Actions` }, { step: Step.PREVIEW, content: c('Step in filter modal').t`Preview` }, ]; const getIsDisabled = (index: number) => { const target = list[index]; if (!target) { return false; } const { step } = target; if (step === Step.CONDITIONS && !!errors.name) { return true; } if (step === Step.ACTIONS && (!!errors.name || !!errors.conditions)) { return true; } if (step === Step.PREVIEW && (!!errors.name || !!errors.actions || !!errors.conditions)) { return true; } return false; }; return ( <header> <Breadcrumb onClick={(index) => { const target = list[index]; if (!target) { return; } const { step } = target; onChange({ ...model, step }); }} getIsDisabled={getIsDisabled} current={list.findIndex(({ step }) => step === model.step)} list={list.map(({ content }) => content)} /> </header> ); }; export default HeaderFilterModal;
6,240
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/modal/useFilterConditions.test.ts
import { renderHook } from '@testing-library/react-hooks'; import { Condition } from '../interfaces'; import useFilterConditions from './useFilterConditions'; describe('useFilterConditions', () => { const condition = { id: 'test' } as Condition; const initialConditions = [condition]; const onChangeConditions = jest.fn(); it('should generate an initial condition', () => { const { result } = renderHook(() => useFilterConditions()); expect(result.current.conditions).toHaveLength(1); }); it('should handle initial conditions', () => { const { result } = renderHook(() => useFilterConditions(initialConditions)); expect(result.current.conditions).toEqual(initialConditions); }); it('should add a condition', () => { const { result } = renderHook(() => useFilterConditions(initialConditions, onChangeConditions)); result.current.onAddCondition(); expect(result.current.conditions).toHaveLength(2); expect(onChangeConditions).toHaveBeenCalled(); }); it('should delete a condition', () => { const { result } = renderHook(() => useFilterConditions(initialConditions, onChangeConditions)); result.current.onDeleteCondition(0); expect(result.current.conditions).toHaveLength(0); expect(onChangeConditions).toHaveBeenCalled(); }); it('should update a condition', () => { const { result } = renderHook(() => useFilterConditions(initialConditions, onChangeConditions)); result.current.onUpdateCondition(0, condition); expect(result.current.conditions).toEqual([condition]); expect(onChangeConditions).toHaveBeenCalled(); }); });
6,241
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/modal/useFilterConditions.ts
import { useEffect, useState } from 'react'; import { generateUID } from '@proton/components/helpers'; import { Condition, ConditionComparator, ConditionType } from '../interfaces'; const generateNewCondition = () => ({ type: ConditionType.SUBJECT, comparator: ConditionComparator.CONTAINS, isOpen: true, id: generateUID('condition'), }); const useFilterConditions = ( initialConditions?: Condition[], onChangeConditions?: (conditions: Condition[]) => void ) => { const [conditions, setConditions] = useState<Condition[]>(initialConditions || [generateNewCondition()]); const onAddCondition = () => { setConditions((conditions: Condition[]) => { return [...conditions, { ...generateNewCondition() }]; }); }; const onDeleteCondition = (i: number) => { setConditions((conditions: Condition[]) => { conditions.splice(i, 1); return [...conditions]; }); }; const onUpdateCondition = (index: number, condition: Condition) => { setConditions((conditions: Condition[]) => { conditions[index] = condition; return [...conditions]; }); }; useEffect(() => { onChangeConditions?.(conditions); }, [conditions]); return { conditions, onAddCondition, onDeleteCondition, onUpdateCondition, }; }; export default useFilterConditions;
6,242
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/modal
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/modal/advanced/AdvancedFilterModal.scss
@import '~@proton/styles/scss/lib'; .advanced-filter-modal { // Special case for the Sieve editor --size: #{rem(1200)}; block-size: 100%; .scroll-inner, .scroll-child, .modal-two-content { display: flex; flex-flow: column nowrap; flex: 1 1 auto; } .scroll-inner, .scroll-child { inline-size: 100%; } .react-codemirror2 { flex: 1 1 auto; } .CodeMirror { block-size: 100%; min-block-size: 13em; } }
6,243
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/modal
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/modal/advanced/AdvancedFilterModal.tsx
import { FormEvent, useMemo, useState } from 'react'; import { c } from 'ttag'; import { Href } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { addTreeFilter, checkSieveFilter, updateFilter } from '@proton/shared/lib/api/filters'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { Form, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, useDebounceInput, useModalState, } from '../../../../components'; import { useApi, useApiWithoutResult, useEventManager, useFilters, useNotifications, useUserSettings, } from '../../../../hooks'; import { FILTER_VERSION } from '../../constants'; import { AdvancedSimpleFilterModalModel, ErrorsSieve, Filter } from '../../interfaces'; import { convertModel, sieveTemplates } from '../../utils'; import CloseFilterModal from '../CloseFilterModal'; import FilterNameForm from '../FilterNameForm'; import FooterAdvancedFilterModal from './FooterAdvancedFilterModal'; import SieveForm from './SieveForm'; import './AdvancedFilterModal.scss'; interface Props extends ModalProps { filter?: Filter; } const checkNameErrors = (name: string, filters: Filter[]): string => { if (!name) { return c('Error').t`This field is required`; } const trimmedName = name.trim(); if (filters.find(({ Name }: Filter) => Name.trim() === trimmedName)) { return c('Error').t`Filter with this name already exists`; } return ''; }; const checkSieveErrors = (sieve: string, issuesLength: number): string => { if (!sieve) { return c('Error').t`This field is required`; } if (issuesLength) { return c('Error').t`Invalid Sieve code`; } return ''; }; const AdvancedFilterModal = ({ filter, ...rest }: Props) => { const api = useApi(); const [loading, withLoading] = useLoading(); const [filters = []] = useFilters(); const [userSettings] = useUserSettings(); const { createNotification } = useNotifications(); const { call } = useEventManager(); const [closeFilterModalProps, setCloseFilterModalOpen] = useModalState(); const { onClose } = rest; const isEdit = !!filter?.ID; const title = isEdit ? c('Title').t`Edit Sieve filter` : c('Title').t`Add Sieve filter`; const sieveTemplate = sieveTemplates[filter?.Version || FILTER_VERSION]; const initialModel = { id: filter?.ID, sieve: filter?.Sieve || sieveTemplate || '', name: filter?.Name || '', issues: [], }; const [model, setModel] = useState<AdvancedSimpleFilterModalModel>(initialModel); const sieve = useDebounceInput(model.sieve); const errors = useMemo<ErrorsSieve>(() => { return { name: !model.name || model.name !== initialModel.name ? checkNameErrors(model.name, filters) : '', sieve: checkSieveErrors(model.sieve, model.issues.length), }; }, [model.name, model.sieve, model.issues]); const reqCreate = useApiWithoutResult<{ Filter: Filter }>(addTreeFilter); const reqUpdate = useApiWithoutResult<{ Filter: Filter }>(updateFilter); const createFilter = async (filter: Filter) => { try { const { Filter } = await reqCreate.request(filter); createNotification({ text: c('Notification').t`${Filter.Name} created`, }); } finally { // Some failed request will add the filter but in disabled mode // So we have to refresh the list in both cases await call(); onClose?.(); } }; const editFilter = async (filter: Filter) => { const { Filter } = await reqUpdate.request(filter.ID, filter); await call(); createNotification({ text: c('Filter notification').t`Filter ${Filter.Name} updated`, }); onClose?.(); }; const checkSieve = async () => { const { Issues = [] } = await api(checkSieveFilter({ Version: FILTER_VERSION, Sieve: sieve })); const issues = Issues.length ? Issues : []; setModel({ ...model, issues, }); return issues; }; const handleSubmit = async (event: FormEvent<HTMLFormElement>) => { event.preventDefault(); const issues = await checkSieve(); if (issues.length) { return; } if (isEdit) { await editFilter(convertModel(model, true)); return; } await createFilter(convertModel(model, true)); }; const handleClose = () => { if (model.name === initialModel.name && model.sieve === initialModel.sieve) { return onClose?.(); } setCloseFilterModalOpen(true); }; // translator: full sentence is: To work properly, each filter must contain at least a name and a valid Sieve script. You can learn more about Sieve programming language const link = ( <Href key="more-info-link" href={getKnowledgeBaseUrl('/sieve-advanced-custom-filters')}>{c('Info') .t`learn more about Sieve programming language`}</Href> ); return ( <> <ModalTwo as={Form} onSubmit={(event: FormEvent<HTMLFormElement>) => withLoading(handleSubmit(event))} {...rest} onClose={handleClose} className="advanced-filter-modal" > <ModalTwoHeader title={title} /> <ModalTwoContent> <p className="mb-4"> { // translator: full sentence is: To work properly, each filter must contain at least a name and a valid Sieve script. You can learn more about Sieve programming language c('Info') .jt`To work properly, each filter must contain at least a name and a valid Sieve script. You can ${link}.` } </p> <FilterNameForm model={model} onChange={(newModel) => setModel(newModel as AdvancedSimpleFilterModalModel)} errors={errors} loading={loading} isSieveFilter /> <SieveForm model={model} onChange={setModel} userSettings={userSettings} /> </ModalTwoContent> <ModalTwoFooter> <FooterAdvancedFilterModal errors={errors} onClose={handleClose} loading={loading} /> </ModalTwoFooter> </ModalTwo> <CloseFilterModal {...closeFilterModalProps} handleDiscard={onClose} /> </> ); }; export default AdvancedFilterModal;
6,244
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/modal
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/modal/advanced/FooterAdvancedFilterModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { ErrorsSieve } from '../../interfaces'; interface Props { onClose: () => void; loading: boolean; errors: ErrorsSieve; } const FooterAdvancedFilterModal = ({ errors, onClose, loading }: Props) => { const disabled = loading || !!errors.name; return ( <> <Button shape="outline" disabled={loading} onClick={onClose}>{c('Action').t`Cancel`}</Button> <Button color="norm" disabled={disabled} type="submit">{c('Action').t`Save`}</Button> </> ); }; export default FooterAdvancedFilterModal;
6,245
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/modal
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/modal/advanced/SieveEditor.scss
@import '~@proton/styles/scss/lib'; .CodeMirror-lint-tooltip { &#{&} { z-index: $layer-tooltips; } } .react-codemirror2 { font-size: rem(14); }
6,246
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/modal
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/modal/advanced/SieveEditor.tsx
import { useEffect, useRef } from 'react'; import { Controlled as CodeMirror } from 'react-codemirror2'; import { Editor, EditorChange, EditorConfiguration } from 'codemirror'; import { Annotation, Linter } from 'codemirror/addon/lint/lint'; import 'codemirror/addon/lint/lint'; import 'codemirror/mode/sieve/sieve'; import { normalize } from '../../utils'; import './SieveEditor.scss'; import 'codemirror/addon/lint/lint.css'; import 'codemirror/lib/codemirror.css'; import 'codemirror/theme/base16-dark.css'; interface Props { value: string; issues?: Annotation[]; onChange: (editor: Editor, data: EditorChange, value: string) => void; theme?: string; } let uglyGlobalLintRef: ((content: string) => Annotation[]) | undefined; const clean = normalize(); const customLint: Linter<{}> = (content = '') => { const lint = uglyGlobalLintRef; return lint ? lint(clean(content)) : []; }; const SieveEditor = ({ value, issues = [], onChange, theme }: Props) => { const editorRef = useRef<Editor>(); const options: EditorConfiguration = { mode: 'sieve', lineNumbers: true, lineWrapping: true, readOnly: false, fixedGutter: false, gutters: ['CodeMirror-lint-markers'], lint: { getAnnotations: customLint, }, ...(theme ? { theme } : {}), }; useEffect(() => { /* Ugly hack to avoid broken context with react lifecycle as we can't unregister the hook and we need to have the right API for the hook */ uglyGlobalLintRef = () => issues; return () => { uglyGlobalLintRef = undefined; }; }, [issues]); useEffect(() => { /** * Autorefresh addon does not fix the initial rendering issue correctly * cf. https://codemirror.net/5/doc/manual.html#addon_autorefresh * * We need to manually trigger it manually */ const timeoutId = setTimeout(() => { editorRef.current?.refresh(); }, 500); return () => { clearTimeout(timeoutId); }; }, []); return ( <CodeMirror className="border mt-4" value={value} options={options} onBeforeChange={onChange} editorDidMount={(editor) => { editorRef.current = editor; }} /> ); }; export default SieveEditor;
6,247
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/modal
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/modal/advanced/SieveForm.tsx
import { Suspense, lazy, useMemo } from 'react'; import { Loader } from '@proton/components/components'; import { UserSettings } from '@proton/shared/lib/interfaces'; import { isDarkTheme } from '@proton/shared/lib/themes/helpers'; import { AdvancedSimpleFilterModalModel } from '../../interfaces'; const LazySieveEditor = lazy(() => import(/* webpackChunkName: "SieveEditor" */ './SieveEditor')); interface Props { model: AdvancedSimpleFilterModalModel; onChange: (newModel: AdvancedSimpleFilterModalModel) => void; userSettings: UserSettings; } const SieveForm = ({ model, userSettings, onChange }: Props) => { const theme = useMemo(() => (isDarkTheme() ? 'base16-dark' : ''), [userSettings.Theme]); return ( <Suspense fallback={<Loader size="large" />}> <LazySieveEditor value={model.sieve} issues={model.issues} theme={theme} onChange={(editor, data, sieve) => onChange({ ...model, sieve })} /> </Suspense> ); }; export default SieveForm;
6,248
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/spams/Spams.helpers.tsx
import { c } from 'ttag'; import { ACCENT_COLORS_MAP } from '@proton/shared/lib/colors'; import { SpamItem, SpamListAction, SpamListActionName, SpamLocation } from './Spams.interfaces'; export const isSpamDomain = (item: SpamItem) => 'domain' in item; export const isSpamEmail = (item: SpamItem) => 'email' in item; type ApiCallState = 'success' | 'fail'; export const getNotificationByAction = (action: SpamListActionName, apiCallstate: ApiCallState, item: SpamItem) => { const isDomain = 'domain' in item; const name = isDomain ? item.domain : item.email; const translationsMap: Record<SpamListActionName, Record<ApiCallState, string>> = { block: { fail: isDomain ? c('Domain spam notification').t`${name} failed to move to block list` : c('Email spam notification').t`${name} failed to move to block list`, success: isDomain ? c('Domain spam notification').t`${name} moved to block list` : c('Email spam notification').t`${name} moved to block list`, }, delete: { fail: isDomain ? c('Domain spam notification').t`${name} deletion failed` : c('Email spam notification').t`${name} deletion failed`, success: isDomain ? c('Domain spam notification').t`${name} successfully deleted` : c('Email spam notification').t`${name} successfully deleted`, }, spam: { fail: isDomain ? c('Domain spam notification').t`${name} failed to move to spam list` : c('Email spam notification').t`${name} failed to move to spam list`, success: isDomain ? c('Domain spam notification').t`${name} moved to spam list` : c('Email spam notification').t`${name} moved to spam list`, }, unspam: { fail: isDomain ? c('Domain spam notification').t`${name} failed to move to allow list` : c('Email spam notification').t`${name} failed to move to allow list`, success: isDomain ? c('Domain spam notification').t`${name} moved to allow list` : c('Email spam notification').t`${name} moved to allow list`, }, }; return translationsMap[action][apiCallstate]; }; export type HandleSpamListActionClick = (type: SpamListActionName, item: SpamItem) => void; export const getActionsByLocation = (item: SpamItem, onClick: HandleSpamListActionClick): SpamListAction[] => { const actions: Record<SpamListActionName, SpamListAction> = { block: { name: c('Action').t`Block`, onClick: () => onClick('block', item) }, delete: { name: c('Action').t`Delete`, onClick: () => onClick('delete', item) }, spam: { name: c('Action').t`Spam`, onClick: () => onClick('spam', item) }, unspam: { name: c('Action').t`Allow`, onClick: () => onClick('unspam', item) }, }; switch (item.location) { case 'BLOCKED': return [actions.spam, actions.unspam, actions.delete]; case 'SPAM': return [actions.block, actions.unspam, actions.delete]; case 'NON_SPAM': return [actions.spam, actions.block, actions.delete]; default: throw new Error('Invalid use case'); } }; export const getLabelByLocation = (location: SpamLocation): { name: string; color: string } => { switch (location) { case 'BLOCKED': return { name: c('Label').t`Block`, color: ACCENT_COLORS_MAP.purple.color }; case 'NON_SPAM': return { name: c('Label').t`Allow`, color: ACCENT_COLORS_MAP.reef.color }; case 'SPAM': return { name: c('Label').t`Spam`, color: ACCENT_COLORS_MAP.carrot.color }; default: throw new Error('Invalid use case'); } };
6,249
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/spams/Spams.interfaces.ts
export type SpamNavItem = 'ALL' | SpamLocation; export type SpamLocation = 'SPAM' | 'NON_SPAM' | 'BLOCKED'; interface SpamBase { id: string; location: SpamLocation; } interface SpamEmailItem extends SpamBase { email: string | undefined; } interface SpamDomainItem extends SpamBase { domain: string | undefined; } /** * A spam item can be a domain or an email address */ export type SpamItem = SpamEmailItem | SpamDomainItem; export type SpamListActionName = 'block' | 'delete' | 'spam' | 'unspam'; export type SpamListAction = { name: string; onClick: () => void };
6,250
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/spams/Spams.tsx
import { useEffect, useRef } from 'react'; import { c } from 'ttag'; import { LabelStack, Loader, Pagination, SearchInput, Table, TableBody, TableCell, TableHeader, TableRow, useModalState, } from '@proton/components/components'; import { useErrorHandler, useNotifications } from '@proton/components/hooks'; import useIsMounted from '@proton/hooks/useIsMounted'; import { HandleSpamListActionClick, getActionsByLocation, getLabelByLocation, getNotificationByAction, } from './Spams.helpers'; import { SpamLocation } from './Spams.interfaces'; import SpamsButtonDropdown from './SpamsButtonDropdown'; import SpamsNav from './SpamsNav'; import useSpamApi from './hooks/useSpamApi'; import useSpamState from './hooks/useSpamState'; import SpamModal, { SpamMode } from './modals/SpamModal'; const getActions = (): { type: SpamLocation; getName: () => string }[] => { return [ { type: 'SPAM', getName: () => c('Action').t`Spam` }, { type: 'BLOCKED', getName: () => c('Action').t`Block` }, { type: 'NON_SPAM', getName: () => c('Action').t`Allow` }, ] as { type: SpamLocation; getName: () => string }[]; }; const ELEMENTS_PER_PAGE = 10; interface Props { isOrganization?: boolean; } const Spams = ({ isOrganization }: Props) => { const isMounted = useIsMounted(); const [modalProps, openModal, renderModal] = useModalState(); const { createNotification } = useNotifications(); const { fetchSpams, insertSpam, updateSpam, deleteSpam } = useSpamApi(isOrganization); const errorHandler = useErrorHandler(); const abortFetchSpams = useRef(new AbortController()); const [{ status, list, globalTotal, total, search, display, modal, page }, dispatch] = useSpamState((nextState) => { abortFetchSpams.current?.abort(); abortFetchSpams.current = new AbortController(); void fetchSpams( nextState.display, nextState.search, nextState.page - 1, ELEMENTS_PER_PAGE, abortFetchSpams.current ).then((result) => { if (isMounted()) { dispatch({ type: 'setList', payload: result }); } }); }); const handleMoveSpam: HandleSpamListActionClick = (action, item) => { const actionApiCall = (() => { switch (action) { case 'block': return () => updateSpam(item.id, 'BLOCKED'); case 'delete': return () => deleteSpam(item.id); case 'spam': return () => updateSpam(item.id, 'SPAM'); case 'unspam': return () => updateSpam(item.id, 'NON_SPAM'); default: throw new Error('Action does not exist'); } })(); dispatch({ type: 'loading', payload: true }); actionApiCall() .then(() => { dispatch({ type: 'refetchList' }); createNotification({ text: getNotificationByAction(action, 'success', item), type: 'success', }); }) .catch((e) => { errorHandler(e); createNotification({ text: getNotificationByAction(action, 'fail', item), type: 'error', }); dispatch({ type: 'loading', payload: false }); }); }; const handleInsertSpam = async (type: SpamMode, name: string) => { if (!modal) { return; } await insertSpam(modal, type, name); if (!isMounted()) { return; } dispatch({ type: 'refetchList' }); createNotification({ text: type === 'email' ? c('Email spam notification').t`${name} added` : c('Domain spam notification').t`${name} added`, type: 'success', }); }; useEffect(() => { dispatch({ type: 'fetchList' }); }, []); return ( <> <div className="mb-8"> <SpamsButtonDropdown title={c('Action').t`Add address or domain`} actions={getActions().map(({ getName, type }) => ({ name: getName(), onClick: () => { dispatch({ type: 'setModal', payload: type }); openModal(true); }, }))} buttonProps={{ hasCaret: true, color: 'norm', }} /> </div> {globalTotal > 0 && ( <> <div className="mb-8"> <SearchInput onChange={(nextSearch) => { if (nextSearch !== search) { dispatch({ type: 'setSearch', payload: nextSearch }); } }} placeholder={c('FilterSettings').t`Search list`} /> </div> <SpamsNav selected={display} onChange={(nextDisplay) => dispatch({ type: 'setDisplay', payload: nextDisplay })} /> </> )} {'loading' === status && <Loader size="large" />} {'displayResults' === status && ( <> <Table hasActions responsive="cards"> <TableHeader> <tr> <TableCell type="header">{c('TableHeader').t`Email address or domain`}</TableCell> <TableCell type="header">{c('TableHeader').t`List`}</TableCell> <TableCell type="header">{c('TableHeader').t`Edit`}</TableCell> </tr> </TableHeader> <TableBody> {list.map((item) => ( <TableRow key={item.id}> <TableCell> <span className="text-ellipsis inline-block max-w-full align-bottom" title={'domain' in item ? item.domain : item.email} > {'domain' in item ? item.domain : item.email} </span> </TableCell> <TableCell label={c('TableHeader').t`Marked as`}> <LabelStack labels={[getLabelByLocation(item.location)]} /> </TableCell> <TableCell> <SpamsButtonDropdown title="…" actions={getActionsByLocation(item, handleMoveSpam)} /> </TableCell> </TableRow> ))} </TableBody> </Table> </> )} <div className="text-center"> <Pagination total={total} page={page} limit={ELEMENTS_PER_PAGE} onSelect={(page) => { dispatch({ type: 'setPage', payload: page }); }} onNext={() => { dispatch({ type: 'setPage', payload: page + 1 }); }} onPrevious={() => { dispatch({ type: 'setPage', payload: page - 1 }); }} /> </div> {renderModal && modal && <SpamModal modalProps={modalProps} type={modal} onAdd={handleInsertSpam} />} </> ); }; export default Spams;
6,251
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/spams/SpamsButtonDropdown.tsx
import { useRef, useState } from 'react'; import { Button } from '@proton/atoms'; import { Dropdown, DropdownButton, DropdownMenu, DropdownMenuButton } from '@proton/components/components'; import { DropdownButtonProps } from '@proton/components/components/dropdown/DropdownButton'; import useUid from '@proton/components/hooks/useUid'; import { SpamListAction } from './Spams.interfaces'; interface Props { title: string; actions: SpamListAction[]; buttonProps?: DropdownButtonProps<typeof Button>; } const SpamsButtonDropdown = ({ title, actions, buttonProps }: Props) => { const uid = useUid(); const anchorRef = useRef<HTMLButtonElement>(null); const [isOpen, setIsOpen] = useState(false); return ( <> <DropdownButton as={Button} isOpen={isOpen} onClick={() => setIsOpen(!isOpen)} ref={anchorRef} type="button" {...buttonProps} > {title} </DropdownButton> <Dropdown anchorRef={anchorRef} disableDefaultArrowNavigation id={uid} isOpen={isOpen} onClose={() => setIsOpen(!isOpen)} > <DropdownMenu> {actions.map((action, index) => ( <DropdownMenuButton key={index} className="text-left" onClick={action.onClick}> {action.name} </DropdownMenuButton> ))} </DropdownMenu> </Dropdown> </> ); }; export default SpamsButtonDropdown;
6,252
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/spams/SpamsNav.tsx
import { c } from 'ttag'; import clsx from '@proton/utils/clsx'; import { SpamNavItem } from './Spams.interfaces'; interface Props { onChange: (type: SpamNavItem) => void; selected: SpamNavItem; } const getNav = (): [type: SpamNavItem, getName: () => string][] => { return [ ['ALL', () => c('Navigation').t`All`], ['SPAM', () => c('Navigation').t`Spam`], ['BLOCKED', () => c('Navigation').t`Block`], ['NON_SPAM', () => c('Navigation').t`Allow`], ]; }; const SpamFiltersNav = ({ selected, onChange }: Props) => ( <ul className="unstyled block"> {getNav().map(([type, getName]) => ( <li key={type} onClick={() => onChange(type)} className={clsx([ 'cursor-pointer inline-block border-bottom padding p-4 text-center', selected !== type && 'color-weak', selected === type && 'border-primary text-bold color-norm', ])} > {getName()} </li> ))} </ul> ); export default SpamFiltersNav;
6,253
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/spams
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/spams/hooks/useSpamApi.ts
import { useApi } from '@proton/components/hooks'; import { addIncomingDefault, deleteIncomingDefaults, getIncomingDefaults, updateIncomingDefault, } from '@proton/shared/lib/api/incomingDefaults'; import { addOrgIncomingDefault, deleteOrgIncomingDefaults, getOrgIncomingDefaults, updateOrgIncomingDefault, } from '@proton/shared/lib/api/orgIncomingDefaults'; import { INCOMING_DEFAULTS_LOCATION } from '@proton/shared/lib/constants'; import { IncomingDefault } from '@proton/shared/lib/interfaces'; import { SpamItem, SpamLocation, SpamNavItem } from '../Spams.interfaces'; const LOCATION_BY_TYPE: Record<SpamLocation, number> = { SPAM: INCOMING_DEFAULTS_LOCATION.SPAM, NON_SPAM: INCOMING_DEFAULTS_LOCATION.INBOX, BLOCKED: INCOMING_DEFAULTS_LOCATION.BLOCKED, }; interface IncomingDefaultsApiResults { Code: number; IncomingDefaults: IncomingDefault[]; Total: number; GlobalTotal: number; } interface IncomingDefaultsApiResult { Code: number; IncomingDefault: IncomingDefault; } interface IncomingDefaultsDeleteApiResult { Code: number; Responses: []; } const getHumanReadableLocation = (location: INCOMING_DEFAULTS_LOCATION): SpamLocation => { if (location === LOCATION_BY_TYPE.NON_SPAM) { return 'NON_SPAM'; } if (location === LOCATION_BY_TYPE.SPAM) { return 'SPAM'; } if (location === LOCATION_BY_TYPE.BLOCKED) { return 'BLOCKED'; } throw new Error('location is not valid'); }; export type FetchSpams = ( location: SpamNavItem, search: string | undefined, page: number, limit: number, abortController: AbortController ) => Promise<{ list: SpamItem[]; total: number; globalTotal: number }>; const useSpamApi = (isOrganization: boolean = false) => { const api = useApi(); const fetchSpams: FetchSpams = async (location, search, page, limit, abortController) => { const incomingDefaultParams = { Page: page, Keyword: search, PageSize: limit, Location: location === 'ALL' ? undefined : LOCATION_BY_TYPE[location], }; const result = await api<IncomingDefaultsApiResults>({ ...(isOrganization ? getOrgIncomingDefaults(incomingDefaultParams) : getIncomingDefaults(incomingDefaultParams)), signal: abortController ? abortController.signal : undefined, }); const noResult = !result || !result?.IncomingDefaults || !Array.isArray(result.IncomingDefaults); if (noResult) { return { list: [], total: 0, globalTotal: 0 }; } const nextList: SpamItem[] = result.IncomingDefaults.map((item) => { const base = { id: item.ID, location: getHumanReadableLocation(item.Location) }; if (item.Domain) { return { ...base, domain: item.Domain }; } if (item.Email) { return { ...base, email: item.Email }; } throw new Error('Item is invalid'); }); return { list: nextList, total: result.Total, globalTotal: result.GlobalTotal }; }; const insertSpam = async (location: SpamLocation, type: 'email' | 'domain', name: string) => { const params = { Location: LOCATION_BY_TYPE[location], Domain: type === 'domain' ? name : undefined, Email: type === 'email' ? name : undefined, }; return api<IncomingDefaultsApiResult>( isOrganization ? addOrgIncomingDefault(params) : addIncomingDefault(params) ); }; const updateSpam = async (id: string, nextLocation: SpamLocation) => { const params = { Location: LOCATION_BY_TYPE[nextLocation] }; return api<IncomingDefaultsApiResult>( isOrganization ? updateOrgIncomingDefault(id, params) : updateIncomingDefault(id, params) ); }; const deleteSpam = async (id: string) => { return api<IncomingDefaultsDeleteApiResult>( isOrganization ? deleteOrgIncomingDefaults([id]) : deleteIncomingDefaults([id]) ); }; return { fetchSpams, insertSpam, updateSpam, deleteSpam }; }; export default useSpamApi;
6,254
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/spams
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/spams/hooks/useSpamState.ts
import { Reducer, useCallback, useReducer } from 'react'; import { SpamItem, SpamLocation, SpamNavItem } from '../Spams.interfaces'; interface State { display: SpamNavItem; search: string | undefined; list: SpamItem[]; total: number; globalTotal: number; modal: SpamLocation | undefined; status: 'loading' | 'noResults' | 'displayResults'; page: number; } type Action = | { type: 'setDisplay'; payload: State['display'] } | { type: 'setSearch'; payload: State['search'] } | { type: 'setList'; payload: Pick<State, 'list' | 'total' | 'globalTotal'> } | { type: 'setModal'; payload: SpamLocation } | { type: 'refetchList' } | { type: 'loading'; payload: boolean } | { type: 'fetchList' } | { type: 'setPage'; payload: number }; const INITIAL_PAGE = 1; const reducer = (fetchSpams: (args: State) => void) => (state: State, action: Action): State => { switch (action.type) { case 'fetchList': fetchSpams(state); return state; case 'setList': const nextStatus: State['status'] = action.payload.list.length ? 'displayResults' : 'noResults'; return { ...state, globalTotal: action.payload.globalTotal, list: action.payload.list, status: nextStatus, total: action.payload.total, }; case 'setSearch': if (state.search === action.payload) { return state; } const setSearchState: State = { ...state, list: [], page: INITIAL_PAGE, search: action.payload || undefined, status: 'loading', total: 0, }; fetchSpams(setSearchState); return setSearchState; case 'setDisplay': if (state.display === action.payload) { return state; } const setDisplayState: State = { ...state, display: action.payload, list: [], page: INITIAL_PAGE, status: 'loading', total: 0, }; fetchSpams(setDisplayState); return setDisplayState; case 'setModal': return { ...state, modal: action.payload }; case 'refetchList': const refetchListState: State = { ...state, list: [], status: 'loading', total: 0, }; fetchSpams(refetchListState); return refetchListState; case 'loading': return { ...state, status: // eslint-disable-next-line no-nested-ternary action.payload === true ? 'loading' : state.list.length > 0 ? 'displayResults' : 'noResults', }; case 'setPage': const setPageState: State = { ...state, list: [], page: action.payload, status: 'loading', total: 0, }; fetchSpams(setPageState); return setPageState; default: throw new Error('unknown action'); } }; const useSpamState = (fetchSpams: (args: State) => void) => { // In order to avoid double calls we need to memoize this callback const reducerMemoized = useCallback(reducer(fetchSpams), []); return useReducer<Reducer<State, Action>>(reducerMemoized, { display: 'ALL', globalTotal: 0, list: [], modal: undefined, page: INITIAL_PAGE, search: '', status: 'loading', total: 0, }); }; export default useSpamState;
6,255
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/spams
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/spams/modals/SpamModal.tsx
import { useEffect, useRef, useState } from 'react'; import { c } from 'ttag'; import { Button, Input } from '@proton/atoms'; import { validateEmailAddress } from '@proton/shared/lib/helpers/email'; import { isDomain } from '@proton/shared/lib/helpers/validators'; import { Field, Form, Label, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, Radio, Row, } from '../../../../components'; import { SpamLocation } from '../Spams.interfaces'; export type SpamMode = 'email' | 'domain'; interface Props { type: SpamLocation; onAdd: (mode: SpamMode, name: string) => void; modalProps: ModalProps; } const SpamModal = ({ type, onAdd, modalProps }: Props) => { const I18N: Record<SpamLocation, string> = { BLOCKED: c('Title').t`Add to block list`, NON_SPAM: c('Title').t`Add to allow list`, SPAM: c('Title').t`Add to spam list`, }; const inputElementRef = useRef<HTMLInputElement>(null); const [mode, setMode] = useState<SpamMode>('email'); const [email, setEmail] = useState(''); const [domain, setDomain] = useState(''); const [error, setError] = useState(''); const [isValid, setIsValid] = useState(false); const { onClose } = modalProps; const handleSubmit = () => { onClose?.(); onAdd(mode, domain || email); }; useEffect(() => { setDomain(''); setEmail(''); setIsValid(false); inputElementRef.current?.focus(); }, [mode]); useEffect(() => { if ((mode === 'email' && email === '') || (mode === 'domain' && domain === '')) { setError(''); setIsValid(false); } if (mode === 'email' && email !== '') { const isValidEmail = email && validateEmailAddress(email); if (isValidEmail) { setError(''); setIsValid(true); } else { setError(c('Error').t`Invalid email address`); setIsValid(false); } } if (mode === 'domain' && domain !== '') { const isValidDomain = domain && isDomain(domain); if (isValidDomain) { setError(''); setIsValid(true); } else { setError(c('Error').t`Invalid domain`); setIsValid(false); } } }, [email, domain]); return ( <ModalTwo size="large" as={Form} onSubmit={handleSubmit} {...modalProps} data-testid="spam-modal"> <ModalTwoHeader title={I18N[type]} /> <ModalTwoContent> <Row> <Label id="descAddressType">{c('Label').t`Address type`}</Label> <Field className="mt-1 pt-0.5"> <Radio id="email-mode" checked={mode === 'email'} onChange={() => setMode('email')} className="mr-4" name="filterMode" aria-describedby="descAddressType" > {c('Label').t`Email`} </Radio> <Radio id="domain-mode" checked={mode === 'domain'} onChange={() => setMode('domain')} name="filterMode" aria-describedby="descAddressType" > {c('Label').t`Domain`} </Radio> </Field> </Row> <Row> <Label htmlFor={`${mode}Input`}> {mode === 'email' ? c('Label').t`Email` : c('Label').t`Domain`} </Label> <Input id={`${mode}Input`} ref={inputElementRef} value={mode === 'email' ? email : domain} type={mode === 'email' ? 'email' : 'text'} placeholder={ mode === 'email' ? c('Placeholder').t`example@domain.com` : c('Placeholder').t`domain.com` } onChange={(e) => (mode === 'email' ? setEmail(e.target.value) : setDomain(e.target.value))} error={error} /> </Row> </ModalTwoContent> <ModalTwoFooter> <Button onClick={onClose}>{c('Action').t`Cancel`}</Button> <Button color="norm" type="submit" disabled={!isValid}> {mode === 'email' ? c('Action').t`Add address` : c('Action').t`Add domain`} </Button> </ModalTwoFooter> </ModalTwo> ); }; export default SpamModal;
6,256
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/spams
petrpan-code/ProtonMail/WebClients/packages/components/containers/filters/spams/test/Spams.test.tsx
import React from 'react'; import { fireEvent, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { clearAll, render } from '@proton/components/containers/contacts/tests/render'; import Spams from '../Spams'; import SpamModal from '../modals/SpamModal'; describe('Spams - Incoming defaults', () => { afterEach(() => { clearAll(); }); it('Should display an empty list', () => { render(<Spams />); expect(screen.getByRole('button', { name: 'Add address or domain' })).toBeInTheDocument(); expect(screen.queryByRole('table')).not.toBeInTheDocument(); }); it('Should display blocked email modal', async () => { render(<Spams />); fireEvent.click(screen.getByRole('button', { name: 'Add address or domain' })); fireEvent.click(screen.getByRole('button', { name: 'Block' })); const modal = await screen.findByTestId('spam-modal'); expect(modal).toHaveTextContent('Add to block list'); }); it('Should display blocked email modal with organization', async () => { render(<Spams isOrganization />); fireEvent.click(screen.getByRole('button', { name: 'Add address or domain' })); fireEvent.click(screen.getByRole('button', { name: 'Block' })); const modal = await screen.findByTestId('spam-modal'); expect(modal).toHaveTextContent('Add to block list'); }); it('Modal submission should return correct values', async () => { const mockedSubmit = jest.fn(); const EMAIL = 'homer@simpsons.fr'; render( <SpamModal modalProps={{ open: true, }} type="SPAM" onAdd={mockedSubmit} /> ); const emailInputs = screen.getAllByLabelText('Email'); const emailRadio = emailInputs[0]; const emailInput = emailInputs[1]; await userEvent.click(emailRadio); expect(emailRadio).toBeChecked(); await userEvent.type(emailInput, EMAIL); // Dom actually got 2 button called "add address" at this moment. The submit one is the second const submitButton = screen.getByRole('button', { name: 'Add address' }); await userEvent.click(submitButton); const submitCalls = mockedSubmit.mock.calls.length; const submitCallsMode = mockedSubmit.mock.calls[0][0]; const submitCallsEmail = mockedSubmit.mock.calls[0][1]; expect(submitCalls).toBe(1); expect(submitCallsMode).toBe('email'); expect(submitCallsEmail).toBe(EMAIL); }); });
6,257
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/forceRefresh/Provider.tsx
import { ReactNode, forwardRef, useCallback, useImperativeHandle, useState } from 'react'; import Context, { RefreshFn } from './context'; interface Props { children: ReactNode; } const ForceRefreshProvider = forwardRef<RefreshFn, Props>(({ children }: Props, ref) => { const [state, setState] = useState(1); const refresh = useCallback(() => setState((i) => i + 1), []); useImperativeHandle(ref, () => refresh); return ( <Context.Provider value={refresh} key={state}> {children} </Context.Provider> ); }); export default ForceRefreshProvider;
6,258
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/forceRefresh/context.ts
import { createContext } from 'react'; import noop from '@proton/utils/noop'; export type RefreshFn = () => void; export default createContext<RefreshFn>(noop);
6,259
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/forgotUsername/MinimalForgotUsernameContainer.tsx
import { useState } from 'react'; import { Link, useHistory } from 'react-router-dom'; import { c } from 'ttag'; import { useLoading } from '@proton/hooks'; import { requestUsername } from '@proton/shared/lib/api/reset'; import { Alert, EmailInput, PrimaryButton } from '../../components'; import { useApi, useNotifications } from '../../hooks'; const MinimalForgotUsernameContainer = () => { const api = useApi(); const history = useHistory(); const [loading, withLoading] = useLoading(); const { createNotification } = useNotifications(); const [email, setEmail] = useState(''); const handleSubmit = async () => { await api(requestUsername({ Email: email })); createNotification({ text: c('Success') .t`If you entered a valid notification email we will send you an email with your usernames in the next minute`, }); history.push('/login'); }; return ( <form onSubmit={(e) => { e.preventDefault(); withLoading(handleSubmit()); }} > <Alert className="mb-4">{c('Info') .t`Enter your recovery email address, and we'll send you your username(s). (This is usually the email address you provided during signup.)`}</Alert> <div className="mb-4"> <EmailInput name="email" autoFocus autoCapitalize="off" autoCorrect="off" id="email" placeholder={c('Placeholder').t`Email`} value={email} onChange={({ target }) => setEmail(target.value)} required /> </div> <div className="flex flex-nowrap flex-justify-space-between mb-4"> <Link to="/login">{c('Link').t`Back to login`}</Link> <PrimaryButton loading={loading} type="submit">{c('Action').t`Email me my username(s)`}</PrimaryButton> </div> </form> ); }; export default MinimalForgotUsernameContainer;
6,260
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/forward/AttachmentsCondition.spec.tsx
import { render } from '@testing-library/react'; import { Condition, ConditionComparator } from '../filters/interfaces'; import AttachmentsCondition from './AttachmentsCondition'; describe('AttachmentsCondition', () => { const condition1 = { comparator: ConditionComparator.DOES_NOT_CONTAIN } as Condition; const condition2 = { comparator: ConditionComparator.CONTAINS } as Condition; const onUpdate = jest.fn(); describe('when we click on the "With attachment" radio', () => { it('should call the onUpdate function with the right condition', () => { const { getByText } = render(<AttachmentsCondition index={0} condition={condition1} onUpdate={onUpdate} />); getByText('With attachment').click(); expect(onUpdate).toHaveBeenCalledWith({ comparator: ConditionComparator.CONTAINS }); }); }); describe('when we click on the "Without attachment" radio', () => { it('should call the onUpdate function with the right condition', () => { const { getByText } = render(<AttachmentsCondition index={0} condition={condition2} onUpdate={onUpdate} />); getByText('Without attachment').click(); expect(onUpdate).toHaveBeenCalledWith({ comparator: ConditionComparator.DOES_NOT_CONTAIN }); }); }); });
6,261
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/forward/AttachmentsCondition.tsx
import { c } from 'ttag'; import { Radio } from '../../components'; import { Condition, ConditionComparator } from '../filters/interfaces'; interface Props { index: number; condition: Condition; onUpdate: (condition: Condition) => void; } const AttachmentsCondition = ({ index, condition, onUpdate }: Props) => { const withAttachment = condition?.comparator === ConditionComparator.CONTAINS; const toggleAttachment = () => { onUpdate({ ...condition, comparator: withAttachment ? ConditionComparator.DOES_NOT_CONTAIN : ConditionComparator.CONTAINS, }); }; return ( <div className="flex w-full mb-6 on-mobile-flex-column"> <Radio id={`condition-${index}-with-attachment`} name={`attachment-condition-${index}`} className="inline-flex flex-align-items-center mr-4 mb-2 md:mb-0" checked={withAttachment} onChange={toggleAttachment} > {c('email_forwarding_2023: Label').t`With attachment`} </Radio> <Radio id={`condition-${index}-without-attachment`} name={`attachment-condition-${index}`} className="inline-flex flex-align-items-center" checked={!withAttachment} onChange={toggleAttachment} > {c('email_forwarding_2023: Label').t`Without attachment`} </Radio> </div> ); }; export default AttachmentsCondition;
6,262
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/forward/ConfirmDeleteForwarding.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { ModalProps, Prompt } from '../../components'; interface Props { reActivateE2EE: boolean; modalProps: ModalProps; onDelete: () => Promise<void>; onClose: () => void; } const ConfirmDeleteForwarding = ({ reActivateE2EE, onDelete, onClose, modalProps }: Props) => { const [loading, withLoading] = useLoading(); return ( <Prompt title={c('email_forwarding_2023: Title').t`Delete forwarding?`} buttons={[ <Button color="danger" loading={loading} onClick={() => withLoading(onDelete())}>{c( 'email_forwarding_2023: Action' ).t`Delete`}</Button>, <Button autoFocus onClick={onClose}>{c('email_forwarding_2023: Action').t`Cancel`}</Button>, ]} {...modalProps} > <p> <span className="mr-1">{c('email_forwarding_2023: Prompt') .t`Forwarding to the destination address will end.`}</span> {reActivateE2EE ? ( <span>{c('email_forwarding_2023: Prompt') .t`End-to-end encryption will be re-enabled for the sender address.`}</span> ) : null} </p> </Prompt> ); }; export default ConfirmDeleteForwarding;
6,263
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/forward/ForwardCondition.spec.tsx
import { render } from '@testing-library/react'; import { useNotifications } from '../../hooks'; import { Condition, ConditionType, FilterStatement } from '../filters/interfaces'; import ForwardCondition from './ForwardCondition'; jest.mock('@proton/components/hooks/useNotifications'); const mockUseNotifications = useNotifications as jest.MockedFunction<any>; mockUseNotifications.mockReturnValue({ createNotification: jest.fn(), }); describe('ForwardCondition', () => { const setup = ({ index = 0, type = ConditionType.SUBJECT } = {}) => { const onDelete = jest.fn(); const onUpdate = jest.fn(); const onChangeStatement = jest.fn(); const condition = { type, values: ['token1', 'token2'] } as Condition; const statement = FilterStatement.ALL; const utils = render( <ForwardCondition statement={statement} condition={condition} displayDelete index={index} onDelete={onDelete} onUpdate={onUpdate} onChangeStatement={onChangeStatement} /> ); return { ...utils, onDelete, onUpdate, onChangeStatement }; }; describe('when we click on the "Delete" button', () => { it('should call the onDelete function', () => { const { getByTestId, onDelete } = setup(); getByTestId('forward:condition:delete-button_0').click(); expect(onDelete).toHaveBeenCalled(); }); }); test('only the first condition should have an "If" label', () => { const { getByText } = setup(); expect(getByText('If')).toBeInTheDocument(); const { getByTestId } = setup({ index: 1 }); expect(getByTestId('forward:condition:ifor-select_1')).toBeInTheDocument(); }); describe('when condition type is "Attachments"', () => { it('should render the attachment inputs', () => { const { getByText } = setup({ type: ConditionType.ATTACHMENTS }); expect(getByText('With attachment')).toBeInTheDocument(); expect(getByText('Without attachment')).toBeInTheDocument(); }); }); });
6,264
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/forward/ForwardCondition.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { Icon, Option, SelectTwo, Tooltip } from '../../components'; import { COMPARATORS, TYPES, getComparatorLabels, getConditionTypeLabels } from '../filters/constants'; import { Condition, ConditionComparator, ConditionType, FilterStatement } from '../filters/interfaces'; import AttachmentsCondition from './AttachmentsCondition'; import InputCondition from './InputCondition'; interface Props { condition: Condition; index: number; displayDelete: boolean; onDelete: () => void; onUpdate: (condition: Condition) => void; statement: FilterStatement; onChangeStatement: (statement: FilterStatement) => void; validator?: (validations: string[]) => string; } const ForwardCondition = ({ index, displayDelete, condition, onDelete, onUpdate, onChangeStatement, validator, statement, }: Props) => { const isFirst = index === 0; const typeOptions = TYPES.filter( ({ value }) => value !== ConditionType.RECIPIENT && value !== ConditionType.SELECT ).map(({ value }) => { return { text: getConditionTypeLabels(value), value }; }); const comparatorOptions = COMPARATORS.map(({ value }) => ({ text: getComparatorLabels(value), value, })); return ( <> <span id={`condition_${index}`} className="sr-only">{c('email_forwarding_2023: Placeholder') .t`Condition:`}</span> {isFirst ? ( <label className="text-bold mb-0.5" id={`ifor_${index}`} aria-describedby={`condition_${index}`}>{c( 'Condition label' ).t`If`}</label> ) : ( <div className="inline-block text-bold mb-0.5"> <SelectTwo className="w-auto" unstyled value={statement} onChange={({ value }) => onChangeStatement(value as FilterStatement)} id={`ifor_${index}`} aria-describedby={`condition_${index}`} data-testid={`forward:condition:ifor-select_${index}`} > <Option value={FilterStatement.ALL} title={c('email_forwarding_2023: Label').t`And`} /> <Option value={FilterStatement.ANY} title={c('email_forwarding_2023: Label').t`Or`} /> </SelectTwo> </div> )} <div className="flex flex-nowrap gap-2"> <div className="flex-item-fluid flex gap-4"> <div className="flex-item-fluid flex flex-wrap on-mobile-flex-column gap-4"> <div className="flex-item-fluid"> <SelectTwo value={condition.type} onChange={({ value }) => onUpdate({ ...condition, type: value as ConditionType })} aria-describedby={`condition_${index} ifor_${index}`} id={`conditiontype_${index}`} > {typeOptions.map(({ text, value }) => ( <Option key={value} value={value} title={text} /> ))} </SelectTwo> </div> <div className="flex-item-fluid"> {[ConditionType.SUBJECT, ConditionType.SENDER, ConditionType.RECIPIENT].includes( condition.type ) && ( <SelectTwo value={condition.comparator} onChange={({ value }) => { onUpdate({ ...condition, comparator: value as ConditionComparator, }); }} aria-describedby={`condition_${index} ifor_${index} conditiontype_${index}`} id={`conditioncomparator_${index}`} > {comparatorOptions.map(({ text, value }) => ( <Option key={value} value={value} title={text} /> ))} </SelectTwo> )} </div> </div> {condition.type === ConditionType.ATTACHMENTS ? ( <AttachmentsCondition index={index} condition={condition} onUpdate={onUpdate} /> ) : ( <InputCondition index={index} validator={validator} condition={condition} onUpdate={onUpdate} /> )} </div> {displayDelete && ( <div className="flex-item-noshrink w-custom" style={{ '--w-custom': '3em' }}> <Tooltip title={c('email_forwarding_2023: Action').t`Delete this condition`}> <Button data-testid={`forward:condition:delete-button_${index}`} className="ml-auto flex" shape="ghost" onClick={() => onDelete()} icon > <Icon name="trash" alt={c('email_forwarding_2023: Action').t`Delete this condition`} /> </Button> </Tooltip> </div> )} </div> </> ); }; export default ForwardCondition;
6,265
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/forward/ForwardConditions.spec.tsx
import { render } from '@testing-library/react'; import { useNotifications } from '../../hooks'; import { ConditionComparator, ConditionType, FilterStatement } from '../filters/interfaces'; import ForwardConditions from './ForwardConditions'; jest.mock('@proton/components/hooks/useNotifications'); const mockUseNotifications = useNotifications as jest.MockedFunction<any>; mockUseNotifications.mockReturnValue({ createNotification: jest.fn(), }); describe('ForwardConditions', () => { const setup = ({ statement = FilterStatement.ALL } = {}) => { const onChangeStatement = jest.fn(); const onChangeConditions = jest.fn(); const validator = jest.fn(); const conditions = [ { id: 'id1', type: ConditionType.SENDER, values: ['token1', 'token2'], comparator: ConditionComparator.CONTAINS, isOpen: true, }, { id: 'id2', type: ConditionType.SUBJECT, values: ['token1', 'token2'], comparator: ConditionComparator.CONTAINS, isOpen: true, }, { id: 'id3', type: ConditionType.SUBJECT, values: ['token1', 'token2'], comparator: ConditionComparator.CONTAINS, isOpen: true, }, { id: 'id4', type: ConditionType.SUBJECT, values: ['token1', 'token2'], comparator: ConditionComparator.CONTAINS, isOpen: true, }, ]; const utils = render( <ForwardConditions statement={statement} onChangeConditions={onChangeConditions} onChangeStatement={onChangeStatement} validator={validator} conditions={conditions} /> ); return { ...utils, conditions, onChangeStatement, onChangeConditions }; }; describe('when the statement change', () => { it('should change all statements', () => { const { getAllByText, conditions } = setup(); const numberOfSelect = conditions.length - 1; expect(getAllByText('And')).toHaveLength(numberOfSelect); expect(setup({ statement: FilterStatement.ANY }).getAllByText('Or')).toHaveLength(numberOfSelect); }); }); test('only the first condition should have an "If" label', () => { const { getAllByText } = setup(); expect(getAllByText('If')).toHaveLength(1); }); it('should have 1 delete button per condition', () => { const { getAllByTestId, conditions } = setup(); expect(getAllByTestId('forward:condition:delete-button_', { exact: false })).toHaveLength(conditions.length); }); });
6,266
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/forward/ForwardConditions.tsx
import { c } from 'ttag'; import { UnderlineButton } from '../../components'; import { Condition, FilterStatement } from '../filters/interfaces'; import useFilterConditions from '../filters/modal/useFilterConditions'; import ForwardCondition from './ForwardCondition'; interface Props { conditions?: Condition[]; statement: FilterStatement; onChangeStatement: (statement: FilterStatement) => void; validator: (validations: string[]) => string; onChangeConditions: (conditions: Condition[]) => void; } const ForwardConditions = ({ statement, onChangeStatement, validator, conditions: initialConditions, onChangeConditions, }: Props) => { const { conditions, onAddCondition, onDeleteCondition, onUpdateCondition } = useFilterConditions( initialConditions, onChangeConditions ); return ( <> <div className="mb-2"> {conditions.map((condition, index) => ( <ForwardCondition index={index} key={condition.id} condition={condition} displayDelete onDelete={() => onDeleteCondition(index)} onUpdate={(newCondition) => onUpdateCondition(index, newCondition)} statement={statement} validator={validator} onChangeStatement={onChangeStatement} /> ))} </div> {conditions.every((c) => !c.error) && ( <UnderlineButton onClick={onAddCondition}>{c('email_forwarding_2023: Action') .t`Add condition`}</UnderlineButton> )} </> ); }; export default ForwardConditions;
6,267
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/forward/ForwardModal.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Button, Href } from '@proton/atoms'; import { CryptoProxy, PrivateKeyReference, PublicKeyReference } from '@proton/crypto/lib'; import useLoading from '@proton/hooks/useLoading'; import { SetupForwardingParameters, setupForwarding, updateForwardingFilter } from '@proton/shared/lib/api/forwardings'; import { ADDRESS_RECEIVE, ENCRYPTION_CONFIGS, ENCRYPTION_TYPES, RECIPIENT_TYPES } from '@proton/shared/lib/constants'; import { emailValidator, requiredValidator } from '@proton/shared/lib/helpers/formValidators'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { Address, DecryptedKey, ForwardingType, OutgoingAddressForwarding } from '@proton/shared/lib/interfaces'; import { addAddressKeysProcess, getEmailFromKey, splitKeys } from '@proton/shared/lib/keys'; import illustration from '@proton/styles/assets/img/illustrations/forward-email-verification.svg'; import { useKTVerifier } from '..'; import { Form, Icon, InputFieldTwo, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, Option, SelectTwo, useFormErrors, } from '../../components'; import { useAddressFlags, useAddresses, useApi, useAuthentication, useEventManager, useGetAddressKeys, useGetPublicKeysForInbox, useGetUser, useGetUserKeys, useNotifications, } from '../../hooks'; import { Condition, FilterStatement } from '../filters/interfaces'; import ForwardConditions from './ForwardConditions'; import { getInternalParameters, getSieveParameters, getSieveTree } from './helpers'; interface Props extends ModalProps { forward?: OutgoingAddressForwarding; } enum Step { Setup, Verification, } interface Model { step: Step; loading?: boolean; edit?: boolean; addressID: string; isExternal?: boolean; isInternal?: boolean; forwardeeEmail: string; forwardeePublicKey?: PublicKeyReference; forwarderKey?: PrivateKeyReference; forwarderAddressKeys?: DecryptedKey[]; keySupportE2EEForwarding?: boolean; keyErrors?: string[]; statement: FilterStatement; conditions: Condition[]; } const getTitle = (model: Model) => { const { step } = model; if (step === Step.Setup) { return c('email_forwarding_2023: Title').t`Set up forwarding`; } if (step === Step.Verification) { return c('email_forwarding_2023: Title').t`Request confirmation`; } return ''; }; const getDefaultModel = ({ forward, addresses }: { addresses: Address[]; forward?: OutgoingAddressForwarding }) => { const isEditing = !!forward; const { statement, conditions } = isEditing ? getSieveParameters(forward.Filter?.Tree || []) : { statement: FilterStatement.ALL, conditions: [] }; const [firstAddress] = addresses; return { step: Step.Setup, addressID: isEditing ? forward.ForwarderAddressID : firstAddress?.ID || '', forwardeeEmail: isEditing ? forward.ForwardeeEmail : '', statement, conditions, }; }; const encryptionConfig = ENCRYPTION_CONFIGS[ENCRYPTION_TYPES.CURVE25519]; const ForwardModal = ({ forward, onClose, ...rest }: Props) => { const isEditing = !!forward; const [addresses = []] = useAddresses(); const api = useApi(); const getUser = useGetUser(); const silentApi = <T,>(config: any) => api<T>({ ...config, silence: true }); const { keyTransparencyVerify, keyTransparencyCommit } = useKTVerifier(silentApi, getUser); const authentication = useAuthentication(); const getPublicKeysForInbox = useGetPublicKeysForInbox(); const getAddressKeys = useGetAddressKeys(); const getUserKeys = useGetUserKeys(); const { createNotification } = useNotifications(); const { call } = useEventManager(); const { validator, onFormSubmit } = useFormErrors(); const [loading, withLoading] = useLoading(); const filteredAddresses = addresses.filter(({ Receive }) => Receive === ADDRESS_RECEIVE.RECEIVE_YES); const [model, setModel] = useState<Model>(getDefaultModel({ forward, addresses: filteredAddresses })); const inputsDisabled = model.loading || isEditing; const forwarderAddress = addresses.find(({ ID }) => ID === model.addressID); const forwarderEmail = forwarderAddress?.Email || ''; const addressFlags = useAddressFlags(forwarderAddress); const boldForwardeeEmail = <strong key="forwardee-email">{model.forwardeeEmail}</strong>; const boldForwarderEmail = <strong key="forwarder-email">{forwarderEmail}</strong>; const learnMoreLink = ( <Href href={getKnowledgeBaseUrl('/email-forwarding')}>{c('email_forwarding_2023: Link').t`Learn more`}</Href> ); const generateNewKey = async () => { if (!forwarderAddress) { throw new Error('No address'); } if (!model.forwarderAddressKeys) { throw new Error('No forwarder address keys'); } const userKeys = await getUserKeys(); const [newKey] = await addAddressKeysProcess({ api, userKeys, encryptionConfig, addresses, address: forwarderAddress, addressKeys: model.forwarderAddressKeys, keyPassword: authentication.getPassword(), keyTransparencyVerify, }); const { privateKey: forwarderKey } = newKey; const [forwarderAddressKeys] = await Promise.all([ getAddressKeys(model.addressID), keyTransparencyCommit(userKeys), ]); return { forwarderKey, forwarderAddressKeys, }; }; const handleEdit = async () => { if (isEditing) { await api( updateForwardingFilter( forward.ID, getSieveTree({ conditions: model.conditions, statement: model.statement, email: model.forwardeeEmail, }), forward.Filter?.Version || 2 ) ); await call(); onClose?.(); createNotification({ text: c('email_forwarding_2023: Success').t`Changes saved` }); } }; const handleSetup = async () => { const [forwarderAddressKeys, forwardeeKeysConfig] = await Promise.all([ getAddressKeys(model.addressID), getPublicKeysForInbox({ email: model.forwardeeEmail }), ]); // Abort the setup if e.g. the given address is internal but does not exist const apiErrors = forwardeeKeysConfig.Errors || []; if (apiErrors.length > 0) { apiErrors.forEach((error: string) => { createNotification({ text: error, type: 'error' }); }); return; } const isInternal = forwardeeKeysConfig.RecipientType === RECIPIENT_TYPES.TYPE_INTERNAL; const isExternal = forwardeeKeysConfig.RecipientType === RECIPIENT_TYPES.TYPE_EXTERNAL; const { privateKeys } = splitKeys(forwarderAddressKeys); const [forwarderKey] = privateKeys; const keySupportE2EEForwarding = await CryptoProxy.doesKeySupportE2EEForwarding({ forwarderKey }); let forwardeePublicKey: PublicKeyReference | undefined; let forwardeeEmailFromPublicKey: string | undefined; if (isInternal) { // While forwarding could be setup with generic catch-all addresses, we disallow this as the catch-all address case is triggered // if the forwardee is a private subuser who has yet to login (i.e.has missing keys). // In such case, the admin public keys are temporarily returned instead, meaning that E2EE forwarding will be (permanently) setup with the admin, rather // than the subuser, which is undesirable. if (forwardeeKeysConfig.isCatchAll) { createNotification({ text: 'This address cannot be used as forwarding recipient', type: 'error' }); return; } const [primaryForwardeeKey] = forwardeeKeysConfig.publicKeys; forwardeePublicKey = await CryptoProxy.importPublicKey({ armoredKey: primaryForwardeeKey.armoredKey, }); forwardeeEmailFromPublicKey = getEmailFromKey(forwardeePublicKey); } setModel({ ...model, forwarderAddressKeys, keySupportE2EEForwarding, keyErrors: forwardeeKeysConfig.Errors, forwarderKey, forwardeePublicKey, forwardeeEmail: forwardeeEmailFromPublicKey || model.forwardeeEmail, isExternal, isInternal, step: Step.Verification, }); }; const handleVerification = async () => { // Disable encryption if the email is external if (model.isExternal && addressFlags?.encryptionDisabled === false) { await addressFlags?.handleSetAddressFlags(true, addressFlags?.expectSignatureDisabled); } const params: SetupForwardingParameters = { ForwarderAddressID: model.addressID, ForwardeeEmail: model.forwardeeEmail, Type: model.isInternal ? ForwardingType.InternalEncrypted : ForwardingType.ExternalUnencrypted, Tree: getSieveTree({ conditions: model.conditions, statement: model.statement, email: model.forwardeeEmail, }), Version: forward?.Filter?.Version || 2, }; let requireNewKey = false; if (model.isInternal && forwarderAddress?.Keys && model.forwardeePublicKey && model.forwarderKey) { let forwarderKey = model.forwarderKey; if (!model.keySupportE2EEForwarding) { // The forwarding material generation will fail if the address key is e.g. RSA instead of ECC 25519 // So we generate automatically a new ECC 25519 key for the address const newProperties = await generateNewKey(); // Save the new key in case something goes wrong later setModel({ ...model, ...newProperties, }); forwarderKey = newProperties.forwarderKey; } const { activationToken, forwardeeKey, proxyInstances } = await getInternalParameters( forwarderKey, [{ email: model.forwardeeEmail, name: model.forwardeeEmail }], model.forwardeePublicKey ); params.ForwardeePrivateKey = forwardeeKey; params.ActivationToken = activationToken; params.ProxyInstances = proxyInstances; } await api(setupForwarding(params)); await call(); onClose?.(); createNotification({ text: c('email_forwarding_2023: Success').t`Email sent to ${model.forwardeeEmail}.` }); if (requireNewKey) { createNotification({ text: c('email_forwarding_2023: Success') .t`A new encryption key has been generated for ${forwarderEmail}.`, }); } }; const handleSubmit = async () => { if (loading || !onFormSubmit()) { return; } if (isEditing) { return handleEdit(); } if (model.step === Step.Setup) { return handleSetup(); } if (model.step === Step.Verification) { return handleVerification(); } }; const handleBack = () => { setModel({ ...model, step: Step.Setup }); }; return ( <ModalTwo as={Form} onClose={onClose} onSubmit={() => withLoading(handleSubmit())} onReset={() => { onClose?.(); }} {...rest} > <ModalTwoHeader title={getTitle(model)} /> <ModalTwoContent> {model.step === Step.Setup && ( <> <InputFieldTwo id="from-select" as={SelectTwo} label={c('email_forwarding_2023: Label').t`Forward from`} value={model.addressID} onValue={(value: unknown) => setModel({ ...model, addressID: value as string })} disabled={inputsDisabled} disabledOnlyField={inputsDisabled} autoFocus > {filteredAddresses.map(({ ID, Email }) => ( <Option title={Email} key={ID} value={ID}> {Email} </Option> ))} </InputFieldTwo> <InputFieldTwo id="to-input" label={c('email_forwarding_2023: Label').t`Forward to`} placeholder={c('email_forwarding_2023: Placeholder').t`Enter email address`} disabled={inputsDisabled} disabledOnlyField={inputsDisabled} readOnly={isEditing} type="email" error={validator([ requiredValidator(model.forwardeeEmail), emailValidator(model.forwardeeEmail), ])} value={model.forwardeeEmail} onValue={(value: string) => setModel({ ...model, forwardeeEmail: value })} required /> <hr className="my-4" /> <ForwardConditions conditions={model.conditions} statement={model.statement} validator={validator} onChangeStatement={(newStatement) => setModel({ ...model, statement: newStatement })} onChangeConditions={(newConditions) => setModel({ ...model, conditions: newConditions })} /> </> )} {model.step === Step.Verification && ( <> <div className="text-center"> <img src={illustration} alt="" /> <p>{c('email_forwarding_2023: Info') .jt`A confirmation email will be sent to ${boldForwardeeEmail}`}</p> <p>{c('email_forwarding_2023: Info') .t`Forwarding to this address will become active once the recipient accepts the forwarding.`}</p> </div> {model.isExternal ? ( <div className="border rounded-lg p-4 flex flex-nowrap flex-align-items-center mb-3"> <Icon name="exclamation-circle" className="flex-item-noshrink color-danger" /> <p className="text-sm color-weak flex-item-fluid pl-4 my-0"> {c('email_forwarding_2023: Info') .jt`Forwarding to an address without end-to-end encryption will disable end-to-end encryption for your ${boldForwarderEmail} address, but zero-access encryption remains enabled. ${learnMoreLink}`} </p> </div> ) : null} {model.isExternal || model.keySupportE2EEForwarding ? null : ( <div className="border rounded-lg p-4 flex flex-nowrap flex-align-items-center mb-3"> <Icon name="exclamation-circle" className="flex-item-noshrink color-danger" /> <p className="text-sm color-weak flex-item-fluid pl-4 my-0"> {c('email_forwarding_2023: Info') .jt`A new encryption key will be generated for ${boldForwarderEmail}.`} </p> </div> )} {model?.keyErrors?.length ? ( <div className="border rounded-lg p-4 flex flex-nowrap flex-align-items-center"> <Icon name="exclamation-circle" className="flex-item-noshrink color-danger" /> <p className="text-sm color-weak flex-item-fluid pl-4 my-0"> {model.keyErrors.join(' ')} </p> </div> ) : null} </> )} </ModalTwoContent> <ModalTwoFooter> {model.step === Step.Setup && ( <> <Button disabled={loading} type="reset">{c('email_forwarding_2023: Action').t`Cancel`}</Button> <Button loading={loading} color="norm" type="submit"> {isEditing ? c('email_forwarding_2023: Action').t`Save` : c('email_forwarding_2023: Action').t`Next`} </Button> </> )} {model.step === Step.Verification && ( <> <Button onClick={handleBack}>{c('email_forwarding_2023: Action').t`Back`}</Button> <Button loading={loading} color="norm" type="submit">{c('email_forwarding_2023: Action') .t`Send confirmation email`}</Button> </> )} </ModalTwoFooter> </ModalTwo> ); }; export default ForwardModal;
6,268
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/forward/ForwardSection.tsx
import { useEffect, useMemo, useState } from 'react'; import { useLocation } from 'react-router'; import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { Href } from '@proton/atoms/Href'; import useIncomingAddressForwarding from '@proton/components/hooks/useIncomingAddressForwarding'; import useOutgoingAddressForwardings from '@proton/components/hooks/useOutgoingAddressForwardings'; import { APP_UPSELL_REF_PATH, MAIL_UPSELL_PATHS, UPSELL_COMPONENT } from '@proton/shared/lib/constants'; import { getUpsellRef } from '@proton/shared/lib/helpers/upsell'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import isTruthy from '@proton/utils/isTruthy'; import { MailUpsellButton, Tabs, UpsellModal, useModalState, useModalTwo } from '../../components'; import { useAddresses, useUser } from '../../hooks'; import { SettingsParagraph, SettingsSection, SettingsSectionWide } from '../account'; import { useFlag } from '../unleash'; import ForwardModal from './ForwardModal'; import IncomingForwardTable from './IncomingForwardTable'; import OutgoingForwardTable from './OutgoingForwardTable'; import { getChainedForwardingEmails } from './helpers'; const ForwardSection = () => { const location = useLocation(); const hash = location.hash; const [user] = useUser(); const [addresses = [], loadingAddresses] = useAddresses(); const isEmailForwardingEnabled = useFlag('EmailForwarding'); const [incomingAddressForwardings = [], loadingIncomingAddressForwardings] = useIncomingAddressForwarding(); const [outgoingAddressForwardings = [], loadingOutgoingAddressForwardings] = useOutgoingAddressForwardings(); const isIncomingTableAvailable = incomingAddressForwardings.length > 0; const isOutgoingTableAvailable = isEmailForwardingEnabled && outgoingAddressForwardings.length > 0; const chainedEmails = useMemo(() => { if ( incomingAddressForwardings.length === 0 || outgoingAddressForwardings.length === 0 || addresses.length === 0 ) { return []; } return getChainedForwardingEmails(incomingAddressForwardings, outgoingAddressForwardings, addresses); }, [incomingAddressForwardings, outgoingAddressForwardings, addresses]); const [activeTab, setActiveTab] = useState(0); const [upsellModalProps, handleUpsellModalDisplay, renderUpsellModal] = useModalState(); const [forwardModal, showModal] = useModalTwo(ForwardModal); const upsellRef = getUpsellRef({ app: APP_UPSELL_REF_PATH.MAIL_UPSELL_REF_PATH, component: UPSELL_COMPONENT.MODAL, feature: MAIL_UPSELL_PATHS.FORWARD_EMAILS, isSettings: true, }); // Focus incoming tab if hash is #forward useEffect(() => { if (hash === '#forward' && isIncomingTableAvailable && isOutgoingTableAvailable) { setActiveTab(1); // Incoming tab is second location.hash = ''; } }, [hash, isIncomingTableAvailable, isOutgoingTableAvailable]); return ( <SettingsSectionWide className="no-scroll"> <SettingsSection> <SettingsParagraph> <span> {c('email_forwarding_2023: Info').t`Automatically forward emails to another email address.`} </span> <br /> <Href href={getKnowledgeBaseUrl('/email-forwarding')}>{c('email_forwarding_2023: Link') .t`Learn more`}</Href> </SettingsParagraph> {isEmailForwardingEnabled ? ( <div className="mb-4"> {user.hasPaidMail ? ( <Button color="norm" onClick={() => showModal(true)}>{c('email_forwarding_2023: Action') .t`Add forwarding rule`}</Button> ) : ( <MailUpsellButton onClick={() => handleUpsellModalDisplay(true)} text={c('email_forwarding_2023: Action').t`Set up email forwarding`} /> )} </div> ) : null} <Tabs tabs={[ isOutgoingTableAvailable && { title: c('email_forwarding_2023: Incoming forwarding tab name').t`From me`, content: ( <OutgoingForwardTable addresses={addresses} forwardings={outgoingAddressForwardings} chainedEmails={chainedEmails} loading={loadingAddresses && loadingIncomingAddressForwardings} user={user} /> ), }, isIncomingTableAvailable && { title: c('email_forwarding_2023: Outgoing forwarding tab name').t`To me`, content: ( <IncomingForwardTable addresses={addresses} forwardings={incomingAddressForwardings} chainedEmails={chainedEmails} loading={loadingAddresses && loadingOutgoingAddressForwardings} /> ), }, ].filter(isTruthy)} value={activeTab} onChange={setActiveTab} /> </SettingsSection> {forwardModal} {renderUpsellModal && ( <UpsellModal title={c('email_forwarding_2023: Title').t`Automatically forward emails to other accounts`} description={c('email_forwarding_2023: Description') .t`Unlock email forwarding to easily manage incoming information and more premium features when you upgrade.`} modalProps={upsellModalProps} upsellRef={upsellRef} features={[ 'more-storage', 'more-email-addresses', 'unlimited-folders-and-labels', 'custom-email-domains', ]} /> )} </SettingsSectionWide> ); }; export default ForwardSection;
6,269
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/forward/ForwardStatus.spec.tsx
import { render } from '@testing-library/react'; import { ForwardingState, OutgoingAddressForwarding } from '@proton/shared/lib/interfaces'; import ForwardStatus from './ForwardStatus'; describe('ForwardStatus', () => { const setup = (state: ForwardingState) => { const utils = render(<ForwardStatus forward={{ State: state } as OutgoingAddressForwarding} />); return { ...utils }; }; describe('when forward is pending', () => { it('should render a pending badge', () => { const { getByText } = setup(ForwardingState.Pending); expect(getByText('Pending')).toBeInTheDocument(); }); }); describe('when forward is active', () => { it('should render an active badge', () => { const { getByText } = setup(ForwardingState.Active); expect(getByText('Active')).toBeInTheDocument(); }); }); describe('when forward is outdated', () => { it('should render an outdated badge', () => { const { getByText } = setup(ForwardingState.Outdated); expect(getByText('Outdated')).toBeInTheDocument(); }); }); describe('when forward is paused', () => { it('should render a paused badge', () => { const { getByText } = setup(ForwardingState.Paused); expect(getByText('Paused')).toBeInTheDocument(); }); }); describe('when forward is rejected', () => { it('should render a rejected badge', () => { const { getByText } = setup(ForwardingState.Rejected); expect(getByText('Declined')).toBeInTheDocument(); }); }); });
6,270
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/forward/ForwardStatus.tsx
import { c } from 'ttag'; import { ForwardingState, IncomingAddressForwarding, OutgoingAddressForwarding } from '@proton/shared/lib/interfaces'; import { Badge } from '../../components'; interface Props { forward: IncomingAddressForwarding | OutgoingAddressForwarding; } const ForwardStatus = ({ forward }: Props) => { if (forward.State === ForwardingState.Pending) { return ( <Badge type="origin" tooltip={c('email_forwarding_2023: Info') .t`Forwardee is invited and needs to accept/reject the invitation or update`} >{c('email_forwarding_2023: Status').t`Pending`}</Badge> ); } if (forward.State === ForwardingState.Active) { return ( <Badge type="success" tooltip={c('email_forwarding_2023: Info').t`Forwarding is active`}>{c( 'email_forwarding_2023: Status' ).t`Active`}</Badge> ); } if (forward.State === ForwardingState.Outdated) { return ( <Badge type="warning" tooltip={c('email_forwarding_2023: Info').t`Please update your forwarding keys`}>{c( 'email_forwarding_2023: Status' ).t`Outdated`}</Badge> ); } if (forward.State === ForwardingState.Paused) { return ( <Badge type="origin" tooltip={c('email_forwarding_2023: Info').t`The forwarding is temporarily paused`}>{c( 'email_forwarding_2023: Status' ).t`Paused`}</Badge> ); } if (forward.State === ForwardingState.Rejected) { return ( <Badge type="origin" tooltip={c('email_forwarding_2023: Info').t`The forwardee rejected the forwarding request`} >{c('email_forwarding_2023: Status').t`Declined`}</Badge> ); } return null; }; export default ForwardStatus;
6,271
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/forward/IncomingForwardActions.spec.tsx
import { fireEvent, render } from '@testing-library/react'; import { rejectForwarding } from '@proton/shared/lib/api/forwardings'; import { Address, ForwardingState, IncomingAddressForwarding } from '@proton/shared/lib/interfaces'; import { applyHOCs, withApi, withAuthentication, withCache, withConfig, withEventManager } from '@proton/testing'; import { useApi, useGetAddressKeys, useGetMailSettings, useGetUserKeys, useNotifications, useUser } from '../../hooks'; import IncomingForwardActions from './IncomingForwardActions'; jest.mock('@proton/components/hooks/useApi'); const mockedUseApi = useApi as jest.MockedFunction<typeof useApi>; jest.mock('@proton/components/hooks/useUserKeys'); const mockUseGetUserKeys = useGetUserKeys as jest.MockedFunction<any>; mockUseGetUserKeys.mockReturnValue(jest.fn()); jest.mock('@proton/components/hooks/useUser'); const mockedUseUser = useUser as jest.MockedFunction<typeof useUser>; mockedUseUser.mockReturnValue([{}] as any); jest.mock('@proton/components/hooks/useGetAddressKeys'); const mockUseGetAddressKeys = useGetAddressKeys as jest.MockedFunction<any>; mockUseGetAddressKeys.mockReturnValue(jest.fn()); jest.mock('@proton/components/hooks/useNotifications'); const mockUseNotifications = useNotifications as jest.MockedFunction<any>; mockUseNotifications.mockReturnValue({ createNotification: jest.fn(), }); jest.mock('@proton/components/hooks/useMailSettings'); const mockUseMailSettings = useGetMailSettings as jest.MockedFunction<any>; mockUseMailSettings.mockReturnValue(jest.fn()); const IncomingAddressForwardingContext = applyHOCs( withCache(), withApi(), withEventManager(), withConfig(), withAuthentication() )(IncomingForwardActions); describe('IncomingForwardActions', () => { const setup = ({ State = ForwardingState.Pending } = {}) => { const mockApi = jest.fn(); mockedUseApi.mockReturnValue(mockApi); const forward = { ID: 'id', ForwardeeAddressID: 'id', ForwarderEmail: 'email', ForwardingKeys: [ { PrivateKey: 'privateKey', ActivationToken: 'token', }, ], State, } as IncomingAddressForwarding; const addresses = [ { ID: 'id', Email: 'email', }, ] as Address[]; const utils = render(<IncomingAddressForwardingContext forward={forward} addresses={addresses} />); fireEvent.click(utils.getByTitle('Open actions dropdown')); return { ...utils, forward, mockApi }; }; describe('when incoming forwarding is pending', () => { it('should show accept and decline buttons', () => { const { getByText } = setup(); expect(getByText('Accept')).toBeInTheDocument(); expect(getByText('Decline')).toBeInTheDocument(); }); }); describe('when we click "Decline"', () => { it('should call the api', () => { const { getByText, mockApi, forward } = setup(); fireEvent.click(getByText('Decline')); expect(mockApi).toHaveBeenCalledWith(rejectForwarding(forward.ID)); }); }); });
6,272
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/forward/IncomingForwardActions.tsx
import { c } from 'ttag'; import useLoading from '@proton/hooks/useLoading'; import { deleteForwarding, rejectForwarding } from '@proton/shared/lib/api/forwardings'; import { Address, ForwardingState, IncomingAddressForwarding } from '@proton/shared/lib/interfaces'; import isTruthy from '@proton/utils/isTruthy'; import { useKTVerifier } from '..'; import { DropdownActions } from '../../components'; import { useApi, useEventManager, useGetAddressKeys, useGetUser, useGetUserKeys, useNotifications } from '../../hooks'; import useVerifyOutboundPublicKeys from '../keyTransparency/useVerifyOutboundPublicKeys'; import { acceptIncomingForwarding } from './helpers'; interface Props { forward: IncomingAddressForwarding; addresses: Address[]; } const IncomingForwardActions = ({ forward, addresses }: Props) => { const api = useApi(); const [loading, withLoading] = useLoading(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const getUserKeys = useGetUserKeys(); const getUser = useGetUser(); const verifyOutboundPublicKeys = useVerifyOutboundPublicKeys(); const silentApi = <T,>(config: any) => api<T>({ ...config, silence: true }); const { keyTransparencyVerify, keyTransparencyCommit } = useKTVerifier(silentApi, getUser); const address = addresses.find(({ ID }) => ID === forward.ForwardeeAddressID); const getAddressKeys = useGetAddressKeys(); const isPending = forward.State === ForwardingState.Pending; const isActive = forward.State === ForwardingState.Active; const isRejected = forward.State === ForwardingState.Rejected; const hasForwardingKeys = !!forward.ForwardingKeys?.length; const handleAccept = async () => { if (!address) { throw new Error('No address'); } const [userKeys, addressKeys] = await Promise.all([getUserKeys(), getAddressKeys(address.ID)]); await acceptIncomingForwarding({ api, userKeys, addressKeys, address, forward, keyTransparencyVerify, keyTransparencyCommit, verifyOutboundPublicKeys, }); await call(); createNotification({ text: c('email_forwarding_2023: Success').t`Forwarding accepted` }); }; const handleDecline = async () => { await api(rejectForwarding(forward.ID)); await call(); createNotification({ text: c('email_forwarding_2023: Success').t`Forwarding declined` }); }; const handleDelete = async () => { await api(deleteForwarding(forward.ID)); await call(); createNotification({ text: c('email_forwarding_2023: Success').t`Forwarding deleted` }); }; const list = [ isPending && address && hasForwardingKeys && { text: c('email_forwarding_2023: Action').t`Accept`, onClick: () => { void withLoading(handleAccept()); }, }, isPending && { text: c('email_forwarding_2023: Action').t`Decline`, onClick: async () => { void withLoading(handleDecline()); }, }, (isActive || isRejected) && { text: c('email_forwarding_2023: Action').t`Delete`, onClick: async () => { void withLoading(handleDelete()); }, }, ].filter(isTruthy); return <DropdownActions list={list} size="small" loading={loading} />; }; export default IncomingForwardActions;
6,273
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/forward/IncomingForwardTable.spec.tsx
import { render } from '@testing-library/react'; import { useUser } from '@proton/components/hooks'; import { Address, ForwardingState, ForwardingType } from '@proton/shared/lib/interfaces'; import { applyHOCs, withApi, withAuthentication, withCache, withConfig, withEventManager, withNotifications, } from '@proton/testing'; import IncomingForwardTable from './IncomingForwardTable'; jest.mock('@proton/components/hooks/useUser'); const mockedUseUser = useUser as jest.MockedFunction<typeof useUser>; mockedUseUser.mockReturnValue([{}] as any); const IncomingForwardTableContext = applyHOCs( withApi(), withEventManager(), withCache(), withNotifications(), withConfig(), withAuthentication() )(IncomingForwardTable); describe('IncomingForwardTable', () => { const setup = () => { const addresses = [ { ID: 'addressID', Email: 'forwardeeEmail', }, ] as Address[]; const chainedEmails = ['']; const forwardings = [ { ID: 'id', ForwardeeAddressID: 'addressID', ForwarderEmail: 'forwarderEmail', CreateTime: 0, Type: ForwardingType.InternalEncrypted, State: ForwardingState.Active, Filter: null, }, ]; const utils = render( <IncomingForwardTableContext forwardings={forwardings} addresses={addresses} chainedEmails={chainedEmails} /> ); return { ...utils }; }; describe('when we display incoming address forwarding', () => { it('should show forwarder email address', () => { const { getByText } = setup(); expect(getByText('forwarderEmail')).toBeInTheDocument(); }); it('should show forwardee email address', () => { const { getByText } = setup(); expect(getByText('forwardeeEmail')).toBeInTheDocument(); }); }); });
6,274
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/forward/IncomingForwardTable.tsx
import { c } from 'ttag'; import { Address, IncomingAddressForwarding } from '@proton/shared/lib/interfaces'; import { Table, TableBody, TableCell, TableHeader, TableHeaderCell, TableRow } from '../../components'; import ForwardStatus from './ForwardStatus'; import IncomingForwardActions from './IncomingForwardActions'; import WarningChainedForwarding from './WarningChainedForwarding'; interface Props { addresses: Address[]; loading?: boolean; forwardings: IncomingAddressForwarding[]; chainedEmails: string[]; } const IncomingForwardTable = ({ addresses, loading, forwardings, chainedEmails }: Props) => { return ( <Table responsive="cards" hasActions={!!forwardings.length}> <TableHeader> <TableRow> <TableHeaderCell>{c('email_forwarding_2023: Header').t`From`}</TableHeaderCell> <TableHeaderCell>{c('email_forwarding_2023: Header').t`To`}</TableHeaderCell> <TableHeaderCell className="w-custom" style={{ '--w-custom': '11em' }}>{c( 'email_forwarding_2023: Header' ).t`Status`}</TableHeaderCell> <TableHeaderCell className="w-custom" style={{ '--w-custom': '9em' }}>{c( 'email_forwarding_2023: Header' ).t`Actions`}</TableHeaderCell> </TableRow> </TableHeader> <TableBody loading={loading} colSpan={4}> {forwardings.length === 0 && ( <TableRow> <TableCell colSpan={4} className="text-center">{c('email_forwarding_2023: Info') .t`No incoming forwarding rules`}</TableCell> </TableRow> )} {forwardings.map((forward) => { const from = forward.ForwarderEmail; const toAddress = addresses.find(({ ID }) => ID === forward.ForwardeeAddressID); if (toAddress === undefined) { return null; } const to = toAddress.Email; return ( <TableRow key={forward.ID}> <TableCell label={c('email_forwarding_2023: Header').t`From`}> <div className="text-ellipsis" title={from}> {from} </div> </TableCell> <TableCell label={c('email_forwarding_2023: Header').t`To`}> <div className="text-ellipsis"> <WarningChainedForwarding chainedEmails={chainedEmails} forwardEmail={to} /> <span title={to}>{to}</span> </div> </TableCell> <TableCell label={c('email_forwarding_2023: Header').t`Status`}> <ForwardStatus forward={forward} /> </TableCell> <TableCell> <IncomingForwardActions forward={forward} addresses={addresses} /> </TableCell> </TableRow> ); })} </TableBody> </Table> ); }; export default IncomingForwardTable;
6,275
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/forward/InputCondition.spec.tsx
import { fireEvent, render } from '@testing-library/react'; import { useNotifications } from '../../hooks'; import { Condition } from '../filters/interfaces'; import InputCondition from './InputCondition'; jest.mock('@proton/components/hooks/useNotifications'); const mockCreateNotification = jest.fn(); const mockUseNotifications = useNotifications as jest.MockedFunction<any>; mockUseNotifications.mockReturnValue({ createNotification: mockCreateNotification, }); describe('InputCondition', () => { const setup = () => { const condition = { values: ['token1'], } as Condition; const onUpdate = jest.fn(); const utils = render(<InputCondition index={0} condition={condition} onUpdate={onUpdate} />); const input = utils.getByRole('textbox'); const removeButton = utils.getByTitle('Remove “token1”'); return { ...utils, removeButton, input, onUpdate, condition }; }; describe('when we submit the input', () => { it('should add a token and clear the input', () => { const { input, onUpdate, condition } = setup(); fireEvent.change(input, { target: { value: 'token2' } }); expect(input).toHaveValue('token2'); fireEvent.keyDown(input, { key: 'Enter', code: 'Enter' }); expect(onUpdate).toHaveBeenCalledWith({ ...condition, values: ['token1', 'token2'] }); expect(input).toHaveValue(''); }); it('should only add non existing token', () => { const { input } = setup(); fireEvent.change(input, { target: { value: 'token1' } }); fireEvent.keyDown(input, { key: 'Enter', code: 'Enter' }); expect(input).toHaveValue(''); expect(mockCreateNotification).toHaveBeenCalledWith({ text: 'Token already exists', type: 'error', }); }); it('should not add empty token', () => { const { input, onUpdate, condition } = setup(); fireEvent.change(input, { target: { value: '' } }); fireEvent.keyDown(input, { key: 'Enter', code: 'Enter' }); expect(onUpdate).not.toHaveBeenCalledWith({ ...condition, values: ['token1', ''] }); }); }); describe('when we blur the input', () => { it('should add a token and clear the input', () => { const { input, onUpdate, condition } = setup(); fireEvent.change(input, { target: { value: 'token2' } }); expect(input).toHaveValue('token2'); fireEvent.blur(input); expect(onUpdate).toHaveBeenCalledWith({ ...condition, values: ['token1', 'token2'] }); expect(input).toHaveValue(''); }); }); describe('when we remove a token', () => { it('should remove the token', () => { const { removeButton, onUpdate, condition } = setup(); fireEvent.click(removeButton); expect(onUpdate).toHaveBeenCalledWith({ ...condition, values: [] }); }); }); });
6,276
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/forward/InputCondition.tsx
import { KeyboardEvent, useState } from 'react'; import { c } from 'ttag'; import { InputFieldTwo } from '../../components'; import { useNotifications } from '../../hooks'; import { Condition } from '../filters/interfaces'; import TokensCondition from './TokensCondition'; interface Props { index: number; condition: Condition; onUpdate: (condition: Condition) => void; validator?: (validations: string[]) => string; } const InputCondition = ({ index, validator, condition, onUpdate }: Props) => { const { createNotification } = useNotifications(); const [inputValue, setInputValue] = useState(''); const noTokens = !condition.values || condition.values.length === 0; const error = noTokens && validator ? validator([c('email_forwarding_2023: Error').t`Condition incomplete, please add a token`]) : undefined; const onAddNewToken = () => { const values = condition.values || []; const clearedInputValue = inputValue.trim(); if (!clearedInputValue.length) { return; } if (values.includes(clearedInputValue)) { createNotification({ text: c('email_forwarding_2023: Error').t`Token already exists`, type: 'error' }); } else { values.push(clearedInputValue); onUpdate({ ...condition, values }); } setInputValue(''); }; const onRemoveToken = (i: number) => { const values = condition.values || []; const newValues = values.filter((_, index) => index !== i); onUpdate({ ...condition, values: newValues }); }; return ( <> <span id={`conditionvalue_${index}`} className="sr-only">{c('email_forwarding_2023: Placeholder') .t`Type text or keyword for this condition:`}</span> <InputFieldTwo onValue={setInputValue} value={inputValue} dense error={error} placeholder={c('email_forwarding_2023: Placeholder').t`Type text or keyword`} aria-describedby={`conditionvalue_${index} ifor_${index} conditiontype_${index} conditioncomparator_${index}`} id={`conditionvalue_${index}`} onKeyDown={(event: KeyboardEvent<HTMLInputElement>) => { if (event.key === 'Enter') { event.preventDefault(); onAddNewToken(); } }} onBlur={() => { if (inputValue) { onAddNewToken(); } }} /> <TokensCondition condition={condition} onRemove={onRemoveToken} /> </> ); }; export default InputCondition;
6,277
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/forward/OutgoingForwardActions.tsx
import { c } from 'ttag'; import { deleteForwarding, pauseForwarding, resendForwardingInvitation, resumeForwarding, } from '@proton/shared/lib/api/forwardings'; import { Address, ForwardingState, ForwardingType, OutgoingAddressForwarding, UserModel, } from '@proton/shared/lib/interfaces'; import isTruthy from '@proton/utils/isTruthy'; import { DropdownActions, useModalState, useModalTwo } from '../../components'; import { useActiveBreakpoint, useAddressFlags, useApi, useEventManager, useGetAddressKeys, useGetPublicKeysForInbox, useNotifications, } from '../../hooks'; import ConfirmDeleteForwarding from './ConfirmDeleteForwarding'; import ForwardModal from './ForwardModal'; import { enableForwarding, isLastOutgoingNonE2EEForwarding } from './helpers'; interface Props { forward: OutgoingAddressForwarding; user: UserModel; forwardings: OutgoingAddressForwarding[]; addresses: Address[]; } const OutgoingForwardActions = ({ user, forward, addresses, forwardings }: Props) => { const isPending = forward.State === ForwardingState.Pending; const isActive = forward.State === ForwardingState.Active; const isPaused = forward.State === ForwardingState.Paused; const isOutdated = forward.State === ForwardingState.Outdated; const isRejected = forward.State === ForwardingState.Rejected; const sentSuccessMessage = c('email_forwarding_2023: Success').t`Email sent to ${forward.ForwardeeEmail}`; const isInternal = forward.Type === ForwardingType.InternalEncrypted; const isExternal = forward.Type === ForwardingType.ExternalUnencrypted; const address = addresses.find((address) => address.ID === forward.ForwarderAddressID) as Address; const isLast = isLastOutgoingNonE2EEForwarding(forward, forwardings); const pointToProton = address?.ProtonMX === true; // the domain's record point to Proton servers const reActivateE2EE = pointToProton && isLast; const api = useApi(); const addressFlags = useAddressFlags(address); const getPublicKeysForInbox = useGetPublicKeysForInbox(); const getAddressKeys = useGetAddressKeys(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const [forwardModal, showModal] = useModalTwo(ForwardModal); const [confirmModalProps, setConfirmModalOpen, renderConfirmModal] = useModalState(); const handleDeleteForwarding = async () => { await api(deleteForwarding(forward.ID)); // Re-enable E2EE for this address if deleting last outgoing forwarding if (reActivateE2EE && addressFlags && addressFlags.encryptionDisabled) { await addressFlags.handleSetAddressFlags(false, addressFlags.expectSignatureDisabled); } await call(); setConfirmModalOpen(false); createNotification({ text: 'Forwarding deleted' }); }; const list = [ user.hasPaidMail && { text: c('email_forwarding_2023: Action').t`Edit conditions`, onClick: () => { void showModal({ forward }); }, }, user.hasPaidMail && isInternal && (isOutdated || isRejected) && { text: isOutdated ? c('email_forwarding_2023: Action').t`Re-enable` : c('email_forwarding_2023: Action').t`Request confirmation`, onClick: async () => { const [forwarderAddressKeys, forwardeePublicKeys] = await Promise.all([ getAddressKeys(forward.ForwarderAddressID), getPublicKeysForInbox({ email: forward.ForwardeeEmail }), ]); await enableForwarding({ api, forwarderAddressKeys, forwardeePublicKeys, forward, }); await call(); createNotification({ text: sentSuccessMessage }); }, }, user.hasPaidMail && isExternal && isRejected && { text: c('email_forwarding_2023: Action').t`Request confirmation`, onClick: async () => { await api(resendForwardingInvitation(forward.ID)); await call(); createNotification({ text: sentSuccessMessage }); }, }, user.hasPaidMail && isExternal && isPending && { text: c('email_forwarding_2023: Action').t`Re-send confirmation email`, onClick: async () => { await api(resendForwardingInvitation(forward.ID)); await call(); createNotification({ text: sentSuccessMessage }); }, }, user.hasPaidMail && isActive && { text: c('email_forwarding_2023: Action').t`Pause`, onClick: async () => { await api(pauseForwarding(forward.ID)); await call(); createNotification({ text: c('email_forwarding_2023: Success').t`Forwarding paused` }); }, }, user.hasPaidMail && isPaused && { text: c('email_forwarding_2023: Action').t`Resume`, onClick: async () => { await api(resumeForwarding(forward.ID)); await call(); createNotification({ text: c('email_forwarding_2023: Success').t`Forwarding resumed` }); }, }, { text: c('email_forwarding_2023: Action').t`Delete`, onClick: () => { setConfirmModalOpen(true); }, }, ].filter(isTruthy); const { isDesktop } = useActiveBreakpoint(); return ( <> <DropdownActions iconName={isDesktop ? 'three-dots-vertical' : undefined} list={list} size="small" shape="ghost" /> {forwardModal} {renderConfirmModal ? ( <ConfirmDeleteForwarding modalProps={confirmModalProps} onDelete={handleDeleteForwarding} onClose={() => setConfirmModalOpen(false)} reActivateE2EE={reActivateE2EE} /> ) : null} </> ); }; export default OutgoingForwardActions;
6,278
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/forward/OutgoingForwardTable.spec.tsx
import { render } from '@testing-library/react'; import { useAddresses, useAddressesKeys } from '@proton/components/hooks'; import { Address, ForwardingState, ForwardingType, UserModel } from '@proton/shared/lib/interfaces'; import { applyHOCs, mockUseUser, withApi, withAuthentication, withCache, withConfig, withEventManager, withNotifications, } from '@proton/testing'; import OutgoingForwardTable from './OutgoingForwardTable'; const OutgoingForwardTableContext = applyHOCs( withApi(), withEventManager(), withCache(), withNotifications(), withConfig(), withAuthentication() )(OutgoingForwardTable); jest.mock('@proton/components/hooks/useAddresses'); const mockUseAddresses = useAddresses as jest.MockedFunction<any>; jest.mock('@proton/components/hooks/useAddressesKeys'); const mockUserAddressesKeys = useAddressesKeys as jest.MockedFunction<any>; describe('OutgoingForwardTable', () => { beforeEach(() => { const mockAddresses = [{ ID: 'AddressID' } as Address]; const mockAddressesKeys = [{}]; mockUseUser(); mockUseAddresses.mockReturnValue([mockAddresses, false]); mockUserAddressesKeys.mockReturnValue(mockAddressesKeys); }); const setup = () => { const addresses = [ { ID: 'addressID', Email: 'forwarderEmail', }, ] as Address[]; const chainedEmails = ['']; const user = {} as UserModel; const forwardings = [ { ID: 'id', ForwarderAddressID: 'addressID', ForwardeeEmail: 'forwardeeEmail', State: ForwardingState.Active, CreateTime: 0, Type: ForwardingType.InternalEncrypted, Filter: null, }, ]; const utils = render( <OutgoingForwardTableContext user={user} forwardings={forwardings} addresses={addresses} chainedEmails={chainedEmails} /> ); return { ...utils }; }; describe('when we display outgoing address forwarding', () => { it('should show forwarder email address', () => { const { getByText } = setup(); expect(getByText('forwarderEmail')).toBeInTheDocument(); }); it('should show forwardee email address', () => { const { getByText } = setup(); expect(getByText('forwardeeEmail')).toBeInTheDocument(); }); }); });
6,279
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/forward/OutgoingForwardTable.tsx
import { c } from 'ttag'; import { Address, OutgoingAddressForwarding, UserModel } from '@proton/shared/lib/interfaces'; import { Table, TableBody, TableCell, TableHeader, TableHeaderCell, TableRow } from '../../components'; import ForwardStatus from './ForwardStatus'; import OutgoingForwardActions from './OutgoingForwardActions'; import WarningChainedForwarding from './WarningChainedForwarding'; interface Props { addresses: Address[]; loading?: boolean; forwardings: OutgoingAddressForwarding[]; user: UserModel; chainedEmails: string[]; } const OutgoingForwardTable = ({ addresses, loading, forwardings, chainedEmails, user }: Props) => { return ( <Table responsive="cards" hasActions={!!forwardings.length}> <TableHeader> <TableRow> <TableHeaderCell>{c('email_forwarding_2023: Header').t`From`}</TableHeaderCell> <TableHeaderCell>{c('email_forwarding_2023: Header').t`To`}</TableHeaderCell> <TableHeaderCell className="w-custom" style={{ '--w-custom': '11em' }}>{c( 'email_forwarding_2023: Header' ).t`Status`}</TableHeaderCell> <TableHeaderCell className="w-custom" style={{ '--w-custom': '5em' }}>{c( 'email_forwarding_2023: Header' ).t`Actions`}</TableHeaderCell> </TableRow> </TableHeader> <TableBody loading={loading} colSpan={4}> {forwardings.length === 0 && ( <TableRow> <TableCell colSpan={4} className="text-center">{c('email_forwarding_2023: Info') .t`No outgoing forwarding rules`}</TableCell> </TableRow> )} {forwardings.map((forward) => { const to = forward.ForwardeeEmail; const fromAddress = addresses.find(({ ID }) => ID === forward.ForwarderAddressID); if (fromAddress === undefined) { return null; } const from = fromAddress.Email; return ( <TableRow key={forward.ID}> <TableCell label={c('email_forwarding_2023: Header').t`From`}> <div className="text-ellipsis"> <WarningChainedForwarding chainedEmails={chainedEmails} forwardEmail={from} /> <span title={from}>{from}</span> </div> </TableCell> <TableCell label={c('email_forwarding_2023: Header').t`To`}> <div className="text-ellipsis" title={to}> {to} </div> </TableCell> <TableCell label={c('email_forwarding_2023: Header').t`Status`}> <ForwardStatus forward={forward} /> </TableCell> <TableCell> <OutgoingForwardActions addresses={addresses} user={user} forward={forward} forwardings={forwardings} /> </TableCell> </TableRow> ); })} </TableBody> </Table> ); }; export default OutgoingForwardTable;
6,280
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/forward/TokensCondition.tsx
import { Fragment } from 'react'; import { c } from 'ttag'; import { Icon } from '../../components'; import { Condition } from '../filters/interfaces'; interface TokenProps { index: number; value: string; onRemove: (index: number) => void; } const Token = ({ index, value, onRemove }: TokenProps) => { return ( <Fragment key={`${value}-${index}`}> {index > 0 && <span className="mx-2 text-sm mb-2">{c('email_forwarding_2023: Label').t`or`}</span>} <span className="inline-flex max-w-full flex-nowrap flex-row flex-align-items-center mb-2 condition-token"> <small className="text-ellipsis text-no-decoration" title={value}> {value} </small> <button type="button" className="flex flex-item-noshrink ml-2" title={c('email_forwarding_2023: Action').t`Remove “${value}”`} onClick={() => onRemove(index)} > <Icon name="cross" size={11} /> <span className="sr-only">{c('email_forwarding_2023: Action').t`Remove “${value}”`}</span> </button> </span> </Fragment> ); }; interface Props { condition: Condition; onRemove: (index: number) => void; } const TokensCondition = ({ condition, onRemove }: Props) => { const renderToken = (token: string, i: number) => <Token key={i} index={i} value={token} onRemove={onRemove} />; return <div className="mb-4 flex flex-align-items-center">{condition.values?.map(renderToken)}</div>; }; export default TokensCondition;
6,281
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/forward/TokensConditon.spec.tsx
import { render } from '@testing-library/react'; import { Condition } from '../filters/interfaces'; import TokensCondition from './TokensCondition'; describe('TokensCondition', () => { const setup = () => { const condition = { values: ['token1', 'token2'], } as Condition; const onRemove = jest.fn(); const utils = render(<TokensCondition condition={condition} onRemove={onRemove} />); return { ...utils, condition, onRemove }; }; it('should render a list of condition tokens', () => { const { getByText } = setup(); expect(getByText('token1')).toBeInTheDocument(); expect(getByText('token2')).toBeInTheDocument(); }); it('should render a remove button for each token', () => { const { getAllByRole } = setup(); expect(getAllByRole('button')).toHaveLength(2); }); it('should call onRemove when clicking on a remove button', () => { const { getAllByRole, onRemove } = setup(); getAllByRole('button')[0].click(); expect(onRemove).toHaveBeenCalledWith(0); }); });
6,282
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/forward/WarningChainedForwarding.spec.tsx
import { render } from '@testing-library/react'; import WarningChainedForwarding from './WarningChainedForwarding'; describe('WarningChainedForwarding', () => { const email1 = 'panda@proton.me'; const email2 = 'tiger@proton.me'; describe('when email is chained', () => { it('should render a warning icon', () => { const { getByRole } = render(<WarningChainedForwarding chainedEmails={[email1]} forwardEmail={email1} />); expect(getByRole('img', { hidden: true })).toBeInTheDocument(); }); }); describe('when email is not chained', () => { it('should not render a warning icon', () => { const { queryByRole } = render(<WarningChainedForwarding chainedEmails={[email2]} forwardEmail={email1} />); expect(queryByRole('img', { hidden: true })).toBeNull(); }); it('even if chained emails is empty', () => { const { queryByRole } = render(<WarningChainedForwarding chainedEmails={[]} forwardEmail={email1} />); expect(queryByRole('img', { hidden: true })).toBeNull(); }); }); });
6,283
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/forward/WarningChainedForwarding.tsx
import { c } from 'ttag'; import { Icon, Tooltip } from '../../components'; import { isChainedForwarding } from './helpers'; interface Props { chainedEmails: string[]; forwardEmail: string; } const WarningChainedForwarding = ({ chainedEmails, forwardEmail }: Props) => { if (!isChainedForwarding(chainedEmails, forwardEmail)) { return null; } return ( <Tooltip title={c('email_forwarding_2023: Forwarding tooltip') .t`Emails forwarded to you are excluded and will not be forwarded.`} > <Icon name="exclamation-triangle-filled" className="mr-2 color-warning" alt={c('email_forwarding_2023: Warning').t`Warning`} /> </Tooltip> ); }; export default WarningChainedForwarding;
6,284
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/forward/helpers.test.ts
import { ForwardingType, OutgoingAddressForwarding } from '@proton/shared/lib/interfaces'; import { isLastOutgoingNonE2EEForwarding } from './helpers'; describe('isLastOutgoingNonE2EEForwarding', () => { describe('when forward is encrypted', () => { it('should return false', () => { const forward = { Type: ForwardingType.InternalEncrypted } as OutgoingAddressForwarding; const forwarding = [forward]; const result = isLastOutgoingNonE2EEForwarding(forward, forwarding); expect(result).toBeFalsy(); }); }); describe('when there is multiple external outgoing setup', () => { it('should return false', () => { const forward = { ForwarderAddressID: 'ForwarderAddressID', Type: ForwardingType.ExternalUnencrypted, } as OutgoingAddressForwarding; const forwarding = [forward, forward]; const result = isLastOutgoingNonE2EEForwarding(forward, forwarding); expect(result).toBeFalsy(); }); }); describe('when it is the latest external outgoing setup', () => { it('should return true', () => { const forward = { ForwarderAddressID: 'ForwarderAddressID', Type: ForwardingType.ExternalUnencrypted, } as OutgoingAddressForwarding; const internalForwarding = { ForwarderAddressID: 'ForwarderAddressID', Type: ForwardingType.ExternalEncrypted, } as OutgoingAddressForwarding; const forwarding = [forward, internalForwarding]; const result = isLastOutgoingNonE2EEForwarding(forward, forwarding); expect(result).toBeTruthy(); }); }); });
6,285
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/forward/helpers.ts
import { CryptoProxy, MaybeArray, PrivateKeyReference, PublicKeyReference } from '@proton/crypto'; import { arrayToHexString } from '@proton/crypto/lib/utils'; import { updateForwarding } from '@proton/shared/lib/api/forwardings'; import { getAndVerifyApiKeys } from '@proton/shared/lib/api/helpers/getAndVerifyApiKeys'; import { castKeys } from '@proton/shared/lib/api/helpers/getPublicKeysEmailHelperWithKT'; import { createAddressKeyRouteV2 } from '@proton/shared/lib/api/keys'; import { canonicalizeEmailByGuess } from '@proton/shared/lib/helpers/email'; import { toMap } from '@proton/shared/lib/helpers/object'; import { ActiveKey, Address, Api, ApiKeysConfig, DecryptedKey, ForwardingType, IncomingAddressForwarding, KeyTransparencyCommit, KeyTransparencyVerify, OutgoingAddressForwarding, VerifyOutboundPublicKeys, } from '@proton/shared/lib/interfaces'; import { decryptMemberToken, getAddressKeyToken, getDefaultKeyFlags, getEmailFromKey, getSignedKeyListWithDeferredPublish, splitKeys, } from '@proton/shared/lib/keys'; import { getActiveKeyObject, getActiveKeys, getNormalizedActiveKeys } from '@proton/shared/lib/keys/getActiveKeys'; import { fromSieveTree, toSieveTree } from '@proton/sieve'; import { SIEVE_VERSION, SieveBranch } from '@proton/sieve/src/interface'; import { generateUID } from '../..'; import { COMPARATORS, OPERATORS, TYPES } from '../filters/constants'; import { Condition, FilterCondition, FilterOperator, FilterStatement } from '../filters/interfaces'; const toSieveOperator = (statement: FilterStatement): FilterOperator => { const operatorsMap = toMap(OPERATORS, 'value'); return operatorsMap[statement]; }; const toSieveConditions = (conditions: Condition[]): FilterCondition[] => { const comparatorsMap = toMap(COMPARATORS, 'value'); const typesMap = toMap(TYPES, 'value'); return conditions.map((cond) => ({ Comparator: comparatorsMap[cond.comparator], Type: typesMap[cond.type], Values: cond.values || [], })); }; export const getSieveTree = ({ conditions, statement, version = 2, email, }: { conditions: Condition[]; statement: FilterStatement; version?: SIEVE_VERSION; email: string; }): SieveBranch[] | null => { if (conditions.length === 0) { return null; } return toSieveTree( { Operator: toSieveOperator(statement), Conditions: toSieveConditions(conditions), Actions: { FileInto: [], Vacation: '', Mark: { Read: false, Starred: false }, Redirects: [{ Address: email, Copy: true }], }, }, version ); }; export const getSieveParameters = (tree: SieveBranch[]): { conditions: Condition[]; statement: FilterStatement } => { const simple = fromSieveTree(tree); if (!simple) { return { conditions: [], statement: FilterStatement.ALL, }; } return { conditions: simple.Conditions.map((cond) => ({ type: cond.Type.value, comparator: cond.Comparator.value, values: cond.Values || [], isOpen: true, defaultValue: cond.Values[0] || '', id: generateUID('condition'), })) || [], statement: simple.Operator?.value || FilterStatement.ALL, }; }; interface ForwardingAddressKeyParameters { api: Api; privateKey: PrivateKeyReference; address: Address; activeKeys: ActiveKey[]; privateKeyArmored: string; signature: string; encryptedToken: string; addressForwardingID: string; keyTransparencyVerify: KeyTransparencyVerify; } export const generateForwardingAddressKey = async ({ api, privateKey, address, activeKeys, privateKeyArmored, signature, encryptedToken, addressForwardingID, keyTransparencyVerify, }: ForwardingAddressKeyParameters) => { const newActiveKey = await getActiveKeyObject(privateKey, { ID: 'tmp', primary: 0, flags: getDefaultKeyFlags(address), }); const updatedActiveKeys = getNormalizedActiveKeys(address, [newActiveKey]); const [SignedKeyList, onSKLPublishSuccess] = await getSignedKeyListWithDeferredPublish( activeKeys, address, keyTransparencyVerify ); const { Key } = await api( createAddressKeyRouteV2({ AddressID: address.ID, Primary: newActiveKey.primary, PrivateKey: privateKeyArmored, SignedKeyList, Signature: signature, Token: encryptedToken, AddressForwardingID: addressForwardingID, }) ); await onSKLPublishSuccess(); newActiveKey.ID = Key.ID; return [newActiveKey, updatedActiveKeys] as const; }; interface UserID { name?: string; email?: string; } const generateRandomHexPassphrase = () => { const randomBytes = crypto.getRandomValues(new Uint8Array(32)); return arrayToHexString(randomBytes); }; const generateForwardingMaterial = async ( passphrase: string, forwarderPrivateKey: PrivateKeyReference, userIDsForForwardeeKey: MaybeArray<UserID> ) => { const forwardingMaterial = await CryptoProxy.generateE2EEForwardingMaterial({ passphrase, forwarderKey: forwarderPrivateKey, userIDsForForwardeeKey, }); return forwardingMaterial; }; const encryptAndSignPassphrase = async ( passphrase: string, forwarderPrivateKey: PrivateKeyReference, forwardeePublicKey: PublicKeyReference ) => { const activationToken = await CryptoProxy.encryptMessage({ textData: passphrase, signingKeys: [forwarderPrivateKey], encryptionKeys: [forwardeePublicKey], }); return activationToken.message; }; interface ProxyInstance { keyVersion: number; forwarderKeyFingerprint: Uint8Array; forwardeeKeyFingerprint: Uint8Array; proxyParameter: Uint8Array; } const mapProxyInstance = (proxyInstance: ProxyInstance) => ({ PgpVersion: proxyInstance.keyVersion, ForwarderKeyFingerprint: arrayToHexString(proxyInstance.forwarderKeyFingerprint), ForwardeeKeyFingerprint: arrayToHexString(proxyInstance.forwardeeKeyFingerprint), ProxyParam: arrayToHexString(proxyInstance.proxyParameter), }); export const getInternalParameters = async ( forwarderPrivateKey: PrivateKeyReference, userIDsForForwardeeKey: MaybeArray<UserID>, forwardeePublicKey: PublicKeyReference ) => { const passphrase = generateRandomHexPassphrase(); const [forwardingMaterial, activationToken] = await Promise.all([ generateForwardingMaterial(passphrase, forwarderPrivateKey, userIDsForForwardeeKey), encryptAndSignPassphrase(passphrase, forwarderPrivateKey, forwardeePublicKey), ]); const proxyInstances = forwardingMaterial.proxyInstances.map(mapProxyInstance); return { activationToken, forwardeeKey: forwardingMaterial.forwardeeKey, proxyInstances, }; }; interface AcceptIncomingForwardingParameters { api: Api; address: Address; addressKeys: DecryptedKey[]; userKeys: DecryptedKey[]; forward: IncomingAddressForwarding; keyTransparencyVerify: KeyTransparencyVerify; keyTransparencyCommit: KeyTransparencyCommit; verifyOutboundPublicKeys: VerifyOutboundPublicKeys; } export const acceptIncomingForwarding = async ({ api, address, addressKeys: forwardeeAddressKeys, userKeys, forward, keyTransparencyVerify, keyTransparencyCommit, verifyOutboundPublicKeys, }: AcceptIncomingForwardingParameters) => { if (!address) { throw new Error('No address'); } const forwardeeEmail = address.Email; const splitUserKeys = splitKeys(userKeys); const splitAddressKeys = splitKeys(forwardeeAddressKeys); const [primaryAddressKey] = address.Keys; if (!primaryAddressKey || !primaryAddressKey.Token) { throw new Error('No primary address key'); } const decryptedPrimaryAddressKeyToken = await getAddressKeyToken({ Token: primaryAddressKey.Token, Signature: primaryAddressKey.Signature, privateKeys: splitUserKeys.privateKeys, publicKeys: splitUserKeys.publicKeys, }); const { addressKeys: forwarderAddressKeys } = await getAndVerifyApiKeys({ api, email: forward.ForwarderEmail, verifyOutboundPublicKeys, internalKeysOnly: true, }); const publicKeys = await Promise.all( castKeys(forwarderAddressKeys).map((processedApiKey) => CryptoProxy.importPublicKey({ armoredKey: processedApiKey.armoredKey }) ) ); let activeKeys = await getActiveKeys(address, address.SignedKeyList, address.Keys, forwardeeAddressKeys); for (const forwardingKey of forward.ForwardingKeys || []) { const decryptedToken = await decryptMemberToken( forwardingKey.ActivationToken, splitAddressKeys.privateKeys, publicKeys ); let privateKey = await CryptoProxy.importPrivateKey({ armoredKey: forwardingKey.PrivateKey, passphrase: decryptedToken, }); const extractedEmail = getEmailFromKey(privateKey); // The forwardee email address can change before the user has accepted the forwarding // So we need to update the private key with the email address returned by the API // Use strict comparison because capitalization matters if (extractedEmail !== forwardeeEmail) { const updatedPrivateKey = await CryptoProxy.cloneKeyAndChangeUserIDs({ userIDs: [{ name: forwardeeEmail, email: forwardeeEmail }], privateKey, }); await CryptoProxy.clearKey({ key: privateKey }); privateKey = updatedPrivateKey; } const armoredPrivateKey = await CryptoProxy.exportPrivateKey({ privateKey, passphrase: decryptedPrimaryAddressKeyToken, }); const [, updatedActiveKeys] = await generateForwardingAddressKey({ api, address, keyTransparencyVerify, addressForwardingID: forward.ID, encryptedToken: primaryAddressKey.Token, signature: primaryAddressKey.Signature, privateKeyArmored: armoredPrivateKey, activeKeys, privateKey, }); await keyTransparencyCommit(userKeys); activeKeys = updatedActiveKeys; } }; interface EnableForwardingParameters { api: Api; forward: OutgoingAddressForwarding; forwarderAddressKeys: DecryptedKey[]; forwardeePublicKeys: ApiKeysConfig; } export const enableForwarding = async ({ api, forward, forwarderAddressKeys, forwardeePublicKeys, }: EnableForwardingParameters) => { const email = forward.ForwardeeEmail; const splitForwarderAddressKeys = splitKeys(forwarderAddressKeys); const [forwarderKey] = splitForwarderAddressKeys.privateKeys; const [forwardeePublicKeyArmored] = forwardeePublicKeys.publicKeys || []; const forwardeePublicKey = await CryptoProxy.importPublicKey({ armoredKey: forwardeePublicKeyArmored.armoredKey }); const { activationToken, forwardeeKey, proxyInstances } = await getInternalParameters( forwarderKey, [{ email, name: email }], forwardeePublicKey ); await api( updateForwarding({ ID: forward.ID, ForwardeePrivateKey: forwardeeKey, ActivationToken: activationToken, ProxyInstances: proxyInstances, }) ); }; export const getChainedForwardingEmails = ( incoming: IncomingAddressForwarding[], outgoing: OutgoingAddressForwarding[], addresses: Address[] ) => { const addressesMap = toMap(addresses); const forwardeeEmails = incoming.map(({ ForwardeeAddressID }) => canonicalizeEmailByGuess(addressesMap[ForwardeeAddressID]?.Email) ); const forwarderEmails = outgoing.map(({ ForwarderAddressID }) => canonicalizeEmailByGuess(addressesMap[ForwarderAddressID]?.Email) ); return forwarderEmails.filter((email) => forwardeeEmails.includes(email)); }; export const isChainedForwarding = (chainedEmails: string[], email: string) => { // chainedEmails is already canonicalized by getChainedForwardingEmails return chainedEmails.includes(canonicalizeEmailByGuess(email)); }; export const isLastOutgoingNonE2EEForwarding = ( forward: OutgoingAddressForwarding, forwarding: OutgoingAddressForwarding[] ): boolean => { if (forward.Type !== ForwardingType.ExternalUnencrypted) { return false; } const last = forwarding.filter( (f) => f.Type === ForwardingType.ExternalUnencrypted && f.ForwarderAddressID === forward.ForwarderAddressID ); return last.length <= 1; };
6,286
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/general/AutoSaveContactsToggle.tsx
import { ChangeEvent } from 'react'; import { c } from 'ttag'; import { useLoading } from '@proton/hooks'; import { updateAutoSaveContacts } from '@proton/shared/lib/api/mailSettings'; import { Toggle } from '../../components'; import { useApi, useEventManager, useNotifications } from '../../hooks'; interface Props { autoSaveContacts: boolean; id?: string; className?: string; } const AutoSaveContactsToggle = ({ autoSaveContacts, id, className }: Props) => { const api = useApi(); const [loading, withLoading] = useLoading(); const { createNotification } = useNotifications(); const { call } = useEventManager(); const handleChange = async (event: ChangeEvent<HTMLInputElement>) => { await api(updateAutoSaveContacts(+event.target.checked)); await call(); createNotification({ text: c('Success').t`Preference saved` }); }; return ( <Toggle id={id} className={className} loading={loading} checked={autoSaveContacts} onChange={(event) => withLoading(handleChange(event))} /> ); }; export default AutoSaveContactsToggle;
6,287
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/general/DateFormatSection.tsx
import { c } from 'ttag'; import { useLoading } from '@proton/hooks'; import { updateDateFormat } from '@proton/shared/lib/api/settings'; import { dateLocaleCode } from '@proton/shared/lib/i18n'; import { getBrowserLocale } from '@proton/shared/lib/i18n/helper'; import { loadDateLocale } from '@proton/shared/lib/i18n/loadLocale'; import { SETTINGS_DATE_FORMAT } from '@proton/shared/lib/interfaces'; import { getDefaultDateFormat } from '@proton/shared/lib/settings/helper'; import { Option, SelectTwo } from '../../components'; import { useApi, useEventManager, useNotifications, useUserSettings } from '../../hooks'; import SettingsLayout from '../account/SettingsLayout'; import SettingsLayoutLeft from '../account/SettingsLayoutLeft'; import SettingsLayoutRight from '../account/SettingsLayoutRight'; const DateFormatSection = () => { const api = useApi(); const [userSettings] = useUserSettings(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const [loading, withLoading] = useLoading(); const handleDateFormat = async (value: SETTINGS_DATE_FORMAT) => { await loadDateLocale(dateLocaleCode, getBrowserLocale(), { ...userSettings, DateFormat: value }); await api(updateDateFormat(value)); await call(); createNotification({ text: c('Success').t`Preference saved` }); }; const defaultFormat = getDefaultDateFormat()?.toUpperCase(); return ( <SettingsLayout> <SettingsLayoutLeft> <label className="text-semibold" htmlFor="date-format-select" id="label-date-format-select"> {c('Label').t`Date format`} </label> </SettingsLayoutLeft> <SettingsLayoutRight> <SelectTwo id="date-format-select" value={userSettings.DateFormat} loading={loading} onChange={({ value }) => withLoading(handleDateFormat(value))} aria-describedby="label-date-format-select" > <Option title={c('Option').t`Automatic (${defaultFormat})`} value={SETTINGS_DATE_FORMAT.LOCALE_DEFAULT} /> <Option title="DD/MM/YYYY" value={SETTINGS_DATE_FORMAT.DDMMYYYY} /> <Option title="MM/DD/YYYY" value={SETTINGS_DATE_FORMAT.MMDDYYYY} /> <Option title="YYYY/MM/DD" value={SETTINGS_DATE_FORMAT.YYYYMMDD} /> </SelectTwo> </SettingsLayoutRight> </SettingsLayout> ); }; export default DateFormatSection;
6,288
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/general/LanguageAndTimeSection.tsx
import { IS_DATE_FORMAT_ENABLED } from '@proton/shared/lib/i18n/dateFnLocale'; import { locales } from '@proton/shared/lib/i18n/locales'; import { SettingsSection } from '../account'; import DateFormatSection from './DateFormatSection'; import LanguageSection from './LanguageSection'; import TimeFormatSection from './TimeFormatSection'; import WeekStartSection from './WeekStartSection'; const LanguageAndTimeSection = () => { return ( <SettingsSection> <LanguageSection locales={locales} /> <TimeFormatSection /> <WeekStartSection /> {IS_DATE_FORMAT_ENABLED && <DateFormatSection />} </SettingsSection> ); }; export default LanguageAndTimeSection;
6,289
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/general/LanguageSection.tsx
import { c } from 'ttag'; import { Href } from '@proton/atoms/Href'; import { useLoading } from '@proton/hooks'; import { updateLocale } from '@proton/shared/lib/api/settings'; import { getBlogURL } from '@proton/shared/lib/helpers/url'; import { getBrowserLocale, getClosestLocaleCode } from '@proton/shared/lib/i18n/helper'; import { loadDateLocale, loadLocale } from '@proton/shared/lib/i18n/loadLocale'; import { TtagLocaleMap } from '@proton/shared/lib/interfaces/Locale'; import { Option, SelectTwo } from '../../components'; import { useApi, useConfig, useEventManager, useForceRefresh, useNotifications, useUserSettings } from '../../hooks'; import SettingsLayout from '../account/SettingsLayout'; import SettingsLayoutLeft from '../account/SettingsLayoutLeft'; import SettingsLayoutRight from '../account/SettingsLayoutRight'; interface Props { locales: TtagLocaleMap; } const LanguageSection = ({ locales = {} }: Props) => { const api = useApi(); const { call } = useEventManager(); const { LOCALES = {} } = useConfig(); const [userSettings] = useUserSettings(); const { createNotification } = useNotifications(); const [loading, withLoading] = useLoading(); const forceRefresh = useForceRefresh(); const languageOptions = Object.entries(LOCALES).map(([key, value]) => ( <Option key={key} title={value} value={key} /> )); const handleChange = async (locale: string) => { await api(updateLocale(locale)); const localeCode = getClosestLocaleCode(locale, locales); await Promise.all([ loadLocale(localeCode, locales), loadDateLocale(localeCode, getBrowserLocale(), userSettings), ]); await call(); createNotification({ text: c('Success').t`Locale updated` }); forceRefresh(); }; const displayedValue = getClosestLocaleCode(userSettings?.Locale, locales); return ( <SettingsLayout> <SettingsLayoutLeft> <label className="text-semibold" htmlFor="languageSelect" id="label-languageSelect"> {c('Label').t`Default language`} </label> </SettingsLayoutLeft> <SettingsLayoutRight> <SelectTwo id="languageSelect" value={displayedValue} disabled={loading} onChange={({ value }) => { void withLoading(handleChange(value)); }} aria-describedby="label-languageSelect" > {languageOptions} </SelectTwo> <div className="mt-1 text-sm"> <Href href={getBlogURL('/translation-community')}>{c('Link').t`Help translate`}</Href> </div> </SettingsLayoutRight> </SettingsLayout> ); }; export default LanguageSection;
6,290
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/general/PmMeButton.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { setupAddress } from '@proton/shared/lib/api/addresses'; import { DEFAULT_ENCRYPTION_CONFIG, ENCRYPTION_CONFIGS } from '@proton/shared/lib/constants'; import { missingKeysSelfProcess } from '@proton/shared/lib/keys'; import noop from '@proton/utils/noop'; import { useAddresses, useApi, useAuthentication, useEventManager, useGetUserKeys, useModals, useNotifications, usePremiumDomains, useUser, } from '../../hooks'; import { useKTVerifier } from '../keyTransparency'; import UnlockModal from '../login/UnlockModal'; const PmMeButton = () => { const [user] = useUser(); const [loading, withLoading] = useLoading(); const { createNotification } = useNotifications(); const { createModal } = useModals(); const api = useApi(); const { call } = useEventManager(); const authentication = useAuthentication(); const [addresses, loadingAddresses] = useAddresses(); const [premiumDomains, loadingPremiumDomains] = usePremiumDomains(); const getUserKeys = useGetUserKeys(); const isLoadingDependencies = loadingAddresses || loadingPremiumDomains; const [Domain = ''] = premiumDomains || []; const { keyTransparencyVerify, keyTransparencyCommit } = useKTVerifier(api, async () => user); const createPremiumAddress = async () => { const [{ DisplayName = '', Signature = '' } = {}] = addresses || []; await new Promise<string>((resolve, reject) => { createModal(<UnlockModal onClose={() => reject()} onSuccess={resolve} />); }); const { Address } = await api( setupAddress({ Domain, DisplayName: DisplayName || '', // DisplayName can be null Signature: Signature || '', // Signature can be null }) ); const userKeys = await getUserKeys(); await missingKeysSelfProcess({ api, userKeys, addresses, addressesToGenerate: [Address], password: authentication.getPassword(), encryptionConfig: ENCRYPTION_CONFIGS[DEFAULT_ENCRYPTION_CONFIG], onUpdate: noop, keyTransparencyVerify, }); await keyTransparencyCommit(userKeys); await call(); createNotification({ text: c('Success').t`Premium address created` }); }; return ( <Button color="norm" disabled={isLoadingDependencies || !Domain} loading={loading} onClick={() => withLoading(createPremiumAddress())} > {c('Action').t`Activate ${user.Name}@pm.me`} </Button> ); }; export default PmMeButton;
6,291
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/general/PmMeSection.tsx
import { c } from 'ttag'; import { APP_UPSELL_REF_PATH, MAIL_APP_NAME, MAIL_UPSELL_PATHS, UPSELL_COMPONENT } from '@proton/shared/lib/constants'; import { getUpsellRef } from '@proton/shared/lib/helpers/upsell'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { MailUpsellButton, PmMeUpsellModal, useModalState, useSettingsLink } from '../../components'; import { useUser } from '../../hooks'; import { SettingsParagraph, SettingsSection } from '../account'; import PmMeButton from './PmMeButton'; interface Props { isPMAddressActive: boolean; } const PmMeSection = ({ isPMAddressActive }: Props) => { const goToSettings = useSettingsLink(); const [{ hasPaidMail, Name }] = useUser(); const [upsellModalProps, handleUpsellModalDisplay, renderUpsellModal] = useModalState(); const handleUpgrade = () => { const upsellRef = getUpsellRef({ app: APP_UPSELL_REF_PATH.MAIL_UPSELL_REF_PATH, component: UPSELL_COMPONENT.BANNER, feature: MAIL_UPSELL_PATHS.PM_ME, isSettings: true, }); goToSettings(`/upgrade?ref=${upsellRef}`, undefined, false); }; const display: 'can-enable' | 'has-enabled' | 'free-needs-upgrade' | 'free-can-only-receive' = (() => { if (hasPaidMail) { if (!isPMAddressActive) { return 'can-enable'; } else { return 'has-enabled'; } } else { if (!isPMAddressActive) { return 'free-needs-upgrade'; } else { return 'free-can-only-receive'; } } })(); if (display === 'has-enabled') { return null; } return ( <SettingsSection> {display === 'can-enable' && ( <> <SettingsParagraph className="mb-4" learnMoreUrl={getKnowledgeBaseUrl('/pm-me-addresses')}> {c('Info') .t`Add a @pm.me email address to your account. This simple, shorter domain stands for "${MAIL_APP_NAME} me" or "Private Message me."`} </SettingsParagraph> <PmMeButton /> </> )} {display === 'free-needs-upgrade' && ( <> <SettingsParagraph className="mb-4" learnMoreUrl={getKnowledgeBaseUrl('/pm-me-addresses')}> {c('Info') .t`Upgrade to add a shorter @pm.me address to your account that is easier to share. It stands for “${MAIL_APP_NAME} me” or “Private Message me”.`} </SettingsParagraph> <MailUpsellButton onClick={() => handleUpsellModalDisplay(true)} text={c('Action').t`Activate ${Name}@pm.me`} /> </> )} {display === 'free-can-only-receive' && ( <> <SettingsParagraph className="mb-4"> {c('Info') .t`With your current plan, you can only receive messages with your @pm.me address. Upgrade to send messages and create additional addresses using @pm.me.`} </SettingsParagraph> <MailUpsellButton onClick={handleUpgrade} text={c('Action').t`Send messages with @pm.me`} /> </> )} {renderUpsellModal && <PmMeUpsellModal modalProps={upsellModalProps} />} </SettingsSection> ); }; export default PmMeSection;
6,292
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/general/ShortcutsSection.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Field, Label, Row } from '../../components'; import ShortcutsToggle from './ShortcutsToggle'; interface Props { onOpenShortcutsModal: () => void; } const ShortcutsSection = ({ onOpenShortcutsModal }: Props) => { return ( <Row> <Label htmlFor="shortcutsToggle">{c('Title').t`Keyboard shortcuts`}</Label> <Field className="pt-2"> <div> <ShortcutsToggle className="mr-4" id="shortcutsToggle" /> </div> <div className="mt-4"> <Button size="small" onClick={onOpenShortcutsModal}>{c('Action') .t`Display keyboard shortcuts`}</Button> </div> </Field> </Row> ); }; export default ShortcutsSection;
6,293
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/general/ShortcutsToggle.tsx
import { ChangeEvent } from 'react'; import { c } from 'ttag'; import { updateShortcuts } from '@proton/shared/lib/api/mailSettings'; import { DEFAULT_MAILSETTINGS } from '@proton/shared/lib/mail/mailSettings'; import { Toggle } from '../../components'; import { useApiWithoutResult, useEventManager, useMailSettings, useNotifications, useToggle } from '../../hooks'; interface Props { id: string; className?: string; } const ShortcutsToggle = ({ id, className, ...rest }: Props) => { const { call } = useEventManager(); const [{ Shortcuts } = DEFAULT_MAILSETTINGS] = useMailSettings(); const { createNotification } = useNotifications(); const { request, loading } = useApiWithoutResult(updateShortcuts); const { state, toggle } = useToggle(!!Shortcuts); const handleChange = async ({ target }: ChangeEvent<HTMLInputElement>) => { await request(+target.checked); call(); toggle(); createNotification({ text: c('Success').t`Keyboard shortcuts preferences updated` }); }; return <Toggle id={id} className={className} checked={state} onChange={handleChange} loading={loading} {...rest} />; }; export default ShortcutsToggle;
6,294
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/general/TimeFormatSection.tsx
import { c } from 'ttag'; import { useLoading } from '@proton/hooks'; import { updateTimeFormat } from '@proton/shared/lib/api/settings'; import { dateLocaleCode } from '@proton/shared/lib/i18n'; import { getBrowserLocale } from '@proton/shared/lib/i18n/helper'; import { loadDateLocale } from '@proton/shared/lib/i18n/loadLocale'; import { SETTINGS_TIME_FORMAT } from '@proton/shared/lib/interfaces'; import { getDefaultTimeFormat } from '@proton/shared/lib/settings/helper'; import { Option, SelectTwo } from '../../components'; import { useApi, useEventManager, useNotifications, useUserSettings } from '../../hooks'; import SettingsLayout from '../account/SettingsLayout'; import SettingsLayoutLeft from '../account/SettingsLayoutLeft'; import SettingsLayoutRight from '../account/SettingsLayoutRight'; const TimeSection = () => { const api = useApi(); const [userSettings] = useUserSettings(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const [loading, withLoading] = useLoading(); const handleTimeFormat = async (value: SETTINGS_TIME_FORMAT) => { await loadDateLocale(dateLocaleCode, getBrowserLocale(), { ...userSettings, TimeFormat: value }); await api(updateTimeFormat(value)); await call(); createNotification({ text: c('Success').t`Preference saved` }); }; const timeFormats = [ { title: '1:00pm', value: SETTINGS_TIME_FORMAT.H12 }, { title: '13:00', value: SETTINGS_TIME_FORMAT.H24 }, ]; const [h12, h24] = timeFormats; const defaultFormat = getDefaultTimeFormat() === SETTINGS_TIME_FORMAT.H12 ? h12.title : h24.title; return ( <SettingsLayout> <SettingsLayoutLeft> <label className="text-semibold" htmlFor="time-format-select" id="label-time-format"> {c('Label').t`Time format`} </label> </SettingsLayoutLeft> <SettingsLayoutRight> <SelectTwo id="time-format-select" value={userSettings.TimeFormat} loading={loading} onChange={({ value }) => withLoading(handleTimeFormat(value))} aria-describedby="label-time-format" > {[ { title: c('Option').t`Automatic (${defaultFormat})`, value: SETTINGS_TIME_FORMAT.LOCALE_DEFAULT, }, ...timeFormats, ].map((option) => ( <Option key={option.value} {...option} /> ))} </SelectTwo> </SettingsLayoutRight> </SettingsLayout> ); }; export default TimeSection;
6,295
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/general/WeekStartSection.tsx
import { c } from 'ttag'; import SettingsLayout from '../account/SettingsLayout'; import SettingsLayoutLeft from '../account/SettingsLayoutLeft'; import SettingsLayoutRight from '../account/SettingsLayoutRight'; import {WeekStartSelector} from "../calendar/settings"; const WeekStartSection = () => { return ( <SettingsLayout> <SettingsLayoutLeft> <label className="text-semibold" htmlFor="week-start-select" id="label-week-start-select"> {c('Label').t`Week start`} </label> </SettingsLayoutLeft> <SettingsLayoutRight> <WeekStartSelector/> </SettingsLayoutRight> </SettingsLayout> ); }; export default WeekStartSection;
6,296
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/general/index.ts
export { default as LanguageAndTimeSection } from './LanguageAndTimeSection'; export { default as LanguageSection } from './LanguageSection'; export { default as AutoSaveContactsToggle } from './AutoSaveContactsToggle'; export { default as TimeFormatSection } from './TimeFormatSection'; export { default as DateFormatSection } from './DateFormatSection'; export { default as WeekStartSection } from './WeekStartSection'; export { default as ShortcutsToggle } from './ShortcutsToggle'; export { default as PmMeSection } from './PmMeSection';
6,297
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/gmailSyncModal/GmailSyncModal.tsx
import { c } from 'ttag'; import { SYNC_G_OAUTH_SCOPES, SYNC_SOURCE, SYNC_SUCCESS_NOTIFICATION } from '@proton/activation/src/constants'; import useOAuthPopup from '@proton/activation/src/hooks/useOAuthPopup'; import { ImportProvider, OAuthProps } from '@proton/activation/src/interface'; import { useEasySwitchDispatch, useEasySwitchSelector } from '@proton/activation/src/logic/store'; import { changeCreateLoadingState, createSyncItem } from '@proton/activation/src/logic/sync/sync.actions'; import { selectCreateSyncState } from '@proton/activation/src/logic/sync/sync.selectors'; import { Button } from '@proton/atoms/Button'; import ModalContent from '@proton/components/components/modalTwo/ModalContent'; import ModalHeader from '@proton/components/components/modalTwo/ModalHeader'; import { ModalProps, ModalTwo } from '@proton/components/index'; import GmailSyncModalAnimation from './GmailSyncModalAnimation'; import SignInWithGoogle from './SignInWithGoogle'; interface Props extends ModalProps { onSyncCallback?: (hasError: boolean) => void; onSyncSkipCallback?: () => void; noSkip?: boolean; } const GmailSyncModal = ({ onSyncCallback, onSyncSkipCallback, noSkip, ...rest }: Props) => { const dispatch = useEasySwitchDispatch(); const syncState = useEasySwitchSelector(selectCreateSyncState); const loading = syncState === 'pending'; const { triggerOAuthPopup, loadingConfig } = useOAuthPopup({ errorMessage: c('loc_nightly:Error').t`Your sync will not be processed.`, }); const handleGoogleSync = () => { triggerOAuthPopup({ provider: ImportProvider.GOOGLE, scope: SYNC_G_OAUTH_SCOPES.join(' '), callback: async (oAuthProps: OAuthProps) => { const { Code, Provider, RedirectUri } = oAuthProps; dispatch(changeCreateLoadingState('pending')); const res = await dispatch( createSyncItem({ Code, Provider, RedirectUri, Source: SYNC_SOURCE, notification: SYNC_SUCCESS_NOTIFICATION, }) ); const hasError = res.type.endsWith('rejected'); if (!hasError) { rest?.onClose?.(); } onSyncCallback?.(hasError); }, }); }; const handleSyncSkip = () => { onSyncSkipCallback?.(); rest?.onClose?.(); }; const handleClose = () => { onSyncSkipCallback?.(); rest?.onClose?.(); }; return ( <ModalTwo size="xlarge" fullscreenOnMobile {...rest} onClose={handleClose}> <ModalHeader /> <ModalContent className="m-8 mt-0 flex flex-row flex-align-items-center flex-nowrap gap-7"> <div className="flex flex-column flex-item-fluid gap-7"> <h1 className="text-break text-4xl"> <strong>{c('Gmail forwarding').t`Automatically forward`}</strong> &nbsp; <br className="lg:hidden" /> {c('Gmail forwarding').t`Gmail messages to your inbox`} </h1> <div className="lg:hidden flex-item-grow-2"> <GmailSyncModalAnimation /> </div> <div className="flex flex-column flex-align-items-center gap-4"> <SignInWithGoogle onClick={handleGoogleSync} loading={loading} disabled={loadingConfig} /> {!noSkip && ( <Button shape="ghost" color="norm" fullWidth onClick={handleSyncSkip}>{c('Action') .t`Skip`}</Button> )} </div> </div> <div className="hidden lg:block w-6/10"> <GmailSyncModalAnimation /> </div> </ModalContent> </ModalTwo> ); }; export default GmailSyncModal;
6,298
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/gmailSyncModal/GmailSyncModalAnimation.scss
@use 'sass:map'; @use 'sass:math'; @import '~@proton/styles/scss/lib'; .gsma { $keyframes: ( initial_pause: 0.5, envelope: 0.5, inbox: 0.75, inbox_pause: 0.25, new-mail: 0.5, new-mail_pause: 1, forwarded: 0.75, forwarded_pause: 0.5, received: 0.6, received_pause: 0.5, trackers: 0.6, trackers_pause: 0.5, encrypted: 0.6, encrypted_pause: 0.5, arrows: 0.5, ); @function duration($key) { @return map.get($keyframes, $key) * 1s; } @function delay($key) { $value: 0; @each $k, $v in $keyframes { $value: $value + $v; @if $k == $key { @return $value * 1s; } } } position: relative; padding: 1.5rem; overflow: hidden; border-radius: var(--border-radius-lg); font-size: em(18); line-height: 1.2; pointer-events: none; &::before { content: ''; position: absolute; inset: 0; z-index: -1; background-image: linear-gradient(to bottom, var(--interaction-norm-minor-2), var(--interaction-norm)); opacity: 0.22; } &-gmail-username-inbox { position: relative; z-index: 1; display: inline-flex; max-inline-size: 100%; margin-block-end: 1.5rem; flex-flow: row nowrap; align-items: stretch; } &-gmail-logo { position: relative; z-index: 1; display: inline-flex; inline-size: rem(56); block-size: rem(56); padding: 0.5rem; flex: 0 0 auto; border-radius: var(--border-radius-lg); box-shadow: var(--shadow-lifted); background-color: var(--background-norm); animation: duration(envelope) easing(ease-out-quart) delay(initial_pause) both anime-gsma-gmail-logo; @keyframes anime-gsma-gmail-logo { from { scale: 0; opacity: 0; } to { scale: 1; opacity: 1; } } img { inline-size: rem(40); block-size: rem(30); margin: auto; } } &-username { position: relative; display: flex; max-inline-size: calc(100% - #{rem(56)}); padding-inline: 1rem; justify-content: center; align-items: center; animation: duration(inbox) easing(ease-out-back) delay(envelope) both anime-gsma-username; @keyframes anime-gsma-username { from { translate: -1rem 0; opacity: 0; } to { translate: 0 0; opacity: 1; } } &::before { content: ''; position: absolute; inset-inline: #{rem(56) * -1} 0; inset-block: 0; transform-origin: center right; z-index: -1; border-radius: var(--border-radius-lg) var(--border-radius-md) var(--border-radius-md) var(--border-radius-lg); box-shadow: var(--shadow-norm); background-color: var(--background-norm); animation: duration(inbox) easing(ease-out-back) delay(envelope) both anime-gsma-username-background; @keyframes anime-gsma-username-background { from { scale: 0.8 1; opacity: 0; } to { scale: 1; opacity: 1; } } } &-content { overflow: hidden; text-overflow: ellipsis; } } &-auto-forward { position: relative; z-index: 1; display: flex; min-block-size: rem(35); margin-block-end: 1.5rem; flex-flow: row nowrap; align-items: stretch; gap: 1rem; animation: duration(new-mail) easing(ease-out-back) delay(inbox_pause) both anime-gsma-auto-forward; @keyframes anime-gsma-auto-forward { from { translate: 0 -1rem; opacity: 0; } to { translate: 0 0; opacity: 1; } } } &-envelope { position: relative; z-index: 1; flex: 0 0 auto; animation: duration(forwarded) easing(ease-out-quad) delay(new-mail_pause) both anime-gsma-envelope; @keyframes anime-gsma-envelope { from { inset-inline-start: 0; } to { inset-inline-start: calc(100% - #{rem(55)}); } } img { inline-size: rem(55); block-size: rem(35); box-shadow: var(--shadow-norm); animation: duration(forwarded) easing(ease-in-quart) delay(new-mail_pause) both anime-gsma-envelope-img; @keyframes anime-gsma-envelope-img { from { translate: 0 0; scale: 1; rotate: 0deg; opacity: 1; } to { translate: 0 4rem; scale: 0.5; rotate: 70deg; opacity: 0; } } } &::before { content: '1'; position: absolute; inset-block-start: -0.75rem; inset-inline-end: -0.75rem; z-index: 2; display: flex; block-size: 1.5rem; inline-size: 1.5rem; justify-content: center; align-items: center; border-radius: 50%; background-color: var(--signal-danger); color: var(--signal-danger-contrast); font-weight: bold; animation: duration(forwarded) easing(ease-in-cubic) delay(new-mail_pause) both anime-gsma-envelope-count; @keyframes anime-gsma-envelope-count { from { inset-block-start: -0.75rem; } to { inset-block-start: calc(100% + 0.75rem); } } } } &-new-email { position: relative; display: flex; padding-block: 0.5rem; padding-inline: 1rem; justify-content: center; align-items: center; border-radius: var(--border-radius-md); box-shadow: var(--shadow-norm); background-color: var(--background-norm); animation: duration(forwarded) easing(ease-out-quad) delay(new-mail_pause) both anime-gsma-new-email; @keyframes anime-gsma-new-email { from { inset-inline-start: 0; opacity: 1; } 50% { opacity: 0; } to { inset-inline-start: calc(100% - 4.5rem); opacity: 0; } } } &-forwarded { position: absolute; inset-block-start: 0; inset-inline-start: 0; z-index: 1; display: flex; padding-block: 0.5rem; padding-inline: 1rem; justify-content: center; align-items: center; border-radius: var(--border-radius-md); box-shadow: var(--shadow-norm); background-color: var(--background-norm); animation: duration(forwarded) easing(ease-out-cubic) delay(new-mail_pause) both anime-gsma-forwarded; @keyframes anime-gsma-forwarded { from { translate: calc(-100% - 2rem) 0; opacity: 0; } to { translate: 0 0; opacity: 1; } } } &-proton { display: flex; inline-size: rem(56); block-size: rem(56); padding: 0.25rem; margin-block-end: 1.5rem; margin-inline-start: auto; aspect-ratio: 1; border-radius: var(--border-radius-lg); box-shadow: var(--shadow-lifted); background-color: var(--background-norm); animation: duration(forwarded) easing(ease-out-quint) delay(new-mail_pause) both anime-gsma-proton; @keyframes anime-gsma-proton { from { scale: 0; opacity: 0; } to { scale: 1; opacity: 1; } } &-logo { margin: auto; } } &-received, &-trackers, &-encrypted { display: flex; margin-block-end: 1.5rem; flex-flow: row nowrap; justify-content: flex-end; align-items: center; &-inner { display: flex; min-block-size: rem(50); padding-block: 0.5rem; padding-inline: 1rem; flex-flow: row nowrap; justify-content: stretch; border-radius: var(--border-radius-md); box-shadow: var(--shadow-norm); animation: anime-gsma-rte-inner easing(ease-out-cubic) both; @keyframes anime-gsma-rte-inner { from { translate: 0 -1.5rem; opacity: 0; } to { translate: 0 0; opacity: 1; } } &-content { display: flex; flex-flow: row nowrap; justify-content: flex-start; align-items: center; animation: anime-gsma-rte-inner-content easing(ease-out-cubic) both; animation-duration: inherit; animation-delay: inherit; @keyframes anime-gsma-rte-inner-content { from { translate: 0 -2.5rem; opacity: 0; } to { translate: 0 0; opacity: 1; } } } } img { margin-inline-end: 0.5rem; flex: 0 0 auto; animation: anime-gsma-icon-rotate easing(ease-out-cubic) both; animation-duration: inherit; animation-delay: inherit; @keyframes anime-gsma-icon-rotate { from { rotate: 0deg; scale: 0; opacity: 0; } to { rotate: 360deg; scale: 1; opacity: 1; } } } } &-received { &-inner { animation-duration: duration(received); animation-delay: delay(forwarded_pause); } } &-trackers { &-inner { animation-duration: duration(trackers); animation-delay: delay(received_pause); } img { animation-duration: duration(trackers); animation-delay: #{delay(received_pause) + math.div(duration(trackers), 2)}; } } &-encrypted { margin-block-end: 0; &-inner { animation-duration: duration(encrypted); animation-delay: delay(trackers_pause); } img { animation-duration: duration(encrypted); animation-delay: #{delay(trackers_pause) + math.div(duration(encrypted), 2)}; } } &-arrows { @include media('>medium') { display: none; } @include media('<=medium') { position: relative; display: flex; margin-block-start: 4.5rem; flex-flow: column nowrap; align-items: center; animation: duration(arrows) easing(ease-out-quint) delay(encrypted_pause) both anime-gsma-arrows; @keyframes anime-gsma-arrows { from { opacity: 0; } to { opacity: 1; } } &::before { content: ''; position: absolute; inset-block-start: -1.5rem; inset-inline-start: 50%; display: block; inline-size: 40%; aspect-ratio: 1; translate: -50% 0; border-radius: 50%; background-image: linear-gradient(to bottom, var(--background-norm), transparent 50%); opacity: 0.3; } &-inner { margin-block-end: -1.15rem; flex: 0 0 auto; animation: 1.5s easing(ease-in-out-quint) 0s both infinite anime-gsma-arrows-icon; &:nth-child(2) { animation-delay: 0.1s; } &:nth-child(3) { animation-delay: 0.2s; } @keyframes anime-gsma-arrows-icon { from { translate: 0 -0.25rem; opacity: 0; } 40% { translate: 0 0; opacity: 1; } 60% { opacity: 1; } to { opacity: 0; } } &:nth-child(1) &-icon { opacity: 0.1; } &:nth-child(2) &-icon { opacity: 0.5; } } } } }
6,299