index
int64
0
0
repo_id
stringlengths
16
181
file_path
stringlengths
28
270
content
stringlengths
1
11.6M
__index_level_0__
int64
0
10k
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/DriveSidebar
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/DriveSidebar/DriveSidebarDevices/index.ts
import DriveSidebarDevices from './SidebarDevices'; export default DriveSidebarDevices;
2,800
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/DriveSidebar
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/DriveSidebar/DriveSidebarFolders/DriveSidebarFolders.tsx
import { useEffect } from 'react'; import { useFolderTree } from '../../../../../store'; import DriveSidebarFoldersRoot from './DriveSidebarFoldersRoot'; import DriveSidebarSubfolders from './DriveSidebarSubfolders'; interface Props { path: string; shareId: string; linkId: string; setSidebarLevel: (level: number) => void; } export default function DriveSidebarFolders({ shareId, linkId, path, setSidebarLevel }: Props) { const { deepestOpenedLevel, rootFolder, toggleExpand } = useFolderTree(shareId, { rootLinkId: linkId }); useEffect(() => { setSidebarLevel(deepestOpenedLevel); }, [deepestOpenedLevel]); return ( <> <DriveSidebarFoldersRoot path={path} shareId={shareId} linkId={linkId} rootFolder={rootFolder} toggleExpand={toggleExpand} /> <DriveSidebarSubfolders shareId={shareId} rootFolder={rootFolder} toggleExpand={toggleExpand} /> </> ); }
2,801
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/DriveSidebar
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/DriveSidebar/DriveSidebarFolders/DriveSidebarFoldersRoot.tsx
import { c } from 'ttag'; import { Loader } from '@proton/components'; import { LinkURLType } from '@proton/shared/lib/drive/constants'; import { TreeItem } from '../../../../../store'; import FileRecoveryIcon from '../../../../ResolveLockedVolumes/FileRecovery/FileRecoveryIcon'; import DriveSidebarListItem from '../DriveSidebarListItem'; import ExpandButton from './ExpandButton'; interface Props { path: string; shareId: string; linkId: string; rootFolder?: TreeItem; toggleExpand: (linkId: string) => void; } export default function DriveSidebarFoldersRoot({ path, shareId, linkId, rootFolder, toggleExpand }: Props) { const isLoading = !rootFolder?.isLoaded; const url = `/${shareId}/${LinkURLType.FOLDER}/${linkId}`; return ( <DriveSidebarListItem key="root" to={url} icon="inbox" shareId={shareId} isActive={path === url} onDoubleClick={() => toggleExpand(linkId)} > <span className="text-ellipsis">{c('Title').t`My files`}</span> {isLoading ? ( <Loader className="drive-sidebar--icon inline-flex" /> ) : ( rootFolder.children.length > 0 && ( <ExpandButton className="flex-item-noshrink" expanded={rootFolder.isExpanded} onClick={() => toggleExpand(rootFolder.link.linkId)} /> ) )} <FileRecoveryIcon className="ml-2" /> </DriveSidebarListItem> ); }
2,802
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/DriveSidebar
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/DriveSidebar/DriveSidebarFolders/DriveSidebarSubfolder.tsx
import { FileIcon, FileNameDisplay, Loader, SidebarListItem, SidebarListItemContent, SidebarListItemLink, } from '@proton/components'; import { TreeItem } from '../../../../../store'; import { generateSidebarItemStyle } from '../utils'; import ExpandButton from './ExpandButton'; import useSubfolderLoading from './useSubfolderLoading'; interface Props { shareId: string; folder: TreeItem; level: number; toggleExpand: () => void; } export default function DriveSidebarSubfolder({ shareId, folder, level, toggleExpand }: Props) { const isLoading = useSubfolderLoading(folder); const handleFolderClick = (e: any) => { if (e.detail !== 1) { e.stopPropagation(); e.preventDefault(); } }; const expandeButtonStyle: React.CSSProperties = folder.children.length === 0 && folder.isLoaded ? { visibility: 'hidden', } : {}; return ( <SidebarListItem> <SidebarListItemLink to={`/${shareId}/folder/${folder.link.linkId}`} onClick={handleFolderClick} onDoubleClick={toggleExpand} > <SidebarListItemContent> <div className="flex flex-nowrap flex-align-items-center gap-2" data-testid="sidebar-sub-folders" style={generateSidebarItemStyle(level)} > <ExpandButton expanded={folder.isExpanded} onClick={toggleExpand} style={expandeButtonStyle} /> {isLoading ? ( <Loader className="flex flex-item-noshrink drive-sidebar--icon" /> ) : ( <FileIcon className="flex-item-centered-vert drive-sidebar--icon" mimeType="Folder" /> )} <FileNameDisplay text={folder.link.name} /> </div> </SidebarListItemContent> </SidebarListItemLink> </SidebarListItem> ); }
2,803
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/DriveSidebar
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/DriveSidebar/DriveSidebarFolders/DriveSidebarSubfolders.tsx
import { ReactNode } from 'react'; import { TreeItem } from '../../../../../store'; import DriveSidebarSubfolder from './DriveSidebarSubfolder'; interface Props { shareId: string; rootFolder?: TreeItem; toggleExpand: (linkId: string) => void; defaultLevel?: number; } export default function DriveSidebarSubfolders({ shareId, rootFolder, toggleExpand, defaultLevel = 0 }: Props) { if (!rootFolder || !rootFolder.isExpanded || !rootFolder.children?.length) { return null; } const folderReducer = (acc: ReactNode[], folder: TreeItem, level = defaultLevel): any[] => { acc.push( <DriveSidebarSubfolder key={folder.link.linkId} shareId={shareId} folder={folder} level={level} toggleExpand={() => toggleExpand(folder.link.linkId)} /> ); if (folder.isExpanded && folder.children?.length) { folder.children.forEach((subfolder: TreeItem) => folderReducer(acc, subfolder, level + 1)); } return acc; }; return <>{rootFolder.children.reduce((acc: ReactNode[], folder: TreeItem) => folderReducer(acc, folder), [])}</>; }
2,804
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/DriveSidebar
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/DriveSidebar/DriveSidebarFolders/ExpandButton.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Icon } from '@proton/components'; import clsx from '@proton/utils/clsx'; interface Props { className?: string; expanded: boolean; onClick: () => void; style?: React.CSSProperties; } export default function ExpandButton({ className, expanded, onClick, style }: Props) { const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => { e.stopPropagation(); e.preventDefault(); onClick(); }; return ( <Button shape="ghost" size="small" icon className={clsx([ 'flex-item-noshrink flex flex-align-items-center drive-sidebar--button-expand', className, ])} onClick={handleClick} aria-expanded={expanded} title={expanded ? c('Action').t`Collapse folder` : c('Action').t`Expand folder`} style={style} data-testid="sidebar-expand-folder" > <Icon name={expanded ? 'chevron-down-filled' : 'chevron-right-filled'} alt={expanded ? c('Action').t`Collapse folder` : c('Action').t`Expand folder`} /> </Button> ); }
2,805
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/DriveSidebar
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/DriveSidebar/DriveSidebarFolders/useSubfolderLoading.ts
import { useEffect, useState } from 'react'; import { TreeItem } from '../../../../../store'; export default function useSubfolderLoading(folder: TreeItem) { const [isLoading, setIsLoading] = useState(false); useEffect(() => { if (folder.isLoaded) { setIsLoading(false); } if (!folder.isExpanded || folder.isLoaded) { return; } const t = setTimeout(() => setIsLoading(true), 250); return () => { clearTimeout(t); }; }, [folder]); return isLoading; }
2,806
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/ConflictModal.tsx
import React, { ReactNode, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Checkbox, ModalStateProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, PrimaryButton, Radio, Row, useModalTwo, } from '@proton/components'; import { TransferConflictStrategy } from '../../store'; export interface ConflictModalProps { name: string; isFolder?: boolean; originalIsDraft?: boolean; originalIsFolder?: boolean; apply: (strategy: TransferConflictStrategy, all: boolean) => void; cancelAll: () => void; onConfirm?: () => void; title?: string; children?: ReactNode; cancel?: ReactNode; confirm?: ReactNode; loading?: boolean; className?: string; small?: boolean; tiny?: boolean; noTitleEllipsis?: boolean; mode?: 'alert'; submitProps?: any; closeProps?: any; } export default function ConflictModal({ name, isFolder = false, originalIsDraft = false, originalIsFolder = false, apply, cancelAll, onClose, ...modalProps }: ConflictModalProps & ModalStateProps) { const [strategy, setStrategy] = useState(TransferConflictStrategy.Replace); const [applyAll, setApplyAll] = useState(false); const isSameType = originalIsFolder === isFolder; const uploadName = ( <strong className="text-break" key="filename"> {name} </strong> ); const replaceFile = <strong key="replaceFile">{c('Action').t`Replace file`}</strong>; const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); apply(strategy, applyAll); onClose(); }; const closeAndCancel = () => { onClose(); cancelAll(); }; return ( <ModalTwo as="form" onClose={closeAndCancel} onSubmit={handleSubmit} size="small" {...modalProps}> <ModalTwoHeader title={ isSameType ? ( <>{isFolder ? c('Title').t`Duplicate folder found` : c('Title').t`Duplicate file found`}</> ) : ( <>{c('Label').t`Duplicate found`}</> ) } /> <ModalTwoContent> <p> {originalIsDraft ? c('Info') .jt`It looks like you recently tried to upload ${uploadName}. If the upload failed, please ${replaceFile}. If the upload is still in progress, replacing it will cancel the ongoing upload.` : c('Info').jt`${uploadName} already exists in this location.`} <br /> {c('Info').t`What do you want to do?`} </p> <Row> <Radio id={TransferConflictStrategy.Replace} checked={strategy === TransferConflictStrategy.Replace} onChange={() => setStrategy(TransferConflictStrategy.Replace)} name="strategy" className="inline-flex flex-nowrap" > <div data-testid="replace-exiting"> <strong> {originalIsFolder ? c('Label').t`Replace existing folder` : c('Label').t`Replace existing file`} </strong> <br /> <span className="color-weak"> {isSameType ? ( <> {originalIsFolder ? c('Info').t`This will upload a new version of the folder` : c('Info').t`This will upload a new version of the file`} </> ) : ( <> {originalIsFolder ? c('Info').t`This will replace the existing folder with the file` : c('Info').t`This will replace the existing file with the folder`} </> )} </span> </div> </Radio> </Row> <Row> <Radio id={TransferConflictStrategy.Rename} checked={strategy === TransferConflictStrategy.Rename} onChange={() => setStrategy(TransferConflictStrategy.Rename)} name="strategy" className="inline-flex flex-nowrap" > <div data-testid="keep-both"> <strong> {isSameType ? ( <> {originalIsFolder ? c('Label').t`Keep both folders` : c('Label').t`Keep both files`} </> ) : ( <>{c('Label').t`Keep both`}</> )} </strong> <br /> <span className="color-weak"> {isFolder ? c('Info').t`A number will be added to the folder name` : c('Info').t`A number will be added to the filename`} </span> </div> </Radio> </Row> <Row> <Radio id={TransferConflictStrategy.Skip} checked={strategy === TransferConflictStrategy.Skip} onChange={() => setStrategy(TransferConflictStrategy.Skip)} name="strategy" className="inline-flex flex-nowrap" > <div data-testid="skip-upload"> <strong>{isFolder ? c('Label').t`Skip folder` : c('Label').t`Skip file`}</strong> <br /> <span className="color-weak"> {isFolder ? c('Info').t`Folder will not be uploaded` : c('Info').t`File will not be updated`} </span> </div> </Radio> </Row> <hr /> <Row> <Checkbox data-testid="apply-to-all" onChange={() => setApplyAll((value) => !value)}> {isFolder ? c('Label').t`Apply to all duplicated folders` : c('Label').t`Apply to all duplicated files`} </Checkbox> </Row> </ModalTwoContent> <ModalTwoFooter> <Button type="button" onClick={closeAndCancel}> {c('Action').t`Cancel all uploads`} </Button> <PrimaryButton type="submit">{c('Action').t`Continue`}</PrimaryButton> </ModalTwoFooter> </ModalTwo> ); } export const useConflictModal = () => { return useModalTwo<ConflictModalProps, void>(ConflictModal, false); };
2,807
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/CreateFileModal.tsx
import React, { ChangeEvent, FocusEvent, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { InputFieldTwo, ModalStateProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, PrimaryButton, useFormErrors, useModalTwo, } from '@proton/components'; import { useLoading } from '@proton/hooks'; import noop from '@proton/utils/noop'; import useActiveShare from '../../hooks/drive/useActiveShare'; import { formatLinkName, useActions, validateLinkNameField } from '../../store'; interface Props { onClose?: () => void; folder?: { shareId: string; linkId: string }; } const CreateFileModal = ({ onClose, folder, ...modalProps }: Props & ModalStateProps) => { const { activeFolder } = useActiveShare(); const { createFile } = useActions(); const [fileName, setFileName] = useState(''); const [loading, withLoading] = useLoading(); const { validator, onFormSubmit } = useFormErrors(); const handleBlur = ({ target }: FocusEvent<HTMLInputElement>) => { setFileName(formatLinkName(target.value)); }; const handleChange = ({ target }: ChangeEvent<HTMLInputElement>) => { setFileName(target.value); }; const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (!onFormSubmit()) { return; } let formattedName = formatLinkName(fileName); if (!formattedName.includes('.')) { formattedName = `${formattedName}.txt`; } const parentFolder = folder || activeFolder; if (!parentFolder) { return; } await createFile(parentFolder.shareId, parentFolder.linkId, formattedName); onClose?.(); }; return ( <ModalTwo as="form" disableCloseOnEscape={loading} onClose={onClose} onSubmit={(e: React.FormEvent) => withLoading(handleSubmit(e)).catch(noop)} size="large" {...modalProps} > <ModalTwoHeader closeButtonProps={{ disabled: loading }} title={c('Title').t`Create a new file`} /> <ModalTwoContent> <InputFieldTwo id="file-name" autoFocus value={fileName} label={c('Label').t`File name`} placeholder={c('Placeholder').t`Enter a new file name`} onChange={handleChange} onBlur={handleBlur} error={validator([validateLinkNameField(fileName) || ''])} required /> </ModalTwoContent> <ModalTwoFooter> <Button type="button" onClick={onClose} disabled={loading}> {c('Action').t`Cancel`} </Button> <PrimaryButton type="submit" loading={loading}> {c('Action').t`Create`} </PrimaryButton> </ModalTwoFooter> </ModalTwo> ); }; export default CreateFileModal; export const useCreateFileModal = () => { return useModalTwo<Props | void, void>(CreateFileModal, false); };
2,808
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/CreateFolderModal.tsx
import React, { ChangeEvent, FocusEvent, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { InputFieldTwo, ModalStateProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, PrimaryButton, useFormErrors, useModalTwo, } from '@proton/components'; import { useLoading } from '@proton/hooks'; import noop from '@proton/utils/noop'; import useActiveShare from '../../hooks/drive/useActiveShare'; import { formatLinkName, useActions, validateLinkNameField } from '../../store'; interface Props { onClose?: () => void; onCreateDone?: (folderId: string) => void; folder?: { shareId: string; linkId: string }; } const CreateFolderModal = ({ onClose, folder, onCreateDone, ...modalProps }: Props & ModalStateProps) => { const { activeFolder } = useActiveShare(); const { createFolder } = useActions(); const [folderName, setFolderName] = useState(''); const [loading, withLoading] = useLoading(); const { validator, onFormSubmit } = useFormErrors(); const handleBlur = ({ target }: FocusEvent<HTMLInputElement>) => { setFolderName(formatLinkName(target.value)); }; const handleChange = ({ target }: ChangeEvent<HTMLInputElement>) => { setFolderName(target.value); }; const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); if (!onFormSubmit()) { return; } const formattedName = formatLinkName(folderName); setFolderName(formattedName); const parentFolder = folder || activeFolder; if (!parentFolder) { return; } const folderId = await createFolder( new AbortController().signal, parentFolder.shareId, parentFolder.linkId, formattedName ); onCreateDone?.(folderId); onClose?.(); }; return ( <ModalTwo as="form" disableCloseOnEscape={loading} onClose={onClose} onSubmit={(e: React.FormEvent) => withLoading(handleSubmit(e)).catch(noop)} size="large" {...modalProps} > <ModalTwoHeader closeButtonProps={{ disabled: loading }} title={c('Title').t`Create a new folder`} /> <ModalTwoContent> <InputFieldTwo id="folder-name" autoFocus value={folderName} label={c('Label').t`Folder name`} placeholder={c('Placeholder').t`Enter a new folder name`} onChange={handleChange} onBlur={handleBlur} error={validator([validateLinkNameField(folderName) || ''])} data-testid="input-new-folder-name" required /> </ModalTwoContent> <ModalTwoFooter> <Button type="button" onClick={onClose} disabled={loading}> {c('Action').t`Cancel`} </Button> <PrimaryButton type="submit" loading={loading}> {c('Action').t`Create`} </PrimaryButton> </ModalTwoFooter> </ModalTwo> ); }; export default CreateFolderModal; export const useCreateFolderModal = () => { return useModalTwo<Props | void, void>(CreateFolderModal, false); };
2,809
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/DeleteLockedVolumesConfirmModal.tsx
import React, { useState } from 'react'; import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms'; import { Alert, Checkbox, ModalStateProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, useModalTwo, } from '@proton/components'; import { useLoading } from '@proton/hooks'; import { DRIVE_APP_NAME } from '@proton/shared/lib/constants'; import noop from '@proton/utils/noop'; interface Props { onClose?: () => void; onSubmit: () => Promise<unknown>; volumeCount: number; } const DeleteLockedVolumesConfirmModal = ({ onClose = noop, onSubmit, volumeCount, ...modalProps }: Props & ModalStateProps) => { const [isChecked, setIsChecked] = useState(false); const [isLoading, withLoading] = useLoading(); const modalTitle = c('Label').ngettext(msgid`Delete drive?`, `Delete drives?`, volumeCount); const warningTitle = c('Label').t`This will permanently delete all files in your locked drive.`; const warningInfo = c('Info') .t`Note: data may still be available locally on devices where you have installed ${DRIVE_APP_NAME}.`; const confirmationText = c('Label').t`Yes, I want to permanently delete my old files`; const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => { setIsChecked(e.target.checked); }; const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); return withLoading(onSubmit()); }; return ( <ModalTwo onClose={onClose} size="small" as="form" disableCloseOnEscape={isLoading} onSubmit={handleSubmit} {...modalProps} > <ModalTwoHeader title={modalTitle} /> <ModalTwoContent> <Alert type="warning" className="mb-8"> <span> <strong>{warningTitle}</strong> </span> </Alert> <p>{warningInfo}</p> <Checkbox onChange={handleChange}>{confirmationText}</Checkbox> </ModalTwoContent> <ModalTwoFooter> <Button type="button" onClick={onClose}> {c('Action').t`Back`} </Button> <Button color="danger" type="submit" disabled={!isChecked} loading={isLoading}> {c('Action').t`Delete`} </Button> </ModalTwoFooter> </ModalTwo> ); }; export default DeleteLockedVolumesConfirmModal; export const useDeleteLockedVolumesConfirmModal = () => { return useModalTwo<Props, void>(DeleteLockedVolumesConfirmModal, false); };
2,810
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/DetailsModal.tsx
import { ReactNode, useEffect, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Alert, FileNameDisplay, Icon, ModalStateProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, Row, Tooltip, useModalTwo, } from '@proton/components'; import EllipsisLoader from '@proton/components/components/loader/EllipsisLoader'; import { useLoading } from '@proton/hooks'; import { getNumAccessesTooltipMessage, getSizeTooltipMessage } from '@proton/shared/lib/drive/translations'; import humanSize, { bytesSize } from '@proton/shared/lib/helpers/humanSize'; import { DriveFileRevision, SignatureIssues, useLinkDetailsView } from '../../store'; import { ParsedExtendedAttributes } from '../../store/_links/extendedAttributes'; import useRevisions from '../../store/_revisions/useRevisions'; import { formatAccessCount } from '../../utils/formatters'; import { Cells } from '../FileBrowser'; import SignatureAlert from '../SignatureAlert'; import ModalContentLoader from './ModalContentLoader'; const { UserNameCell, LocationCell, TimeCell, DescriptiveTypeCell, MimeTypeCell } = Cells; export interface Props { shareId: string; linkId: string; onClose?: () => void; } interface RowProps { label: React.ReactNode; title?: string; children: ReactNode; dataTestId?: string; } interface RevisionDetailsModalProps { shareId: string; linkId: string; revision: DriveFileRevision; name: string; } export function RevisionDetailsModal({ shareId, linkId, revision, name, onClose, ...modalProps }: RevisionDetailsModalProps & ModalStateProps) { const { getRevisionDecryptedXattrs, checkRevisionSignature } = useRevisions(shareId, linkId); const [xattrs, setXattrs] = useState<ParsedExtendedAttributes>(); const [signatureIssues, setSignatureIssues] = useState<SignatureIssues>(); const [signatureNetworkError, setSignatureNetworkError] = useState<boolean>(false); const [isLoading, withIsLoading] = useLoading(); const [isSignatureLoading, withSignatureLoading] = useLoading(); useEffect(() => { const ac = new AbortController(); void withIsLoading( getRevisionDecryptedXattrs(ac.signal, revision.xAttr, revision.signatureAddress).then((decryptedXattrs) => { if (!decryptedXattrs) { return; } setXattrs(decryptedXattrs.xattrs); if (signatureIssues) { setSignatureIssues({ ...signatureIssues, ...decryptedXattrs.signatureIssues }); } else { setSignatureIssues(decryptedXattrs.signatureIssues); } }) ); return () => { ac.abort(); }; }, [revision.xAttr, revision.signatureAddress]); useEffect(() => { const ac = new AbortController(); void withSignatureLoading( checkRevisionSignature(ac.signal, revision.id).then((blocksSignatureIssues) => { if (signatureIssues) { setSignatureIssues({ ...signatureIssues, ...blocksSignatureIssues }); } else { setSignatureIssues(blocksSignatureIssues); } }) ).catch(() => { setSignatureNetworkError(true); }); return () => { ac.abort(); }; }, [revision.id]); const renderModalState = () => { return ( <ModalTwoContent> <SignatureAlert loading={isSignatureLoading} signatureIssues={signatureIssues} signatureNetworkError={signatureNetworkError} signatureAddress={revision.signatureAddress} isFile name={name} className="mb-4" /> <DetailsRow label={c('Title').t`Name`}> <FileNameDisplay text={name} /> </DetailsRow> <DetailsRow label={c('Title').t`Uploaded by`}> <span className="text-pre">{revision.signatureEmail}</span> </DetailsRow> <DetailsRow label={c('Title').t`Uploaded`}> <TimeCell time={revision.createTime} /> </DetailsRow> <DetailsRow label={c('Title').t`Modified`}> {xattrs?.Common.ModificationTime ? ( <TimeCell time={xattrs.Common.ModificationTime} /> ) : isLoading ? ( <EllipsisLoader /> ) : ( '-' )} </DetailsRow> <DetailsRow label={ <> {c('Title').t`Size`} <Tooltip title={c('Info') .t`The encrypted data is slightly larger due to the overhead of the encryption and signatures, which ensure the security of your data.`} className="ml-1 mb-1" > <Icon name="info-circle" size={14} alt={c('Info') .t`The encrypted data is slightly larger due to the overhead of the encryption and signatures, which ensure the security of your data.`} /> </Tooltip> </> } > <span title={bytesSize(revision.size)}>{humanSize(revision.size)}</span> </DetailsRow> <DetailsRow label={c('Title').t`Original size`}> {xattrs?.Common.Size ? ( <span title={bytesSize(xattrs?.Common.Size)}>{humanSize(xattrs?.Common.Size)}</span> ) : isLoading ? ( <EllipsisLoader /> ) : ( '-' )} </DetailsRow> {xattrs?.Common.Digests && ( // This should not be visible in the UI, but needed for e2e <span data-testid="drive:file-digest" className="hidden" aria-hidden="true"> {xattrs.Common.Digests.SHA1} </span> )} </ModalTwoContent> ); }; return ( <ModalTwo onClose={onClose} size="large" {...modalProps}> <ModalTwoHeader title={c('Title').t`Version details`} /> {renderModalState()} <ModalTwoFooter> <Button onClick={onClose}>{c('Action').t`Close`}</Button> </ModalTwoFooter> </ModalTwo> ); } export default function DetailsModal({ shareId, linkId, onClose, ...modalProps }: Props & ModalStateProps) { const { isLinkLoading, isSignatureIssuesLoading, isNumberOfAccessesLoading, error, link, signatureIssues, signatureNetworkError, numberOfAccesses, } = useLinkDetailsView(shareId, linkId); const renderModalState = () => { if (isLinkLoading) { return <ModalContentLoader>{c('Info').t`Loading link`}</ModalContentLoader>; } if (!link || error) { return ( <ModalTwoContent> <Alert type="error">{c('Info').t`Cannot load link`}</Alert> </ModalTwoContent> ); } const isShared = link.shareUrl && !link.shareUrl.isExpired ? c('Info').t`Yes` : c('Info').t`No`; return ( <ModalTwoContent> <SignatureAlert loading={isSignatureIssuesLoading} signatureIssues={signatureIssues} signatureNetworkError={signatureNetworkError} signatureAddress={link.signatureAddress} corruptedLink={link.corruptedLink} isFile={link.isFile} name={link.name} className="mb-4" /> <DetailsRow label={c('Title').t`Name`}> <FileNameDisplay text={link.name} /> </DetailsRow> <DetailsRow label={c('Title').t`Uploaded by`}> <UserNameCell /> </DetailsRow> {link.parentLinkId && ( <DetailsRow label={c('Title').t`Location`}> <LocationCell shareId={shareId} parentLinkId={link.parentLinkId} /> </DetailsRow> )} <DetailsRow label={c('Title').t`Uploaded`}> <TimeCell time={link.createTime} /> </DetailsRow> <DetailsRow label={c('Title').t`Modified`}> {link.corruptedLink ? '-' : <TimeCell time={link.fileModifyTime} />} </DetailsRow> {link.isFile && ( <> <DetailsRow label={c('Title').t`Type`}> <DescriptiveTypeCell mimeType={link.mimeType} isFile={link.isFile} /> </DetailsRow> <DetailsRow label={c('Title').t`MIME type`}> <MimeTypeCell mimeType={link.mimeType} /> </DetailsRow> <DetailsRow label={ <> {c('Title').t`Size`} <Tooltip title={getSizeTooltipMessage()} className="ml-1 mb-1"> <Icon name="info-circle" size={14} alt={getSizeTooltipMessage()} /> </Tooltip> </> } dataTestId="file-size" > <span title={bytesSize(link.size)}>{humanSize(link.size)}</span> </DetailsRow> {link.originalSize !== undefined && ( <DetailsRow label={c('Title').t`Original size`}> <span title={bytesSize(link.originalSize)}>{humanSize(link.originalSize)}</span> </DetailsRow> )} </> )} <DetailsRow label={c('Title').t`Shared`} dataTestId={'drive:is-shared'}> {isShared} </DetailsRow> {(numberOfAccesses !== undefined || isNumberOfAccessesLoading) && ( <DetailsRow label={ <> {c('Title').t`# of downloads`} <Tooltip title={getNumAccessesTooltipMessage()} className="ml-1 mb-1"> <Icon name="info-circle" size={14} alt={getNumAccessesTooltipMessage()} /> </Tooltip> </> } > {formatAccessCount(numberOfAccesses)} </DetailsRow> )} {link.digests && ( // This should not be visible in the UI, but needed for e2e <span data-testid="drive:file-digest" className="hidden" aria-hidden="true"> {link.digests.sha1} </span> )} {link.activeRevision?.photo?.contentHash && ( // This should not be visible in the UI, but needed for e2e <span data-testid="drive:photo-contentHash" className="hidden" aria-hidden="true"> {link.activeRevision.photo.contentHash} </span> )} </ModalTwoContent> ); }; return ( <ModalTwo onClose={onClose} size="large" {...modalProps}> <ModalTwoHeader title={getTitle(link?.isFile)} /> {renderModalState()} <ModalTwoFooter> <Button onClick={onClose}>{c('Action').t`Close`}</Button> </ModalTwoFooter> </ModalTwo> ); } function DetailsRow({ label, title, children, dataTestId }: RowProps) { return ( <Row title={title}> <span className="label cursor-default">{label}</span> <div className="pt-2" data-testid={dataTestId}> <b>{children}</b> </div> </Row> ); } function getTitle(isFile?: boolean) { if (isFile === undefined) { return c('Title').t`Item details`; } return isFile ? c('Title').t`File details` : c('Title').t`Folder details`; } export const useDetailsModal = () => { return useModalTwo<Props, unknown>(DetailsModal, false); }; export const useRevisionDetailsModal = () => { return useModalTwo<RevisionDetailsModalProps, unknown>(RevisionDetailsModal, false); };
2,811
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/DownloadIsTooBigModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { BasicModal, ModalStateProps, PrimaryButton, useModalTwo } from '@proton/components'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; type Props = { onCancel?: () => void; onSubmit?: () => void; }; export default function DownloadIsTooBigModal({ onSubmit, onCancel, onClose, open, ...modalProps }: Props & ModalStateProps) { const handleCancel = () => { onCancel?.(); onClose(); }; const recommendedBrowser = ( <a href={getKnowledgeBaseUrl('/recommended-browsers')} target="_blank"> {c('Info').t`recommended browser`} </a> ); return ( <BasicModal title={c('Title').t`Browser might run out of memory`} isOpen={open === undefined ? true : open} onClose={handleCancel} footer={ <> <Button onClick={handleCancel}>{c('Action').t`Cancel`}</Button> <PrimaryButton onClick={() => { onSubmit?.(); onClose(); }} > {c('Action').t`Download anyway`} </PrimaryButton> </> } {...modalProps} > <p>{c('Info') .jt`Your current browser does not support the downloading of large files due to the unavailability of service workers. Downloading large files may freeze or leave the browser unresponsive. Please use the latest versions of a ${recommendedBrowser} and try again.`}</p> </BasicModal> ); } export const useDownloadIsTooBigModal = () => { return useModalTwo<Props, void>(DownloadIsTooBigModal, false); };
2,812
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/DriveOnboardingModal.tsx
import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms'; import { Icon, Loader, ModalTwo, ModalTwoContent, OnboardingContent, OnboardingModal, OnboardingStep, OnboardingStepRenderCallback, } from '@proton/components'; import { DRIVE_APP_NAME } from '@proton/shared/lib/constants'; import drive1gbSvg from '@proton/styles/assets/img/onboarding/drive-1gb.svg'; import onboardingWelcome from '@proton/styles/assets/img/onboarding/drive-welcome.svg'; import useChecklist from '../onboarding/useChecklist'; interface Props { showGenericSteps?: boolean; onDone?: () => void; open?: boolean; } const DriveOnboardingModal = (props: Props) => { const { isLoading, expiresInDays } = useChecklist(); if (isLoading) { return ( <ModalTwo open={true} size="small"> <ModalTwoContent className="my-8"> <div className="flex flex-column flex-align-items-center"> <Loader size="medium" className="my-4" /> </div> </ModalTwoContent> </ModalTwo> ); } const onboardingSteps = [ ({ onNext, displayGenericSteps }: OnboardingStepRenderCallback) => ( <OnboardingStep> <OnboardingContent title={c('Onboarding Title').t`Welcome to ${DRIVE_APP_NAME}`} description={c('Onboarding Info') .t`Your trusty online vault for vital documents and precious memories.`} img={<img src={onboardingWelcome} alt={DRIVE_APP_NAME} />} /> <footer> <Button size="large" color="norm" fullWidth onClick={onNext}> {displayGenericSteps || expiresInDays > 0 ? c('Onboarding Action').t`Next` : c('Onboarding Action').t`Start using ${DRIVE_APP_NAME}`} </Button> </footer> </OnboardingStep> ), ]; if (expiresInDays > 0) { onboardingSteps.push(({ onNext, displayGenericSteps }: OnboardingStepRenderCallback) => ( <OnboardingStep> <OnboardingContent title={c('Onboarding Title').t`Your welcome bonus`} description={c('Onboarding Info') .t`Get started using ${DRIVE_APP_NAME} and we'll double your free storage to 1GB!`} img={<img src={drive1gbSvg} alt={DRIVE_APP_NAME} />} /> <div> {c('Onboarding Info').ngettext( msgid`Simply complete the following in the next ${expiresInDays} day:`, `Simply complete the following in the next ${expiresInDays} days:`, expiresInDays )} <ul className="unstyled mt-4"> <li className="my-2 flex flex-nowrap"> <Icon name="checkmark-circle" className="flex-item-noshrink mr-1 mt-0.5" /> <span className="flex-item-fluid">{c('Onboarding Info').t`Upload a file`}</span> </li> <li className="my-2 flex flex-nowrap"> <Icon name="checkmark-circle" className="flex-item-noshrink mr-1 mt-0.5" />{' '} <span className="flex-item-fluid">{c('Onboarding Info').t`Create a share link`}</span> </li> <li className="my-2 flex flex-nowrap"> <Icon name="checkmark-circle" className="flex-item-noshrink mr-1 mt-0.5" />{' '} <span className="flex-item-fluid">{c('Onboarding Info').t`Set a recovery method`}</span> </li> </ul> </div> <footer> <Button size="large" color="norm" fullWidth onClick={onNext}> {displayGenericSteps ? c('Onboarding Action').t`Next` : c('Onboarding Action').t`Start using ${DRIVE_APP_NAME}`} </Button> </footer> </OnboardingStep> )); } return <OnboardingModal {...props}>{onboardingSteps}</OnboardingModal>; }; export default DriveOnboardingModal;
2,813
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/DriveStartupModals.tsx
import { useEffect, useRef } from 'react'; import { FeatureCode, RebrandingFeedbackModal, getShouldOpenReferralModal, useFeature, useModalState, useRebrandingFeedback, useSubscription, } from '@proton/components'; import { OPEN_OFFER_MODAL_EVENT } from '@proton/shared/lib/constants'; const DriveStartupModals = () => { // Referral modal const [subscription] = useSubscription(); const seenReferralModal = useFeature<boolean>(FeatureCode.SeenReferralModal); const shouldOpenReferralModal = getShouldOpenReferralModal({ subscription, feature: seenReferralModal.feature }); const [rebrandingFeedbackModal, setRebrandingFeedbackModal, renderRebrandingFeedbackModal] = useModalState(); const handleRebrandingFeedbackModalDisplay = useRebrandingFeedback(); const onceRef = useRef(false); useEffect(() => { if (onceRef.current) { return; } const openModal = (setModalOpen: (newValue: boolean) => void) => { onceRef.current = true; setModalOpen(true); }; if (shouldOpenReferralModal.open) { onceRef.current = true; document.dispatchEvent(new CustomEvent(OPEN_OFFER_MODAL_EVENT)); } else if (handleRebrandingFeedbackModalDisplay) { openModal(setRebrandingFeedbackModal); } }, [shouldOpenReferralModal.open, handleRebrandingFeedbackModalDisplay]); return ( <> {renderRebrandingFeedbackModal && ( <RebrandingFeedbackModal onMount={handleRebrandingFeedbackModalDisplay} {...rebrandingFeedbackModal} /> )} </> ); }; export default DriveStartupModals;
2,814
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/FileThresholdModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms/index'; import { BasicModal, ModalStateProps, PrimaryButton, useModalTwo } from '@proton/components'; type Props = { type?: FileThresholdModalType; onSubmit: () => void; onCancel: () => void; }; export type FileThresholdModalType = 'fileNumberTotal' | 'fileSizeTotal'; export const FileThresholdModal = ({ onSubmit, onCancel, onClose, type = 'fileNumberTotal', open, ...modalProps }: Props & ModalStateProps) => { const handleCancel = () => { onCancel(); onClose?.(); }; return ( <BasicModal title={ type === 'fileNumberTotal' ? c('Title').t`Performance might be affected` : c('Title').t`Uploading a large file or folder` } isOpen={open === undefined ? true : open} onClose={handleCancel} footer={ <> <Button onClick={handleCancel}>{c('Action').t`Cancel`}</Button> <PrimaryButton onClick={() => { onSubmit(); onClose?.(); }} > {c('Action').t`Upload anyway`} </PrimaryButton> </> } {...modalProps} > <p> {type === 'fileNumberTotal' ? c('Info').t`Uploading hundreds of files at once may have a performance impact.` : c('Info') .t`For best results, avoid streaming and memory-intensive activities or split your upload into smaller batches.`} </p> </BasicModal> ); }; export const useFileThresholdModal = () => { return useModalTwo<Props, void>(FileThresholdModal, false); };
2,815
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/FilesDetailsModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Alert, Field, Label, ModalStateProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, Row, useModalTwo, } from '@proton/components'; import humanSize from '@proton/shared/lib/helpers/humanSize'; import { DecryptedLink, useLinksDetailsView } from '../../store'; import ModalContentLoader from './ModalContentLoader'; interface Props { selectedItems: DecryptedLink[]; onClose?: () => void; } const FilesDetailsModal = ({ selectedItems, onClose, ...modalProps }: Props & ModalStateProps) => { const { isLoading, hasError, count, size } = useLinksDetailsView(selectedItems); let title = c('Title').t`Item details`; let labelCount = c('Title').t`Number of items`; const renderModalState = () => { if (isLoading) { return <ModalContentLoader>{c('Info').t`Loading links`}</ModalContentLoader>; } if (hasError) { return ( <ModalTwoContent> <Alert type="error">{c('Info').t`Cannot load links`}</Alert> </ModalTwoContent> ); } return ( <ModalTwoContent> <Row> <Label style={{ cursor: 'default' }}>{labelCount}</Label> <Field className="pt-2"> <b data-testid="number-of-items">{count}</b> </Field> </Row> <Row> <Label style={{ cursor: 'default' }}>{c('Title').t`Total size`}</Label> <Field className="pt-2"> <b>{humanSize(size)}</b> </Field> </Row> </ModalTwoContent> ); }; return ( <ModalTwo onClose={onClose} size="large" {...modalProps}> <ModalTwoHeader title={title} /> {renderModalState()} <ModalTwoFooter> <Button onClick={onClose}>{c('Action').t`Close`}</Button> </ModalTwoFooter> </ModalTwo> ); }; export default FilesDetailsModal; export const useFilesDetailsModal = () => { return useModalTwo<Props, void>(FilesDetailsModal, false); };
2,816
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/KeyReactivationModal.tsx
import React, { useState } from 'react'; import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms'; import { ModalStateProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, RadioGroup, useModalTwo } from '@proton/components'; import { DRIVE_APP_NAME } from '@proton/shared/lib/constants'; import noop from '@proton/utils/noop'; import { LockedVolumeResolveMethod } from '../ResolveLockedVolumes/KeyReactivation/interfaces'; interface Props { defaultResolveMethod: LockedVolumeResolveMethod; onClose?: () => void; onSubmit?: (type: LockedVolumeResolveMethod) => void; volumeCount: number; } const OptionLabel = ({ title, info }: { title: string; info: string }) => { return ( <div className="ml-2"> <span className="text-bold">{title}</span> <p className="m-0 color-weak">{info}</p> </div> ); }; const KeyReactivationModal = ({ onClose, onSubmit = noop, defaultResolveMethod, volumeCount, ...modalProps }: Props & ModalStateProps) => { const [radioGroupValue, setRadioGroupValue] = useState<number>( defaultResolveMethod || LockedVolumeResolveMethod.ReactivateKeys ); const handleChange = (payload: LockedVolumeResolveMethod) => { setRadioGroupValue(payload); }; const questionText = <strong>{c('Info').t`What would you like to do?`}</strong>; const infoText = c('Info') .jt`One of your encrypted drives is locked. This is most likely due to a recent password reset.`; const deleteDriveLabelText = c('Info').ngettext(msgid`Delete locked drive`, `Delete locked drives`, volumeCount); const radioOptions = [ { label: ( <OptionLabel title={c('Label').t`Unlock drive (recommended)`} info={c('Info').t`Unlock drive to recover files`} /> ), value: LockedVolumeResolveMethod.ReactivateKeys, }, { label: ( <OptionLabel title={c('Label').t`Unlock later`} info={c('Info').t`Continue using ${DRIVE_APP_NAME} and unlock drive later`} /> ), value: LockedVolumeResolveMethod.UnlockLater, }, { label: ( <OptionLabel title={deleteDriveLabelText} info={c('Info').t`Permanently delete all files in your locked drive`} /> ), value: LockedVolumeResolveMethod.DeleteOldFiles, }, ]; return ( <ModalTwo onClose={onClose} onReset={onClose} onSubmit={(e: any) => { e.preventDefault(); onSubmit(radioGroupValue); if (radioGroupValue === LockedVolumeResolveMethod.UnlockLater) { onClose(); } }} size="small" as="form" {...modalProps} > <ModalTwoHeader title={c('Action').t`Drive Locked`} /> <ModalTwoContent onReset={noop} onSubmit={() => onSubmit(radioGroupValue)}> <p className="mt-0 mb-2">{infoText}</p> <p className="mt-2">{questionText}</p> <RadioGroup options={radioOptions} value={radioGroupValue} onChange={handleChange} name="action-type" className="flex-nowrap mb-4" /> </ModalTwoContent> <ModalTwoFooter> <Button type="reset">{c('Action').t`Cancel`}</Button> <Button color="norm" type="submit" data-testid="drive-key-reactivations-options:continue"> {c('Action').t`Continue`} </Button> </ModalTwoFooter> </ModalTwo> ); }; export default KeyReactivationModal; export const useKeyReactivationModal = () => { return useModalTwo<Props, void>(KeyReactivationModal, false); };
2,817
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/ModalContentLoader.tsx
import { ReactNode } from 'react'; import { Loader, ModalTwoContent, TextLoader } from '@proton/components'; const ModalContentLoader = ({ children }: { children: ReactNode }) => { return ( <div className="modal-content py-7"> <ModalTwoContent className="my-8"> <div className="flex flex-column flex-align-items-center"> <Loader size="medium" className="my-4" /> <TextLoader className="m-0">{children}</TextLoader> </div> </ModalTwoContent> </div> ); }; export default ModalContentLoader;
2,818
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/RenameModal.tsx
import React, { ChangeEvent, FocusEvent, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Field, InputFieldTwo, Label, ModalStateProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, PrimaryButton, Row, useModalTwo, } from '@proton/components'; import { useLoading } from '@proton/hooks'; import noop from '@proton/utils/noop'; import { DecryptedLink, formatLinkName, splitLinkName, useActions, validateLinkNameField } from '../../store'; interface Props { onClose?: () => void; item: DecryptedLink; } const RenameModal = ({ item, onClose, ...modalProps }: Props & ModalStateProps) => { const { renameLink } = useActions(); const [name, setName] = useState(item.name); const [loading, withLoading] = useLoading(); const [autofocusDone, setAutofocusDone] = useState(false); const selectNamePart = (e: FocusEvent<HTMLInputElement>) => { if (autofocusDone) { return; } setAutofocusDone(true); const [namePart] = splitLinkName(item.name); if (!namePart || !item.isFile) { return e.target.select(); } e.target.setSelectionRange(0, namePart.length); }; const handleBlur = ({ target }: FocusEvent<HTMLInputElement>) => { setName(formatLinkName(target.value)); }; const handleChange = ({ target }: ChangeEvent<HTMLInputElement>) => { setName(target.value); }; const ac = new AbortController(); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); const formattedName = formatLinkName(name); setName(formattedName); await renameLink(ac.signal, item.rootShareId, item.linkId, formattedName); onClose?.(); }; const validationError = validateLinkNameField(name); return ( <ModalTwo as="form" disableCloseOnEscape={loading} onClose={onClose} onSubmit={(e: React.FormEvent) => withLoading(handleSubmit(e)).catch(noop)} size="large" {...modalProps} > <ModalTwoHeader closeButtonProps={{ disabled: loading }} title={!item.isFile ? c('Title').t`Rename a folder` : c('Title').t`Rename a file`} /> <ModalTwoContent> <Row className="my-4"> <Label>{!item.isFile ? c('Label').t`Folder name` : c('Label').t`File name`}</Label> <Field> <InputFieldTwo id="link-name" value={name} autoFocus placeholder={c('Placeholder').t`New name`} onChange={handleChange} onBlur={handleBlur} onFocus={selectNamePart} error={validationError} required data-testid="input-rename" /> </Field> </Row> </ModalTwoContent> <ModalTwoFooter> <Button type="button" onClick={onClose} disabled={loading}> {c('Action').t`Cancel`} </Button> <PrimaryButton type="submit" loading={loading}> {c('Action').t`Rename`} </PrimaryButton> </ModalTwoFooter> </ModalTwo> ); }; export default RenameModal; export const useRenameModal = () => { return useModalTwo<Props, void>(RenameModal, false); };
2,819
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/SignatureIssueModal.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { Checkbox, Form, ModalStateProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, Radio, Row, useModalTwo, } from '@proton/components'; import { SignatureIssues } from '../../store'; import { TransferSignatureIssueStrategy } from '../../store'; import { SignatureAlertBody } from '../SignatureAlert'; interface ConflictModalProps { isFile: boolean; name: string; downloadName: string; signatureAddress?: string; signatureIssues: SignatureIssues; apply: (strategy: TransferSignatureIssueStrategy, all: boolean) => void; cancelAll: () => void; } export default function SignatureIssueModal({ isFile, name, downloadName, signatureAddress, signatureIssues, apply, cancelAll, onClose, ...modalProps }: ConflictModalProps & ModalStateProps) { const [strategy, setStrategy] = useState(TransferSignatureIssueStrategy.Abort); const [applyAll, setApplyAll] = useState(false); const handleClose = () => { cancelAll(); onClose(); }; const downloadFileName = ( <strong className="text-break" key="downloadFileName"> {downloadName} </strong> ); return ( <ModalTwo as={Form} onClose={handleClose} onSubmit={() => { apply(strategy, applyAll); onClose(); }} size="small" {...modalProps} > <ModalTwoHeader title={isFile ? c('Title').t`Download unverified file?` : c('Title').t`Download unverified folder?`} /> <ModalTwoContent> <p> <SignatureAlertBody signatureIssues={signatureIssues} signatureAddress={signatureAddress} isFile={isFile} name={name} /> </p> <p>{c('Info').t`What do you want to do?`}</p> <Row> <Radio id={TransferSignatureIssueStrategy.Abort} checked={strategy === TransferSignatureIssueStrategy.Abort} onChange={() => setStrategy(TransferSignatureIssueStrategy.Abort)} name="strategy" className="inline-flex flex-nowrap" > <div> <strong>{c('Label').t`Cancel download`}</strong> <br /> <span className="color-weak"> {c('Info').jt`Download of ${downloadFileName} will be aborted`} </span> </div> </Radio> </Row> <Row> <Radio id={TransferSignatureIssueStrategy.Continue} checked={strategy === TransferSignatureIssueStrategy.Continue} onChange={() => setStrategy(TransferSignatureIssueStrategy.Continue)} name="strategy" className="inline-flex flex-nowrap" > <div> <strong>{c('Label').t`Download anyway`}</strong> <br /> <span className="color-weak">{c('Info').t`Signature check will be ignored`}</span> </div> </Radio> </Row> <hr /> <Row> <Checkbox onChange={() => setApplyAll((value) => !value)}> {c('Label').t`Apply to all unverified items`} </Checkbox> </Row> </ModalTwoContent> <ModalTwoFooter> <Button onClick={handleClose}>{c('Action').t`Cancel all downloads`}</Button> <Button type="submit" color="norm"> {c('Action').t`Continue`} </Button> </ModalTwoFooter> </ModalTwo> ); } export const useSignatureIssueModal = () => { return useModalTwo<ConflictModalProps, void>(SignatureIssueModal, false); };
2,820
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/UnlockDriveConfirmationDialog.tsx
import React from 'react'; import { c } from 'ttag'; import { Button, ButtonLike } from '@proton/atoms'; import { ModalStateProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, SettingsLink, useModalTwo, } from '@proton/components'; import { APPS, BRAND_NAME, DRIVE_APP_NAME } from '@proton/shared/lib/constants'; import noop from '@proton/utils/noop'; interface Props { onBack?: () => void; onSubmit?: () => void; } const UnlockDriveConfirmationDialog = ({ onClose = noop, onSubmit = noop, ...modalProps }: Props & ModalStateProps) => { return ( <ModalTwo onClose={onClose} size="small" {...modalProps}> <ModalTwoHeader title={c('Label').t`Unlock drive`} /> <ModalTwoContent onSubmit={() => onSubmit()}> <p> {c('Info') .t`Because ${DRIVE_APP_NAME} is end-to-end encrypted, we cannot access or decrypt your files for you. To unlock your drive after a password reset, you must have one of the following:`} </p> <ul> <li>{c('Info').t`Your previous password`}</li> <li>{c('Info').t`An active recovery file`}</li> <li>{c('Info').t`Your previous recovery phrase`}</li> </ul> <p> {c('Info') .t`If you have one of these, continue to ${BRAND_NAME} Account setting to start the unblock process.`} </p> </ModalTwoContent> <ModalTwoFooter> <Button color="weak" type="button" onClick={onClose}> {c('Action').t`Back`} </Button> <ButtonLike as={SettingsLink} type="submit" color="norm" path="/recovery" app={APPS.PROTONDRIVE} data-testid="drive-key-reactivations-options:continue" onClick={onClose} > {c('Action').t`Continue`} </ButtonLike> </ModalTwoFooter> </ModalTwo> ); }; export default UnlockDriveConfirmationDialog; export const useUnlockDriveConfirmationDialog = () => { return useModalTwo<Props | void, void>(UnlockDriveConfirmationDialog, false); };
2,821
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/FilesRecoveryModal/FilesRecoveryModal.tsx
import { c } from 'ttag'; import { ModalStateProps, ModalTwo, useModalTwo, useNotifications } from '@proton/components'; import { useLoading } from '@proton/hooks'; import { useLockedVolume } from '../../../store'; import FilesRecoveryState from './FilesRecoveryState'; const FilesRecoveryModal = ({ onClose, ...modalProps }: ModalStateProps) => { const { restoreVolumes } = useLockedVolume(); const [recovering, withRecovering] = useLoading(); const { createNotification } = useNotifications(); const handleRecoveryClick = async () => { await withRecovering( restoreVolumes(new AbortController().signal) .then(() => { createNotification({ text: c('Success').t`Recovery has started`, }); }) .catch(() => onClose?.()) ); onClose?.(); }; return ( <ModalTwo onClose={onClose} {...modalProps}> <FilesRecoveryState recovering={recovering} onRecovery={handleRecoveryClick} onClose={onClose} /> </ModalTwo> ); }; export default FilesRecoveryModal; export const useFilesRecoveryModal = () => { return useModalTwo<void, void>(FilesRecoveryModal, false); };
2,822
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/FilesRecoveryModal/FilesRecoveryState.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Alert, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, PrimaryButton } from '@proton/components'; import keyAndFileSvg from '@proton/styles/assets/img/illustrations/file-recovery.svg'; interface Props { onRecovery: () => void; onClose?: () => void; recovering?: boolean; } const FilesRecoveryState = ({ onRecovery, onClose, recovering }: Props) => { const title = c('Title').t`Restore your files`; return ( <> <ModalTwoHeader title={c('Title').t`File recovery process`} closeButtonProps={{ disabled: recovering }} /> <ModalTwoContent> <div className="p-4 flex w-full"> <img src={keyAndFileSvg} alt={title} className="w-1/2 m-auto" /> </div> <Alert className="my-4"> <div>{c('Info').jt`Would you like to restore your files?`}</div> <div>{c('Info').jt`Recovery process might take some time.`}</div> </Alert> </ModalTwoContent> <ModalTwoFooter> <div className="flex flex-justify-space-between w-full flex-nowrap"> <Button disabled={recovering} autoFocus className="min-w-custom" style={{ '--min-w-custom': '7em' }} onClick={onClose} >{c('Action').t`Cancel`}</Button> <PrimaryButton loading={recovering} className="min-w-custom" style={{ '--min-w-custom': '7em' }} onClick={onRecovery} > {c('Action').t`Start recovering`} </PrimaryButton> </div> </ModalTwoFooter> </> ); }; export default FilesRecoveryState;
2,823
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/MoveToFolderModal/EmptyFileTreePlaceholder.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import noContentSvg from '@proton/styles/assets/img/illustrations/empty-folder.svg'; interface Props { onCreate: () => void; } const EmptyFileTreePlaceholder = ({ onCreate }: Props) => { const title = c('Title').t`You have no folders yet`; return ( <div className="p-4 flex flex-column flex-align-items-center w-full"> <img src={noContentSvg} alt={title} className="p-4 mb-4 w-1/2" /> <h2 className="text-bold">{title}</h2> <p className="m-0">{c('Info').t`Create your first folder and start moving your files.`}</p> <div className="my-8 flex flex-column w-custom" style={{ '--w-custom': '13em' }}> <Button size="large" color="norm" className="mx-4 mt-1 text-strong" onClick={onCreate}> {c('Action').t`Create`} </Button> </div> </div> ); }; export default EmptyFileTreePlaceholder;
2,824
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/MoveToFolderModal/ModalContent.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Alert, Icon, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, PrimaryButton, UnderlineButton, } from '@proton/components'; import { DecryptedLink, TreeItem } from '../../../store'; import FolderTree from '../../FolderTree/FolderTree'; import EmptyFileTreePlaceholder from './EmptyFileTreePlaceholder'; export const ModalContent = ({ rootItems, isLoading, isMoveDisabled, toggleExpand, selectedLinkId, onSelect, title, isMobile, onCreate, }: { rootItems: TreeItem[]; isLoading: boolean; isTreeLoaded: boolean; isMoveDisabled: boolean; toggleExpand: (linkId: string) => void; onSelect: (link: DecryptedLink) => void; title: string; isMobile: boolean; selectedLinkId: string | undefined; onCreate: (selectedFolder?: string) => void; }) => { if (rootItems.length === 0) { return ( <> <ModalTwoHeader closeButtonProps={{ disabled: isLoading }} /> <EmptyFileTreePlaceholder onCreate={() => onCreate(selectedLinkId)} /> </> ); } return ( <> <ModalTwoHeader title={title} closeButtonProps={{ disabled: isLoading }} /> <ModalTwoContent> <Alert className="mb-4">{c('Info').t`Select a folder to move to.`}</Alert> <FolderTree treeItems={rootItems} isLoaded={true} selectedItemId={selectedLinkId} onSelect={onSelect} toggleExpand={toggleExpand} /> </ModalTwoContent> <ModalTwoFooter> <div className="flex flex-justify-space-between w-full flex-nowrap"> {isMobile ? ( <Button icon disabled={isLoading || !selectedLinkId} onClick={() => onCreate(selectedLinkId)} title={c('Action').t`Create new folder`} > <Icon name="folder-plus" /> </Button> ) : ( <UnderlineButton disabled={isLoading || !selectedLinkId} onClick={() => onCreate(selectedLinkId)} > {c('Action').t`Create new folder`} </UnderlineButton> )} <div> <Button type="reset" disabled={isLoading} autoFocus> {c('Action').t`Close`} </Button> <PrimaryButton className="ml-4" loading={isLoading} type="submit" disabled={isMoveDisabled}> {c('Action').t`Move`} </PrimaryButton> </div> </div> </ModalTwoFooter> </> ); };
2,825
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/MoveToFolderModal/MoveToFolderModal.tsx
import React, { useState } from 'react'; import { c, msgid } from 'ttag'; import { ModalTwo, useActiveBreakpoint, useModalTwo } from '@proton/components'; import { useLoading } from '@proton/hooks'; import { DecryptedLink, useActions, useTreeForModals } from '../../../store'; import { selectMessageForItemList } from '../../sections/helpers'; import CreateFolderModal from '../CreateFolderModal'; import ModalContentLoader from '../ModalContentLoader'; import { ModalContent } from './ModalContent'; interface Props { shareId: string; selectedItems: DecryptedLink[]; onClose?: () => void; } const MoveToFolderModal = ({ shareId, selectedItems, onClose, ...modalProps }: Props) => { const { moveLinks } = useActions(); const { rootItems, expand, toggleExpand, isLoaded: isTreeLoaded, } = useTreeForModals(shareId, { rootExpanded: true, foldersOnly: true }); const [loading, withLoading] = useLoading(); const [selectedFolder, setSelectedFolder] = useState<string>(); const { isNarrow } = useActiveBreakpoint(); const [createFolderModal, showCreateFolderModal] = useModalTwo(CreateFolderModal); const moveLinksToFolder = async (parentFolderId: string) => { await moveLinks(new AbortController().signal, { shareId, linksToMove: selectedItems, newParentLinkId: parentFolderId, }); }; const onSelect = (link: DecryptedLink) => { if (!loading) { setSelectedFolder(link.linkId); } }; const handleSubmit = async () => { if (selectedFolder) { await moveLinksToFolder(selectedFolder); onClose?.(); } }; const handleCreateNewFolderClick = (selectedItemParentLinkId?: string) => { if (rootItems.length > 1 && selectedItemParentLinkId === undefined) { return; } const targetLinkId = selectedItemParentLinkId || rootItems[0]?.link.linkId || selectedItems[0]?.parentLinkId; if (!targetLinkId) { return; } void showCreateFolderModal({ folder: { shareId: shareId, linkId: targetLinkId }, onCreateDone: async (newFolderId: string) => { expand(targetLinkId); setSelectedFolder(newFolderId); }, }); }; const itemsToMove = selectedItems.map((item) => item.linkId); const itemsToMoveCount = itemsToMove.length; const messages = { allFiles: c('Notification').ngettext( msgid`Move ${itemsToMoveCount} file`, `Move ${itemsToMoveCount} files`, itemsToMoveCount ), allFolders: c('Notification').ngettext( msgid`Move ${itemsToMoveCount} folder`, `Move ${itemsToMoveCount} folders`, itemsToMoveCount ), mixed: c('Notification').ngettext( msgid`Move ${itemsToMoveCount} item`, `Move ${itemsToMoveCount} items`, itemsToMoveCount ), }; const isMoveDisabled = !selectedFolder || selectedItems.some((item) => [ item.linkId, // Moving folder to its own folder is not possible. item.parentLinkId, // Moving item to the same location is no-op. ].includes(selectedFolder) ); const title = selectMessageForItemList( selectedItems.map((item) => item.isFile), messages ); return ( <> <ModalTwo onClose={onClose} size="large" as="form" onSubmit={(e: React.FormEvent) => { e.preventDefault(); withLoading(handleSubmit()).catch(console.error); }} onReset={() => { onClose?.(); }} {...modalProps} > {isTreeLoaded ? ( <ModalContent isLoading={loading} isTreeLoaded={isTreeLoaded} title={title} rootItems={rootItems} selectedLinkId={selectedFolder} isMoveDisabled={isMoveDisabled} isMobile={isNarrow} toggleExpand={toggleExpand} onSelect={onSelect} onCreate={handleCreateNewFolderClick} /> ) : ( <ModalContentLoader>{c('Info').t`Loading`}</ModalContentLoader> )} </ModalTwo> {createFolderModal} </> ); }; export default MoveToFolderModal; export const useMoveToFolderModal = (): [JSX.Element | null, ({ shareId, selectedItems }: Props) => void] => { const [moveToFolderModal, showMoveToFolderModal] = useModalTwo<Props, void>(MoveToFolderModal, false); const handleShowMoveToFolderModal = ({ shareId, selectedItems }: Props) => { if (!shareId || !selectedItems.length) { return; } void showMoveToFolderModal({ shareId, selectedItems }); }; return [moveToFolderModal, handleShowMoveToFolderModal]; };
2,826
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/RemoveDeviceModal/RemoveDeviceModal.tsx
import React, { useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Form, InputFieldTwo, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, Row, useFormErrors, useModalTwo, } from '@proton/components'; import { useLoading } from '@proton/hooks'; import { DRIVE_APP_NAME } from '@proton/shared/lib/constants'; import { requiredValidator } from '@proton/shared/lib/helpers/formValidators'; import noop from '@proton/utils/noop'; import { Device, useActions } from '../../../store'; interface Props { onClose?: () => void; device: Device; } export const deviceNameValidator = (value: string, deviceName: string) => value !== deviceName ? c('Error').t`Device name does not match` : ''; const RemoveDeviceModal = ({ device, onClose, ...modalProps }: Props) => { const { removeDevice } = useActions(); const [submitting, withSubmitting] = useLoading(); const { validator, onFormSubmit } = useFormErrors(); const [model, setModel] = useState(() => { return { name: '', }; }); const handleSubmit = async () => { if (!onFormSubmit()) { return; } return removeDevice(device.id, new AbortController().signal).then(() => { onClose?.(); }); }; const deviceNameValidation = validator([ requiredValidator(model.name), deviceNameValidator(model.name, device.name), ]); const deviceName = <strong className="text-break">{device.name}</strong>; return ( <ModalTwo as={Form} disableCloseOnEscape={submitting} onClose={onClose} onReset={onClose} onSubmit={() => withSubmitting(handleSubmit()).catch(noop)} size="small" {...modalProps} > <ModalTwoHeader closeButtonProps={{ disabled: submitting }} title={c('Title').t`Remove device?`} /> <ModalTwoContent> <p key={'remove-device-modal-content-paragraph-1'}> {c('Info') .jt`This will remove the synced device ${deviceName} from ${DRIVE_APP_NAME} and stop syncing folders you added to My Computers.`} </p> <p key={'remove-device-modal-content-paragraph-2'}> {c('Info').t`Enter the device name to confirm removal.`} </p> <Row className="my-4"> <InputFieldTwo aria-required autoFocus label={c('Label').t`Device name`} placeholder={c('Placeholder').t`Enter device name`} title={c('Label').t`Enter device name`} error={deviceNameValidation} value={model.name} onValue={(value: string) => setModel({ name: value })} /> </Row> </ModalTwoContent> <ModalTwoFooter> <Button type="button" onClick={onClose} disabled={submitting}> {c('Action').t`Cancel`} </Button> <Button type="submit" loading={submitting} color="danger"> {c('Action').t`Remove device`} </Button> </ModalTwoFooter> </ModalTwo> ); }; export default RemoveDeviceModal; export const useRemoveDeviceModal = () => { return useModalTwo<Props, void>(RemoveDeviceModal, false); };
2,827
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/RemoveDeviceModal/index.ts
export { default } from './RemoveDeviceModal'; export { useRemoveDeviceModal } from './RemoveDeviceModal';
2,828
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/RenameDeviceModal/RenameDeviceModal.tsx
import React, { useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Form, InputFieldTwo, ModalStateProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, Row, useFormErrors, useModalTwo, } from '@proton/components'; import { useLoading } from '@proton/hooks'; import { requiredValidator } from '@proton/shared/lib/helpers/formValidators'; import noop from '@proton/utils/noop'; import { Device, useActions } from '../../../store'; interface Props { onClose?: () => void; device: Device; } const RenameDeviceModal = ({ device, onClose, ...modalProps }: Props & ModalStateProps) => { const { renameDevice } = useActions(); const [submitting, withSubmitting] = useLoading(); const { validator, onFormSubmit } = useFormErrors(); const [model, setModel] = useState(() => { return { name: device.name, }; }); const handleSubmit = async () => { if (!onFormSubmit()) { return; } await renameDevice({ shareId: device.shareId, linkId: device.linkId, deviceId: device.id, newName: model.name, haveLegacyName: device.haveLegacyName, }); onClose?.(); }; const deviceNameValidation = validator([requiredValidator(model.name)]); return ( <ModalTwo as={Form} disableCloseOnEscape={submitting} onClose={onClose} onReset={onClose} onSubmit={() => withSubmitting(handleSubmit()).catch(noop)} size="small" {...modalProps} > <ModalTwoHeader closeButtonProps={{ disabled: submitting }} title={c('Title').t`Rename device`} /> <ModalTwoContent> <Row className="my-4"> <InputFieldTwo aria-required autoFocus label={c('Label').t`Device name`} placeholder={c('Placeholder').t`Enter device name`} title={c('Label').t`Enter device name`} error={deviceNameValidation} value={model.name} onValue={(value: string) => setModel({ name: value })} /> </Row> </ModalTwoContent> <ModalTwoFooter> <Button type="button" onClick={onClose} disabled={submitting}> {c('Action').t`Cancel`} </Button> <Button type="submit" loading={submitting} disabled={device.name === model.name} color="norm"> {c('Action').t`Rename`} </Button> </ModalTwoFooter> </ModalTwo> ); }; export default RenameDeviceModal; export const useRenameDeviceModal = () => { return useModalTwo<Props, void>(RenameDeviceModal, false); };
2,829
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/RenameDeviceModal/index.ts
export { default } from './RenameDeviceModal'; export { useRenameDeviceModal } from './RenameDeviceModal';
2,830
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/ReportAbuseModal/FileCard.tsx
import React from 'react'; import { FileIcon, FileNameDisplay } from '@proton/components'; import clsx from '@proton/utils/clsx'; import { Cells } from '../../FileBrowser'; import { LinkInfo } from './types'; interface Props { linkInfo: LinkInfo; className?: string; } export const FileCard = ({ linkInfo, className }: Props) => { return ( <div className={clsx(['flex', 'flex-nowrap', 'rounded', 'border', 'p-4', 'flex-align-items-center', className])} > <div className="flex flex-column flex-nowrap bg-grey mr-4 flex-item-noshrink"> <FileIcon size={28} mimeType={linkInfo.mimeType} alt={linkInfo.name} /> </div> <div className="flex flex-column flex-nowrap"> <div className="text-bold flex w-full"> <FileNameDisplay text={linkInfo.name} /> </div> {linkInfo.mimeType !== 'Folder' && <Cells.SizeCell size={linkInfo.size} />} </div> </div> ); };
2,831
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/ReportAbuseModal/ReportAbuseModal.tsx
import React, { useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Form, InputFieldTwo, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, Option, PrimaryButton, SelectTwo, TextAreaTwo, useFormErrors, useNotifications, } from '@proton/components'; import { useLoading } from '@proton/hooks'; import { emailValidator, requiredValidator } from '@proton/shared/lib/helpers/formValidators'; import noop from '@proton/utils/noop'; import { sendErrorReport } from '../../../utils/errorHandling'; import { FileCard } from './FileCard'; import { AbuseCategory, AbuseCateroryType, AbuseFormProps, ReportAbuseRequestPayload } from './types'; const ABUSE_CATEGORIES: AbuseCategory[] = [ { type: 'spam', getText: () => c('Label').t`Spam`, }, { type: 'copyright', getText: () => c('Label').t`Copyright infringement`, }, { type: 'child-abuse', getText: () => c('Label').t`Child sexual abuse material`, }, { type: 'stolen-data', getText: () => c('Label').t`Stolen data`, }, { type: 'malware', getText: () => c('Label').t`Malware`, }, { type: 'other', getText: () => c('Label').t`Other`, }, ]; const CATEGORIES_WITH_EMAIL_VERIFICATION: AbuseCateroryType[] = ['copyright', 'stolen-data']; const ReportAbuseModal = ({ onClose = noop, linkInfo, onSubmit, open }: AbuseFormProps) => { const [submitting, withSubmitting] = useLoading(); const { createNotification } = useNotifications(); const { validator, onFormSubmit } = useFormErrors(); const [model, setModel] = useState(() => { return { Category: null as null | AbuseCateroryType, Email: '', Comment: '', }; }); const INFO_TEXT = c('Info').t`Use this form to notify us of inappropriate, illegal, or otherwise malicious shared files. You are about to report:`; const TEXTAREA_PLACEHOLDER = c('Label').t`Please provide full details to help us take appropriate action`; const handleChange = (key: keyof typeof model) => { return (value: any) => setModel({ ...model, [key]: value }); }; const handleSubmit = async () => { if (!onFormSubmit()) { return; } try { const payload: ReportAbuseRequestPayload = { linkId: linkInfo.linkId, abuseCategory: model.Category!, }; if (model.Email) { payload.reporterEmail = model.Email; } if (model.Comment) { payload.reporterMessage = model.Comment; } await onSubmit(payload); createNotification({ text: c('Info').t`Report has been sent` }); onClose?.(); } catch (e) { createNotification({ text: c('Error').t`Report failed to be sent`, type: 'error' }); sendErrorReport(e); } }; const requiresAdditionalValidation = CATEGORIES_WITH_EMAIL_VERIFICATION.includes(model.Category!) && model.Category !== null; const emailValidation = requiresAdditionalValidation ? validator([emailValidator(model.Email)]) : null; const commentValidation = requiresAdditionalValidation ? validator([requiredValidator(model.Comment)]) : null; return ( <ModalTwo as={Form} onClose={onClose} onReset={onClose} onSubmit={() => withSubmitting(handleSubmit()).catch(noop)} open={open} size="small" > <ModalTwoHeader title={c('Action').t`Submit report`} /> <ModalTwoContent> <p className="mt-0">{INFO_TEXT}</p> <FileCard linkInfo={linkInfo} className="mb-4" /> <div className="mb-2"> <InputFieldTwo aria-required as={SelectTwo} autoFocus disabled={submitting} error={validator([requiredValidator(model.Category)])} id="Category" label={c('Label').t`Category`} onValue={handleChange('Category')} placeholder={c('Label').t`Select type of abuse`} value={model.Category} > {ABUSE_CATEGORIES.map((option) => ( <Option title={option.getText()} value={option.type} key={option.type} /> ))} </InputFieldTwo> </div> <div className="mb-2"> <InputFieldTwo data-testid="report-abuse-email" disabled={submitting} error={emailValidation} id="LinkName" label={c('Label').t`Email`} onValue={handleChange('Email')} placeholder={c('Placeholder').t`Enter your email address`} type="email" value={model.Email} /> </div> <div className="mb-2"> <InputFieldTwo as={TextAreaTwo} disabled={submitting} error={commentValidation} id="Comment" label={c('Label').t`Comment`} onValue={handleChange('Comment')} placeholder={TEXTAREA_PLACEHOLDER} rows={2} value={model.Comment} /> </div> </ModalTwoContent> <ModalTwoFooter> <Button color="weak" type="reset" disabled={submitting} onClick={onClose}> {c('Action').t`Cancel`} </Button> <PrimaryButton type="submit" loading={submitting}> {c('Action').t`Submit`} </PrimaryButton> </ModalTwoFooter> </ModalTwo> ); }; export default ReportAbuseModal;
2,832
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/ReportAbuseModal/types.ts
export type ReportAbuseRequestPayload = { linkId: string; abuseCategory: AbuseCateroryType; reporterEmail?: string; reporterMessage?: string; }; export interface AbuseFormProps { onClose?: () => void; linkInfo: LinkInfo; onSubmit: (params: { linkId: string; abuseCategory: string; reporterEmail?: string; reporterMessage?: string; }) => Promise<void>; open?: boolean; } export type AbuseCateroryType = 'spam' | 'copyright' | 'child-abuse' | 'stolen-data' | 'malware' | 'other'; export interface AbuseCategory { type: AbuseCateroryType; getText: () => string; } export interface LinkInfo { name: string; mimeType: string; size: number; linkId: string; }
2,833
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/RevisionsModal/RevisionsModal.scss
.revisions-modal-list-separator { background-color: var(--border-weak); } .revisions-modal-list-title--current { color: var(--interaction-norm); }
2,834
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/RevisionsModal/RevisionsModal.tsx
import { c } from 'ttag'; import { ButtonLike, CircleLoader } from '@proton/atoms'; import { AppLink, ModalStateProps, ModalTwo, ModalTwoContent, ModalTwoHeader, RevisionsUpgradeBanner, getRetentionLabel, useModalTwo, useUser, } from '@proton/components'; import { APPS } from '@proton/shared/lib/constants'; import { RevisionRetentionDaysSetting } from '@proton/shared/lib/interfaces/drive/userSettings'; import { DecryptedLink, useUserSettings } from '../../../store'; import { RevisionList, RevisionsProvider, useRevisionsProvider } from '../../revisions'; import './RevisionsModal.scss'; interface Props { link: DecryptedLink; } const RevisionsSettingsBanner = ({ revisionRetentionDays, }: { revisionRetentionDays: RevisionRetentionDaysSetting; }) => { const retentionLabel = getRetentionLabel(revisionRetentionDays); return ( <div className="flex flex-align-items-center flex-justify-space-between"> <p className="m-0 color-weak"> {revisionRetentionDays === 0 ? c('Info').t`Previous versions are not saved` : c('Info').t`Previous versions are kept for ${retentionLabel}`} </p> <ButtonLike as={AppLink} to="/drive/version-history" toApp={APPS.PROTONACCOUNT} shape="solid" size="small" >{c('Action').t`Change`}</ButtonLike> </div> ); }; const RevisionsModalContent = () => { const [{ hasPaidDrive }] = useUser(); const { revisionRetentionDays } = useUserSettings(); const { isLoading, currentRevision, categorizedRevisions } = useRevisionsProvider(); return ( <> {hasPaidDrive ? ( <RevisionsSettingsBanner revisionRetentionDays={revisionRetentionDays} /> ) : ( <RevisionsUpgradeBanner /> )} {isLoading && <CircleLoader className="w-full m-auto mt-5" size="large" />} {!isLoading && currentRevision ? ( <RevisionList currentRevision={currentRevision} categorizedRevisions={categorizedRevisions} /> ) : null} </> ); }; const RevisionsModal = ({ link, ...modalProps }: Props & ModalStateProps) => { return ( <ModalTwo size="large" {...modalProps}> <ModalTwoHeader title={c('Title').t`Version history`} /> <ModalTwoContent className="mb-8"> <RevisionsProvider link={link}> <RevisionsModalContent /> </RevisionsProvider> </ModalTwoContent> </ModalTwo> ); }; export default RevisionsModal; export const useRevisionsModal = () => { return useModalTwo<Props, void>(RevisionsModal, false); };
2,835
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/RevisionsModal/index.ts
export { default } from './RevisionsModal';
2,836
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/SelectLinkToShareModal/EmptyFileTreePlaceholder.tsx
import { c } from 'ttag'; import noContentSvg from '@proton/styles/assets/img/illustrations/empty-folder.svg'; const EmptyFileTreePlaceholder = () => { const title = c('Title').t`You have no files to share`; return ( <div className="p-4 flex flex-column flex-align-items-center w-full"> <img src={noContentSvg} alt="" className="p-4 mb-4 w-1/3" /> <h2 className="text-bold">{title}</h2> <p className="m-0 pb-11">{c('Info').t`Go to "My files" and upload some files first.`}</p> </div> ); }; export default EmptyFileTreePlaceholder;
2,837
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/SelectLinkToShareModal/ModalContent.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Alert, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, PrimaryButton } from '@proton/components'; import { DecryptedLink, TreeItem } from '../../../store'; import FolderTree from '../../FolderTree/FolderTree'; import EmptyFileTreePlaceholder from './EmptyFileTreePlaceholder'; export const ModalContent = ({ rootItems, isLoading, isSharingDisabled, actionText, toggleExpand, onSelect, selectedLinkId, }: { rootItems: TreeItem[]; isLoading: boolean; isTreeLoaded: boolean; selectedLinkId: string | undefined; isSharingDisabled: boolean; actionText: string; toggleExpand: (linkId: string) => void; onSelect: (link: DecryptedLink) => void; }) => { if (rootItems.length === 0) { return ( <> <ModalTwoHeader closeButtonProps={{ disabled: isLoading }} /> <EmptyFileTreePlaceholder /> </> ); } return ( <> <ModalTwoHeader title={c('Action').t`Share item`} closeButtonProps={{ disabled: isLoading }} /> <ModalTwoContent> <Alert className="mb-4">{c('Info') .t`Select an uploaded file or folder and create a link to it.`}</Alert> <FolderTree treeItems={rootItems} isLoaded={true} selectedItemId={selectedLinkId} onSelect={onSelect} toggleExpand={toggleExpand} /> </ModalTwoContent> <ModalTwoFooter> <Button type="reset" className="w-custom" style={{ '--w-custom': '8em' }} disabled={isLoading}> {c('Action').t`Cancel`} </Button> <PrimaryButton className="ml-4 w-custom" style={{ '--w-custom': '8em' }} loading={isLoading} type="submit" disabled={isSharingDisabled} > {actionText} </PrimaryButton> </ModalTwoFooter> </> ); };
2,838
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/SelectLinkToShareModal/SelectLinkToShareModal.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { ModalStateProps, ModalTwo, useModalTwo } from '@proton/components'; import { useLoading } from '@proton/hooks'; import { DecryptedLink, useTreeForModals } from '../../../store'; import ModalContentLoader from '../ModalContentLoader'; import { useLinkSharingModal } from '../ShareLinkModal/ShareLinkModal'; import { ModalContent } from './ModalContent'; interface Props { shareId: string; showLinkSharingModal: ReturnType<typeof useLinkSharingModal>[1]; onClose?: () => void; } const SelectedFileToShareModal = ({ shareId, onClose, showLinkSharingModal, ...modalProps }: Props & ModalStateProps) => { const { rootItems, toggleExpand, isLoaded: isTreeLoaded } = useTreeForModals(shareId, { rootExpanded: true }); const [loading, withLoading] = useLoading(); const [selectedFile, setSelectedFile] = useState<DecryptedLink>(); const onSelect = async (link: DecryptedLink) => { if (!loading) { setSelectedFile(link); } }; const handleSubmit = async () => { if (selectedFile) { void showLinkSharingModal({ shareId, linkId: selectedFile.linkId }); onClose?.(); } }; const isSharingDisabled = !selectedFile || !selectedFile.parentLinkId; return ( <ModalTwo onReset={onClose} onClose={onClose} onSubmit={(e: any) => { e.preventDefault(); withLoading(handleSubmit()).catch(console.error); }} size="large" as="form" {...modalProps} > {isTreeLoaded ? ( <ModalContent isLoading={loading} isTreeLoaded={isTreeLoaded} rootItems={rootItems} selectedLinkId={selectedFile?.linkId} isSharingDisabled={isSharingDisabled} actionText={selectedFile?.shareUrl ? c('Action').t`Manage link` : c('Action').t`Create link`} toggleExpand={toggleExpand} onSelect={onSelect} /> ) : ( <ModalContentLoader>{c('Info').t`Loading`}</ModalContentLoader> )} </ModalTwo> ); }; export default SelectedFileToShareModal; export const useFileSharingModal = () => { return useModalTwo<Props, void>(SelectedFileToShareModal, false); };
2,839
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/ShareLinkModal/DateTime.tsx
import * as React from 'react'; import { format as formatDate, fromUnixTime } from 'date-fns'; import { dateLocale } from '@proton/shared/lib/i18n'; interface Props extends React.HTMLAttributes<HTMLTimeElement> { value: number; format?: string; } const DateTime = ({ value, format = 'PPp', ...rest }: Props) => { return <time {...rest}>{formatDate(fromUnixTime(value), format, { locale: dateLocale })}</time>; }; export default DateTime;
2,840
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/ShareLinkModal/ErrorState.tsx
import { PropsWithChildren } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Alert, ModalTwoContent, ModalTwoFooter, ModalTwoHeader } from '@proton/components'; interface Props { onClose?: () => void; } function ErrorState({ children, onClose }: PropsWithChildren<Props>) { return ( <> <ModalTwoHeader title={c('Title').t`Manage secure link`} /> <ModalTwoContent> <Alert className="mb-4" type="error"> {children} </Alert> </ModalTwoContent> <ModalTwoFooter> <Button onClick={onClose}>{c('Action').t`Done`}</Button> </ModalTwoFooter> </> ); } export default ErrorState;
2,841
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/ShareLinkModal/ExpirationTimeDatePicker.tsx
import { useState } from 'react'; import { fromUnixTime, getDate, getHours, getMinutes, getMonth, getUnixTime, getYear } from 'date-fns'; import { c } from 'ttag'; import { DateInput, TimeInput } from '@proton/components'; interface Props { expiration: number | null; handleExpirationChange: (exp: number) => void; disabled?: boolean; allowTime?: boolean; } const getMaxDate = () => { const date = new Date(); date.setDate(date.getDate() + 90); return date; }; const ExpirationTimeDatePicker = ({ expiration, handleExpirationChange, disabled, allowTime }: Props) => { const initialValue = expiration ? fromUnixTime(expiration) : undefined; const [expDate, setExpDate] = useState<Date | undefined>(initialValue); const [expTime, setExpTime] = useState<Date | undefined>(initialValue); const MIN_DATE = new Date(); const date = getMaxDate(); const MAX_DATE = date; const [maxTime, setMaxTime] = useState<Date | undefined>(expTime ? date : undefined); const handleChangeDate = (value: Date | undefined) => { if (value) { setExpDate(value); const year = getYear(value); const month = getMonth(value); const day = getDate(value); if (!expTime) { setExpTime(value); } if (year === getYear(MAX_DATE) && month === getMonth(MAX_DATE) && day === getDate(MAX_DATE)) { const date = getMaxDate(); setMaxTime(date); setExpTime(value); } else { setMaxTime(undefined); } let tempDate = value; if (expiration) { tempDate = fromUnixTime(expiration); tempDate.setFullYear(year); tempDate.setMonth(month); tempDate.setDate(day); } handleExpirationChange(getUnixTime(tempDate)); } }; const handleChangeTime = (value: Date) => { setExpTime(value); const hours = getHours(value); const minutes = getMinutes(value); if (expiration) { const tempDate = fromUnixTime(expiration); tempDate.setHours(hours); tempDate.setMinutes(minutes); handleExpirationChange(getUnixTime(tempDate)); } }; return ( <> <DateInput id="epirationDateInputId" className="flex-item-fluid flex-item-grow-2" disabled={disabled} value={expDate} onChange={handleChangeDate} displayWeekNumbers={false} min={MIN_DATE} max={MAX_DATE} placeholder={c('Title').t`Date`} title={c('Title').t`Select link expiration date`} hasToday={false} data-testid="epirationDateInputId" /> {allowTime && expTime && ( <TimeInput id="epirationTimeInputId" className="ml-2 flex-item-fluid" disabled={disabled} value={expTime} onChange={handleChangeTime} max={maxTime} title={c('Title').t`Select link expiration time`} data-testid="epirationTimeInputId" /> )} </> ); }; export default ExpirationTimeDatePicker;
2,842
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/ShareLinkModal/GeneratedLinkState.tsx
import { useEffect, useRef, useState } from 'react'; import { getUnixTime } from 'date-fns'; import { c, msgid } from 'ttag'; import { Button, Input } from '@proton/atoms'; import { Alert, Details, FileNameDisplay, Icon, InputFieldTwo, Label, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, PasswordInputTwo, PrimaryButton, Row, Summary, Toggle, useNotifications, } from '@proton/components'; import { textToClipboard } from '@proton/shared/lib/helpers/browser'; import ExpirationTimeDatePicker from './ExpirationTimeDatePicker'; const MAX_CUSTOM_PASSWORD_LENGTH = 50; interface Props { itemName: string; sharedInfoMessage: string; initialExpiration: number | null; url: string; passwordToggledOn: boolean; modificationDisabled: boolean; expirationToggledOn: boolean; customPassword: string; modalTitleID: string; deleting?: boolean; saving?: boolean; onClose?: () => void; onSaveLinkClick: ( password?: string, duration?: number | null ) => Promise<void | (unknown & { expirationTime: number | null })>; onDeleteLinkClick: () => void; onIncludePasswordToggle: () => void; onIncludeExpirationTimeToogle: () => void; onFormStateChange: (state: { isFormDirty: boolean }) => void; } function GeneratedLinkState({ itemName, sharedInfoMessage, initialExpiration, url, customPassword, deleting, saving, passwordToggledOn, modificationDisabled, expirationToggledOn, onSaveLinkClick, onDeleteLinkClick, onIncludePasswordToggle, onIncludeExpirationTimeToogle, onFormStateChange, }: Props) { const contentRef = useRef<HTMLDivElement>(null); const { createNotification } = useNotifications(); const [password, setPassword] = useState(customPassword); const [expiration, setExpiration] = useState(initialExpiration); const [additionalSettingsExpanded, setAdditionalSettingsExpanded] = useState( Boolean(customPassword || initialExpiration) ); const isFormDirty = Boolean( (expiration !== initialExpiration && expirationToggledOn) || (initialExpiration && !expirationToggledOn) || (password !== customPassword && passwordToggledOn) || (!passwordToggledOn && customPassword) ); const isPasswordInvalid = password.length > MAX_CUSTOM_PASSWORD_LENGTH; const isFormInvalid = isPasswordInvalid; const isSaveDisabled = !isFormDirty || deleting || (passwordToggledOn && !password) || (expirationToggledOn && !expiration) || isFormInvalid; const handleChangePassword = (e: React.ChangeEvent<HTMLInputElement>) => { setPassword(e.target.value); }; useEffect(() => { onFormStateChange({ isFormDirty }); }, [isFormDirty, onFormStateChange]); const handleCopyURLClick = () => { if (contentRef.current) { textToClipboard(url, contentRef.current); createNotification({ text: c('Success').t`The link to your file was successfully copied`, }); } }; const handleSubmit = async () => { // The idea here is following: // newCustomPassword is undefined in case we don't want to update it // or newCustomPassword is an empty string when password needs to be removed // or newCustomPassword is, well, a password string let newCustomPassword; if (!passwordToggledOn) { if (customPassword.length !== 0) { newCustomPassword = ''; } } else if (password !== customPassword) { newCustomPassword = password; } let newDuration: number | null | undefined = null; if (expirationToggledOn) { newDuration = expiration && expiration !== initialExpiration ? expiration - getUnixTime(Date.now()) : undefined; } const result = await onSaveLinkClick(newCustomPassword, newDuration); // Because we are dealing with duration, ExpirationTime on server is expiration + request time. if (result && result?.expirationTime) { setExpiration(result.expirationTime); } }; const boldNameText = ( <span key="name" style={{ whiteSpace: 'nowrap' }}> <b> <FileNameDisplay text={itemName} className="max-w-4/5" /> </b> : </span> ); return ( <> <ModalTwoHeader title={c('Title').t`Share via link`} closeButtonProps={{ disabled: saving || deleting }} /> <ModalTwoContent> <div ref={contentRef}> <p data-testid="shareable-info-text">{c('Info').jt`Shareable link for ${boldNameText}`} </p> <Row className="mb-2 md:mb-0"> <div className="flex flex-item-fluid mb-2 md:mb-0"> <Input readOnly value={url} className="no-scroll text-ellipsis" data-testid="sharing-modal-url" /> </div> <div className="flex-no-min-children flex-justify-end ml-0 md:ml-2"> <PrimaryButton id="copy-url-button" onClick={handleCopyURLClick} className="min-w-custom" style={{ '--min-w-custom': '7em' }} >{c('Action').t`Copy link`}</PrimaryButton> </div> </Row> <Alert data-testid="secure-link-text" className="mb-4"> {sharedInfoMessage} </Alert> <Details open={additionalSettingsExpanded} onToggle={() => { setAdditionalSettingsExpanded(!additionalSettingsExpanded); }} className="border-none" > <Summary tabIndex={0}> <h3>{c('Title').t`Privacy settings`}</h3> </Summary> {modificationDisabled ? ( <Alert type="warning"> {c('Info') .t`This link was created with old Drive version and can not be modified. Delete this link and create a new one to change the settings.`} </Alert> ) : ( <> <div className="flex-no-min-children flex-nowrap mb-4 on-mobile-flex-column mb-2 md:mb-0"> <Label htmlFor="passwordModeToggle"> <span className="mr-2">{c('Label').t`Protect with password`}</span> </Label> <div className="flex flex-justify-start pt-2 mr-0 md:mr-2" data-testid="sharing-modal-passwordModeToggle" > <Toggle id="passwordModeToggle" className="mb-2 md:mb-0" disabled={saving} checked={passwordToggledOn} onChange={() => { onIncludePasswordToggle(); if (!passwordToggledOn) { setPassword(customPassword); } }} /> </div> <div className="flex-no-min-children flex-item-fluid mb-2 md:mb-0 field-two-icon-container-empty min-h-0 md:min-h-none"> {passwordToggledOn && ( <> <InputFieldTwo id="sharing-modal-password" as={PasswordInputTwo} data-testid="sharing-modal-password" labelContainerClassName="sr-only" label={c('Label').t`Password`} disabled={saving} value={password} error={ isPasswordInvalid && c('Info').ngettext( msgid`Only ${MAX_CUSTOM_PASSWORD_LENGTH} character is allowed`, `Only ${MAX_CUSTOM_PASSWORD_LENGTH} characters are allowed`, MAX_CUSTOM_PASSWORD_LENGTH ) } assistiveText={`${password.length}/${MAX_CUSTOM_PASSWORD_LENGTH}`} onInput={handleChangePassword} /> </> )} </div> </div> <div className="flex-no-min-children flex-nowrap on-mobile-flex-column mb-2 md:mb-4"> <Label htmlFor="expirationTimeModeToggle"> <span className="mr-2">{c('Label').t`Set expiration date`}</span> </Label> <div className="flex flex-justify-start pt-2 mr-0 md:mr-2" data-testid="sharing-modal-expirationTimeModeToggle" > <Toggle id="expirationTimeModeToggle" className="mb-2 md:mb-0" disabled={saving} checked={expirationToggledOn} onChange={onIncludeExpirationTimeToogle} /> </div> <div className="flex-no-min-children flex-item-fluid flex-align-items-center mb-2 md:mb-0 field-two-icon-container-empty min-h-0 md:min-h-none"> {expirationToggledOn && ( <ExpirationTimeDatePicker disabled={saving} allowTime={false} expiration={expiration} handleExpirationChange={(exp: number) => setExpiration(exp)} /> )} </div> </div> </> )} </Details> </div> </ModalTwoContent> <ModalTwoFooter> <div className="flex flex-justify-space-between w-full"> <Button loading={deleting} disabled={saving} onClick={onDeleteLinkClick} className="mb-2 md:mb-0 inline-flex flex-align-items-center" > <Icon name="link-slash" className="mr-2" /> {c('Action').t`Stop sharing`} </Button> <div className="ml-auto"> <PrimaryButton loading={saving} disabled={isSaveDisabled} className="ml-4" type="submit" onClick={(e) => { e.preventDefault(); void handleSubmit(); }} > {c('Action').t`Save`} </PrimaryButton> </div> </div> </ModalTwoFooter> </> ); } export default GeneratedLinkState;
2,843
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/ShareLinkModal/ShareLinkModal.scss
.field.field--accented, .accented { color: var(--primary); font-weight: var(--font-weight-bold); }
2,844
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/ShareLinkModal/ShareLinkModal.tsx
import { useEffect, useState } from 'react'; import { c } from 'ttag'; import { ModalStateProps, ModalTwo, useConfirmActionModal, useModalTwo } from '@proton/components'; import { useShareURLView } from '../../../store'; import ModalContentLoader from '../ModalContentLoader'; import ErrorState from './ErrorState'; import GeneratedLinkState from './GeneratedLinkState'; interface Props { modalTitleID?: string; shareId: string; linkId: string; } export function ShareLinkModal({ modalTitleID = 'share-link-modal', shareId, linkId, onClose, ...modalProps }: Props & ModalStateProps) { const [confirmActionModal, showConfirmActionModal] = useConfirmActionModal(); const { isDeleting, isSaving, name, initialExpiration, customPassword, sharedLink, confirmationMessage, loadingMessage, errorMessage, sharedInfoMessage, hasCustomPassword, hasGeneratedPasswordIncluded, hasExpirationTime, saveSharedLink, deleteLink, } = useShareURLView(shareId, linkId); const [passwordToggledOn, setPasswordToggledOn] = useState(false); const [expirationToggledOn, setExpirationToggledOn] = useState(false); const [isSharingFormDirty, setIsSharingFormDirty] = useState(false); const handleFormStateChange = ({ isFormDirty }: { isFormDirty: boolean }) => { setIsSharingFormDirty(isFormDirty); }; useEffect(() => { if (!loadingMessage) { setPasswordToggledOn(hasCustomPassword); setExpirationToggledOn(hasExpirationTime); } }, [loadingMessage]); const handleDeleteLink = async () => { void showConfirmActionModal({ title: c('Title').t`Stop sharing with everyone?`, submitText: c('Action').t`Stop sharing`, message: confirmationMessage, canUndo: true, onSubmit: () => deleteLink().finally(() => onClose()), }); }; const handleClose = () => { if (!isSharingFormDirty) { onClose?.(); return; } void showConfirmActionModal({ title: c('Title').t`Discard changes?`, submitText: c('Title').t`Discard`, message: c('Info').t`You will lose all unsaved changes.`, onSubmit: async () => onClose?.(), canUndo: true, }); }; const toggleIncludePassword = () => { setPasswordToggledOn((passwordToggledOn) => !passwordToggledOn); }; const toggleIncludeExpirationTime = () => { setExpirationToggledOn((expirationToggledOn) => !expirationToggledOn); }; const renderModalState = () => { if (errorMessage) { return <ErrorState onClose={onClose}>{errorMessage}</ErrorState>; } if (loadingMessage) { return <ModalContentLoader>{loadingMessage}</ModalContentLoader>; } return ( <GeneratedLinkState modalTitleID={modalTitleID} passwordToggledOn={passwordToggledOn} expirationToggledOn={expirationToggledOn} itemName={name} sharedInfoMessage={sharedInfoMessage} onClose={handleClose} onIncludePasswordToggle={toggleIncludePassword} onIncludeExpirationTimeToogle={toggleIncludeExpirationTime} onSaveLinkClick={saveSharedLink} onDeleteLinkClick={handleDeleteLink} onFormStateChange={handleFormStateChange} customPassword={customPassword} initialExpiration={initialExpiration} url={sharedLink} modificationDisabled={!hasGeneratedPasswordIncluded} deleting={isDeleting} saving={isSaving} /> ); }; return ( <> <ModalTwo as="form" onClose={handleClose} onReset={(e: any) => { e.preventDefault(); handleClose(); }} disableCloseOnEscape={isSaving || isDeleting} size="large" {...modalProps} > {renderModalState()} </ModalTwo> {confirmActionModal} </> ); } export default ShareLinkModal; export const useLinkSharingModal = () => { return useModalTwo<Props, void>(ShareLinkModal, false); };
2,845
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/UpsellFloatingModal/UpsellFloatingModal.scss
@import '~@proton/styles/scss/lib'; .upsell-floating-modal { position: fixed; inset-block: auto 0; inset-inline: auto 0; } .upsell-floating-modal-content { background-color: #1b1340; } .upsell-floating-modal-dialog { --size: #{rem(360)}; --margin: #{rem(24)}; } .upsell-floating-modal-badge { background-color: #eef8f5; color: #2c9f78; } .upsell-floating-modal-tooltip { // Override default theme --text-norm: white; position: absolute; inset-inline-end: rem(12); inset-block-start: rem(12); }
2,846
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/UpsellFloatingModal/UpsellFloatingModal.tsx
import { MouseEvent as ReactMouseEvent, useLayoutEffect, useRef, useState } from 'react'; import { c } from 'ttag'; import { Button, ButtonLike } from '@proton/atoms/Button'; import { Icon, ModalStateProps, ModalTwo, ModalTwoFooter, Tooltip } from '@proton/components/components'; import Dialog from '@proton/components/components/dialog/Dialog'; import { Portal } from '@proton/components/components/portal'; import { useActiveBreakpoint } from '@proton/components/hooks'; import usePrevious from '@proton/hooks/usePrevious'; import { modalTwoRootClassName } from '@proton/shared/lib/busy'; import { DRIVE_APP_NAME } from '@proton/shared/lib/constants'; import { DRIVE_PRICING_PAGE } from '@proton/shared/lib/drive/urls'; import bigLogoWhite from '@proton/styles/assets/img/drive/big-logo-white.svg'; import clsx from '@proton/utils/clsx'; import './UpsellFloatingModal.scss'; interface ChildProps { open: boolean; onClose: () => void; onBlockNewOpening: () => void; } const UpsellFloatingModalContent = ({ onClose }: Pick<ChildProps, 'onClose'>) => { return ( <> <div className="upsell-floating-modal-content w-full flex flex-justify-center p-14"> <Tooltip className="upsell-floating-modal-tooltip" title={c('Action').t`Close`} onClick={onClose}> <Button className="flex-item-noshrink" icon shape="ghost" data-testid="modal:close"> <Icon className="modal-close-icon" name="cross-big" alt={c('Action').t`Close`} /> </Button> </Tooltip> <img className="block" src={bigLogoWhite} alt={DRIVE_APP_NAME} /> </div> <div className="my-4 mx-5"> <span className="upsell-floating-modal-badge text-semibold rounded py-1 px-4 mt-2">{c('Info') .t`Free forever`}</span> <h4 className="text-bold mt-3">{c('Info').t`Swiss encrypted file storage`}</h4> <p className="m-0 mt-1"> {c('Info') .t`With ${DRIVE_APP_NAME}, your data is protected with end-to-end encryption. Only you can decrypt it.`} </p> </div> <ModalTwoFooter> <ButtonLike as="a" href={DRIVE_PRICING_PAGE} target="_blank" className="w-full" color="norm">{c('Action') .t`Get ${DRIVE_APP_NAME}`}</ButtonLike> </ModalTwoFooter> </> ); }; enum ExitState { idle, exiting, exited, } const DesktopUpsellFloatingModal = ({ open, onClose, onBlockNewOpening }: ChildProps) => { const [exit, setExit] = useState(() => (open ? ExitState.idle : ExitState.exited)); const active = exit !== ExitState.exited; const previousOpen = usePrevious(open); useLayoutEffect(() => { if (!previousOpen && open) { setExit(ExitState.idle); } else if (previousOpen && !open) { setExit(ExitState.exiting); } else if (!previousOpen && !open && !active) { onBlockNewOpening(); } }, [previousOpen, open, active]); if (!active) { return null; } const exiting = exit === ExitState.exiting; return ( <Portal> <div className={clsx(modalTwoRootClassName, 'upsell-floating-modal', exiting && 'modal-two--out')} onAnimationEnd={({ animationName }) => { if (exiting && animationName === 'anime-modal-two-out') { setExit(ExitState.exited); } }} > <Dialog className="modal-two-dialog upsell-floating-modal-dialog "> <div className="modal-two-dialog-container"> <UpsellFloatingModalContent onClose={onClose} /> </div> </Dialog> </div> </Portal> ); }; const MobileUpsellFloatingModal = ({ open, onClose, onBlockNewOpening }: ChildProps) => { const ref = useRef<HTMLDivElement>(null); const handleClose = () => { onClose(); onBlockNewOpening(); }; // We listen for click outside and test if the click will contain the ref const handleOutsideClick = (e: ReactMouseEvent<HTMLDivElement, MouseEvent>) => { if (e.target && !ref.current?.contains(e.target as Element)) { handleClose(); } }; return ( // TODO: need to find a better way than put a click on div <div onClick={handleOutsideClick}> <ModalTwo open={open} onClose={handleClose}> <div ref={ref}> <UpsellFloatingModalContent onClose={handleClose} /> </div> </ModalTwo> </div> ); }; interface Props { onResolve: () => void; onlyOnce: boolean; } const UpsellFloatingModal = ({ onlyOnce = false, ...modalProps }: Props & ModalStateProps) => { const { isNarrow } = useActiveBreakpoint(); const [wasOpened, setWasOpened] = useState(false); const handleBlockNewOpening = () => { if (onlyOnce) { setWasOpened(true); } }; const props = { ...modalProps, onBlockNewOpening: handleBlockNewOpening, }; if (wasOpened) { return null; } if (isNarrow) { return <MobileUpsellFloatingModal {...props} />; } return <DesktopUpsellFloatingModal {...props} />; }; export default UpsellFloatingModal;
2,847
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/UpsellFloatingModal/constants.ts
export const UPSELL_MODAL_TIMEOUT = 10000;
2,848
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/UpsellFloatingModal/index.ts
export { default } from './UpsellFloatingModal'; export { default as useUpsellFloatingModal } from './useUpsellFloatingModal';
2,849
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/modals/UpsellFloatingModal/useUpsellFloatingModal.tsx
import { useEffect } from 'react'; import { useModalTwo } from '@proton/components'; import { useActiveBreakpoint } from '@proton/components/hooks'; import { IS_PROTON_USER_COOKIE_NAME } from '@proton/components/hooks/useIsProtonUserCookie'; import { getCookie } from '@proton/shared/lib/helpers/cookies'; import { useDownload } from '../../../store'; import UpsellFloatingModal from './UpsellFloatingModal'; import { UPSELL_MODAL_TIMEOUT } from './constants'; interface ModalProps { onlyOnce?: true; } const useUpsellFloatingModal = (): ReturnType<typeof useModalTwo<ModalProps, unknown>> => { const [renderUpsellFloatingModal, showUpsellFloatingModal] = useModalTwo<ModalProps | void, unknown>( UpsellFloatingModal, false ); const { isNarrow } = useActiveBreakpoint(); const { hasDownloads } = useDownload(); // If user is proton user we disable upsell auto-show const isProtonUser = !!getCookie(IS_PROTON_USER_COOKIE_NAME); useEffect(() => { if (isProtonUser) { return; } if (hasDownloads) { void showUpsellFloatingModal({ onlyOnce: true }); } }, [hasDownloads, isProtonUser]); useEffect(() => { if (isNarrow || isProtonUser) { return; } const timeout = setTimeout(() => { void showUpsellFloatingModal(); }, UPSELL_MODAL_TIMEOUT); return () => { clearTimeout(timeout); }; }, [isNarrow, isProtonUser]); return [renderUpsellFloatingModal, showUpsellFloatingModal]; }; export default useUpsellFloatingModal;
2,850
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/onboarding/GiftFloatingButton.tsx
import { useEffect, useState } from 'react'; import { c, msgid } from 'ttag'; import { ThemeColorUnion } from '@proton/colors'; import { FloatingButton, Icon, IconName, Row, Spotlight, useActiveBreakpoint, useAuthentication, useDrawerWidth, useLocalState, } from '@proton/components'; import { getAppHref } from '@proton/shared/lib/apps/helper'; import { getSlugFromApp } from '@proton/shared/lib/apps/slugHelper'; import { APPS, BRAND_NAME, DRIVE_APP_NAME } from '@proton/shared/lib/constants'; import { rootFontSize } from '@proton/shared/lib/helpers/dom'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { ChecklistKey } from '@proton/shared/lib/interfaces'; import spotlightIcon from '@proton/styles/assets/img/illustrations/spotlight-stars.svg'; import clsx from '@proton/utils/clsx'; import useActiveShare from '../../hooks/drive/useActiveShare'; import { useFileUploadInput } from '../../store'; import { useFileSharingModal } from '../modals/SelectLinkToShareModal/SelectLinkToShareModal'; import { useLinkSharingModal } from '../modals/ShareLinkModal/ShareLinkModal'; import useChecklist from './useChecklist'; export default function GiftFloatingButton() { const checklist = useChecklist(); const { isNarrow } = useActiveBreakpoint(); if (isNarrow || checklist.isLoading || checklist.expiresInDays === 0 || !checklist.isVisible) { return null; } if (checklist.isCompleted) { return <WelcomeActionsDoneSpotlight onSeen={checklist.markCompletedAsSeen} />; } return ( <WelcomeActionsSpotlight reloadChecklist={checklist.reload} completedActions={checklist.completedActions} expiresInDays={checklist.expiresInDays} /> ); } function WelcomeActionsDoneSpotlight({ onSeen }: { onSeen: (dismiss?: boolean) => void }) { const [show, setShow] = useState(false); // Wait a bit so user can see it opening it up (if opened right away, // it might feel as part of the page), and also it allows JS to properly // calculate position of the modal when everything is rendered. useEffect(() => { setTimeout(() => { setShow(true); // Product wants to mark it seen on backend automatically. onSeen(false); }, 1000); }, []); const spotlightContent = ( <div className="flex flex-nowrap"> <figure className="flex-item flex-item-noshrink mr-4"> <img src={spotlightIcon} alt="" /> </figure> <div className="flex-item"> <h6 className="text-semibold">{c('Title').t`You’ve got 1 GB of storage`}</h6> <div className="mb-4 color-weak">{c('Info').t`Way to go, you’ve just doubled your free storage!`}</div> </div> </div> ); return ( <FloatingSpotlight content={spotlightContent} show={show} onClick={onSeen} color="success" icon="checkmark" /> ); } function WelcomeActionsSpotlight({ reloadChecklist, completedActions, expiresInDays, }: { reloadChecklist: () => void; completedActions: ChecklistKey[]; expiresInDays: number; }) { const [showPopup, setShowPopup] = useLocalState(true, 'welcome-actions-spotlight'); const [showList, setShowList] = useState(false); const [fileSharingModal, showFileSharingModal] = useFileSharingModal(); const [linkSharingModal, showLinkSharingModal] = useLinkSharingModal(); const toggleOpen = () => { setShowPopup(false); // Any click will remove automatic popup. setShowList(!showList); // Load latest progress before opening checklist again os user doesnt // need to reload the whole page. if (!showList) { reloadChecklist(); } }; const spotlightContent = showPopup ? ( <div className="flex flex-nowrap"> <figure className="flex-item flex-item-noshrink mr-4"> <img src={spotlightIcon} alt="" /> </figure> <div className="flex-item"> <h6 className="text-semibold">{c('Title').t`Your 500 MB bonus`}</h6> {/* translator: You have X days left to claim your 500 MB welcome bonus and double your storage */} {c('Info').ngettext( msgid`You have ${expiresInDays} day left to claim your 500 MB welcome bonus and `, `You have ${expiresInDays} days left to claim your 500 MB welcome bonus and `, expiresInDays )} <a href={getKnowledgeBaseUrl('/more-storage-proton-drive')} target="_blank">{c('Info') .t`double your storage`}</a> </div> </div> ) : ( <div> <h6 className="text-semibold">{c('Title').t`Your welcome actions`}</h6> <div className="mb-4 color-weak"> {c('Info').t`Get to know ${DRIVE_APP_NAME} and earn your 500 MB storage bonus! Take action today.`} </div> <WelcomeActions completedActions={completedActions} onActionDone={toggleOpen} showFileSharingModal={showFileSharingModal} showLinkSharingModal={showLinkSharingModal} /> </div> ); return ( <> <FloatingSpotlight content={spotlightContent} hasClose={showPopup} show={showPopup || showList} onClick={toggleOpen} color={showList ? 'weak' : 'norm'} icon={showList ? 'cross' : 'gift'} /> {fileSharingModal} {linkSharingModal} </> ); } function FloatingSpotlight({ content, show, color, icon, hasClose = false, onClick, }: { content: React.ReactNode; show: boolean; color: ThemeColorUnion; icon: IconName; hasClose?: boolean; onClick: () => void; }) { const drawerWidth = useDrawerWidth(); // 1.6 is the default right offset on the floating button. Adding to that space that the drawer is taking const rightOffset = drawerWidth / rootFontSize() + 1.6; return ( <Spotlight content={content} show={show} originalPlacement="top-end" className="max-w-custom upper-layer" style={{ '--max-w-custom': '25em' }} hasClose={hasClose} > <FloatingButton title={c('Action').t`Your 500 MB bonus`} onClick={onClick} color={color} className="w-custom h-custom" style={{ '--w-custom': '3em', '--h-custom': '3em', '--right': `${rightOffset}rem` }} > <Icon size={24} name={icon} className="m-auto" /> </FloatingButton> </Spotlight> ); } function WelcomeActions({ completedActions, onActionDone, showFileSharingModal, showLinkSharingModal, }: { completedActions: ChecklistKey[]; onActionDone: () => void; showFileSharingModal: ReturnType<typeof useFileSharingModal>[1]; showLinkSharingModal: ReturnType<typeof useLinkSharingModal>[1]; }) { const getIconName = (actionName: ChecklistKey, iconName: IconName) => { return completedActions.includes(actionName) ? 'checkmark' : iconName; }; const { activeFolder } = useActiveShare(); const { inputRef: fileInput, handleClick, handleChange: handleFileChange, } = useFileUploadInput(activeFolder.shareId, activeFolder.linkId); const { getLocalID } = useAuthentication(); return ( <> <WelcomeAction icon="checkmark" title={c('Label').t`Create ${BRAND_NAME} account`} /> <input multiple type="file" ref={fileInput} className="hidden" onChange={(e) => { handleFileChange(e); onActionDone(); }} /> <WelcomeAction icon={getIconName(ChecklistKey.DriveUpload, 'arrow-up-line')} title={c('Label').t`Upload your first file`} text={c('Info').t`And access it from anywhere`} action={() => { handleClick(); }} /> <WelcomeAction icon={getIconName(ChecklistKey.DriveShare, 'link')} title={c('Label').t`Create a share link`} text={c('Info').t`It’s easy and secure`} action={() => { void showFileSharingModal({ shareId: activeFolder.shareId, showLinkSharingModal }); onActionDone(); }} /> <WelcomeAction icon={getIconName(ChecklistKey.RecoveryMethod, 'key-skeleton')} title={c('Label').t`Set recovery method`} text={c('Info').t`Makes your account safer`} action={() => { const slug = getSlugFromApp(APPS.PROTONDRIVE); const url = `/${slug}/recovery`; window.open(getAppHref(url, APPS.PROTONACCOUNT, getLocalID())); onActionDone(); }} /> </> ); } function WelcomeAction({ icon, title, text, action, }: { icon: IconName; title: string; text?: string; action?: () => void; }) { const [onHover, setOnHover] = useState(false); const isDone = icon === 'checkmark'; return ( <Row className={clsx(['flex flex-align-items-center rounded', !isDone && 'cursor-pointer'])} onClick={isDone ? undefined : action} onMouseEnter={() => setOnHover(true)} onMouseLeave={() => setOnHover(false)} > <div className={clsx([ 'flex-item-nowrap h-custom w-custom rounded mr-2', 'flex flex-justify-center flex-align-items-center', isDone ? 'bg-success' : 'bg-weak', ])} style={{ '--w-custom': '2.5em', '--h-custom': '2.5em' }} > <Icon name={icon} /> </div> <div className={clsx(['flex-item-fluid', isDone && 'text-strike color-weak'])}> {title} {!isDone && text && <div className="color-weak">{text}</div>} </div> {!isDone && ( <Icon name={onHover ? 'arrow-right' : 'chevron-right'} className={onHover ? '' : 'color-weak'} /> )} </Row> ); }
2,851
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/onboarding/useChecklist.ts
import { useEffect, useState } from 'react'; import { differenceInDays, fromUnixTime } from 'date-fns'; import { useApi, useUser } from '@proton/components'; import { useLoading } from '@proton/hooks'; import { getDriveChecklist, seenCompletedDriveChecklist } from '@proton/shared/lib/api/checklist'; import { ChecklistApiResponse } from '@proton/shared/lib/interfaces'; export default function useChecklist() { const api = useApi(); const [user] = useUser(); const [isLoading, withLoading] = useLoading(false); const [checklist, setChecklist] = useState<ChecklistApiResponse>(); useEffect(() => { if (user.isPaid) { return; } withLoading(api<ChecklistApiResponse>(getDriveChecklist('get-started')).then(setChecklist)).catch( console.error ); }, []); const reload = () => { api<ChecklistApiResponse>(getDriveChecklist('get-started')).then(setChecklist).catch(console.error); }; const expiresInDays = checklist?.ExpiresAt ? differenceInDays(fromUnixTime(checklist.ExpiresAt), new Date()) : 0; // If dismiss is set to true, then the checklist disappears completely. // If set to false, it just marks seen on backend but keeps it on web for the session. const markCompletedAsSeen = (dismiss: boolean = true) => { if (dismiss) { setChecklist(undefined); } void api<ChecklistApiResponse>(seenCompletedDriveChecklist('get-started')); }; return { isLoading, completedActions: checklist?.Items || [], isCompleted: checklist ? checklist.UserWasRewarded : true, isVisible: checklist?.Visible || false, expiresInDays, reload, markCompletedAsSeen, }; }
2,852
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/revisions/RevisionList.tsx
import { fromUnixTime, isToday } from 'date-fns'; import { c } from 'ttag'; import type { DriveFileRevision } from '../../store'; import RevisionListItem from './RevisionListItem'; import type { CategorizedRevisions } from './getCategorizedRevisions'; interface Props { currentRevision: DriveFileRevision; categorizedRevisions: CategorizedRevisions; } const RevisionList = ({ currentRevision, categorizedRevisions }: Props) => { const currentRevisionFormat = isToday(fromUnixTime(currentRevision.createTime)) ? 'time' : 'date'; return ( <ul className="unstyled"> <li data-testid="current-revision"> <span className="text-lg text-semibold revisions-modal-list-title--current">{c('Info') .t`Current version`}</span> <ul className="unstyled my-4 ml-4"> <RevisionListItem formatType={currentRevisionFormat} revision={currentRevision} isCurrent /> </ul> </li> {!!categorizedRevisions.size ? ( <> <li tabIndex={-1}> <hr className="mb-5 revisions-modal-list-separator" /> </li> {[...categorizedRevisions.entries()].map(([key, revisionCategory]) => { return ( <li data-testid="previous-revisions" key={key}> <span className="text-lg text-semibold color-weak">{revisionCategory.title}</span> <ul className="unstyled my-3 ml-4"> {revisionCategory.list.map((revision) => ( <RevisionListItem key={revision.id} formatType={key === 'today' || key === 'yesterday' ? 'time' : 'date'} revision={revision} /> ))} </ul> </li> ); })} </> ) : null} </ul> ); }; export default RevisionList;
2,853
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/revisions/RevisionListItem.scss
.revision-list-item { display: grid; grid-template-columns: 25% 50% 25%; align-items: center; }
2,854
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/revisions/RevisionListItem.tsx
import { useRef } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { Icon, TimeIntl } from '@proton/components'; import type { DriveFileRevision } from '../../store'; import { useContextMenuControls } from '../FileBrowser'; import { RevisionsItemContextMenu } from './RevisionsItemContextMenu'; import './RevisionListItem.scss'; const RevisionListItem = ({ revision, formatType = 'date', isCurrent = false, }: { revision: DriveFileRevision; formatType?: 'date' | 'time'; isCurrent?: boolean; }) => { const contextMenuControls = useContextMenuControls(); const ref = useRef<HTMLButtonElement>(null); const options: Intl.DateTimeFormatOptions = formatType === 'date' ? { month: 'short', day: 'numeric', } : { hour: 'numeric', minute: 'numeric', }; return ( <> <RevisionsItemContextMenu anchorRef={ref} isOpen={contextMenuControls.isOpen} position={contextMenuControls.position} open={contextMenuControls.open} close={contextMenuControls.close} revision={revision} isCurrent={isCurrent} /> <li className="revision-list-item mb-4"> <TimeIntl className="flex-item-fluid" options={options}> {revision.createTime} </TimeIntl> <p className="text-ellipsis text-center m-0">{revision.signatureEmail}</p> <Button className="ml-auto" ref={ref} shape="ghost" size="small" icon onClick={(e) => { contextMenuControls.handleContextMenu(e); }} onTouchEnd={(e) => { contextMenuControls.handleContextMenuTouch(e); }} > <Icon name="three-dots-vertical" alt={c('Action').t`More options`} /> </Button> </li> </> ); }; export default RevisionListItem;
2,855
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/revisions/RevisionPreview.scss
@import '~@proton/styles/scss/lib'; .revision-preview { position: relative; z-index: $layer-modals; &--behind { z-index: $layer-modals - 1; } }
2,856
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/revisions/RevisionsItemContextMenu.tsx
import { ContextSeparator } from '@proton/components/components'; import type { DriveFileRevision } from '../../store'; import { ContextMenuProps } from '../FileBrowser'; import { ItemContextMenu } from '../sections/ContextMenu/ItemContextMenu'; import { RevisionDeleteButton, RevisionDetailsButton, RevisionDownloadButton, RevisionPreviewButton, RevisionRestoreButton, } from './ContextMenuButtons'; import { useRevisionsProvider } from './RevisionsProvider'; export function RevisionsItemContextMenu({ anchorRef, isOpen, position, open, close, revision, isCurrent, }: ContextMenuProps & { revision: DriveFileRevision; isCurrent: boolean; }) { const { hasPreviewAvailable, openRevisionPreview, downloadRevision, openRevisionDetails, deleteRevision, restoreRevision, } = useRevisionsProvider(); if (isCurrent) { return ( <ItemContextMenu isOpen={isOpen} open={open} close={close} position={position} anchorRef={anchorRef}> {hasPreviewAvailable ? ( <RevisionPreviewButton revision={revision} openRevisionPreview={openRevisionPreview} close={close} /> ) : null} <RevisionDownloadButton revision={revision} downloadRevision={downloadRevision} close={close} /> <RevisionDetailsButton revision={revision} openRevisionDetails={openRevisionDetails} close={close} /> </ItemContextMenu> ); } return ( <ItemContextMenu isOpen={isOpen} open={open} close={close} position={position} anchorRef={anchorRef}> {hasPreviewAvailable && ( <> <RevisionPreviewButton revision={revision} openRevisionPreview={openRevisionPreview} close={close} /> <ContextSeparator /> </> )} <RevisionRestoreButton restoreRevision={restoreRevision} revision={revision} close={close} /> <RevisionDownloadButton revision={revision} downloadRevision={downloadRevision} close={close} /> <ContextSeparator /> <RevisionDetailsButton revision={revision} openRevisionDetails={openRevisionDetails} close={close} /> <ContextSeparator /> <RevisionDeleteButton deleteRevision={deleteRevision} revision={revision} close={close} /> </ItemContextMenu> ); }
2,857
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/revisions/RevisionsProvider.tsx
import { PropsWithChildren, createContext, useContext, useMemo, useRef, useState } from 'react'; import { fromUnixTime } from 'date-fns'; import { c } from 'ttag'; import { useConfirmActionModal, useNotifications } from '@proton/components'; import { isPreviewAvailable } from '@proton/shared/lib/helpers/preview'; import { dateLocale } from '@proton/shared/lib/i18n'; import { FileRevisionState } from '@proton/shared/lib/interfaces/drive/file'; import clsx from '@proton/utils/clsx'; import { DecryptedLink, DriveFileRevision, useDownload, useRevisionsView } from '../../store'; import PortalPreview from '../PortalPreview'; import { useRevisionDetailsModal } from '../modals/DetailsModal'; import { CategorizedRevisions, getCategorizedRevisions } from './getCategorizedRevisions'; import './RevisionPreview.scss'; export interface RevisionsProviderState { hasPreviewAvailable: boolean; isLoading: boolean; currentRevision: DriveFileRevision; categorizedRevisions: CategorizedRevisions; openRevisionPreview: (revision: DriveFileRevision) => void; openRevisionDetails: (revision: DriveFileRevision) => void; deleteRevision: (abortSignal: AbortSignal, revision: DriveFileRevision) => void; restoreRevision: (abortSignal: AbortSignal, revision: DriveFileRevision) => void; downloadRevision: (revisionId: string) => void; } const RevisionsContext = createContext<RevisionsProviderState | null>(null); export const RevisionsProvider = ({ link, children, }: PropsWithChildren<{ link: DecryptedLink; }>) => { const { createNotification } = useNotifications(); const ref = useRef(null); const { isLoading, revisions: [currentRevision, ...olderRevisions], deleteRevision, restoreRevision, } = useRevisionsView(link.rootShareId, link.linkId); const categorizedRevisions = useMemo(() => getCategorizedRevisions(olderRevisions), [olderRevisions]); const [confirmModal, showConfirmModal] = useConfirmActionModal(); const [revisionDetailsModal, showRevisionDetailsModal] = useRevisionDetailsModal(); const hasPreviewAvailable = !!link.mimeType && isPreviewAvailable(link.mimeType, link.size); const [selectedRevision, setSelectedRevision] = useState<DriveFileRevision | null>(null); const { download } = useDownload(); const downloadRevision = (revisionId: string) => { void download([{ ...link, shareId: link.rootShareId, revisionId: revisionId }]); }; const openRevisionDetails = (revision: DriveFileRevision) => { void showRevisionDetailsModal({ revision, shareId: link.rootShareId, linkId: link.linkId, name: link.name, }); }; const handleRevisionDelete = (abortSignal: AbortSignal, revision: DriveFileRevision) => { const formattedRevisionDate = new Intl.DateTimeFormat(dateLocale.code, { dateStyle: 'long', timeStyle: 'short', }).format(fromUnixTime(revision.createTime)); void showConfirmModal({ size: 'small', title: c('Action').t`Delete this version`, submitText: c('Action').t`Delete permanently`, message: ( <> { // translator: complete sentence example: Are you sure you want to permanently delete Yearly reports.docx, February 6, 2023 at 12:00 from the version history? c('Info').t`Are you sure you want to permanently delete` } &nbsp; <span className="text-bold"> {link.name}, {formattedRevisionDate} </span> &nbsp; { // translator: complete sentence example: Are you sure you want to permanently delete Yearly reports.docx, February 6, 2023 at 12:00 from the version history? c('Info').t`from the version history?` } </> ), onSubmit: () => deleteRevision(abortSignal, revision.id).then(() => { createNotification({ text: c('Info').t`Version is deleted`, }); }), }); }; const handleRevisionRestore = (abortSignal: AbortSignal, revision: DriveFileRevision) => { const formattedRevisionDate = new Intl.DateTimeFormat(dateLocale.code, { dateStyle: 'long', timeStyle: 'short', }).format(fromUnixTime(revision.createTime)); void showConfirmModal({ size: 'small', title: c('Action').t`Restore this version`, submitText: c('Action').t`Restore`, actionType: 'norm', canUndo: true, message: ( <> <span className="text-bold">{link.name}</span> &nbsp; { // translator: complete sentence example: Yearly reports.docx. will be restored to the version from February 6, 2023 at 12:00. All other versions will still be saved. c('Info') .t`will be restored to the version from ${formattedRevisionDate}. All other versions will still be saved.` } </> ), onSubmit: () => restoreRevision(abortSignal, revision.id).then((Code) => { if (Code === 1000) { createNotification({ text: c('Info').t`Version is restored`, }); } else { createNotification({ text: c('Info').t`Restore is in progress. This can take a few seconds.`, }); } }), }); }; const openRevisionPreview = (revision: DriveFileRevision) => { setSelectedRevision(revision); }; return ( <RevisionsContext.Provider value={{ hasPreviewAvailable, isLoading, deleteRevision: handleRevisionDelete, restoreRevision: handleRevisionRestore, currentRevision, categorizedRevisions, openRevisionPreview, openRevisionDetails, downloadRevision, }} > {children} {selectedRevision && ( <PortalPreview key="portal-preview-revisions" open={!!selectedRevision} ref={ref} revisionId={selectedRevision.id} shareId={link.rootShareId} linkId={link.linkId} date={selectedRevision.createTime} className={clsx( 'revision-preview', (confirmModal?.props.open || revisionDetailsModal?.props.open) && 'revision-preview--behind' )} onDetails={() => openRevisionDetails(selectedRevision)} onRestore={ selectedRevision.state !== FileRevisionState.Active ? () => { handleRevisionRestore(new AbortController().signal, selectedRevision); } : undefined } onClose={() => setSelectedRevision(null)} onExit={() => setSelectedRevision(null)} /> )} {revisionDetailsModal} {confirmModal} </RevisionsContext.Provider> ); }; export const useRevisionsProvider = () => { const state = useContext(RevisionsContext); if (!state) { throw new Error('Trying to use uninitialized RevisionsProvider'); } return state; };
2,858
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/revisions/getCategorizedRevisions.test.ts
import { DriveFileRevision } from '../../store'; import { getCategorizedRevisions } from './getCategorizedRevisions'; describe('getCategorizedRevisions', () => { beforeEach(() => { jest.useFakeTimers().setSystemTime(new Date('2023-03-17T20:00:00')); }); afterEach(() => { jest.useRealTimers(); }); it('categorizes revisions correctly', () => { const revisions = [ { createTime: 1679058000 }, // March 17, 2023 at 2:00 PM { createTime: 1679036400 }, // March 17, 2023 at 7:00 AM { createTime: 1678968000 }, // March 16, 2023 at 12:00 PM { createTime: 1678986000 }, // March 16, 2023 at 5:00 PM { createTime: 1678950000 }, // March 16, 2023 at 7:00 AM { createTime: 1678777200 }, // March 14, 2023 at 7:00 AM { createTime: 1678431600 }, // March 10, 2023 at 7:00 AM { createTime: 1678172400 }, // March 7, 2023 at 7:00 AM { createTime: 1675753200 }, // February 7, 2023 at 7:00 AM { createTime: 1675234800 }, // February 1, 2023 at 7:00 AM { createTime: 1640415600 }, // December 25, 2021 at 7:00 AM { createTime: 1621926000 }, // May 25, 2021 at 7:00 AM { createTime: 1593500400 }, // June 30, 2020 at 7:00 AM { createTime: 1559372400 }, // June 1, 2019 at 7:00 AM ] as DriveFileRevision[]; const result = getCategorizedRevisions(revisions, 'en-US'); expect([...result.entries()]).toStrictEqual([ ['today', { title: 'Today', list: [revisions[0], revisions[1]] }], ['yesterday', { title: 'Yesterday', list: [revisions[2], revisions[3], revisions[4]] }], ['d2', { title: 'Tuesday', list: [revisions[5]] }], ['last-week', { title: 'Last week', list: [revisions[6], revisions[7]] }], ['m1', { title: 'February', list: [revisions[8], revisions[9]] }], ['2021', { title: '2021', list: [revisions[10], revisions[11]] }], ['2020', { title: '2020', list: [revisions[12]] }], ['2019', { title: '2019', list: [revisions[13]] }], ]); }); });
2,859
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/revisions/getCategorizedRevisions.ts
import { fromUnixTime, isThisWeek, isThisYear, isToday, isYesterday } from 'date-fns'; import { c } from 'ttag'; import { dateLocale } from '@proton/shared/lib/i18n'; import isLastWeek from '@proton/utils/isLastWeek'; import { DriveFileRevision } from '../../store'; export type RevisionCategory = { title: string; list: DriveFileRevision[] }; export type CategorizedRevisions = Map<string, RevisionCategory>; export function getCategorizedRevisions( revisions: DriveFileRevision[], localeCode = dateLocale.code ): CategorizedRevisions { return revisions.reduce<CategorizedRevisions>((result, revision) => { const dateStart = fromUnixTime(revision.createTime); switch (true) { case isToday(dateStart): const todayRevisions = result.get('today'); result.set( 'today', todayRevisions ? { title: todayRevisions.title, list: [...todayRevisions.list, revision] } : { title: c('Info').t`Today`, list: [revision] } ); break; case isYesterday(dateStart): const yesterdayRevisions = result.get('yesterday'); result.set( 'yesterday', yesterdayRevisions ? { title: yesterdayRevisions.title, list: [...yesterdayRevisions.list, revision] } : { title: c('Info').t`Yesterday`, list: [revision] } ); break; case isThisWeek(dateStart): const dayOfWeek = dateStart.getDay(); const dayOfWeekRevisions = result.get(`d${dayOfWeek}`); result.set( `d${dayOfWeek}`, dayOfWeekRevisions ? { title: dayOfWeekRevisions.title, list: [...dayOfWeekRevisions.list, revision] } : { title: new Intl.DateTimeFormat(localeCode, { weekday: 'long' }).format(dateStart), list: [revision], } ); break; case isLastWeek(dateStart): const lastWeekRevisions = result.get('last-week'); result.set( 'last-week', lastWeekRevisions ? { title: lastWeekRevisions.title, list: [...lastWeekRevisions.list, revision] } : { title: c('Info').t`Last week`, list: [revision] } ); break; case isThisYear(dateStart): const monthOfYear = dateStart.getMonth(); const monthOfYearRevisions = result.get(`m${monthOfYear}`); result.set( `m${monthOfYear}`, monthOfYearRevisions ? { title: monthOfYearRevisions.title, list: [...monthOfYearRevisions.list, revision], } : { title: new Intl.DateTimeFormat(localeCode, { month: 'long' }).format(dateStart), list: [revision], } ); break; default: const year = dateStart.getFullYear().toString(); const yearRevisions = result.get(year); result.set( year, yearRevisions ? { title: yearRevisions.title, list: [...yearRevisions.list, revision] } : { title: new Intl.DateTimeFormat(localeCode, { year: 'numeric' }).format(dateStart), list: [revision], } ); break; } return result; }, new Map()); }
2,860
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/revisions/index.ts
export * from './RevisionsProvider'; export { default as RevisionList } from './RevisionList';
2,861
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/revisions
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/revisions/ContextMenuButtons/RevisionDeleteButton.tsx
import { c } from 'ttag'; import type { DriveFileRevision } from '../../../store'; import { ContextMenuButton } from '../../sections/ContextMenu'; import { RevisionsProviderState } from '../RevisionsProvider'; interface Props { revision: DriveFileRevision; deleteRevision: RevisionsProviderState['deleteRevision']; close: () => void; } const RevisionDeleteButton = ({ revision, deleteRevision, close }: Props) => { return ( <ContextMenuButton name={c('Action').t`Delete version`} icon="trash-cross" testId="context-menu-revision-delete" action={() => deleteRevision(new AbortController().signal, revision)} close={close} /> ); }; export default RevisionDeleteButton;
2,862
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/revisions
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/revisions/ContextMenuButtons/RevisionDetailsButton.tsx
import { c } from 'ttag'; import type { DriveFileRevision } from '../../../store'; import { ContextMenuButton } from '../../sections/ContextMenu'; import { RevisionsProviderState } from '../RevisionsProvider'; interface Props { revision: DriveFileRevision; openRevisionDetails: RevisionsProviderState['openRevisionDetails']; close: () => void; } const RevisionDetailsButton = ({ revision, openRevisionDetails, close }: Props) => { return ( <ContextMenuButton name={c('Action').t`Details`} icon="info-circle" testId="context-menu-details" action={() => openRevisionDetails(revision)} close={close} /> ); }; export default RevisionDetailsButton;
2,863
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/revisions
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/revisions/ContextMenuButtons/RevisionDownloadButton.tsx
import { c } from 'ttag'; import type { DriveFileRevision } from '../../../store'; import { ContextMenuButton } from '../../sections/ContextMenu'; import { RevisionsProviderState } from '../RevisionsProvider'; interface Props { revision: DriveFileRevision; downloadRevision: RevisionsProviderState['downloadRevision']; close: () => void; } const RevisionDownloadButton = ({ revision, downloadRevision, close }: Props) => { return ( <ContextMenuButton name={c('Action').t`Download`} icon="arrow-down-line" testId="context-menu-download" action={() => downloadRevision(revision.id)} close={close} /> ); }; export default RevisionDownloadButton;
2,864
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/revisions
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/revisions/ContextMenuButtons/RevisionPreviewButton.tsx
import { c } from 'ttag'; import type { DriveFileRevision } from '../../../store'; import { ContextMenuButton } from '../../sections/ContextMenu'; import { RevisionsProviderState } from '../RevisionsProvider'; interface Props { revision: DriveFileRevision; openRevisionPreview: RevisionsProviderState['openRevisionPreview']; close: () => void; } const RevisionPreviewButton = ({ revision, openRevisionPreview, close }: Props) => { return ( <ContextMenuButton name={c('Action').t`Preview`} icon="eye" testId="context-menu-preview" action={() => openRevisionPreview(revision)} close={close} /> ); }; export default RevisionPreviewButton;
2,865
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/revisions
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/revisions/ContextMenuButtons/RevisionRestoreButton.tsx
import { c } from 'ttag'; import type { DriveFileRevision } from '../../../store'; import { ContextMenuButton } from '../../sections/ContextMenu'; import { RevisionsProviderState } from '../RevisionsProvider'; interface Props { revision: DriveFileRevision; restoreRevision: RevisionsProviderState['deleteRevision']; close: () => void; } const RevisionRestoreButton = ({ revision, restoreRevision, close }: Props) => { return ( <ContextMenuButton name={c('Action').t`Restore version`} icon="arrow-rotate-right" testId="context-menu-revision-restore" action={() => restoreRevision(new AbortController().signal, revision)} close={close} /> ); }; export default RevisionRestoreButton;
2,866
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/revisions
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/revisions/ContextMenuButtons/RevisionSaveAsCopyButton.tsx
import { c } from 'ttag'; import { ContextMenuButton } from '../../sections/ContextMenu'; interface Props { close: () => void; } const RevisionSaveAsCopyButton = ({ close }: Props) => { return ( <ContextMenuButton name={c('Action').t`Save version as copy`} icon="squares" testId="context-menu-revision-save-as-copy" action={() => {}} close={close} /> ); }; export default RevisionSaveAsCopyButton;
2,867
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/revisions
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/revisions/ContextMenuButtons/index.ts
export { default as RevisionDeleteButton } from './RevisionDeleteButton'; export { default as RevisionDetailsButton } from './RevisionDetailsButton'; export { default as RevisionRestoreButton } from './RevisionRestoreButton'; export { default as RevisionSaveAsCopyButton } from './RevisionSaveAsCopyButton'; export { default as RevisionDownloadButton } from './RevisionDownloadButton'; export { default as RevisionPreviewButton } from './RevisionPreviewButton';
2,868
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/SortDropdown.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Dropdown, DropdownCaret, DropdownMenu, DropdownMenuButton, generateUID, usePopperAnchor, } from '@proton/components'; import { SORT_DIRECTION } from '@proton/shared/lib/constants'; import { SortParams } from '../FileBrowser/interface'; export default function SortDropdown<T extends string>({ sortFields, sortField, onSort, className, }: { sortFields?: T[]; sortField: SortParams<T>['sortField']; onSort?: (sortParams: SortParams<T>) => void; className?: string; }) { const [uid] = useState(generateUID('dropdown')); const { anchorRef, isOpen, toggle, close } = usePopperAnchor<HTMLButtonElement>(); const dropdownMenuButtons = sortFields?.map((sortFieldToCheck) => ( <DropdownMenuButton key={sortFieldToCheck} className="flex flex-nowrap text-left" onClick={() => onSort?.({ sortField: sortFieldToCheck, sortOrder: SORT_DIRECTION.ASC })} aria-current={sortField === sortFieldToCheck} > {translateSortField(sortFieldToCheck)} </DropdownMenuButton> )); return ( <> <Button className={className} aria-describedby={uid} ref={anchorRef} aria-expanded={isOpen} onClick={toggle} data-testid="toolbar-sort" title={c('Title').t`Sort files/folders`} shape="ghost" size="small" icon > <DropdownCaret isOpen={isOpen} className="expand-caret toolbar-icon my-auto" size={16} /> </Button> <Dropdown id={uid} isOpen={isOpen} anchorRef={anchorRef} onClose={close} originalPlacement="bottom-start" className="dropdown--no-max-size" > <DropdownMenu>{dropdownMenuButtons}</DropdownMenu> </Dropdown> </> ); } export function translateSortField(sortField: string): string { const translations: Record<string, string> = { name: c('Label').t`Name`, size: c('Label').t`Size`, // Type is not used (in UI) at this moment, but users might have set // it, so we keep the code, so it continue to work until user changes // the sorting. Also, we might get it back at some point. mimeType: c('Label').t`Type`, fileModifyTime: c('Label').t`Modified`, metaDataModifyTime: c('Label').t`Modified`, linkCreateTime: c('Label').t`Created`, linkExpireTime: c('Label').t`Expires`, numAccesses: c('Label').t`# of downloads`, trashed: c('Label').t`Deleted`, }; return translations[sortField]; }
2,869
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/helpers.tsx
import { c } from 'ttag'; import { LinkURLType, fileDescriptions } from '@proton/shared/lib/drive/constants'; import isTruthy from '@proton/utils/isTruthy'; import { DecryptedLink } from '../../store'; export const selectMessageForItemList = ( isFiles: boolean[], messages: { allFiles: string; allFolders: string; mixed: string; } ) => { const allFiles = isFiles.every((isFile) => isFile); const allFolders = isFiles.every((isFile) => !isFile); const message = (allFiles && messages.allFiles) || (allFolders && messages.allFolders) || messages.mixed; return message; }; export const toLinkURLType = (isFile: boolean) => { return isFile ? LinkURLType.FILE : LinkURLType.FOLDER; }; export const getMimeTypeDescription = (mimeType: string) => { if (fileDescriptions[mimeType]) { return fileDescriptions[mimeType]; } if (mimeType.startsWith('audio/')) { return c('Label').t`Audio file`; } if (mimeType.startsWith('video/')) { return c('Label').t`Video file`; } if (mimeType.startsWith('text/')) { return c('Label').t`Text`; } if (mimeType.startsWith('image/')) { return c('Label').t`Image`; } return c('Label').t`Unknown file`; }; export const getSelectedItems = (items: DecryptedLink[], selectedItemIds: string[]): DecryptedLink[] => { if (items) { return selectedItemIds .map((selectedItemId) => items.find(({ linkId, isLocked }) => !isLocked && selectedItemId === linkId)) .filter(isTruthy) as DecryptedLink[]; } return []; };
2,870
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/sections.scss
.section--header { font-size: 1.1em; } // This prevent separator to be alone .section-toolbar--hide-alone:first-child { display: none; } .sections--empty-trash-bar { background-color: var(--signal-info); }
2,871
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/useIsEditEnabled.tsx
import { useEarlyAccess } from '@proton/components'; export default function useIsEditEnabled() { const { currentEnvironment } = useEarlyAccess(); return currentEnvironment === 'alpha'; }
2,872
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/ContextMenu/ContextMenuButton.tsx
import { PropsWithChildren } from 'react'; import { DropdownMenuButton, Icon, IconName } from '@proton/components'; interface Props { name: string; icon: IconName; testId: string; action: () => void; close: () => void; } const ContextMenuButton = ({ name, icon, testId, action, close, children }: PropsWithChildren<Props>) => { return ( <DropdownMenuButton key={name} onContextMenu={(e) => e.stopPropagation()} className="flex flex-align-items-center flex-nowrap text-left" onClick={(e) => { e.stopPropagation(); action(); close(); }} data-testid={testId} > <Icon className="mr-2 flex-item-noshrink" name={icon} /> {name} {children} </DropdownMenuButton> ); }; export default ContextMenuButton;
2,873
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/ContextMenu/ItemContextMenu.tsx
import { useEffect } from 'react'; import { ContextMenu, DropdownSizeUnit } from '@proton/components'; import { ContextMenuProps } from '../../FileBrowser/interface'; export function ItemContextMenu({ anchorRef, isOpen, position, open, close, children }: ContextMenuProps) { useEffect(() => { if (position) { /* close event doesn't fire on mobile when clicking on another context menu target. unless menu is manually closed, it retains its position */ if (isOpen) { close(); } open(); } }, [position?.left, position?.top]); return ( <ContextMenu isOpen={isOpen} close={close} position={position} size={{ maxHeight: DropdownSizeUnit.Viewport, maxWidth: DropdownSizeUnit.Viewport }} anchorRef={anchorRef} > {children} </ContextMenu> ); }
2,874
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/ContextMenu/index.ts
export { default as ContextMenuButton } from './ContextMenuButton'; export * from './buttons';
2,875
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/ContextMenu
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/ContextMenu/buttons/CopyLinkButton.tsx
import { c } from 'ttag'; import { useActions } from '../../../../store'; import ContextMenuButton from '../ContextMenuButton'; interface Props { shareId: string; linkId: string; close: () => void; } const CopyLinkButton = ({ shareId, linkId, close }: Props) => { const { copyShareLinkToClipboard } = useActions(); // We can use it here since we don't need confirmModal if (!copyShareLinkToClipboard) { return null; } return ( <ContextMenuButton name={c('Action').t`Copy link`} icon="link" testId="context-menu-share-link" action={() => copyShareLinkToClipboard(new AbortController().signal, shareId, linkId)} close={close} /> ); }; export default CopyLinkButton;
2,876
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/ContextMenu
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/ContextMenu/buttons/DetailsButton.tsx
import { c } from 'ttag'; import { DecryptedLink } from '../../../../store'; import { useDetailsModal } from '../../../modals/DetailsModal'; import { useFilesDetailsModal } from '../../../modals/FilesDetailsModal'; import ContextMenuButton from '../ContextMenuButton'; interface Props { selectedLinks: DecryptedLink[]; showDetailsModal: ReturnType<typeof useDetailsModal>[1]; showFilesDetailsModal: ReturnType<typeof useFilesDetailsModal>[1]; close: () => void; } const DetailsButton = ({ selectedLinks, showDetailsModal, showFilesDetailsModal, close }: Props) => { return ( <ContextMenuButton name={c('Action').t`Details`} icon="info-circle" testId="context-menu-details" action={() => { if (selectedLinks.length === 1) { void showDetailsModal({ shareId: selectedLinks[0].rootShareId, linkId: selectedLinks[0].linkId }); } else if (selectedLinks.length > 1) { void showFilesDetailsModal({ selectedItems: selectedLinks }); } }} close={close} /> ); }; export default DetailsButton;
2,877
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/ContextMenu
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/ContextMenu/buttons/DownloadButton.tsx
import { c } from 'ttag'; import { DecryptedLink, useDownload } from '../../../../store'; import ContextMenuButton from '../ContextMenuButton'; interface Props { selectedLinks: DecryptedLink[]; close: () => void; } const DownloadButton = ({ selectedLinks, close }: Props) => { const { download } = useDownload(); const onClick = () => { void download( selectedLinks.map((link) => ({ ...link, shareId: link.rootShareId, })) ); }; return ( <ContextMenuButton name={c('Action').t`Download`} icon="arrow-down-line" testId="context-menu-download" action={onClick} close={close} /> ); }; export default DownloadButton;
2,878
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/ContextMenu
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/ContextMenu/buttons/PreviewButton.tsx
import { c } from 'ttag'; import useOpenPreview from '../../../useOpenPreview'; import ContextMenuButton from '../ContextMenuButton'; interface Props { shareId: string; linkId: string; close: () => void; } const PreviewButton = ({ shareId, linkId, close }: Props) => { const openPreview = useOpenPreview(); return ( <ContextMenuButton name={c('Action').t`Preview`} icon="eye" testId="context-menu-preview" action={() => openPreview(shareId, linkId)} close={close} /> ); }; export default PreviewButton;
2,879
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/ContextMenu
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/ContextMenu/buttons/RenameButton.tsx
import { c } from 'ttag'; import { DecryptedLink } from '../../../../store'; import { useRenameModal } from '../../../modals/RenameModal'; import ContextMenuButton from '../ContextMenuButton'; interface Props { link: DecryptedLink; showRenameModal: ReturnType<typeof useRenameModal>[1]; close: () => void; } const RenameButton = ({ link, showRenameModal, close }: Props) => { return ( <ContextMenuButton name={c('Action').t`Rename`} icon="pen-square" testId="context-menu-rename" action={() => showRenameModal({ item: link })} close={close} /> ); }; export default RenameButton;
2,880
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/ContextMenu
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/ContextMenu/buttons/RevisionsButton.tsx
import { c } from 'ttag'; import { NewFeatureTag } from '@proton/components'; import { DecryptedLink } from '../../../../store'; import { useRevisionsModal } from '../../../modals/RevisionsModal/RevisionsModal'; import ContextMenuButton from '../ContextMenuButton'; interface Props { selectedLink: DecryptedLink; showRevisionsModal: ReturnType<typeof useRevisionsModal>[1]; close: () => void; } const RevisionsButton = ({ selectedLink, showRevisionsModal, close }: Props) => { return ( <ContextMenuButton name={c('Action').t`See version history`} icon="clock-rotate-left" testId="context-menu-revisions" action={() => showRevisionsModal({ link: selectedLink })} close={close} > {/*// TODO: Remove this after the 17/07/2023*/} <NewFeatureTag featureKey="revisions" showOnce endDate={new Date('2023-07-17')} className="ml-2 md:ml-12 flex-item-noshrink" /> </ContextMenuButton> ); }; export default RevisionsButton;
2,881
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/ContextMenu
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/ContextMenu/buttons/ShareFileButton.tsx
import { c } from 'ttag'; import { useFileSharingModal } from '../../../modals/SelectLinkToShareModal/SelectLinkToShareModal'; import { useLinkSharingModal } from '../../../modals/ShareLinkModal/ShareLinkModal'; import ContextMenuButton from '../ContextMenuButton'; interface Props { shareId: string; showFileSharingModal: ReturnType<typeof useFileSharingModal>[1]; showLinkSharingModal: ReturnType<typeof useLinkSharingModal>[1]; close: () => void; } const ShareButton = ({ shareId, showFileSharingModal, showLinkSharingModal, close }: Props) => { return ( <ContextMenuButton name={c('Action').t`Get link`} icon="link" testId="context-menu-shareViaLink" action={() => showFileSharingModal({ shareId, showLinkSharingModal })} close={close} /> ); }; export default ShareButton;
2,882
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/ContextMenu
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/ContextMenu/buttons/ShareLinkButton.tsx
import { c } from 'ttag'; import { DecryptedLink } from '../../../../store'; import { useLinkSharingModal } from '../../../modals/ShareLinkModal/ShareLinkModal'; import ContextMenuButton from '../ContextMenuButton'; interface Props { shareId: string; link: DecryptedLink; showLinkSharingModal: ReturnType<typeof useLinkSharingModal>[1]; close: () => void; } const ShareLinkButton = ({ shareId, link, showLinkSharingModal, close }: Props) => { const hasSharedLink = !!link.shareUrl; return ( <ContextMenuButton name={hasSharedLink ? c('Action').t`Manage link` : c('Action').t`Get link`} icon={hasSharedLink ? 'link-pen' : 'link'} testId="context-menu-manage-link" action={() => showLinkSharingModal({ shareId, linkId: link.linkId })} close={close} /> ); }; export default ShareLinkButton;
2,883
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/ContextMenu
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/ContextMenu/buttons/index.ts
export { default as DetailsButton } from './DetailsButton'; export { default as DownloadButton } from './DownloadButton'; export { default as CopyLinkButton } from './CopyLinkButton'; export { default as PreviewButton } from './PreviewButton'; export { default as RenameButton } from './RenameButton'; export { default as ShareFileButton } from './ShareFileButton'; export { default as ShareLinkButton } from './ShareLinkButton'; export { default as RevisionsButton } from './RevisionsButton';
2,884
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Devices/Devices.tsx
import { useCallback, useMemo, useRef } from 'react'; import { useActiveBreakpoint } from '@proton/components'; import useNavigate from '../../../hooks/drive/useNavigate'; import { useDevicesView } from '../../../store'; import FileBrowser, { Cells, useItemContextMenu, useSelection } from '../../FileBrowser'; import { BrowserItemId, FileBrowserBaseItem, ListViewHeaderItem } from '../../FileBrowser/interface'; import { GridViewItemDevice } from '../FileBrowser/GridViewItemDevice'; import { DeviceNameCell } from '../FileBrowser/contentCells'; import headerCellsCommon from '../FileBrowser/headerCells'; import { DevicesItemContextMenu } from './ContextMenu/DevicesContextMenu'; import EmptyDevices from './EmptyDevices'; import { getSelectedItems } from './Toolbar/DevicesToolbar'; import { getDevicesSectionName } from './constants'; import headerCells from './headerCells'; export interface DeviceItem extends FileBrowserBaseItem { modificationTime: number; name: string; } interface Props { view: ReturnType<typeof useDevicesView>; } const { ContextMenuCell } = Cells; const desktopCells: React.FC<{ item: DeviceItem }>[] = [DeviceNameCell, ContextMenuCell]; const mobileCells = [DeviceNameCell, ContextMenuCell]; const headerItemsDesktop: ListViewHeaderItem[] = [headerCells.name, headerCellsCommon.placeholder]; const headerItemsMobile: ListViewHeaderItem[] = [headerCells.name, headerCellsCommon.placeholder]; function Devices({ view }: Props) { const contextMenuAnchorRef = useRef<HTMLDivElement>(null); const { navigateToLink } = useNavigate(); const browserItemContextMenu = useItemContextMenu(); const selectionControls = useSelection(); const { isDesktop } = useActiveBreakpoint(); const { layout, items: browserItems, isLoading } = view; const sectionTitle = getDevicesSectionName(); const selectedItems = useMemo( () => getSelectedItems(browserItems, selectionControls!.selectedItemIds), [browserItems, selectionControls!.selectedItemIds] ); const handleClick = useCallback( (id: BrowserItemId) => { const item = browserItems.find((item) => item.id === id); if (!item) { return; } document.getSelection()?.removeAllRanges(); navigateToLink(item.shareId, item.linkId, false); }, [navigateToLink, browserItems] ); /* eslint-disable react/display-name */ const GridHeaderComponent = useMemo( () => () => { return null; }, [isLoading] ); if (!browserItems.length && !isLoading) { return <EmptyDevices />; } const Cells = isDesktop ? desktopCells : mobileCells; const headerItems = isDesktop ? headerItemsDesktop : headerItemsMobile; return ( <> <DevicesItemContextMenu selectedDevices={selectedItems} anchorRef={contextMenuAnchorRef} close={browserItemContextMenu.close} isOpen={browserItemContextMenu.isOpen} open={browserItemContextMenu.open} position={browserItemContextMenu.position} /> <FileBrowser isMultiSelectionDisabled={true} caption={sectionTitle} items={browserItems} headerItems={headerItems} layout={layout} loading={isLoading} Cells={Cells} GridHeaderComponent={GridHeaderComponent} GridViewItem={GridViewItemDevice} onItemOpen={handleClick} contextMenuAnchorRef={contextMenuAnchorRef} onItemContextMenu={browserItemContextMenu.handleContextMenu} /> </> ); } export default Devices;
2,885
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Devices/DevicesView.tsx
import { useAppTitle } from '@proton/components'; import { useDevicesView } from '../../../store'; import { FileBrowserStateProvider } from '../../FileBrowser'; import ToolbarRow from '../ToolbarRow/ToolbarRow'; import Devices from './Devices'; import DevicesToolbar from './Toolbar/DevicesToolbar'; import { getDevicesSectionName } from './constants'; function DevicesView() { const sectionTitle = getDevicesSectionName(); useAppTitle(sectionTitle); const driveView = useDevicesView(); return ( <FileBrowserStateProvider itemIds={driveView.items.map(({ id }) => id)}> <ToolbarRow titleArea={<span className="text-strong pl-1">{sectionTitle}</span>} toolbar={<DevicesToolbar items={driveView.items} />} /> <Devices view={driveView} /> </FileBrowserStateProvider> ); } export default DevicesView;
2,886
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Devices/EmptyDevices.tsx
import React, { FC } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Icon } from '@proton/components'; import emptyDevicesImg from '@proton/styles/assets/img/illustrations/empty-devices.svg'; import useDesktopDownloads from '../../../hooks/drive/useDesktopDownloads'; import { DriveEmptyView } from '../../layout/DriveEmptyView'; type Props = {}; const EmptyDevices: FC<Props> = () => { const { isLoading, downloads } = useDesktopDownloads(); return ( <DriveEmptyView image={emptyDevicesImg} title={ // translator: Shown as a call to action when there are no computers synced c('Info').t`Want to sync files faster?` } subtitle={ // translator: Shown as a call to action when there are no computers synced c('Info').t`Get the desktop app to sync files from your computer.` } > {!isLoading && ( <div className="flex flex-column gap-2"> {downloads.map(({ platform, icon, name, url, startDownload }, index) => { return ( <Button key={platform} onClick={startDownload} className="mx-auto flex flex-align-items-center flex-justify-center gap-2 w-2/3" disabled={!url} color="norm" shape={index === 0 ? 'solid' : 'outline'} > <Icon name={icon} /> <span> { // translator: Download button for Drive desktop: "Download Windows app" c('Info').t`Download ${name} app` } </span> </Button> ); })} </div> )} </DriveEmptyView> ); }; export default EmptyDevices;
2,887
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Devices/constants.ts
import { c } from 'ttag'; export const getDevicesSectionName = () => c('Title').t`Computers`;
2,888
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Devices/headerCells.tsx
import { c } from 'ttag'; export const name = { type: 'name', getText: () => c('Label').t`Name`, props: { className: 'filebrowser-list-header-name-cell', }, }; export const modificationTimeDevice = { type: 'modificationTime', getText: () => c('Label').t`Modified`, props: { className: 'w-1/6', }, }; export default { name, modificationTimeDevice, };
2,889
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Devices
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Devices/ContextMenu/DevicesContextMenu.tsx
import { Device } from '../../../../store'; import { ContextMenuProps } from '../../../FileBrowser/interface'; import { useRemoveDeviceModal } from '../../../modals/RemoveDeviceModal'; import { useRenameDeviceModal } from '../../../modals/RenameDeviceModal'; import { ItemContextMenu } from '../../ContextMenu/ItemContextMenu'; import { RemoveButton, RenameButton } from './buttons'; export function DevicesItemContextMenu({ selectedDevices, anchorRef, isOpen, position, open, close, }: ContextMenuProps & { selectedDevices: Device[]; }) { const [renameDeviceModal, showRenameDeviceModal] = useRenameDeviceModal(); const [removeDeviceModal, showRemoveDeviceModal] = useRemoveDeviceModal(); const isOnlyOneItem = selectedDevices.length === 1; if (!isOnlyOneItem) { return null; } return ( <> <ItemContextMenu isOpen={isOpen} open={open} close={close} position={position} anchorRef={anchorRef}> <RenameButton showRenameDeviceModal={showRenameDeviceModal} device={selectedDevices[0]} close={close} /> <RemoveButton showRemoveDeviceModal={showRemoveDeviceModal} device={selectedDevices[0]} close={close} /> </ItemContextMenu> {renameDeviceModal} {removeDeviceModal} </> ); }
2,890
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Devices/ContextMenu
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Devices/ContextMenu/buttons/RemoveButton.tsx
import { c } from 'ttag'; import { Device } from '../../../../../store'; import { useRemoveDeviceModal } from '../../../../modals/RemoveDeviceModal'; import { ContextMenuButton } from '../../../ContextMenu'; interface Props { device: Device; showRemoveDeviceModal: ReturnType<typeof useRemoveDeviceModal>[1]; close: () => void; } const RemoveButton = ({ device, showRemoveDeviceModal, close }: Props) => { return ( <ContextMenuButton name={c('Action').t`Remove`} icon="trash" testId="context-menu-rename" action={() => showRemoveDeviceModal({ device })} close={close} /> ); }; export default RemoveButton;
2,891
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Devices/ContextMenu
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Devices/ContextMenu/buttons/RenameButton.tsx
import { c } from 'ttag'; import { Device } from '../../../../../store'; import { useRenameDeviceModal } from '../../../../modals/RenameDeviceModal'; import { ContextMenuButton } from '../../../ContextMenu'; interface Props { device: Device; showRenameDeviceModal: ReturnType<typeof useRenameDeviceModal>[1]; close: () => void; } const RenameButton = ({ device, showRenameDeviceModal, close }: Props) => { return ( <ContextMenuButton name={c('Action').t`Rename`} icon="pen-square" testId="context-menu-rename" action={() => showRenameDeviceModal({ device })} close={close} /> ); }; export default RenameButton;
2,892
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Devices/ContextMenu
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Devices/ContextMenu/buttons/index.ts
export { default as RenameButton } from './RenameButton'; export { default as RemoveButton } from './RemoveButton';
2,893
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Devices
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Devices/Toolbar/DevicesToolbar.tsx
import { useMemo } from 'react'; import { Toolbar } from '@proton/components'; import isTruthy from '@proton/utils/isTruthy'; import { Device } from '../../../../store'; import { useSelection } from '../../../FileBrowser'; import { LayoutButton } from '../../ToolbarButtons'; import DesktopDownloadDropdown from '../../ToolbarButtons/DesktopDownloadDropdown'; import { RemoveButton, RenameButton } from './buttons'; interface Props { items: Device[]; } export const getSelectedItems = (items: Device[], selectedItemIds: string[]): Device[] => { if (items) { return selectedItemIds.map((selectedItemId) => items.find(({ id }) => selectedItemId === id)).filter(isTruthy); } return []; }; const DevicesToolbar = ({ items }: Props) => { const selectionControls = useSelection()!; const selectedItems = useMemo( () => getSelectedItems(items, selectionControls!.selectedItemIds), [items, selectionControls!.selectedItemIds] ); const renderSelectionActions = () => { if (!selectedItems.length) { return null; } return ( <> <RenameButton selectedDevices={selectedItems} /> <RemoveButton selectedDevices={selectedItems} /> </> ); }; return ( <Toolbar className="py-1 px-2 toolbar--heavy toolbar--in-container"> <div className="gap-2 flex">{renderSelectionActions()}</div> <span className="ml-auto flex flex-nowrap"> <DesktopDownloadDropdown className="flex-align-self-center mr-2" /> <LayoutButton /> </span> </Toolbar> ); }; export default DevicesToolbar;
2,894
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Devices/Toolbar
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Devices/Toolbar/buttons/RemoveButton.tsx
import { c } from 'ttag'; import { Icon, ToolbarButton } from '@proton/components'; import { Device } from '../../../../../store'; import { useRemoveDeviceModal } from '../../../../modals/RemoveDeviceModal'; import { isMultiSelect } from '../../../ToolbarButtons/utils'; interface Props { selectedDevices: Device[]; } const Remove = ({ selectedDevices }: Props) => { const [removeDeviceModal, showRemoveDeviceModal] = useRemoveDeviceModal(); const isDisabled = isMultiSelect(selectedDevices); if (isDisabled) { return null; } return ( <> <ToolbarButton title={c('Action').t`Remove device`} icon={<Icon name="trash" />} onClick={() => showRemoveDeviceModal({ device: selectedDevices[0] })} data-testid="toolbar-delete" /> {removeDeviceModal} </> ); }; export default Remove;
2,895
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Devices/Toolbar
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Devices/Toolbar/buttons/RenameButton.tsx
import { c } from 'ttag'; import { Icon, ToolbarButton } from '@proton/components'; import { Device } from '../../../../../store'; import { useRenameDeviceModal } from '../../../../modals/RenameDeviceModal'; import { isMultiSelect } from '../../../ToolbarButtons/utils'; interface Props { selectedDevices: Device[]; } const RenameButton = ({ selectedDevices }: Props) => { const [renameDeviceModal, showRenameDeviceModal] = useRenameDeviceModal(); const isDisabled = isMultiSelect(selectedDevices); if (isDisabled) { return null; } return ( <> <ToolbarButton title={c('Action').t`Rename`} icon={<Icon name="pen-square" />} onClick={() => showRenameDeviceModal({ device: selectedDevices[0] })} data-testid="toolbar-rename" /> {renameDeviceModal} </> ); }; export default RenameButton;
2,896
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Devices/Toolbar
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Devices/Toolbar/buttons/index.ts
export { default as RemoveButton } from './RemoveButton'; export { default as RenameButton } from './RenameButton';
2,897
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive/Drive.tsx
import { useCallback, useEffect, useMemo, useRef } from 'react'; import { useActiveBreakpoint } from '@proton/components'; import { DriveFolder } from '../../../hooks/drive/useActiveShare'; import useDriveDragMove from '../../../hooks/drive/useDriveDragMove'; import useNavigate from '../../../hooks/drive/useNavigate'; import { EncryptedLink, LinkShareUrl, useFolderView, useThumbnailsDownload } from '../../../store'; import { SortField } from '../../../store/_views/utils/useSorting'; import FileBrowser, { Cells, GridHeader, useContextMenuControls, useItemContextMenu, useSelection, } from '../../FileBrowser'; import { BrowserItemId, FileBrowserBaseItem, ListViewHeaderItem } from '../../FileBrowser/interface'; import useOpenPreview from '../../useOpenPreview'; import { GridViewItem } from '../FileBrowser/GridViewItemLink'; import { ModifiedCell, NameCell, ShareOptionsCell, SizeCell } from '../FileBrowser/contentCells'; import headerItems from '../FileBrowser/headerCells'; import { translateSortField } from '../SortDropdown'; import { getSelectedItems } from '../helpers'; import { DriveItemContextMenu } from './DriveContextMenu'; import EmptyDeviceRoot from './EmptyDeviceRoot'; import EmptyFolder from './EmptyFolder'; import { FolderContextMenu } from './FolderContextMenu'; export interface DriveItem extends FileBrowserBaseItem { activeRevision?: EncryptedLink['activeRevision']; cachedThumbnailUrl?: string; hasThumbnail: boolean; isFile: boolean; mimeType: string; fileModifyTime: number; name: string; shareUrl?: LinkShareUrl; signatureIssues?: any; size: number; trashed: number | null; parentLinkId: string; } interface Props { activeFolder: DriveFolder; folderView: ReturnType<typeof useFolderView>; } const { CheckboxCell, ContextMenuCell } = Cells; const myFilesDesktopCells: React.FC<{ item: DriveItem }>[] = [ CheckboxCell, NameCell, ModifiedCell, SizeCell, ShareOptionsCell, ContextMenuCell, ]; const myFilesMobileCells = [CheckboxCell, NameCell, ContextMenuCell]; const headerItemsDesktop: ListViewHeaderItem[] = [ headerItems.checkbox, headerItems.name, headerItems.modificationDate, headerItems.size, headerItems.placeholder, headerItems.placeholder, ]; const headerItemsMobile: ListViewHeaderItem[] = [headerItems.checkbox, headerItems.name, headerItems.placeholder]; type DriveSortFields = Extract<SortField, SortField.name | SortField.fileModifyTime | SortField.size>; const SORT_FIELDS: DriveSortFields[] = [SortField.name, SortField.fileModifyTime, SortField.size]; function Drive({ activeFolder, folderView }: Props) { const { shareId, linkId } = activeFolder; const contextMenuAnchorRef = useRef<HTMLDivElement>(null); const browserContextMenu = useContextMenuControls(); const browserItemContextMenu = useItemContextMenu(); const thumbnails = useThumbnailsDownload(); const { navigateToLink } = useNavigate(); const selectionControls = useSelection(); const { isDesktop } = useActiveBreakpoint(); const { layout, folderName, items, sortParams, setSorting, isLoading } = folderView; const selectedItems = useMemo( () => getSelectedItems(items, selectionControls!.selectedItemIds), [items, selectionControls!.selectedItemIds] ); const openPreview = useOpenPreview(); const browserItems: DriveItem[] = items.map((item) => ({ ...item, id: item.linkId })); const { getDragMoveControls } = useDriveDragMove(shareId, browserItems, selectionControls!.clearSelections); /* eslint-disable react/display-name */ const GridHeaderComponent = useMemo( () => ({ scrollAreaRef }: { scrollAreaRef: React.RefObject<HTMLDivElement> }) => { const activeSortingText = translateSortField(sortParams.sortField); return ( <GridHeader isLoading={isLoading} sortFields={SORT_FIELDS} onSort={setSorting} sortField={sortParams.sortField} sortOrder={sortParams.sortOrder} itemCount={browserItems.length} scrollAreaRef={scrollAreaRef} activeSortingText={activeSortingText} /> ); }, [sortParams.sortField, sortParams.sortOrder, isLoading] ); const handleItemRender = (item: DriveItem) => { if (item.hasThumbnail && item.activeRevision && !item.cachedThumbnailUrl) { thumbnails.addToDownloadQueue(shareId, item.id, item.activeRevision.id); } }; const handleClick = useCallback( (id: BrowserItemId) => { const item = browserItems.find((item) => item.id === id); if (!item) { return; } document.getSelection()?.removeAllRanges(); if (item.isFile) { openPreview(shareId, id); return; } navigateToLink(shareId, id, item.isFile); }, [navigateToLink, shareId, browserItems] ); const handleScroll = () => { browserContextMenu.close(); browserItemContextMenu.close(); }; useEffect(() => { browserContextMenu.close(); browserItemContextMenu.close(); }, [shareId, linkId]); if (!items.length && !isLoading) { if (folderView.isActiveLinkReadOnly) { return <EmptyDeviceRoot />; } return <EmptyFolder shareId={shareId} />; } const Cells = isDesktop ? myFilesDesktopCells : myFilesMobileCells; const headerItems = isDesktop ? headerItemsDesktop : headerItemsMobile; return ( <> <FolderContextMenu isActiveLinkReadOnly={folderView.isActiveLinkReadOnly} shareId={shareId} anchorRef={contextMenuAnchorRef} close={browserContextMenu.close} isOpen={browserContextMenu.isOpen} open={browserContextMenu.open} position={browserContextMenu.position} /> <DriveItemContextMenu isActiveLinkReadOnly={folderView.isActiveLinkReadOnly} shareId={shareId} selectedLinks={selectedItems} anchorRef={contextMenuAnchorRef} close={browserItemContextMenu.close} isOpen={browserItemContextMenu.isOpen} open={browserItemContextMenu.open} position={browserItemContextMenu.position} /> <FileBrowser // data caption={folderName} headerItems={headerItems} items={browserItems} layout={layout} loading={isLoading} sortParams={sortParams} // components Cells={Cells} GridHeaderComponent={GridHeaderComponent} GridViewItem={GridViewItem} // handlers onItemOpen={handleClick} contextMenuAnchorRef={contextMenuAnchorRef} onItemContextMenu={browserItemContextMenu.handleContextMenu} onItemRender={handleItemRender} onSort={setSorting} onScroll={handleScroll} onViewContextMenu={browserContextMenu.handleContextMenu} getDragMoveControls={folderView.isActiveLinkReadOnly ? undefined : getDragMoveControls} /> </> ); } export default Drive;
2,898
0
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive/DriveContextMenu.tsx
import { ContextSeparator } from '@proton/components'; import { isPreviewAvailable } from '@proton/shared/lib/helpers/preview'; import { DecryptedLink } from '../../../store'; import { ContextMenuProps } from '../../FileBrowser/interface'; import { useDetailsModal } from '../../modals/DetailsModal'; import { useFilesDetailsModal } from '../../modals/FilesDetailsModal'; import { useMoveToFolderModal } from '../../modals/MoveToFolderModal/MoveToFolderModal'; import { useRenameModal } from '../../modals/RenameModal'; import { useRevisionsModal } from '../../modals/RevisionsModal/RevisionsModal'; import { useLinkSharingModal } from '../../modals/ShareLinkModal/ShareLinkModal'; import { CopyLinkButton, DetailsButton, DownloadButton, PreviewButton, RenameButton, RevisionsButton, ShareLinkButton, } from '../ContextMenu'; import { ItemContextMenu } from '../ContextMenu/ItemContextMenu'; import { MoveToFolderButton, MoveToTrashButton } from './ContextMenuButtons'; export function DriveItemContextMenu({ shareId, selectedLinks, anchorRef, isOpen, position, open, close, children, isActiveLinkReadOnly, }: ContextMenuProps & { shareId: string; selectedLinks: DecryptedLink[]; isActiveLinkReadOnly?: boolean; }) { const selectedLink = selectedLinks[0]; const isOnlyOneItem = selectedLinks.length === 1; const isOnlyOneFileItem = isOnlyOneItem && selectedLink.isFile; const hasPreviewAvailable = isOnlyOneFileItem && selectedLink.mimeType && isPreviewAvailable(selectedLink.mimeType, selectedLink.size); const hasLink = isOnlyOneItem && selectedLink.shareUrl && !selectedLink.shareUrl.isExpired && !selectedLink.trashed; const [detailsModal, showDetailsModal] = useDetailsModal(); const [filesDetailsModal, showFilesDetailsModal] = useFilesDetailsModal(); const [moveToFolderModal, showMoveToFolderModal] = useMoveToFolderModal(); const [renameModal, showRenameModal] = useRenameModal(); const [linkSharingModal, showLinkSharingModal] = useLinkSharingModal(); const [revisionsModal, showRevisionsModal] = useRevisionsModal(); return ( <> <ItemContextMenu isOpen={isOpen} open={open} close={close} position={position} anchorRef={anchorRef}> {hasPreviewAvailable && ( <PreviewButton shareId={selectedLink.rootShareId} linkId={selectedLink.linkId} close={close} /> )} {hasPreviewAvailable && <ContextSeparator />} <DownloadButton selectedLinks={selectedLinks} close={close} /> {hasLink && ( <CopyLinkButton shareId={selectedLink.rootShareId} linkId={selectedLink.linkId} close={close} /> )} {isOnlyOneItem && ( <ShareLinkButton shareId={shareId} showLinkSharingModal={showLinkSharingModal} link={selectedLink} close={close} /> )} <ContextSeparator /> {!isActiveLinkReadOnly ? ( <MoveToFolderButton shareId={shareId} selectedLinks={selectedLinks} showMoveToFolderModal={showMoveToFolderModal} close={close} /> ) : null} {isOnlyOneItem && !isActiveLinkReadOnly && ( <RenameButton showRenameModal={showRenameModal} link={selectedLink} close={close} /> )} <DetailsButton selectedLinks={selectedLinks} showDetailsModal={showDetailsModal} showFilesDetailsModal={showFilesDetailsModal} close={close} /> <ContextSeparator /> {isOnlyOneFileItem && ( <> <RevisionsButton selectedLink={selectedLink} showRevisionsModal={showRevisionsModal} close={close} /> <ContextSeparator /> </> )} <MoveToTrashButton selectedLinks={selectedLinks} close={close} /> {children} </ItemContextMenu> {filesDetailsModal} {detailsModal} {moveToFolderModal} {renameModal} {linkSharingModal} {revisionsModal} </> ); }
2,899