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/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive/DriveToolbar.tsx
|
import { useMemo } from 'react';
import { Vr } from '@proton/atoms';
import { Toolbar, useActiveBreakpoint } from '@proton/components';
import { getDevice } from '@proton/shared/lib/helpers/browser';
import { DecryptedLink } from '../../../store';
import { useSelection } from '../../FileBrowser';
import {
DetailsButton,
DownloadButton,
LayoutButton,
PreviewButton,
RenameButton,
ShareButton,
ShareLinkButton,
} from '../ToolbarButtons';
import { getSelectedItems } from '../helpers';
import useIsEditEnabled from '../useIsEditEnabled';
import {
ActionsDropdown,
CreateNewFileButton,
CreateNewFolderButton,
MoveToFolderButton,
MoveToTrashButton,
UploadFileButton,
UploadFolderButton,
} from './ToolbarButtons';
interface Props {
shareId: string;
linkId: string;
items: DecryptedLink[];
showOptionsForNoSelection?: boolean;
isLinkReadOnly?: boolean;
}
const DriveToolbar = ({ shareId, items, showOptionsForNoSelection = true, isLinkReadOnly }: Props) => {
const isDesktop = !getDevice()?.type;
const { isNarrow } = useActiveBreakpoint();
const selectionControls = useSelection()!;
const isEditEnabled = useIsEditEnabled();
const selectedItems = useMemo(
() => getSelectedItems(items, selectionControls!.selectedItemIds),
[items, selectionControls!.selectedItemIds]
);
const shouldShowShareButton = !isLinkReadOnly || items.length > 0;
const renderSelectionActions = () => {
if (!selectedItems.length) {
if (!showOptionsForNoSelection) {
return null;
}
return (
<>
{!isLinkReadOnly ? (
<>
<CreateNewFolderButton />
{isEditEnabled && <CreateNewFileButton />}
<Vr />
{isDesktop && <UploadFolderButton />}
<UploadFileButton />
<Vr />
</>
) : null}
{shouldShowShareButton && <ShareButton shareId={shareId} />}
</>
);
}
return (
<>
<PreviewButton selectedLinks={selectedItems} />
<DownloadButton selectedLinks={selectedItems} />
{isNarrow ? (
<ActionsDropdown shareId={shareId} selectedLinks={selectedItems} />
) : (
<>
<ShareLinkButton selectedLinks={selectedItems} />
<Vr />
{!isLinkReadOnly ? (
<>
<MoveToFolderButton shareId={shareId} selectedLinks={selectedItems} />
<RenameButton selectedLinks={selectedItems} />
</>
) : null}
<DetailsButton selectedLinks={selectedItems} />
<Vr />
<MoveToTrashButton selectedLinks={selectedItems} />
</>
)}
</>
);
};
return (
<Toolbar className="py-1 px-2 toolbar--heavy toolbar--in-container">
<div className="gap-2 flex flex-nowrap flex-item-noshrink">{renderSelectionActions()}</div>
<span className="ml-auto flex flex-nowrap flex-item-noshrink">
{selectedItems.length > 0 && <Vr className="hidden md:flex mx-2" />}
<LayoutButton />
</span>
</Toolbar>
);
};
export default DriveToolbar;
| 2,900
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive/DriveView.tsx
|
import { useEffect } from 'react';
import { Toolbar } from '@proton/components';
import { LinkURLType, RESPONSE_CODE } from '@proton/shared/lib/drive/constants';
import useActiveShare from '../../../hooks/drive/useActiveShare';
import useNavigate from '../../../hooks/drive/useNavigate';
import { useFolderView } from '../../../store';
import DriveBreadcrumbs from '../../DriveBreadcrumbs';
import { FileBrowserStateProvider } from '../../FileBrowser';
import UploadDragDrop from '../../uploads/UploadDragDrop/UploadDragDrop';
import ToolbarRow from '../ToolbarRow/ToolbarRow';
import Drive from './Drive';
import DriveToolbar from './DriveToolbar';
export type DriveSectionRouteProps = { shareId?: string; type?: LinkURLType; linkId?: string };
function DriveView() {
const { activeFolder } = useActiveShare();
const { navigateToRoot, navigateToLink } = useNavigate();
const folderView = useFolderView(activeFolder);
useEffect(() => {
if (folderView.error) {
const code = folderView.error.data?.Code;
if (code === RESPONSE_CODE.INVALID_LINK_TYPE) {
navigateToLink(activeFolder.shareId, activeFolder.linkId, true);
} else if (code === RESPONSE_CODE.NOT_FOUND || code === RESPONSE_CODE.INVALID_ID) {
navigateToRoot();
} else {
throw folderView.error;
}
}
}, [folderView.error]);
const breadcrumbs = activeFolder && <DriveBreadcrumbs activeFolder={activeFolder} />;
const toolbar = activeFolder ? (
<DriveToolbar
isLinkReadOnly={folderView.isActiveLinkReadOnly}
shareId={activeFolder.shareId}
linkId={activeFolder.linkId}
items={folderView.items}
/>
) : (
<Toolbar className="toolbar--in-container" />
);
return (
<FileBrowserStateProvider itemIds={folderView.items.map(({ linkId }) => linkId)}>
<UploadDragDrop
shareId={activeFolder.shareId}
linkId={activeFolder.linkId}
className="flex flex-column flex-nowrap flex-item-fluid"
disabled={folderView.isActiveLinkReadOnly}
>
<ToolbarRow titleArea={breadcrumbs} toolbar={toolbar} />
{activeFolder && <Drive activeFolder={activeFolder} folderView={folderView} />}
</UploadDragDrop>
</FileBrowserStateProvider>
);
}
export default DriveView;
| 2,901
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive/EmptyDeviceRoot.tsx
|
import { FC } from 'react';
import { c } from 'ttag';
import emptySvg from '@proton/styles/assets/img/illustrations/empty-device-root.svg';
import { DriveEmptyView } from '../../layout/DriveEmptyView';
type Props = {};
const EmptyDeviceRoot: FC<Props> = () => {
return (
<DriveEmptyView
image={emptySvg}
title={
// translator: Shown when accessing an empty computer
c('Info').t`No synced folders`
}
subtitle={
// translator: Shown when accessing an empty computer
c('Info').t`Folders you sync from your computer will appear here.`
}
/>
);
};
export default EmptyDeviceRoot;
| 2,902
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive/EmptyFolder.tsx
|
import { useEffect, useState } from 'react';
import { c } from 'ttag';
import { usePopperAnchor } from '@proton/components';
import emptySvg from '@proton/styles/assets/img/illustrations/empty-my-files.svg';
import { DriveEmptyView } from '../../layout/DriveEmptyView';
import { FolderContextMenu } from './FolderContextMenu';
const EmptyFolder = ({ shareId }: { shareId: string }) => {
const { anchorRef, isOpen, open, close } = usePopperAnchor<HTMLDivElement>();
const [contextMenuPosition, setContextMenuPosition] = useState<{ top: number; left: number }>();
useEffect(() => {
if (!anchorRef.current) {
return;
}
let node = anchorRef.current;
const handleContextMenu = (ev: MouseEvent) => {
ev.stopPropagation();
ev.preventDefault();
if (isOpen) {
close();
}
setContextMenuPosition({ top: ev.clientY, left: ev.clientX });
};
node.addEventListener('contextmenu', handleContextMenu);
return () => {
node.removeEventListener('contextmenu', handleContextMenu);
};
}, [anchorRef, isOpen, close, setContextMenuPosition]);
return (
<>
<DriveEmptyView
image={emptySvg}
title={
// translator: Shown as a call to action when there are no files in a folder
c('Info').t`Drop files here`
}
subtitle={
// translator: Shown as a call to action when there are no files in a folder
c('Info').t`Or use the "+ New" button`
}
ref={anchorRef}
onClick={close}
dataTestId="my-files-empty-placeholder"
/>
<FolderContextMenu
shareId={shareId}
isOpen={isOpen}
open={open}
close={close}
position={contextMenuPosition}
anchorRef={anchorRef}
/>
</>
);
};
export default EmptyFolder;
| 2,903
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive/FolderContextMenu.tsx
|
import { useEffect } from 'react';
import * as React from 'react';
import { ContextMenu, ContextSeparator } from '@proton/components';
import useActiveShare from '../../../hooks/drive/useActiveShare';
import { useFileUploadInput, useFolderUploadInput } from '../../../store';
import { ContextMenuProps } from '../../FileBrowser/interface';
import { useCreateFileModal } from '../../modals/CreateFileModal';
import { useCreateFolderModal } from '../../modals/CreateFolderModal';
import { useFileSharingModal } from '../../modals/SelectLinkToShareModal/SelectLinkToShareModal';
import { useLinkSharingModal } from '../../modals/ShareLinkModal/ShareLinkModal';
import { ShareFileButton } from '../ContextMenu/buttons';
import useIsEditEnabled from '../useIsEditEnabled';
import { CreateNewFileButton, CreateNewFolderButton, UploadFileButton, UploadFolderButton } from './ContextMenuButtons';
export function FolderContextMenu({
shareId,
anchorRef,
isOpen,
position,
open,
close,
isActiveLinkReadOnly,
}: ContextMenuProps & {
shareId: string;
isActiveLinkReadOnly?: boolean;
}) {
useEffect(() => {
if (position) {
open();
}
}, [position]);
const isEditEnabled = useIsEditEnabled();
const { activeFolder } = useActiveShare();
const {
inputRef: fileInput,
handleClick: fileClick,
handleChange: fileChange,
} = useFileUploadInput(activeFolder.shareId, activeFolder.linkId);
const {
inputRef: folderInput,
handleClick: folderClick,
handleChange: folderChange,
} = useFolderUploadInput(activeFolder.shareId, activeFolder.linkId);
const [createFolderModal, showCreateFolderModal] = useCreateFolderModal();
const [createFileModal, showCreateFileModal] = useCreateFileModal();
const [fileSharingModal, showFileSharingModal] = useFileSharingModal();
const [linkSharingModal, showLinkSharingModal] = useLinkSharingModal();
// ContextMenu is removed from DOM when any action is executed but inputs
// need to stay rendered so onChange handler can work.
return (
<>
<input multiple type="file" ref={fileInput} className="hidden" onChange={fileChange} />
<input type="file" ref={folderInput} className="hidden" onChange={folderChange} />
{createFolderModal}
{createFileModal}
{fileSharingModal}
{linkSharingModal}
<ContextMenu isOpen={isOpen} close={close} position={position} anchorRef={anchorRef}>
{!isActiveLinkReadOnly && <CreateNewFolderButton close={close} action={showCreateFolderModal} />}
{isEditEnabled && !isActiveLinkReadOnly && (
<CreateNewFileButton close={close} action={showCreateFileModal} />
)}
{!isActiveLinkReadOnly && <ContextSeparator />}
{!isActiveLinkReadOnly ? (
<>
<UploadFileButton close={close} onClick={fileClick} />
<UploadFolderButton close={close} onClick={folderClick} />
<ContextSeparator />
</>
) : null}
<ShareFileButton
close={close}
shareId={shareId}
showFileSharingModal={showFileSharingModal}
showLinkSharingModal={showLinkSharingModal}
/>
</ContextMenu>
</>
);
}
| 2,904
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive/ContextMenuButtons/CreateNewFileButton.tsx
|
import { c } from 'ttag';
import { ContextMenuButton } from '../../ContextMenu';
interface Props {
action: () => void;
close: () => void;
}
const CreateNewFileButton = ({ close, action }: Props) => {
return (
<ContextMenuButton
testId="toolbar-new-file"
icon="file"
name={c('Action').t`Create new text file`}
action={action}
close={close}
/>
);
};
export default CreateNewFileButton;
| 2,905
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive/ContextMenuButtons/CreateNewFolderButton.tsx
|
import { c } from 'ttag';
import { ContextMenuButton } from '../../ContextMenu';
interface Props {
action: () => void;
close: () => void;
}
const CreateNewFolderButton = ({ close, action }: Props) => {
return (
<ContextMenuButton
testId="toolbar-new-folder"
icon="folder-plus"
name={c('Action').t`Create new folder`}
action={action}
close={close}
/>
);
};
export default CreateNewFolderButton;
| 2,906
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive/ContextMenuButtons/MoveToFolderButton.tsx
|
import { c } from 'ttag';
import { DecryptedLink } from '../../../../store';
import { useMoveToFolderModal } from '../../../modals/MoveToFolderModal/MoveToFolderModal';
import { ContextMenuButton } from '../../ContextMenu';
interface Props {
shareId: string;
selectedLinks: DecryptedLink[];
showMoveToFolderModal: ReturnType<typeof useMoveToFolderModal>[1];
close: () => void;
}
const MoveToFolderButton = ({ shareId, selectedLinks, showMoveToFolderModal, close }: Props) => {
return (
<ContextMenuButton
name={c('Action').t`Move to folder`}
icon="arrows-cross"
testId="context-menu-move"
action={() => showMoveToFolderModal({ shareId, selectedItems: selectedLinks })}
close={close}
/>
);
};
export default MoveToFolderButton;
| 2,907
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive/ContextMenuButtons/MoveToTrashButton.tsx
|
import { c } from 'ttag';
import { DecryptedLink, useActions } from '../../../../store';
import { ContextMenuButton } from '../../ContextMenu';
interface Props {
selectedLinks: DecryptedLink[];
close: () => void;
}
const MoveToTrashButton = ({ selectedLinks, close }: Props) => {
const { trashLinks } = useActions(); // We can use it here since we don't need confirmModal
return (
<ContextMenuButton
name={c('Action').t`Move to trash`}
icon="trash"
testId="context-menu-trash"
action={() => trashLinks(new AbortController().signal, selectedLinks)}
close={close}
/>
);
};
export default MoveToTrashButton;
| 2,908
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive/ContextMenuButtons/UploadFileButton.tsx
|
import { c } from 'ttag';
import { ContextMenuButton } from '../../ContextMenu';
interface Props {
close: () => void;
onClick: () => void;
}
const UploadFileButton = ({ close, onClick }: Props) => {
return (
<ContextMenuButton
testId="context-upload-file"
icon="file-arrow-in-up"
name={c('Action').t`Upload file`}
action={onClick}
close={close}
/>
);
};
export default UploadFileButton;
| 2,909
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive/ContextMenuButtons/UploadFolderButton.tsx
|
import { c } from 'ttag';
import { ContextMenuButton } from '../../ContextMenu';
interface Props {
close: () => void;
onClick: () => void;
}
const UploadFolderButton = ({ close, onClick }: Props) => {
return (
<ContextMenuButton
testId="context-upload-folder"
icon="folder-arrow-up"
name={c('Action').t`Upload folder`}
action={onClick}
close={close}
/>
);
};
export default UploadFolderButton;
| 2,910
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive/ContextMenuButtons/index.ts
|
export { default as CreateNewFileButton } from './CreateNewFileButton';
export { default as CreateNewFolderButton } from './CreateNewFolderButton';
export { default as MoveToFolderButton } from './MoveToFolderButton';
export { default as MoveToTrashButton } from './MoveToTrashButton';
export { default as UploadFileButton } from './UploadFileButton';
export { default as UploadFolderButton } from './UploadFolderButton';
| 2,911
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive/ToolbarButtons/ActionsDropdown.tsx
|
import { useState } from 'react';
import { c } from 'ttag';
import {
Dropdown,
DropdownMenu,
DropdownMenuButton,
Icon,
IconName,
ToolbarButton,
generateUID,
usePopperAnchor,
} from '@proton/components';
import { DecryptedLink, useActions } from '../../../../store';
import { useDetailsModal } from '../../../modals/DetailsModal';
import { useFilesDetailsModal } from '../../../modals/FilesDetailsModal';
import { useMoveToFolderModal } from '../../../modals/MoveToFolderModal/MoveToFolderModal';
import { useRenameModal } from '../../../modals/RenameModal';
import { useLinkSharingModal } from '../../../modals/ShareLinkModal/ShareLinkModal';
interface Props {
shareId: string;
selectedLinks: DecryptedLink[];
}
const ActionsDropdown = ({ shareId, selectedLinks }: Props) => {
const [uid] = useState(generateUID('actions-dropdown'));
const { anchorRef, isOpen, toggle, close } = usePopperAnchor<HTMLButtonElement>();
const [filesDetailsModal, showFilesDetailsModal] = useFilesDetailsModal();
const [detailsModal, showDetailsModal] = useDetailsModal();
const [moveToFolderModal, showMoveToFolderModal] = useMoveToFolderModal();
const [renameModal, showRenameModal] = useRenameModal();
const [linkSharingModal, showLinkSharingModal] = useLinkSharingModal();
const { trashLinks } = useActions();
const hasFoldersSelected = selectedLinks.some((item) => !item.isFile);
const isMultiSelect = selectedLinks.length > 1;
const hasSharedLink = !!selectedLinks[0]?.shareUrl;
const selectedLinkIds = selectedLinks.map(({ linkId }) => linkId);
const menuItems: {
hidden: boolean;
name: string;
icon: IconName;
testId: string;
action: () => void;
}[] = [
{
hidden: isMultiSelect || hasFoldersSelected,
name: hasSharedLink ? c('Action').t`Manage link` : c('Action').t`Get link`,
icon: 'link',
testId: 'actions-dropdown-share-link',
action: () => showLinkSharingModal({ shareId: shareId, linkId: selectedLinkIds[0] }),
},
{
hidden: false,
name: c('Action').t`Move to folder`,
icon: 'arrows-cross',
testId: 'actions-dropdown-move',
action: () => showMoveToFolderModal({ shareId, selectedItems: selectedLinks }),
},
{
hidden: isMultiSelect,
name: c('Action').t`Rename`,
icon: 'pen-square',
testId: 'actions-dropdown-rename',
action: () => showRenameModal({ item: selectedLinks[0] }),
},
{
hidden: isMultiSelect,
name: c('Action').t`Details`,
icon: 'info-circle',
testId: 'actions-dropdown-details',
action: () => showDetailsModal({ shareId, linkId: selectedLinkIds[0] }),
},
{
hidden: !isMultiSelect || hasFoldersSelected,
name: c('Action').t`Details`,
icon: 'info-circle',
testId: 'actions-dropdown-details',
action: () => showFilesDetailsModal({ selectedItems: selectedLinks }),
},
{
hidden: false,
name: c('Action').t`Move to trash`,
icon: 'trash',
testId: 'actions-dropdown-trash',
action: () => trashLinks(new AbortController().signal, selectedLinks),
},
{
hidden: isMultiSelect,
name: hasSharedLink ? c('Action').t`Sharing options` : c('Action').t`Share via link`,
icon: 'link',
testId: 'actions-dropdown-share-link',
action: () => showLinkSharingModal({ shareId: shareId, linkId: selectedLinkIds[0] }),
},
];
const dropdownMenuButtons = menuItems
.filter((menuItem) => !menuItem.hidden)
.map((item) => (
<DropdownMenuButton
key={item.name}
hidden={item.hidden}
onContextMenu={(e) => e.stopPropagation()}
className="flex flex-nowrap text-left"
onClick={(e) => {
e.stopPropagation();
item.action();
close();
}}
data-testid={item.testId}
>
<Icon className="mt-1 mr-2" name={item.icon} />
{item.name}
</DropdownMenuButton>
));
return (
<>
<ToolbarButton
disabled={!selectedLinks.length}
aria-describedby={uid}
ref={anchorRef}
aria-expanded={isOpen}
onClick={toggle}
icon={<Icon name="chevron-down-filled" alt={c('Title').t`Show actions`} rotate={isOpen ? 180 : 0} />}
data-testid="actions-dropdown"
title={c('Title').t`Show actions`}
/>
<Dropdown id={uid} isOpen={isOpen} anchorRef={anchorRef} onClose={close} originalPlacement="bottom">
<DropdownMenu>{dropdownMenuButtons}</DropdownMenu>
</Dropdown>
{filesDetailsModal}
{detailsModal}
{moveToFolderModal}
{renameModal}
{linkSharingModal}
</>
);
};
export default ActionsDropdown;
| 2,912
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive/ToolbarButtons/CreateNewFileButton.tsx
|
import { c } from 'ttag';
import { Icon, ToolbarButton } from '@proton/components';
import { useCreateFileModal } from '../../../modals/CreateFileModal';
const CreateNewFileButton = () => {
const [createFileModal, showCreateFileModal] = useCreateFileModal();
return (
<>
<ToolbarButton
icon={<Icon name="file" alt={c('Action').t`Create new text file`} />}
title={c('Action').t`Create new text file`}
onClick={() => showCreateFileModal()}
data-testid="toolbar-create-file"
/>
{createFileModal}
</>
);
};
export default CreateNewFileButton;
| 2,913
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive/ToolbarButtons/CreateNewFolderButton.tsx
|
import { c } from 'ttag';
import { Icon, ToolbarButton } from '@proton/components';
import { useCreateFolderModal } from '../../../modals/CreateFolderModal';
const CreateNewFolderButton = () => {
const [createFolderModal, showCreateFolderModal] = useCreateFolderModal();
return (
<>
<ToolbarButton
icon={<Icon name="folder-plus" alt={c('Action').t`Create new folder`} />}
title={c('Action').t`Create new folder`}
onClick={() => showCreateFolderModal()}
data-testid="toolbar-new-folder"
/>
{createFolderModal}
</>
);
};
export default CreateNewFolderButton;
| 2,914
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive/ToolbarButtons/MoveToFolderButton.tsx
|
import { c } from 'ttag';
import { Icon, ToolbarButton } from '@proton/components';
import { DecryptedLink } from '../../../../store';
import { useMoveToFolderModal } from '../../../modals/MoveToFolderModal/MoveToFolderModal';
interface Props {
shareId: string;
selectedLinks: DecryptedLink[];
}
const MoveToFolderButton = ({ shareId, selectedLinks }: Props) => {
const [moveToFolderModal, showMoveToFolderModal] = useMoveToFolderModal();
return (
<>
<ToolbarButton
title={c('Action').t`Move to folder`}
icon={<Icon name="arrows-cross" alt={c('Action').t`Move to folder`} />}
onClick={() => showMoveToFolderModal({ shareId, selectedItems: selectedLinks })}
data-testid="toolbar-move"
/>
{moveToFolderModal}
</>
);
};
export default MoveToFolderButton;
| 2,915
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive/ToolbarButtons/MoveToTrashButton.tsx
|
import { c } from 'ttag';
import { Icon, ToolbarButton } from '@proton/components';
import { useLoading } from '@proton/hooks';
import { DecryptedLink, useActions } from '../../../../store';
interface Props {
selectedLinks: DecryptedLink[];
}
const MoveToTrashButton = ({ selectedLinks }: Props) => {
const [isLoading, withLoading] = useLoading();
const { trashLinks } = useActions();
return (
<ToolbarButton
disabled={isLoading}
title={c('Action').t`Move to trash`}
icon={<Icon name="trash" alt={c('Action').t`Move to trash`} />}
onClick={() => withLoading(trashLinks(new AbortController().signal, selectedLinks))}
data-testid="toolbar-trash"
/>
);
};
export default MoveToTrashButton;
| 2,916
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive/ToolbarButtons/UploadFileButton.tsx
|
import { c } from 'ttag';
import { Icon, ToolbarButton } from '@proton/components';
import useActiveShare from '../../../../hooks/drive/useActiveShare';
import { useFileUploadInput } from '../../../../store';
const UploadFileButton = () => {
const { activeFolder } = useActiveShare();
const {
inputRef: fileInput,
handleClick,
handleChange,
} = useFileUploadInput(activeFolder.shareId, activeFolder.linkId);
return (
<>
<input multiple type="file" ref={fileInput} className="hidden" onChange={handleChange} />
<ToolbarButton
data-testid="toolbar-upload-file"
icon={<Icon name="file-arrow-in-up" alt={c('Action').t`Upload file`} />}
title={c('Action').t`Upload file`}
onClick={handleClick}
/>
</>
);
};
export default UploadFileButton;
| 2,917
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive/ToolbarButtons/UploadFolderButton.tsx
|
import { c } from 'ttag';
import { Icon, ToolbarButton } from '@proton/components';
import useActiveShare from '../../../../hooks/drive/useActiveShare';
import { useFolderUploadInput } from '../../../../store';
const UploadFolderButton = () => {
const { activeFolder } = useActiveShare();
const {
inputRef: fileInput,
handleClick: handleUploadFolder,
handleChange,
} = useFolderUploadInput(activeFolder.shareId, activeFolder.linkId);
return (
<>
<input type="file" ref={fileInput} className="hidden" onChange={handleChange} />
<ToolbarButton
data-testid="toolbar-upload-folder"
icon={<Icon name="folder-arrow-up" alt={c('Action').t`Upload folder`} />}
title={c('Action').t`Upload folder`}
onClick={handleUploadFolder}
/>
</>
);
};
export default UploadFolderButton;
| 2,918
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Drive/ToolbarButtons/index.ts
|
export { default as ActionsDropdown } from './ActionsDropdown';
export { default as CreateNewFileButton } from './CreateNewFileButton';
export { default as CreateNewFolderButton } from './CreateNewFolderButton';
export { default as MoveToFolderButton } from './MoveToFolderButton';
export { default as MoveToTrashButton } from './MoveToTrashButton';
export { default as UploadFileButton } from './UploadFileButton';
export { default as UploadFolderButton } from './UploadFolderButton';
| 2,919
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/FileBrowser/CopyLinkIcon.tsx
|
import { useCallback, useState } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { Icon, Tooltip } from '@proton/components';
import { useActions } from '../../../store';
import { BrowserItemId } from '../../FileBrowser/interface';
interface Props {
shareId: string;
linkId: BrowserItemId;
trashed: number | null;
isExpired: boolean;
className?: string;
}
const CopyLinkIcon = ({ shareId, linkId, trashed, isExpired, className }: Props) => {
const [isLoading, setIsLoading] = useState(false);
const { copyShareLinkToClipboard } = useActions();
const handleGetLink = useCallback(
(e) => {
if (!copyShareLinkToClipboard) {
return;
}
setIsLoading(true);
e.stopPropagation(); // To not show file preview when clicking (to not trigger other click event).
e.preventDefault(); // To not show file preview when pressing enter (to disable click event).
copyShareLinkToClipboard(new AbortController().signal, shareId, linkId).finally(() => {
setIsLoading(false);
});
},
[shareId, linkId]
);
if (!copyShareLinkToClipboard || isExpired || trashed) {
return null;
}
return (
<Tooltip title={c('Action').t`Copy link`}>
<Button
loading={isLoading}
icon
shape="ghost"
size="small"
className={className}
onClick={handleGetLink}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
handleGetLink(e);
}
}}
>
<Icon name="link" alt={c('Action').t`Copy link`} />
</Button>
</Tooltip>
);
};
export default CopyLinkIcon;
| 2,920
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/FileBrowser/GridViewItem.tsx
|
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { Checkbox, FileNameDisplay, Icon } from '@proton/components';
import clsx from '@proton/utils/clsx';
import { stopPropagation } from '../../../utils/stopPropagation';
import { useCheckbox, useItemContextMenu, useSelection } from '../../FileBrowser';
import { SelectionState } from '../../FileBrowser/hooks/useSelectionControls';
import { DeviceItem } from '../Devices/Devices';
import { DriveItem } from '../Drive/Drive';
import { SharedLinkItem } from '../SharedLinks/SharedLinks';
import { TrashItem } from '../Trash/Trash';
const GridViewItemBase = ({
IconComponent,
SignatureIconComponent,
item,
disableSelection = false,
}: {
IconComponent: React.ReactNode;
SignatureIconComponent?: React.ReactNode;
item: DriveItem | TrashItem | SharedLinkItem | DeviceItem;
disableSelection?: boolean;
}) => {
const selectionControls = useSelection()!;
const contextMenuControls = useItemContextMenu();
const { handleCheckboxChange, handleCheckboxClick, handleCheckboxWrapperClick } = useCheckbox(item.id);
const isContextMenuButtonActive = contextMenuControls.isOpen && selectionControls.selectedItemIds.includes(item.id);
return (
<>
<div className="flex flex-item-fluid flex-justify-center flex-align-items-center file-browser-grid-item--container">
{IconComponent}
</div>
<div
className={clsx([
'flex file-browser-grid-item--select',
selectionControls?.selectionState !== SelectionState.NONE ? null : 'mouse:group-hover:opacity-100',
])}
onTouchStart={stopPropagation}
onKeyDown={stopPropagation}
onClick={handleCheckboxWrapperClick}
>
{!disableSelection ? (
<Checkbox
disabled={item.isLocked}
className="increase-click-surface file-browser-grid-item-checkbox"
checked={selectionControls.isSelected(item.id)}
onChange={handleCheckboxChange}
onClick={handleCheckboxClick}
/>
) : null}
</div>
<div className="file-browser-grid-item--file-name flex border-top">
{SignatureIconComponent ? SignatureIconComponent : null}
<FileNameDisplay text={item.name} className="mx-auto" data-testid="grid-item-name" />
<Button
shape="ghost"
size="small"
icon
className={clsx([
'file-browser-grid-view--options',
isContextMenuButtonActive ? 'file-browser--options-focus' : 'mouse:group-hover:opacity-100',
])}
onClick={(e) => {
selectionControls?.selectItem(item.id);
contextMenuControls.handleContextMenu(e);
}}
onTouchEnd={(e) => {
selectionControls?.selectItem(item.id);
contextMenuControls.handleContextMenuTouch?.(e);
}}
>
<Icon name="three-dots-vertical" alt={c('Action').t`More options`} />
</Button>
</div>
</>
);
};
export default GridViewItemBase;
| 2,921
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/FileBrowser/GridViewItemDevice.tsx
|
import { Icon } from '@proton/components';
import { DeviceItem } from '../Devices/Devices';
import GridViewItemBase from './GridViewItem';
import { getDeviceIconText } from './utils';
export function GridViewItemDevice({ item }: { item: DeviceItem }) {
const iconText = getDeviceIconText(item.name);
return (
<GridViewItemBase
IconComponent={<Icon name="tv" size={42} alt={iconText}></Icon>}
item={item}
disableSelection
/>
);
}
| 2,922
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/FileBrowser/GridViewItemLink.tsx
|
import { FileIcon } from '@proton/components';
import SignatureIcon from '../../SignatureIcon';
import { DriveItem } from '../Drive/Drive';
import { SharedLinkItem } from '../SharedLinks/SharedLinks';
import { TrashItem } from '../Trash/Trash';
import GridViewItemBase from './GridViewItem';
import { getLinkIconText } from './utils';
export function GridViewItem({ item }: { item: DriveItem | TrashItem | SharedLinkItem }) {
const iconText = getLinkIconText({
isFile: item.isFile,
mimeType: item.mimeType,
linkName: item.name,
});
const IconComponent = (
<>
{item.cachedThumbnailUrl ? (
<img src={item.cachedThumbnailUrl} className="file-browser-grid-item--thumbnail" alt={iconText} />
) : (
<FileIcon size={48} mimeType={item.isFile ? item.mimeType : 'Folder'} alt={iconText} />
)}
</>
);
return (
<GridViewItemBase
IconComponent={IconComponent}
SignatureIconComponent={
<SignatureIcon
isFile={item.isFile}
signatureIssues={item.signatureIssues}
className="file-browser-grid-view--signature-icon"
/>
}
item={item}
/>
);
}
| 2,923
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/FileBrowser/contentCells.tsx
|
import { c } from 'ttag';
import { FileIcon, Icon, TableCell, useActiveBreakpoint } from '@proton/components';
import clsx from '@proton/utils/clsx';
import useActiveShare from '../../../hooks/drive/useActiveShare';
import { formatAccessCount } from '../../../utils/formatters';
import { Cells } from '../../FileBrowser';
import SignatureIcon from '../../SignatureIcon';
import { DeviceItem } from '../Devices/Devices';
import { DriveItem } from '../Drive/Drive';
import { SharedLinkItem } from '../SharedLinks/SharedLinks';
import { TrashItem } from '../Trash/Trash';
import CopyLinkIcon from './CopyLinkIcon';
import { getDeviceIconText, getLinkIconText } from './utils';
const { LocationCell: LocationCellBase, SizeCell: SizeCellBase, NameCell: NameCellBase, TimeCell } = Cells;
export const NameCell = ({ item }: { item: DriveItem | SharedLinkItem | TrashItem }) => {
const iconText = getLinkIconText({
linkName: item.name,
mimeType: item.mimeType,
isFile: item.isFile,
});
return (
<TableCell className="m-0 flex flex-align-items-center flex-nowrap flex-item-fluid" data-testid="column-name">
{item.cachedThumbnailUrl ? (
<img
src={item.cachedThumbnailUrl}
alt={iconText}
className="file-browser-list-item--thumbnail flex-item-noshrink mr-2"
/>
) : (
<FileIcon mimeType={item.isFile ? item.mimeType : 'Folder'} alt={iconText} className="mr-2" />
)}
<SignatureIcon
signatureIssues={item.signatureIssues}
isFile={item.isFile}
className="mr-2 flex-item-noshrink"
/>
<NameCellBase name={item.name} />
</TableCell>
);
};
export const DeviceNameCell = ({ item }: { item: DeviceItem }) => {
const iconText = getDeviceIconText(item.name);
return (
<TableCell
className="m-0 flex flex-align-items-center flex-nowrap flex-item-fluid filebrowser-list-device-name-cell"
data-testid="column-name"
>
<Icon name="tv" alt={iconText} className="mr-2" />
<NameCellBase name={item.name} />
</TableCell>
);
};
export const ModifiedCell = ({ item }: { item: DriveItem }) => {
return (
<TableCell className="flex flex-align-items-center m-0 w-1/6" data-testid="column-modified">
<TimeCell time={item.fileModifyTime} />
</TableCell>
);
};
export const ModifiedCellDevice = ({ item }: { item: DeviceItem }) => {
return (
<TableCell className="flex flex-align-items-center m-0 w-1/6" data-testid="column-modified">
<TimeCell time={item.modificationTime} />
</TableCell>
);
};
export function SizeCell({ item }: { item: DriveItem | TrashItem }) {
const { isDesktop } = useActiveBreakpoint();
return (
<TableCell
className={clsx(['flex flex-align-items-center m-0', isDesktop ? 'w-1/10' : 'w-1/6'])}
data-testid="column-size"
>
{item.isFile ? <SizeCellBase size={item.size} /> : '-'}
</TableCell>
);
}
export const DeletedCell = ({ item }: { item: TrashItem }) => {
return (
<TableCell className="m-0 w-1/4" data-testid="column-trashed">
<TimeCell time={item.trashed || item.fileModifyTime} />
</TableCell>
);
};
export const CreatedCell = ({ item }: { item: TrashItem }) => {
return (
<TableCell className="m-0 w-1/6" data-testid="column-share-created">
{item.shareUrl?.createTime && <TimeCell time={item.shareUrl.createTime} />}
</TableCell>
);
};
export const LocationCell = ({ item }: { item: TrashItem | SharedLinkItem }) => {
const { isDesktop } = useActiveBreakpoint();
const shareId = item.rootShareId;
return (
<TableCell className={clsx(['m-0', isDesktop ? 'w-1/5' : 'w-1/4'])} data-testid="column-location">
<LocationCellBase shareId={shareId} parentLinkId={item.parentLinkId} />
</TableCell>
);
};
export const AccessCountCell = ({ item }: { item: TrashItem }) => {
return (
<TableCell className="m-0 w-1/6" data-testid="column-num-accesses">
{formatAccessCount(item.shareUrl?.numAccesses)}
</TableCell>
);
};
export const ExpirationCell = ({ item }: { item: TrashItem }) => {
const { isDesktop } = useActiveBreakpoint();
const expiredPart = isDesktop ? (
<span className="ml-1">{c('Label').t`(Expired)`}</span>
) : (
<span>{c('Label').t`Expired`}</span>
);
let expiration;
if (item.shareUrl) {
expiration = item.shareUrl.expireTime ? (
<div className="flex flex-nowrap">
{(isDesktop || !item.shareUrl.isExpired) && <TimeCell time={item.shareUrl.expireTime} />}
{item.shareUrl.isExpired ? expiredPart : null}
</div>
) : (
c('Label').t`Never`
);
}
return (
<TableCell className="m-0 w-1/5" data-testid="column-share-expires">
{expiration}
</TableCell>
);
};
export const ShareOptionsCell = ({ item }: { item: DriveItem }) => {
const { activeShareId } = useActiveShare();
return (
<TableCell
className="m-0 file-browser-list--icon-column file-browser-list--context-menu-column flex flex-align-items-center"
data-testid="column-share-options"
>
{item.shareUrl ? (
<CopyLinkIcon
shareId={activeShareId}
linkId={item.id}
isExpired={Boolean(item.shareUrl?.isExpired)}
trashed={item.trashed}
/>
) : null}
</TableCell>
);
};
| 2,924
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/FileBrowser/headerCells.tsx
|
import { c } from 'ttag';
import { HeaderCellsPresets } from '../../FileBrowser/interface';
export const checkbox = {
type: HeaderCellsPresets.Checkbox,
};
export const name = {
type: 'name',
getText: () => c('Label').t`Name`,
sorting: true,
};
export const location = {
type: 'location',
getText: () => c('Label').t`Location`,
props: {
className: 'w-1/5',
},
};
export const trashed = {
type: 'trashed',
getText: () => c('Label').t`Deleted`,
props: {
className: 'w-1/4',
},
sorting: true,
};
export const size = {
type: 'size',
getText: () => c('Label').t`Size`,
props: {
className: 'w-1/10',
},
sorting: true,
};
export const modificationDate = {
type: 'fileModifyTime',
getText: () => c('Label').t`Modified`,
props: {
className: 'w-1/6',
},
sorting: true,
};
export const creationDate = {
type: 'linkCreateTime',
getText: () => c('Label').t`Created`,
props: {
className: 'w-1/6',
},
sorting: true,
};
export const accessCount = {
type: 'numAccesses',
getText: () => c('Label').t`# of downloads`,
props: {
className: 'w-1/6',
},
sorting: true,
};
export const expirationDate = {
type: 'linkExpireTime',
getText: () => c('Label').t`Expires`,
props: {
className: 'w-1/5',
},
sorting: true,
};
export const placeholder = {
type: HeaderCellsPresets.Placeholder,
props: {
className: 'file-browser-list--context-menu-column',
},
};
export default {
checkbox,
location,
modificationDate,
name,
placeholder,
size,
trashed,
creationDate,
expirationDate,
accessCount,
};
| 2,925
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/FileBrowser/utils.tsx
|
import { c } from 'ttag';
export const getLinkIconText = ({
isFile,
mimeType,
linkName,
}: {
linkName: string;
isFile: boolean;
mimeType: string;
}) => `${!isFile ? c('Label').t`Folder` : `${c('Label').t`File`} - ${mimeType}`} - ${linkName}`;
export const getDeviceIconText = (name: string) => {
return `${c('Label').t`Device`} - ${name}`;
};
| 2,926
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos/EmptyPhotos.tsx
|
import { FC } from 'react';
import { c } from 'ttag';
import { Href } from '@proton/atoms';
import { DRIVE_APP_NAME } from '@proton/shared/lib/constants';
import { DRIVE_ANDROID_APP, DRIVE_IOS_APP } from '@proton/shared/lib/drive/urls';
import appStoreSvg from '@proton/styles/assets/img/illustrations/app-store.svg';
import emptyPhotosSvg from '@proton/styles/assets/img/illustrations/empty-photos.svg';
import playStoreSvg from '@proton/styles/assets/img/illustrations/play-store.svg';
import { DriveEmptyView } from '../../layout/DriveEmptyView';
type Props = {};
export const EmptyPhotos: FC<Props> = () => {
return (
<DriveEmptyView
image={emptyPhotosSvg}
title={
// translator: Shown as a call to action when there are no photos synced
c('Info').t`Ready to add some photos?`
}
subtitle={
// translator: Shown as a call to action when there are no photos synced
c('Info').t`Get the app to backup photos from your phone.`
}
>
<div className="mt-10 flex flex-align-items-center flex-justify-center gap-4">
<Href href={DRIVE_ANDROID_APP}>
<img width="140" src={playStoreSvg} alt={c('Info').t`${DRIVE_APP_NAME} on Play Store`} />
</Href>
<Href href={DRIVE_IOS_APP}>
<img width="140" src={appStoreSvg} alt={c('Info').t`${DRIVE_APP_NAME} on App Store`} />
</Href>
</div>
</DriveEmptyView>
);
};
export default EmptyPhotos;
| 2,927
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos/PhotosGrid.tsx
|
import React, { FC, ReactNode, useCallback, useMemo, useRef, useState } from 'react';
import { Loader, useElementRect } from '@proton/components';
import { rootFontSize } from '@proton/shared/lib/helpers/dom';
import type { PhotoGridItem } from '../../../store';
import { isPhotoGroup } from '../../../store/_photos';
import { PhotosCard, PhotosGroup } from './grid';
type Props = {
data: PhotoGridItem[];
onItemRender: (linkId: string, domRef: React.MutableRefObject<unknown>) => void;
onItemRenderLoadedLink: (linkId: string, domRef: React.MutableRefObject<unknown>) => void;
hasSelection: boolean;
isLoadingMore: boolean;
onItemClick: (linkId: string) => void;
onSelectChange: (index: number, isSelected: boolean) => void;
isGroupSelected: (groupIndex: number) => boolean | 'some';
isItemSelected: (linkId: string) => boolean;
};
export const PhotosGrid: FC<Props> = ({
data,
onItemRender,
onItemRenderLoadedLink,
isLoadingMore,
onItemClick,
onSelectChange,
hasSelection,
isGroupSelected,
isItemSelected,
}) => {
const containerRef = useRef<HTMLDivElement>(null);
const containerRect = useElementRect(containerRef);
const [scrollPosition, setScrollPosition] = useState(0);
const handleScroll = useCallback(() => {
requestAnimationFrame(() => {
if (!containerRef || !containerRef.current) {
return;
}
setScrollPosition(containerRef.current.scrollTop);
});
}, [containerRef, setScrollPosition]);
const emRatio = rootFontSize();
const dimensions = useMemo(() => {
if (!containerRect) {
return null;
}
// Inner scroll container dimensions
const containerWidth = containerRect.width - 2 * emRatio;
const containerHeight = containerRect.height;
// Item base dimensions (should be scaled)
const width = 10 * emRatio;
const height = 13.75 * emRatio;
// Gap between items (never scaled)
const gap = 0.25 * emRatio;
// Height of group (never scaled)
const groupHeight = 2.75 * emRatio;
// Amount of items per row (to calculate repsonsive scaling)
const itemsPerLine = Math.max(2, Math.floor((containerWidth + gap) / (width + gap)));
// Multiplicative scaling to apply to final values
const scaling = (containerWidth - (itemsPerLine - 1) * gap) / (itemsPerLine * width);
// Item dimensions (scaled)
const itemHeight = height * scaling;
const itemWidth = width * scaling;
// Helper to know if an item is within the viewport
const scrollMargin = (itemHeight + gap) * 2;
const itemShouldRender = (y: number, scrollPosition: number) =>
y >= scrollPosition - itemHeight - scrollMargin && y <= scrollPosition + containerHeight + scrollMargin;
return {
itemHeight,
itemWidth,
gap,
groupHeight,
itemsPerLine,
itemShouldRender,
};
}, [containerRect, emRatio]);
const [gridItems, innerStyle] = useMemo(() => {
if (!dimensions) {
return [];
}
const { gap, itemHeight, itemWidth, groupHeight, itemsPerLine, itemShouldRender } = dimensions;
const items: ReactNode[] = [];
let currentX = 0;
let currentY = 0;
let lastY = 0;
// Attempt to make the animation a bit more dynamic
// and not visually repetitive
const animationOffset = Math.max(itemsPerLine === 7 ? 5 : 7, Math.round(itemsPerLine * 0.6));
data.forEach((item, i) => {
if (isPhotoGroup(item)) {
if (currentX != 0) {
currentY += itemHeight + gap;
}
currentX = 0;
const y = currentY;
lastY = y;
if (itemShouldRender(y, scrollPosition)) {
items.push(
<PhotosGroup
key={item}
style={{
position: 'absolute',
height: `${groupHeight}px`,
width: '100%',
top: `${y}px`,
}}
text={item}
// Do not show separator on first item
showSeparatorLine={i > 0}
onSelect={(isSelected) => {
onSelectChange(i, isSelected);
}}
selected={isGroupSelected(i)}
/>
);
}
currentY += groupHeight + gap;
} else {
const x = currentX * (itemWidth + gap);
const y = currentY;
lastY = y;
const isSelected = isItemSelected(item.linkId);
if (itemShouldRender(y, scrollPosition)) {
items.push(
<PhotosCard
key={item.linkId}
photo={item}
onRender={onItemRender}
onRenderLoadedLink={onItemRenderLoadedLink}
onClick={() => {
if (hasSelection) {
onSelectChange(i, !isSelected);
} else {
onItemClick(item.linkId);
}
}}
onSelect={(isSelected) => {
onSelectChange(i, isSelected);
}}
selected={isSelected}
style={{
position: 'absolute',
width: itemWidth,
height: itemHeight,
top: `${y}px`,
left: `${x}px`,
animationDelay: `${
Math.round(((i % animationOffset) / (animationOffset / 2)) * 10) / 10
}s`,
}}
hasSelection={hasSelection}
/>
);
}
currentX++;
if (currentX >= itemsPerLine) {
currentY += itemHeight + gap;
currentX = 0;
}
}
});
const innerStyle = {
height: `${lastY + itemHeight}px`,
};
return [items, innerStyle];
}, [data, isItemSelected, isGroupSelected, dimensions, scrollPosition]);
return (
<div className="p-4 overflow-auto outline-none--at-all" ref={containerRef} onScroll={handleScroll}>
<div className="relative w-full" style={innerStyle}>
{gridItems}
</div>
{isLoadingMore && <Loader />}
</div>
);
};
| 2,928
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos/PhotosView.tsx
|
import React, { FC, useCallback, useMemo, useRef, useState } from 'react';
import { c, msgid } from 'ttag';
import { NavigationControl, TopBanner, useAppTitle, useFlag } from '@proton/components';
import { Loader } from '@proton/components/components';
import { useShiftKey } from '../../../hooks/util/useShiftKey';
import { PhotoLink, usePhotosView, useThumbnailsDownload } from '../../../store';
import PortalPreview from '../../PortalPreview';
import { useDetailsModal } from '../../modals/DetailsModal';
import { useLinkSharingModal } from '../../modals/ShareLinkModal/ShareLinkModal';
import UploadDragDrop from '../../uploads/UploadDragDrop/UploadDragDrop';
import ToolbarRow from '../ToolbarRow/ToolbarRow';
import { EmptyPhotos } from './EmptyPhotos';
import { PhotosGrid } from './PhotosGrid';
import { PhotosClearSelectionButton } from './components/PhotosClearSelectionButton';
import PhotosRecoveryBanner from './components/PhotosRecoveryBanner/PhotosRecoveryBanner';
import { usePhotosSelection } from './hooks';
import { PhotosToolbar } from './toolbar';
export const PhotosView: FC<void> = () => {
useAppTitle(c('Title').t`Photos`);
const isUploadDisabled = useFlag('DrivePhotosUploadDisabled');
const {
shareId,
linkId,
photos,
isLoading,
isLoadingMore,
loadPhotoLink,
photoLinkIdToIndexMap,
photoLinkIds,
requestDownload,
} = usePhotosView();
const { selectedItems, clearSelection, isGroupSelected, isItemSelected, handleSelection } = usePhotosSelection(
photos,
photoLinkIdToIndexMap
);
const [detailsModal, showDetailsModal] = useDetailsModal();
const [linkSharingModal, showLinkSharingModal] = useLinkSharingModal();
const [previewLinkId, setPreviewLinkId] = useState<string | undefined>();
const isShiftPressed = useShiftKey();
const thumbnails = useThumbnailsDownload();
const handleItemRender = (itemLinkId: string, domRef: React.MutableRefObject<unknown>) =>
loadPhotoLink(itemLinkId, domRef);
const handleItemRenderLoadedLink = (itemLinkId: string, domRef: React.MutableRefObject<unknown>) => {
if (shareId) {
thumbnails.addToDownloadQueue(shareId, itemLinkId, undefined, domRef);
}
};
const photoCount = photoLinkIds.length;
const selectedCount = selectedItems.length;
const handleToolbarPreview = useCallback(() => {
let selected = selectedItems[0];
if (selectedItems.length === 1 && selected) {
setPreviewLinkId(selected.linkId);
}
}, [selectedItems, setPreviewLinkId]);
const previewRef = useRef<HTMLDivElement>(null);
const previewIndex = useMemo(
() => photoLinkIds.findIndex((item) => item === previewLinkId),
[photoLinkIds, previewLinkId]
);
const previewItem = useMemo(
() => (previewLinkId !== undefined ? (photos[photoLinkIdToIndexMap[previewLinkId]] as PhotoLink) : undefined),
[photos, previewLinkId, photoLinkIdToIndexMap]
);
const setPreviewIndex = useCallback(
(index: number) => setPreviewLinkId(photoLinkIds[index]),
[setPreviewLinkId, photoLinkIds]
);
if (isLoading && !isLoadingMore) {
return <Loader />;
}
if (!shareId || !linkId) {
return <EmptyPhotos />;
}
const isEmpty = photos.length === 0;
return (
<>
{detailsModal}
{linkSharingModal}
{isUploadDisabled && (
<TopBanner className="bg-warning">{c('Info')
.t`We are experiencing technical issues. Uploading new photos is temporarily disabled.`}</TopBanner>
)}
{previewItem && (
<PortalPreview
ref={previewRef}
shareId={shareId}
linkId={previewItem.linkId}
revisionId={previewItem.activeRevision.id}
key="portal-preview-photos"
open={!!previewItem}
date={previewItem.activeRevision.photo.captureTime}
onShare={
!!previewItem?.trashed
? undefined
: () => showLinkSharingModal({ shareId, linkId: previewItem.linkId })
}
onDetails={() =>
showDetailsModal({
shareId,
linkId: previewItem.activeRevision.photo.linkId,
})
}
navigationControls={
<NavigationControl
current={previewIndex + 1}
total={photoCount}
rootRef={previewRef}
onPrev={() => setPreviewIndex(previewIndex - 1)}
onNext={() => setPreviewIndex(previewIndex + 1)}
/>
}
onClose={() => setPreviewLinkId(undefined)}
onExit={() => setPreviewLinkId(undefined)}
/>
)}
<PhotosRecoveryBanner />
<UploadDragDrop
disabled={isUploadDisabled}
isForPhotos
shareId={shareId}
linkId={linkId}
className="flex flex-column flex-nowrap flex-item-fluid"
>
<ToolbarRow
titleArea={
<span className="text-strong pl-1">
{selectedCount > 0 ? (
<div className="flex gap-2">
<PhotosClearSelectionButton onClick={clearSelection} />
{/* aria-live & aria-atomic ensure the count gets revocalized when it changes */}
<span aria-live="polite" aria-atomic="true">
{c('Info').ngettext(
msgid`${selectedCount} selected`,
`${selectedCount} selected`,
selectedCount
)}
</span>
</div>
) : (
c('Title').t`Photos`
)}
</span>
}
toolbar={
<PhotosToolbar
shareId={shareId}
linkId={linkId}
selectedItems={selectedItems}
onPreview={handleToolbarPreview}
requestDownload={requestDownload}
uploadDisabled={isUploadDisabled}
/>
}
/>
{isEmpty ? (
<EmptyPhotos />
) : (
<PhotosGrid
data={photos}
onItemRender={handleItemRender}
onItemRenderLoadedLink={handleItemRenderLoadedLink}
isLoadingMore={isLoadingMore}
onItemClick={setPreviewLinkId}
hasSelection={selectedCount > 0}
onSelectChange={(i, isSelected) =>
handleSelection(i, { isSelected, isMultiSelect: isShiftPressed() })
}
isGroupSelected={isGroupSelected}
isItemSelected={isItemSelected}
/>
)}
</UploadDragDrop>
</>
);
};
| 2,929
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos/index.ts
|
export { PhotosView } from './PhotosView';
| 2,930
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos/components/PhotosClearSelectionButton.tsx
|
import { FC } from 'react';
import { c } from 'ttag';
import { Icon, ToolbarButton } from '@proton/components/components';
interface Props {
onClick: () => void;
}
export const PhotosClearSelectionButton: FC<Props> = ({ onClick }) => {
return (
<ToolbarButton
title={c('Action').t`Clear selection`}
icon={<Icon name="cross" alt={c('Action').t`Clear selection`} />}
onClick={onClick}
data-testid="toolbar-clear-selection"
/>
);
};
| 2,931
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos/components
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos/components/PhotosRecoveryBanner/PhotosRecoveryBanner.tsx
|
import { useEffect, useState } from 'react';
import { c, msgid } from 'ttag';
import { Button } from '@proton/atoms/Button';
import { CircleLoader } from '@proton/atoms/CircleLoader';
import { TopBanner } from '@proton/components/containers';
import clsx from '@proton/utils/clsx';
import { usePhotosRecovery } from '../../../../../store';
import { RECOVERY_STATE } from '../../../../../store/_photos/usePhotosRecovery';
const getPhotosRecoveryProgressText = (
recoveryState: RECOVERY_STATE,
countOfUnrecoveredLinksLeft: number,
countOfFailedLinks: number
) => {
const baseText = c('Info').t`Restoring Photos... Please keep the tab open`;
if (recoveryState === 'READY') {
return c('Info').t`Restore Photos`;
}
if (recoveryState === 'FAILED') {
return c('Info').t`An issue occurred during the restore process.`;
}
if (recoveryState === 'SUCCEED') {
return c('Info').t`Photos have been successfully recovered.`;
}
const errorMessage = !!countOfFailedLinks
? c('Failed').ngettext(msgid`${countOfFailedLinks} failed`, `${countOfFailedLinks} failed`, countOfFailedLinks)
: '';
if (countOfUnrecoveredLinksLeft) {
return `${baseText}: ${c('Success').ngettext(
msgid`${countOfUnrecoveredLinksLeft} left`,
`${countOfUnrecoveredLinksLeft} left`,
countOfUnrecoveredLinksLeft
)} ${errorMessage}`;
}
return `${baseText}.`;
};
const PhotosRecoveryBanner = () => {
const {
start,
state: recoveryState,
countOfUnrecoveredLinksLeft,
countOfFailedLinks,
needsRecovery,
} = usePhotosRecovery();
const [showBanner, setShowBanner] = useState<boolean>(false);
useEffect(() => {
setShowBanner(needsRecovery);
}, [needsRecovery]);
if (!showBanner) {
return null;
}
return (
<TopBanner
className={clsx(
recoveryState === 'SUCCEED' && 'bg-success',
recoveryState === 'FAILED' && 'bg-danger',
recoveryState !== 'FAILED' && recoveryState !== 'SUCCEED' && 'bg-warning'
)}
>
<div className="flex flex-align-items-center flex-justify-center">
<span className="mr-2 py-1 inline-block">
{getPhotosRecoveryProgressText(recoveryState, countOfUnrecoveredLinksLeft, countOfFailedLinks)}
</span>
{recoveryState === 'READY' && (
<Button size="small" onClick={start}>
{c('Action').t`Start`}
</Button>
)}
{recoveryState === 'SUCCEED' && (
<Button size="small" onClick={() => setShowBanner(false)}>
{c('Action').t`Ok`}
</Button>
)}
{recoveryState === 'FAILED' && (
<Button size="small" onClick={start}>
{c('Action').t`Retry`}
</Button>
)}
{recoveryState !== 'SUCCEED' && recoveryState !== 'FAILED' && recoveryState !== 'READY' && (
<CircleLoader />
)}
</div>
</TopBanner>
);
};
export default PhotosRecoveryBanner;
| 2,932
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos/grid/PhotosCard.scss
|
@keyframes photos-card-loading {
/**
* Animating `opacity` is intended, as animating background-color
* will cause Chrome to trigger paint.
*
* See https://web.dev/animations-guide/#triggers
*/
from {
opacity: 0;
}
to {
opacity: 1;
}
}
.photos-card {
user-select: none;
background-color: var(--background-weak);
&:hover {
background-color: var(--background-weak);
}
&--loading {
&::before {
inline-size: 100%;
block-size: 100%;
content: '';
display: block;
opacity: 0;
background-color: var(--background-strong);
animation: photos-card-loading alternate 1s ease-in-out infinite both;
animation-delay: inherit;
}
}
&--hide-checkbox {
& > .checkbox-container {
display: none;
}
&:hover > .checkbox-container,
&:focus-within > .checkbox-container {
display: block;
}
}
&--selected {
border: 1px var(--interaction-norm) solid;
&:hover {
border: 1px var(--interaction-norm) solid;
}
&::after {
inline-size: 100%;
block-size: 100%;
position: absolute;
inset-block-start: 0;
content: '';
display: block;
opacity: 0.3;
background-color: var(--interaction-norm);
}
}
}
.photos-card-thumbnail {
pointer-events: none;
object-fit: cover;
&--empty {
background-color: var(--background-weak);
}
}
.photos-card-video-info {
padding-block-start: 100%;
background: linear-gradient(180deg, rgb(0 0 0 / 0) 86.82%, rgb(0 0 0 / 0.4) 100%);
color: white;
}
.photos-card-share-icon {
background-color: rgb(112 109 107 / 0.8);
inline-size: 20px;
block-size: 20px;
}
| 2,933
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos/grid/PhotosCard.tsx
|
import React, { CSSProperties, FC, useCallback, useEffect, useRef, useState } from 'react';
import { formatDuration } from 'date-fns';
import { c } from 'ttag';
import { ButtonLike } from '@proton/atoms/Button';
import { Checkbox, FileIcon, Icon } from '@proton/components/components';
import { isVideo } from '@proton/shared/lib/helpers/mimetype';
import { dateLocale } from '@proton/shared/lib/i18n';
import playCircleFilledIcon from '@proton/styles/assets/img/drive/play-circle-filled.svg';
import clsx from '@proton/utils/clsx';
import type { PhotoLink } from '../../../../store/';
import { stopPropagation } from '../../../../utils/stopPropagation';
import SignatureIcon from '../../../SignatureIcon';
import { getMimeTypeDescription } from '../../helpers';
import { formatVideoDuration } from './formatVideoDuration';
import './PhotosCard.scss';
type Props = {
photo: PhotoLink;
selected: boolean;
onRender: (linkId: string, domRef: React.MutableRefObject<unknown>) => void;
onRenderLoadedLink: (linkId: string, domRef: React.MutableRefObject<unknown>) => void;
style: CSSProperties;
onClick: () => void;
onSelect: (isSelected: boolean) => void;
hasSelection: boolean;
};
const getAltText = ({ mimeType, name }: PhotoLink) =>
`${c('Label').t`Photo`} - ${getMimeTypeDescription(mimeType || '')} - ${name}`;
export const PhotosCard: FC<Props> = ({
style,
onRender,
onRenderLoadedLink,
photo,
onClick,
onSelect,
selected,
hasSelection,
}) => {
const [imageReady, setImageReady] = useState(false);
const ref = useRef(null);
// First call when photo is rendered to request caching link meta data.
useEffect(() => {
if (!photo.name) {
onRender(photo.linkId, ref);
}
}, [photo.name, photo.linkId]);
// Once we have link meta data (link has name which is missing during
// photo listing), we can initiate thumbnail loading.
// The separation is needed to call thumbnail queue when link is already
// present in cache to not fetch or decrypt meta data more than once.
useEffect(() => {
if (photo.name) {
onRenderLoadedLink(photo.linkId, ref);
}
}, [photo.name]);
const thumbUrl = photo.cachedThumbnailUrl;
const isThumbnailLoading = photo.hasThumbnail === undefined || (photo.hasThumbnail && !imageReady);
const isActive = !!photo.activeRevision.id && !!photo.activeRevision.photo.linkId;
useEffect(() => {
if (thumbUrl) {
const image = new Image();
image.src = thumbUrl;
image.onload = () => {
setImageReady(true);
};
}
}, [thumbUrl]);
const onKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLDivElement>) => {
if (e.key !== ' ') {
return;
}
e.preventDefault();
onClick();
},
[onClick]
);
const showCheckbox = hasSelection;
const isLoaded = !isThumbnailLoading && isActive;
return (
<ButtonLike
as="div"
ref={ref}
style={style}
className={clsx(
'button-for-icon', // `aria-busy` buttons get extra padding, this avoids that
'relative photos-card p-0 border-none rounded-none',
isThumbnailLoading && 'photos-card--loading',
!showCheckbox && 'photos-card--hide-checkbox',
selected && 'photos-card--selected'
)}
onClick={onClick}
onKeyDown={onKeyDown}
tabIndex={0}
aria-busy={!isLoaded}
>
<Checkbox
className="absolute top-0 left-0 ml-2 mt-2"
checked={selected}
onClick={stopPropagation}
onKeyDown={(e) => {
if (e.key !== 'Shift') {
e.stopPropagation();
}
}}
onChange={() => {
onSelect(!selected);
}}
// If we are in select mode, then we don't need to focus the checkbox
// as the main card action is already bound to select
tabIndex={hasSelection ? -1 : 0}
aria-label={
// translator: This string is used by screen readers to inform the user of a selection action
c('Info').t`Select item`
}
></Checkbox>
{isLoaded ? (
<div className="w-full h-full relative">
{!photo.hasThumbnail ? (
<div className="flex flex-align-items-center flex-justify-center w-full h-full photos-card-thumbnail photos-card-thumbnail--empty">
<FileIcon mimeType={photo.mimeType || ''} size={48} />
</div>
) : (
<img
data-testid="photo-card"
src={thumbUrl}
alt={getAltText(photo)}
className="w-full h-full photos-card-thumbnail"
/>
)}
{(photo.signatureIssues || photo.isShared) && (
<div className="absolute top right mr-2 mt-2 flex flex-align-items-center gap-1">
{photo.signatureIssues && (
<SignatureIcon
isFile
signatureIssues={photo.signatureIssues}
className="color-danger"
/>
)}
{photo.isShared && (
<div className="photos-card-share-icon rounded-50 flex flex-align-items-center flex-justify-center">
<Icon name="link" color="white" size={12} />
</div>
)}
</div>
)}
{photo.mimeType && isVideo(photo.mimeType) && (
<div className="w-full absolute bottom flex flex-justify-end flex-align-items-center px-2 py-2 photos-card-video-info">
{photo.duration && (
<time
className="text-semibold mr-1"
dateTime={formatDuration(
{ seconds: Math.floor(photo.duration) },
{
locale: dateLocale,
}
)}
>
{formatVideoDuration(photo.duration)}
</time>
)}
<img src={playCircleFilledIcon} alt="" />
</div>
)}
</div>
) : null}
</ButtonLike>
);
};
| 2,934
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos/grid/PhotosGroup.tsx
|
import * as React from 'react';
import { CSSProperties, FC } from 'react';
import { c } from 'ttag';
import { Checkbox } from '@proton/components/components';
type Props = {
style: CSSProperties;
text: string;
showSeparatorLine: boolean;
onSelect: (isSelected: boolean) => void;
selected: boolean | 'some';
};
export const PhotosGroup: FC<Props> = ({ style, text, showSeparatorLine, onSelect, selected }) => {
return (
<div
style={style}
data-testid="month-text"
className="text-semibold text-no-wrap text-capitalize py-3 flex flex-align-items-center flex-nowrap"
>
<Checkbox
className="mr-2"
checked={!!selected}
indeterminate={selected === 'some'}
onChange={() => {
if (selected === 'some') {
onSelect(true);
} else {
onSelect(!selected);
}
}}
// Note: browsers combine aria-label and the actual label, the translation string is correct
aria-label={
// translator: Used by screen readers to provide context for Photos groups (e.g. Select all items for September)
c('Info').t`Select all items for`
}
>
{text}
</Checkbox>
{showSeparatorLine && <hr className="w-full m-0 ml-3 h-0 border-bottom border-weak" />}
</div>
);
};
| 2,935
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos/grid/formatVideoDuration.test.ts
|
import { formatVideoDuration } from './formatVideoDuration';
jest.mock('@proton/shared/lib/i18n', () => ({
dateLocale: {
code: 'en-US',
formatLong: {
time: jest.fn(),
},
},
}));
describe('formatVideoDuration()', () => {
it('format a duration without hours', () => {
const durationInSeconds = 65; // 1 minute and 5 seconds
const formattedDuration = formatVideoDuration(durationInSeconds);
expect(formattedDuration).toBe('1:05');
});
it('format a duration with hours', () => {
const durationInSeconds = 3665; // 1 hour, 1 minute, and 5 seconds
const formattedDuration = formatVideoDuration(durationInSeconds);
expect(formattedDuration).toBe('1:01:05');
});
it('format a duration in different locale', () => {
const durationInSeconds = 3665; // 1 hour, 1 minute, and 5 seconds
const formattedDuration = formatVideoDuration(durationInSeconds, 'fr-FR');
expect(formattedDuration).toBe('1:01:05');
});
});
| 2,936
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos/grid/formatVideoDuration.ts
|
import { dateLocale } from '@proton/shared/lib/i18n';
export const formatVideoDuration = (seconds: number, localeCode = dateLocale.code) => {
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
const remainingSeconds = Math.floor(seconds % 60);
let formattedDuration = '';
if (hours > 0) {
formattedDuration += `${hours}:`;
}
const minutesFormatted = new Intl.NumberFormat(localeCode, {
minimumIntegerDigits: hours > 0 ? 2 : 1,
}).format(minutes);
const secondsFormatted = new Intl.NumberFormat(localeCode, {
minimumIntegerDigits: 2,
}).format(remainingSeconds);
formattedDuration += `${minutesFormatted}:${secondsFormatted}`;
return formattedDuration;
};
| 2,937
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos/grid/index.ts
|
export { PhotosGroup } from './PhotosGroup';
export { PhotosCard } from './PhotosCard';
| 2,938
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos/hooks/index.ts
|
export { usePhotosSelection } from './usePhotosSelection';
| 2,939
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos/hooks/usePhotosSelection.test.ts
|
import { act, renderHook } from '@testing-library/react-hooks';
import { isPhotoGroup } from '../../../../store/_photos';
import type { PhotoGroup } from '../../../../store/_photos/interface';
import { getGroupLinkIds, usePhotosSelection } from './usePhotosSelection';
const groups: Record<PhotoGroup, string[]> = {
group1: ['id1', 'id2', 'id3'],
group2: ['id4', 'id5'],
empty: [],
group3: ['id6'],
};
const makeItem = (linkId: string) => ({ linkId });
const data = Object.keys(groups).reduce<(string | ReturnType<typeof makeItem>)[]>((acc, item) => {
acc.push(item);
acc.push(...groups[item].map(makeItem));
return acc;
}, []);
const indexMap = data.reduce<Record<string, number>>((acc, item, index) => {
if (!isPhotoGroup(item)) {
acc[item.linkId] = index;
}
return acc;
}, {});
describe('usePhotosSelection', () => {
let hook: {
current: ReturnType<typeof usePhotosSelection>;
};
beforeEach(() => {
jest.resetAllMocks();
const { result } = renderHook(() => usePhotosSelection(data, indexMap));
hook = result;
expect(hook.current.selectedItems).toStrictEqual([]);
});
it('selects IDs', () => {
const input = ['id1', 'id2'];
const expected = input.map(makeItem);
act(() => {
hook.current.setSelected(true, ...input);
});
expect(hook.current.selectedItems).toStrictEqual(expected);
});
it('removes the IDs from the map', () => {
const input = ['id1', 'id2'];
const params = ['id1'];
const expected = ['id2'].map(makeItem);
act(() => {
hook.current.setSelected(true, ...input);
hook.current.setSelected(false, ...params);
});
expect(hook.current.selectedItems).toStrictEqual(expected);
});
it("does not fail when removing IDs that aren't in the state", () => {
const input = ['id1', 'id2'];
const params = ['not-in-state', 'blah'];
const expected = input.map(makeItem);
act(() => {
hook.current.setSelected(true, ...input);
hook.current.setSelected(false, ...params);
});
expect(hook.current.selectedItems).toStrictEqual(expected);
});
it("does not show IDs that aren't in the data", () => {
const input = ['id9001'];
const expected: any[] = [];
act(() => {
hook.current.setSelected(true, ...input);
});
expect(hook.current.selectedItems).toStrictEqual(expected);
});
it('clears selection', () => {
const input = ['id1', 'id2'];
const expected: any[] = [];
act(() => {
hook.current.setSelected(true, ...input);
hook.current.clearSelection();
});
expect(hook.current.selectedItems).toStrictEqual(expected);
});
describe('handleSelection', () => {
it('selects groups properly', () => {
const id = 'group1';
act(() => {
hook.current.handleSelection(
data.findIndex((group) => group === id),
{ isSelected: true }
);
});
expect(hook.current.selectedItems).toStrictEqual(groups[id].map(makeItem));
});
it('selects items properly', () => {
const id = 'id2';
const index = indexMap[id];
act(() => {
hook.current.handleSelection(index, { isSelected: true });
});
expect(hook.current.selectedItems).toStrictEqual([data[index]]);
});
});
describe('isGroupSelected', () => {
it('returns true for a fully selected group', () => {
const id = 'group1';
const group = groups[id];
act(() => {
hook.current.setSelected(true, ...group);
});
expect(hook.current.isGroupSelected(data.findIndex((item) => item === id))).toBe(true);
});
it("returns 'some' for a partially selected group (start not selected)", () => {
const id = 'group1';
const group = groups[id];
act(() => {
hook.current.setSelected(true, ...group.slice(1, 2));
});
expect(hook.current.isGroupSelected(data.findIndex((item) => item === id))).toBe('some');
});
it("returns 'some' for a partially selected group (middle not selected)", () => {
const id = 'group1';
const group = groups[id];
act(() => {
hook.current.setSelected(true, group[0], group[2]);
});
expect(hook.current.isGroupSelected(data.findIndex((item) => item === id))).toBe('some');
});
it("returns 'some' for a partially selected group (end not selected)", () => {
const id = 'group1';
const group = groups[id];
act(() => {
hook.current.setSelected(true, ...group.slice(0, 2));
});
expect(hook.current.isGroupSelected(data.findIndex((item) => item === id))).toBe('some');
});
it("returns 'some' if only the first item is selected", () => {
const id = 'group1';
const group = groups[id];
act(() => {
hook.current.setSelected(true, group[0]);
});
expect(hook.current.isGroupSelected(data.findIndex((item) => item === id))).toBe('some');
});
it("returns 'some' if only the last item is selected", () => {
const id = 'group1';
const group = groups[id];
act(() => {
hook.current.setSelected(true, group[group.length - 1]);
});
expect(hook.current.isGroupSelected(data.findIndex((item) => item === id))).toBe('some');
});
it('returns false for a non-selected group', () => {
const id = 'group1';
const group = groups[id];
const otherId = 'group2';
act(() => {
hook.current.setSelected(true, ...group);
});
expect(hook.current.isGroupSelected(data.findIndex((item) => item === otherId))).toBe(false);
});
it('returns false for an empty group', () => {
const id = 'empty';
expect(hook.current.isGroupSelected(data.findIndex((item) => item === id))).toBe(false);
});
});
describe('isItemSelected', () => {
it('returns true for a selected item', () => {
const id = 'id1';
act(() => {
hook.current.setSelected(true, id);
});
expect(hook.current.isItemSelected(id)).toBe(true);
});
it('returns false for a non-selected item', () => {
const id = 'id1';
const otherId = 'id2';
act(() => {
hook.current.setSelected(true, id);
});
expect(hook.current.isItemSelected(otherId)).toBe(false);
});
});
describe('isMultiSelect', () => {
it('select multiple items', () => {
const id = 'id1';
const lastId = 'id6';
act(() => {
hook.current.handleSelection(
data.findIndex((link) => typeof link !== 'string' && link.linkId === id),
{ isSelected: true, isMultiSelect: true }
);
});
expect(hook.current.isItemSelected(id)).toBe(true);
act(() => {
hook.current.handleSelection(
data.findIndex((link) => typeof link !== 'string' && link.linkId === lastId),
{ isSelected: true, isMultiSelect: true }
);
});
expect(hook.current.selectedItems).toStrictEqual(data.filter((item) => typeof item !== 'string'));
});
it('select multiple items after selecting a group', () => {
const id = 'group1';
const lastId = 'id6';
act(() => {
hook.current.handleSelection(
data.findIndex((group) => group === id),
{ isSelected: true, isMultiSelect: true }
);
});
act(() => {
hook.current.handleSelection(
data.findIndex((link) => typeof link !== 'string' && link.linkId === lastId),
{ isSelected: true, isMultiSelect: true }
);
});
expect(hook.current.selectedItems).toStrictEqual(data.filter((item) => typeof item !== 'string'));
});
it('select multiple from higher index to lower', () => {
const id = 'id6';
const lastId = 'id1';
act(() => {
hook.current.handleSelection(
data.findIndex((link) => typeof link !== 'string' && link.linkId === id),
{ isSelected: true, isMultiSelect: true }
);
});
expect(hook.current.isItemSelected(id)).toBe(true);
act(() => {
hook.current.handleSelection(
data.findIndex((link) => typeof link !== 'string' && link.linkId === lastId),
{ isSelected: true, isMultiSelect: true }
);
});
expect(hook.current.selectedItems).toStrictEqual(data.filter((item) => typeof item !== 'string'));
});
it('unselect multiple items ', () => {
const id = 'id1';
const id2 = 'id2';
const lastId = 'id6';
act(() => {
hook.current.handleSelection(
data.findIndex((link) => typeof link !== 'string' && link.linkId === id),
{ isSelected: true, isMultiSelect: true }
);
});
act(() => {
hook.current.handleSelection(
data.findIndex((link) => typeof link !== 'string' && link.linkId === lastId),
{ isSelected: true, isMultiSelect: true }
);
});
expect(hook.current.selectedItems).toStrictEqual(data.filter((item) => typeof item !== 'string'));
act(() => {
hook.current.handleSelection(
data.findIndex((link) => typeof link !== 'string' && link.linkId === id2),
{ isSelected: true, isMultiSelect: true }
);
});
expect(hook.current.isGroupSelected(data.findIndex((item) => item === id || item === id2))).toBe(false);
});
});
});
describe('getGroupLinkIds', () => {
it('gets all group items', () => {
const id = 'group1';
act(() => {
const groupItems = getGroupLinkIds(
data,
data.findIndex((item) => item === id)
);
expect(groupItems).toStrictEqual(groups[id]);
});
});
it('handles empty groups', () => {
const id = 'empty';
act(() => {
const groupItems = getGroupLinkIds(
data,
data.findIndex((item) => item === id)
);
expect(groupItems).toStrictEqual([]);
});
});
it('handles the last group properly', () => {
const id = 'group3';
act(() => {
const groupItems = getGroupLinkIds(
data,
data.findIndex((item) => item === id)
);
expect(groupItems).toStrictEqual(groups[id]);
});
});
it('does not error on out-of-bounds groups', () => {
act(() => {
const groupItems = getGroupLinkIds(data, 9000);
expect(groupItems).toStrictEqual([]);
});
});
it('does not error on non-groups', () => {
const id = 'id1';
act(() => {
const groupItems = getGroupLinkIds(data, indexMap[id]);
expect(groupItems).toStrictEqual([]);
});
});
});
| 2,940
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos/hooks/usePhotosSelection.ts
|
import { useCallback, useMemo, useState } from 'react';
import { isPhotoGroup } from '../../../../store/_photos';
import type { PhotoGroup } from '../../../../store/_photos/interface';
type SelectionItem = { linkId: string };
type SelectionGroup = PhotoGroup;
export const getGroupLinkIds = <T extends SelectionItem>(data: (T | SelectionGroup)[], groupIndex: number) => {
if (!isPhotoGroup(data[groupIndex])) {
return [];
}
const items: string[] = [];
for (let i = groupIndex + 1; i < data.length; i++) {
const current = data[i];
if (isPhotoGroup(current)) {
break;
}
items.push(current.linkId);
}
return items;
};
export type HandleSelectionArgs = {
isSelected: boolean;
isMultiSelect?: boolean;
};
export const usePhotosSelection = <T extends SelectionItem>(
data: (T | SelectionGroup)[],
photoLinkIdToIndexMap: Record<string, number>
) => {
const [selection, setSelection] = useState<Record<string, boolean>>({});
const [lastIndex, setLastIndex] = useState<number | undefined>();
const setSelected = useCallback(
(isSelected: boolean, ...linkIds: string[]) => {
setSelection((state) => {
let newState = { ...state };
linkIds.forEach((linkId) => {
if (isSelected) {
newState[linkId] = true;
} else {
delete newState[linkId];
}
});
return newState;
});
},
[setSelection]
);
const clearSelection = useCallback(() => {
setSelection({});
setLastIndex(undefined);
}, [setSelection]);
const handleSelection = useCallback(
(index: number, { isSelected, isMultiSelect }: HandleSelectionArgs) => {
const item = data[index];
if (isPhotoGroup(item)) {
const groupLinkIds = getGroupLinkIds(data, index);
setSelected(isSelected, ...groupLinkIds);
const lastIndexLinkId = groupLinkIds.shift();
setLastIndex(lastIndexLinkId ? photoLinkIdToIndexMap[lastIndexLinkId] : undefined);
} else {
if (isMultiSelect && lastIndex !== undefined) {
const startIndex = lastIndex < index ? lastIndex : index;
const endIndex = lastIndex < index ? index : lastIndex;
const items = (
data.slice(startIndex, endIndex + 1).filter((item) => !isPhotoGroup(item)) as T[]
).map((item) => item.linkId);
setSelection({});
setSelected(true, ...items);
return;
}
setLastIndex(index);
setSelected(isSelected, item.linkId);
}
},
[data, setSelected, photoLinkIdToIndexMap, lastIndex]
);
const selectedItems = useMemo(
() =>
Object.keys(selection).reduce<T[]>((acc, linkId) => {
const item = data[photoLinkIdToIndexMap[linkId]];
if (item && !isPhotoGroup(item)) {
acc.push(item);
}
return acc;
}, []),
[selection, data, photoLinkIdToIndexMap]
);
const isGroupSelected = useCallback(
(groupIndex: number) => {
let linkIds = getGroupLinkIds(data, groupIndex);
let selectedCount = 0;
for (let linkId of linkIds) {
if (selection[linkId]) {
selectedCount++;
} else if (selectedCount > 0) {
break;
}
}
if (selectedCount === 0) {
return false;
}
return selectedCount === linkIds.length || 'some';
},
[data, selection]
);
const isItemSelected = useCallback((linkId: string) => !!selection[linkId], [selection]);
return {
selectedItems,
setSelected,
clearSelection,
handleSelection,
isGroupSelected,
isItemSelected,
};
};
export default usePhotosSelection;
| 2,941
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos/toolbar/PhotosDownloadButton.tsx
|
import { FC } from 'react';
import { c } from 'ttag';
import { CircleLoader } from '@proton/atoms';
import { Icon, ToolbarButton } from '@proton/components';
import useLoading from '@proton/hooks/useLoading';
import noop from '@proton/utils/noop';
import { PhotoLink } from '../../../../store';
interface Props {
selectedLinks: PhotoLink[];
requestDownload: (linkIds: string[]) => Promise<void>;
}
export const PhotosDownloadButton: FC<Props> = ({ requestDownload, selectedLinks }) => {
const [loading, withLoading] = useLoading();
const onClick = () => {
const linkIds = selectedLinks.map((link) => link.linkId);
withLoading(requestDownload(linkIds)).catch(noop);
};
return (
<ToolbarButton
title={c('Action').t`Download`}
disabled={loading}
icon={loading ? <CircleLoader /> : <Icon name="arrow-down-line" alt={c('Action').t`Download`} />}
onClick={onClick}
data-testid="toolbar-download"
/>
);
};
export default PhotosDownloadButton;
| 2,942
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos/toolbar/PhotosPreviewButton.tsx
|
import { FC } from 'react';
import { c } from 'ttag';
import { Icon, ToolbarButton } from '@proton/components/components';
interface Props {
onClick: () => void;
}
export const PhotosPreviewButton: FC<Props> = ({ onClick }) => {
return (
<ToolbarButton
title={c('Action').t`Preview`}
icon={<Icon name="eye" alt={c('Action').t`Preview`} />}
onClick={onClick}
data-testid="toolbar-preview"
/>
);
};
| 2,943
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos/toolbar/PhotosToolbar.tsx
|
import { FC } from 'react';
import { Vr } from '@proton/atoms/Vr';
import { Toolbar } from '@proton/components';
import { DecryptedLink, PhotoLink } from '../../../../store';
import { MoveToTrashButton } from '../../Drive/ToolbarButtons';
import { DetailsButton, ShareLinkButton } from '../../ToolbarButtons';
import { PhotosDownloadButton } from './PhotosDownloadButton';
import { PhotosPreviewButton } from './PhotosPreviewButton';
import { PhotosUploadButton } from './PhotosUploadButton';
interface Props {
shareId: string;
linkId: string;
selectedItems: PhotoLink[];
onPreview: () => void;
requestDownload: (linkIds: string[]) => Promise<void>;
uploadDisabled: boolean;
}
export const PhotosToolbar: FC<Props> = ({
shareId,
linkId,
selectedItems,
onPreview,
requestDownload,
uploadDisabled,
}) => {
const hasSelection = selectedItems.length > 0;
const hasMultipleSelected = selectedItems.length > 1;
let links = selectedItems as DecryptedLink[];
return (
<Toolbar className="py-1 px-2 toolbar--heavy toolbar--in-container">
<div className="gap-2 flex">
{!uploadDisabled && <PhotosUploadButton shareId={shareId} linkId={linkId} />}
{hasSelection && (
<>
{!uploadDisabled && <Vr />}
{!hasMultipleSelected && <PhotosPreviewButton onClick={onPreview} />}
<PhotosDownloadButton requestDownload={requestDownload} selectedLinks={selectedItems} />
<ShareLinkButton selectedLinks={links} />
<Vr />
<DetailsButton selectedLinks={links} />
<Vr />
<MoveToTrashButton selectedLinks={links} />
</>
)}
</div>
</Toolbar>
);
};
| 2,944
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos/toolbar/PhotosUploadButton.tsx
|
import { FC } from 'react';
import { c } from 'ttag';
import { Icon, ToolbarButton } from '@proton/components/components';
import { PHOTOS_ACCEPTED_INPUT } from '@proton/shared/lib/drive/constants';
import { useFileUploadInput } from '../../../../store';
interface Props {
shareId: string;
linkId: string;
}
export const PhotosUploadButton: FC<Props> = ({ shareId, linkId }) => {
const { inputRef: fileInput, handleClick, handleChange } = useFileUploadInput(shareId, linkId, true);
return (
<>
<input
multiple
type="file"
ref={fileInput}
className="hidden"
onChange={handleChange}
accept={PHOTOS_ACCEPTED_INPUT}
/>
<ToolbarButton
onClick={handleClick}
icon={<Icon name="file-arrow-in-up" alt={c('Action').t`Upload photos`} />}
data-testid="toolbar-photos-upload"
title={c('Action').t`Upload photos`}
/>
</>
);
};
| 2,945
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Photos/toolbar/index.ts
|
export * from './PhotosToolbar';
| 2,946
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Search/NoSearchResultsView.tsx
|
import { FC } from 'react';
import { c } from 'ttag';
import { PrimaryButton } from '@proton/components';
import { DRIVE_APP_NAME } from '@proton/shared/lib/constants';
import noResultSearchSvg from '@proton/styles/assets/img/illustrations/empty-search.svg';
import { useSearchControl } from '../../../store';
import { DriveEmptyView } from '../../layout/DriveEmptyView';
const getTitle = (isReady: boolean) => {
if (isReady) {
// translator: Shown when searching and no results are found
return c('Title').t`No results found`;
}
// translator: Shown when searching and search is not enabled yet
return c('Title').t`Enable drive search`;
};
const getSubtitles = (isReady: boolean) => {
if (isReady) {
return [
// translator: Shown when searching and no results are found
c('Info').t`Try searching by file name, date, or type.`,
// translator: Shown when searching and no results are found
c('Info').t`Also try looking in Trash.`,
];
}
// translator: Shown when searching and search is not enabled yet
return c('Info').t`To enable truly private search ${DRIVE_APP_NAME} needs to index your files locally.`;
};
type Props = {};
export const NoSearchResultsView: FC<Props> = () => {
const { prepareSearchData, hasData, isEnablingEncryptedSearch } = useSearchControl();
const isReady = hasData && !isEnablingEncryptedSearch;
return (
<DriveEmptyView image={noResultSearchSvg} title={getTitle(isReady)} subtitle={getSubtitles(isReady)}>
{!isReady && (
<div className="flex flex-justify-center">
<PrimaryButton
size="large"
className="text-bold"
onClick={() => prepareSearchData()}
loading={isEnablingEncryptedSearch}
disabled={isEnablingEncryptedSearch || hasData}
>
{c('Action').t`Enable drive search`}
</PrimaryButton>
</div>
)}
</DriveEmptyView>
);
};
| 2,947
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Search/Search.tsx
|
import { useCallback, useMemo, useRef } from 'react';
import { c } from 'ttag';
import { useActiveBreakpoint } from '@proton/components';
import useDriveDragMove from '../../../hooks/drive/useDriveDragMove';
import useNavigate from '../../../hooks/drive/useNavigate';
import { EncryptedLink, LinkShareUrl, useSearchView, useThumbnailsDownload } from '../../../store';
import { SortField } from '../../../store/_views/utils/useSorting';
import FileBrowser, { Cells, GridHeader, useItemContextMenu, useSelection } from '../../FileBrowser';
import { BrowserItemId, FileBrowserBaseItem, ListViewHeaderItem } from '../../FileBrowser/interface';
import { GridViewItem } from '../FileBrowser/GridViewItemLink';
import { LocationCell, ModifiedCell, NameCell, SizeCell } from '../FileBrowser/contentCells';
import headerItems from '../FileBrowser/headerCells';
import { translateSortField } from '../SortDropdown';
import { getSelectedItems } from '../helpers';
import { NoSearchResultsView } from './NoSearchResultsView';
import { SearchItemContextMenu } from './SearchItemContextMenu';
export interface SearchItem 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;
rootShareId: string;
}
interface Props {
shareId: string;
searchView: ReturnType<typeof useSearchView>;
}
const { CheckboxCell, ContextMenuCell } = Cells;
const desktopCells: React.FC<{ item: SearchItem }>[] = [
CheckboxCell,
NameCell,
LocationCell,
ModifiedCell,
SizeCell,
ContextMenuCell,
];
const mobileCells = [CheckboxCell, NameCell, ContextMenuCell];
const headerItemsDesktop: ListViewHeaderItem[] = [
headerItems.checkbox,
headerItems.name,
headerItems.location,
headerItems.modificationDate,
headerItems.size,
headerItems.placeholder,
];
const headerItemsMobile: ListViewHeaderItem[] = [headerItems.checkbox, headerItems.name, headerItems.placeholder];
type SearchSortFields = Extract<SortField, SortField.name | SortField.fileModifyTime | SortField.size>;
const SORT_FIELDS: SearchSortFields[] = [SortField.name, SortField.size, SortField.fileModifyTime];
export const Search = ({ shareId, searchView }: Props) => {
const contextMenuAnchorRef = useRef<HTMLDivElement>(null);
const browserItemContextMenu = useItemContextMenu();
const thumbnails = useThumbnailsDownload();
const { navigateToLink } = useNavigate();
const selectionControls = useSelection();
const { isDesktop } = useActiveBreakpoint();
const { layout, items, sortParams, setSorting, isLoading } = searchView;
const selectedItems = useMemo(
() => getSelectedItems(items, selectionControls!.selectedItemIds),
[items, selectionControls!.selectedItemIds]
);
const browserItems: SearchItem[] = 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: SearchItem) => {
if (item.hasThumbnail && item.activeRevision && !item.cachedThumbnailUrl) {
thumbnails.addToDownloadQueue(item.rootShareId, item.id, item.activeRevision.id);
}
};
const handleClick = useCallback(
(id: BrowserItemId) => {
const item = browserItems.find((item) => item.id === id);
if (!item) {
return;
}
document.getSelection()?.removeAllRanges();
navigateToLink(shareId, item.id, item.isFile);
},
[navigateToLink, shareId, browserItems]
);
const Cells = isDesktop ? desktopCells : mobileCells;
const headerItems = isDesktop ? headerItemsDesktop : headerItemsMobile;
if (!items.length && !isLoading) {
return <NoSearchResultsView />;
}
return (
<>
<SearchItemContextMenu
shareId={shareId}
selectedLinks={selectedItems}
anchorRef={contextMenuAnchorRef}
close={browserItemContextMenu.close}
isOpen={browserItemContextMenu.isOpen}
open={browserItemContextMenu.open}
position={browserItemContextMenu.position}
/>
<FileBrowser
// data
caption={c('Title').t`Search results`}
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={browserItemContextMenu.close}
getDragMoveControls={getDragMoveControls}
/>
</>
);
};
| 2,948
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Search/SearchItemContextMenu.tsx
|
import { ContextSeparator } from '@proton/components';
import { DecryptedLink } from '../../../store';
import { ContextMenuProps } from '../../FileBrowser/interface';
import { DriveItemContextMenu } from '../Drive/DriveContextMenu';
import { GoToParent } from './ContextMenuButtons';
export function SearchItemContextMenu(
props: ContextMenuProps & {
shareId: string;
selectedLinks: DecryptedLink[];
}
) {
const { shareId, selectedLinks, close } = props;
const isOnlyOneItem = selectedLinks.length === 1;
return (
<DriveItemContextMenu {...props}>
{isOnlyOneItem && (
<>
<ContextSeparator />
<GoToParent shareId={shareId} parentLinkId={selectedLinks[0].parentLinkId} close={close} />
</>
)}
</DriveItemContextMenu>
);
}
| 2,949
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Search/SearchView.tsx
|
import { useEffect } from 'react';
import { useLocation } from 'react-router';
import { c, msgid } from 'ttag';
// TODO: handle with container
import useActiveShare from '../../../hooks/drive/useActiveShare';
import { useSearchView } from '../../../store';
import { extractSearchParameters } from '../../../store/_search/utils';
import { FileBrowserStateProvider } from '../../FileBrowser';
import DriveToolbar from '../Drive/DriveToolbar';
import ToolbarRow from '../ToolbarRow/ToolbarRow';
import { Search } from './Search';
export function SearchView() {
const { activeFolder, setDefaultRoot } = useActiveShare();
useEffect(setDefaultRoot, []);
const location = useLocation();
const query = extractSearchParameters(location);
const searchView = useSearchView(activeFolder.shareId, query);
return (
<FileBrowserStateProvider itemIds={searchView.items.map(({ linkId }) => linkId)}>
<ToolbarRow
titleArea={
<span className="text-strong pl-1">
{searchView.isLoading
? c('Title').t`Searching…`
: c('Title').ngettext(
msgid`Found ${searchView.numberOfResults} result`,
`Found ${searchView.numberOfResults} results`,
searchView.numberOfResults
)}
</span>
}
toolbar={
<DriveToolbar
shareId={activeFolder.shareId}
linkId={activeFolder.linkId}
items={searchView.items}
showOptionsForNoSelection={false}
/>
}
/>
<Search shareId={activeFolder.shareId} searchView={searchView} />
</FileBrowserStateProvider>
);
}
| 2,950
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Search
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Search/ContextMenuButtons/GoToParent.tsx
|
import { c } from 'ttag';
import useNavigate from '../../../../hooks/drive/useNavigate';
import { ContextMenuButton } from '../../ContextMenu';
interface Props {
shareId: string;
parentLinkId: string;
close: () => void;
}
export default function GoToParent({ shareId, parentLinkId, close }: Props) {
const { navigateToLink } = useNavigate();
return (
<ContextMenuButton
testId="go-to-parent"
icon="folder"
name={c('Action').t`Go to parent`}
action={() => navigateToLink(shareId, parentLinkId, false)}
close={close}
/>
);
}
| 2,951
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Search
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Search/ContextMenuButtons/index.ts
|
export { default as GoToParent } from './GoToParent';
| 2,952
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/SharedLinks/EmptyShared.tsx
|
import { FC } from 'react';
import { c } from 'ttag';
import { PrimaryButton } from '@proton/components';
import noLinksSvg from '@proton/styles/assets/img/illustrations/empty-shared.svg';
import { DriveEmptyView } from '../../layout/DriveEmptyView';
import { useFileSharingModal } from '../../modals/SelectLinkToShareModal/SelectLinkToShareModal';
import { useLinkSharingModal } from '../../modals/ShareLinkModal/ShareLinkModal';
type Props = {
shareId?: string;
};
const EmptyShared: FC<Props> = ({ shareId }) => {
const [fileSharingModal, showFileSharingModal] = useFileSharingModal();
const [linkSharingModal, showLinkSharingModal] = useLinkSharingModal();
const onShareFile = () => {
if (shareId) {
void showFileSharingModal({ shareId, showLinkSharingModal });
}
};
return (
<DriveEmptyView
image={noLinksSvg}
title={
// translator: Shown on empty Shared page
c('Info').t`Share files with links`
}
subtitle={
// translator: Shown on empty Shared page
c('Info').t`Create links and share your files with others.`
}
dataTestId="shared-links-empty-placeholder"
>
<div className="flex flex-justify-center">
<PrimaryButton
size="large"
className="text-bold w-custom"
style={{ '--w-custom': '13em' }}
onClick={onShareFile}
>
{c('Action').t`Share file`}
</PrimaryButton>
</div>
{fileSharingModal}
{linkSharingModal}
</DriveEmptyView>
);
};
export default EmptyShared;
| 2,953
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/SharedLinks/ShareFileSidebarButton.tsx
|
import { c } from 'ttag';
import { FloatingButton, Icon, SidebarPrimaryButton } from '@proton/components';
import useActiveShare from '../../../hooks/drive/useActiveShare';
import { useFileSharingModal } from '../../modals/SelectLinkToShareModal/SelectLinkToShareModal';
import { useLinkSharingModal } from '../../modals/ShareLinkModal/ShareLinkModal';
interface Props {
mobileVersion?: boolean;
}
const ShareFileSidebarButton = ({ mobileVersion }: Props) => {
const { activeShareId } = useActiveShare();
const [fileSharingModal, showFileSharingModal] = useFileSharingModal();
const [linkSharingModal, showLinkSharingModal] = useLinkSharingModal();
const onShareFile = () => {
if (activeShareId) {
void showFileSharingModal({ shareId: activeShareId, showLinkSharingModal });
}
};
return (
<>
{mobileVersion ? (
<FloatingButton onClick={onShareFile} title={c('Action').t`Share item`} disabled={!activeShareId}>
<Icon size={24} name="link" className="m-auto" />
</FloatingButton>
) : (
<SidebarPrimaryButton className="hidden md:flex" disabled={!activeShareId} onClick={onShareFile}>
{c('Action').t`Share item`}
</SidebarPrimaryButton>
)}
{fileSharingModal}
{linkSharingModal}
</>
);
};
export default ShareFileSidebarButton;
| 2,954
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/SharedLinks/SharedLinks.tsx
|
import { useCallback, useMemo, useRef } from 'react';
import { c } from 'ttag';
import { useActiveBreakpoint } from '@proton/components';
import useNavigate from '../../../hooks/drive/useNavigate';
import { EncryptedLink, LinkShareUrl, useSharedLinksView, useThumbnailsDownload } from '../../../store';
import { SortField } from '../../../store/_views/utils/useSorting';
import FileBrowser, {
BrowserItemId,
Cells,
FileBrowserBaseItem,
GridHeader,
ListViewHeaderItem,
useItemContextMenu,
useSelection,
} from '../../FileBrowser';
import { GridViewItem } from '../FileBrowser/GridViewItemLink';
import { AccessCountCell, CreatedCell, ExpirationCell, LocationCell, NameCell } from '../FileBrowser/contentCells';
import headerItems from '../FileBrowser/headerCells';
import { translateSortField } from '../SortDropdown';
import { getSelectedItems } from '../helpers';
import EmptyShared from './EmptyShared';
import { SharedLinksItemContextMenu } from './SharedLinksItemContextMenu';
export interface SharedLinkItem 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;
rootShareId: string;
}
type Props = {
shareId: string;
sharedLinksView: ReturnType<typeof useSharedLinksView>;
};
const { CheckboxCell, ContextMenuCell } = Cells;
const desktopCells: React.FC<{ item: SharedLinkItem }>[] = [
CheckboxCell,
NameCell,
LocationCell,
CreatedCell,
AccessCountCell,
ExpirationCell,
ContextMenuCell,
];
const mobileCells = [CheckboxCell, NameCell, LocationCell, ExpirationCell, ContextMenuCell];
const headerItemsDesktop: ListViewHeaderItem[] = [
headerItems.checkbox,
headerItems.name,
headerItems.location,
headerItems.creationDate,
headerItems.accessCount,
headerItems.expirationDate,
headerItems.placeholder,
];
const headeItemsMobile: ListViewHeaderItem[] = [
headerItems.checkbox,
headerItems.name,
headerItems.location,
headerItems.expirationDate,
headerItems.placeholder,
];
type SharedLinksSortFields = Extract<
SortField,
SortField.name | SortField.linkCreateTime | SortField.linkExpireTime | SortField.numAccesses
>;
const SORT_FIELDS: SharedLinksSortFields[] = [
SortField.name,
SortField.linkCreateTime,
SortField.linkExpireTime,
SortField.numAccesses,
];
const SharedLinks = ({ shareId, sharedLinksView }: Props) => {
const contextMenuAnchorRef = useRef<HTMLDivElement>(null);
const { navigateToLink } = useNavigate();
const browserItemContextMenu = useItemContextMenu();
const thumbnails = useThumbnailsDownload();
const selectionControls = useSelection();
const { isDesktop } = useActiveBreakpoint();
const { layout, items, sortParams, setSorting, isLoading } = sharedLinksView;
const selectedItems = useMemo(
() => getSelectedItems(items, selectionControls!.selectedItemIds),
[items, selectionControls!.selectedItemIds]
);
const browserItems: SharedLinkItem[] = items.map((item) => ({ ...item, id: item.linkId }));
const handleClick = useCallback(
(id: BrowserItemId) => {
const item = browserItems.find((item) => item.id === id);
if (!item) {
return;
}
document.getSelection()?.removeAllRanges();
navigateToLink(item.rootShareId, item.id, item.isFile);
},
[navigateToLink, shareId, browserItems]
);
const handleItemRender = (item: SharedLinkItem) => {
if (item.hasThumbnail && item.activeRevision && !item.cachedThumbnailUrl) {
thumbnails.addToDownloadQueue(item.rootShareId, item.id, item.activeRevision.id);
}
};
/* 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]
);
if (!items.length && !isLoading) {
return <EmptyShared shareId={shareId} />;
}
const Cells = isDesktop ? desktopCells : mobileCells;
const headerItems = isDesktop ? headerItemsDesktop : headeItemsMobile;
return (
<>
<SharedLinksItemContextMenu
selectedLinks={selectedItems}
anchorRef={contextMenuAnchorRef}
close={browserItemContextMenu.close}
isOpen={browserItemContextMenu.isOpen}
open={browserItemContextMenu.open}
position={browserItemContextMenu.position}
/>
<FileBrowser
caption={c('Title').t`Shared`}
items={browserItems}
headerItems={headerItems}
layout={layout}
loading={isLoading}
sortParams={sortParams}
Cells={Cells}
GridHeaderComponent={GridHeaderComponent}
GridViewItem={GridViewItem}
contextMenuAnchorRef={contextMenuAnchorRef}
onItemContextMenu={browserItemContextMenu.handleContextMenu}
onItemOpen={handleClick}
onItemRender={handleItemRender}
onSort={setSorting}
onScroll={browserItemContextMenu.close}
/>
</>
);
};
export default SharedLinks;
| 2,955
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/SharedLinks/SharedLinksItemContextMenu.tsx
|
import { isPreviewAvailable } from '@proton/shared/lib/helpers/preview';
import { DecryptedLink, useActions } from '../../../store';
import { ContextMenuProps } from '../../FileBrowser';
import { useDetailsModal } from '../../modals/DetailsModal';
import { useFilesDetailsModal } from '../../modals/FilesDetailsModal';
import { useRenameModal } from '../../modals/RenameModal';
import { useLinkSharingModal } from '../../modals/ShareLinkModal/ShareLinkModal';
import { DetailsButton, DownloadButton, PreviewButton, RenameButton, ShareLinkButton } from '../ContextMenu';
import { ItemContextMenu } from '../ContextMenu/ItemContextMenu';
import { StopSharingButton } from './ContextMenuButtons';
export function SharedLinksItemContextMenu({
selectedLinks,
anchorRef,
isOpen,
position,
open,
close,
}: ContextMenuProps & {
selectedLinks: DecryptedLink[];
}) {
const selectedLink = selectedLinks[0];
const isOnlyOneItem = selectedLinks.length === 1;
const hasPreviewAvailable =
isOnlyOneItem &&
selectedLink.isFile &&
selectedLink.mimeType &&
isPreviewAvailable(selectedLink.mimeType, selectedLink.size);
const { stopSharingLinks, confirmModal } = useActions();
const [renameModal, showRenameModal] = useRenameModal();
const [detailsModal, showDetailsModal] = useDetailsModal();
const [filesDetailsModal, showFilesDetailsModal] = useFilesDetailsModal();
const [linkSharingModal, showLinkSharingModal] = useLinkSharingModal();
return (
<>
<ItemContextMenu isOpen={isOpen} open={open} close={close} position={position} anchorRef={anchorRef}>
{hasPreviewAvailable && (
<PreviewButton shareId={selectedLink.rootShareId} linkId={selectedLink.linkId} close={close} />
)}
{<DownloadButton selectedLinks={selectedLinks} close={close} />}
{isOnlyOneItem && <RenameButton showRenameModal={showRenameModal} link={selectedLink} close={close} />}
<DetailsButton
selectedLinks={selectedLinks}
showDetailsModal={showDetailsModal}
showFilesDetailsModal={showFilesDetailsModal}
close={close}
/>
{isOnlyOneItem && (
<ShareLinkButton
shareId={selectedLink.rootShareId}
showLinkSharingModal={showLinkSharingModal}
link={selectedLink}
close={close}
/>
)}
<StopSharingButton selectedLinks={selectedLinks} stopSharingLinks={stopSharingLinks} close={close} />
</ItemContextMenu>
{renameModal}
{detailsModal}
{filesDetailsModal}
{linkSharingModal}
{confirmModal}
</>
);
}
| 2,956
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/SharedLinks/SharedLinksToolbar.tsx
|
import { useMemo } from 'react';
import { Vr } from '@proton/atoms';
import { Toolbar } from '@proton/components';
import { DecryptedLink } from '../../../store';
import { useSelection } from '../../FileBrowser';
import {
DetailsButton,
DownloadButton,
LayoutButton,
PreviewButton,
RenameButton,
ShareButton,
ShareLinkButton,
} from '../ToolbarButtons';
import { getSelectedItems } from '../helpers';
import { StopSharingButton } from './ToolbarButtons';
interface Props {
shareId: string;
items: DecryptedLink[];
}
const SharedLinksToolbar = ({ shareId, items }: Props) => {
const selectionControls = useSelection()!;
const selectedItems = useMemo(
() => getSelectedItems(items, selectionControls!.selectedItemIds),
[items, selectionControls!.selectedItemIds]
);
const renderSelectionActions = () => {
if (!selectedItems.length) {
return (
<>
<ShareButton shareId={shareId} />
</>
);
}
return (
<>
<PreviewButton selectedLinks={selectedItems} />
<DownloadButton selectedLinks={selectedItems} />
<Vr />
<RenameButton selectedLinks={selectedItems} />
<DetailsButton selectedLinks={selectedItems} />
<Vr />
<ShareLinkButton selectedLinks={selectedItems} />
<StopSharingButton selectedLinks={selectedItems} />
</>
);
};
return (
<Toolbar className="py-1 px-2 toolbar--heavy toolbar--in-container">
<div className="gap-2 flex flex-nowrap flex-item-noshrink">{renderSelectionActions()}</div>
<span className="ml-auto flex flex-nowrap flex-item-noshrink">
<Vr className="hidden lg:flex mx-2" />
<LayoutButton />
</span>
</Toolbar>
);
};
export default SharedLinksToolbar;
| 2,957
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/SharedLinks/SharedLinksView.tsx
|
import { useEffect } from 'react';
import { c } from 'ttag';
import { useAppTitle } from '@proton/components';
import useActiveShare from '../../../hooks/drive/useActiveShare';
import { useSharedLinksView } from '../../../store';
import { FileBrowserStateProvider } from '../../FileBrowser';
import ToolbarRow from '../ToolbarRow/ToolbarRow';
import SharedLinks from './SharedLinks';
import SharedLinksToolbar from './SharedLinksToolbar';
const SharedLinksView = () => {
useAppTitle(c('Title').t`Shared`);
const { activeShareId, setDefaultRoot } = useActiveShare();
useEffect(setDefaultRoot, []);
const sharedLinksView = useSharedLinksView(activeShareId);
return (
<FileBrowserStateProvider itemIds={sharedLinksView.items.map(({ linkId }) => linkId)}>
<ToolbarRow
titleArea={<span className="text-strong pl-1">{c('Info').t`My Links`}</span>}
toolbar={<SharedLinksToolbar shareId={activeShareId} items={sharedLinksView.items} />}
/>
<SharedLinks shareId={activeShareId} sharedLinksView={sharedLinksView} />
</FileBrowserStateProvider>
);
};
export default SharedLinksView;
| 2,958
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/SharedLinks
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/SharedLinks/ContextMenuButtons/StopSharingButton.tsx
|
import { c } from 'ttag';
import { DecryptedLink, useActions } from '../../../../store';
import { ContextMenuButton } from '../../ContextMenu';
interface Props {
selectedLinks: DecryptedLink[];
stopSharingLinks: ReturnType<typeof useActions>['stopSharingLinks'];
close: () => void;
}
const StopSharingButton = ({ selectedLinks, stopSharingLinks, close }: Props) => {
return (
<ContextMenuButton
name={c('Action').t`Stop sharing`}
icon="link-slash"
testId="context-menu-stop-sharing"
action={() => stopSharingLinks(new AbortController().signal, selectedLinks)}
close={close}
/>
);
};
export default StopSharingButton;
| 2,959
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/SharedLinks
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/SharedLinks/ContextMenuButtons/index.ts
|
export { default as StopSharingButton } from './StopSharingButton';
| 2,960
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/SharedLinks
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/SharedLinks/ToolbarButtons/StopSharingButton.tsx
|
import { c } from 'ttag';
import { Icon, ToolbarButton } from '@proton/components';
import { DecryptedLink, useActions } from '../../../../store';
import { noSelection } from '../../ToolbarButtons/utils';
interface Props {
selectedLinks: DecryptedLink[];
}
const StopSharingButton = ({ selectedLinks }: Props) => {
const { stopSharingLinks, confirmModal } = useActions();
if (noSelection(selectedLinks)) {
return null;
}
return (
<>
<ToolbarButton
title={c('Action').t`Stop sharing`}
icon={<Icon name="link-slash" />}
onClick={() => stopSharingLinks(new AbortController().signal, selectedLinks)}
data-testid="toolbar-button-stop-sharing"
/>
{confirmModal}
</>
);
};
export default StopSharingButton;
| 2,961
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/SharedLinks
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/SharedLinks/ToolbarButtons/index.ts
|
export { default as StopSharingButton } from './StopSharingButton';
| 2,962
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/ToolbarButtons/DesktopDownloadDropdown.tsx
|
import { c } from 'ttag';
import { CircleLoader } from '@proton/atoms/CircleLoader';
import {
Dropdown,
DropdownButton,
DropdownMenu,
DropdownMenuButton,
DropdownSizeUnit,
Icon,
usePopperAnchor,
} from '@proton/components';
import useDesktopDownloads from '../../../hooks/drive/useDesktopDownloads';
interface Props {
className?: string;
}
const DesktopDownloadDropdown = ({ className }: Props) => {
const { anchorRef, isOpen, toggle, close } = usePopperAnchor<HTMLButtonElement>();
const { isLoading, downloads } = useDesktopDownloads();
return (
<>
<DropdownButton
ref={anchorRef}
isOpen={isOpen}
onClick={toggle}
hasCaret
shape="ghost"
size="small"
className={className}
>
{c('Action').t`Download apps`}
</DropdownButton>
<Dropdown
isOpen={isOpen}
anchorRef={anchorRef}
onClose={close}
size={{
width: DropdownSizeUnit.Anchor,
}}
>
<DropdownMenu>
{isLoading ? (
<CircleLoader className="w-full flex flex-align-items-center my-2" />
) : (
downloads.map(({ platform, icon, name, url, startDownload }) => (
<DropdownMenuButton
className="text-left flex flex-align-items-center"
key={platform}
disabled={!url}
onClick={startDownload}
>
<Icon name={icon} className="color-weak mr-2" />
{name}
</DropdownMenuButton>
))
)}
</DropdownMenu>
</Dropdown>
</>
);
};
export default DesktopDownloadDropdown;
| 2,963
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/ToolbarButtons/DetailsButton.tsx
|
import { c } from 'ttag';
import { Icon, ToolbarButton } from '@proton/components';
import { DecryptedLink } from '../../../store';
import { useDetailsModal } from '../../modals/DetailsModal';
import { useFilesDetailsModal } from '../../modals/FilesDetailsModal';
import { noSelection } from './utils';
interface Props {
selectedLinks: DecryptedLink[];
}
const DetailsButton = ({ selectedLinks }: Props) => {
const [filesDetailsModal, showFilesDetailsModal] = useFilesDetailsModal();
const [detailsModal, showDetailsModal] = useDetailsModal();
if (noSelection(selectedLinks)) {
return null;
}
return (
<>
<ToolbarButton
title={c('Action').t`Details`}
icon={<Icon name="info-circle" alt={c('Action').t`Details`} />}
onClick={() => {
if (selectedLinks.length === 1) {
void showDetailsModal({
shareId: selectedLinks[0].rootShareId,
linkId: selectedLinks[0].linkId,
});
} else if (selectedLinks.length > 1) {
void showFilesDetailsModal({ selectedItems: selectedLinks });
}
}}
data-testid="toolbar-details"
/>
{detailsModal}
{filesDetailsModal}
</>
);
};
export default DetailsButton;
| 2,964
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/ToolbarButtons/DownloadButton.tsx
|
import { c } from 'ttag';
import { Icon, ToolbarButton } from '@proton/components';
import { DecryptedLink, useDownload } from '../../../store';
import { hasFoldersSelected, noSelection } from './utils';
interface Props {
selectedLinks: DecryptedLink[];
disabledFolders?: boolean;
}
const DownloadButton = ({ selectedLinks, disabledFolders }: Props) => {
const { download } = useDownload();
const onClick = () => {
void download(
selectedLinks.map((link) => ({
...link,
shareId: link.rootShareId,
}))
);
};
if (noSelection(selectedLinks) || (disabledFolders && hasFoldersSelected(selectedLinks))) {
return null;
}
return (
<ToolbarButton
title={c('Action').t`Download`}
icon={<Icon name="arrow-down-line" alt={c('Action').t`Download`} />}
onClick={onClick}
data-testid="toolbar-download"
/>
);
};
export default DownloadButton;
| 2,965
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/ToolbarButtons/LayoutButton.tsx
|
import { c } from 'ttag';
import { Icon, ToolbarButton, useNotifications } from '@proton/components';
import { LayoutSetting } from '@proton/shared/lib/interfaces/drive/userSettings';
import { useUserSettings } from '../../../store';
const LayoutButton = () => {
const { createNotification } = useNotifications();
const { layout, changeLayout } = useUserSettings();
const handleClick = (e: any) => {
void changeLayout(layout === LayoutSetting.Grid ? LayoutSetting.List : LayoutSetting.Grid);
// Show notification after ten clicks.
if (e.detail === 10) {
createNotification({
type: 'info',
text: 'To list, or not to grid',
});
}
};
return (
<ToolbarButton
onClick={handleClick}
icon={
<Icon
name={layout === LayoutSetting.Grid ? 'list-bullets' : 'grid-3'}
alt={layout === LayoutSetting.Grid ? c('Action').t`Grid layout` : 'List layout'}
/>
}
data-testid="toolbar-layout"
title={c('Title').t`Change layout`}
/>
);
};
export default LayoutButton;
| 2,966
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/ToolbarButtons/PreviewButton.tsx
|
import { c } from 'ttag';
import { Icon, ToolbarButton } from '@proton/components';
import { isPreviewAvailable } from '@proton/shared/lib/helpers/preview';
import { DecryptedLink } from '../../../store';
import useOpenPreview from '../../useOpenPreview';
import { hasFoldersSelected, isMultiSelect } from './utils';
interface Props {
selectedLinks: DecryptedLink[];
}
const PreviewButton = ({ selectedLinks }: Props) => {
const openPreview = useOpenPreview();
const disabled =
isMultiSelect(selectedLinks) ||
hasFoldersSelected(selectedLinks) ||
!selectedLinks[0]?.mimeType ||
!isPreviewAvailable(selectedLinks[0].mimeType, selectedLinks[0].size);
if (disabled) {
return null;
}
return (
<ToolbarButton
title={c('Action').t`Preview`}
icon={<Icon name="eye" alt={c('Action').t`Preview`} />}
onClick={() => {
if (selectedLinks.length) {
openPreview(selectedLinks[0].rootShareId, selectedLinks[0].linkId);
}
}}
data-testid="toolbar-preview"
/>
);
};
export default PreviewButton;
| 2,967
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/ToolbarButtons/RenameButton.tsx
|
import { c } from 'ttag';
import { Icon, ToolbarButton } from '@proton/components';
import { DecryptedLink } from '../../../store';
import { useRenameModal } from '../../modals/RenameModal';
import { isMultiSelect, noSelection } from './utils';
interface Props {
selectedLinks: DecryptedLink[];
}
const RenameButton = ({ selectedLinks }: Props) => {
const [renameModal, showRenameModal] = useRenameModal();
if (noSelection(selectedLinks) || isMultiSelect(selectedLinks)) {
return null;
}
return (
<>
<ToolbarButton
title={c('Action').t`Rename`}
icon={<Icon name="pen-square" alt={c('Action').t`Rename`} />}
onClick={() => showRenameModal({ item: selectedLinks[0] })}
data-testid="toolbar-rename"
/>
{renameModal}
</>
);
};
export default RenameButton;
| 2,968
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/ToolbarButtons/ShareButton.tsx
|
import { c } from 'ttag';
import { Icon, ToolbarButton } from '@proton/components';
import { useFileSharingModal } from '../../modals/SelectLinkToShareModal/SelectLinkToShareModal';
import { useLinkSharingModal } from '../../modals/ShareLinkModal/ShareLinkModal';
interface Props {
shareId: string;
}
const ShareButton = ({ shareId }: Props) => {
const [fileSharingModal, showFileSharingModal] = useFileSharingModal();
const [linkSharingModal, showLinkSharingModal] = useLinkSharingModal();
return (
<>
<ToolbarButton
title={c('Action').t`Get link`}
icon={<Icon name="link" alt={c('Action').t`Get link`} />}
onClick={() => {
void showFileSharingModal({ shareId, showLinkSharingModal });
}}
data-testid="toolbar-share-via-link"
/>
{fileSharingModal}
{linkSharingModal}
</>
);
};
export default ShareButton;
| 2,969
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/ToolbarButtons/ShareLinkButton.tsx
|
import { c } from 'ttag';
import { Icon, ToolbarButton } from '@proton/components';
import { DecryptedLink } from '../../../store';
import { useLinkSharingModal } from '../../modals/ShareLinkModal/ShareLinkModal';
import { isMultiSelect, noSelection } from './utils';
interface Props {
selectedLinks: DecryptedLink[];
}
const ShareLinkButton = ({ selectedLinks }: Props) => {
const [linkSharingModal, showLinkSharingModal] = useLinkSharingModal();
if (noSelection(selectedLinks) || isMultiSelect(selectedLinks)) {
return null;
}
const hasSharedLink = !!selectedLinks[0]?.shareUrl;
return (
<>
<ToolbarButton
disabled={noSelection(selectedLinks) || isMultiSelect(selectedLinks)}
title={hasSharedLink ? c('Action').t`Manage link` : c('Action').t`Get link`}
icon={
<Icon
name={hasSharedLink ? 'link-pen' : 'link'}
alt={hasSharedLink ? c('Action').t`Manage link` : c('Action').t`Get link`}
/>
}
onClick={() =>
showLinkSharingModal({ shareId: selectedLinks[0].rootShareId, linkId: selectedLinks[0].linkId })
}
data-testid="toolbar-share-link"
/>
{linkSharingModal}
</>
);
};
export default ShareLinkButton;
| 2,970
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/ToolbarButtons/index.ts
|
export { default as DetailsButton } from './DetailsButton';
export { default as DownloadButton } from './DownloadButton';
export { default as LayoutButton } from './LayoutButton';
export { default as PreviewButton } from './PreviewButton';
export { default as RenameButton } from './RenameButton';
export { default as ShareButton } from './ShareButton';
export { default as ShareLinkButton } from './ShareLinkButton';
| 2,971
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/ToolbarButtons/utils.ts
|
export function noSelection(selectedItems: any[]): boolean {
return selectedItems.length === 0;
}
export function isMultiSelect(selectedItems: any[]): boolean {
return selectedItems.length > 1;
}
export function hasFoldersSelected(selectedItems: { isFile: boolean }[]): boolean {
return selectedItems.some((item) => !item.isFile);
}
| 2,972
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/ToolbarRow/ToolbarRow.scss
|
@import '~@proton/styles/scss/lib';
.toolbar-row {
flex-direction: column;
@include media('>medium') {
flex-direction: row-reverse;
justify-content: space-between;
}
&-toolbar {
min-block-size: rem(44);
border-block-end: 1px solid var(--border-weak);
@include media('>medium') {
border-block-end: none;
}
}
&-titleArea {
min-block-size: rem(36);
}
}
| 2,973
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/ToolbarRow/ToolbarRow.tsx
|
import { ReactNode } from 'react';
import './ToolbarRow.scss';
interface Props {
titleArea: ReactNode;
toolbar: ReactNode;
}
const ToolbarRow = ({ titleArea, toolbar }: Props) => {
return (
<div className="toolbar-row flex flex-nowrap w-full border-bottom border-weak flex-item-noshrink">
<div className="toolbar-row-toolbar flex-item-noshrink">{toolbar}</div>
<div className="toolbar-row-titleArea flex flex-align-items-center pl-3 pr-1">{titleArea}</div>
</div>
);
};
export default ToolbarRow;
| 2,974
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Trash/EmptyTrash.tsx
|
import { FC } from 'react';
import { c } from 'ttag';
import noContentSvg from '@proton/styles/assets/img/illustrations/empty-trash.svg';
import { DriveEmptyView } from '../../layout/DriveEmptyView';
type Props = {};
const EmptyTrash: FC<Props> = () => {
return (
<DriveEmptyView
image={noContentSvg}
title={
// translator: Shown on empty Trash page
c('Info').t`Trash is empty`
}
subtitle={
// translator: Shown on empty Trash page
c('Info').t`Items moved to the trash will stay here until deleted`
}
/>
);
};
export default EmptyTrash;
| 2,975
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Trash/Trash.tsx
|
import { useCallback, useMemo, useRef } from 'react';
import { c } from 'ttag';
import { useActiveBreakpoint } from '@proton/components';
import useNavigate from '../../../hooks/drive/useNavigate';
import { EncryptedLink, LinkShareUrl, useThumbnailsDownload } from '../../../store';
import { useTrashView } from '../../../store';
import { SortField } from '../../../store/_views/utils/useSorting';
import FileBrowser, { Cells, GridHeader, useItemContextMenu, useSelection } from '../../FileBrowser';
import { BrowserItemId, FileBrowserBaseItem, ListViewHeaderItem } from '../../FileBrowser/interface';
import { GridViewItem } from '../FileBrowser/GridViewItemLink';
import { DeletedCell, LocationCell, NameCell, SizeCell } from '../FileBrowser/contentCells';
import headerItems from '../FileBrowser/headerCells';
import { translateSortField } from '../SortDropdown';
import { getSelectedItems } from '../helpers';
import EmptyTrash from './EmptyTrash';
import { TrashItemContextMenu } from './TrashItemContextMenu';
export interface TrashItem 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;
rootShareId: string;
}
interface Props {
shareId: string;
trashView: ReturnType<typeof useTrashView>;
}
const { CheckboxCell, ContextMenuCell } = Cells;
const desktopCells: React.FC<{ item: TrashItem }>[] = [
CheckboxCell,
NameCell,
LocationCell,
DeletedCell,
SizeCell,
ContextMenuCell,
];
const mobileCells = [CheckboxCell, NameCell, LocationCell, SizeCell, ContextMenuCell];
const headerItemsDesktop: ListViewHeaderItem[] = [
headerItems.checkbox,
headerItems.name,
headerItems.location,
headerItems.trashed,
headerItems.size,
headerItems.placeholder,
];
const headeItemsMobile: ListViewHeaderItem[] = [
headerItems.checkbox,
headerItems.name,
headerItems.location,
headerItems.size,
headerItems.placeholder,
];
type TrashSortFields = Extract<SortField, SortField.name | SortField.size | SortField.trashed>;
const SORT_FIELDS: TrashSortFields[] = [SortField.name, SortField.trashed, SortField.size];
function Trash({ trashView }: Props) {
const contextMenuAnchorRef = useRef<HTMLDivElement>(null);
const { navigateToLink } = useNavigate();
const browserItemContextMenu = useItemContextMenu();
const thumbnails = useThumbnailsDownload();
const selectionControls = useSelection();
const { isDesktop } = useActiveBreakpoint();
const { layout, items, sortParams, setSorting, isLoading } = trashView;
const selectedItems = useMemo(
() => getSelectedItems(items, selectionControls!.selectedItemIds),
[items, selectionControls!.selectedItemIds]
);
const browserItems: TrashItem[] = items.map((item) => ({ ...item, id: item.linkId }));
const handleClick = useCallback(
(id: BrowserItemId) => {
const item = browserItems.find((item) => item.id === id);
if (!item) {
return;
}
document.getSelection()?.removeAllRanges();
if (!item.isFile) {
return;
}
navigateToLink(item.rootShareId, id, item.isFile);
},
[navigateToLink, browserItems]
);
const handleItemRender = (item: TrashItem) => {
if (item.hasThumbnail && item.activeRevision && !item.cachedThumbnailUrl) {
thumbnails.addToDownloadQueue(item.rootShareId, item.id, item.activeRevision.id);
}
};
/* 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]
);
if (!items.length && !isLoading) {
return <EmptyTrash />;
}
const Cells = isDesktop ? desktopCells : mobileCells;
const headerItems = isDesktop ? headerItemsDesktop : headeItemsMobile;
return (
<>
<TrashItemContextMenu
selectedLinks={selectedItems}
anchorRef={contextMenuAnchorRef}
close={browserItemContextMenu.close}
isOpen={browserItemContextMenu.isOpen}
open={browserItemContextMenu.open}
position={browserItemContextMenu.position}
/>
<FileBrowser
caption={c('Title').t`Trash`}
items={browserItems}
headerItems={headerItems}
layout={layout}
loading={isLoading}
sortParams={sortParams}
Cells={Cells}
GridHeaderComponent={GridHeaderComponent}
GridViewItem={GridViewItem}
onItemOpen={handleClick}
contextMenuAnchorRef={contextMenuAnchorRef}
onItemContextMenu={browserItemContextMenu.handleContextMenu}
onItemRender={handleItemRender}
onSort={setSorting}
onScroll={browserItemContextMenu.close}
/>
</>
);
}
export default Trash;
| 2,976
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Trash/TrashItemContextMenu.tsx
|
import { isPreviewAvailable } from '@proton/shared/lib/helpers/preview';
import { DecryptedLink, useActions } from '../../../store';
import { ContextMenuProps } from '../../FileBrowser';
import { useDetailsModal } from '../../modals/DetailsModal';
import { useFilesDetailsModal } from '../../modals/FilesDetailsModal';
import { DetailsButton, DownloadButton, PreviewButton } from '../ContextMenu';
import { ItemContextMenu } from '../ContextMenu/ItemContextMenu';
import { DeletePermanentlyButton, RestoreFromTrashButton } from './ContextMenuButtons';
export function TrashItemContextMenu({
selectedLinks,
anchorRef,
isOpen,
position,
open,
close,
}: ContextMenuProps & {
selectedLinks: DecryptedLink[];
}) {
const selectedLink = selectedLinks[0];
const hasPreviewAvailable =
selectedLinks.length === 1 &&
selectedLink.isFile &&
selectedLink.mimeType &&
isPreviewAvailable(selectedLink.mimeType, selectedLink.size);
const hasDownloadAvailable = !selectedLinks.some((item) => !item.isFile);
const [detailsModal, showDetailsModal] = useDetailsModal();
const [filesDetailsModal, showFilesDetailsModal] = useFilesDetailsModal();
const { deletePermanently, restoreLinks, confirmModal } = useActions();
return (
<>
<ItemContextMenu isOpen={isOpen} open={open} close={close} position={position} anchorRef={anchorRef}>
{hasPreviewAvailable && (
<PreviewButton shareId={selectedLink.rootShareId} linkId={selectedLink.linkId} close={close} />
)}
{hasDownloadAvailable && <DownloadButton selectedLinks={selectedLinks} close={close} />}
<DetailsButton
selectedLinks={selectedLinks}
showDetailsModal={showDetailsModal}
showFilesDetailsModal={showFilesDetailsModal}
close={close}
/>
<RestoreFromTrashButton restoreLinks={restoreLinks} selectedLinks={selectedLinks} close={close} />
<DeletePermanentlyButton
selectedLinks={selectedLinks}
deletePermanently={deletePermanently}
close={close}
/>
</ItemContextMenu>
{detailsModal}
{filesDetailsModal}
{confirmModal}
</>
);
}
| 2,977
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Trash/TrashToolbar.tsx
|
import { useMemo } from 'react';
import { Vr } from '@proton/atoms';
import { Toolbar } from '@proton/components';
import { DecryptedLink } from '../../../store';
import { useSelection } from '../../FileBrowser';
import { DetailsButton, DownloadButton, LayoutButton, PreviewButton } from '../ToolbarButtons';
import { getSelectedItems } from '../helpers';
import { DeletePermanentlyButton, RestoreFromTrashButton } from './ToolbarButtons';
interface Props {
items: DecryptedLink[];
}
const TrashToolbar = ({ items }: Props) => {
const selectionControls = useSelection()!;
const selectedItems = useMemo(
() => getSelectedItems(items, selectionControls!.selectedItemIds),
[items, selectionControls!.selectedItemIds]
);
const renderSelectionActions = () => {
if (!selectedItems.length) {
return null;
}
return (
<>
<PreviewButton selectedLinks={selectedItems} />
<DownloadButton selectedLinks={selectedItems} disabledFolders />
<Vr className="section-toolbar--hide-alone" />
<DetailsButton selectedLinks={selectedItems} />
<Vr />
<RestoreFromTrashButton selectedLinks={selectedItems} />
<DeletePermanentlyButton selectedLinks={selectedItems} />
</>
);
};
return (
<Toolbar className="py-1 px-2 toolbar--heavy toolbar--in-container">
<div className="gap-2 flex flex-nowrap flex-item-noshrink">{renderSelectionActions()}</div>
<span className="ml-auto flex flex-nowrap flex-item-noshrink">
{selectedItems.length > 0 && <Vr className="hidden lg:flex mx-2" />}
<LayoutButton />
</span>
</Toolbar>
);
};
export default TrashToolbar;
| 2,978
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Trash/TrashView.tsx
|
import { useEffect } from 'react';
import { c } from 'ttag';
import { useAppTitle } from '@proton/components';
import useActiveShare from '../../../hooks/drive/useActiveShare';
import { useTrashView } from '../../../store';
import { FileBrowserStateProvider } from '../../FileBrowser';
import ToolbarRow from '../ToolbarRow/ToolbarRow';
import EmptyTrashNotification from './EmptyTrashNotification';
import Trash from './Trash';
import TrashToolbar from './TrashToolbar';
const TrashView = () => {
useAppTitle(c('Title').t`Trash`);
const { activeShareId, setDefaultRoot } = useActiveShare();
useEffect(setDefaultRoot, []);
const trashView = useTrashView();
return (
<FileBrowserStateProvider itemIds={trashView.items.map(({ linkId }) => linkId)}>
<ToolbarRow
titleArea={<span className="text-strong pl-1">{c('Info').t`Trash`}</span>}
toolbar={<TrashToolbar items={trashView.items} />}
/>
<EmptyTrashNotification className="border-bottom border-weak" disabled={trashView.items.length === 0} />
<Trash shareId={activeShareId} trashView={trashView} />
</FileBrowserStateProvider>
);
};
export default TrashView;
| 2,979
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Trash
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Trash/ContextMenuButtons/DeletePermanentlyButton.tsx
|
import { c } from 'ttag';
import { DecryptedLink, useActions } from '../../../../store';
import { ContextMenuButton } from '../../ContextMenu';
interface Props {
selectedLinks: DecryptedLink[];
deletePermanently: ReturnType<typeof useActions>['deletePermanently'];
close: () => void;
}
const DeletePermanentlyButton = ({ selectedLinks, deletePermanently, close }: Props) => {
return (
<ContextMenuButton
name={c('Action').t`Delete permanently`}
icon="cross-circle"
testId="context-menu-delete"
action={() => deletePermanently(new AbortController().signal, selectedLinks)}
close={close}
/>
);
};
export default DeletePermanentlyButton;
| 2,980
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Trash
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Trash/ContextMenuButtons/RestoreFromTrashButton.tsx
|
import { c } from 'ttag';
import { DecryptedLink, useActions } from '../../../../store';
import { ContextMenuButton } from '../../ContextMenu';
interface Props {
selectedLinks: DecryptedLink[];
restoreLinks: ReturnType<typeof useActions>['restoreLinks'];
close: () => void;
}
const RestoreFromTrashButton = ({ selectedLinks, restoreLinks, close }: Props) => {
return (
<ContextMenuButton
name={c('Action').t`Restore from trash`}
icon="arrow-rotate-right"
testId="context-menu-restore"
action={() => restoreLinks(new AbortController().signal, selectedLinks)}
close={close}
/>
);
};
export default RestoreFromTrashButton;
| 2,981
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Trash
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Trash/ContextMenuButtons/index.ts
|
export { default as DeletePermanentlyButton } from './DeletePermanentlyButton';
export { default as RestoreFromTrashButton } from './RestoreFromTrashButton';
| 2,982
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Trash
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Trash/EmptyTrashNotification/EmptyTrashNotification.scss
|
.empty-trash-notification {
background-color: var(--signal-info-minor-2); // This color is not available as class at the moment
}
| 2,983
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Trash
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Trash/EmptyTrashNotification/EmptyTrashNotification.tsx
|
import { c } from 'ttag';
import { Button } from '@proton/atoms/Button';
import clsx from '@proton/utils/clsx';
import { useActions } from '../../../../store';
interface Props {
disabled?: boolean;
className?: string;
}
const EmptyTrashNotification = ({ disabled, className }: Props) => {
const { emptyTrash, confirmModal } = useActions();
const handleEmptyTrashClick = () => {
void emptyTrash(new AbortController().signal);
};
return (
<>
<div
className={clsx(
className,
'empty-trash-notification section--header flex flex-align-items-center flex-item-noshrink on-mobile-flex-column px-4 py-2'
)}
>
<p className="m-0 flex-item-fluid text-sm py-2">
{c('Info').t`Items in the trash will stay here until you delete them permanently`}
</p>
<Button
className="text-sm flex flex-justify-end"
color="norm"
size="medium"
shape="ghost"
disabled={disabled}
onClick={handleEmptyTrashClick}
data-testid="empty-trash"
>
{c('Action').t`Empty trash`}
</Button>
</div>
{confirmModal}
</>
);
};
export default EmptyTrashNotification;
| 2,984
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Trash
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Trash/EmptyTrashNotification/index.ts
|
export { default } from './EmptyTrashNotification';
| 2,985
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Trash
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Trash/ToolbarButtons/DeletePermanentlyButton.tsx
|
import { c } from 'ttag';
import { Icon, ToolbarButton } from '@proton/components';
import { DecryptedLink, useActions } from '../../../../store';
interface Props {
selectedLinks: DecryptedLink[];
}
const DeletePermanentlyButton = ({ selectedLinks }: Props) => {
const { deletePermanently, confirmModal } = useActions();
return (
<>
<ToolbarButton
title={c('Action').t`Delete permanently`}
icon={<Icon name="cross-circle" />}
onClick={() => deletePermanently(new AbortController().signal, selectedLinks)}
data-testid="toolbar-delete"
/>
{confirmModal}
</>
);
};
export default DeletePermanentlyButton;
| 2,986
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Trash
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Trash/ToolbarButtons/RestoreFromTrashButton.tsx
|
import { c } from 'ttag';
import { Icon, ToolbarButton } from '@proton/components';
import { useLoading } from '@proton/hooks';
import { DecryptedLink, useActions } from '../../../../store';
interface Props {
selectedLinks: DecryptedLink[];
}
const RestoreFromTrashButton = ({ selectedLinks }: Props) => {
const [restoreLoading, withRestoreLoading] = useLoading();
const { restoreLinks } = useActions();
return (
<ToolbarButton
disabled={restoreLoading}
title={c('Action').t`Restore from trash`}
icon={<Icon name="arrow-rotate-right" />}
onClick={() => withRestoreLoading(restoreLinks(new AbortController().signal, selectedLinks))}
data-testid="toolbar-restore"
/>
);
};
export default RestoreFromTrashButton;
| 2,987
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Trash
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/sections/Trash/ToolbarButtons/index.ts
|
export { default as DeletePermanentlyButton } from './DeletePermanentlyButton';
export { default as RestoreFromTrashButton } from './RestoreFromTrashButton';
| 2,988
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/uploads
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/uploads/UploadDragDrop/UploadDragDrop.scss
|
@import '~@proton/styles/scss/lib';
.upload-drag-drop {
position: fixed;
inset: 0;
background: var(--backdrop-norm);
z-index: 30;
display: flex;
align-items: center;
justify-content: center;
&-infobox {
inline-size: rem(490);
min-inline-size: rem(380);
background: var(--background-norm);
color: var(--text-norm);
border-radius: var(--border-radius-md);
box-shadow: var(--shadow-lifted);
text-align: center;
pointer-events: none;
}
&-image {
max-inline-size: rem(380);
}
}
| 2,989
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/uploads
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/uploads/UploadDragDrop/UploadDragDrop.tsx
|
import { ReactNode, SyntheticEvent, useCallback, useState } from 'react';
import * as React from 'react';
import { c } from 'ttag';
import { useNotifications } from '@proton/components/hooks';
import { DS_STORE } from '@proton/shared/lib/drive/constants';
import { isImage, isVideo } from '@proton/shared/lib/helpers/mimetype';
import dragdropImageSvg from '@proton/styles/assets/img/illustrations/drag-and-drop.svg';
import { UploadFileList, mimeTypeFromFile, useUpload } from '../../../store';
import { isTransferCancelError } from '../../../utils/transfer';
interface UploadDragDropProps {
children: ReactNode;
shareId: string;
linkId: string;
className?: string;
disabled?: boolean;
isForPhotos?: boolean;
}
const UploadDragDrop = ({
children,
className,
disabled,
shareId,
linkId,
isForPhotos = false,
}: UploadDragDropProps) => {
const { createNotification } = useNotifications();
const { uploadFiles } = useUpload();
const [overlayIsVisible, setOverlayIsVisible] = useState(false);
const overlayEnabled = !disabled;
const handleDragOver = useCallback(
(e: React.DragEvent<HTMLDivElement>) => {
if (!e.dataTransfer.types.includes('Files')) {
return;
}
if (overlayIsVisible !== overlayEnabled) {
setOverlayIsVisible(overlayEnabled);
}
},
[overlayEnabled, overlayIsVisible]
);
const handleDragLeave = useCallback(() => {
setOverlayIsVisible(false);
}, [overlayIsVisible]);
const handleDrop = useCallback(
async (e: React.DragEvent<HTMLDivElement>) => {
e.preventDefault();
setOverlayIsVisible(false);
const { items } = e.dataTransfer;
if (!items) {
return;
}
const filesToUpload: UploadFileList = [];
let unSupportedFiles = false;
const traverseDirectories = async (item: any, path: string[] = []) => {
if (item.isFile) {
return new Promise<void>((resolve, reject) => {
item.file(
async (file: File) => {
// For photos, we check if the image format is supported
if (
isForPhotos &&
!(await mimeTypeFromFile(file).then((mime) => isImage(mime) || isVideo(mime))) &&
file.name !== DS_STORE
) {
unSupportedFiles = true;
resolve();
return;
}
filesToUpload.push({ path, file });
resolve();
},
(error: Error) => {
createNotification({
type: 'warning',
// translator: here is an example of full sentence: File ".abc" cannot be uploaded due to "browser specific error such as hidden files are not allowed" error
text: c('Error').t`File "${item.name}" cannot be uploaded due to "${error}" error`,
});
reject(new Error(`Unable to get File ${item}: ${error}`));
}
);
});
}
if (item.isDirectory) {
const reader = item.createReader();
// For photos we don't push folder
if (!isForPhotos) {
const modificationTime = await new Promise<Date | undefined>((resolve, reject) => {
item.getMetadata(resolve, reject);
})
.then((metadata: any) => {
return metadata.modificationTime;
})
.catch(() => {
// For example, Firefox does not support `getMetadata`
// and there is no other way to get modification time
// at this moment.
return undefined;
});
filesToUpload.push({
path,
folder: item.name,
modificationTime,
});
}
// Iterates over folders recursively and puts them into filesToUpload list
const getEntries = async () => {
const promises: Promise<any>[] = [];
// Folders are read in batch, need to wait
await new Promise<PromiseSettledResult<any>[] | void>((resolve, reject) => {
reader.readEntries(
(entries: any[]) => {
if (entries.length) {
entries.forEach((entry) =>
promises.push(
// For photos we don't push file/folder structure
traverseDirectories(entry, isForPhotos ? [] : [...path, item.name])
)
);
resolve(getEntries());
} else {
resolve();
}
},
(error: Error) => reject(new Error(`Unable to traverse directory ${item}: ${error}`))
);
});
return Promise.allSettled(promises);
};
await getEntries();
}
};
const promises: Promise<any>[] = [];
for (let i = 0; i < items.length; i++) {
const item = (items[i] as any).getAsEntry
? (items[i] as any).getAsEntry()
: items[i].webkitGetAsEntry();
if (item) {
promises.push(traverseDirectories(item));
}
}
// Need to wait for all files to have been read
const results = await Promise.allSettled(promises);
if (unSupportedFiles) {
createNotification({
type: 'warning',
text: c('Error').t`Some files were ignored because they are not supported in Photos`,
});
}
const errors = results.reduce((err, result) => {
if (result.status === 'rejected') {
err.push(result.reason);
}
return err;
}, [] as string[]);
if (errors.length) {
console.error(errors);
}
uploadFiles(shareId, linkId, filesToUpload, isForPhotos).catch((err) => {
if (!isTransferCancelError(err)) {
console.error(err);
}
});
},
[overlayIsVisible]
);
const preventDefaultEvent = useCallback((e: SyntheticEvent) => e.preventDefault(), []);
return (
<div
className={className}
onDragEnter={handleDragOver}
onDragOver={handleDragOver}
onDrop={preventDefaultEvent}
>
<img className="visibility-hidden absolute h-0 w-0" src={dragdropImageSvg} alt="" aria-hidden="true" />
{children}
{overlayEnabled && overlayIsVisible && (
<div
className="upload-drag-drop"
onDragLeave={handleDragLeave}
onDragOver={preventDefaultEvent}
onDrop={handleDrop}
>
<section className="upload-drag-drop-infobox p-14 pt-11">
<img className="upload-drag-drop-image" src={dragdropImageSvg} alt="" aria-hidden="true" />
<h2 className="text-bold mt-4 mb-0">{c('Title').t`Drop to upload`}</h2>
<p className="mt-4 mb-0">{c('Info').t`Your files will be encrypted and then saved.`}</p>
</section>
</div>
)}
</div>
);
};
export default UploadDragDrop;
| 2,990
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/containers/DevicesContainer.tsx
|
import { Redirect, Route, RouteComponentProps, Switch } from 'react-router-dom';
import DevicesView from '../components/sections/Devices/DevicesView';
const DevicesContainer = ({ match }: RouteComponentProps) => {
return (
<Switch>
<Route path={match.url} exact component={DevicesView} />
<Redirect to="/devices" />
</Switch>
);
};
export default DevicesContainer;
| 2,991
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/containers/DriveDummyContainer.tsx
|
import { useRef } from 'react';
import { c } from 'ttag';
import {
CalendarDrawerAppButton,
CollapsingBreadcrumbs,
ContactDrawerAppButton,
DrawerSidebar,
MainLogo,
ModalsChildren,
PrivateAppContainer,
PrivateMainArea,
SidebarPrimaryButton,
useActiveBreakpoint,
useToggle,
useUser,
} from '@proton/components';
import DrawerVisibilityButton from '@proton/components/components/drawer/DrawerVisibilityButton';
import { DRIVE_APP_NAME } from '@proton/shared/lib/constants';
import isTruthy from '@proton/utils/isTruthy';
import { ListView } from '../components/FileBrowser';
import { ListViewHeaderItem } from '../components/FileBrowser/interface';
import { DriveHeader } from '../components/layout/DriveHeader';
import { getDriveDrawerPermissions } from '../components/layout/drawerPermissions';
import DriveSidebar from '../components/layout/sidebar/DriveSidebar';
import { DriveItem } from '../components/sections/Drive/Drive';
import { ModifiedCell, NameCell, SizeCell } from '../components/sections/FileBrowser/contentCells';
import headerItems from '../components/sections/FileBrowser/headerCells';
import ToolbarRow from '../components/sections/ToolbarRow/ToolbarRow';
const desktopCells: React.FC<{ item: DriveItem }>[] = [NameCell, ModifiedCell, SizeCell];
const mobileCells = [NameCell];
const headerItemsDesktop: ListViewHeaderItem[] = [headerItems.name, headerItems.modificationDate, headerItems.size];
const headerItemsMobile: ListViewHeaderItem[] = [headerItems.name, headerItems.placeholder];
const DriveDummyContainer = () => {
const [user] = useUser();
const scrollAreaRef = useRef<HTMLDivElement>(null);
const { state: expanded, toggle: toggleExpanded } = useToggle();
const { isDesktop } = useActiveBreakpoint();
const logo = <MainLogo to="/" />;
const dummyUploadButton = (
<SidebarPrimaryButton className="hidden md:flex">{c('Action').t`New upload`}</SidebarPrimaryButton>
);
const dummyFolderTitle = c('Title').t`My files`;
const header = <DriveHeader isHeaderExpanded={expanded} toggleHeaderExpanded={toggleExpanded} />;
const sidebar = (
<DriveSidebar
logo={logo}
primary={dummyUploadButton}
isHeaderExpanded={expanded}
toggleHeaderExpanded={toggleExpanded}
/>
);
const items: DriveItem[] = [
{
id: 'dummy-link-1',
parentLinkId: '',
mimeType: 'text/plain',
name: 'Private files',
fileModifyTime: Date.now() / 1000,
trashed: null,
size: 1024 * 1024,
isFile: false,
hasThumbnail: false,
},
{
id: 'dummy-link-2',
parentLinkId: '',
mimeType: 'text/plain',
name: `Welcome to ${DRIVE_APP_NAME}.txt`,
fileModifyTime: Date.now() / 1000,
trashed: null,
size: 1024 * 1024,
isFile: true,
hasThumbnail: false,
},
];
const headerItems = isDesktop ? headerItemsDesktop : headerItemsMobile;
const Cells = isDesktop ? desktopCells : mobileCells;
const permissions = getDriveDrawerPermissions({ user });
const drawerSidebarButtons = [
permissions.contacts && <ContactDrawerAppButton />,
permissions.calendar && <CalendarDrawerAppButton />,
].filter(isTruthy);
const canShowDrawer = drawerSidebarButtons.length > 0;
return (
<>
<ModalsChildren />
<PrivateAppContainer header={header} sidebar={sidebar}>
<PrivateMainArea
hasToolbar
className="flex-no-min-children flex-column flex-nowrap "
drawerSidebar={<DrawerSidebar buttons={drawerSidebarButtons} />}
drawerVisibilityButton={canShowDrawer ? <DrawerVisibilityButton /> : undefined}
>
<div className="flex flex-column flex-nowrap w-full">
<ToolbarRow
titleArea={
<CollapsingBreadcrumbs
breadcrumbs={[
{
key: 'my-files',
text: c('Title').t`My files`,
noShrink: true,
highlighted: true,
},
]}
/>
}
toolbar={<></>}
/>
<ListView
caption={dummyFolderTitle}
Cells={Cells}
headerItems={headerItems}
items={items}
loading={false}
scrollAreaRef={scrollAreaRef}
/>
</div>
</PrivateMainArea>
</PrivateAppContainer>
</>
);
};
export default DriveDummyContainer;
| 2,992
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/containers/FolderContainer.tsx
|
import { useEffect, useMemo, useRef, useState } from 'react';
import { Route, RouteComponentProps } from 'react-router';
import { useAppTitle } from '@proton/components';
import { LinkURLType } from '@proton/shared/lib/drive/constants';
import DriveView, { DriveSectionRouteProps } from '../components/sections/Drive/DriveView';
import useActiveShare, { DriveFolder } from '../hooks/drive/useActiveShare';
import { useFolderContainerTitle } from '../hooks/drive/useFolderContainerTitle';
import useNavigate from '../hooks/drive/useNavigate';
import { useDefaultShare } from '../store';
import PreviewContainer from './PreviewContainer';
export default function FolderContainer({ match }: RouteComponentProps<DriveSectionRouteProps>) {
const { navigateToRoot } = useNavigate();
const { activeFolder, setFolder } = useActiveShare();
const lastFolderPromise = useRef<Promise<DriveFolder | undefined>>();
const [, setError] = useState();
const { getDefaultShare, isShareAvailable } = useDefaultShare();
useFolderContainerTitle({ params: match.params, setAppTitle: useAppTitle });
const hasValidLinkType = (type: string) => {
return type === LinkURLType.FILE || type === LinkURLType.FOLDER;
};
const folderPromise = useMemo(async () => {
const { shareId, type, linkId } = match.params;
if (!shareId && !type && !linkId) {
const defaultShare = await getDefaultShare();
if (defaultShare) {
return { shareId: defaultShare.shareId, linkId: defaultShare.rootLinkId };
}
setError(() => {
// Throwing error in async function does not propagate it to
// the view. Therefore we need to use this setError hack.
throw new Error('Drive is not initilized, cache has been cleared unexpectedly');
});
} else if (!shareId || !hasValidLinkType(type as string) || !linkId) {
console.warn('Missing parameters, should be none or shareId/type/linkId');
navigateToRoot();
} else if (type === LinkURLType.FOLDER) {
const ac = new AbortController();
const isAvailable = await isShareAvailable(ac.signal, shareId);
if (!isAvailable) {
console.warn('Provided share is not available, probably locked or soft deleted');
navigateToRoot();
return;
}
return { shareId, linkId };
}
return lastFolderPromise.current;
}, [match.params.shareId, match.params.type, match.params.linkId]);
useEffect(() => {
folderPromise
.then((folder) => {
if (folder) {
setFolder(folder);
}
})
.catch((err) => {
console.warn(err);
navigateToRoot();
});
}, [folderPromise]);
// In case we open preview, folder doesn't need to change.
lastFolderPromise.current = folderPromise;
const shouldRenderDriveView = Boolean(activeFolder.shareId && activeFolder.linkId);
return (
<>
{shouldRenderDriveView ? <DriveView /> : null}
<Route path={`/:shareId?/${LinkURLType.FILE}/:linkId?`} component={PreviewContainer} exact />
</>
);
}
| 2,993
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/containers/MainContainer.tsx
|
import { useEffect, useState } from 'react';
import { Redirect, Route, Switch } from 'react-router-dom';
import {
GlobalLoader,
GlobalLoaderProvider,
LoaderPage,
LocationErrorBoundary,
ModalsChildren,
useWelcomeFlags,
} from '@proton/components';
import { QuickSettingsRemindersProvider } from '@proton/components/hooks/drawer/useQuickSettingsReminders';
import { useLoading } from '@proton/hooks';
import TransferManager from '../components/TransferManager/TransferManager';
import DriveWindow from '../components/layout/DriveWindow';
import DriveStartupModals from '../components/modals/DriveStartupModals';
import GiftFloatingButton from '../components/onboarding/GiftFloatingButton';
import { ActiveShareProvider } from '../hooks/drive/useActiveShare';
import { DriveProvider, useDefaultShare, useDriveEventManager, usePhotosFeatureFlag, useSearchControl } from '../store';
import DevicesContainer from './DevicesContainer';
import FolderContainer from './FolderContainer';
import OnboardingContainer from './OnboardingContainer';
import { PhotosContainer } from './PhotosContainer';
import { SearchContainer } from './SearchContainer';
import SharedURLsContainer from './SharedLinksContainer';
import TrashContainer from './TrashContainer';
// Empty shared root for blurred container.
const DEFAULT_VOLUME_INITIAL_STATE: {
volumeId: string | undefined;
shareId: string | undefined;
linkId: string | undefined;
} = {
volumeId: undefined,
shareId: undefined,
linkId: undefined,
};
const InitContainer = () => {
const { getDefaultShare } = useDefaultShare();
const [loading, withLoading] = useLoading(true);
const [error, setError] = useState();
const [defaultShareRoot, setDefaultShareRoot] =
useState<typeof DEFAULT_VOLUME_INITIAL_STATE>(DEFAULT_VOLUME_INITIAL_STATE);
const [welcomeFlags, setWelcomeFlagsDone] = useWelcomeFlags();
const { searchEnabled } = useSearchControl();
const driveEventManager = useDriveEventManager();
const isPhotosEnabled = usePhotosFeatureFlag();
useEffect(() => {
const initPromise = getDefaultShare()
.then(({ shareId, rootLinkId: linkId, volumeId }) => {
setDefaultShareRoot({ volumeId, shareId, linkId });
})
.catch((err) => {
setError(err);
});
void withLoading(initPromise);
}, []);
useEffect(() => {
const { volumeId } = defaultShareRoot;
if (volumeId === undefined) {
return;
}
driveEventManager.volumes.startSubscription(volumeId).catch(console.warn);
return () => {
driveEventManager.volumes.unsubscribe(volumeId);
};
}, [defaultShareRoot.volumeId]);
if (loading) {
return (
<>
<ModalsChildren />
<LoaderPage />
</>
);
}
if (error || !defaultShareRoot.shareId || !defaultShareRoot.linkId) {
throw error || new Error('Default share failed to be loaded');
}
const rootShare = { shareId: defaultShareRoot.shareId, linkId: defaultShareRoot.linkId };
if (!welcomeFlags.isDone) {
return (
<ActiveShareProvider defaultShareRoot={rootShare}>
<OnboardingContainer onDone={setWelcomeFlagsDone} />
</ActiveShareProvider>
);
}
return (
<ActiveShareProvider defaultShareRoot={rootShare}>
<DriveStartupModals />
<ModalsChildren />
<TransferManager />
<GiftFloatingButton />
<DriveWindow>
<Switch>
<Route path="/devices" component={DevicesContainer} />
<Route path="/trash" component={TrashContainer} />
<Route path="/shared-urls" component={SharedURLsContainer} />
{isPhotosEnabled && <Route path="/photos" component={PhotosContainer} />}
{searchEnabled && <Route path="/search" component={SearchContainer} />}
<Route path="/:shareId?/:type/:linkId?" component={FolderContainer} />
<Redirect to={`/${defaultShareRoot?.shareId}/folder/${defaultShareRoot?.linkId}`} />
</Switch>
</DriveWindow>
</ActiveShareProvider>
);
};
const MainContainer = () => {
return (
<GlobalLoaderProvider>
<GlobalLoader />
<LocationErrorBoundary>
<DriveProvider>
<QuickSettingsRemindersProvider>
<InitContainer />
</QuickSettingsRemindersProvider>
</DriveProvider>
</LocationErrorBoundary>
</GlobalLoaderProvider>
);
};
export default MainContainer;
| 2,994
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/containers/OnboardingContainer.tsx
|
import DriveOnboardingModal from '../components/modals/DriveOnboardingModal';
import DriveDummyContainer from './DriveDummyContainer';
interface Props {
onDone: () => void;
}
const OnboardingContainer = ({ onDone }: Props) => {
return (
<>
<DriveDummyContainer />
<DriveOnboardingModal open onDone={onDone} />
</>
);
};
export default OnboardingContainer;
| 2,995
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/containers/PhotosContainer.tsx
|
import { FC } from 'react';
import { Redirect, Route, RouteComponentProps, Switch } from 'react-router-dom';
import { PhotosView } from '../components/sections/Photos';
export const PhotosContainer: FC<RouteComponentProps> = ({ match }) => {
return (
<Switch>
<Route path={match.url} exact component={PhotosView} />
<Redirect to="/photos" />
</Switch>
);
};
| 2,996
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/containers/PreviewContainer.tsx
|
import { useCallback, useEffect, useMemo, useRef } from 'react';
import { RouteComponentProps, useLocation } from 'react-router-dom';
import { c } from 'ttag';
import { FilePreview, NavigationControl } from '@proton/components';
import { HTTP_STATUS_CODE } from '@proton/shared/lib/constants';
import { RESPONSE_CODE } from '@proton/shared/lib/drive/constants';
import { SignatureAlertBody } from '../components/SignatureAlert';
import SignatureIcon from '../components/SignatureIcon';
import { useDetailsModal } from '../components/modals/DetailsModal';
import { useLinkSharingModal } from '../components/modals/ShareLinkModal/ShareLinkModal';
import useIsEditEnabled from '../components/sections/useIsEditEnabled';
import useActiveShare from '../hooks/drive/useActiveShare';
import useNavigate from '../hooks/drive/useNavigate';
import { DecryptedLink, useActions, useFileView } from '../store';
// TODO: ideally not use here
import useSearchResults from '../store/_search/useSearchResults';
const getSharedStatus = (link?: DecryptedLink) => {
if (!link?.isShared) {
return '';
}
if (link?.shareUrl?.isExpired || link?.trashed) {
return 'inactive';
}
return 'shared';
};
export default function PreviewContainer({ match }: RouteComponentProps<{ shareId: string; linkId: string }>) {
const { shareId, linkId } = match.params;
const { navigateToLink, navigateToSharedURLs, navigateToTrash, navigateToRoot, navigateToSearch } = useNavigate();
const { setFolder } = useActiveShare();
const [detailsModal, showDetailsModal] = useDetailsModal();
const [linkSharingModal, showLinkSharingModal] = useLinkSharingModal();
const { query: lastQuery } = useSearchResults();
const { saveFile } = useActions();
const isEditEnabled = useIsEditEnabled();
const referer = new URLSearchParams(useLocation().search).get('r');
const useNavigation =
!referer?.startsWith('/shared-urls') && !referer?.startsWith('/trash') && !referer?.startsWith('/search');
const { isLinkLoading, isContentLoading, error, link, contents, contentsMimeType, downloadFile, navigation } =
useFileView(shareId, linkId, useNavigation);
// If the link is not type of file, probably user modified the URL.
useEffect(() => {
if (link && !link.isFile) {
navigateToLink(shareId, linkId, false);
}
}, [link?.isFile]);
useEffect(() => {
if (link) {
setFolder({ shareId, linkId: link.parentLinkId });
}
}, [shareId, link?.parentLinkId]);
useEffect(() => {
if (!error) {
return;
}
if (
// Block not found (storage response).
error.status === HTTP_STATUS_CODE.NOT_FOUND ||
// Meta data not found (API response).
error.data?.Code === RESPONSE_CODE.NOT_FOUND ||
error.data?.Code === RESPONSE_CODE.INVALID_ID
) {
navigateToRoot();
}
}, [error]);
const navigateToParent = useCallback(() => {
if (referer?.startsWith('/shared-urls')) {
navigateToSharedURLs();
return;
}
if (referer?.startsWith('/trash')) {
navigateToTrash();
return;
}
if (referer?.startsWith('/search')) {
if (lastQuery) {
navigateToSearch(lastQuery);
return;
}
}
if (link?.parentLinkId) {
navigateToLink(shareId, link.parentLinkId, false);
}
}, [link?.parentLinkId, shareId, referer]);
const onOpen = useCallback(
(linkId: string | undefined) => {
if (linkId) {
navigateToLink(shareId, linkId, true);
}
},
[shareId]
);
const signatureStatus = useMemo(() => {
if (!link) {
return;
}
return (
<SignatureIcon isFile={link.isFile} signatureIssues={link.signatureIssues} className="ml-2 color-danger" />
);
}, [link]);
const signatureConfirmation = useMemo(() => {
if (!link?.signatureIssues?.blocks) {
return;
}
return (
<SignatureAlertBody
signatureIssues={link.signatureIssues}
signatureAddress={link.signatureAddress}
isFile={link.isFile}
name={link.name}
/>
);
}, [link]);
const handleSaveFile = useCallback(
(content: Uint8Array[]) => {
if (!link) {
return Promise.reject('missing link');
}
return saveFile(shareId, link.parentLinkId, link.name, link.mimeType, content);
},
[shareId, link?.name, link?.parentLinkId]
);
const rootRef = useRef<HTMLDivElement>(null);
return (
<>
<FilePreview
isMetaLoading={isLinkLoading}
isLoading={isContentLoading}
error={error ? error.message || error.toString?.() || c('Info').t`Unknown error` : undefined}
contents={contents}
fileName={link?.name}
mimeType={contentsMimeType}
sharedStatus={getSharedStatus(link)}
fileSize={link?.size}
onClose={navigateToParent}
onDownload={downloadFile}
onSave={isEditEnabled ? handleSaveFile : undefined}
onDetails={() => showDetailsModal({ shareId, linkId })}
onShare={isLinkLoading || !!link?.trashed ? undefined : () => showLinkSharingModal({ shareId, linkId })}
imgThumbnailUrl={link?.cachedThumbnailUrl}
ref={rootRef}
navigationControls={
link &&
navigation && (
<NavigationControl
current={navigation.current}
total={navigation.total}
rootRef={rootRef}
onPrev={() => onOpen?.(navigation.prevLinkId)}
onNext={() => onOpen?.(navigation.nextLinkId)}
/>
)
}
signatureStatus={signatureStatus}
signatureConfirmation={signatureConfirmation}
/>
{detailsModal}
{linkSharingModal}
</>
);
}
| 2,997
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/containers/PublicSharedLinkContainer.tsx
|
import { useEffect, useState } from 'react';
import { c } from 'ttag';
import { LocationErrorBoundary } from '@proton/components';
import { useLoading } from '@proton/hooks';
import { getApiError } from '@proton/shared/lib/api/helpers/apiErrorHelper';
import { ErrorPage, LoadingPage, PasswordPage, SharedFilePage, SharedFolderPage } from '../components/SharedPage';
import usePublicToken from '../hooks/drive/usePublicToken';
import { DecryptedLink, PublicDriveProvider, useDownload, usePublicAuth, usePublicShare } from '../store';
export default function PublicSharedLinkContainer() {
return (
<LocationErrorBoundary>
<PublicDriveProvider>
<PublicShareLinkInitContainer />
</PublicDriveProvider>
</LocationErrorBoundary>
);
}
/**
* PublicShareLinkInitContainer initiate public session for shared link.
* That is to initiate SRP handshake and ask for password if needed to
* initiate session itself.
*/
function PublicShareLinkInitContainer() {
const { clearDownloads } = useDownload();
const { token, urlPassword } = usePublicToken();
const { isLoading, error, isPasswordNeeded, submitPassword } = usePublicAuth(token, urlPassword);
// If password to the share was changed, page need to reload everything.
// In such case we need to also clear all downloads to not keep anything
// from before.
useEffect(() => {
if (isLoading) {
clearDownloads();
}
}, [isLoading]);
if (isLoading) {
return <LoadingPage />;
}
if (error) {
return <ErrorPage />;
}
if (isPasswordNeeded) {
return <PasswordPage submitPassword={submitPassword} />;
}
return <PublicSharedLink token={token} />;
}
/**
* PublicSharedLink loads and decrypt the public share.
* Based on the link it renders shared file or folder page.
*/
function PublicSharedLink({ token }: { token: string }) {
const { loadPublicShare } = usePublicShare();
const [isLoading, withLoading] = useLoading(true);
const [link, setLink] = useState<DecryptedLink>();
const [error, setError] = useState<string>();
useEffect(() => {
const abortController = new AbortController();
void withLoading(
loadPublicShare(abortController.signal)
.then(({ link }) => setLink(link))
.catch((error) => {
console.error(error);
const apiError = getApiError(error);
setError(apiError.message || error.message || c('Info').t`Cannot load shared link`);
})
);
return () => {
abortController.abort();
};
}, []);
if (isLoading) {
return <LoadingPage />;
}
if (error || !link) {
return <ErrorPage />;
}
if (link.isFile) {
return <SharedFilePage token={token} link={link} />;
}
return <SharedFolderPage token={token} rootLink={link} />;
}
| 2,998
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/containers/SearchContainer.tsx
|
import { SearchView } from '../components/sections/Search/SearchView';
export const SearchContainer = () => {
return <SearchView />;
};
| 2,999
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.