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/FileBrowser
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser/ListView/ListHeader.tsx
|
import * as React from 'react';
import { c, msgid } from 'ttag';
import { Checkbox, Icon, Loader, TableHeaderCell, TableRowSticky, Tooltip } from '@proton/components';
import { SORT_DIRECTION } from '@proton/shared/lib/constants';
import { getNumAccessesTooltipMessage } from '@proton/shared/lib/drive/translations';
import clsx from '@proton/utils/clsx';
import { stopPropagation } from '../../../utils/stopPropagation';
import { SelectionState } from '../hooks/useSelectionControls';
import { SortParams } from '../interface';
import { useSelection } from '../state/useSelection';
interface Props<T> {
scrollAreaRef: React.RefObject<HTMLDivElement>;
sortParams?: SortParams<T>;
isLoading: boolean;
items: any[];
onSort?: (params: SortParams<T>) => void;
itemCount: number;
isMultiSelectionDisabled?: boolean;
}
export enum HeaderCellsPresets {
Checkbox,
Placeholder,
}
const HeaderCell = <T,>({
item,
isLoading,
sortParams,
itemCount,
onSort,
isMultiSelectionDisabled,
}: {
item: any;
isLoading: boolean;
itemCount: number;
onSort: (key: T) => void;
sortParams?: SortParams<T>;
isMultiSelectionDisabled?: boolean;
}) => {
const selection = useSelection();
const selectedCount = selection?.selectedItemIds.length;
if (item.type === HeaderCellsPresets.Checkbox && selection) {
return (
<TableHeaderCell className="file-browser-header-checkbox-cell">
<div role="presentation" key="select-all" className="flex pl-2" onClick={stopPropagation}>
<Checkbox
indeterminate={selection.selectionState === SelectionState.SOME}
className="increase-click-surface mr-1"
disabled={!itemCount}
checked={selection?.selectionState !== SelectionState.NONE}
onChange={
selection?.selectionState === SelectionState.SOME
? selection.clearSelections
: selection.toggleAllSelected
}
data-testid="checkbox-select-all"
>
{selectedCount && selection?.selectionState !== SelectionState.NONE ? (
<span className="ml-2">
{c('Info').ngettext(
msgid`${selectedCount} selected`,
`${selectedCount} selected`,
selectedCount
)}
</span>
) : null}
</Checkbox>
{selection?.selectionState !== SelectionState.NONE && isLoading ? (
<Loader className="flex flex-item-noshrink" />
) : null}
</div>
</TableHeaderCell>
);
}
if (!isMultiSelectionDisabled && selection?.selectionState !== SelectionState.NONE) {
return null;
}
if (item.type === HeaderCellsPresets.Placeholder) {
return (
<TableHeaderCell
className={clsx(['file-browser-list--icon-column', item.props?.className])}
style={item.props.style}
/>
);
}
const getSortDirectionForKey = (key: T) => (sortParams?.sortField === key ? sortParams.sortOrder : undefined);
return (
<TableHeaderCell
className={item.props?.className}
direction={getSortDirectionForKey(item.type)}
onSort={item.sorting ? () => onSort?.(item.type) : undefined}
isLoading={isLoading && sortParams?.sortField === item.type}
data-testid="sort-by"
>
{item.getText()}
{item.type === 'numAccesses' && (
<Tooltip className="pl-1" title={getNumAccessesTooltipMessage()}>
<Icon name="info-circle" size={14} alt={getNumAccessesTooltipMessage()} />
</Tooltip>
)}
</TableHeaderCell>
);
};
const ListHeader = <T,>({
scrollAreaRef,
items,
sortParams,
isLoading,
itemCount,
onSort,
isMultiSelectionDisabled,
}: Props<T>) => {
const handleSort = (key: T) => {
if (!sortParams || !onSort) {
return;
}
const direction =
sortParams.sortField === key && sortParams.sortOrder === SORT_DIRECTION.ASC
? SORT_DIRECTION.DESC
: SORT_DIRECTION.ASC;
onSort({ sortField: key, sortOrder: direction });
};
return (
<thead onContextMenu={(e) => e.stopPropagation()}>
<TableRowSticky scrollAreaRef={scrollAreaRef}>
{items.map((item, index) => (
<HeaderCell
item={item}
isLoading={isLoading}
sortParams={sortParams}
key={index}
itemCount={itemCount}
onSort={handleSort}
isMultiSelectionDisabled={isMultiSelectionDisabled}
/>
))}
</TableRowSticky>
</thead>
);
};
export default ListHeader;
| 2,700
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser/ListView/ListView.tsx
|
import { useRef } from 'react';
import { FixedSizeList, ListChildComponentProps } from 'react-window';
import {
Table,
TableBody,
TableCellBusy,
useActiveBreakpoint,
useElementRect,
useRightToLeft,
} from '@proton/components';
import { rootFontSize } from '@proton/shared/lib/helpers/dom';
import clsx from '@proton/utils/clsx';
import { FileBrowserProps } from '../FileBrowser';
import { BrowserItemId, DragMoveControls, FileBrowserBaseItem } from '../interface';
import { useSelection } from '../state/useSelection';
import ItemRow from './ItemRow';
import ListHeader from './ListHeader';
interface ListItemData<T extends FileBrowserBaseItem> {
items: T[];
loading: boolean;
itemCount: number;
Cells: React.FC<{ item: T }>[];
isMultiSelectionDisabled: boolean;
onItemContextMenu?: (e: any) => void;
onItemOpen?: (id: BrowserItemId) => void;
onItemRender?: (item: T) => void;
getDragMoveControls?: (item: T) => DragMoveControls;
}
interface ListItemRowProps<T extends FileBrowserBaseItem> extends ListChildComponentProps {
data: ListItemData<T>;
}
const ListItemRow = <T extends FileBrowserBaseItem>({ index, style, data }: ListItemRowProps<T>) => {
const {
items,
loading,
itemCount,
Cells,
isMultiSelectionDisabled,
onItemContextMenu,
onItemOpen,
onItemRender,
getDragMoveControls,
} = data;
if (loading && index === itemCount - 1) {
return (
<tr style={style} className="flex">
<TableCellBusy className="flex w-full text-lg flex-justify-center flex-align-items-center m-0" />
</tr>
);
}
const item = items[index];
if (!item) {
return null;
}
return (
<ItemRow
style={style}
item={item}
Cells={Cells}
isMultiSelectionDisabled={isMultiSelectionDisabled}
onItemContextMenu={onItemContextMenu}
onItemOpen={onItemOpen}
onItemRender={onItemRender}
dragMoveControls={getDragMoveControls?.(item)}
/>
);
};
const TableBodyRenderer = ({
children,
className,
...props
}: React.DetailedHTMLProps<React.TableHTMLAttributes<HTMLTableElement>, HTMLTableElement>) => {
return (
<Table
{...props}
borderWeak
className={clsx(['file-browser-table simple-table--is-hoverable border-none border-collapse', className])}
>
<TableBody>{children}</TableBody>
</Table>
);
};
type Props<T extends FileBrowserBaseItem, T1> = Omit<
FileBrowserProps<T, T1>,
'onScrollEnd' | 'layout' | 'GridHeaderComponent' | 'GridViewItem'
> & {
scrollAreaRef: React.RefObject<HTMLDivElement>;
};
export const ListView = <T extends FileBrowserBaseItem, T1>({
caption,
items,
headerItems,
loading = false,
sortParams,
isMultiSelectionDisabled,
Cells,
onItemContextMenu,
onItemOpen,
onItemRender,
onScroll,
onViewContextMenu,
onSort,
contextMenuAnchorRef,
scrollAreaRef,
getDragMoveControls,
}: Props<T, T1>) => {
const { isDesktop } = useActiveBreakpoint();
const [isRTL] = useRightToLeft();
const selectionControls = useSelection();
const containerRef = useRef<HTMLDivElement>(null);
const rect = useElementRect(containerRef);
const itemCount = loading ? items.length + 1 : items.length;
const itemHeight = rootFontSize() * 2.75; // 2.75 x 16 = we want 44px by default
const itemData = {
items,
isDesktop,
itemCount,
loading,
isMultiSelectionDisabled,
Cells,
onItemContextMenu,
onItemOpen,
onItemRender,
getDragMoveControls,
};
return (
<div
className="flex flex-column flex-item-fluid-auto flex-nowrap"
onClick={selectionControls?.clearSelections}
onContextMenu={onViewContextMenu}
ref={containerRef}
role="presentation"
>
<Table borderWeak caption={caption} className="file-browser-table m-0">
<ListHeader
scrollAreaRef={scrollAreaRef}
items={headerItems}
isLoading={loading}
itemCount={items.length}
onSort={onSort}
sortParams={sortParams}
isMultiSelectionDisabled={isMultiSelectionDisabled}
/>
</Table>
<div className="flex-no-min-children flex-column flex-item-fluid w-full no-scroll" ref={contextMenuAnchorRef}>
{rect && (
<FixedSizeList
direction={isRTL ? 'rtl' : 'ltr'}
itemCount={itemCount}
itemSize={itemHeight}
// @ts-ignore
// FixedSizeList wraps our ListItemRow which breaks the type safety.
// The reason is that we have generic type for several fields and all
// has to be the same one to make it work. We can ignore it as far as
// we properly state types on all places to guarantee the types.
itemData={itemData}
onScroll={onScroll}
width={rect.width}
height={rect.height}
outerRef={scrollAreaRef}
innerElementType={TableBodyRenderer}
itemKey={(index, data) =>
loading && index === itemCount - 1 ? 'loader' : `${data.items[index].id}`
}
>
{ListItemRow}
</FixedSizeList>
)}
</div>
</div>
);
};
| 2,701
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser/ListView
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser/ListView/Cells/CheckboxCell.tsx
|
import { memo } from 'react';
import { Checkbox, TableCell } from '@proton/components';
import clsx from '@proton/utils/clsx';
import { stopPropagation } from '../../../../utils/stopPropagation';
import { useFileBrowserCheckbox } from '../../hooks/useFileBrowserCheckbox';
import { SelectionState } from '../../hooks/useSelectionControls';
import { FileBrowserBaseItem } from '../../interface';
import { useSelection } from '../../state/useSelection';
interface Props {
className?: string;
isDisabled?: boolean;
isSelected?: boolean;
onCheckboxChange?: (e: any) => void;
onCheckboxClick?: (e: any) => void;
onCheckboxWrapperClick?: (e: any) => void;
}
const CheckboxCellBase = ({
className,
isDisabled,
isSelected,
onCheckboxChange,
onCheckboxClick,
onCheckboxWrapperClick,
}: Props) => {
return (
<TableCell className="m-0 flex file-browser-list-checkbox-cell" data-testid="column-checkbox">
<div
role="presentation"
className={clsx(['flex flex-align-items-center pl-2', className])}
onTouchStart={stopPropagation}
onKeyDown={stopPropagation}
onClick={onCheckboxWrapperClick}
>
<Checkbox
disabled={isDisabled}
className="increase-click-surface"
checked={isSelected}
onChange={onCheckboxChange}
onClick={onCheckboxClick}
/>
</div>
</TableCell>
);
};
export const CheckboxCell = memo(({ item }: { item: FileBrowserBaseItem }) => {
const selectionControls = useSelection();
const isSelected = Boolean(selectionControls?.isSelected(item.id));
const { handleCheckboxChange, handleCheckboxClick, handleCheckboxWrapperClick } = useFileBrowserCheckbox(item.id);
return (
<CheckboxCellBase
className={
selectionControls?.selectionState !== SelectionState.NONE ? undefined : 'mouse:group-hover:opacity-100'
}
isDisabled={Boolean(item.isLocked)}
isSelected={isSelected}
onCheckboxChange={handleCheckboxChange}
onCheckboxClick={handleCheckboxClick}
onCheckboxWrapperClick={handleCheckboxWrapperClick}
/>
);
});
CheckboxCell.displayName = 'CheckboxCell';
| 2,702
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser/ListView
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser/ListView/Cells/ContextMenuCell.tsx
|
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { Icon, TableCell } from '@proton/components';
import { FileBrowserBaseItem } from '../../interface';
import { useItemContextMenu } from '../../state/useItemContextMenu';
import { useSelection } from '../../state/useSelection';
export const ContextMenuCell = ({ item }: { item: FileBrowserBaseItem }) => {
const contextMenuControls = useItemContextMenu();
const selectionControls = useSelection();
const isContextMenuButtonActive =
contextMenuControls.isOpen && selectionControls?.selectedItemIds.includes(item.id);
return (
<TableCell
className="m-0 file-browser-list--icon-column file-browser-list--context-menu-column flex flex-align-items-center"
data-testid="column-options"
>
<Button
shape="ghost"
size="small"
icon
onClick={(e) => {
selectionControls?.selectItem(item.id);
contextMenuControls.handleContextMenu(e);
}}
onTouchEnd={(e) => {
selectionControls?.selectItem(item.id);
contextMenuControls.handleContextMenuTouch?.(e);
}}
className={isContextMenuButtonActive ? 'file-browser--options-focus' : 'mouse:group-hover:opacity-100'}
>
<Icon name="three-dots-vertical" alt={c('Action').t`More options`} />
</Button>
</TableCell>
);
};
| 2,703
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser/ListView
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser/ListView/Cells/DescriptiveTypeCell.tsx
|
import { c } from 'ttag';
import { getMimeTypeDescription } from '../../../sections/helpers';
interface Props {
mimeType: string;
isFile: boolean;
}
export const DescriptiveTypeCell = ({ mimeType, isFile }: Props) => {
const type = isFile ? getMimeTypeDescription(mimeType) : c('Label').t`Folder`;
return (
<div key="Type" title={type} className="text-ellipsis">
<span className="text-pre">{type}</span>
</div>
);
};
| 2,704
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser/ListView
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser/ListView/Cells/LocationCell.tsx
|
import { useEffect, useRef, useState } from 'react';
import { Icon } from '@proton/components';
import { useLinkPath } from '../../../../store';
interface Props {
shareId: string;
parentLinkId: string;
isTrashed?: boolean;
}
export const LocationCell = ({ shareId, parentLinkId, isTrashed }: Props) => {
const [location, setLocation] = useState<string>();
const { getPath } = useLinkPath();
const abortController = useRef(new AbortController());
const previousParentLinkId = useRef(parentLinkId);
useEffect(() => {
void getPath(abortController.current.signal, shareId, parentLinkId).then(setLocation);
return () => {
// Abort only when parent ID changes which means the whole location
// changed and is not needed anymore. All other cases we just want
// to update location based on the latest cache state.
if (previousParentLinkId.current !== parentLinkId) {
abortController.current.abort();
abortController.current = new AbortController();
previousParentLinkId.current = parentLinkId;
}
};
}, [getPath, shareId, parentLinkId]);
return (
<div key="location" title={location} className="text-ellipsis">
<span className="text-pre">
{isTrashed && <Icon name="trash" className="mr-1" />}
{location}
</span>
</div>
);
};
| 2,705
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser/ListView
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser/ListView/Cells/MimeTypeCell.tsx
|
interface Props {
mimeType: string;
}
export const MimeTypeCell = ({ mimeType }: Props) => (
<div key="mimeType" title={mimeType} className="text-ellipsis">
<span className="text-pre">{mimeType}</span>
</div>
);
| 2,706
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser/ListView
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser/ListView/Cells/NameCell.tsx
|
import { FileNameDisplay } from '@proton/components';
export const NameCell = ({ name }: { name: string }) => (
<div className="flex mr-4" data-testid="name-cell">
<FileNameDisplay text={name} />
</div>
);
| 2,707
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser/ListView
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser/ListView/Cells/SizeCell.tsx
|
import { shortHumanSize } from '@proton/shared/lib/helpers/humanSize';
import clsx from '@proton/utils/clsx';
interface Props {
size: number;
className?: string;
}
export const SizeCell = ({ size, className }: Props) => {
const readableSize = shortHumanSize(size);
return (
<div className={clsx(['text-ellipsis flex flex-align-items-center', className])} title={readableSize}>
<span className="text-pre">{readableSize}</span>
</div>
);
};
| 2,708
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser/ListView
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser/ListView/Cells/TimeCell.tsx
|
import { TimeIntl } from '@proton/components';
import { readableTime } from '@proton/shared/lib/helpers/time';
import { dateLocale } from '@proton/shared/lib/i18n';
interface Props {
time: number;
}
export const TimeCell = ({ time }: Props) => {
return (
<div className="text-ellipsis" title={readableTime(time, { locale: dateLocale, format: 'PP' })}>
<span className="text-pre">
<TimeIntl
options={{
year: 'numeric',
day: 'numeric',
month: 'short',
hour: 'numeric',
minute: 'numeric',
}}
>
{time}
</TimeIntl>
</span>
</div>
);
};
| 2,709
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser/ListView
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser/ListView/Cells/UserNameCell.tsx
|
import { useUser } from '@proton/components';
export const UserNameCell = () => {
const [{ Name }] = useUser();
return (
<div key="userName" title={Name} className="text-ellipsis">
<span className="text-pre">{Name}</span>
</div>
);
};
| 2,710
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser/ListView
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser/ListView/Cells/index.ts
|
export { CheckboxCell } from './CheckboxCell';
export { ContextMenuCell } from './ContextMenuCell';
export { DescriptiveTypeCell } from './DescriptiveTypeCell';
export { LocationCell } from './LocationCell';
export { MimeTypeCell } from './MimeTypeCell';
export { NameCell } from './NameCell';
export { SizeCell } from './SizeCell';
export { TimeCell } from './TimeCell';
export { UserNameCell } from './UserNameCell';
| 2,711
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser/hooks/useContextMenuControls.ts
|
import { useCallback, useRef, useState } from 'react';
const DROPDOWN_ANIMATION_TIME = 200; // ms
export function useContextMenuControls() {
const lastCloseTime = useRef<number>();
const [isOpen, setIsOpen] = useState(false);
const [position, setPosition] = useState<{ top: number; left: number }>();
const open = useCallback(() => {
// Quick hack.
// Dropdown does not recompute the height right away and if the context
// menu is open quickly with another content, scrollbar or empty space
// is displayed.
// The better solution would be to not count the new height at the end
// of the animation but sooner. That is tricky and can affect all apps.
// Please find better solution once you are around.
const delay = !lastCloseTime.current ? 0 : DROPDOWN_ANIMATION_TIME - (Date.now() - lastCloseTime.current);
setTimeout(() => setIsOpen(true), Math.max(delay, 0));
}, []);
const close = useCallback(() => {
setIsOpen(false);
setPosition(undefined);
lastCloseTime.current = Date.now();
}, []);
const handleContextMenu = (e: React.MouseEvent<Element>) => {
e.stopPropagation();
e.preventDefault();
setPosition({ top: e.clientY, left: e.clientX });
};
const handleContextMenuTouch = (e: React.TouchEvent<Element>) => {
e.stopPropagation();
e.preventDefault();
const touchPosition = e.changedTouches[e.changedTouches.length - 1];
setPosition({ top: touchPosition.clientY, left: touchPosition.clientX });
};
const value = {
isOpen,
handleContextMenu,
handleContextMenuTouch,
open,
close,
position,
};
return value;
}
| 2,712
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser/hooks/useDragAndDrop.tsx
|
import { useCallback } from 'react';
import { c, msgid } from 'ttag';
import { useDragMove } from '@proton/components';
import { CUSTOM_DATA_FORMAT } from '@proton/shared/lib/drive/constants';
import noop from '@proton/utils/noop';
import { DecryptedLink } from '../../../store';
import { selectMessageForItemList } from '../../sections/helpers';
import { DragMoveControls, FileBrowserBaseItem } from '../interface';
import { useSelection } from '../state/useSelection';
interface Options {
item: FileBrowserBaseItem;
dragMoveControls?: DragMoveControls;
}
function useDragAndDrop({ item, dragMoveControls }: Options) {
const selectionControls = useSelection();
// Timer for click and double click detection.
const dragMove = useDragMove({
dragging: dragMoveControls?.dragging ?? false,
setDragging: dragMoveControls?.setDragging ?? noop,
format: CUSTOM_DATA_FORMAT,
formatter: JSON.stringify,
});
const isDraggingSelected = dragMoveControls?.selectedItems.some(({ id }) => id === item.id);
const dragMoveItems = isDraggingSelected ? dragMoveControls!.selectedItems : [item];
const movingCount = dragMoveItems.length;
const texts = {
allFiles: c('Notification').ngettext(msgid`Move ${movingCount} file`, `Move ${movingCount} files`, movingCount),
allFolders: c('Notification').ngettext(
msgid`Move ${movingCount} folder`,
`Move ${movingCount} folders`,
movingCount
),
mixed: c('Notification').ngettext(msgid`Move ${movingCount} item`, `Move ${movingCount} items`, movingCount),
};
const moveText = selectMessageForItemList(
dragMoveItems.map((item) => (item as unknown as DecryptedLink).isFile),
texts
);
const unlessDisabled = <A extends any[], R>(fn?: (...args: A) => R) => (item.isLocked ? undefined : fn);
const handleDragStart = unlessDisabled(
useCallback(
(e: React.DragEvent<HTMLTableRowElement>) => {
if (!isDraggingSelected) {
selectionControls?.selectItem(item.id);
}
dragMove.handleDragStart(e);
},
[isDraggingSelected, dragMove.handleDragStart, selectionControls?.selectItem]
)
);
const handleDragEnd = useCallback(
(e) => {
e.currentTarget.blur();
dragMove.handleDragEnd();
},
[dragMove.handleDragEnd]
);
const draggable = dragMoveControls && !item.isLocked;
return {
dragMoveItems,
dragMove,
draggable,
itemHandlers: {
onDragEnd: handleDragEnd,
onDragEnter: unlessDisabled(dragMoveControls?.handleDragEnter),
onDragLeave: unlessDisabled(dragMoveControls?.handleDragLeave),
onDragOver: unlessDisabled(dragMoveControls?.handleDragOver),
onDragStart: handleDragStart,
onDrop: unlessDisabled(dragMoveControls?.handleDrop),
},
moveText,
};
}
export default useDragAndDrop;
| 2,713
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser/hooks/useFileBrowserCheckbox.ts
|
import { useCallback } from 'react';
import { useSelection } from '../state/useSelection';
export const useFileBrowserCheckbox = (id: string) => {
const selectionControls = useSelection();
const isSelected = Boolean(selectionControls?.isSelected(id));
const handleCheckboxChange = useCallback((e) => {
const el = document.activeElement ?? e.currentTarget;
if (isSelected && 'blur' in el) {
(el as any).blur();
}
}, []);
const handleCheckboxClick = useCallback(
(e) => {
if (!e.shiftKey) {
selectionControls?.toggleSelectItem(id);
}
},
[selectionControls?.toggleSelectItem]
);
const handleCheckboxWrapperClick = useCallback(
(e) => {
e.stopPropagation();
// Wrapper handles shift key, because FF has issues: https://bugzilla.mozilla.org/show_bug.cgi?id=559506
if (e.shiftKey) {
selectionControls?.toggleRange?.(id);
}
},
[selectionControls?.toggleRange]
);
return {
handleCheckboxChange,
handleCheckboxClick,
handleCheckboxWrapperClick,
};
};
| 2,714
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser/hooks/useFileBrowserItem.tsx
|
import { useCallback, useRef } from 'react';
import { BrowserItemId } from '../interface';
import { useSelection } from '../state/useSelection';
const DOUBLE_CLICK_MS = 500;
interface Options {
id: BrowserItemId;
isItemLocked?: boolean;
isMultiSelectionDisabled?: boolean;
onItemOpen?: (id: BrowserItemId) => void;
onItemContextMenu?: (e: React.MouseEvent<HTMLElement, MouseEvent>) => void;
}
function useFileBrowserItem({
id,
isItemLocked,
isMultiSelectionDisabled = false,
onItemContextMenu,
onItemOpen,
}: Options) {
const selection = useSelection();
// Timer for click and double click detection.
const clickTimerIdRef = useRef<NodeJS.Timeout | undefined>(undefined);
const touchStarted = useRef(false);
const isSelected = selection?.isSelected(id);
const unlessDisabled = <A extends any[], R>(fn?: (...args: A) => R) => (isItemLocked ? undefined : fn);
const handleClick = unlessDisabled(
useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
e.stopPropagation();
if (clickTimerIdRef.current) {
clearTimeout(clickTimerIdRef.current);
clickTimerIdRef.current = undefined;
if (id) {
onItemOpen?.(id);
}
} else {
// We do selection right away, not in timeout, because then
// would app look like slow. There is no harm to select
// items right away even if we navigate to different folder
// or show file preview in few miliseconds.
if (!id) {
return;
}
if (e.shiftKey && !isMultiSelectionDisabled) {
selection?.toggleRange(id);
} else if ((e.ctrlKey || e.metaKey) && !isMultiSelectionDisabled) {
selection?.toggleSelectItem(id);
} else {
selection?.selectItem(id);
}
clickTimerIdRef.current = setTimeout(() => {
clickTimerIdRef.current = undefined;
}, DOUBLE_CLICK_MS);
}
},
[selection?.toggleRange, selection?.toggleSelectItem, onItemOpen]
)
);
const handleKeyDown = unlessDisabled(
useCallback(
(e: React.KeyboardEvent<HTMLTableRowElement>) => {
if (e.key === ' ' || e.key === 'Enter') {
onItemOpen?.(id);
}
},
[onItemOpen]
)
);
const handleTouchStart = unlessDisabled(
useCallback(
(e: React.TouchEvent<HTMLTableRowElement>) => {
e.stopPropagation();
touchStarted.current = true;
},
[touchStarted]
)
);
const handleTouchCancel = unlessDisabled(
useCallback(() => {
if (touchStarted.current) {
touchStarted.current = false;
}
}, [touchStarted])
);
const handleTouchEnd = unlessDisabled(
useCallback(() => {
if (touchStarted.current) {
onItemOpen?.(id);
}
touchStarted.current = false;
}, [touchStarted, onItemOpen])
);
const onContextMenu = useCallback(
(e) => {
e.stopPropagation();
if (isItemLocked) {
return;
}
e.preventDefault();
if (!isSelected) {
selection?.selectItem(id);
}
onItemContextMenu?.(e);
},
[onItemContextMenu, selection?.selectItem, selection?.selectedItemIds]
);
const handleMouseDown = useCallback(() => document.getSelection()?.removeAllRanges(), []);
return {
isSelected,
itemHandlers: {
onTouchCancel: handleTouchCancel,
onTouchMove: handleTouchCancel,
onTouchStart: handleTouchStart,
onTouchEnd: handleTouchEnd,
onClick: handleClick,
onKeyDown: handleKeyDown,
onMouseDown: handleMouseDown,
onContextMenu,
},
};
}
export default useFileBrowserItem;
| 2,715
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser/hooks/useSelectionControls.test.ts
|
import { act, renderHook } from '@testing-library/react-hooks';
import { SelectionState, useSelectionControls } from './useSelectionControls';
const ALL_IDS = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
describe('useSelection', () => {
let hook: {
current: ReturnType<typeof useSelectionControls>;
};
let rerenderHook: (props?: unknown) => void;
let itemIds = ALL_IDS;
beforeEach(() => {
const { result, rerender } = renderHook(() => useSelectionControls({ itemIds }));
hook = result;
rerenderHook = rerender;
});
it('toggleSelectItem', () => {
const itemIdToToggle = '1';
const secondItemIdToToggle = '2';
act(() => {
hook.current.toggleSelectItem(itemIdToToggle);
});
expect(hook.current.selectedItemIds).toMatchObject([itemIdToToggle]);
// Select new item
rerenderHook();
act(() => {
hook.current.toggleSelectItem(secondItemIdToToggle);
});
expect(hook.current.selectedItemIds).toMatchObject([itemIdToToggle, secondItemIdToToggle]);
// Unselect items one by one
rerenderHook();
act(() => {
hook.current.toggleSelectItem(itemIdToToggle);
hook.current.toggleSelectItem(secondItemIdToToggle);
});
rerenderHook();
expect(hook.current.selectedItemIds).toMatchObject([]);
});
it('toggleAllSelected', () => {
act(() => {
hook.current.toggleAllSelected();
});
expect(hook.current.selectedItemIds).toMatchObject(ALL_IDS);
});
it('toggleRange', () => {
act(() => {
hook.current.selectItem('3');
});
act(() => {
hook.current.toggleRange('5');
});
expect(hook.current.selectedItemIds).toMatchObject(['3', '4', '5']);
});
it('toggleRange with no selectItem before', () => {
act(() => {
hook.current.toggleRange('5');
});
expect(hook.current.selectedItemIds).toMatchObject(['5']);
});
it('selectItem', () => {
act(() => {
hook.current.selectItem('1');
});
act(() => {
hook.current.selectItem('3');
});
expect(hook.current.selectedItemIds).toMatchObject(['3']);
});
it('clearSelection', () => {
act(() => {
hook.current.toggleAllSelected();
});
act(() => {
hook.current.clearSelections();
});
expect(hook.current.selectedItemIds).toMatchObject([]);
});
it('isSelected', () => {
act(() => {
hook.current.selectItem('2');
});
expect(hook.current.isSelected('2')).toBe(true);
expect(hook.current.isSelected('1')).toBe(false);
});
it('selectionState', () => {
act(() => {
hook.current.selectItem('2');
hook.current.selectItem('1');
});
expect(hook.current.selectionState).toBe(SelectionState.SOME);
act(() => {
hook.current.toggleAllSelected();
});
expect(hook.current.selectionState).toBe(SelectionState.ALL);
act(() => {
hook.current.toggleAllSelected();
});
expect(hook.current.selectionState).toBe(SelectionState.NONE);
});
it('should reset multiSelectedStartId on itemIds changes', () => {
act(() => {
hook.current.selectItem('3');
});
itemIds = ['10', '11', '12'];
rerenderHook();
act(() => {
hook.current.toggleRange('10');
});
expect(hook.current.selectedItemIds).toMatchObject(['10']);
});
});
| 2,716
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser/hooks/useSelectionControls.ts
|
import { useCallback, useEffect, useMemo, useState } from 'react';
import { BrowserItemId } from '../interface';
export enum SelectionState {
NONE,
ALL,
SOME,
}
export function useSelectionControls({ itemIds }: { itemIds: BrowserItemId[] }) {
const [selectedItemIds, setSelectedItems] = useState<BrowserItemId[]>([]);
const [multiSelectStartId, setMultiSelectStartId] = useState<BrowserItemId>();
const selectionState = useMemo(() => {
if (selectedItemIds.length === 0) {
return SelectionState.NONE;
}
if (selectedItemIds.length !== itemIds.length) {
return SelectionState.SOME;
}
return SelectionState.ALL;
}, [selectedItemIds, itemIds]);
useEffect(() => {
const isItemInFolder = (itemId: BrowserItemId) => itemIds.some((folderItemIds) => folderItemIds === itemId);
const selected = selectedItemIds.filter(isItemInFolder);
// If selected items were removed from children, remove them from selected as well
if (selectedItemIds.length !== selected.length) {
setSelectedItems(selected);
setMultiSelectStartId(undefined);
}
}, [itemIds, selectedItemIds]);
const toggleSelectItem = useCallback((id: BrowserItemId) => {
setSelectedItems((selectedItemIds) => {
const previousExcludingSelected = selectedItemIds.filter((itemId) => itemId !== id);
const isPreviouslySelected = previousExcludingSelected.length !== selectedItemIds.length;
if (!isPreviouslySelected || previousExcludingSelected.length) {
setMultiSelectStartId(id);
} else {
setMultiSelectStartId(undefined);
}
return isPreviouslySelected ? previousExcludingSelected : [...selectedItemIds, id];
});
}, []);
const toggleAllSelected = useCallback(() => {
setSelectedItems((ids) => (ids.length === itemIds.length ? [] : [...itemIds]));
setMultiSelectStartId(undefined);
}, [itemIds]);
const toggleRange = useCallback(
(selectedBrowserItemId: BrowserItemId) => {
// range between item matching selectedBrowserItemId and multiSelectStartId
if (!multiSelectStartId) {
setMultiSelectStartId(selectedBrowserItemId);
setSelectedItems([selectedBrowserItemId]);
return;
}
const selected: BrowserItemId[] = [];
let i = 0;
let matchConditions = [multiSelectStartId, selectedBrowserItemId];
while (matchConditions.length) {
const id = itemIds[i];
if (matchConditions.includes(id)) {
matchConditions = matchConditions.filter((itemId) => itemId !== id);
selected.push(id);
} else if (selected.length) {
selected.push(id);
}
i++;
}
setSelectedItems(selected);
},
[itemIds, multiSelectStartId]
);
const selectItem = useCallback(
(id: BrowserItemId) => {
// preventing same simple selection from happening to avoid re-rendering
if (selectedItemIds.length !== 1 || selectedItemIds[0] !== id) {
setSelectedItems([id]);
}
setMultiSelectStartId(id);
},
[selectedItemIds]
);
const clearSelections = useCallback(() => {
setSelectedItems([]);
setMultiSelectStartId(undefined);
}, []);
const isSelected = (itemId: BrowserItemId) => selectedItemIds.some((id) => id === itemId);
return {
selectedItemIds,
toggleSelectItem,
toggleAllSelected,
selectItem,
clearSelections,
toggleRange,
isSelected,
selectionState,
};
}
| 2,717
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser/state/index.tsx
|
import { FileBrowserItemContextMenuProvider } from './useItemContextMenu';
import { SelectionProvider } from './useSelection';
export const FileBrowserStateProvider = ({ itemIds, children }: { children: React.ReactNode; itemIds: string[] }) => {
return (
<SelectionProvider itemIds={itemIds}>
<FileBrowserItemContextMenuProvider>{children}</FileBrowserItemContextMenuProvider>
</SelectionProvider>
);
};
| 2,718
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser/state/useItemContextMenu.tsx
|
import React, { ReactNode, createContext, useContext } from 'react';
import { useContextMenuControls } from '../hooks/useContextMenuControls';
interface Controls {
isOpen: boolean;
handleContextMenu: (e: React.MouseEvent<Element>) => void;
handleContextMenuTouch: (e: React.TouchEvent<Element>) => void;
open: () => void;
close: () => void;
position:
| {
top: number;
left: number;
}
| undefined;
}
const FileBrowserItemContextMenuContext = createContext<Controls | null>(null);
interface Props {
children: ReactNode;
}
export function FileBrowserItemContextMenuProvider({ children }: Props) {
const contextMenuControls = useContextMenuControls();
return (
<FileBrowserItemContextMenuContext.Provider value={contextMenuControls}>
{children}
</FileBrowserItemContextMenuContext.Provider>
);
}
export function useItemContextMenu() {
const state = useContext(FileBrowserItemContextMenuContext);
if (!state) {
throw new Error('Trying to use uninitialized FileBrowserItemContextMenuProvider');
}
return state;
}
| 2,719
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FileBrowser/state/useSelection.tsx
|
import { ReactNode, createContext, useContext } from 'react';
import { SelectionState, useSelectionControls } from '../hooks/useSelectionControls';
import { BrowserItemId } from '../interface';
export interface Item<T = any> {
id: BrowserItemId;
data: T;
disabled?: boolean;
}
interface SelectionFunctions {
selectedItemIds: BrowserItemId[];
toggleSelectItem: (id: BrowserItemId) => void;
toggleAllSelected: () => void;
selectItem: (id: BrowserItemId) => void;
clearSelections: () => void;
toggleRange: (selectedBrowserItemId: BrowserItemId) => void;
isSelected: (linkId: string) => boolean;
selectionState: SelectionState;
}
const SelectionContext = createContext<SelectionFunctions | null>(null);
interface Props {
itemIds: string[];
children: ReactNode;
}
export function SelectionProvider({ itemIds, children }: Props) {
const selectionFunction = useSelectionControls({ itemIds });
return <SelectionContext.Provider value={selectionFunction}>{children}</SelectionContext.Provider>;
}
export function useSelection() {
const state = useContext(SelectionContext);
if (!state) {
return null;
}
return state;
}
| 2,720
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FolderTree/ExpandableRow.tsx
|
import React, { ReactNode, useRef } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { FileIcon, Icon, TableRowBusy, Tooltip } from '@proton/components';
import clsx from '@proton/utils/clsx';
import { DecryptedLink } from '../../store';
import FloatingEllipsis from './FloatingEllipsis';
interface Props {
link: DecryptedLink;
depth: number;
isDisabled?: boolean;
isSelected: boolean;
isExpanded: boolean;
isLoaded: boolean;
onSelect: (link: DecryptedLink) => void;
toggleExpand: (linkId: string) => void;
children?: ReactNode;
}
const ExpandableRow = ({
link,
depth,
isDisabled = false,
isSelected,
isExpanded,
isLoaded,
onSelect,
toggleExpand,
children,
}: Props) => {
const handleSelect = () => {
if (isDisabled) {
return;
}
onSelect(link);
};
const paddingElement = { width: `${depth * 1.5}em` };
const floatingEllipsisVisibilityControlRef = useRef<HTMLDivElement>(null);
return (
<>
<tr
className={clsx(['folder-tree-list-item', !isDisabled && 'cursor-pointer', isSelected && 'bg-strong'])}
onClick={handleSelect}
>
<td className="flex flex-align-items-center flex-nowrap m-0 pl-custom relative">
<div
className={clsx([
`folder-tree-list-item-selected flex flex-item-noshrink`,
!isSelected && 'folder-tree-list-item-selected-hidden',
])}
>
<span className="inline-flex bg-primary rounded-50 folder-tree-list-item-selected-check">
<Icon name="checkmark" className="p-1" size={16} />
</span>
</div>
<div className="flex flex-item-noshrink folder-tree-list-item-indent" style={paddingElement}></div>
<div className="folder-tree-list-item-expand flex-item-noshrink relative">
<Button
disabled={isDisabled}
style={{ visibility: link.isFile ? 'hidden' : 'visible' }}
className="folder-tree-list-item-expand-button increase-click-surface"
onClick={(e) => {
e.stopPropagation();
e.currentTarget.blur();
toggleExpand(link.linkId);
}}
>
<Icon
size={12}
name="chevron-down"
alt={isExpanded ? c('Action').t`Collapse` : c('Action').t`Expand`}
className={isExpanded ? 'rotateX-180' : undefined}
/>
</Button>
</div>
<div
key="Name"
className="folder-tree-list-item-name flex flex-align-items-center flex-nowrap w-full"
>
<FileIcon mimeType={link.isFile ? link.mimeType : 'Folder'} className="mr-2" />
<Tooltip title={link.name} originalPlacement="bottom">
<span ref={floatingEllipsisVisibilityControlRef} className="text-nowrap pr-8">
{link.name}
</span>
</Tooltip>
</div>
<FloatingEllipsis visibilityControlRef={floatingEllipsisVisibilityControlRef} />
</td>
</tr>
{isExpanded && (
<>
{children}
{!isLoaded && <TableRowBusy />}
</>
)}
</>
);
};
export default ExpandableRow;
| 2,721
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FolderTree/FloatingEllipsis.scss
|
@import '~@proton/styles/scss/lib';
.floating-ellipsis {
inline-size: 32px;
inset-inline-start: 0;
overflow: visible;
block-size: 100%;
background: linear-gradient(to right, transparent 0, var(--background-norm) 8px);
position: absolute;
opacity: 1;
z-index: $layer-notifications;
pointer-events: none;
transition: opacity 150ms ease-in;
&::after {
content: '\2026';
position: absolute;
inset-inline-end: 0;
padding-inline-end: 8px;
inset-block-start: 50%;
transform: translate(0, -50%);
}
&-hidden {
opacity: 0;
transition: opacity 150ms ease-in;
}
}
| 2,722
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FolderTree/FloatingEllipsis.tsx
|
import React, { useEffect, useRef } from 'react';
import { useFloatingEllipsisEventBasedUpdater } from './hooks';
const FloatingEllipsis = ({ visibilityControlRef }: { visibilityControlRef: React.RefObject<HTMLDivElement> }) => {
const elem = useRef<HTMLDivElement>(null);
const updateVisibility = useFloatingEllipsisEventBasedUpdater({
visibilityControlRef,
elem,
});
useEffect(() => {
updateVisibility();
}, []);
return <div className="floating-ellipsis floating-ellipsis-hidden" ref={elem}></div>;
};
export default FloatingEllipsis;
| 2,723
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FolderTree/FloatingEllipsisContext.ts
|
import { createContext } from 'react';
import { FloatingEllipsisContextValue } from './hooks';
export const FloatingEllipsisContext = createContext<FloatingEllipsisContextValue>({
events: new EventTarget(),
getDimensions: () => ({ scrollWidth: 0, scrollLeft: 0 }),
});
| 2,724
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FolderTree/FolderTree.scss
|
.folder-tree {
@extend .border;
@extend .scroll-if-needed;
border-radius: var(--border-radius-md);
block-size: 28em;
&-table {
inline-size: auto;
min-inline-size: 100%;
max-inline-size: initial;
}
&-list-item {
td {
padding-block: 0;
}
&-expand {
padding: 0.85em;
&-button {
@extend .button;
@extend .button-for-icon;
display: flex;
padding: 0;
}
}
}
&-list-item-indent {
padding: 0;
border: none;
margin: 0;
}
&-list-item-name {
min-inline-size: 10em;
box-sizing: content-box;
}
&-list-item-selected {
justify-content: center;
min-inline-size: 3em;
opacity: 1;
&-hidden {
opacity: 0;
}
&-check {
padding-block: 0.15em;
padding-inline: 0.15em 0;
}
}
}
| 2,725
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FolderTree/FolderTree.tsx
|
import React, { useRef } from 'react';
import { TableRowBusy } from '@proton/components';
import { DecryptedLink, TreeItem } from '../../store';
import ExpandableRow from './ExpandableRow';
import { FloatingEllipsisContext } from './FloatingEllipsisContext';
import useFloatingEllipsisContext from './hooks/useFloatingEllipsisContext';
interface Props {
treeItems: TreeItem | TreeItem[];
selectedItemId?: string;
onSelect: (link: DecryptedLink) => void;
rowIsDisabled?: (item: TreeItem) => boolean;
toggleExpand: (linkId: string) => void;
isLoaded: boolean;
}
const FolderTree = ({ isLoaded, treeItems, selectedItemId, onSelect, rowIsDisabled, toggleExpand }: Props) => {
const treeItemsArray = Array.isArray(treeItems) ? treeItems : [treeItems];
const containerRef = useRef<HTMLDivElement>(null);
const resizableRef = useRef<HTMLTableElement>(null);
const context = useFloatingEllipsisContext({ containerRef, resizableRef });
const generateRows = (items: TreeItem[], depth = 0) => {
const rows = items.map((item: TreeItem) => {
const { link, children, isExpanded, isLoaded } = item;
const isDisabled = rowIsDisabled ? rowIsDisabled(item) : false;
const childrenRows = children.length ? generateRows(children, depth + 1) : null;
return (
<ExpandableRow
key={link.linkId}
link={link}
isDisabled={isDisabled}
isSelected={selectedItemId === link.linkId}
isExpanded={isExpanded}
isLoaded={isLoaded}
depth={depth}
onSelect={onSelect}
toggleExpand={toggleExpand}
>
{childrenRows}
</ExpandableRow>
);
});
return <>{rows}</>;
};
const rows = generateRows(treeItemsArray);
return (
<FloatingEllipsisContext.Provider value={context}>
<div className="folder-tree" ref={containerRef}>
<table ref={resizableRef} className="folder-tree-table simple-table simple-table--is-hoverable ">
<tbody>{isLoaded ? rows : <TableRowBusy />}</tbody>
</table>
</div>
</FloatingEllipsisContext.Provider>
);
};
export default FolderTree;
| 2,726
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FolderTree
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FolderTree/hooks/index.ts
|
export * from './useFloatingEllipsisContext';
export * from './useFloatingEllipsisEventBasedUpdater';
| 2,727
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FolderTree
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FolderTree/hooks/useFloatingEllipsisContext.ts
|
import { RefObject, useEffect, useState } from 'react';
export type FloatingEllipsisEventType = 'resize' | 'scroll';
export interface FloatingEllipsisContextValue {
events: EventTarget;
getDimensions: () => FloatingEllipsisContainerDimensions;
}
export interface FloatingEllipsisContainerDimensions {
scrollWidth: number;
scrollLeft: number;
}
export const useFloatingEllipsisContext = ({
containerRef,
resizableRef,
}: {
containerRef: RefObject<HTMLDivElement>;
resizableRef?: RefObject<HTMLElement>;
}): FloatingEllipsisContextValue => {
const [events] = useState<EventTarget>(new EventTarget());
const getDimensions = (): FloatingEllipsisContainerDimensions => ({
scrollWidth: containerRef.current?.clientWidth ?? 0,
scrollLeft: containerRef.current?.scrollLeft ?? 0,
});
const [context] = useState<FloatingEllipsisContextValue>({
events,
getDimensions,
});
const triggerScroll = () => events.dispatchEvent(new Event('scroll' as FloatingEllipsisEventType));
const resizeObserver = new ResizeObserver(() => {
events.dispatchEvent(new Event('resize' as FloatingEllipsisEventType));
});
useEffect(() => {
if (!containerRef.current) {
return;
}
resizeObserver.observe(containerRef.current);
containerRef.current.addEventListener('scroll', triggerScroll);
if (resizableRef?.current) {
resizeObserver.observe(resizableRef.current);
}
return () => {
if (!containerRef.current) {
return;
}
resizeObserver.disconnect();
containerRef.current.removeEventListener('scroll', triggerScroll);
};
}, []);
return context;
};
export default useFloatingEllipsisContext;
| 2,728
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FolderTree
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/FolderTree/hooks/useFloatingEllipsisEventBasedUpdater.ts
|
import React, { useContext, useEffect } from 'react';
import { FloatingEllipsisContext } from '../FloatingEllipsisContext';
import { FloatingEllipsisContextValue, FloatingEllipsisEventType } from './useFloatingEllipsisContext';
const VISIBILITY_CLASS = 'floating-ellipsis-hidden';
export const useFloatingEllipsisEventBasedUpdater = ({
visibilityControlRef,
elem,
}: {
visibilityControlRef: React.RefObject<HTMLDivElement>;
elem: React.RefObject<HTMLDivElement>;
}): (() => void) => {
const { events, getDimensions } = useContext<FloatingEllipsisContextValue>(FloatingEllipsisContext);
const updateVisibility = () => {
if (!elem.current) {
return;
}
const { scrollWidth, scrollLeft } = getDimensions();
if (!visibilityControlRef.current) {
return;
}
const rightEnd = visibilityControlRef.current.offsetLeft + visibilityControlRef.current.offsetWidth;
const elemWidth = elem.current?.offsetWidth || 0;
const visible = rightEnd > scrollWidth + scrollLeft;
if (visible) {
elem.current.style.left = `${scrollWidth + scrollLeft - elemWidth}px`;
elem.current.classList.remove(VISIBILITY_CLASS);
} else {
elem.current.classList.add(VISIBILITY_CLASS);
}
};
useEffect(() => {
const eventTypes: FloatingEllipsisEventType[] = ['resize', 'scroll'];
eventTypes.forEach((eventType) => events.addEventListener(eventType, updateVisibility));
return () => {
eventTypes.forEach((eventType) => events.removeEventListener(eventType, updateVisibility));
};
}, [events]);
return updateVisibility;
};
export default useFloatingEllipsisEventBasedUpdater;
| 2,729
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/PortalPreview/PortalPreview.tsx
|
import { ReactNode, Ref, forwardRef, useMemo } from 'react';
import { c } from 'ttag';
import { ModalStateProps } from '@proton/components/components';
import { Portal } from '@proton/components/components/portal';
import { FilePreview } from '@proton/components/containers';
import { useFileView } from '../../store';
import { SignatureAlertBody } from '../SignatureAlert';
import SignatureIcon from '../SignatureIcon';
interface Props {
shareId: string;
linkId: string;
revisionId?: string;
date?: Date | string | number;
onDetails?: () => void;
onRestore?: () => void;
onShare?: () => void;
className?: string;
navigationControls?: ReactNode;
}
const PortalPreview = (
{
shareId,
linkId,
revisionId,
onDetails,
onRestore,
onShare,
date,
className,
navigationControls,
...modalProps
}: Props & ModalStateProps,
ref: Ref<HTMLDivElement>
) => {
const { contents, contentsMimeType, link, error, isLinkLoading, isContentLoading, downloadFile } = useFileView(
shareId,
linkId,
false,
revisionId
);
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]);
if (!modalProps.open) {
return null;
}
const showCachedThumbnail = revisionId === link?.activeRevision?.id;
return (
<Portal>
<div className={className}>
<FilePreview
imgThumbnailUrl={showCachedThumbnail ? link?.cachedThumbnailUrl : undefined}
isMetaLoading={isLinkLoading}
isLoading={isContentLoading}
error={error ? error.message || error.toString?.() || c('Info').t`Unknown error` : undefined}
fileName={link?.name}
mimeType={contentsMimeType}
fileSize={link?.size}
contents={contents}
onClose={() => {
modalProps.onClose();
modalProps.onExit();
}}
ref={ref}
onDownload={downloadFile}
onDetails={onDetails}
onRestore={onRestore}
onShare={onShare}
date={date}
navigationControls={navigationControls}
signatureStatus={signatureStatus}
signatureConfirmation={signatureConfirmation}
/>
</div>
</Portal>
);
};
export default forwardRef(PortalPreview);
| 2,730
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/PortalPreview/index.ts
|
export { default } from './PortalPreview';
| 2,731
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/ResolveLockedVolumes/LockedVolumesBanner.tsx
|
import { useEffect } from 'react';
import { c } from 'ttag';
import { InlineLinkButton, TopBanner } from '@proton/components';
import { useLoading } from '@proton/hooks';
import { useLockedVolume } from '../../store';
import { useFilesRecoveryModal } from '../modals/FilesRecoveryModal/FilesRecoveryModal';
import useResolveLockedSharesFlow from './KeyReactivation/useResolveLockedSharesFlow';
interface Props {
onClose: () => void;
}
const LockedVolumesBanner = ({ onClose }: Props) => {
const [filesRecoveryModal, showFilesRecoveryModal] = useFilesRecoveryModal();
const [loading, withLoading] = useLoading(true);
const { isReadyForPreparation, prepareVolumesForRestore, hasLockedVolumes, hasVolumesForRestore } =
useLockedVolume();
const {
openKeyReactivationModal,
keyReactivationModal,
deleteLockedVolumesConfirmModal,
unlockDriveConfirmationDialog,
} = useResolveLockedSharesFlow({
onSuccess: () => {
prepareVolumesForRestore(new AbortController().signal).catch(console.error);
},
onError: onClose,
});
useEffect(() => {
// Prepare volumes only if there are locked volumes already loaded
// so we dont set loading to false too soon in which case we would
// show banner about locked volumes for a brief moment before we
// display the final banner about option to recover files.
if (isReadyForPreparation) {
withLoading(prepareVolumesForRestore(new AbortController().signal)).catch(console.error);
}
}, [isReadyForPreparation, prepareVolumesForRestore]);
const StartRecoveryButton = (
<InlineLinkButton key="file-recovery-more" onClick={() => showFilesRecoveryModal()}>
{c('Info').t`More`}
</InlineLinkButton>
);
const KeyReactivationButton = (
<InlineLinkButton
key="key-reactivation"
onClick={openKeyReactivationModal}
data-testid="recovery-banner:key-reactivation-button"
>
{c('Info').t`Learn more`}
</InlineLinkButton>
);
const reactivateMessage = c('Info')
.jt`Your files are no longer accessible due to a password reset. Re-upload the old encryption key to regain the access. ${KeyReactivationButton}`;
const recoveryMessage = c('Info')
.jt`Some of your files are no longer accessible. Restore the access to your files. ${StartRecoveryButton}`;
return !loading && hasLockedVolumes ? (
<>
<TopBanner className="bg-danger" onClose={onClose}>
{hasVolumesForRestore ? recoveryMessage : reactivateMessage}
</TopBanner>
{filesRecoveryModal}
{keyReactivationModal}
{deleteLockedVolumesConfirmModal}
{unlockDriveConfirmationDialog}
</>
) : null;
};
export default LockedVolumesBanner;
| 2,732
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/ResolveLockedVolumes
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/ResolveLockedVolumes/FileRecovery/FileRecoveryIcon.tsx
|
import { c } from 'ttag';
import { Icon, Tooltip, useModalTwo } from '@proton/components';
import { useLockedVolume } from '../../../store';
import FilesRecoveryModal from '../../modals/FilesRecoveryModal/FilesRecoveryModal';
interface Props {
className?: string;
}
const FileRecoveryIcon = ({ className }: Props) => {
const [fileRecoveryModal, showFileRecoveryModal] = useModalTwo(FilesRecoveryModal);
const { hasVolumesForRestore } = useLockedVolume();
return hasVolumesForRestore ? (
<>
<Tooltip title={c('Title').t`You have inaccessible files`}>
<Icon
color="red"
name="fire"
className={className}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
void showFileRecoveryModal({});
}}
/>
</Tooltip>
{fileRecoveryModal}
</>
) : null;
};
export default FileRecoveryIcon;
| 2,733
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/ResolveLockedVolumes
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/ResolveLockedVolumes/KeyReactivation/interfaces.tsx
|
export enum LockedVolumeResolveMethod {
ResolveMethodSelection,
DeleteOldFiles,
UnlockLater,
ReactivateKeys,
}
| 2,734
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/ResolveLockedVolumes
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/ResolveLockedVolumes/KeyReactivation/useResolveLockedSharesFlow.tsx
|
import { useRef } from 'react';
import { c } from 'ttag';
import { useNotifications } from '@proton/components';
import { useLockedVolume } from '../../../store';
import { useDeleteLockedVolumesConfirmModal } from '../../modals/DeleteLockedVolumesConfirmModal';
import { useKeyReactivationModal } from '../../modals/KeyReactivationModal';
import { useUnlockDriveConfirmationDialog } from '../../modals/UnlockDriveConfirmationDialog';
import { LockedVolumeResolveMethod } from './interfaces';
interface ReactivationParams {
onSuccess?: () => void;
onError?: () => void;
}
const useResolveLockedSharesFlow = ({ onSuccess, onError }: ReactivationParams) => {
const lastResolveMethod = useRef<LockedVolumeResolveMethod>(LockedVolumeResolveMethod.ReactivateKeys);
const { lockedVolumesCount, deleteLockedVolumes } = useLockedVolume();
const [keyReactivationModal, showKeyReactivationModal] = useKeyReactivationModal();
const [deleteLockedVolumesConfirmModal, showDeleteLockedVolumesConfirmModal] = useDeleteLockedVolumesConfirmModal();
const [unlockDriveConfirmationDialog, showUnlockDriveConfirmationDialog] = useUnlockDriveConfirmationDialog();
const { createNotification } = useNotifications();
const handleDeleteLockedVolumesSubmit = async () => {
try {
await deleteLockedVolumes();
createNotification({
text: c('Notification').t`Your old files will be deleted in 72 hours`,
});
onSuccess?.();
} catch (e) {
onError?.();
}
};
const handleResolveMethodSelection = (type: LockedVolumeResolveMethod) => {
switch (type) {
case LockedVolumeResolveMethod.ResolveMethodSelection:
void showKeyReactivationModal({
onSubmit: handleResolveMethodSelection,
defaultResolveMethod: lastResolveMethod.current,
volumeCount: lockedVolumesCount,
});
break;
case LockedVolumeResolveMethod.DeleteOldFiles:
void showDeleteLockedVolumesConfirmModal({
onSubmit: handleDeleteLockedVolumesSubmit,
volumeCount: lockedVolumesCount,
});
break;
case LockedVolumeResolveMethod.ReactivateKeys:
void showUnlockDriveConfirmationDialog();
break;
case LockedVolumeResolveMethod.UnlockLater:
onSuccess?.();
break;
default:
break;
}
};
const openKeyReactivationModal = () => {
void handleResolveMethodSelection(LockedVolumeResolveMethod.ResolveMethodSelection);
};
return {
openKeyReactivationModal,
keyReactivationModal,
deleteLockedVolumesConfirmModal,
unlockDriveConfirmationDialog,
};
};
export default useResolveLockedSharesFlow;
| 2,735
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage/LoadingPage.tsx
|
import { c } from 'ttag';
import { LoaderPage } from '@proton/components';
import SharedPageLayout from './Layout/SharedPageLayout';
export default function LoadingPage() {
return (
<SharedPageLayout>
<div className="flex flex-column flex-align-items-center flex-justify-center w-full h-full">
<LoaderPage text={c('Info').t`Decrypting files`} />
</div>
</SharedPageLayout>
);
}
| 2,736
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage/SharedFilePage.tsx
|
import { c } from 'ttag';
import { FilePreviewContent } from '@proton/components/containers/filePreview/FilePreview';
import { useActiveBreakpoint } from '@proton/components/hooks';
import { DecryptedLink } from '../../store';
import { usePublicFileView } from '../../store/_views/useFileView';
import { FileBrowserStateProvider } from '../FileBrowser';
import { useUpsellFloatingModal } from '../modals/UpsellFloatingModal';
import Breadcrumbs from './Layout/Breadcrumbs';
import HeaderSecureLabel from './Layout/HeaderSecureLabel';
import HeaderSize from './Layout/HeaderSize';
import SharedPageFooter from './Layout/SharedPageFooter';
import SharedPageHeader from './Layout/SharedPageHeader';
import SharedPageLayout from './Layout/SharedPageLayout';
interface Props {
token: string;
link: DecryptedLink;
}
export default function SharedFilePage({ token, link }: Props) {
const { isLinkLoading, isContentLoading, error, contents, downloadFile } = usePublicFileView(token, link.linkId);
const [renderUpsellFloatingModal] = useUpsellFloatingModal();
const { isNarrow } = useActiveBreakpoint();
return (
<FileBrowserStateProvider itemIds={[link.linkId]}>
<SharedPageLayout
FooterComponent={<SharedPageFooter rootItem={link} items={[{ id: link.linkId, ...link }]} />}
>
<SharedPageHeader rootItem={link} items={[{ id: link.linkId, ...link }]} className="mt-3 mb-4">
<div className="w-full flex flex-align-items-center">
<Breadcrumbs
token={token}
name={link.name}
linkId={link.linkId}
className="w-full lg:w-auto shared-folder-header-breadcrumbs pb-1"
/>
<div className="flex flex-item-fluid-auto lg:flex-row-reverse lg:flex-item-fluid">
<HeaderSecureLabel className="lg:ml-auto" />
{link.size ? <HeaderSize size={link.size} /> : null}
</div>
</div>
</SharedPageHeader>
<FilePreviewContent
isMetaLoading={isLinkLoading}
isLoading={isContentLoading}
onDownload={!isNarrow ? downloadFile : undefined}
error={error ? error.message || error.toString?.() || c('Info').t`Unknown error` : undefined}
contents={contents}
fileName={link?.name}
mimeType={link?.mimeType}
fileSize={link?.size}
imgThumbnailUrl={link?.cachedThumbnailUrl}
/>
</SharedPageLayout>
{renderUpsellFloatingModal}
</FileBrowserStateProvider>
);
}
| 2,737
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage/index.ts
|
export { default as ErrorPage } from './SharedPageError';
export { default as LoadingPage } from './LoadingPage';
export { default as PasswordPage } from './PasswordPage';
export { default as SharedFilePage } from './SharedFilePage';
export { default as SharedFolderPage } from './SharedFolderPage/SharedFolderPage';
| 2,738
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage/interface.ts
|
import { DecryptedLink } from '../../store';
export interface PublicLink extends DecryptedLink {
id: string;
progress?: {
total?: number;
progress: number;
percent: number;
isFinished: boolean;
};
}
| 2,739
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage/Layout/Breadcrumbs.tsx
|
import { useEffect, useState } from 'react';
import { CollapsingBreadcrumbs } from '@proton/components';
import { BreadcrumbInfo } from '@proton/components/components/collapsingBreadcrumbs/interfaces';
import clsx from '@proton/utils/clsx';
import { useLinkPathPublic } from '../../../store/_views/useLinkPath';
interface Props {
token: string;
name: string;
linkId: string;
onNavigate?: (linkId: string) => void;
className?: string;
}
export default function Breadcrumbs({ token, name, linkId, onNavigate, className }: Props) {
const { traverseLinksToRoot } = useLinkPathPublic(); // TODO: Get data using usePublicFolderView instead one day.
const defaultBreadcrumbs: BreadcrumbInfo[] = [
{
key: 'default',
title: name,
text: name,
noShrink: true,
},
];
const [breadcrumbs, setBreadcrumbs] = useState(defaultBreadcrumbs);
useEffect(() => {
const abortController = new AbortController();
traverseLinksToRoot(abortController.signal, token, linkId)
.then((pathItems) => {
const breadcrumbs = pathItems.map((item) => {
const breadcrumb: BreadcrumbInfo = {
key: item.linkId,
text: item.name,
collapsedText: item.name,
onClick: item.linkId === linkId || !onNavigate ? undefined : () => onNavigate(item.linkId),
};
return breadcrumb;
});
setBreadcrumbs(breadcrumbs);
})
.catch((err: any) => {
if (err.name !== 'AbortError') {
console.warn(err);
setBreadcrumbs(defaultBreadcrumbs);
}
});
return () => {
abortController.abort();
};
}, [traverseLinksToRoot, onNavigate, token, linkId]);
return <CollapsingBreadcrumbs breadcrumbs={breadcrumbs} className={clsx(['text-4xl', className])} />;
}
| 2,740
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage/Layout/DownloadButton.tsx
|
import { useEffect, useState } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { Icon } from '@proton/components';
import clsx from '@proton/utils/clsx';
import usePublicToken from '../../../hooks/drive/usePublicToken';
import { DecryptedLink, useDownload } from '../../../store';
import { isTransferActive, isTransferPaused } from '../../../utils/transfer';
import { useSelection } from '../../FileBrowser';
import { getSelectedItems } from '../../sections/helpers';
import { PublicLink } from '../interface';
import { useDownloadNotifications } from './useDownloadNotifications';
export interface DownloadButtonProps {
rootItem: DecryptedLink;
items: PublicLink[];
className?: string;
}
export function DownloadButton({ items, className, rootItem }: DownloadButtonProps) {
const [downloadedSize, setDownloadedSize] = useState<number>(0);
const [totalSize, setTotalSize] = useState<number>(0);
const { token } = usePublicToken();
const selectionControls = useSelection();
const { downloads, download, clearDownloads, getDownloadsLinksProgresses } = useDownload();
useDownloadNotifications(downloads);
const selectedItems = getSelectedItems(items || [], selectionControls?.selectedItemIds || []);
const count = selectedItems.length;
const handleDownload = () => {
// To keep always only one download around.
clearDownloads();
const downloadLinks = selectedItems.length
? selectedItems.map((link) => ({ ...link, shareId: token }))
: [{ ...rootItem, shareId: token }];
void download(downloadLinks);
};
const isDownloading = downloads.some((transfer) => isTransferActive(transfer) || isTransferPaused(transfer));
const updateProgress = () => {
const downloadLinksProgresses = getDownloadsLinksProgresses();
// In case of "Download all" (which has no selected item) from folder
// share, the top folder is included in progresses as well which needs
// to be excluded to not count progress twice. But in case of file
// share the root item must be included otherwise no progress would
// be tracked.
const progressInfo = Object.entries(downloadLinksProgresses).reduce(
(previousValue, [linkId, { progress, total }]) => {
if (
(linkId !== rootItem.linkId || Object.keys(downloadLinksProgresses).length === 1) &&
total !== undefined
) {
return {
progress: previousValue.progress + progress,
total: previousValue.total + total!,
};
} else {
return previousValue;
}
},
{
progress: 0,
total: 0,
}
);
setDownloadedSize(progressInfo.progress);
setTotalSize(progressInfo.total);
};
// Enrich link date with download progress. Downloads changes only when
// status changes, not the progress, so if download is active, it needs
// to run in interval until download is finished.
useEffect(() => {
updateProgress();
if (!downloads.some(isTransferActive)) {
// Progresses are not handled by state and might be updated
// without notifying a bit after downloads state is changed.
const id = setTimeout(updateProgress, 500);
return () => {
clearTimeout(id);
};
}
const id = setInterval(updateProgress, 500);
return () => {
clearInterval(id);
};
}, [downloads]);
useEffect(() => {
if (isDownloading === false && Boolean(totalSize)) {
setTotalSize(0);
setDownloadedSize(0);
}
}, [isDownloading]);
let idleText: string;
if (rootItem.isFile) {
idleText = c('Action').t`Download`;
} else {
idleText = count ? c('Action').t`Download (${count})` : c('Action').t`Download all`;
}
const percentageValue = totalSize !== 0 ? Math.round((100 * downloadedSize) / totalSize) : 0;
const inProgressText = c('Label').jt`Downloading ${percentageValue}%`;
return (
<Button
className={clsx(['flex-item-centered-vert', className])}
color="norm"
onClick={handleDownload}
loading={isDownloading}
>
{isDownloading ? inProgressText : idleText}
{!isDownloading ? <Icon name="arrow-down-line" className="ml-2" /> : null}
</Button>
);
}
| 2,741
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage/Layout/HeaderSecureLabel.tsx
|
import { c } from 'ttag';
import { Icon } from '@proton/components/components';
import clsx from '@proton/utils/clsx';
interface Props {
className?: string;
}
const HeaderSecureLabel = ({ className }: Props) => (
<div className={clsx('color-success flex flex-row flex-align-center', className)}>
<Icon name="lock-open-check-filled" className="mr-2" />
<span className="encryption-block-text">{c('Info').t`End-to-end encrypted`}</span>
</div>
);
export default HeaderSecureLabel;
| 2,742
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage/Layout/HeaderSize.tsx
|
import { shortHumanSize } from '@proton/shared/lib/helpers/humanSize';
interface Props {
size: number;
}
const HeaderSize = ({ size }: Props) => {
const readableSize = shortHumanSize(size);
return (
<div>
<span className="color-disabled mx-2">•</span>
<span className="color-weak text-pre">{readableSize}</span>
</div>
);
};
export default HeaderSize;
| 2,743
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage/Layout/Layout.scss
|
@import '~@proton/styles/scss/lib';
.shared-page-layout {
&-loader {
color: var(--primary);
}
&-container {
inline-size: 95vw;
margin-inline: auto;
border-radius: var(--border-radius-lg);
min-block-size: rem(315); // To fit exactly 4 items on different screens before its expanded.
padding-block-end: 2em;
@include media('>small') {
padding-block-end: 3em;
}
@include media('>1230px') {
padding-block-end: 0;
}
}
&-encryption-block-text {
color: var(--signal-success);
}
}
.shared-folder-empty-placeholder-container {
position: relative;
padding-block-start: rem(38);
}
.shared-folder-empty-placeholder-text {
max-inline-size: rem(380);
}
.collapsing-breadcrumbs.shared-folder-header-breadcrumbs {
margin-inline-start: -0.25em;
}
| 2,744
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage/Layout/ReportAbuseButton.tsx
|
import React from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms/Button';
import { Icon, Tooltip, useModalTwo } from '@proton/components';
import { usePublicShare } from '../../../store';
import ReportAbuseModal from '../../modals/ReportAbuseModal/ReportAbuseModal';
import { LinkInfo } from '../../modals/ReportAbuseModal/types';
interface Props {
linkInfo: LinkInfo;
className?: string;
}
export default function ReportAbuseButton({ linkInfo, className }: Props) {
const [reportAbuseModal, showReportAbuseModal] = useModalTwo(ReportAbuseModal);
const { submitAbuseReport } = usePublicShare();
return (
<>
<Tooltip title={c('Action').t`Report an issue`}>
<Button
shape="solid"
size="medium"
color="weak"
data-testid="report-abuse-button"
className={className}
icon
onClick={() => showReportAbuseModal({ linkInfo, onSubmit: submitAbuseReport })}
>
<Icon className="color-weak" name="flag-filled" alt={c('Action').t`Report an issue`} />
</Button>
</Tooltip>
{reportAbuseModal}
</>
);
}
| 2,745
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage/Layout/SharedPageFooter.tsx
|
import { useActiveBreakpoint } from '@proton/components/hooks';
import { DownloadButton, DownloadButtonProps } from './DownloadButton';
import ReportAbuseButton from './ReportAbuseButton';
interface Props extends DownloadButtonProps {}
const SharedPageFooter = ({ rootItem, items }: Props) => {
const { isNarrow } = useActiveBreakpoint();
if (isNarrow && items.length > 0) {
return (
<div className="fixed bottom p-4 flex flex-justify-center bg-weak w-full">
<DownloadButton className="flex-item flex-item-fluid" rootItem={rootItem} items={items} />
</div>
);
}
return <ReportAbuseButton className="ml-1 mb-4 fixed left bottom" linkInfo={rootItem} />;
};
export default SharedPageFooter;
| 2,746
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage/Layout/SharedPageHeader.tsx
|
import { useActiveBreakpoint } from '@proton/components/hooks';
import clsx from '@proton/utils/clsx';
import { DownloadButton, DownloadButtonProps } from './DownloadButton';
interface Props extends DownloadButtonProps {
children: React.ReactNode;
className?: string;
}
export default function SharedPageHeader({ children, rootItem, items, className }: Props) {
const { isNarrow } = useActiveBreakpoint();
return (
<div className={clsx('flex flex-nowrap flex-justify-space-between flex-align-items-center', className)}>
<div className="flex flex-nowrap flex-item-fluid flex-align-items-center mb-0 pb-0 mr-4 shared-page-layout-header">
{children}
</div>
{isNarrow || items.length === 0 ? null : <DownloadButton rootItem={rootItem} items={items} />}
</div>
);
}
| 2,747
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage/Layout/SharedPageLayout.tsx
|
import React from 'react';
import { c } from 'ttag';
import { ButtonLike } from '@proton/atoms';
import { Header, MainLogo, UnAuthenticated, UnAuthenticatedAppsDropdown, useConfig } from '@proton/components';
import Footer from '@proton/components/components/footer/Footer';
import { IS_PROTON_USER_COOKIE_NAME } from '@proton/components/hooks/useIsProtonUserCookie';
import { getAppName } from '@proton/shared/lib/apps/helper';
import { APPS } from '@proton/shared/lib/constants';
import { DRIVE_PRICING_PAGE } from '@proton/shared/lib/drive/urls';
import { getCookie } from '@proton/shared/lib/helpers/cookies';
import clsx from '@proton/utils/clsx';
import './Layout.scss';
interface Props {
FooterComponent?: React.ReactNode;
children: React.ReactNode;
className?: string;
}
export default function SharedPageLayout({ FooterComponent, children, className }: Props) {
const { APP_NAME } = useConfig();
// This does not allow to get any user information but allow us to know if the user was already logged in Proton
const isProtonUser = !!getCookie(IS_PROTON_USER_COOKIE_NAME);
const containerClassname = clsx([
'shared-page-layout-bg flex-no-min-children flex-nowrap flex-column h-full scroll-if-needed relative',
className,
]);
return (
<UnAuthenticated>
<div className={containerClassname}>
<Header className="shadow-norm flex flex-align-items-center">
<h1 className="sr-only">{getAppName(APP_NAME)}</h1>
<div className="logo-container flex flex-justify-space-between flex-align-items-center flex-nowrap">
<MainLogo to="/" />
<UnAuthenticatedAppsDropdown />
</div>
<div className="flex flex-justify-end flex-item-fluid flex-item-centered-vert">
{isProtonUser ? (
<ButtonLike color="norm" as="a" href={APPS.PROTONDRIVE} target="_blank">
{c('Action').t`Go to Drive`}
</ButtonLike>
) : (
<ButtonLike color="norm" as="a" href={DRIVE_PRICING_PAGE} target="_blank">
{c('Action').t`Try for free`}
</ButtonLike>
)}
</div>
</Header>
<main
className={clsx([
'shared-page-layout-container flex flex-no-min-children flex-nowrap on-mobile-flex-column',
'flex-item-fluid',
])}
>
<div className="flex-item-fluid mb-4 md:mb-0 flex flex-column flex-nowrap">{children}</div>
</main>
<Footer className="flex-justify-space-between flex-align-items-center p-0 mt-6 md:mt-0">
{FooterComponent}
</Footer>
</div>
</UnAuthenticated>
);
}
| 2,748
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage/Layout/useDownloadNotifications.tsx
|
import { useEffect } from 'react';
import { c } from 'ttag';
import { NotificationType, useNotifications } from '@proton/components';
import {
isTransferCanceled,
isTransferDone,
isTransferFailed,
isTransferPausedByConnection,
} from '../../../utils/transfer';
import { Download } from '../../TransferManager/transfer';
export function useDownloadNotifications(downloads: Download[]) {
const { createNotification, hideNotification } = useNotifications();
let type: NotificationType = 'info';
let text: string | undefined;
let expiration: number | undefined = -1;
let showCloseButton = false;
if (downloads.some(isTransferPausedByConnection)) {
type = 'warning';
text = c('Info').t`Download paused due to connection issue; it will resume automatically`;
}
if (downloads.some(isTransferDone)) {
text = c('Info').t`Download finished`;
expiration = undefined;
showCloseButton = true;
}
if (downloads.some(isTransferFailed)) {
type = 'error';
const error = downloads[0].error;
if (error) {
text = c('Info').t`Download failed due to ${error}`;
} else {
text = c('Info').t`Download failed`;
}
showCloseButton = true;
}
if (downloads.some(isTransferCanceled)) {
type = 'warning';
text = c('Info').t`Download canceled`;
expiration = 5000;
showCloseButton = true;
}
useEffect(() => {
if (!text) {
return;
}
const notificationId = createNotification({
type,
text,
expiration,
showCloseButton,
});
return () => {
hideNotification(notificationId);
};
}, [type, text]);
}
| 2,749
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage/PasswordPage/PasswordPage.scss
|
.password-page--icon-container {
background: var(--interaction-norm-minor-1);
}
| 2,750
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage/PasswordPage/PasswordPage.tsx
|
import { FormEvent, useState } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { Icon, InputFieldTwo, PasswordInputTwo } from '@proton/components';
import { useLoading } from '@proton/hooks';
import SharedPageLayout from '../Layout/SharedPageLayout';
import './PasswordPage.scss';
interface Props {
submitPassword: (password: string) => Promise<void>;
}
export default function PasswordPage({ submitPassword }: Props) {
const [loading, withLoading] = useLoading(false);
const [password, setPassword] = useState('');
const handlePasswordSubmit = (e: FormEvent) => {
e.preventDefault();
void withLoading(submitPassword(password));
};
return (
<SharedPageLayout>
<div className="flex flex-item-fluid flex-align-items-center py-7 mb-14">
<div
className="password-page--form-container ui-standard w-full relative shadow-lifted max-w-custom mx-auto px-8 py-11 rounded"
style={{ '--max-w-custom': '30rem' }}
>
<div className="flex flex-justify-center pb-7">
<span className="password-page--icon-container rounded p-4">
<Icon name="key-skeleton" className="color-primary" size={28} />
</span>
</div>
<h3 className="text-center text-bold mb-2">{c('Title').t`This link is password protected`}</h3>
<p className="text-center mt-0">{c('Info')
.t`Please enter the password to decrypt and view content.`}</p>
<form className="w-full mt-8" autoComplete="off" onSubmit={handlePasswordSubmit}>
<div className="mt-4 mb-8">
<InputFieldTwo
bigger
as={PasswordInputTwo}
label={c('Label').t`Password`}
autoComplete="off"
id="password"
disabled={loading}
value={password}
onValue={setPassword}
placeholder={c('Info').t`Enter password`}
assistiveText={c('Info').t`Link owner has the password`}
/>
</div>
<Button
size="large"
fullWidth
color="norm"
disabled={!password}
loading={loading}
type="submit"
>
{c('Action').t`Continue`}
</Button>
</form>
</div>
</div>
</SharedPageLayout>
);
}
| 2,751
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage/PasswordPage/index.ts
|
export { default } from './PasswordPage';
| 2,752
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage/SharedFolderPage/CellComponents.tsx
|
import { c } from 'ttag';
import { Button } from '@proton/atoms/Button';
import { FileIcon, Icon, TableCell, useActiveBreakpoint } from '@proton/components';
import clsx from '@proton/utils/clsx';
import usePublicToken from '../../../hooks/drive/usePublicToken';
import { useDownload } from '../../../store';
import { isTransferActive, isTransferPaused } from '../../../utils/transfer';
import { Cells, HeaderCellsPresets } from '../../FileBrowser';
import { getLinkIconText } from '../../sections/FileBrowser/utils';
import { PublicLink } from '../interface';
export const headerCellsDesktop = [
{
type: HeaderCellsPresets.Checkbox,
},
{
type: 'name',
getText: () => c('Label').t`Name`,
sorting: true,
},
{
type: 'size',
getText: () => c('Label').t`Size`,
props: {
className: 'w-custom text-right',
style: { '--w-custom': '11em' },
},
sorting: true,
},
{
type: HeaderCellsPresets.Placeholder,
props: {
className: 'w-custom',
style: { '--w-custom': '11em' },
},
},
];
export const headerCellsMobile = headerCellsDesktop.slice(0, -1);
export const contentCellsDesktop: React.FC<{ item: PublicLink }>[] = [
Cells.CheckboxCell,
NameCell,
SizeCell,
DownloadCell,
];
export const contentCellsMobile = contentCellsDesktop.slice(0, -1);
function NameCell({ item }: { item: PublicLink }) {
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" />
)}
<Cells.NameCell name={item.name} />
</TableCell>
);
}
function SizeCell({ item }: { item: PublicLink }) {
const { isNarrow } = useActiveBreakpoint();
if (item.progress) {
return (
<TableCell
className="m-0 w-custom flex flex-nowrap flex-justify-end"
style={{ '--w-custom': '11em' }}
data-testid="column-size"
>
{!isNarrow && item.progress.progress > 0 && (
<>
<Cells.SizeCell size={item.progress.progress} />/
</>
)}
{item.progress.total !== undefined ? <Cells.SizeCell size={item.progress.total} /> : '-'}
</TableCell>
);
}
const styleValue = isNarrow ? '6em' : '11em';
return (
<TableCell
className="m-0 flex flex-nowrap flex-justify-end w-custom"
style={{ '--w-custom': styleValue }}
data-testid="column-size"
>
{item.isFile ? <Cells.SizeCell size={item.size} /> : '-'}
</TableCell>
);
}
function DownloadCell({ item }: { item: PublicLink }) {
const { token } = usePublicToken();
const { download, downloads, clearDownloads } = useDownload();
const isCurrentInProgress = Boolean(item.progress);
const handleClick = () => {
clearDownloads();
void download([{ ...item, shareId: token }]);
};
const isAnyInProgress = downloads.some((transfer) => isTransferActive(transfer) || isTransferPaused(transfer));
const className = clsx([
'flex-item-centered-vert ',
'file-browser-list--download-button',
'mouse:group-hover:opacity-100',
]);
return (
<TableCell
className="m-0 flex flex-nowrap flex-justify-end file-browser-list--icon-column w-custom"
style={{ '--w-custom': '11em' }}
data-testid="column-size"
>
<Button
className={className}
shape="ghost"
size="small"
onClick={handleClick}
loading={isCurrentInProgress}
disabled={isAnyInProgress && !isCurrentInProgress}
>
<span>{c('Action').t`Download`}</span>
{!isCurrentInProgress ? <Icon name="arrow-down-line" className="ml-2" /> : null}
</Button>
</TableCell>
);
}
| 2,753
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage/SharedFolderPage/EmptyPlaceholder.tsx
|
import { c } from 'ttag';
import { ButtonLike } from '@proton/atoms/Button';
import { EmptyViewContainer } from '@proton/components';
import { DRIVE_APP_NAME } from '@proton/shared/lib/constants';
import { DRIVE_LANDING_PAGE } from '@proton/shared/lib/drive/urls';
import noContentSvg from '@proton/styles/assets/img/illustrations/shared-page-empty-list.svg';
export const EmptyPlaceholder = () => (
<div className="flex flex-item-fluid flex-justify-center shared-folder-empty-placeholder-container">
<EmptyViewContainer
className="p-4"
imageProps={{ src: noContentSvg, title: c('Info').t`Nothing here yet` }}
data-testid="shared-folder-empty-placeholder"
>
<h3 className="text-bold">{c('Info').t`Nothing here yet`}</h3>
<p className="color-hint shared-folder-empty-placeholder-text">
{c('Info').t`Need to share a file? Then get ${DRIVE_APP_NAME},
the safest way to share, store, and sync your files.`}
</p>
<div className="flex flex-justify-center">
<ButtonLike color="norm" shape="outline" as="a" href={DRIVE_LANDING_PAGE} target="_blank">
{c('Action').t`Get ${DRIVE_APP_NAME}`}
</ButtonLike>
</div>
</EmptyViewContainer>
</div>
);
| 2,754
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage/SharedFolderPage/FileBrowser.scss
|
@import '~@proton/styles/scss/lib';
.shared-url-file-browser {
overflow: hidden;
@include media('<=small') {
margin-inline: -2.5vw;
}
}
.flex .shared-url-file-browser {
flex: 1;
}
@media (hover: hover) and (pointer: fine) {
.mouse\:group-hover\:opacity-100.file-browser-list--download-button[disabled] {
opacity: 0;
}
}
| 2,755
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage/SharedFolderPage/FileBrowser.tsx
|
import { useCallback } from 'react';
import { useActiveBreakpoint } from '@proton/components/hooks';
import { LayoutSetting } from '@proton/shared/lib/interfaces/drive/userSettings';
import clsx from '@proton/utils/clsx';
import usePublicToken from '../../../hooks/drive/usePublicToken';
import { DecryptedLink, useThumbnailsDownload } from '../../../store';
import { SortField } from '../../../store/_views/utils/useSorting';
import FileBrowser, { BrowserItemId, SortParams } from '../../FileBrowser';
import { PublicLink } from '../interface';
import { contentCellsDesktop, contentCellsMobile, headerCellsDesktop, headerCellsMobile } from './CellComponents';
import { EmptyPlaceholder } from './EmptyPlaceholder';
import './FileBrowser.scss';
interface Props {
folderName: string;
items: PublicLink[];
isLoading?: boolean;
sortParams?: SortParams<SortField>;
setSorting?: (params: SortParams<SortField>) => void;
onItemOpen?: (item: DecryptedLink) => void;
}
export default function SharedFileBrowser({ folderName, items, isLoading, sortParams, setSorting, onItemOpen }: Props) {
const { isNarrow } = useActiveBreakpoint();
const thumbnails = useThumbnailsDownload();
const { token } = usePublicToken();
const handleItemOpen = useCallback(
(id: BrowserItemId) => {
const item = items.find((item) => item.linkId === id);
if (!item) {
return;
}
onItemOpen?.(item);
},
[items]
);
const contentCells = isNarrow ? contentCellsMobile : contentCellsDesktop;
const headerCells = isNarrow ? headerCellsMobile : headerCellsDesktop;
const classname = clsx(['flex flex-column flex-nowrap shared-url-file-browser', isNarrow && 'flex-item-fluid']);
const isListEmpty = items.length === 0 && !isLoading;
const handleItemRender = (item: DecryptedLink) => {
if (item.hasThumbnail && item.activeRevision && !item.cachedThumbnailUrl) {
thumbnails.addToDownloadQueue(token, item.linkId, item.activeRevision.id);
}
};
return (
<div className={classname}>
{isListEmpty ? (
<EmptyPlaceholder />
) : (
<FileBrowser
caption={folderName}
headerItems={headerCells}
items={items}
layout={LayoutSetting.List}
loading={isLoading}
sortParams={sortParams}
Cells={contentCells}
onSort={setSorting}
onItemOpen={handleItemOpen}
onItemRender={handleItemRender}
/>
)}
</div>
);
}
| 2,756
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage/SharedFolderPage/SharedFolderPage.tsx
|
import { useEffect, useMemo, useRef, useState } from 'react';
import { c } from 'ttag';
import { NavigationControl } from '@proton/components/containers';
import FilePreview from '@proton/components/containers/filePreview/FilePreview';
import { DecryptedLink, useDownload, usePublicFolderView } from '../../../store';
import { usePublicFileView } from '../../../store/_views/useFileView';
import { SortParams } from '../../../store/_views/utils/useSorting';
import { isTransferActive } from '../../../utils/transfer';
import { FileBrowserStateProvider } from '../../FileBrowser';
import { useUpsellFloatingModal } from '../../modals/UpsellFloatingModal';
import Breadcrumbs from '../Layout/Breadcrumbs';
import HeaderSecureLabel from '../Layout/HeaderSecureLabel';
import HeaderSize from '../Layout/HeaderSize';
import SharedPageFooter from '../Layout/SharedPageFooter';
import SharedPageHeader from '../Layout/SharedPageHeader';
import SharedPageLayout from '../Layout/SharedPageLayout';
import { PublicLink } from '../interface';
import SharedFileBrowser from './FileBrowser';
interface Props {
token: string;
rootLink: DecryptedLink;
}
interface PreviewContainerProps {
shareId: string;
linkId: DecryptedLink['linkId'];
sortParams: SortParams;
onClose: () => void;
onNavigate: (linkId: DecryptedLink['linkId']) => void;
onDownload: () => void;
}
function SharedPagePreviewContainer({
shareId,
linkId,
sortParams,
onClose,
onNavigate,
onDownload,
}: PreviewContainerProps) {
const {
isLinkLoading,
isContentLoading,
error,
contents,
navigation,
link: loadedLink,
} = usePublicFileView(shareId, linkId, true, sortParams);
const rootRef = useRef<HTMLDivElement>(null);
return (
<FilePreview
colorUi="standard"
isMetaLoading={isLinkLoading}
isLoading={isContentLoading}
error={error ? error.message || error.toString?.() || c('Info').t`Unknown error` : undefined}
fileName={loadedLink?.name}
mimeType={loadedLink?.mimeType}
imgThumbnailUrl={loadedLink?.cachedThumbnailUrl}
fileSize={loadedLink?.size}
contents={contents}
ref={rootRef}
navigationControls={
loadedLink &&
navigation && (
<NavigationControl
current={navigation.current}
total={navigation.total}
rootRef={rootRef}
onPrev={() => onNavigate(navigation.prevLinkId)}
onNext={() => onNavigate(navigation.nextLinkId)}
/>
)
}
onClose={onClose}
onDownload={onDownload}
/>
);
}
export default function SharedFolder({ token, rootLink }: Props) {
const [linkId, setLinkId] = useState(rootLink.linkId);
const folderView = usePublicFolderView(token, linkId);
const { downloads, getDownloadsLinksProgresses, download } = useDownload();
const [fileBrowserItems, setFileBrowserItems] = useState<PublicLink[]>([]);
const [displayedLink, setDiplayedLink] = useState<DecryptedLink | undefined>();
const [previewDisplayed, setPreviewDisplayed] = useState(false);
const [renderUpsellFloatingModal] = useUpsellFloatingModal();
const onItemOpen = (item: DecryptedLink) => {
if (item.isFile) {
setPreviewDisplayed(true);
setDiplayedLink(item);
return;
}
setLinkId(item.linkId);
};
const handleClose = () => {
setPreviewDisplayed(false);
};
const handleNavigationPreview = (newLinkId: DecryptedLink['linkId']) => {
setDiplayedLink(fileBrowserItems.find((link) => link.linkId === newLinkId));
};
const shouldRenderPreviewContainer = previewDisplayed && displayedLink;
const updateFileBrowserItems = () => {
const linksProgresses = getDownloadsLinksProgresses();
setFileBrowserItems(
folderView.items.map((item) => {
const progress = linksProgresses[item.linkId];
const total = item.isFile ? item.size : progress?.total;
const percent = (() => {
if (progress === undefined || total === undefined) {
return 0;
}
if (total === 0) {
return 100;
}
return Math.round((100 / total) * progress.progress);
})();
return {
id: item.linkId,
...item,
progress: !progress
? undefined
: {
total,
progress: progress.progress,
percent,
isFinished: percent === 100,
},
itemRowStyle: !progress
? undefined
: {
background: `linear-gradient(90deg, var(--interaction-norm-minor-2) ${percent}%, var(--background-norm) ${percent}%)`,
},
};
})
);
};
// Enrich link date with download progress. Downloads changes only when
// status changes, not the progress, so if download is active, it needs
// to run in interval until download is finished.
useEffect(() => {
updateFileBrowserItems();
if (!downloads.some(isTransferActive)) {
// Progresses are not handled by state and might be updated
// without notifying a bit after downloads state is changed.
const id = setTimeout(updateFileBrowserItems, 500);
return () => {
clearTimeout(id);
};
}
const id = setInterval(updateFileBrowserItems, 500);
return () => {
clearInterval(id);
};
}, [folderView.items, downloads]);
const handlePreviewDownload = () => {
if (!displayedLink) {
return;
}
void download([{ ...displayedLink, shareId: token }]);
};
const { totalSize } = useMemo(
() =>
fileBrowserItems.reduce(
(previousValue, currentValue) => {
if (previousValue.haveSubFolder || !currentValue.isFile) {
return { haveSubFolder: true, totalSize: 0 };
}
return {
...previousValue,
totalSize: previousValue.totalSize + currentValue.size,
};
},
{ haveSubFolder: false, totalSize: 0 }
),
[fileBrowserItems]
);
return (
<FileBrowserStateProvider itemIds={fileBrowserItems.map(({ linkId }) => linkId)}>
<SharedPageLayout FooterComponent={<SharedPageFooter rootItem={rootLink} items={fileBrowserItems} />}>
<SharedPageHeader rootItem={rootLink} items={fileBrowserItems} className="mt-7 mb-8">
<div className="max-w-full flex flex-align-items-center">
<Breadcrumbs
token={token}
name={folderView.folderName}
linkId={linkId}
onNavigate={setLinkId}
className="w-full shared-folder-header-breadcrumbs pb-1"
/>
<div className="flex flex-align-items-center">
<HeaderSecureLabel />
{totalSize ? <HeaderSize size={totalSize} /> : null}
</div>
</div>
</SharedPageHeader>
{shouldRenderPreviewContainer && (
<SharedPagePreviewContainer
shareId={token}
linkId={displayedLink.linkId}
sortParams={folderView.sortParams}
onNavigate={handleNavigationPreview}
onClose={handleClose}
onDownload={handlePreviewDownload}
/>
)}
<SharedFileBrowser {...folderView} onItemOpen={onItemOpen} items={fileBrowserItems} />
</SharedPageLayout>
{renderUpsellFloatingModal}
</FileBrowserStateProvider>
);
}
| 2,757
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage/SharedPageError/SharedPageError.tsx
|
import React from 'react';
import { c } from 'ttag';
import { ButtonLike } from '@proton/atoms/Button';
import { DRIVE_LANDING_PAGE } from '@proton/shared/lib/drive/urls';
import notFoundSvg from '@proton/styles/assets/img/illustrations/shared-page-not-found.svg';
import SharedPageLayout from '../Layout/SharedPageLayout';
export default function SharedPageError() {
return (
<SharedPageLayout>
<div className="flex flex-item-fluid flex-align-items-center py-7 mb-14">
<div
className="password-page--form-container ui-standard w-full relative shadow-lifted max-w-custom mx-auto px-8 py-11 rounded"
style={{ '--max-w-custom': '30rem' }}
>
<figure className="flex flex-justify-center pb-7">
<img className="h-auto" src={notFoundSvg} alt={c('Info').t`Shared link not found`} />
</figure>
<h3 className="text-center text-bold">{c('Title').t`Hm, we couldn't find that one`}</h3>
<p className="text-center mt-2 mb-14">
{c('Info')
.t`This file may have been deleted, moved or made unavailable. Try reaching out to the file owner.`}
</p>
<ButtonLike as="a" size="large" fullWidth color="norm" href={DRIVE_LANDING_PAGE}>
{c('Action').t`Back to Homepage`}
</ButtonLike>
</div>
</div>
</SharedPageLayout>
);
}
| 2,758
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/SharedPage/SharedPageError/index.ts
|
export { default } from './SharedPageError';
| 2,759
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/TransferManager/Buttons.tsx
|
import { Button } from '@proton/atoms';
import { Icon, Tooltip } from '@proton/components';
import clsx from '@proton/utils/clsx';
import { TransfersManagerButtonsProps } from './interfaces';
const Buttons = ({ className, buttons, id }: TransfersManagerButtonsProps) => {
const elClassName = clsx(['flex flex-nowrap flex-justify-end', className]);
return (
<div className={elClassName} id={id}>
{buttons.map(({ disabled, onClick, title, testId, iconName }) => (
<Tooltip title={title} key={title}>
<Button
icon
type="button"
disabled={disabled}
onClick={onClick}
className="transfers-manager-list-item-controls-button on-rtl-mirror"
data-testid={testId ? testId : undefined}
>
<Icon size={12} name={iconName} alt={title} />
</Button>
</Tooltip>
))}
</div>
);
};
export default Buttons;
| 2,760
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/TransferManager/Header.tsx
|
import { useEffect, useMemo, useRef, useState } from 'react';
import { c, msgid } from 'ttag';
import { Button } from '@proton/atoms';
import { Icon, Tooltip } from '@proton/components';
import clsx from '@proton/utils/clsx';
import {
calculateProgress,
isTransferActive,
isTransferCanceled,
isTransferDone,
isTransferError,
isTransferManuallyPaused,
} from '../../utils/transfer';
import { Download, TransfersStats, Upload } from './transfer';
interface Props {
downloads: Download[];
uploads: Upload[];
stats: TransfersStats;
minimized: boolean;
onToggleMinimize: () => void;
onClose: () => void;
}
const Header = ({ downloads, uploads, stats, onClose, onToggleMinimize, minimized = false }: Props) => {
const [uploadsInSession, setUploadsInSession] = useState<Upload[]>([]);
const [downloadsInSession, setDownloadsInSession] = useState<Download[]>([]);
const minimizeRef = useRef<HTMLButtonElement>(null);
const transfers = useMemo(() => [...downloads, ...uploads], [uploads, downloads]);
const activeUploads = useMemo(() => uploads.filter(isTransferActive), [uploads]);
const activeDownloads = useMemo(() => downloads.filter(isTransferActive), [downloads]);
const doneUploads = useMemo(() => uploads.filter(isTransferDone), [uploads]);
const doneDownloads = useMemo(() => downloads.filter(isTransferDone), [downloads]);
const pausedTransfers = useMemo(() => transfers.filter(isTransferManuallyPaused), [transfers]);
const failedTransfers = useMemo(() => transfers.filter(isTransferError), [transfers]);
const canceledTransfers = useMemo(() => transfers.filter(isTransferCanceled), [transfers]);
const activeUploadsCount = activeUploads.length;
const activeDownloadsCount = activeDownloads.length;
useEffect(() => {
if (activeUploadsCount) {
setUploadsInSession((uploadsInSession) => [
...doneUploads.filter((done) => uploadsInSession.some(({ id }) => id === done.id)),
...activeUploads,
]);
} else {
setUploadsInSession([]);
}
}, [activeUploads, doneUploads, activeUploadsCount]);
useEffect(() => {
if (activeDownloadsCount) {
setDownloadsInSession((downloadsInSession) => [
...doneDownloads.filter((done) => downloadsInSession.some(({ id }) => id === done.id)),
...activeDownloads,
]);
} else {
setDownloadsInSession([]);
}
}, [activeDownloads, activeDownloadsCount]);
const getHeadingText = () => {
const headingElements: string[] = [];
const activeCount = activeUploadsCount + activeDownloadsCount;
const doneUploadsCount = doneUploads.length;
const doneDownloadsCount = doneDownloads.length;
const doneCount = doneUploadsCount + doneDownloadsCount;
const errorCount = failedTransfers.length;
const canceledCount = canceledTransfers.length;
const pausedCount = pausedTransfers.length;
if (!activeCount) {
if (doneUploadsCount && doneDownloadsCount) {
headingElements.push(
c('Info').ngettext(msgid`${doneCount} finished`, `${doneCount} finished`, doneCount)
);
} else {
if (doneUploadsCount) {
headingElements.push(
c('Info').ngettext(
msgid`${doneUploadsCount} uploaded`,
`${doneUploadsCount} uploaded`,
doneUploadsCount
)
);
}
if (doneDownloadsCount) {
headingElements.push(
c('Info').ngettext(
msgid`${doneDownloadsCount} downloaded`,
`${doneDownloadsCount} downloaded`,
doneDownloadsCount
)
);
}
}
}
if (activeUploadsCount) {
const uploadProgress = calculateProgress(stats, uploadsInSession);
headingElements.push(
c('Info').ngettext(
msgid`${activeUploadsCount} uploading (${uploadProgress}%)`,
`${activeUploadsCount} uploading (${uploadProgress}%)`,
activeUploadsCount
)
);
}
if (activeDownloadsCount) {
if (downloadsInSession.some(({ meta: { size } }) => size === undefined)) {
headingElements.push(
c('Info').ngettext(
msgid`${activeDownloadsCount} downloading`,
`${activeDownloadsCount} downloading`,
activeDownloadsCount
)
);
} else {
const downloadProgress = calculateProgress(stats, downloadsInSession);
headingElements.push(
c('Info').ngettext(
msgid`${activeDownloadsCount} downloading (${downloadProgress}%)`,
`${activeDownloadsCount} downloading (${downloadProgress}%)`,
activeDownloadsCount
)
);
}
}
if (pausedCount) {
headingElements.push(
c('Info').ngettext(msgid`${pausedCount} paused`, `${pausedCount} paused`, pausedCount)
);
}
if (canceledCount) {
headingElements.push(
c('Info').ngettext(msgid`${canceledCount} canceled`, `${canceledCount} canceled`, canceledCount)
);
}
if (errorCount) {
headingElements.push(c('Info').ngettext(msgid`${errorCount} failed`, `${errorCount} failed`, errorCount));
}
return headingElements.join(', ');
};
const minMaxTitle = minimized ? c('Action').t`Maximize transfers` : c('Action').t`Minimize transfers`;
const closeTitle = c('Action').t`Close transfers`;
return (
<div className="transfers-manager-heading ui-prominent flex flex-align-items-center flex-nowrap px-2">
<div
role="presentation"
className="flex-item-fluid p-2"
aria-atomic="true"
aria-live="polite"
data-testid="drive-transfers-manager:header"
onClick={minimized ? onToggleMinimize : undefined}
>
{getHeadingText()}
</div>
<Tooltip title={minMaxTitle}>
<Button
icon
ref={minimizeRef}
type="button"
shape="ghost"
onClick={() => {
onToggleMinimize();
minimizeRef.current?.blur();
}}
aria-expanded={!minimized}
aria-controls="transfer-manager"
>
<Icon className={clsx(['m-auto', minimized && 'rotateX-180'])} name="low-dash" />
<span className="sr-only">{minMaxTitle}</span>
</Button>
</Tooltip>
<Tooltip title={closeTitle}>
<Button icon type="button" shape="ghost" data-testid="drive-transfers-manager:close" onClick={onClose}>
<Icon className="m-auto" name="cross" alt={closeTitle} />
</Button>
</Tooltip>
</div>
);
};
export default Header;
| 2,761
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/TransferManager/HeaderButtons.tsx
|
import { c } from 'ttag';
import clsx from '@proton/utils/clsx';
import {
isTransferCanceled,
isTransferDone,
isTransferFailed,
isTransferFinalizing,
isTransferOngoing,
isTransferPaused,
} from '../../utils/transfer';
import Buttons from './Buttons';
import { TransferManagerButtonProps } from './interfaces';
import { Download, TransferType, Upload } from './transfer';
import useTransferControls from './useTransferControls';
type TransferManagerEntry = { transfer: Upload | Download; type: TransferType };
interface HeaderButtonProps {
entries: TransferManagerEntry[];
className: string;
}
const extractTransferFromEntry = ({ transfer }: TransferManagerEntry) => transfer;
const isInvalidForCancellation = (transfer: Upload | Download) =>
isTransferCanceled(transfer) ||
isTransferFailed(transfer) ||
isTransferFinalizing(transfer) ||
isTransferDone(transfer);
const HeaderButton = ({ entries, className }: HeaderButtonProps) => {
const transferManagerControls = useTransferControls();
const areAllActiveTransfersPaused = entries
.map(extractTransferFromEntry)
.filter(isTransferOngoing)
.every(isTransferPaused);
const hasOnlyInactiveTransfers = entries
.map(extractTransferFromEntry)
.every((transfer) => !isTransferOngoing(transfer));
/*
* Pause icon gets priority over resume icon. Here are the rules:
*
* - mixed transfer –> pause
* - only in progress –> pause
* - cancelled or failed -> pause (disabled)
* – all *active* transfers are paused -> resume
*/
const shouldDisplayResume = entries.length !== 0 && areAllActiveTransfersPaused && !hasOnlyInactiveTransfers;
const testIdPrefix = 'drive-transfers-manager:header-controls-';
const buttons: TransferManagerButtonProps[] = [
{
onClick: () => {
const ongoingEntries = entries.filter(({ transfer }) => isTransferOngoing(transfer));
if (shouldDisplayResume) {
return transferManagerControls.resumeTransfers(ongoingEntries);
}
return transferManagerControls.pauseTransfers(ongoingEntries);
},
disabled: hasOnlyInactiveTransfers,
title: shouldDisplayResume ? c('Action').t`Resume all` : c('Action').t`Pause all`,
iconName: shouldDisplayResume ? 'play' : 'pause',
testId: testIdPrefix + (shouldDisplayResume ? 'play' : 'pause'),
},
{
onClick: () => {
transferManagerControls.cancelTransfers(
entries.filter((entry) => !isInvalidForCancellation(entry.transfer))
);
},
// Only cancelled/failed/finalizing/done transfers -> cancel button disabled
disabled: entries.map(extractTransferFromEntry).every(isInvalidForCancellation),
title: c('Action').t`Cancel all`,
iconName: 'cross',
testId: testIdPrefix + 'cancel',
},
{
onClick: () => {
return transferManagerControls.restartTransfers(
entries.filter(({ transfer }) => {
return isTransferFailed(transfer);
})
);
},
/*
* Restart enabled when there're failed transfers in the list. This also covers
* the case when theres only transfers in progress
*/
disabled: !entries.map(extractTransferFromEntry).some(isTransferFailed),
title: c('Action').t`Restart all`,
iconName: 'arrow-rotate-right',
testId: testIdPrefix + 'restart',
},
];
return (
<div
className={clsx(['flex', 'flex-nowrap', 'flex-justify-end', 'no-scroll', 'flex-item-noshrink', className])}
>
<Buttons buttons={buttons} className="flex-item-noshrink" />
</div>
);
};
export default HeaderButton;
| 2,762
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/TransferManager/ProgressBar.tsx
|
import { Progress } from '@proton/components';
import clsx from '@proton/utils/clsx';
export enum ProgressBarStatus {
Disabled = 'disabled',
Running = 'running',
Success = 'success',
Warning = 'warning',
Error = 'error',
}
interface Props {
status?: ProgressBarStatus;
value: number;
max?: number;
}
const ProgressBar = ({ status = ProgressBarStatus.Success, ...rest }: Props) => (
<Progress className={clsx(['transfers-manager-list-item-progress is-thin', `progress-bar--${status}`])} {...rest} />
);
export default ProgressBar;
| 2,763
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/TransferManager/TransferControls.tsx
|
import { c } from 'ttag';
import { useLoading } from '@proton/hooks';
import {
isTransferFailed,
isTransferFinalizing,
isTransferFinished,
isTransferOngoing,
isTransferPaused,
} from '../../utils/transfer';
import Buttons from './Buttons';
import { TransferManagerButtonProps, TransferProps } from './interfaces';
import { TransferType, Upload } from './transfer';
import useTransferControls from './useTransferControls';
function TransferControls<T extends TransferType>({ transfer, type }: TransferProps<T>) {
const transferControls = useTransferControls();
const [pauseInProgress, withPauseInProgress] = useLoading();
const isFinished = isTransferFinished(transfer);
const isFailed = isTransferFailed(transfer);
const isFinalizing = isTransferFinalizing(transfer);
const isPauseResumeAvailable = isTransferOngoing(transfer);
const isRestartAvailable = isFailed;
const isCancelAvailable = !isFinalizing && !isFinished;
const isTransferWithChildrenFinished = (upload: Upload) => {
if (!isTransferFinished(upload)) {
return false;
}
if (upload.files?.some((transfer) => !isTransferFinished(transfer))) {
return false;
}
if (upload.folders?.some((transfer) => !isTransferWithChildrenFinished(transfer))) {
return false;
}
return true;
};
// Do not show clear button for uploading folders which still have any
// children in progress as that would lead to some edge cases that
// parent with its children is removed from transfer manager but some
// ongoing transfers are still finishing up.
const isRemoveAvailable =
isFinished && (type === TransferType.Download || isTransferWithChildrenFinished(transfer as Upload));
const pauseText = type === TransferType.Download ? c('Action').t`Pause download` : c('Action').t`Pause upload`;
const resumeText = type === TransferType.Download ? c('Action').t`Resume download` : c('Action').t`Resume upload`;
const cancelText = type === TransferType.Download ? c('Action').t`Cancel download` : c('Action').t`Cancel upload`;
const restartText =
type === TransferType.Download ? c('Action').t`Restart download` : c('Action').t`Restart upload`;
const removeText = c('Action').t`Remove from this list`;
const testIdPrefix = 'drive-transfers-manager:item-controls-';
const getButtons = () => {
const buttons: TransferManagerButtonProps[] = [];
if (isPauseResumeAvailable) {
buttons.push({
onClick: () => withPauseInProgress(transferControls.togglePause(transfer, type)),
disabled: pauseInProgress,
title: isTransferPaused(transfer) ? resumeText : pauseText,
iconName: isTransferPaused(transfer) ? 'play' : 'pause',
testId: testIdPrefix + (isTransferPaused(transfer) ? 'play' : 'pause'),
});
}
if (isRestartAvailable) {
buttons.push({
onClick: () => transferControls.restart(transfer, type),
title: restartText,
iconName: 'arrow-rotate-right',
testId: testIdPrefix + 'restart',
});
}
if (isRemoveAvailable) {
buttons.push({
onClick: () => transferControls.remove(transfer, type),
title: removeText,
disabled: isFinalizing,
iconName: 'broom',
testId: testIdPrefix + 'remove',
});
}
if (isCancelAvailable) {
buttons.push({
onClick: () => transferControls.cancel(transfer, type),
title: cancelText,
disabled: isFinalizing,
iconName: 'cross',
testId: testIdPrefix + 'cancel',
});
}
return buttons;
};
return <Buttons className="transfers-manager-list-item-controls" buttons={getButtons()} />;
}
export default TransferControls;
| 2,764
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/TransferManager/TransferItem.tsx
|
import * as React from 'react';
import { FileIcon, FileNameDisplay, Loader } from '@proton/components';
import humanSize, { shortHumanSize } from '@proton/shared/lib/helpers/humanSize';
import clsx from '@proton/utils/clsx';
import {
getProgressBarStatus,
isTransferCanceled,
isTransferDone,
isTransferInitializing,
isTransferPaused,
isTransferPending,
isTransferProgress,
} from '../../utils/transfer';
import ProgressBar from './ProgressBar';
import TransferControls from './TransferControls';
import TransferStateIndicator from './TransferStateIndicator';
import { TransferProps } from './interfaces';
import { TransferType } from './transfer';
type Props<T extends TransferType> = React.HTMLAttributes<HTMLDivElement> &
TransferProps<T> & {
stats: {
progress: number;
speed: number;
};
};
const Transfer = <T extends TransferType>({ stats, transfer, type, className, ...rest }: Props<T>) => {
const isInitializing = isTransferInitializing(transfer);
const isNameUnresolved = isInitializing || isTransferPending(transfer);
const isProgress = isTransferProgress(transfer);
const isPaused = isTransferPaused(transfer);
const isCanceled = isTransferCanceled(transfer);
const isDone = isTransferDone(transfer);
const fileSize = transfer.meta.size;
const progressLimit = fileSize || 1;
const percentageDone = isDone ? 100 : Math.floor(100 * (stats.progress / progressLimit));
const progress = isDone ? progressLimit : stats.progress;
const speed = humanSize(stats.speed);
const isUploadingFolder = type === TransferType.Upload && transfer.meta.mimeType === 'Folder';
return (
<div
className={clsx([
'transfers-manager-list-item p-4',
isCanceled && 'transfers-manager-list-item--canceled',
className,
])}
data-testid="transfer-item-row"
{...rest}
>
<div className="transfers-manager-list-item-name flex flex-nowrap flex-align-items-center text-ellipsis">
<span className="transfers-manager-list-item-icon flex flex-item-noshrink mr-2">
{isInitializing ? <Loader size="small" /> : <FileIcon mimeType={transfer.meta.mimeType} />}
</span>
<span className={clsx(['flex', isNameUnresolved && 'color-weak'])} data-testid="transfer-item-name">
<FileNameDisplay text={transfer.meta.filename} />
</span>
</div>
{!isUploadingFolder && (
<div className="transfers-manager-list-item-size text-right text-ellipsis" title={`${percentageDone}%`}>
{(isProgress || isPaused) && progress > 0 && (
<span className="hidden lg:inline">{shortHumanSize(progress)} / </span>
)}
{fileSize !== undefined
? shortHumanSize(fileSize)
: isProgress && <Loader className="inline" size="small" />}
</div>
)}
<div className="transfers-manager-list-item-status flex flex-nowrap flex-align-items-center flex-justify-end text-ellipsis">
<TransferStateIndicator transfer={transfer} type={type} speed={speed} />
</div>
<TransferControls transfer={transfer} type={type} />
<ProgressBar
status={getProgressBarStatus(transfer.state)}
aria-describedby={transfer.id}
value={isCanceled ? 0 : progress}
max={progressLimit}
/>
</div>
);
};
export default Transfer;
| 2,765
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/TransferManager/TransferManager.scss
|
@import '~@proton/styles/scss/lib';
.transfers-manager {
position: fixed;
inset-inline-end: 0;
inset-block-end: 0;
z-index: $layer-transfer-manager;
box-shadow: var(--shadow-lifted);
color: var(--text-norm);
transition: 0.15s cubic-bezier(0.22, 1, 0.36, 1);
background: var(--background-norm);
@include media('height<=xsmall') {
max-block-size: 100%;
}
@include media('<=small') {
inset-inline-start: 0;
inset-block-end: 0;
}
@include media('>small') {
inline-size: 60%;
max-inline-size: 50em;
margin-inline-end: inherit;
// Make rounded border for both manager and header to not include
// background color of the manager in the corner.
&,
&-heading {
border-start-start-radius: var(--border-radius-md);
border-start-end-radius: 0;
border-end-start-radius: 0;
border-end-end-radius: 0;
}
}
&-heading {
background: var(--background-strong);
color: var(--text-norm);
}
&-heading-tooltip {
align-self: stretch;
justify-content: stretch;
align-items: stretch;
&--isDisabled {
pointer-events: none;
}
}
&-list {
background-color: var(--background-norm);
color: var(--text-norm);
transition: inherit;
block-size: 100%;
margin-block-start: -0.5em;
}
&--minimized &-list,
&--minimized &-list-placeholder {
max-block-size: 0;
visibility: hidden;
}
&--minimized {
@include media('height<=xsmall') {
max-block-size: initial;
block-size: initial;
}
}
&-list-item {
display: grid;
grid-template-rows: 1fr auto;
grid-template-areas: 'name size status controls' 'progress progress progress progress';
column-gap: 1em;
row-gap: 1em;
align-items: center;
block-size: 5em; // To avoid height blinking on status changing
@extend .border-bottom;
@include media('<=small') {
grid-template-columns: 4fr minmax(5em, 2fr) 2.5em minmax(4.5em, 1fr);
}
@include media('>small') {
grid-template-columns: 4fr 2.5fr minmax(6em, 2fr) minmax(4.5em, 1fr);
}
@include media('height>xsmall') {
&:last-child {
border-block-end: none;
}
}
@each $place in (name, size, status, controls, progress) {
&-#{$place} {
grid-area: $place;
}
@if $place != controls and $place != progress {
&--canceled &-#{$place} {
opacity: 0.5;
}
}
}
&-icon {
@include media('<=#{em(420, 16)}') {
display: none;
}
}
&-status {
white-space: nowrap;
font-variant-numeric: tabular-nums;
@include media('<=small') {
svg {
margin: 0;
}
}
}
&-size {
white-space: nowrap;
font-variant-numeric: tabular-nums;
}
&-controls-button {
padding: 0.375em;
& + & {
margin-inline-start: 0.5em;
}
}
.transfers-manager-list-item-controls-button {
opacity: 0;
will-change: opacity;
}
&:hover {
.transfers-manager-list-item-controls-button {
opacity: 1;
}
}
}
&-toolbar {
background-color: var(--background-weak);
}
&-list-placeholder {
background-color: var(--background-norm);
}
&-controls {
display: grid;
grid-template-columns: minmax(min-content, 1fr) auto;
grid-template-areas: 'status controls';
column-gap: 1em;
align-items: center;
block-size: 2em;
}
&-header-buttons {
position: absolute;
inset-inline-end: 0;
}
}
| 2,766
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/TransferManager/TransferManager.tsx
|
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { FixedSizeList, ListChildComponentProps } from 'react-window';
import { c, msgid } from 'ttag';
import {
Tabs,
useActiveBreakpoint,
useConfirmActionModal,
useDrawerWidth,
useElementRect,
useRightToLeft,
useToggle,
useWindowSize,
} from '@proton/components';
import busy from '@proton/shared/lib/busy';
import { rootFontSize } from '@proton/shared/lib/helpers/dom';
import clsx from '@proton/utils/clsx';
import { useTransfersView } from '../../store';
import { isTransferFailed } from '../../utils/transfer';
import Header from './Header';
import HeaderButtons from './HeaderButtons';
import Transfer from './TransferItem';
import { Download, STATE_TO_GROUP_MAP, TransferGroup, TransferType, TransfersStats, Upload } from './transfer';
import useTransferControls from './useTransferControls';
interface TransferListEntry<T extends TransferType> {
transfer: T extends TransferType.Download ? Download : Upload;
type: T;
}
const MAX_VISIBLE_TRANSFERS = 5;
const MAX_VISIBLE_TRANSFERS_MOBILE = 3;
type ListItemData = {
entries: (TransferListEntry<TransferType.Download> | TransferListEntry<TransferType.Upload>)[];
stats: TransfersStats;
};
type ListItemRowProps = Omit<ListChildComponentProps, 'data'> & { data: ListItemData };
const ListItemRow = ({ style, index, data }: ListItemRowProps) => {
const { stats, entries } = data;
const { transfer, type } = entries[index];
return (
<Transfer
style={style}
transfer={transfer}
type={type}
stats={{
progress: stats[transfer.id]?.progress ?? 0,
speed: stats[transfer.id]?.averageSpeed ?? 0,
}}
/>
);
};
const tabIndexToTransferGroup = {
0: undefined,
1: TransferGroup.ACTIVE,
2: TransferGroup.DONE,
3: TransferGroup.FAILURE,
};
type TabIndices = keyof typeof tabIndexToTransferGroup;
const TransferManager = ({
downloads,
uploads,
stats,
onClear,
hasActiveTransfer,
numberOfFailedTransfer,
}: {
downloads: Download[];
uploads: Upload[];
stats: TransfersStats;
onClear: () => void;
hasActiveTransfer: boolean;
numberOfFailedTransfer: {
total: number;
downloads: number;
uploads: number;
};
}) => {
const transferManagerControls = useTransferControls();
const containerRef = useRef<HTMLDivElement>(null);
const headerRef = useRef<HTMLDivElement>(null);
const [activeTabIndex, setActiveTabIndex] = useState<TabIndices>(0);
const windowHeight = useWindowSize()[1];
/*
FixedSizedList (used for virtual scrolling) requires `width` prop to work
correcty. This is why we use 'useElementRect' hook here.
`useElementRect` utilizes `getBoundingClientRect` method to get dimensions
of a given element reference.
*WARNING:* don't introduce conditional rendering to this component –
this will lead to a race condition in which an element could be removed
from DOM while React still keeping its reference. In this case
`getBoundingClientRect` returns zero for each target's dimension, which in certain
cases (here due to useElementRect specifics) cause rendering bugs.
For more details see TransferManagerContainer component
*/
const rect = useElementRect(containerRef);
const rectHeader = useElementRect(headerRef);
const { state: minimized, toggle: toggleMinimized } = useToggle();
const [confirmModal, showConfirmModal] = useConfirmActionModal();
const { isNarrow } = useActiveBreakpoint();
const [isRTL] = useRightToLeft();
const ROW_HEIGHT_PX = 4.375 * rootFontSize(); // 4.375 * 16 = we want 70px by default
useEffect(() => {
window.addEventListener('unload', onClear);
const unregister = busy.register();
return () => {
window.removeEventListener('unload', onClear);
unregister();
};
}, [onClear]);
const getListEntry =
<T extends TransferType>(type: T) =>
(transfer: T extends TransferType.Download ? Download : Upload): TransferListEntry<T> => ({
transfer,
type,
});
const getDownloadListEntry = getListEntry(TransferType.Download);
const getUploadListEntry = getListEntry(TransferType.Upload);
const downloadEntries = useMemo(() => downloads.map(getDownloadListEntry), [downloads]);
const uploadEntries = useMemo(() => uploads.map(getUploadListEntry), [uploads]);
const entries = useMemo(() => {
return [...downloadEntries, ...uploadEntries]
.sort((a, b) => b.transfer.startDate.getTime() - a.transfer.startDate.getTime())
.filter((entry) => {
const transferGroupFilter = tabIndexToTransferGroup[activeTabIndex];
if (transferGroupFilter === undefined) {
return true;
}
return STATE_TO_GROUP_MAP[entry.transfer.state] === transferGroupFilter;
});
}, [downloadEntries, uploadEntries, activeTabIndex]);
const handleCloseClick = () => {
if (hasActiveTransfer) {
void showConfirmModal({
title: c('Title').t`Stop transfers?`,
cancelText: c('Action').t`Continue transfers`,
submitText: c('Action').t`Stop transfers`,
message: c('Info')
.t`There are files that still need to be transferred. Closing the transfer manager will end all operations.`,
onSubmit: async () => onClear(),
canUndo: true,
});
return;
}
if (numberOfFailedTransfer.total) {
let title = c('Title').ngettext(
msgid`${numberOfFailedTransfer.total} failed transfer`,
`${numberOfFailedTransfer.total} failed transfers`,
numberOfFailedTransfer.total
);
let message = c('Info').t`Not all files were transferred. Try uploading or downloading the files again.`;
if (numberOfFailedTransfer.uploads && !numberOfFailedTransfer.downloads) {
title = c('Title').ngettext(
msgid`${numberOfFailedTransfer.total} failed upload`,
`${numberOfFailedTransfer.total} failed uploads`,
numberOfFailedTransfer.total
);
message = c('Info').t`Some files failed to upload. Try uploading the files again.`;
} else if (!numberOfFailedTransfer.uploads && numberOfFailedTransfer.downloads) {
title = c('Title').ngettext(
msgid`${numberOfFailedTransfer.total} failed download`,
`${numberOfFailedTransfer.total} failed downloads`,
numberOfFailedTransfer.total
);
message = c('Info').t`Some files failed to download. Try downloading the files again.`;
}
void showConfirmModal({
title,
message,
cancelText: c('Action').t`Retry`,
submitText: c('Action').t`Close`,
onCancel: () => {
return transferManagerControls.restartTransfers(
entries.filter(({ transfer }) => {
return isTransferFailed(transfer);
})
);
},
onSubmit: async () => onClear(),
canUndo: true,
});
return;
}
onClear();
};
const maxVisibleTransfers = isNarrow ? MAX_VISIBLE_TRANSFERS_MOBILE : MAX_VISIBLE_TRANSFERS;
const calcultateItemsHeight = useCallback(
(itemCount: number) => {
return ROW_HEIGHT_PX * Math.min(maxVisibleTransfers, itemCount);
},
[entries, minimized]
);
const calculateListHeight = useCallback(
(itemCount: number) => {
const itemsHeight = calcultateItemsHeight(itemCount);
if (itemsHeight + (rectHeader?.height || 0) > windowHeight) {
return windowHeight - (rectHeader?.height || 0);
}
return itemsHeight;
},
[windowHeight, minimized]
);
const Content = (
<>
{entries.length === 0 && (
<div
className="transfers-manager-list-placeholder flex flex-justify-center flex-align-items-center"
style={{ height: calcultateItemsHeight(1) }}
>
<span className="mb-4">{c('Info').t`No results found`} </span>
</div>
)}
<div className="transfers-manager-list">
{rect && (
<FixedSizeList
direction={isRTL ? 'rtl' : 'ltr'}
className="outline-none"
itemData={{
entries,
stats,
}}
itemCount={entries.length}
itemSize={ROW_HEIGHT_PX}
height={calculateListHeight(entries.length)}
width={rect.width}
itemKey={(index, { entries }: ListItemData) => entries[index].transfer?.id ?? index}
>
{ListItemRow}
</FixedSizeList>
)}
</div>
</>
);
const drawerWidth = useDrawerWidth();
return (
<>
<div
id="transfer-manager"
className={clsx(['transfers-manager', minimized && 'transfers-manager--minimized'])}
style={{ marginRight: `${drawerWidth}px` }}
>
<div ref={headerRef}>
<Header
downloads={downloads}
uploads={uploads}
stats={stats}
minimized={minimized}
onToggleMinimize={toggleMinimized}
onClose={handleCloseClick}
/>
</div>
<div ref={containerRef} className="flex">
{!minimized && (
<>
<Tabs
tabs={[
{
title: c('Title').t`All`,
content: Content,
},
{
title: c('Title').t`Active`,
content: Content,
},
{
title: c('Title').t`Completed`,
content: Content,
},
{
title: c('Title').t`Failed`,
content: Content,
},
]}
value={activeTabIndex}
onChange={(groupValue) => {
setActiveTabIndex(groupValue as TabIndices);
}}
/>
{!isNarrow && (
<HeaderButtons
className="transfers-manager-header-buttons p-2 pr-4"
entries={entries}
/>
)}
</>
)}
</div>
</div>
{confirmModal}
</>
);
};
/**
* This component is introduced specifically to address the race condition of
* `return null` code branch caused by `clearAllTransfers` call and width
* calculation inside `TransferManager`.
*
* Separating this chunk of code into its component guaranties that
* list element will be *always* present in DOM for correct transfer manager list
* width calculation.
*/
const TransferManagerContainer = () => {
const { downloads, uploads, hasActiveTransfer, numberOfFailedTransfer, stats, clearAllTransfers } =
useTransfersView();
if (!downloads.length && !uploads.length) {
return null;
}
return (
<TransferManager
downloads={downloads}
uploads={uploads}
stats={stats}
onClear={clearAllTransfers}
hasActiveTransfer={hasActiveTransfer}
numberOfFailedTransfer={numberOfFailedTransfer}
/>
);
};
export default TransferManagerContainer;
| 2,767
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/TransferManager/TransferStateIndicator.tsx
|
import { c } from 'ttag';
import { Icon, IconName, Tooltip } from '@proton/components';
import clsx from '@proton/utils/clsx';
import {
isTransferCanceled,
isTransferDone,
isTransferError,
isTransferManuallyPaused,
isTransferProgress,
} from '../../utils/transfer';
import { Download, TransferState, TransferType, Upload } from './transfer';
interface Props {
transfer: Upload | Download;
type: string;
speed: string;
}
const getErrorText = (error: any) => {
if (error?.data?.Error) {
return error.data.Error;
}
return error?.message || c('Info').t`Something went wrong, please try again later.`;
};
const TransferStateIndicator = ({ transfer, type, speed }: Props) => {
const shouldShowDirection =
isTransferProgress(transfer) ||
isTransferManuallyPaused(transfer) ||
isTransferCanceled(transfer) ||
isTransferDone(transfer);
const statuses: { [key in TransferState]: { text: string; icon?: IconName } } = {
[TransferState.Initializing]: {
text: c('Info').t`Initializing`,
},
[TransferState.Conflict]: {
text: c('Info').t`Conflict`,
},
[TransferState.Pending]: {
text: c('Info').t`Queued`,
icon: 'clock',
},
[TransferState.Progress]: {
text:
type === TransferType.Upload && transfer.meta.mimeType === 'Folder'
? c('Info').t`Creating`
: c('Info').t`${speed}/s`,
icon: type === TransferType.Download ? 'arrow-down-line' : 'arrow-up-line',
},
[TransferState.Paused]: {
text: c('Info').t`Paused`,
icon: 'pause',
},
[TransferState.Done]: {
text: type === TransferType.Download ? c('Info').t`Downloaded` : c('Info').t`Uploaded`,
icon: 'checkmark',
},
[TransferState.Error]: {
text: c('Info').t`Failed`,
icon: 'exclamation-circle',
},
[TransferState.SignatureIssue]: {
text: c('Info').t`Signature issue`,
},
[TransferState.NetworkError]: {
text: c('Info').t`Network issue`,
icon: 'exclamation-circle',
},
[TransferState.Canceled]: {
text: c('Info').t`Canceled`,
icon: 'cross',
},
[TransferState.Finalizing]: {
text: c('Info').t`Finalizing`,
icon: 'checkmark',
},
};
const statusInfo = statuses[transfer.state];
const progressTitle = type === TransferType.Download ? c('Info').t`Downloading` : c('Info').t`Uploading`;
const transferTitle = isTransferProgress(transfer) ? progressTitle : statusInfo.text;
const errorText = transfer.error && getErrorText(transfer.error);
return (
<div
className={clsx([
'text-ellipsis flex-no-min-children flex-align-items-center flex-nowrap',
isTransferManuallyPaused(transfer) && 'color-info',
isTransferDone(transfer) && 'color-success',
isTransferError(transfer) && 'color-danger',
])}
id={transfer.id}
title={transferTitle}
>
{/* Mobile icon */}
{statusInfo.icon && !isTransferProgress(transfer) && (
<Tooltip title={errorText} originalPlacement="top">
<span className="flex-item-noshrink md:hidden">
<Icon name={errorText ? 'info-circle' : statusInfo.icon} alt={statusInfo.text} />
</span>
</Tooltip>
)}
{/* Desktop text */}
<span className="hidden md:inline text-ellipsis" data-testid="transfer-item-status">
{errorText && (
<Tooltip title={errorText} originalPlacement="top">
<span className="mr-2">
<Icon name="info-circle" />
</span>
</Tooltip>
)}
{statusInfo.text}
</span>
{shouldShowDirection && (
<Icon
name={type === TransferType.Download ? 'arrow-down-line' : 'arrow-up-line'}
className={clsx(['flex-item-noshrink ml-2', isTransferDone(transfer) && 'md:hidden'])}
alt={progressTitle}
/>
)}
{/* Hidden Info for screen readers */}
<span className="sr-only" aria-atomic="true" aria-live="assertive">
{transfer.meta.filename} {transferTitle}
</span>
</div>
);
};
export default TransferStateIndicator;
| 2,768
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/TransferManager/interfaces.ts
|
import { IconName } from '@proton/components';
import { Download, TransferType, Upload } from './transfer';
export interface DownloadProps {
transfer: Download;
type: TransferType.Download;
}
export interface UploadProps {
transfer: Upload;
type: TransferType.Upload;
}
export interface TransferProps<T extends TransferType> {
transfer: T extends TransferType.Download ? Download : Upload;
type: T;
}
export interface TransferManagerButtonProps {
disabled?: boolean;
testId?: string;
title: string;
onClick: () => void;
iconName: IconName;
}
export interface TransfersManagerButtonsProps {
buttons: TransferManagerButtonProps[];
className?: string;
id?: string;
}
| 2,769
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/TransferManager/transfer.ts
|
/* eslint-disable max-classes-per-file */
export enum TransferState {
Initializing = 'initializing',
Pending = 'pending',
Conflict = 'conflict',
SignatureIssue = 'signatureIssue',
Progress = 'progress',
Finalizing = 'finalizing',
Done = 'done',
Canceled = 'canceled',
Error = 'error',
NetworkError = 'networkError',
Paused = 'paused',
}
export interface TransferProgresses {
[id: string]: number;
}
export interface TransferMeta {
filename: string;
mimeType: string;
size?: number;
}
export interface TransferSummary {
size: number;
progress: number;
}
export class TransferCancel extends Error {
constructor(options: { id: string } | { message: string }) {
super('id' in options ? `Transfer ${options.id} canceled` : options.message);
this.name = 'TransferCancel';
}
}
export class TransferConflict extends Error {
constructor(options: { id: string } | { message: string }) {
super('id' in options ? `Transfer ${options.id} is conflicting` : options.message);
this.name = 'TransferConflict';
}
}
export interface Upload {
id: string;
meta: TransferMeta;
state: TransferState;
startDate: Date;
error?: Error;
files?: Upload[];
folders?: Upload[];
}
export interface Download {
id: string;
meta: TransferMeta;
state: TransferState;
startDate: Date;
error?: Error;
}
export interface PartialDownload extends Download {
partOf: string;
}
export type Transfer = Upload | Download;
export interface ThumbnailMeta {
modifyTime: number;
}
export type API = (query: any) => any;
export interface TransferHistoryStats {
active: boolean;
progress: number;
speed: number;
}
export interface TransfersHistoryStats {
timestamp: Date;
stats: { [id: string]: TransferHistoryStats };
}
export interface TransferStats {
progress: number;
averageSpeed: number;
}
export interface TransfersStats {
[id: string]: TransferStats;
}
export enum TransferType {
Download = 'download',
Upload = 'upload',
}
export enum TransferGroup {
ACTIVE,
DONE,
QUEUED,
FAILURE,
}
export const STATE_TO_GROUP_MAP = {
[TransferState.Progress]: TransferGroup.ACTIVE,
[TransferState.Finalizing]: TransferGroup.ACTIVE,
[TransferState.Paused]: TransferGroup.ACTIVE,
[TransferState.SignatureIssue]: TransferGroup.ACTIVE,
[TransferState.Canceled]: TransferGroup.FAILURE,
[TransferState.NetworkError]: TransferGroup.FAILURE,
[TransferState.Done]: TransferGroup.DONE,
[TransferState.Error]: TransferGroup.FAILURE,
[TransferState.Initializing]: TransferGroup.QUEUED,
[TransferState.Conflict]: TransferGroup.QUEUED,
[TransferState.Pending]: TransferGroup.QUEUED,
};
| 2,770
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/TransferManager/useTransferControls.tsx
|
import { useDownload, useUpload } from '../../store';
import { isTransferPaused } from '../../utils/transfer';
import { Download, TransferType, Upload } from './transfer';
function useTransferControls() {
const { pauseDownloads, resumeDownloads, restartDownloads, cancelDownloads, removeDownloads } = useDownload();
const { pauseUploads, resumeUploads, restartUploads, cancelUploads, removeUploads } = useUpload();
const cancel = (transfer: Download | Upload, type: TransferType) => {
if (type === TransferType.Download) {
return cancelDownloads(transfer.id);
}
if (type === TransferType.Upload) {
return cancelUploads(transfer.id);
}
};
const remove = (transfer: Download | Upload, type: TransferType) => {
if (type === TransferType.Download) {
return removeDownloads(transfer.id);
}
if (type === TransferType.Upload) {
return removeUploads(transfer.id);
}
};
const togglePause = async (transfer: Upload | Download, type: TransferType) => {
if (isTransferPaused(transfer)) {
if (type === TransferType.Download) {
return resumeDownloads(transfer.id);
}
return resumeUploads(transfer.id);
}
if (type === TransferType.Download) {
return pauseDownloads(transfer.id);
}
return pauseUploads(transfer.id);
};
const restart = (transfer: Download | Upload, type: TransferType) => {
try {
if (type === TransferType.Download) {
restartDownloads(transfer.id);
} else {
restartUploads(transfer.id);
}
} catch (e: any) {
console.error(e);
}
};
const pauseTransfers = (entries: { transfer: Download | Upload; type: TransferType }[]) => {
const notPausedEntries = entries.filter(({ transfer }) => !isTransferPaused(transfer));
applyToTransfers(notPausedEntries, pauseDownloads, pauseUploads);
};
const resumeTransfers = (entries: { transfer: Download | Upload; type: TransferType }[]) => {
const pausedEntries = entries.filter(({ transfer }) => isTransferPaused(transfer));
applyToTransfers(pausedEntries, resumeDownloads, resumeUploads);
};
const cancelTransfers = (entries: { transfer: Download | Upload; type: TransferType }[]) => {
applyToTransfers(entries, cancelDownloads, cancelUploads);
};
const restartTransfers = (entries: { transfer: Download | Upload; type: TransferType }[]) => {
applyToTransfers(entries, restartDownloads, restartUploads);
};
return {
cancel,
remove,
restart,
togglePause,
pauseTransfers,
resumeTransfers,
cancelTransfers,
restartTransfers,
};
}
export default useTransferControls;
function applyToTransfers(
entries: { transfer: Download | Upload; type: TransferType }[],
downloadCallback: (id: string, transfer: Download) => void,
uploadCallback: (filter: (data: { id: string }) => boolean) => void
) {
entries
.filter(({ type }) => type === TransferType.Download)
.forEach(({ transfer }) => downloadCallback(transfer.id, transfer as Download));
const uploadIds = entries.filter(({ type }) => type === TransferType.Upload).map(({ transfer: { id } }) => id);
uploadCallback(({ id }) => uploadIds.includes(id));
}
| 2,771
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/drawer/DriveQuickSettings.tsx
|
import { useConfirmActionModal } from '@proton/components/components';
import {
DefaultQuickSettings,
QuickSettingsButtonSection,
QuickSettingsMain,
} from '@proton/components/components/drawer/views/quickSettings';
import DrawerAllSettingsView from '@proton/components/components/drawer/views/quickSettings/DrawerAllSettingsView';
import ClearSearchDataButton from '../layout/search/ClearSearchDataButton';
const DriveQuickSettings = () => {
const [confirmModal, showConfirmModal] = useConfirmActionModal();
return (
<QuickSettingsMain>
<DrawerAllSettingsView />
<DefaultQuickSettings />
<QuickSettingsButtonSection>
<ClearSearchDataButton showConfirmModal={showConfirmModal} />
</QuickSettingsButtonSection>
{confirmModal}
</QuickSettingsMain>
);
};
export default DriveQuickSettings;
| 2,772
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/DriveEmptyView.tsx
|
import { PropsWithChildren, forwardRef } from 'react';
import { EmptyViewContainer } from '@proton/components';
import clsx from '@proton/utils/clsx';
import isTruthy from '@proton/utils/isTruthy';
type MaybeString = string | false | null | undefined;
type Props = PropsWithChildren<{
image: string;
title: string;
subtitle?: MaybeString | MaybeString[];
dataTestId?: string;
onClick?: () => void;
}>;
const filterSubtitles = (subtitle: MaybeString | MaybeString[]): string[] => {
if (Array.isArray(subtitle)) {
return subtitle.filter(isTruthy);
}
if (subtitle) {
return [subtitle];
}
return [];
};
/**
* Common template for empty views across Drive.
*/
export const DriveEmptyView = forwardRef<HTMLDivElement, Props>(
({ image, title, subtitle, dataTestId, onClick, children }, ref) => (
// onClick is used for context menu, so we don't need to care about keyboard events
// eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions
<div ref={ref} onClick={onClick} className="flex w-full flex flex-item-fluid overflow-auto">
<EmptyViewContainer
imageProps={{
src: image,
role: 'presentation',
'aria-hidden': true,
alt: '',
}}
data-testid={dataTestId}
>
<div className={clsx(!!children && 'mb-8')}>
<h3 className="text-bold">{title}</h3>
{filterSubtitles(subtitle).map((text) => (
<p key={text} className={'color-weak m-0 mt-2'}>
{text}
</p>
))}
</div>
{children}
</EmptyViewContainer>
</div>
)
);
DriveEmptyView.displayName = 'DriveEmptyView';
| 2,773
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/DriveHeader.tsx
|
import { ReactNode } from 'react';
import { c } from 'ttag';
import {
PrivateHeader,
RebrandingFeedbackModal,
TopNavbarListItemFeedbackButton,
UserDropdown,
useActiveBreakpoint,
useHasRebrandingFeedback,
useModalState,
} from '@proton/components';
import { APPS } from '@proton/shared/lib/constants';
import { SearchField } from './search/SearchField';
interface Props {
isHeaderExpanded: boolean;
toggleHeaderExpanded: () => void;
searchBox?: ReactNode;
title?: string;
settingsButton?: ReactNode;
}
export const DriveHeader = ({
isHeaderExpanded,
toggleHeaderExpanded,
title = c('Title').t`Drive`,
searchBox,
settingsButton,
}: Props) => {
const { isNarrow, isTablet } = useActiveBreakpoint();
const hasRebrandingFeedback = useHasRebrandingFeedback();
const [rebrandingFeedbackModal, setRebrandingFeedbackModal] = useModalState();
return (
<>
<PrivateHeader
feedbackButton={
hasRebrandingFeedback ? (
<TopNavbarListItemFeedbackButton onClick={() => setRebrandingFeedbackModal(true)} />
) : null
}
userDropdown={<UserDropdown app={APPS.PROTONDRIVE} />}
title={title}
expanded={isHeaderExpanded}
onToggleExpand={toggleHeaderExpanded}
isNarrow={isNarrow}
actionArea={!(isNarrow || isTablet) && searchBox}
settingsButton={settingsButton}
/>
<RebrandingFeedbackModal {...rebrandingFeedbackModal} />
</>
);
};
export const DriveHeaderPrivate = (props: Props) => {
return <DriveHeader {...props} searchBox={<SearchField />} />;
};
| 2,774
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/DriveWindow.tsx
|
import * as React from 'react';
import { useState } from 'react';
import { useLocation } from 'react-router-dom';
import {
CalendarDrawerAppButton,
ContactDrawerAppButton,
DrawerApp,
DrawerSidebar,
MainLogo,
PrivateAppContainer,
PrivateMainArea,
QuickSettingsAppButton,
TopBanners,
useDrawer,
useOpenDrawerOnLoad,
useToggle,
useUser,
} from '@proton/components';
import DrawerVisibilityButton from '@proton/components/components/drawer/DrawerVisibilityButton';
import { APPS } from '@proton/shared/lib/constants';
import { isAppInView } from '@proton/shared/lib/drawer/helpers';
import { DRAWER_NATIVE_APPS } from '@proton/shared/lib/drawer/interfaces';
import isTruthy from '@proton/utils/isTruthy';
import { useIsActiveLinkReadOnly } from '../../store/_views/utils';
import AppErrorBoundary from '../AppErrorBoundary';
import FileRecoveryBanner from '../ResolveLockedVolumes/LockedVolumesBanner';
import DriveQuickSettings from '../drawer/DriveQuickSettings';
import { DriveHeaderPrivate } from './DriveHeader';
import { getDriveDrawerPermissions } from './drawerPermissions';
import ActionMenuButton from './sidebar/ActionMenu/ActionMenuButton';
import DriveSidebar from './sidebar/DriveSidebar';
interface Props {
children?: JSX.Element | JSX.Element[];
}
const DriveWindow = ({ children }: Props) => {
const [user] = useUser();
const { state: expanded, toggle: toggleExpanded } = useToggle();
const [recoveryBannerVisible, setRecoveryBannerVisible] = useState(true);
const { isReadOnly } = useIsActiveLinkReadOnly();
useOpenDrawerOnLoad();
const { appInView, showDrawerSidebar } = useDrawer();
const location = useLocation();
const fileRecoveryBanner = recoveryBannerVisible ? (
<FileRecoveryBanner
onClose={() => {
setRecoveryBannerVisible(false);
}}
/>
) : null;
const top = <TopBanners>{fileRecoveryBanner}</TopBanners>;
const drawerSettingsButton = (
<QuickSettingsAppButton aria-expanded={isAppInView(DRAWER_NATIVE_APPS.QUICK_SETTINGS, appInView)} />
);
const logo = <MainLogo to="/" />;
const header = (
<DriveHeaderPrivate
isHeaderExpanded={expanded}
toggleHeaderExpanded={toggleExpanded}
settingsButton={drawerSettingsButton}
/>
);
const permissions = getDriveDrawerPermissions({ user });
const drawerSidebarButtons = [
permissions.contacts && (
<ContactDrawerAppButton aria-expanded={isAppInView(DRAWER_NATIVE_APPS.CONTACTS, appInView)} />
),
permissions.calendar && <CalendarDrawerAppButton aria-expanded={isAppInView(APPS.PROTONCALENDAR, appInView)} />,
].filter(isTruthy);
const isNewUploadDisabled = location.pathname === '/devices' || isReadOnly;
const sidebar = (
<DriveSidebar
logo={logo}
primary={<ActionMenuButton className="hidden md:flex" disabled={isNewUploadDisabled} />}
isHeaderExpanded={expanded}
toggleHeaderExpanded={toggleExpanded}
/>
);
const canShowDrawer = drawerSidebarButtons.length > 0;
return (
<PrivateAppContainer
top={top}
header={header}
sidebar={sidebar}
drawerApp={<DrawerApp customAppSettings={<DriveQuickSettings />} />}
>
<PrivateMainArea
drawerSidebar={<DrawerSidebar buttons={drawerSidebarButtons} />}
drawerVisibilityButton={canShowDrawer ? <DrawerVisibilityButton /> : undefined}
mainBordered={canShowDrawer && !!showDrawerSidebar}
>
<div className="flex flex-column flex-nowrap w-full">
<AppErrorBoundary>{children}</AppErrorBoundary>
</div>
</PrivateMainArea>
</PrivateAppContainer>
);
};
export default DriveWindow;
| 2,775
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/drawerPermissions.ts
|
import { User, UserType } from '@proton/shared/lib/interfaces';
export const getDriveDrawerPermissions = ({ user }: { user: User }) => {
return {
contacts: true,
calendar: user.Type !== UserType.EXTERNAL,
};
};
| 2,776
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/search/ClearSearchDataButton.tsx
|
import { c } from 'ttag';
import { Tooltip, useConfirmActionModal } from '@proton/components';
import { QuickSettingsButton } from '@proton/components/components/drawer/views/quickSettings';
import { useSearchControl } from '../../../store';
interface Props {
showConfirmModal: ReturnType<typeof useConfirmActionModal>[1];
}
export default function ClearSearchDataButton({ showConfirmModal }: Props) {
const { searchEnabled, hasData, deleteData } = useSearchControl();
if (!hasData || !searchEnabled) {
return null;
}
const handleDeleteESIndex = () => {
void showConfirmModal({
onSubmit: deleteData,
title: c('Info').t`Clear encrypted search data`,
submitText: c('Info').t`Clear data`,
message: c('Info')
.t`Clearing browser data will clear the search index on this device. All files would need to be re-indexed again while using the search functionality.`,
});
};
return (
<>
<Tooltip title={c('Info').t`Clears browser data related to the encrypted search.`}>
<QuickSettingsButton onClick={handleDeleteESIndex}>
{c('Action').t`Clear browser data`}
</QuickSettingsButton>
</Tooltip>
</>
);
}
| 2,777
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/search/SearchDropdown.scss
|
.search-dropdown {
--min-width: 35em;
--max-width: 35em;
}
| 2,778
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/search/SearchDropdown.tsx
|
import * as React from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { Dropdown, DropdownSizeUnit } from '@proton/components';
import { DRIVE_APP_NAME } from '@proton/shared/lib/constants';
import { useSearchLibrary } from '../../../store';
import { SearchIndexingProgress } from './SearchIndexingProgress';
import './SearchDropdown.scss';
interface Props {
isOpen: boolean;
anchorRef: React.RefObject<HTMLDivElement>;
onClose: (e: any) => void;
onClosed: () => void;
}
export const SearchDropdown = ({ isOpen, anchorRef, onClose, onClosed }: Props) => {
const { esStatus } = useSearchLibrary();
const { isRefreshing, dbExists, isEnablingEncryptedSearch } = esStatus;
const showProgress = isEnablingEncryptedSearch || isRefreshing;
const isESActive = dbExists && !isEnablingEncryptedSearch;
return (
<>
<Dropdown
anchorRef={anchorRef as React.RefObject<HTMLElement>}
isOpen={isOpen}
originalPlacement="bottom-start"
autoClose={false}
autoCloseOutside={true}
size={{
height: DropdownSizeUnit.Dynamic,
maxWidth: DropdownSizeUnit.Viewport,
maxHeight: DropdownSizeUnit.Viewport,
}}
onClose={onClose}
onClosed={onClosed}
className="dropdown-content--wide advanced-search-dropdown search-dropdown"
disableDefaultArrowNavigation
>
<div className="px-5 pt-5 pb-4">
<div>
<div className="flex">
<span className="inline-flex text-bold text-lg">
{isESActive ? c('Info').t`Search Enabled` : c('Info').t`Enabling drive search`}
</span>
</div>
<p className="mb-0">
{isESActive
? c('Info')
.t`Private search enabled. You may now close this dialogue and search for files and folders.`
: c('Info')
.t`To enable truly private search, we need to index your files locally. You can still use ${DRIVE_APP_NAME} normally - we’ll let you know when indexing is done.`}
</p>
</div>
{showProgress && <SearchIndexingProgress />}
<div className="flex flex-justify-end mt-4">
<Button shape="ghost" color="norm" onClick={onClose}>{c('Action').t`Got it`}</Button>
</div>
</div>
</Dropdown>
</>
);
};
| 2,779
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/search/SearchField.scss
|
@import '~@proton/styles/scss/lib';
.searchfield-disabled-input-button {
position: absolute;
inline-size: 100%;
block-size: 100%;
z-index: $layer-upper;
cursor: default;
}
.search-spotlight {
max-inline-size: 30em;
}
| 2,780
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/search/SearchField.tsx
|
import React, { useCallback, useRef } from 'react';
import { c } from 'ttag';
import { Button, Href, Input } from '@proton/atoms';
import { Icon, Spotlight, usePopperAnchor } from '@proton/components';
import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url';
import esSpotlightIcon from '@proton/styles/assets/img/illustrations/spotlight-stars.svg';
import useNavigate from '../../../hooks/drive/useNavigate';
import { useSearchControl } from '../../../store';
import { useSearchResults } from '../../../store/_search';
import { sendErrorReport } from '../../../utils/errorHandling';
import { useSpotlight } from '../../useSpotlight';
import { SearchDropdown } from './SearchDropdown';
import { useSearchParams } from './useSearchParams';
import './SearchField.scss';
export const SearchField = () => {
const indexingDropdownAnchorRef = useRef<HTMLDivElement>(null);
const indexingDropdownControl = usePopperAnchor<HTMLButtonElement>();
const { searchSpotlight } = useSpotlight();
const { dbExists } = useSearchResults();
const navigation = useNavigate();
const { searchEnabled, isEnablingEncryptedSearch, isDisabled, disabledReason, prepareSearchData } =
useSearchControl();
const [searchParams, setSearchParams] = useSearchParams();
const handleSearch = useCallback((keyword = '') => {
const encodedKeyword = encodeURIComponent(keyword);
if (keyword.length !== 0) {
navigation.navigateToSearch(encodedKeyword);
} else {
navigation.navigateToRoot();
}
}, []);
const handleFieldFocus = () => {
if (dbExists && !isEnablingEncryptedSearch) {
return;
}
searchSpotlight.close();
if (indexingDropdownControl.isOpen) {
indexingDropdownControl.close();
return;
}
indexingDropdownControl.open();
return prepareSearchData().catch(sendErrorReport);
};
const handleClosedDropdown = (e?: Event) => {
e?.stopPropagation();
indexingDropdownControl.close();
};
if (!searchEnabled) {
return null;
}
const placeholderText = isDisabled ? disabledReason : c('Action').t`Search drive`;
const imageProps = { src: esSpotlightIcon, alt: c('Info').t`Encrypted search is here` };
const shouldShowSpotlight = searchSpotlight.isOpen && !indexingDropdownControl.isOpen;
return (
<div ref={indexingDropdownAnchorRef} className="searchfield-container searchbox">
{
// On Firefox, no event is fired when the input field is disabled.
// This is a small "hack" to open the spotlight when the user clicks on the disabled input.
}
{isEnablingEncryptedSearch ? (
<button
className="searchfield-disabled-input-button"
aria-label={c('Label').t`Show indexing progress of Encrypted Search`}
onClick={() => indexingDropdownControl.open()}
/>
) : null}
<Spotlight
className="search-spotlight"
originalPlacement="bottom-start"
show={shouldShowSpotlight}
onDisplayed={searchSpotlight.onDisplayed}
content={
<div className="flex flex-nowrap">
<figure className="flex-item flex-item-noshrink pr-4">
{imageProps && <img className="h-auto" {...imageProps} alt={imageProps.alt || ''} />}
</figure>
<div className="flex-item">
<div className="text-bold text-lg m-auto">{c('Spotlight').t`Encrypted search is here`}</div>
{c('Spotlight').t`Now you can easily search Drive files while keeping your data secure.`}
<br />
<Href href={getKnowledgeBaseUrl('/search-drive')} title="How does encrypted search work?">
{c('Info').t`How does encrypted search work?`}
</Href>
</div>
</div>
}
>
<>
<Input
value={searchParams}
placeholder={placeholderText}
onFocus={handleFieldFocus}
onChange={(e) => setSearchParams(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleSearch(searchParams);
}
if (e.key === 'Escape') {
setSearchParams('');
e.currentTarget.blur();
}
}}
disabled={isDisabled}
prefix={
<Button
icon
disabled={!searchParams || isDisabled}
shape="ghost"
color="weak"
size="small"
className="rounded-sm"
title={c('Action').t`Search`}
onClick={() => {
handleSearch(searchParams);
}}
>
<Icon name="magnifier" alt={c('Action').t`Search`} />
</Button>
}
suffix={
searchParams ? (
<Button
type="button"
shape="ghost"
color="weak"
size="small"
className="rounded-sm"
title={c('Action').t`Clear`}
onClick={() => {
setSearchParams('');
handleSearch('');
}}
>
{c('Action').t`Clear`}
</Button>
) : null
}
/>
<SearchDropdown
isOpen={indexingDropdownControl.isOpen}
anchorRef={indexingDropdownAnchorRef}
onClose={handleClosedDropdown}
onClosed={handleClosedDropdown}
/>
</>
</Spotlight>
</div>
);
};
| 2,781
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/search/SearchIndexingProgress.tsx
|
import * as React from 'react';
import { c, msgid } from 'ttag';
import { Progress } from '@proton/components';
import clsx from '@proton/utils/clsx';
import { useSearchLibrary } from '../../../store';
import './SearchDropdown.scss';
export const SearchIndexingProgress = () => {
const { esStatus, progressRecorderRef } = useSearchLibrary();
const { isRefreshing } = esStatus;
const {
esIndexingProgressState: { esProgress, totalIndexingItems, estimatedMinutes, currentProgressValue },
} = useSearchLibrary();
const isEstimating = estimatedMinutes === 0 && (totalIndexingItems === 0 || esProgress !== totalIndexingItems);
const progressFromBuildEvent = isRefreshing ? 0 : progressRecorderRef.current[0];
const progressValue = isEstimating ? progressFromBuildEvent : currentProgressValue;
// Progress indicator
const totalProgressToShow = Math.max(esProgress, progressRecorderRef.current[1]);
let progressStatus: string = '';
if (isEstimating) {
progressStatus = c('Info').t`Estimating time remaining...`;
} else if (isRefreshing) {
progressStatus = c('Info').t`Updating drive search...`;
} else {
// translator: esProgress is a number representing the current file being fetched, totalIndexingItems is the total number of files in the drive
progressStatus = c('Info').jt`Indexing items ${esProgress} out of ${totalProgressToShow}` as string;
}
const etaMessage =
estimatedMinutes <= 1
? c('Info').t`Estimated time remaining: Less than a minute`
: // translator: the variable is a positive integer (written in digits) always strictly bigger than 1
c('Info').ngettext(
msgid`Estimated time remaining: ${estimatedMinutes} minute`,
`Estimated time remaining: ${estimatedMinutes} minutes`,
estimatedMinutes
);
return (
<div className="mt-6 flex flex-column">
<span className="color-weak relative advanced-search-progress-status" aria-live="polite" aria-atomic="true">
{progressStatus}
</span>
<div className="flex flex-justify-space-between">
<Progress
value={progressValue || 0}
aria-describedby="timeRemaining"
className={clsx(['my-2 flex-item-fluid'])}
/>
</div>
<span
id="timeRemaining"
aria-live="polite"
aria-atomic="true"
className={clsx([
'color-weak relative advanced-search-time-remaining',
isEstimating ? 'visibility-hidden' : undefined,
])}
>
{etaMessage}
</span>
</div>
);
};
| 2,782
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/search/useSearchParams.tsx
|
import { Dispatch, SetStateAction, useEffect, useState } from 'react';
import { useLocation } from 'react-router';
// TODO: handle it with containers
import { extractSearchParameters } from '../../../store/_search/utils';
export const useSearchParams = () => {
const location = useLocation();
const [value, updateValue] = useState('');
useEffect(() => {
updateValue(extractSearchParameters(location));
}, [location]);
return [value, updateValue] as [string, Dispatch<SetStateAction<string>>];
};
| 2,783
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/ActionMenu/ActionMenuButton.tsx
|
import { PropsWithChildren } from 'react';
import { c } from 'ttag';
import {
Dropdown,
DropdownMenu,
DropdownSizeUnit,
Icon,
SidebarPrimaryButton,
usePopperAnchor,
} from '@proton/components';
import { getDevice } from '@proton/shared/lib/helpers/browser';
import clsx from '@proton/utils/clsx';
import useActiveShare from '../../../../hooks/drive/useActiveShare';
import { useFileUploadInput, useFolderUploadInput } from '../../../../store';
import { useCreateFolderModal } from '../../../modals/CreateFolderModal';
import { CreateNewFolderButton, UploadFileButton, UploadFolderButton } from './ActionMenuButtons';
interface Props {
disabled?: boolean;
className?: string;
}
// We put all input in the parent components because we need input to be present in the DOM
// even when the dropdown is closed
export const ActionMenuButton = ({ disabled, className }: PropsWithChildren<Props>) => {
const { anchorRef, isOpen, toggle, close } = usePopperAnchor<HTMLButtonElement>();
const isDesktop = !getDevice()?.type;
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();
return (
<>
<SidebarPrimaryButton
ref={anchorRef}
disabled={disabled}
className={clsx(className, 'flex flex-justify-center flex-align-items-center')}
onClick={toggle}
>
<Icon className="mr-2" name="plus" />
{
// translator: this string is used on Proton Drive to open a drop-down with 3 actions: Upload file, folder and new folder
c('Action').t`New`
}
</SidebarPrimaryButton>
<input multiple type="file" ref={fileInput} className="hidden" onChange={fileChange} />
<input type="file" ref={folderInput} className="hidden" onChange={folderChange} />
{createFolderModal}
<Dropdown
size={{ width: DropdownSizeUnit.Anchor, height: DropdownSizeUnit.Dynamic }}
isOpen={isOpen}
anchorRef={anchorRef}
onClose={close}
>
<DropdownMenu className="my-1">
<UploadFileButton onClick={fileClick} />
{isDesktop && <UploadFolderButton onClick={folderClick} />}
<hr className="my-2" />
<CreateNewFolderButton onClick={showCreateFolderModal} />
</DropdownMenu>
</Dropdown>
</>
);
};
export default ActionMenuButton;
| 2,784
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/ActionMenu
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/ActionMenu/ActionMenuButtons/CreateNewFolderButton.tsx
|
import { c } from 'ttag';
import { DropdownMenuButton, Icon } from '@proton/components';
interface Props {
onClick: () => void;
}
const CreateNewFolderButton = ({ onClick }: Props) => {
return (
<DropdownMenuButton
className="text-left flex flex-align-items-center"
onClick={onClick}
data-testid="dropdown-new-folder"
>
<Icon className="mr-2" name="folder-plus" />
{c('Action').t`Create new folder`}
</DropdownMenuButton>
);
};
export default CreateNewFolderButton;
| 2,785
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/ActionMenu
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/ActionMenu/ActionMenuButtons/UploadFileButton.tsx
|
import { c } from 'ttag';
import { DropdownMenuButton, Icon } from '@proton/components';
interface Props {
onClick: () => void;
}
const UploadFileButton = ({ onClick }: Props) => {
return (
<>
<DropdownMenuButton
className="text-left flex flex-align-items-center"
onClick={onClick}
data-testid="dropdown-upload-file"
>
<Icon className="mr-2" name="file-arrow-in-up" />
{c('Action').t`Upload file`}
</DropdownMenuButton>
</>
);
};
export default UploadFileButton;
| 2,786
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/ActionMenu
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/ActionMenu/ActionMenuButtons/UploadFolderButton.tsx
|
import { c } from 'ttag';
import { DropdownMenuButton, Icon } from '@proton/components';
interface Props {
onClick: () => void;
}
const UploadFolderButton = ({ onClick }: Props) => {
return (
<>
<DropdownMenuButton
className="text-left flex flex-align-items-center"
onClick={onClick}
data-testid="dropdown-upload-folder"
>
<Icon className="mr-2" name="folder-arrow-up" />
{c('Action').t`Upload folder`}
</DropdownMenuButton>
</>
);
};
export default UploadFolderButton;
| 2,787
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/ActionMenu
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/ActionMenu/ActionMenuButtons/index.ts
|
export { default as CreateNewFolderButton } from './CreateNewFolderButton';
export { default as UploadFileButton } from './UploadFileButton';
export { default as UploadFolderButton } from './UploadFolderButton';
| 2,788
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/DriveSidebar/DriveSidebar.scss
|
@keyframes rotating {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
.location-refresh-rotate {
animation: rotating 0.5s linear infinite;
}
.drive-sidebar--icon {
inline-size: rem(16);
}
.drive-sidebar--button-expand {
&#{&} {
// Specificity -_-v
// In this case we want to have background change only on hover.
color: var(--text-weak);
margin-inline-start: calc(var(--space-1) * -1);
margin-inline-end: calc(var(--space-1) * -1);
&:first-child {
margin-inline-start: calc(var(--space-2) * -1);
}
&[aria-expanded='true'] {
color: var(--text-weak);
}
&:focus,
&[aria-expanded='true'] {
background-color: initial;
}
&:hover,
&[aria-expanded='true']:hover,
&:focus-visible {
background-color: var(--interaction-default-hover);
color: var(--text-norm);
}
}
}
.navigation > .navigation-list:last-child,
.navigation > div > .navigation-list:last-child {
padding-block-end: 0;
}
| 2,789
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/DriveSidebar/DriveSidebar.tsx
|
import { ReactNode, useEffect, useMemo, useState } from 'react';
import { c } from 'ttag';
import { ButtonLike } from '@proton/atoms/Button';
import {
AppsDropdown,
Icon,
SettingsLink,
Sidebar,
SidebarContactItem,
SidebarNav,
useDrawer,
useSubscription,
useUser,
} from '@proton/components';
import useDisplayContactsWidget from '@proton/components/hooks/useDisplayContactsWidget';
import { APPS, DRIVE_UPSELL_PATHS, UPSELL_COMPONENT } from '@proton/shared/lib/constants';
import { DRAWER_NATIVE_APPS } from '@proton/shared/lib/drawer/interfaces';
import { hasDrive, hasFree } from '@proton/shared/lib/helpers/subscription';
import { addUpsellPath, getUpsellRefFromApp } from '@proton/shared/lib/helpers/upsell';
import useActiveShare from '../../../../hooks/drive/useActiveShare';
import { useDebug } from '../../../../hooks/drive/useDebug';
import { ShareWithKey, useDefaultShare } from '../../../../store';
import { useCreateDevice } from '../../../../store/_shares/useCreateDevice';
import { useCreatePhotos } from '../../../../store/_shares/useCreatePhotos';
import DriveSidebarFooter from './DriveSidebarFooter';
import DriveSidebarList from './DriveSidebarList';
interface Props {
isHeaderExpanded: boolean;
toggleHeaderExpanded: () => void;
primary: ReactNode;
logo: ReactNode;
}
const DriveSidebar = ({ logo, primary, isHeaderExpanded, toggleHeaderExpanded }: Props) => {
const { activeShareId } = useActiveShare();
const { getDefaultShare } = useDefaultShare();
const { toggleDrawerApp } = useDrawer();
const debug = useDebug();
const [defaultShare, setDefaultShare] = useState<ShareWithKey>();
const { createDevice } = useCreateDevice();
const { createPhotosShare } = useCreatePhotos();
useEffect(() => {
void getDefaultShare().then(setDefaultShare);
}, [getDefaultShare]);
const displayContactsInHeader = useDisplayContactsWidget();
const [user] = useUser();
const [subscription] = useSubscription();
const { isMember, isSubUser } = user;
const shouldShowDriveUpsell = useMemo(() => {
if (!subscription || isSubUser || isMember) {
return false;
}
return hasFree(subscription) || hasDrive(subscription);
}, [isMember, isSubUser, subscription]);
/*
* The sidebar supports multiple shares, but as we currently have
* only one main share in use, we gonna use the default share only,
* unless the opposite is decided.
*/
const shares = defaultShare ? [defaultShare] : [];
return (
<Sidebar
appsDropdown={<AppsDropdown app={APPS.PROTONDRIVE} />}
logo={logo}
expanded={isHeaderExpanded}
onToggleExpand={toggleHeaderExpanded}
primary={primary}
version={<DriveSidebarFooter />}
contactsButton={
displayContactsInHeader && (
<SidebarContactItem
onClick={() => {
toggleHeaderExpanded();
toggleDrawerApp({ app: DRAWER_NATIVE_APPS.CONTACTS })();
}}
/>
)
}
growContent={false}
extraFooter={
shouldShowDriveUpsell && (
<ButtonLike
className="my-2 w-full flex gap-2 flex-align-items-center flex-justify-center"
as={SettingsLink}
color="norm"
shape="outline"
path={addUpsellPath(
'/upgrade',
getUpsellRefFromApp({
app: APPS.PROTONDRIVE,
feature: DRIVE_UPSELL_PATHS.SIDEBAR,
component: UPSELL_COMPONENT.BUTTON,
})
)}
>
<Icon name="cloud" />
{c('Storage').t`Get more storage`}
</ButtonLike>
)
}
>
<SidebarNav>
<div>
<DriveSidebarList shareId={activeShareId} userShares={shares} />
</div>
</SidebarNav>
{debug ? <button onClick={createDevice}>Create device</button> : null}
{debug ? <button onClick={createPhotosShare}>Create photos</button> : null}
</Sidebar>
);
};
export default DriveSidebar;
| 2,790
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/DriveSidebar/DriveSidebarFooter.tsx
|
import { AppVersion } from '@proton/components';
import changelog from '../../../../../../CHANGELOG.md';
const DriveSidebarFooter = () => <AppVersion changelog={changelog} />;
export default DriveSidebarFooter;
| 2,791
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/DriveSidebar/DriveSidebarList.tsx
|
import { useState } from 'react';
import { useRouteMatch } from 'react-router-dom';
import { c } from 'ttag';
import { SidebarList } from '@proton/components';
import { ShareWithKey, usePhotosFeatureFlag } from '../../../../store';
import { DriveSectionRouteProps } from '../../../sections/Drive/DriveView';
import DriveSidebarDevices from './DriveSidebarDevices';
import DriveSidebarFolders from './DriveSidebarFolders/DriveSidebarFolders';
import DriveSidebarListItem from './DriveSidebarListItem';
interface Props {
shareId?: string;
userShares: ShareWithKey[];
}
const DriveSidebarList = ({ shareId, userShares }: Props) => {
const match = useRouteMatch<DriveSectionRouteProps>();
const isPhotosEnabled = usePhotosFeatureFlag();
const [sidebarWidth, setSidebarWidth] = useState('100%');
const setSidebarLevel = (level: number) => {
const extraWidth = Math.floor(level / 7) * 50;
setSidebarWidth(`${100 + extraWidth}%`);
};
return (
<SidebarList style={{ width: sidebarWidth, maxWidth: sidebarWidth }}>
{userShares.map((userShare) => (
<DriveSidebarFolders
key={userShare.shareId}
path={match.url}
shareId={userShare.shareId}
linkId={userShare.rootLinkId}
setSidebarLevel={setSidebarLevel}
/>
))}
<DriveSidebarDevices path={match.url} setSidebarLevel={setSidebarLevel} />
{isPhotosEnabled && (
<DriveSidebarListItem to="/photos" icon="image" isActive={match.url === '/photos'}>
<span className="text-ellipsis" title={c('Link').t`Photos`}>
{c('Link').t`Photos`}
</span>
</DriveSidebarListItem>
)}
<DriveSidebarListItem
to="/shared-urls"
icon="link"
shareId={shareId}
isActive={match.url === '/shared-urls'}
>
<span className="text-ellipsis" title={c('Link').t`Shared`}>{c('Link').t`Shared`}</span>
</DriveSidebarListItem>
<DriveSidebarListItem to="/trash" icon="trash" shareId={shareId} isActive={match.url === '/trash'}>
<span className="text-ellipsis" title={c('Link').t`Trash`}>{c('Link').t`Trash`}</span>
</DriveSidebarListItem>
</SidebarList>
);
};
export default DriveSidebarList;
| 2,792
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/DriveSidebar/DriveSidebarListItem.tsx
|
import * as React from 'react';
import { MouseEventHandler } from 'react';
import {
IconName,
SidebarListItem,
SidebarListItemContent,
SidebarListItemContentIcon,
SidebarListItemLink,
} from '@proton/components';
import { useLoading } from '@proton/hooks';
import { wait } from '@proton/shared/lib/helpers/promise';
import { useDriveEventManager } from '../../../../store';
import { useVolumesState } from '../../../../store/_volumes';
interface Props {
children: React.ReactNode;
icon: IconName;
isActive: boolean;
shareId?: string;
to: string;
rightIcon?: React.ReactNode;
onDoubleClick?: () => void;
style?: React.CSSProperties;
onClick?: MouseEventHandler<HTMLLIElement>;
}
const DriveSidebarListItem = ({
to,
children,
icon,
shareId,
isActive,
rightIcon,
onDoubleClick,
style,
onClick,
}: Props) => {
const driveEventManager = useDriveEventManager();
const volumeState = useVolumesState();
const [refreshing, withRefreshing] = useLoading(false);
const left = icon ? <SidebarListItemContentIcon name={icon} /> : null;
const handleDoubleClick = () => {
onDoubleClick?.();
if (!refreshing && shareId) {
const volumeId = volumeState.findVolumeId(shareId);
if (volumeId) {
withRefreshing(
Promise.all([driveEventManager.pollEvents.driveEvents({ includeCommon: true }), wait(1000)])
).catch(console.warn);
}
}
};
return (
<SidebarListItem onClick={onClick}>
<SidebarListItemLink to={to} isActive={() => isActive}>
<div className="flex flex-nowrap" style={style}>
<SidebarListItemContent
onDoubleClick={handleDoubleClick}
left={left}
right={rightIcon}
title={typeof children === 'string' ? children : undefined}
data-testid="sidebar-main-sections"
>
{children}
</SidebarListItemContent>
</div>
</SidebarListItemLink>
</SidebarListItem>
);
};
export default DriveSidebarListItem;
| 2,793
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/DriveSidebar/index.ts
|
export { default } from './DriveSidebar';
| 2,794
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/DriveSidebar/utils.ts
|
export const generateSidebarItemStyle = (nestingLevel: number = 0) => {
return { marginLeft: `${(nestingLevel * 10) / 16}rem` };
};
| 2,795
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/DriveSidebar
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/DriveSidebar/DriveSidebarDevices/SidebarDeviceItem.tsx
|
import { useEffect } from 'react';
import useActiveShare from '../../../../../hooks/drive/useActiveShare';
import { useFolderTree } from '../../../../../store';
import { Device } from '../../../../../store/_devices';
import DriveSidebarSubfolders from '../DriveSidebarFolders/DriveSidebarSubfolders';
import ExpandButton from '../DriveSidebarFolders/ExpandButton';
import DriveSidebarListItem from '../DriveSidebarListItem';
import { generateSidebarItemStyle } from '../utils';
export const SidebarDeviceItem = ({
device,
setSidebarLevel,
}: {
device: Device;
setSidebarLevel: (level: number) => void;
}) => {
const { activeFolder } = useActiveShare();
const { deepestOpenedLevel, rootFolder, toggleExpand } = useFolderTree(device.shareId, {
rootLinkId: device.linkId,
});
useEffect(() => {
setSidebarLevel(deepestOpenedLevel);
}, [deepestOpenedLevel]);
const isActive = activeFolder.shareId === device.shareId && activeFolder.linkId === device.linkId;
return (
<div>
<DriveSidebarListItem
to={`/${device.shareId}/folder/${device.linkId}`}
icon="tv"
shareId={device.shareId}
isActive={isActive}
style={generateSidebarItemStyle(1)}
>
<span className="text-ellipsis" title={device.name}>
{device.name}
</span>
<ExpandButton
className="flex-item-noshrink"
expanded={Boolean(rootFolder?.isExpanded)}
onClick={() => toggleExpand(device.linkId)}
/>
</DriveSidebarListItem>
<DriveSidebarSubfolders
shareId={device.shareId}
rootFolder={rootFolder}
toggleExpand={toggleExpand}
defaultLevel={1}
/>
</div>
);
};
| 2,796
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/DriveSidebar
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/DriveSidebar/DriveSidebarDevices/SidebarDevices.tsx
|
import { useState } from 'react';
import { SidebarDeviceList } from './SidebarDevicesList';
import { SidebarDevicesRoot } from './SidebarDevicesRoot';
const DriveSidebarDevices = ({ path, setSidebarLevel }: { path: string; setSidebarLevel: (level: number) => void }) => {
const [isListExpanded, setListExpanded] = useState(false);
const toggleList = () => {
setListExpanded((value) => !value);
};
return (
<>
<SidebarDevicesRoot path={path} toggleExpand={toggleList} isExpanded={isListExpanded} />
<SidebarDeviceList isRootExpanded={isListExpanded} setSidebarLevel={setSidebarLevel} />
</>
);
};
export default DriveSidebarDevices;
| 2,797
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/DriveSidebar
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/DriveSidebar/DriveSidebarDevices/SidebarDevicesList.tsx
|
import { useDevicesListing } from '../../../../../store/_devices';
import { SidebarDeviceItem } from './SidebarDeviceItem';
export const SidebarDeviceList = ({
isRootExpanded,
setSidebarLevel,
}: {
isRootExpanded: boolean;
setSidebarLevel: (level: number) => void;
}) => {
const { cachedDevices } = useDevicesListing();
if (!isRootExpanded || cachedDevices?.length === 0) {
return null;
}
const sortedDevices = [...cachedDevices].sort((a, b) => {
const nameA = a.name.toUpperCase();
const nameB = b.name.toUpperCase();
if (nameA < nameB) {
return -1;
}
return nameA > nameB ? 1 : 0;
});
return (
<>
{sortedDevices.map((device) => (
<SidebarDeviceItem key={device.id + device.name} device={device} setSidebarLevel={setSidebarLevel} />
))}
</>
);
};
| 2,798
|
0
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/DriveSidebar
|
petrpan-code/ProtonMail/WebClients/applications/drive/src/app/components/layout/sidebar/DriveSidebar/DriveSidebarDevices/SidebarDevicesRoot.tsx
|
import { Loader } from '@proton/components';
import { useDevicesListing } from '../../../../../store/_devices';
import { getDevicesSectionName } from '../../../../sections/Devices/constants';
import ExpandButton from '../DriveSidebarFolders/ExpandButton';
import DriveSidebarListItem from '../DriveSidebarListItem';
export function SidebarDevicesRoot({
path,
isExpanded,
toggleExpand,
}: {
path: string;
toggleExpand: () => void;
isExpanded: boolean;
}) {
const { cachedDevices, isLoading } = useDevicesListing();
const sectionTitle = getDevicesSectionName();
return (
<DriveSidebarListItem
key="devices-root"
to={'/devices'}
icon="tv"
isActive={path === '/devices'}
onDoubleClick={toggleExpand}
>
<span className="text-ellipsis" title={sectionTitle}>
{sectionTitle}
</span>
{isLoading ? (
<Loader className="drive-sidebar--icon inline-flex flex-item-noshrink" />
) : (
cachedDevices.length > 0 && (
<ExpandButton className="flex-item-noshrink" expanded={isExpanded} onClick={() => toggleExpand()} />
)
)}
</DriveSidebarListItem>
);
}
| 2,799
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.