index
int64 0
0
| repo_id
stringlengths 16
181
| file_path
stringlengths 28
270
| content
stringlengths 1
11.6M
| __index_level_0__
int64 0
10k
|
|---|---|---|---|---|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/modal/PreviewPDFModal.js
|
import PropTypes from 'prop-types';
import { c } from 'ttag';
import FormModal from './FormModal';
/**
* @deprecated Please use ModalTwo instead
*/
const PreviewPDFModal = ({ url, title = c('Title').t`Preview`, filename, ...rest }) => {
return (
<FormModal title={title} close={c('Action').t`Close`} hasSubmit={false} {...rest}>
<object data={url} className="w-full" type="application/pdf" height={500} title={filename}>
<embed src={url} type="application/pdf" />
</object>
</FormModal>
);
};
PreviewPDFModal.propTypes = {
onClose: PropTypes.func,
url: PropTypes.string,
title: PropTypes.string,
filename: PropTypes.string,
};
export default PreviewPDFModal;
| 5,500
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/modal/Title.tsx
|
import { DetailedHTMLProps, HTMLAttributes, ReactNode } from 'react';
import clsx from '@proton/utils/clsx';
interface Props extends DetailedHTMLProps<HTMLAttributes<HTMLHeadingElement>, HTMLHeadingElement> {
id: string;
children: ReactNode;
}
/**
* @deprecated Please use ModalTwo instead
*/
const Title = ({ children, className, ...rest }: Props) => {
return (
<h1
className={clsx(['modal-title outline-none', className])}
data-focus-trap-fallback="0"
tabIndex={-1}
{...rest}
>
{children}
</h1>
);
};
export default Title;
| 5,501
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/modal/index.ts
|
export { default as DialogModal } from './Dialog';
export { default as ContentModal } from './Content';
export { default as InnerModal } from './Inner';
export { default as HeaderModal } from './Header';
export { default as TitleModal } from './Title';
export { default as FormModal } from './FormModal';
export { default as ConfirmModal } from './Confirm';
export * from './Confirm';
export { default as PreviewPDFModal } from './PreviewPDFModal';
export { default as FooterModal } from './Footer';
export { default as ModalCloseButton } from './ModalCloseButton';
| 5,502
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/modalTwo/Backdrop.scss
|
@import '~@proton/styles/scss/lib';
.modal-two-backdrop {
position: fixed;
z-index: $layer-modals;
inset: 0;
background: var(--backdrop-norm);
animation: 0.1s ease-out forwards;
&--out {
animation-name: anime-modal-two-backdrop-out;
}
&--in {
animation-name: anime-modal-two-backdrop-in;
}
@keyframes anime-modal-two-backdrop-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes anime-modal-two-backdrop-out {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
}
| 5,503
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/modalTwo/Backdrop.tsx
|
import { useEffect, useState } from 'react';
import { isDialogOpen, isModalOpen, modalTwoBackdropRootClassName } from '@proton/shared/lib/busy';
import clsx from '@proton/utils/clsx';
import './Backdrop.scss';
interface Props {
exiting: boolean;
entering: boolean;
}
const Backdrop = ({ entering, exiting }: Props) => {
const [hidden, setHidden] = useState(true);
/**
* Fix for CP-4425
* There is a possible race condition which means that the backdrop remains visible
* after opening a link from LinkConfirmationModal
*/
useEffect(() => {
const handleVisibilityChange = () => {
if (document.visibilityState === 'visible') {
/**
* Remove all modals if no modals are open.
* This removes the backdrop if it remains visible.
*/
if (!isDialogOpen() && !isModalOpen()) {
setHidden(true);
}
}
};
document.addEventListener('visibilitychange', handleVisibilityChange);
return () => {
document.removeEventListener('visibilitychange', handleVisibilityChange);
};
}, []);
const backdropClassName = clsx([
modalTwoBackdropRootClassName,
entering && 'modal-two-backdrop--in',
exiting && 'modal-two-backdrop--out',
!entering && hidden && 'hidden',
]);
return (
<div
className={backdropClassName}
onAnimationStart={({ animationName }) => {
if (animationName === 'anime-modal-two-backdrop-in' && entering) {
setHidden(false);
}
}}
onAnimationEnd={({ animationName }) => {
if (animationName === 'anime-modal-two-backdrop-out' && exiting) {
setHidden(true);
}
}}
/>
);
};
export default Backdrop;
| 5,504
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/modalTwo/BackdropContainer.tsx
|
import { Portal } from '../portal';
import Backdrop from './Backdrop';
import { useModalPositions } from './modalPositions';
const BackdropContainer = () => {
const [modalPositions] = useModalPositions();
return (
<Portal>
<Backdrop entering={modalPositions.length >= 1} exiting={modalPositions.length === 0} />
</Portal>
);
};
export default BackdropContainer;
| 5,505
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/modalTwo/BasicModal.tsx
|
import { ElementType, ReactNode } from 'react';
import { PolymorphicPropsWithoutRef } from 'react-polymorphic-types';
import ModalTwo, { ModalOwnProps as MainModalOwnProps } from './Modal';
import ModalTwoContent from './ModalContent';
import ModalTwoFooter from './ModalFooter';
import ModalTwoHeader from './ModalHeader';
import useModalState from './useModalState';
export interface BasicModalProps extends MainModalOwnProps {
title?: string;
children: ReactNode;
footer: ReactNode;
isOpen: boolean;
hasClose?: boolean;
subline?: string;
titleClassName?: string;
}
const BasicModal = <E extends ElementType>({
title,
children,
footer,
isOpen,
onClose,
onExit,
hasClose,
subline,
titleClassName,
...rest
}: PolymorphicPropsWithoutRef<BasicModalProps, E>) => {
const [modalProps] = useModalState({ open: isOpen, onClose, onExit });
return (
<ModalTwo {...rest} {...modalProps}>
<ModalTwoHeader titleClassName={titleClassName} title={title} subline={subline} hasClose={hasClose} />
<ModalTwoContent>{children}</ModalTwoContent>
{footer && <ModalTwoFooter>{footer}</ModalTwoFooter>}
</ModalTwo>
);
};
export default BasicModal;
| 5,506
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/modalTwo/Modal.scss
|
@import '~@proton/styles/scss/lib';
.modal-two {
position: fixed;
inset: 0;
z-index: $layer-modals;
display: flex;
padding: 3.5em;
overflow: hidden;
flex-flow: column nowrap;
align-items: center;
justify-content: center;
animation: 0.1s ease-out forwards;
animation-name: anime-modal-two-in;
@include media('<=small') {
padding: 2em;
}
@include media('<=xsmall') {
padding: 1em;
}
&--out {
animation-name: anime-modal-two-out;
}
&--out &-dialog {
animation-name: anime-modal-two-dialog-out;
}
&--fullscreen-on-mobile {
@include media('<=xsmall') {
padding: 0;
align-items: stretch;
background: none;
}
@include media('print') {
position: absolute;
inset-block-end: unset;
padding: em(10);
}
}
&--fullscreen-on-mobile &-dialog {
@include media('<=xsmall') {
flex: 1 0 100%;
border-radius: 0;
}
}
&--fullscreen {
padding: 0;
align-items: stretch;
background: none;
}
&--fullscreen &-dialog {
flex: 1 0 100%;
border-radius: 0;
max-inline-size: unset;
}
&--is-behind-backdrop {
z-index: $layer-modals - 1;
}
@keyframes anime-modal-two-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes anime-modal-two-out {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
&-dialog {
--size: #{rem(480)}; // medium
--margin: #{rem(32)};
@include media('<=small') {
--margin: #{rem(24)};
}
@include media('<=xsmall') {
--margin: #{rem(16)};
}
position: relative;
z-index: 1;
display: flex;
max-inline-size: var(--size);
inline-size: 100%;
overflow: hidden;
padding: 0;
margin: auto;
transform-origin: center top;
border-radius: var(--border-radius-lg);
box-shadow: var(--shadow-lifted);
background: var(--modal-background-color);
color: var(--modal-text-color);
animation: 0.25s easing(ease-out-cubic) both;
animation-name: anime-modal-two-dialog-in;
&-container {
flex-grow: 1;
max-inline-size: 100%;
display: flex;
flex-flow: column nowrap;
justify-content: flex-start;
align-items: stretch;
}
&--small {
--size: #{rem(392)};
--margin: #{rem(24)};
}
&--large {
--size: #{rem(600)};
}
&--xlarge {
--size: #{rem(800)};
}
&--full {
--size: 100%;
inline-size: var(--size);
}
@keyframes anime-modal-two-dialog-in {
0% {
transform: scale(0.9);
}
100% {
transform: scale(1);
}
}
@keyframes anime-modal-two-dialog-out {
0% {
transform: scale(1);
}
100% {
transform: scale(0.9);
}
}
}
}
| 5,507
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/modalTwo/Modal.tsx
|
import { type ElementType, createContext, useEffect, useLayoutEffect, useRef, useState } from 'react';
import { type PolymorphicPropsWithoutRef } from 'react-polymorphic-types';
import useInstance from '@proton/hooks/useInstance';
import usePrevious from '@proton/hooks/usePrevious';
import { modalTwoRootClassName } from '@proton/shared/lib/busy';
import clsx from '@proton/utils/clsx';
import { generateUID } from '../../helpers';
import { useHotkeys } from '../../hooks';
import Dialog from '../dialog/Dialog';
import { useFocusTrap } from '../focus';
import { Portal } from '../portal';
import { useModalPosition } from './modalPositions';
import './Modal.scss';
export type ModalSize = 'small' | 'medium' | 'large' | 'xlarge' | 'full';
/**
* Omission of id from ModalOwnProps because in ModalOwnProps "id"
* is optional, whereas in ModalContextValue it is guaranteed.
* Same for size.
*/
type ModalContextValue = ModalOwnProps & { id: string; size: ModalSize };
export const ModalContext = createContext({} as ModalContextValue);
export interface ModalOwnProps {
/**
* Whether the modal is open or not.
*/
open?: boolean;
/**
* Whether the modal should render behind the backdrop
*/
behind?: boolean;
size?: ModalSize;
fullscreenOnMobile?: boolean;
fullscreen?: boolean;
/**
* Disables closing the modal by pressing the 'Escape' key.
*/
disableCloseOnEscape?: boolean;
/**
* Optional id to overwrite the internally generated id, which
* is used for accessibility purposes (e.g.aria-labelledby & id
* of the Title in ModalHeader)
*/
id?: string;
/**
* Allow an additional classname on the root element
*/
rootClassName?: string;
/**
* Fires when the user clicks on the close button or when he
* presses the escape key, unless 'disableCloseOnEscape' is
* set to true.
*/
onClose?: () => void;
/**
* Fires when the Modal has finished its enter animation.
*/
onEnter?: () => void;
/**
* Fires when the Modal has finished its exit animation.
*/
onExit?: () => void;
/**
* Fires when the user clicks on the backdrop outside of the Dialog
*/
onBackdropClick?: () => void;
/**
* Whether the modal should close when clicking outside of it.
*/
enableCloseWhenClickOutside?: boolean;
}
enum ExitState {
idle,
exiting,
exited,
}
const defaultElement = 'div';
export type ModalProps<E extends ElementType = typeof defaultElement> = PolymorphicPropsWithoutRef<ModalOwnProps, E>;
const Modal = <E extends ElementType = typeof defaultElement>({
open,
size = 'medium',
fullscreenOnMobile,
fullscreen,
onClose,
onEnter,
onExit,
onBackdropClick,
onAnimationEnd,
disableCloseOnEscape,
enableCloseWhenClickOutside,
className,
rootClassName,
behind,
as,
...rest
}: PolymorphicPropsWithoutRef<ModalOwnProps, E>) => {
const [exit, setExit] = useState(() => (open ? ExitState.idle : ExitState.exited));
const id = useInstance(() => generateUID('modal'));
const backdropRef = useRef<HTMLDivElement>(null);
const dialogRef = useRef(null);
const active = exit !== ExitState.exited;
const last = useModalPosition(active || false);
const focusTrapProps = useFocusTrap({
active,
rootRef: dialogRef,
});
const modalContextValue: ModalContextValue = {
id,
open,
size,
onClose,
disableCloseOnEscape,
};
const previousOpen = usePrevious(open);
useLayoutEffect(() => {
if (!previousOpen && open) {
setExit(ExitState.idle);
} else if (previousOpen && !open) {
setExit(ExitState.exiting);
}
}, [previousOpen, open]);
useHotkeys(
dialogRef,
[
[
'Escape',
(e) => {
if (!active || disableCloseOnEscape) {
return;
}
e.stopPropagation();
onClose?.();
},
],
],
{ dependencies: [active, disableCloseOnEscape] }
);
/* Relying on a `click` event listener is unsufficient :
* - user might hold his mouse down and try to cancel the
* backdrop click by moving away from the backdrop for the
* mouse up.
* - `mousedown` will trigger before the `click` event and we
* may lose focus on any child field currently focused */
useEffect(() => {
if (!active) {
return;
}
const handleBackdropMouseDown = (mouseDownEvt: MouseEvent) => {
/* prevents focus loss when mouse down on backdrop */
if (mouseDownEvt.target === backdropRef.current) {
mouseDownEvt.preventDefault();
backdropRef.current?.addEventListener(
'mouseup',
(mouseUpEvt) => mouseUpEvt.target === backdropRef.current && onBackdropClick?.(),
{ once: true }
);
}
};
backdropRef.current?.addEventListener('mousedown', handleBackdropMouseDown);
return () => backdropRef.current?.removeEventListener('mousedown', handleBackdropMouseDown);
}, [onBackdropClick, active]);
if (!active) {
return null;
}
const exiting = exit === ExitState.exiting;
const Element: ElementType = as || defaultElement;
return (
<Portal>
<div
ref={backdropRef}
className={clsx([
modalTwoRootClassName,
rootClassName,
exiting && 'modal-two--out',
fullscreenOnMobile && 'modal-two--fullscreen-on-mobile',
fullscreen && 'modal-two--fullscreen',
(!last || behind) && 'modal-two--is-behind-backdrop',
])}
onAnimationEnd={({ animationName }) => {
if (animationName === 'anime-modal-two-in') {
onEnter?.();
}
if (exiting && animationName === 'anime-modal-two-out') {
setExit(ExitState.exited);
onExit?.();
}
}}
onClick={(e) => {
if (enableCloseWhenClickOutside && e.target === e.currentTarget) {
onClose?.();
}
}}
>
<Dialog
ref={dialogRef}
aria-labelledby={id}
aria-describedby={`${id}-description`}
{...focusTrapProps}
className={clsx([
'modal-two-dialog outline-none',
className,
size === 'small' && 'modal-two-dialog--small',
size === 'large' && 'modal-two-dialog--large',
size === 'xlarge' && 'modal-two-dialog--xlarge',
size === 'full' && 'modal-two-dialog--full',
])}
>
<ModalContext.Provider value={modalContextValue}>
<Element className="modal-two-dialog-container" {...rest} />
</ModalContext.Provider>
</Dialog>
</div>
</Portal>
);
};
export default Modal;
| 5,508
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/modalTwo/ModalContent.scss
|
.modal-two-content {
margin-block: 0.5em 1em;
margin-inline: var(--margin);
& > *:first-child {
margin-block-start: 0;
}
& > *:last-child {
margin-block-end: 0;
}
}
| 5,509
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/modalTwo/ModalContent.tsx
|
import { ComponentPropsWithoutRef, useContext } from 'react';
import { Scroll } from '@proton/atoms/Scroll';
import clsx from '@proton/utils/clsx';
import { ModalContext } from './Modal';
import './ModalContent.scss';
export type ModalContentProps = ComponentPropsWithoutRef<'div'>;
const ModalContent = ({ className, ...rest }: ModalContentProps) => {
const { id } = useContext(ModalContext);
return (
<Scroll className="overflow-hidden">
<div id={`${id}-description`} className={clsx([className, 'modal-two-content'])} {...rest} />
</Scroll>
);
};
export default ModalContent;
| 5,510
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/modalTwo/ModalFooter.scss
|
@import '~@proton/styles/scss/lib';
.modal-two-footer {
display: flex;
margin-block: 1em calc(var(--margin) - 0.5em);
margin-inline: var(--margin);
justify-content: space-between;
flex-wrap: wrap-reverse;
flex-shrink: 0;
@include media('<=xsmall') {
flex-direction: column-reverse;
align-items: stretch;
}
&--full {
@include media('>xsmall') {
justify-content: flex-end;
& > *:not(:first-child) {
margin-inline-start: 0.5em;
}
}
}
& > * {
// When children are stacked
margin-block-end: 0.5em;
}
}
| 5,511
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/modalTwo/ModalFooter.tsx
|
import { ComponentPropsWithoutRef, useContext } from 'react';
import clsx from '@proton/utils/clsx';
import { ModalContext } from './Modal';
import './ModalFooter.scss';
const ModalFooter = ({ className: classNameProp, ...rest }: ComponentPropsWithoutRef<'div'>) => {
const { size } = useContext(ModalContext);
const className = clsx([classNameProp, 'modal-two-footer', size === 'full' && 'modal-two-footer--full']);
return <div className={className} {...rest} />;
};
export default ModalFooter;
| 5,512
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/modalTwo/ModalHeader.scss
|
@import '~@proton/styles/scss/lib';
.modal-two-header {
margin-block: var(--margin) 0.5em;
margin-inline: var(--margin);
&-actions {
margin-block-start: em(-9.5); // Same as button for icon
margin-inline-end: em(-10); // Same as button for icon
* + * {
margin-inline-start: 0.25em;
}
}
&-title + &-actions {
margin-block-start: 0;
}
}
| 5,513
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/modalTwo/ModalHeader.tsx
|
import React, { ComponentPropsWithRef, ReactElement, ReactNode, cloneElement, useContext } from 'react';
import { c } from 'ttag';
import { Button, ButtonProps, Vr } from '@proton/atoms';
import generateUID from '@proton/atoms/generateUID';
import clsx from '@proton/utils/clsx';
import { Icon } from '../icon';
import { Tooltip } from '../tooltip';
import { ModalContext } from './Modal';
import './ModalHeader.scss';
interface ModalHeaderProps extends Omit<ComponentPropsWithRef<'div'>, 'children' | 'title'> {
/**
* The title to render in the Modal header.
*/
title?: ReactNode;
/**
* A subline to render below the Title.
* Will not render unless "title" is passed as well.
*/
subline?: string | JSX.Element;
/**
* Intended for use with icon buttons.
* Slot for Element(s) to be rendered next to the close button.
*
*/
actions?: JSX.Element | JSX.Element[];
/**
* Props forwarded to the close Button component
*/
closeButtonProps?: ButtonProps;
/**
* Is the close button displayed? defaults to true
*/
hasClose?: boolean;
/**
* Optional additional title classNames
*/
titleClassName?: string;
/**
* Additional content to be rendered above the scrollable section.
*/
additionalContent?: JSX.Element;
}
const ModalHeader = ({
title,
subline,
actions,
closeButtonProps,
titleClassName,
additionalContent,
hasClose = true,
...rest
}: ModalHeaderProps) => {
const { id, onClose, size } = useContext(ModalContext);
const actionsArray = Array.isArray(actions) ? actions : [actions];
return (
<div className="modal-two-header">
<div
className={clsx(
'flex flex-nowrap flex-item-noshrink flex-align-items-start',
title ? 'flex-justify-space-between' : 'flex-justify-end'
)}
{...rest}
>
{title && (
<div className="modal-two-header-title mt-1">
<h1
id={id}
className={clsx(
'text-bold',
['large', 'full'].includes(size) ? 'text-4xl' : 'text-2xl',
titleClassName
)}
>
{title}
</h1>
{subline && <div className="color-weak text-break">{subline}</div>}
</div>
)}
<div className="modal-two-header-actions flex flex-item-noshrink flex-nowrap flex-align-items-stretch">
{actions && (
<>
{actionsArray.map((action) =>
cloneElement(action as ReactElement, { key: generateUID('modal-action') })
)}
<Vr className="my-1" />
</>
)}
{hasClose && (
<Tooltip title={c('Action').t`Close`}>
<Button
className="flex-item-noshrink"
icon
shape="ghost"
data-testid="modal:close"
onClick={onClose}
{...closeButtonProps}
>
<Icon className="modal-close-icon" name="cross-big" alt={c('Action').t`Close`} />
</Button>
</Tooltip>
)}
</div>
</div>
{additionalContent}
</div>
);
};
export default ModalHeader;
| 5,514
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/modalTwo/ModalTwo.test.tsx
|
import { ReactNode, useEffect, useState } from 'react';
import { fireEvent, render, screen } from '@testing-library/react';
import { Button } from '@proton/atoms';
import ModalTwo from './Modal';
// Mocked so that the modal renders in the same container
jest.mock('react-dom', () => {
const original = jest.requireActual('react-dom');
return {
...original,
createPortal: (node: any) => node,
};
});
const Inner = ({ onMount }: { onMount: () => void }) => {
useEffect(() => {
onMount();
}, []);
return <div data-testid="inner">I'm only mounted once</div>;
};
const MyModal = ({
open,
onClose,
children,
disableCloseOnEscape,
}: {
open: boolean;
onClose: () => void;
children: ReactNode;
disableCloseOnEscape?: boolean;
}) => {
return (
<ModalTwo open={open} onClose={onClose} disableCloseOnEscape={disableCloseOnEscape}>
{children}
<Button data-testid="close-button" onClick={onClose} />
</ModalTwo>
);
};
const Container = ({
children,
open: initialOpen = false,
disableCloseOnEscape,
}: {
children: ReactNode;
open?: boolean;
disableCloseOnEscape?: boolean;
}) => {
const [open, setOpen] = useState(initialOpen);
return (
<>
<Button data-testid="open-button" onClick={() => setOpen(true)} />
<MyModal open={open} onClose={() => setOpen(false)} disableCloseOnEscape={disableCloseOnEscape}>
{children}
</MyModal>
</>
);
};
const getOutModal = (container: Element) => {
return container.querySelector('.modal-two--out');
};
const maybeTriggerOutAnimation = (div?: Element | null) => {
if (!div) {
return;
}
fireEvent.animationEnd(div, { animationName: 'anime-modal-two-out' });
};
describe('ModalTwo rendering', () => {
it('should not render children when closed', () => {
const { queryByTestId } = render(
<ModalTwo>
<div data-testid="inner">Not rendered</div>
</ModalTwo>
);
expect(queryByTestId('inner')).toBeNull();
});
it('should render children when open', () => {
const { queryByTestId } = render(
<ModalTwo open>
<div data-testid="inner">Rendered</div>
</ModalTwo>
);
expect(queryByTestId('inner')).toHaveTextContent('Rendered');
});
it('should render children when going from closed to open', () => {
const { getByTestId, queryByTestId } = render(
<Container>
<div data-testid="inner">Rendered</div>
</Container>
);
expect(queryByTestId('inner')).toBeNull();
fireEvent.click(getByTestId('open-button'));
expect(queryByTestId('inner')).toHaveTextContent('Rendered');
});
it('should not render children when going from open to closed', () => {
const { container, getByTestId, queryByTestId } = render(
<Container open>
<div data-testid="inner">Rendered</div>
</Container>
);
expect(getOutModal(container)).toBeNull();
expect(queryByTestId('inner')).toHaveTextContent('Rendered');
fireEvent.click(getByTestId('close-button'));
maybeTriggerOutAnimation(getOutModal(container));
expect(queryByTestId('inner')).toBeNull();
});
it('should only trigger mount once per render', async () => {
const handleMount = jest.fn();
const { container, getByTestId, queryByTestId } = render(
<Container>
<Inner onMount={handleMount} />
</Container>
);
const run = (n: number) => {
expect(getOutModal(container)).toBeNull();
expect(handleMount).toHaveBeenCalledTimes(n);
expect(queryByTestId('inner')).toBeNull();
fireEvent.click(getByTestId('open-button'));
expect(getOutModal(container)).toBeNull();
expect(handleMount).toHaveBeenCalledTimes(n + 1);
expect(queryByTestId('inner')).toHaveTextContent('mounted once');
fireEvent.click(getByTestId('close-button'));
maybeTriggerOutAnimation(getOutModal(container));
expect(queryByTestId('inner')).toBeNull();
expect(handleMount).toHaveBeenCalledTimes(n + 1);
};
run(0);
run(1);
run(2);
});
it('should only trigger mount once per render if initially opened', async () => {
const handleMount = jest.fn();
const { container, getByTestId, queryByTestId } = render(
<Container open={true}>
<Inner onMount={handleMount} />
</Container>
);
const run = (n: number) => {
expect(getOutModal(container)).toBeNull();
expect(handleMount).toHaveBeenCalledTimes(n);
expect(queryByTestId('inner')).toHaveTextContent('mounted once');
fireEvent.click(getByTestId('close-button'));
maybeTriggerOutAnimation(getOutModal(container));
expect(queryByTestId('inner')).toBeNull();
expect(handleMount).toHaveBeenCalledTimes(n);
fireEvent.click(getByTestId('open-button'));
expect(getOutModal(container)).toBeNull();
expect(handleMount).toHaveBeenCalledTimes(n + 1);
expect(queryByTestId('inner')).toHaveTextContent('mounted once');
};
run(1);
run(2);
run(3);
});
});
describe('ModalTwo Hotkeys', () => {
it('should close on esc', () => {
const { container, getByTestId, queryByTestId } = render(
<Container open={true}>
<div data-testid="inner">Rendered</div>
</Container>
);
expect(getOutModal(container)).toBeNull();
expect(queryByTestId('inner')).toHaveTextContent('Rendered');
fireEvent.keyDown(getByTestId('close-button'), { key: 'Escape' });
maybeTriggerOutAnimation(getOutModal(container));
expect(queryByTestId('inner')).toBeNull();
});
it('should not close on esc if disabled', () => {
const { container, getByTestId, queryByTestId } = render(
<Container open={true} disableCloseOnEscape>
<div data-testid="inner">Rendered</div>
</Container>
);
expect(getOutModal(container)).toBeNull();
expect(queryByTestId('inner')).toHaveTextContent('Rendered');
fireEvent.keyDown(getByTestId('close-button'), { key: 'Escape' });
maybeTriggerOutAnimation(getOutModal(container));
expect(queryByTestId('inner')).toHaveTextContent('Rendered');
});
});
/**
* Due to a JSDom issue `dialog` tag is not understood correctly
* Delete this test when the Jest will implement the fix
* - Issue: https://github.com/jsdom/jsdom/issues/3294
* - Fix pull request: https://github.com/jsdom/jsdom/pull/3403
*/
describe('ModalTwo GetByRole issue', () => {
it('Content should be selectable by role', () => {
render(
<ModalTwo open>
<Button>Hello</Button>
</ModalTwo>
);
expect(screen.getByRole('button', { name: 'Hello' })).toBeVisible();
});
});
| 5,515
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/modalTwo/index.ts
|
export { default as ModalTwo } from './Modal';
export * from './Modal';
export { default as ModalTwoContent } from './ModalContent';
export * from './ModalContent';
export { default as ModalTwoFooter } from './ModalFooter';
export { default as ModalTwoHeader } from './ModalHeader';
export { default as useModalState } from './useModalState';
export { useModalTwo } from './useModalTwo';
export * from './useModalState';
export { default as BasicModal } from './BasicModal';
| 5,516
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/modalTwo/modalPositions.tsx
|
import { ReactNode, createContext, useCallback, useContext, useLayoutEffect, useState } from 'react';
import noop from '@proton/utils/noop';
const ModalPositionsContext = createContext<[any[], (id: any) => () => void]>([[], () => noop]);
export const ModalPositionsProvider = ({ children }: { children: ReactNode }) => {
const [modals, setModals] = useState<any[]>([]);
const addModal = useCallback((id) => {
setModals((oldModals) => [id, ...oldModals]);
return () => {
setModals((oldModals) =>
oldModals.filter((otherId) => {
return id !== otherId;
})
);
};
}, []);
return <ModalPositionsContext.Provider value={[modals, addModal]}>{children}</ModalPositionsContext.Provider>;
};
export const useModalPositions = () => {
return useContext(ModalPositionsContext);
};
export const useModalPosition = (open: boolean): boolean => {
const [modals, addModal] = useModalPositions();
const [id] = useState(() => ({}));
useLayoutEffect(() => {
if (!open) {
return;
}
const removeModal = addModal(id);
return () => {
removeModal();
};
}, [open]);
return modals[0] === id;
};
| 5,517
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/modalTwo/useModalState.ts
|
import { useState } from 'react';
import useControlled from '@proton/hooks/useControlled';
import { generateUID } from '../../helpers';
export interface ModalStateProps {
key: string;
open: boolean;
onClose: () => void;
onExit: () => void;
}
const useModalState = (options?: { open?: boolean; onClose?: () => void; onExit?: () => void }) => {
const { open: controlledOpen, onClose, onExit } = options || {};
const [key, setKey] = useState(() => generateUID());
const [open, setOpen] = useControlled(controlledOpen);
const [render, setRender] = useState(open);
const handleSetOpen = (newValue: boolean) => {
if (newValue) {
setOpen(true);
setRender(true);
} else {
setOpen(false);
}
};
const handleClose = () => {
handleSetOpen(false);
onClose?.();
};
const handleExit = () => {
setRender(false);
setKey(generateUID());
onExit?.();
};
const modalProps: ModalStateProps = {
key,
open: !!open,
onClose: handleClose,
onExit: handleExit,
};
return [modalProps, handleSetOpen, render] as const;
};
export default useModalState;
| 5,518
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/modalTwo/useModalTwo.tsx
|
import { ComponentType, useRef, useState } from 'react';
import noop from '@proton/utils/noop';
import useModalState from './useModalState';
export interface ModalTwoPromiseHandlers<Value> {
onResolve: (value: Value) => void;
onReject: (reason?: any) => void;
}
export const useModalTwo = function <OwnProps, Value>(
Modal: ComponentType<any>,
usePromise = true
): [JSX.Element | null, (ownProps: OwnProps) => Promise<Value>] {
const [props, setOpen, render] = useModalState();
const [ownProps, setOwnProps] = useState<OwnProps>();
const promiseRef = useRef<{
promise: Promise<Value>;
resolve: (value: Value) => void;
reject: (reason?: any) => void;
}>();
const createPromise = () => {
let resolve: (value: Value) => void = noop;
let reject: (reason?: any) => void = noop;
const promise = new Promise<Value>((res, rej) => {
resolve = res;
reject = rej;
});
promiseRef.current = { promise, resolve, reject };
return promise;
};
const handleShowModal = (ownProps: OwnProps) => {
setOwnProps(ownProps);
setOpen(true);
return createPromise();
};
const handleResolve = (value: Value) => {
promiseRef.current?.resolve(value);
props.onClose();
};
const handleReject = (reason?: any) => {
promiseRef.current?.reject(reason);
props.onClose();
};
const promiseHandlers: Partial<ModalTwoPromiseHandlers<Value>> = usePromise
? { onResolve: handleResolve, onReject: handleReject }
: {};
const modal = render ? <Modal {...props} {...ownProps} {...promiseHandlers} /> : null;
return [modal, handleShowModal];
};
| 5,519
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/newFeatureTag/NewFeatureTag.test.tsx
|
import { render, screen } from '@testing-library/react';
import { IsActiveInEnvironmentContainer, SpotlightProps } from '@proton/components/components';
import { getItem, removeItem, setItem } from '@proton/shared/lib/helpers/storage';
import NewFeatureTag from './NewFeatureTag';
jest.mock('@proton/shared/lib/helpers/storage');
const mockedGetItem = jest.mocked(getItem);
const mockedSetItem = jest.mocked(setItem);
const mockedRemoveItem = jest.mocked(removeItem);
const SPOTLIGHT_ID = 'this-is-a-mocked-spotlight';
const NEW_FEATURE_TAG_ID = 'this-is-a-test-instance-of-new-feature-tag';
jest.mock('@proton/components/components', () => ({
__esModule: true,
Spotlight: () => <div data-testid={SPOTLIGHT_ID}></div>,
}));
describe('NewFeatureTag component', () => {
const featureKey = 'feature-key';
const localStorageKey = `${featureKey}-new-tag`;
const defaultValue = 'false';
beforeEach(() => {
// Monday, April 24, 2023 9:00:00 AM
jest.setSystemTime(new Date('2023-04-24T09:00:00'));
jest.clearAllMocks();
});
it('NewFeatureTag should be always shown by default', () => {
// Friday, December 1, 2023 9:00:00 AM
const endDate = new Date('2023-12-1T09:00:00');
mockedGetItem.mockReturnValue(undefined);
const { rerender } = render(<NewFeatureTag featureKey={featureKey} className="ml-10" endDate={endDate} />);
expect(screen.getByText('New')).toBeInTheDocument();
rerender(<NewFeatureTag featureKey={featureKey} className="ml-10" />);
expect(mockedGetItem).toHaveBeenCalledWith(localStorageKey, defaultValue);
expect(mockedSetItem).not.toHaveBeenCalled();
expect(mockedRemoveItem).not.toHaveBeenCalled();
});
it('NewFeatureTag should be show once with showOnce', () => {
const { rerender, unmount } = render(<NewFeatureTag featureKey={featureKey} showOnce className="ml-10" />);
expect(screen.getByText('New')).toBeInTheDocument();
expect(mockedGetItem).toHaveBeenCalledWith(localStorageKey, defaultValue);
unmount();
expect(mockedSetItem).toHaveBeenCalledWith(`${featureKey}-new-tag`, 'true');
mockedGetItem.mockReturnValue('true');
rerender(<NewFeatureTag featureKey={featureKey} showOnce className="ml-10" />);
expect(mockedRemoveItem).not.toHaveBeenCalledWith();
expect(screen.queryByText('New')).not.toBeInTheDocument();
});
it('NewFeatureTag should not be shown if date end', () => {
// Thursday, December 1, 2022 9:00:00 AM
const endDate = new Date('2022-12-01T09:00:00');
const { unmount } = render(<NewFeatureTag featureKey={featureKey} endDate={endDate} className="ml-10" />);
expect(screen.queryByText('New')).not.toBeInTheDocument();
expect(mockedSetItem).not.toHaveBeenCalled();
expect(mockedRemoveItem).toHaveBeenCalledWith(`${featureKey}-new-tag`);
unmount();
expect(setItem).not.toHaveBeenCalled();
});
it('should add a Spotlight', () => {
const spotlightProps: SpotlightProps = {
show: true,
content: <div></div>,
};
const result = render(
<NewFeatureTag featureKey={'doesntmatterhere'} spotlightProps={spotlightProps}></NewFeatureTag>
);
expect(result.getByTestId(SPOTLIGHT_ID)).toBeTruthy();
});
it('should not render if it was not in the proper environment', () => {
const environmentDontRender: IsActiveInEnvironmentContainer = {
default: false,
alpha: false,
beta: false,
};
const resultNotRendered = render(
<NewFeatureTag
data-testid=""
featureKey={'doesntmatterhere'}
isActiveInEnvironment={environmentDontRender}
></NewFeatureTag>
);
expect(() => resultNotRendered.getByTestId(NEW_FEATURE_TAG_ID)).toThrowError(
'Unable to find an element by: [data-testid="this-is-a-test-instance-of-new-feature-tag"]'
);
const environmentRender: IsActiveInEnvironmentContainer = {
default: true,
alpha: true,
beta: true,
};
const resultRendered = render(
<NewFeatureTag
data-testid=""
featureKey={'doesntmatterhere'}
isActiveInEnvironment={environmentRender}
></NewFeatureTag>
);
expect(() => resultRendered.getByTestId(NEW_FEATURE_TAG_ID)).toBeTruthy();
});
});
| 5,520
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/newFeatureTag/NewFeatureTag.tsx
|
import React, { useEffect, useState } from 'react';
import { isPast } from 'date-fns';
import { c } from 'ttag';
import { Spotlight, SpotlightProps } from '@proton/components/components';
import { versionCookieAtLoad } from '@proton/components/hooks/useEarlyAccess';
import { getItem, removeItem, setItem } from '@proton/shared/lib/helpers/storage';
import { EnvironmentExtended } from '@proton/shared/lib/interfaces';
import clsx from '@proton/utils/clsx';
export type IsActiveInEnvironmentContainer = { [key in EnvironmentExtended]?: boolean };
interface Props {
/** Used for localStorage key */
featureKey: string;
/** Will be hide after the user saw it once */
showOnce?: boolean;
/** A date/timestamp when the tag should not be shown anymore */
endDate?: number | Date;
/** Css classes to be applied */
className?: string;
/** When provided, NewFeatureTag will wrap the tag in a Spotlight and pass this property object to it */
spotlightProps?: SpotlightProps;
/**
* When provided, NewFeatureTag be rendered only in environments listed as true in the container
* E.g.: { default: true, alpha: ture } will be rendered in default and alpha but not in beta
* isActiveInEnvironment === undefined will render NewFeatureTag in all environments
*/
isActiveInEnvironment?: IsActiveInEnvironmentContainer;
}
// This NewFeatureTag component is meant to be used to show to the user that a new product feature has dropped
const NewFeatureTag = ({
featureKey,
showOnce = false,
endDate,
className,
spotlightProps,
isActiveInEnvironment,
}: Props) => {
const key = `${featureKey}-new-tag`;
const [wasShown] = useState<boolean>(Boolean(getItem(key, 'false')));
const hasEnded = endDate && isPast(endDate);
const displaySpotlight = !!spotlightProps;
useEffect(() => {
if (hasEnded) {
// Cleanup until the NewFeatureTag call is removed from code
removeItem(key);
} else if (showOnce) {
setItem(key, 'true');
}
}, [hasEnded, showOnce, key]);
if (!!isActiveInEnvironment && !isActiveInEnvironment[versionCookieAtLoad ?? 'default']) {
return null;
}
if ((showOnce && wasShown) || hasEnded) {
return null;
}
const content = (
<span className={clsx('bg-success px-1 py-0.5 rounded text-semibold', className)}>{c('Info').t`New`}</span>
);
if (displaySpotlight) {
return <Spotlight {...spotlightProps}>{content}</Spotlight>;
}
return content;
};
export default NewFeatureTag;
| 5,521
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/newFeatureTag/index.ts
|
export { default as NewFeatureTag } from './NewFeatureTag';
export type { IsActiveInEnvironmentContainer } from './NewFeatureTag';
| 5,522
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/notifications/index.ts
|
export { default as LinkConfirmationModal } from './LinkConfirmationModal/LinkConfirmationModal';
| 5,523
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/notifications
|
petrpan-code/ProtonMail/WebClients/packages/components/components/notifications/LinkConfirmationModal/LinkConfirmationModal.tsx
|
import { useState } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { updateConfirmLink } from '@proton/shared/lib/api/mailSettings';
import { openNewTab } from '@proton/shared/lib/helpers/browser';
import { rtlSanitize } from '@proton/shared/lib/helpers/string';
import { CONFIRM_LINK } from '@proton/shared/lib/mail/mailSettings';
import { useApi, useEventManager } from '../../../hooks';
import { Form } from '../../form';
import { ModalProps, ModalStateProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader } from '../../modalTwo';
import LinkConfirmationModalLink from './LinkConfirmationModalLink';
import LinkConfirmationModalPhishing from './LinkConfirmationModalPhishing';
interface Props extends ModalProps {
link?: string;
isOutside?: boolean;
isPhishingAttempt?: boolean;
modalProps: ModalStateProps;
}
const LinkConfirmationModal = ({ link = '', isOutside = false, isPhishingAttempt = false, modalProps }: Props) => {
const api = useApi();
const { call } = useEventManager();
const [dontAskAgain, setDontAskAgain] = useState(false);
const [understandRisk, setUnderstandRisk] = useState(false);
// https://jira.protontech.ch/browse/SEC-574
const linkToShow = rtlSanitize(link);
// Both are not able to open the link
const isPunnyCodeLink = /:\/\/xn--/.test(link);
const handleConfirm = async () => {
modalProps.onClose();
openNewTab(link);
if (dontAskAgain && !isOutside) {
await api(updateConfirmLink(CONFIRM_LINK.DISABLED));
await call();
}
};
return (
<ModalTwo size="large" as={Form} onSubmit={handleConfirm} {...modalProps}>
<ModalTwoHeader
title={
isPhishingAttempt ? c('Title').t`Warning: suspected fake website` : c('Title').t`Link confirmation`
}
/>
<ModalTwoContent>
{isPhishingAttempt ? (
<LinkConfirmationModalPhishing
link={linkToShow}
onToggle={() => setUnderstandRisk(!understandRisk)}
value={understandRisk}
/>
) : (
<LinkConfirmationModalLink
value={dontAskAgain}
isOutside={isOutside}
isPunnyCoded={isPunnyCodeLink}
link={linkToShow}
onToggle={() => setDontAskAgain(!dontAskAgain)}
/>
)}
</ModalTwoContent>
<ModalTwoFooter>
<Button onClick={modalProps.onClose}>{c('Action').t`Cancel`}</Button>
{/* translator: this string is only for blind people, it will be vocalized: confirm opening of link https://link.com */}
<Button
color="norm"
type="submit"
autoFocus
aria-label={c('Action').t`Confirm opening of link ${linkToShow}`}
disabled={isPhishingAttempt && !understandRisk}
>
{c('Action').t`Confirm`}
</Button>
</ModalTwoFooter>
</ModalTwo>
);
};
export default LinkConfirmationModal;
| 5,524
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/notifications
|
petrpan-code/ProtonMail/WebClients/packages/components/components/notifications/LinkConfirmationModal/LinkConfirmationModalLink.tsx
|
import React from 'react';
import { c } from 'ttag';
import { Href } from '@proton/atoms';
import { useNotifications } from '@proton/components/hooks';
import { isEdge, isIE11 } from '@proton/shared/lib/helpers/browser';
import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url';
import { Copy } from '../../button';
import { Checkbox } from '../../input';
import { Label } from '../../label';
interface Props {
link: string;
isPunnyCoded: boolean;
value: boolean;
onToggle: () => void;
isOutside: boolean;
}
const LinkConfirmationModalLink = ({ link, isPunnyCoded, value, onToggle, isOutside = false }: Props) => {
const { createNotification } = useNotifications();
const isMSBrowser = isEdge() || isIE11();
const handleCopy = () => {
createNotification({
text: c('Notification').t`Link copied to clipboard`,
});
};
return (
<>
{`${c('Info').t`You are about to open another browser tab and visit:`} `}
<span className="text-bold text-break">{link}</span>
<Copy
className="ml-2"
size="small"
tooltipText={c('Info').t`Copy the link to clipboard`}
value={link}
onCopy={handleCopy}
/>
{isPunnyCoded && (
<>
{isMSBrowser
? c('Info')
.t`This link may be a homograph attack and cannot be opened by the Edge browser. If you are certain the link is legitimate, please use a different browser to open it.`
: c('Info')
.t`This link may be a homograph attack. Please verify this is the link you wish to visit, or don't open it.`}
<Href href={getKnowledgeBaseUrl('/homograph-attacks')} title="What are homograph attacks?">
{c('Info').t`Learn more`}
</Href>
</>
)}
{!isOutside && (
<Label className="flex">
<Checkbox checked={value} onChange={onToggle} className="mr-2" />
{c('Label').t`Don't ask again`}
</Label>
)}
</>
);
};
export default LinkConfirmationModalLink;
| 5,525
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/notifications
|
petrpan-code/ProtonMail/WebClients/packages/components/components/notifications/LinkConfirmationModal/LinkConfirmationModalPhishing.tsx
|
import React from 'react';
import { c } from 'ttag';
import { Checkbox } from '../../input';
import { Label } from '../../label';
interface Props {
link: string;
value: boolean;
onToggle: () => void;
}
const LinkConfirmationModalPhishing = ({ link, onToggle, value }: Props) => (
<>
{`${c('Info')
.t`This link leads to a website that might be trying to steal your information, such as passwords and credit card details.`} `}
<br />
<span className="text-bold text-break">{link}</span>
<Label className="flex">
<Checkbox className="mr-2" checked={value} onChange={onToggle} />
{c('Label').t`I understand the risk`}
</Label>
</>
);
export default LinkConfirmationModalPhishing;
| 5,526
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/option/Option.tsx
|
import { ComponentPropsWithoutRef, useEffect, useRef } from 'react';
import usePrevious from '@proton/hooks/usePrevious';
import { scrollIntoView } from '@proton/shared/lib/helpers/dom';
import clsx from '@proton/utils/clsx';
import { DropdownMenuButton } from '../dropdown';
export interface Props<V> extends Omit<ComponentPropsWithoutRef<'button'>, 'value' | 'onChange' | 'title'> {
value: V;
onChange?: (value: V) => void;
selected?: boolean;
active?: boolean;
/**
* Truncates and adds an ellipsis if the text exceeds the width of the dropdown.
*/
truncate?: boolean;
title: string;
disableFocusOnActive?: boolean;
searchStrings?: string[];
}
const Option = <V,>({
type = 'button',
value,
selected,
active,
truncate,
onChange,
title,
children = title,
disableFocusOnActive,
searchStrings,
className,
...rest
}: Props<V>) => {
const ref = useRef<HTMLButtonElement | null>(null);
const previousActive = usePrevious(active);
useEffect(() => {
if (!previousActive && active) {
if (!disableFocusOnActive) {
ref.current?.focus();
} else {
scrollIntoView(ref.current, { block: 'center' });
}
}
}, [active]);
const handleClick = () => {
onChange?.(value);
};
return (
<li className="dropdown-item">
<DropdownMenuButton
ref={ref}
type={type}
isSelected={selected}
onClick={handleClick}
title={title}
className={clsx([
className,
'block w-full text-left',
active && 'active',
truncate ? 'text-ellipsis' : 'text-break',
])}
{...rest}
>
{children}
</DropdownMenuButton>
</li>
);
};
export default Option;
| 5,527
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/option/index.ts
|
export { default as Option } from './Option';
| 5,528
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/orderable/OrderableContainer.tsx
|
import { SortableContainer } from 'react-sortable-hoc';
interface Props {
children: any;
}
export default SortableContainer(({ children }: Props) => children);
| 5,529
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/orderable/OrderableElement.tsx
|
import { SortableElement } from 'react-sortable-hoc';
interface Props {
children: any;
}
export default SortableElement(({ children }: Props) => children);
| 5,530
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/orderable/OrderableHandle.tsx
|
import { SortableHandle } from 'react-sortable-hoc';
interface Props {
children: any;
}
export default SortableHandle(({ children }: Props) => children);
| 5,531
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/orderable/index.ts
|
export { default as OrderableContainer } from './OrderableContainer';
export { default as OrderableElement } from './OrderableElement';
export { default as OrderableHandle } from './OrderableHandle';
| 5,532
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/orderableTable/OrderableTable.scss
|
@import '~@proton/styles/scss/lib';
.orderableHelper {
z-index: 30;
display: flex;
align-items: center;
color: var(--text-norm);
background: var(--background-norm);
border: solid var(--border-norm);
border-block-width: 1px;
border-inline-width: 0;
/**
* We replace td with custom class here because we don't have direct access to it.
* See: https://github.com/ProtonMail/@proton/components/pull/113/files#r305374317
*/
td {
flex: 1;
border: none;
block-size: 100%;
&:first-child {
flex-grow: 0;
flex-basis: rem(35);
}
}
}
| 5,533
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/orderableTable/OrderableTable.tsx
|
import { ReactNode } from 'react';
import { SortableContainerProps } from 'react-sortable-hoc';
import clsx from '@proton/utils/clsx';
import OrderableContainer from '../orderable/OrderableContainer';
import { Table } from '../table';
import './OrderableTable.scss';
interface Props extends SortableContainerProps {
className?: string;
helperClassname?: string;
children?: ReactNode;
caption?: string;
}
const OrderableTable = ({ children = [], className = '', helperClassname, caption, ...props }: Props) => (
<OrderableContainer helperClass={clsx(['orderableHelper simple-table', helperClassname])} useDragHandle {...props}>
<Table caption={caption} className={clsx(['orderableTable', className])}>
{children}
</Table>
</OrderableContainer>
);
export default OrderableTable;
| 5,534
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/orderableTable/OrderableTableBody.tsx
|
import { ReactNode } from 'react';
import { TableBody } from '../table';
interface Props {
children?: ReactNode;
colSpan?: number;
loading?: boolean;
}
const OrderableTableBody = ({ children, colSpan = 0, loading, ...rest }: Props) => (
<TableBody {...rest} colSpan={colSpan + 1} loading={loading}>
{children}
</TableBody>
);
export default OrderableTableBody;
| 5,535
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/orderableTable/OrderableTableHeader.scss
|
@import '~@proton/styles/scss/lib';
.orderableTableHeader {
th:first-child {
inline-size: rem(35);
}
}
| 5,536
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/orderableTable/OrderableTableHeader.tsx
|
import { ReactNode } from 'react';
import clsx from '@proton/utils/clsx';
import { Cell, TableHeader } from '../table';
import './OrderableTableHeader.scss';
interface Props {
cells?: (Cell | ReactNode)[];
className?: string;
children?: ReactNode;
}
const OrderableTableHeader = ({ cells = [], className = '', children = null, ...rest }: Props) => (
<TableHeader
cells={[
null, // column for icon
...cells,
]}
className={clsx(['orderableTableHeader', className])}
{...rest}
>
{children}
</TableHeader>
);
export default OrderableTableHeader;
| 5,537
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/orderableTable/OrderableTableRow.tsx
|
import { ReactNode, Ref, forwardRef } from 'react';
import Icon from '../icon/Icon';
import { OrderableElement, OrderableHandle } from '../orderable';
import { Cell, TableRow } from '../table';
interface Props {
index: number;
className?: string;
cells?: (Cell | ReactNode)[];
disableSort?: boolean;
}
const OrderableTableRow = ({ index, cells = [], className, disableSort, ...rest }: Props, ref: Ref<any>) => {
if (disableSort) {
return <TableRow cells={['', ...cells]} className={className} {...rest} />;
}
return (
<OrderableElement index={index} ref={ref}>
<TableRow
cells={[
<OrderableHandle key="icon">
<span className="flex" data-testid="table:order-icon">
<Icon className="my-auto cursor-row-resize" name="text-align-justify" />
</span>
</OrderableHandle>,
...cells,
]}
className={className}
{...rest}
/>
</OrderableElement>
);
};
export default forwardRef(OrderableTableRow);
| 5,538
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/orderableTable/index.ts
|
export { default as OrderableTable } from './OrderableTable';
export { default as OrderableTableHeader } from './OrderableTableHeader';
export { default as OrderableTableBody } from './OrderableTableBody';
export { default as OrderableTableRow } from './OrderableTableRow';
| 5,539
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/pagination/Pagination.test.js
|
import { fireEvent, render } from '@testing-library/react';
import Pagination from './Pagination';
describe('Pagination component', () => {
const total = 100;
const limit = 10;
it('should render and setup Pagination properly', () => {
const mockOnNext = jest.fn();
const mockOnPrevious = jest.fn();
const mockOnSelect = jest.fn();
const { container, getByTitle } = render(
<Pagination
onNext={mockOnNext}
onPrevious={mockOnPrevious}
onSelect={mockOnSelect}
page={1}
total={total}
limit={limit}
/>
);
const previousButtonNode = container.firstChild.querySelector('.previous-button');
const pageButtonNode = getByTitle('Open pagination');
const nextButtonNode = container.firstChild.querySelector('.next-button');
expect(previousButtonNode).not.toBe(null);
expect(nextButtonNode).not.toBe(null);
expect(previousButtonNode.getAttribute('disabled')).not.toBe(null);
fireEvent.click(previousButtonNode);
expect(mockOnPrevious).toHaveBeenCalledTimes(0);
expect(nextButtonNode.getAttribute('disabled')).toBe(null);
fireEvent.click(nextButtonNode);
expect(mockOnNext).toHaveBeenCalledTimes(1);
fireEvent.click(pageButtonNode);
const options = [].slice.call(document.querySelectorAll('body > .dropdown li'));
expect(options.length).toBe(Math.ceil(total / limit));
fireEvent.click(document.querySelector('body > .dropdown li:last-child button'));
expect(mockOnSelect).toHaveBeenCalledTimes(1);
});
it('should not render NEXT and PREVIOUS buttons', () => {
const mockOnSelect = jest.fn();
const { container } = render(
<Pagination
onSelect={mockOnSelect}
page={1}
total={total}
limit={limit}
hasPrevious={false}
hasNext={false}
/>
);
const previousButtonNode = container.firstChild.querySelector('.previous-button');
const nextButtonNode = container.firstChild.querySelector('.next-button');
expect(previousButtonNode).toBe(null);
expect(nextButtonNode).toBe(null);
});
});
| 5,540
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/pagination/Pagination.tsx
|
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { ButtonGroup } from '../button';
import DropdownMenu from '../dropdown/DropdownMenu';
import DropdownMenuButton from '../dropdown/DropdownMenuButton';
import SimpleDropdown from '../dropdown/SimpleDropdown';
import { Icon } from '../icon';
interface Props {
total: number;
limit: number;
onSelect: (index: number) => void;
page?: number;
onNext?: () => void;
onPrevious?: () => void;
hasNext?: boolean;
hasPrevious?: boolean;
}
const Pagination = ({
onNext,
onPrevious,
onSelect,
hasNext = true,
hasPrevious = true,
page = 1,
total,
limit,
}: Props) => {
if (!total) {
return null;
}
const pages = Math.ceil(total / limit);
if (pages === 1) {
return null;
}
const actions = Array.from({ length: pages }, (a, i) => {
const index = i + 1;
return (
<DropdownMenuButton
key={index}
onClick={() => onSelect(index)}
aria-current={index === page}
className={index === page ? 'is-active text-center' : 'text-center'}
>
{index.toString()}
</DropdownMenuButton>
);
});
const disablePrevious = page === 1;
const disableNext = page === pages;
return (
<ButtonGroup>
{hasPrevious ? (
<Button
icon
className="previous-button on-rtl-mirror"
disabled={disablePrevious}
onClick={onPrevious}
title={c('Title').t`Previous`}
>
<Icon name="arrow-left" />
</Button>
) : null}
<SimpleDropdown as={Button} title={c('Title').t`Open pagination`} content={page}>
<DropdownMenu>{actions}</DropdownMenu>
</SimpleDropdown>
{hasNext ? (
<Button
icon
className="next-button on-rtl-mirror"
disabled={disableNext}
onClick={onNext}
title={c('Title').t`Next`}
>
<Icon name="arrow-right" />
</Button>
) : null}
</ButtonGroup>
);
};
export default Pagination;
| 5,541
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/pagination/PaginationRow.tsx
|
import { memo } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import clsx from '@proton/utils/clsx';
import range from '@proton/utils/range';
import { ButtonGroup } from '../button';
import { Icon } from '../icon';
import { Tooltip } from '../tooltip';
interface Props {
onStart: () => void;
onEnd: () => void;
onPrevious: () => void;
onNext: () => void;
onPage: (pageNumber: number) => void;
page: number;
total: number;
disabled?: boolean;
step?: number;
className?: string;
disableGoToLast?: boolean;
}
const PaginationRow = ({
onStart,
onEnd,
onPrevious,
onNext,
onPage,
page,
disabled,
total,
step = 1,
className,
disableGoToLast = false,
}: Props) => {
const pages = range(page - step, page + step + 1).filter((pageNumber) => pageNumber > 0 && pageNumber <= total);
const goToPageTitle = (page: number) => c('Action').t`Go to page ${page}`;
const disablePrevious = page === 1;
const disableNext = page === total;
return (
<ButtonGroup className={className}>
<Tooltip title={c('Action').t`Go to first page`}>
<Button
className="on-rtl-mirror"
icon
disabled={disabled || disablePrevious}
onClick={() => onStart()}
data-testid="pagination-row:go-to-first-page"
>
<Icon name="chevrons-left" className="block" alt={c('Action').t`Go to first page`} />
</Button>
</Tooltip>
<Tooltip title={c('Action').t`Go to previous page`}>
<Button
className="on-rtl-mirror"
disabled={disabled || disablePrevious}
onClick={() => onPrevious()}
data-testid="pagination-row:go-to-previous-page"
>
<Icon name="chevron-left" className="block" alt={c('Action').t`Go to previous page`} />
</Button>
</Tooltip>
{pages.map((pageNumber) => {
const isActive = pageNumber === page;
return (
<Tooltip key={pageNumber} title={goToPageTitle(pageNumber)}>
<Button
aria-current={isActive}
className={clsx([isActive && 'text-bold', isActive && 'no-pointer-events'])}
disabled={disabled}
onClick={() => onPage(pageNumber)}
data-testid={`pagination-row:go-to-page-${pageNumber}`}
>
<span className="sr-only">{goToPageTitle(pageNumber)}</span>
<span aria-hidden="true">{pageNumber}</span>
</Button>
</Tooltip>
);
})}
<Tooltip title={c('Action').t`Go to next page`}>
<Button
className="on-rtl-mirror"
icon
disabled={disabled || disableNext}
onClick={() => onNext()}
data-testid="pagination-row:go-to-next-page"
>
<Icon name="chevron-right" className="block" alt={c('Action').t`Go to next page`} />
</Button>
</Tooltip>
<Tooltip title={c('Action').t`Go to last page`}>
<Button
icon
disabled={disabled || disableNext || disableGoToLast}
onClick={() => onEnd()}
data-testid="pagination-row:go-to-last-page"
>
<Icon name="chevrons-right" className="block" alt={c('Action').t`Go to last page`} />
</Button>
</Tooltip>
</ButtonGroup>
);
};
export default memo(PaginationRow);
| 5,542
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/pagination/index.ts
|
export { default as usePaginationAsync } from './usePaginationAsync';
export { default as usePagination } from './usePagination';
export { default as Pagination } from './Pagination';
export { default as PaginationRow } from './PaginationRow';
| 5,543
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/pagination/usePagination.ts
|
import { useEffect, useState } from 'react';
const usePagination = <T>(initialList: T[] = [], initialPage = 1, limit = 10) => {
const [page, setPage] = useState(initialPage);
const onNext = () => setPage(page + 1);
const onPrevious = () => setPage(page - 1);
const onSelect = (p: number) => setPage(p);
const list = [...initialList].splice((page - 1) * limit, limit);
const lastPage = Math.ceil(initialList.length / limit);
const isLastPage = page === lastPage;
useEffect(() => {
if (lastPage && page > lastPage) {
onSelect(lastPage);
}
}, [initialList.length]);
return {
page,
isLastPage,
list,
onNext,
onPrevious,
onSelect,
};
};
export default usePagination;
| 5,544
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/pagination/usePaginationAsync.ts
|
import { useState } from 'react';
const usePaginationAsync = (initialPage = 1) => {
const [page, setPage] = useState(initialPage);
const onNext = () => setPage(page + 1);
const onPrevious = () => setPage(page - 1);
const onSelect = (p: number) => setPage(p);
const reset = () => setPage(initialPage);
return {
page,
onNext,
onPrevious,
onSelect,
reset,
};
};
export default usePaginationAsync;
| 5,545
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/popper/Popper.tsx
|
import { CSSProperties, HTMLAttributes, ReactNode, Ref } from 'react';
import Portal from '../portal/Portal';
interface Props extends HTMLAttributes<HTMLDivElement> {
divRef: Ref<HTMLDivElement>;
role?: string;
isOpen?: boolean;
children: ReactNode;
style?: CSSProperties;
}
const Popper = ({ children, isOpen = false, divRef, role = 'tooltip', ...rest }: Props) => {
if (!isOpen) {
return null;
}
return (
<Portal>
<div {...rest} ref={divRef} role={role} hidden={!isOpen} aria-hidden={!isOpen}>
{children}
</div>
</Portal>
);
};
export default Popper;
| 5,546
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/popper/index.ts
|
export { default as usePopper } from './usePopper';
export { default as usePopperAnchor } from './usePopperAnchor';
export { default as usePopperState } from './usePopperState';
export { default as Popper } from './Popper';
export { allPopperPlacements, cornerPopperPlacements } from './utils';
export * from './interface';
| 5,547
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/popper/interface.ts
|
import type { Placement as FloatingUiPlacement } from '@floating-ui/dom';
export type ArrowOffset = 0 | string;
export type PopperPlacement = FloatingUiPlacement;
export type PopperPosition = { top: number; left: number };
export type PopperArrow = { '--arrow-offset': ArrowOffset };
| 5,548
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/popper/usePopper.test.tsx
|
import { useState } from 'react';
import { Middleware, shift as mockedShift } from '@floating-ui/dom';
import { act, render, screen } from '@testing-library/react';
import { PopperPlacement } from '@proton/components/components';
import { wait } from '@proton/shared/lib/helpers/promise';
import usePopper from './usePopper';
jest.mock('@floating-ui/dom', () => {
const originalModule = jest.requireActual('@floating-ui/dom');
// Mock the default export and named export 'foo'
return {
__esModule: true,
...originalModule,
shift: jest.fn(originalModule.shift),
};
});
describe('usePopper', () => {
Object.defineProperties(window.HTMLElement.prototype, {
// @ts-ignore
getBoundingClientRect: {
value: function () {
return {
width: parseFloat(this.style.width) || 0,
height: parseFloat(this.style.height) || 0,
top: parseFloat(this.style.top) || 0,
left: parseFloat(this.style.left) || 0,
};
},
},
clientHeight: {
get: function () {
return 100;
},
},
clientWidth: {
get: function () {
return 100;
},
},
});
const Test = ({
isOpen,
originalPlacement,
anchor,
}: {
isOpen: boolean;
originalPlacement: PopperPlacement;
anchor?: { top: number; left: number };
}) => {
const [ref, setRef] = useState<HTMLDivElement | null>(null);
const { floating, position, arrow, placement } = usePopper({
isOpen,
originalPlacement,
offset: 0,
reference: anchor
? {
mode: 'position',
value: anchor,
anchor: ref,
}
: {
mode: 'element',
value: ref,
},
});
return (
<div>
<div
ref={setRef}
data-testid="reference"
style={{ top: '10px', left: '10px', width: '10px', height: '10px' }}
>
hello world
</div>
<div
ref={floating}
data-testid="floating"
data-placement={placement}
style={{ ...position, ...arrow, width: '1px', height: '1px' }}
>
floating
</div>
</div>
);
};
it('should return a hidden placement when not open', async () => {
render(<Test isOpen={false} originalPlacement="top-start" />);
await act(async () => {});
expect(screen.getByTestId('floating').dataset.placement).toBe('hidden');
});
it('should render a floating element when open', async () => {
render(<Test isOpen={true} originalPlacement="top-start" />);
await act(async () => {});
expect(screen.getByTestId('floating').dataset.placement).toBe('top-start');
// @ts-ignore
expect(screen.getByTestId('floating').style._values).toEqual({
top: '10px',
left: '10px',
width: '1px',
height: '1px',
'--arrow-offset': '0',
});
});
it('should render without race conditions', async () => {
const { rerender } = render(<Test isOpen={true} originalPlacement="top-start" />);
const shift = mockedShift as jest.Mock<Middleware>;
const original = shift();
const mock: Middleware = {
name: 'shift',
fn: async (...args) => {
await wait(1);
return original.fn(...args);
},
};
shift.mockReturnValue(mock);
rerender(<Test isOpen={true} originalPlacement="top-start" />);
shift.mockRestore();
rerender(<Test isOpen={true} originalPlacement="top-start" anchor={{ top: 2, left: 3 }} />);
await act(async () => {});
// @ts-ignore
expect(screen.getByTestId('floating').style._values).toEqual({
top: '2px',
left: '3px',
width: '1px',
height: '1px',
'--arrow-offset': '0',
});
});
it('should render a floating element in an anchor element and in an anchor position', async () => {
const { rerender } = render(<Test isOpen={true} originalPlacement="top-start" />);
await act(async () => {});
// @ts-ignore
expect(screen.getByTestId('floating').style._values).toEqual({
top: '10px',
left: '10px',
width: '1px',
height: '1px',
'--arrow-offset': '0',
});
rerender(<Test isOpen={true} originalPlacement="top-start" anchor={{ top: 1, left: 2 }} />);
await act(async () => {});
// @ts-ignore
expect(screen.getByTestId('floating').style._values).toEqual({
top: '1px',
left: '2px',
width: '1px',
height: '1px',
'--arrow-offset': '0',
});
});
});
| 5,549
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/popper/usePopper.ts
|
import { RefObject, useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react';
import {
Placement,
Strategy,
VirtualElement,
autoUpdate,
computePosition,
flip,
hide,
offset,
shift,
size,
} from '@floating-ui/dom';
import isDeepEqual from '@proton/shared/lib/helpers/isDeepEqual';
import { PopperArrow, PopperPlacement, PopperPosition } from './interface';
import { allPopperPlacements, arrowOffset, getClickRect, getFallbackPlacements, rtlPlacement } from './utils';
type ReferenceType = Element | VirtualElement;
const hiddenPosition: PopperPosition = {
top: -9999,
left: -9999,
};
interface Data {
x: number | null;
y: number | null;
strategy: Strategy;
placement: Placement;
middlewareData: any;
}
interface AvailableSizeVariables {
'--available-width': string;
'--available-height': string;
}
interface PopperReturnValue {
reference: ((el: ReferenceType | null) => void) | null;
floating: ((el: HTMLElement | null) => void) | null;
position: PopperPosition;
arrow: PopperArrow;
placement: PopperPlacement | 'hidden';
availableSize: AvailableSizeVariables | undefined;
update: () => void;
}
interface Props {
isOpen?: boolean;
originalPlacement?: PopperPlacement;
availablePlacements?: PopperPlacement[];
availableSize?: boolean;
reference?:
| {
mode: 'element';
value: HTMLElement | null | undefined;
}
| {
mode: 'position';
value: PopperPosition | null;
anchor?: HTMLElement | null;
};
relativeReference?: RefObject<HTMLElement>;
offset?: number;
updateAnimationFrame?: boolean;
}
const defaultState: Data = {
x: null,
y: null,
strategy: 'fixed',
placement: 'top',
middlewareData: {},
};
const usePopper = ({
isOpen,
originalPlacement = 'top',
availablePlacements = allPopperPlacements,
availableSize,
offset: offsetPx = 10,
relativeReference,
reference: anchorReference,
updateAnimationFrame,
}: Props): PopperReturnValue => {
const [data, setData] = useState<Data>(defaultState);
const reference = useRef<ReferenceType | null>(null);
const floating = useRef<HTMLElement | null>(null);
const cleanupRef = useRef<(() => void) | void | null>(null);
const isMountedRef = useRef(false);
const iterationRef = useRef<Symbol>();
const fallbackPlacements = useMemo(() => {
return getFallbackPlacements(originalPlacement, availablePlacements);
}, []);
const update = useCallback(() => {
const referenceEl = reference.current;
const floatingEl = floating.current;
if (!referenceEl || !floatingEl) {
return;
}
let availableSizeVariables: AvailableSizeVariables | undefined;
const iteration = (iterationRef.current = Symbol('iteration'));
// NOTE: This hook assumes that props never change during the lifetime of the component.
void computePosition(referenceEl, floatingEl, {
placement: originalPlacement,
middleware: [
offset(offsetPx),
flip({ fallbackPlacements }),
shift(),
availableSize
? size({
apply({ elements, availableHeight, availableWidth }) {
availableSizeVariables = {
'--available-height': `${Math.floor(availableHeight)}px`,
'--available-width': `${Math.floor(availableWidth)}px`,
};
Object.entries(availableSizeVariables).forEach(([key, value]) => {
elements.floating.style.setProperty(key, value);
});
},
})
: undefined,
hide(
// Due to a bug (I think) in floating-ui 1.2.0, reference elements in iframes
// get incorrectly computed as "hidden", I'm guessing because it gets a mismatch
// between coordinates relative to the iframe and coordinates relative to the boundary.
// Therefore, we switch the boundary to use the "floating" element (which is not in an iframe).
relativeReference?.current
? {
altBoundary: true,
boundary: relativeReference?.current || undefined,
// This uses the outer viewport size, not the reference's
// inside iframe viewport size
rootBoundary: {
x: 0,
y: 0,
width: document.documentElement.clientWidth,
height: document.documentElement.clientHeight,
},
}
: undefined
),
arrowOffset(),
rtlPlacement(),
],
strategy: 'fixed',
}).then((data) => {
if (!isMountedRef.current || iteration !== iterationRef.current) {
return;
}
data.middlewareData.availableSize = availableSizeVariables;
setData((oldData) => {
if (isDeepEqual(oldData, data)) {
return oldData;
}
return data;
});
});
}, []);
useLayoutEffect(() => {
isMountedRef.current = true;
return () => {
isMountedRef.current = false;
};
}, []);
const runElementMountCallback = useCallback(() => {
cleanupRef.current?.();
cleanupRef.current = null;
const referenceEl = reference.current;
const floatingEl = floating.current;
if (!referenceEl || !floatingEl) {
return;
}
const autoUpdater = () => {
const unsubscribe = autoUpdate(referenceEl, floatingEl, update, {
animationFrame: updateAnimationFrame,
});
let relativeUnsubscribe: (() => void) | undefined;
if (relativeReference?.current) {
relativeUnsubscribe = autoUpdate(relativeReference.current, floatingEl, update, {
animationFrame: updateAnimationFrame,
});
}
return () => {
unsubscribe();
relativeUnsubscribe?.();
};
};
cleanupRef.current = autoUpdater();
}, []);
const setReference = useCallback((node: ReferenceType | null) => {
reference.current = node;
runElementMountCallback();
}, []);
const setFloating = useCallback((node: HTMLElement | null) => {
floating.current = node;
runElementMountCallback();
}, []);
useLayoutEffect(() => {
if (!isOpen) {
setReference(null);
setFloating(null);
setData(defaultState);
}
if (!anchorReference) {
return;
}
if (anchorReference.mode === 'element') {
setReference(anchorReference.value || null);
return;
}
if (anchorReference.mode === 'position') {
if (!anchorReference.value) {
setReference(null);
return;
}
const clickRect = getClickRect(anchorReference.value);
setReference({
getBoundingClientRect: () => {
return clickRect;
},
});
return;
}
}, [anchorReference?.value, anchorReference?.mode, isOpen]);
// x and y are null initially, before the layout effect has fired
const hidden = Boolean(data.middlewareData.hide?.referenceHidden) || data.x === null || data.y === null;
const arrowOffsetValue: string | number = data.middlewareData.arrowOffset?.value;
const adjustedPlacement: PopperPlacement = data.middlewareData.rtlPlacement?.placement || data.placement;
return {
update,
reference: isOpen ? setReference : null,
floating: isOpen ? setFloating : null,
position: hidden
? hiddenPosition
: {
top: data.y || 0,
left: data.x || 0,
},
arrow: {
'--arrow-offset': !arrowOffsetValue ? 0 : `${arrowOffsetValue}px`,
},
placement: hidden ? 'hidden' : adjustedPlacement,
availableSize: data.middlewareData.availableSize,
};
};
export default usePopper;
| 5,550
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/popper/usePopperAnchor.ts
|
import { useRef } from 'react';
import usePopperState from './usePopperState';
const usePopperAnchor = <T>(onChange?: (state: boolean) => void) => {
const ref = useRef<T>(null);
const state = usePopperState(onChange);
return { ...state, anchorRef: ref };
};
export default usePopperAnchor;
| 5,551
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/popper/usePopperState.ts
|
import { useCallback, useState } from 'react';
import useIsMounted from '@proton/hooks/useIsMounted';
const usePopperState = (onChange?: (state: boolean) => void) => {
const [isOpen, setOpen] = useState(false);
const isMounted = useIsMounted();
const open = useCallback(() => {
// setState should not occur when the component is unmounted
if (isMounted()) {
setOpen(true);
}
onChange?.(true);
}, []);
const close = useCallback(() => {
// setState should not occur when the component is unmounted
if (isMounted()) {
setOpen(false);
}
onChange?.(false);
}, []);
const toggle = useCallback(() => {
return isOpen ? close() : open();
}, [isOpen]);
return { isOpen, toggle, open, close };
};
export default usePopperState;
| 5,552
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/popper/utils.test.ts
|
import { getFallbackPlacements, getInvertedRTLPlacement } from '@proton/components/components/popper/utils';
describe('popper utils', () => {
describe('fallback placements', () => {
test('should sort placements when given top-end', () => {
expect(getFallbackPlacements('top-end')).toEqual([
'top-start',
'top',
'bottom-end',
'bottom',
'bottom-start',
'right-start',
'right',
'right-end',
'left-end',
'left',
'left-start',
]);
});
test('should sort placements when given top', () => {
expect(getFallbackPlacements('top')).toEqual([
'top-start',
'top-end',
'bottom',
'bottom-end',
'bottom-start',
'right-start',
'right',
'right-end',
'left-end',
'left',
'left-start',
]);
});
test('should sort placements when given right', () => {
expect(getFallbackPlacements('right')).toEqual([
'right-start',
'right-end',
'left',
'left-end',
'left-start',
'top-start',
'top',
'top-end',
'bottom-end',
'bottom',
'bottom-start',
]);
});
test('should sort placements when given left-start', () => {
expect(getFallbackPlacements('left-start')).toEqual([
'left-end',
'left',
'right-start',
'right',
'right-end',
'top-start',
'top',
'top-end',
'bottom-end',
'bottom',
'bottom-start',
]);
});
test('should sort placements when given left-end', () => {
expect(getFallbackPlacements('left-end')).toEqual([
'left',
'left-start',
'right-end',
'right-start',
'right',
'top-start',
'top',
'top-end',
'bottom-end',
'bottom',
'bottom-start',
]);
});
});
describe('rtl placement', () => {
test('should get rtl placement', () => {
expect(getInvertedRTLPlacement('top-start', true)).toEqual('top-end');
expect(getInvertedRTLPlacement('top-end', true)).toEqual('top-start');
expect(getInvertedRTLPlacement('right-start', true)).toEqual('right-start');
expect(getInvertedRTLPlacement('right-end', true)).toEqual('right-end');
expect(getInvertedRTLPlacement('bottom-end', true)).toEqual('bottom-start');
expect(getInvertedRTLPlacement('bottom-start', true)).toEqual('bottom-end');
expect(getInvertedRTLPlacement('left-start', true)).toEqual('left-start');
expect(getInvertedRTLPlacement('left-end', true)).toEqual('left-end');
expect(getInvertedRTLPlacement('top-start', false)).toEqual('top-start');
expect(getInvertedRTLPlacement('top-end', false)).toEqual('top-end');
expect(getInvertedRTLPlacement('bottom-start', false)).toEqual('bottom-start');
expect(getInvertedRTLPlacement('bottom-end', false)).toEqual('bottom-end');
});
});
});
| 5,553
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/popper/utils.ts
|
import { RefObject } from 'react';
import { Middleware, MiddlewareArguments, MiddlewareReturn } from '@floating-ui/dom';
import { ArrowOffset, PopperPlacement, PopperPosition } from './interface';
export const allPopperPlacements: PopperPlacement[] = [
'top-start',
'top',
'top-end',
'right-start',
'right',
'right-end',
'bottom-end',
'bottom',
'bottom-start',
'left-end',
'left',
'left-start',
];
export const verticalPopperPlacements: PopperPlacement[] = [
'top-start',
'top',
'top-end',
'bottom-end',
'bottom',
'bottom-start',
];
export const getInvertedRTLPlacement = (placement: PopperPlacement, rtl: boolean): PopperPlacement => {
if (!rtl) {
return placement;
}
if (placement.startsWith('top') || placement.startsWith('bottom')) {
return placement.endsWith('-start')
? (placement.replace('-start', '-end') as PopperPlacement)
: (placement.replace('-end', '-start') as PopperPlacement);
}
return placement;
};
const getInvertedPlacement = (placement: PopperPlacement): PopperPlacement => {
const position = placement.split('-')[0];
if (position === 'top') {
return 'bottom';
}
if (position === 'bottom') {
return 'top';
}
if (position === 'left') {
return 'right';
}
if (position === 'right') {
return 'left';
}
return 'top';
};
export const cornerPopperPlacements: PopperPlacement[] = [
'top-start',
'top-end',
'right-start',
'right-end',
'bottom-end',
'bottom-start',
'left-end',
'left-start',
];
const getPlacements = (value: PopperPlacement) => {
return value.split('-') as [PopperPlacement, PopperPlacement | undefined];
};
/**
* Tries to maintain placement as close to the original as possible. In order of
* 1. Same position
* 2. Inverted position
* 3. Remaining
*/
export const getFallbackPlacements = (
originalPlacement: PopperPlacement,
placements = allPopperPlacements
): PopperPlacement[] => {
const groupedPlacements = placements.reduce<Partial<{ [key in PopperPlacement]: PopperPlacement[] }>>(
(acc, cur) => {
const [position] = getPlacements(cur);
let prev = acc[position];
if (!prev) {
prev = acc[position] = [];
}
prev.push(cur);
return acc;
},
{}
);
const [originalPosition, originalAlignment] = getPlacements(originalPlacement);
const invertedPosition = getInvertedPlacement(originalPosition);
const groupedOriginalPlacements = groupedPlacements[originalPosition];
const groupedInvertedPlacements = groupedPlacements[invertedPosition];
if (!groupedOriginalPlacements || !groupedInvertedPlacements) {
return placements;
}
return [
...groupedOriginalPlacements.filter((placement) => placement !== originalPlacement),
...groupedInvertedPlacements.sort((a, b) => {
const [, alignmentA] = a.split('-');
const [, alignmentB] = b.split('-');
if (alignmentA === alignmentB) {
return 0;
}
if (alignmentA === originalAlignment) {
return -1;
}
if (alignmentB === originalAlignment) {
return 1;
}
return 0;
}),
...Object.keys(groupedPlacements).flatMap((placement) => {
if (placement === originalPosition || placement === invertedPosition) {
return [];
}
const placements = groupedPlacements[placement as keyof typeof groupedPlacements];
if (!placements) {
return [];
}
return placements;
}),
];
};
export const shouldShowSideRadius = (
arrowOffset: ArrowOffset,
placement: PopperPlacement | 'hidden',
radiusSize = 8,
arrowSize = 10
) => {
if (placement === 'hidden') {
return false;
}
const offset = arrowOffset === 0 ? arrowOffset : Number(arrowOffset.replace('px', ''));
return !cornerPopperPlacements.includes(placement) || offset > radiusSize + arrowSize;
};
export const getClickRect = (position: PopperPosition) => {
return {
x: position.left,
y: position.top,
top: position.top,
bottom: position.top,
left: position.left,
right: position.left,
width: 0,
height: 0,
};
};
export const arrowOffset = (): Middleware => {
return {
name: 'arrowOffset',
fn({ rects, placement }: MiddlewareArguments): MiddlewareReturn {
const minHeight = Math.min(rects.reference.height, rects.floating.height);
const minWidth = Math.min(rects.reference.width, rects.floating.width);
const horizontalOffset = (minWidth || 0) / 2;
const verticalOffset = (minHeight || 0) / 2;
const placementList: { [key in PopperPlacement]: number } = {
top: 0,
bottom: 0,
left: 0,
right: 0,
'bottom-start': horizontalOffset,
'top-start': horizontalOffset,
'bottom-end': horizontalOffset,
'top-end': horizontalOffset,
'right-end': verticalOffset,
'right-start': verticalOffset,
'left-end': verticalOffset,
'left-start': verticalOffset,
} as const;
return {
data: { value: placementList[placement] || 0 },
};
},
};
};
export const anchorOffset = (ref: RefObject<HTMLElement> | undefined): Middleware => {
return {
name: 'anchorOffset',
fn({ x, y }: MiddlewareArguments): MiddlewareReturn {
if (!ref?.current) {
return {};
}
const position = ref.current.getBoundingClientRect();
return {
x: x + position.x,
y: y + position.y,
};
},
};
};
export const rtlPlacement = (): Middleware => {
return {
name: 'rtlPlacement',
async fn({ placement, elements, platform }: MiddlewareArguments): Promise<MiddlewareReturn> {
// Floating ui transparently handles RTL internally in the x,y values. But we expect the classnames to
// reflect where it's placed so this is just flipping it in the same way that floating ui happens.
const rtl = Boolean(await platform.isRTL?.(elements.floating));
return { data: { placement: getInvertedRTLPlacement(placement, rtl) } };
},
};
};
| 5,554
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/portal/Portal.tsx
|
import { ReactNode } from 'react';
import ReactDOM from 'react-dom';
interface Props {
children: ReactNode;
}
const Portal = ({ children }: Props) => {
return ReactDOM.createPortal(children, document.body);
};
export default Portal;
| 5,555
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/portal/index.ts
|
export { default as Portal } from './Portal';
| 5,556
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/portal
|
petrpan-code/ProtonMail/WebClients/packages/components/components/portal/__mocks__/Portal.tsx
|
export default ({ children }: any) => children;
| 5,557
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/price/Price.scss
|
@import '~@proton/styles/scss/lib';
.price--large {
.amount,
.currency {
font-size: em(48);
line-height: 1.2; // font only takes the place for characters ^^
}
.suffix {
color: var(--text-weak);
}
}
// need to adapt fonts for subscription modal... not enough place
.subscription-modal {
.price--large {
.amount,
.currency {
@include media('<=#{em(1050, 16)}') {
font-size: em(36); // not enough space
}
@include media('<=medium') {
font-size: em(48);
}
@include media('<=#{em(800, 16)}') {
font-size: em(36); // not enough space
}
@include media('<=small') {
font-size: em(48);
}
@include media('<=xsmall') {
font-size: em(36); // not enough space
}
}
}
}
| 5,558
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/price/Price.test.tsx
|
import { render } from '@testing-library/react';
import Price from './Price';
describe('Price component', () => {
it('should render negative price with USD currency', () => {
const { container } = render(<Price currency="USD">{-1500}</Price>);
expect((container.firstChild as any).textContent).toBe('-$15');
});
it('should render price with EUR in suffix', () => {
const { container } = render(<Price currency="EUR">{1500}</Price>);
expect((container.firstChild as any).textContent).toBe('15 €');
});
it('should render price with CHF in prefix', () => {
const { container } = render(<Price currency="CHF">{1500}</Price>);
expect((container.firstChild as any).textContent).toBe('CHF 15');
});
it('should use the divisor defined', () => {
const { container } = render(<Price divisor={1}>{1500}</Price>);
expect((container.firstChild as any).textContent).toBe('1500');
});
it('should render string values as is', () => {
const { container } = render(<Price>{'Let us talk'}</Price>);
expect((container.firstChild as any).textContent).toBe('Let us talk');
});
});
| 5,559
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/price/Price.tsx
|
import { ReactNode } from 'react';
import humanPrice from '@proton/shared/lib/helpers/humanPrice';
import { Currency } from '@proton/shared/lib/interfaces';
import clsx from '@proton/utils/clsx';
import './Price.scss';
const CURRENCIES = {
USD: '$',
EUR: '€',
CHF: 'CHF',
};
export interface Props {
children: number | string;
currency?: Currency | string;
className?: string;
divisor?: number;
suffix?: ReactNode;
prefix?: string;
isDisplayedInSentence?: boolean;
large?: boolean;
'data-testid'?: string;
suffixClassName?: string;
currencyClassName?: string;
amountClassName?: string;
wrapperClassName?: string;
}
const Price = ({
children: amount = 0,
currency = '',
className = '',
divisor = 100,
suffix = '',
prefix = '',
isDisplayedInSentence = false,
large,
'data-testid': dataTestId,
wrapperClassName = 'flex-item-noshrink inline-flex flex-align-items-baseline',
suffixClassName,
currencyClassName,
amountClassName,
}: Props) => {
const value = typeof amount === 'string' ? amount : humanPrice(amount, divisor);
const [integer, decimal] = `${value}`.split('.');
const p = typeof amount === 'number' && amount < 0 ? <span className="prefix">-</span> : null;
const v = (
<span className={clsx(['amount', 'amount--large', amountClassName])} data-testid={dataTestId}>
<span className="integer">{integer}</span>
{decimal ? <span className="decimal">.{decimal}</span> : null}
</span>
);
const s = suffix ? (
<span className={clsx(['suffix', suffixClassName, !isDisplayedInSentence && 'ml-1'])}>{suffix}</span>
) : null;
const pr = prefix ? <span className={clsx(['prefix', isDisplayedInSentence && 'mr-1'])}>{prefix}</span> : null;
if (currency === 'CHF') {
return (
<span
className={clsx(['price', wrapperClassName, large && 'price--large', className])}
data-currency={currency}
>
{pr}
{p}
<span className={clsx(['currency', currencyClassName])}>CHF </span>
{v}
{s}
</span>
); // -CHF 2/month
}
if (currency === 'EUR') {
return (
<span
className={clsx(['price', wrapperClassName, large && 'price--large', className])}
data-currency={currency}
>
{pr}
{p}
{v}
<span className={clsx(['currency', currencyClassName])}> €</span>
{s}
</span>
); // -2 €/month
}
return (
<span
className={clsx(['price', wrapperClassName, large && 'price--large', className])}
data-currency={currency}
>
{pr}
{p}
{!!currency && (
<span className={clsx(['currency', currencyClassName])}>
{CURRENCIES[currency as Currency] || currency}
</span>
)}
{v}
{s}
</span>
); // -$2/month
};
export default Price;
| 5,560
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/price/helper.ts
|
import humanPrice from '@proton/shared/lib/helpers/humanPrice';
import { Currency } from '@proton/shared/lib/interfaces';
export const getSimplePriceString = (currency: Currency, rawPrice: number, suffix: string) => {
const price = humanPrice(rawPrice, 100);
if (currency === 'EUR') {
return `${price} €${suffix}`;
}
if (currency === 'CHF') {
return `CHF ${price}${suffix}`;
}
if (currency === 'USD') {
return `$${price}${suffix}`;
}
return `${currency} ${price}${suffix}`;
};
| 5,561
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/price/index.ts
|
export { default as Price } from './Price';
| 5,562
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/progress/CircularProgress.tsx
|
import { ReactNode } from 'react';
import clsx from '@proton/utils/clsx';
interface Props {
children?: ReactNode;
className?: string;
rootRef?: any;
size?: number;
progress: number;
}
const CircularProgress = ({ children, className, progress, rootRef, size = 32, ...rest }: Props) => {
return (
<svg
ref={rootRef}
viewBox="0 0 35.83098862 35.83098862"
className={clsx(['circle-chart', className])}
width={size}
height={size}
xmlns="http://www.w3.org/2000/svg"
{...rest}
>
<circle
className="circle-chart-background"
strokeDasharray="100, 100"
cx="17.91549431"
cy="17.91549431"
r="15.91549431"
/>
<circle
className="circle-chart-circle"
strokeDasharray={`${progress}, 100`}
strokeLinecap="butt"
cx="17.91549431"
cy="17.91549431"
r="15.91549431"
/>
{children}
</svg>
);
};
export default CircularProgress;
| 5,563
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/progress/DynamicProgress.tsx
|
import clsx from '@proton/utils/clsx';
import Icon from '../icon/Icon';
import { Loader } from '../loader';
import Progress from './Progress';
interface Props {
id: string;
display?: string;
value: number;
max?: number;
loading: boolean;
success?: boolean;
partialSuccess?: boolean;
}
const DynamicProgress = ({
id,
display,
value,
max = 100,
loading,
success = true,
partialSuccess,
...rest
}: Props) => {
const { icon, progressClassname = '' } = loading
? {
icon: <Loader />,
}
: success
? {
icon: (
<span className="inline-flex bg-success rounded-50 p-2">
<Icon name="checkmark" size={24} />
</span>
),
progressClassname: 'progress-bar--success',
}
: partialSuccess
? {
icon: (
<span className="inline-flex bg-warning rounded-50 p-2">
<Icon name="cross" size={24} />
</span>
),
progressClassname: 'progress-bar--warning',
}
: {
icon: (
<span className="inline-flex bg-danger rounded-50 p-2">
<Icon name="cross" size={24} />
</span>
),
progressClassname: 'progress-bar--error',
};
return (
<div className={clsx(['text-center', !display && 'mb-4'])}>
{icon}
<Progress
className={clsx(['mt-4', progressClassname])}
aria-describedby={id}
value={value}
max={max}
{...rest}
/>
{!!display && (
<p aria-atomic="true" aria-live="polite" id={id}>
{display}
</p>
)}
</div>
);
};
export default DynamicProgress;
| 5,564
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/progress/Meter.tsx
|
import { ComponentPropsWithoutRef } from 'react';
import clsx from '@proton/utils/clsx';
import isBetween from '@proton/utils/isBetween';
interface Props extends ComponentPropsWithoutRef<'div'> {
/** whether or not the meter should be thin */
thin?: boolean;
/** whether or not the meter should be squared */
squared?: boolean;
/** add a textual label */
label?: string;
min?: number;
low?: number;
high?: number;
max?: number;
optimum?: number;
value?: number;
}
export enum MeterValue {
Optimum = 0,
Min = 0,
Low = 50,
High = 80,
Max = 100,
}
const { Optimum, Min, Low, High, Max } = MeterValue;
export const getMeterColor = (
value: number,
optimum: number = Optimum,
min: number = Min,
low: number = Low,
high: number = High,
max: number = Max
) => {
const isLow = isBetween(value, min, low);
const isMid = isBetween(value, low, high);
const isHigh = isBetween(value, high, max) || value >= max;
if (isBetween(optimum, min, low)) {
if (isHigh) {
return 'danger';
}
if (isMid) {
return 'warning';
}
if (isLow) {
return 'success';
}
}
if (isBetween(optimum, low, high)) {
if (isHigh) {
return 'warning';
}
if (isMid) {
return 'success';
}
if (isLow) {
return 'warning';
}
}
if (isBetween(optimum, high, max) || optimum === max) {
if (isHigh) {
return 'success';
}
if (isMid) {
return 'warning';
}
if (isLow) {
return 'danger';
}
}
console.error(
`Misuse of getMeterColor, verify values provided for value (${value}), optimum (${optimum}), min (${min}), max (${max}), low (${low}), high (${high})`
);
return 'danger';
};
const Meter = ({
thin = false,
squared = false,
label,
min = Min,
max = Max,
value = 0,
id,
className,
...rest
}: Props) => (
<div
id={id}
className={clsx(['meter-bar', thin && 'is-thin', squared && 'is-squared', className])}
role="meter"
aria-valuemin={min}
aria-valuemax={max}
aria-valuenow={value}
{...rest}
>
<div
className={clsx(['meter-bar-thumb w-custom', `meter-bar-thumb--${getMeterColor(value)}`, 'mr-auto'])}
style={{ '--w-custom': `${Math.ceil((value / max) * 100)}%` }}
>
{!rest['aria-labelledby'] && <span className="sr-only">{label || `${value} / ${max}`}</span>}
</div>
</div>
);
export default Meter;
| 5,565
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/progress/Progress.tsx
|
import clsx from '@proton/utils/clsx';
interface Props {
value: number;
max?: number;
id?: string;
className?: string;
}
const Progress = ({ value = 50, max = 100, id, className, ...rest }: Props) => {
return (
<progress
aria-describedby={id}
className={clsx(['progress-bar w-full', className])}
value={value}
max={max}
{...rest}
/>
);
};
export default Progress;
| 5,566
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/progress/index.ts
|
export { default as Progress } from './Progress';
export { default as DynamicProgress } from './DynamicProgress';
export * from './Meter';
export { default as Meter } from './Meter';
export { default as CircularProgress } from './CircularProgress';
| 5,567
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/prompt/Prompt.scss
|
@import '~@proton/styles/scss/lib';
.prompt {
&#{&} {
--size: #{rem(288)};
}
&-header {
margin-block: 1.5em 0.5em;
margin-inline: var(--margin);
}
&-actions {
margin-block: 0.5em;
margin-inline: var(--margin);
}
&-footer {
&#{&} {
display: block;
}
}
}
| 5,568
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/prompt/Prompt.tsx
|
import { ReactElement, ReactNode, cloneElement, useContext } from 'react';
import clsx from '@proton/utils/clsx';
import { ModalContentProps, ModalContext, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter } from '../modalTwo';
import './Prompt.scss';
const PromptTitle = ({ children }: { children: ReactNode }) => (
<h1 id={useContext(ModalContext).id} className="text-lg text-bold">
{children}
</h1>
);
export interface PromptProps extends Omit<ModalProps, 'children' | 'size' | 'title'> {
title: string | JSX.Element;
subline?: string;
footnote?: string;
buttons: JSX.Element | [JSX.Element] | [JSX.Element, JSX.Element] | [JSX.Element, JSX.Element, JSX.Element];
actions?: JSX.Element | [JSX.Element] | [JSX.Element, JSX.Element] | undefined;
children: ReactNode;
ModalContentProps?: ModalContentProps;
'data-testid'?: string;
}
const Prompt = ({
title,
subline,
footnote,
buttons,
actions,
className,
children,
ModalContentProps,
'data-testid': dataTestId,
...rest
}: PromptProps) => {
const buttonArray = Array.isArray(buttons) ? buttons : [buttons];
const [firstButton, secondButton, thirdButton] = buttonArray.map((child) =>
cloneElement(child as ReactElement, { fullWidth: true })
);
const actionsContent = (() => {
if (actions === undefined) {
return null;
}
const actionsArray = Array.isArray(actions) ? actions : [actions];
const [firstAction, secondAction] = actionsArray.map((child) => cloneElement(child as ReactElement));
return (
<div className="prompt-actions">
<div className="flex flex-column gap-2">
{firstAction}
{secondAction}
</div>
</div>
);
})();
return (
<ModalTwo size="small" {...rest} className={clsx([className, 'prompt'])}>
<div className="prompt-header" data-testid={dataTestId}>
<PromptTitle>{title}</PromptTitle>
{subline && <div className="color-weak text-break">{subline}</div>}
</div>
<ModalTwoContent {...ModalContentProps}>{children}</ModalTwoContent>
{actionsContent}
<ModalTwoFooter className="prompt-footer">
<div className={clsx('flex gap-2', footnote && 'pb-2')}>
{firstButton}
{secondButton}
{thirdButton}
</div>
{footnote && <p className="color-weak text-break text-center text-sm">{footnote}</p>}
</ModalTwoFooter>
</ModalTwo>
);
};
export default Prompt;
| 5,569
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/prompt/index.ts
|
export { default as Prompt } from './Prompt';
export * from './Prompt';
| 5,570
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/protonBadge/ProtonBadge.scss
|
@import '~@proton/styles/scss/lib';
.label-proton-badge {
padding-inline: em(6, 12);
block-size: rem(18);
&--selected {
// only to use when component is in a selected element in mail list
background-color: var(--email-item-selected-text-color);
}
}
| 5,571
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/protonBadge/ProtonBadge.tsx
|
import { Tooltip } from '@proton/components/components';
import clsx from '@proton/utils/clsx';
import './ProtonBadge.scss';
interface Props {
text: string;
tooltipText: string;
selected?: boolean;
}
const ProtonBadge = ({ text, tooltipText, selected = false }: Props) => {
return (
<Tooltip title={tooltipText}>
<span
className={clsx(
'label-proton-badge inline-flex rounded bg-weak flex-item-noshrink text-ellipsis text-semibold ml-2 text-sm mr-1',
selected && 'label-proton-badge--selected'
)}
data-testid="proton-badge"
>
<span className="label-proton-badge-text color-primary m-auto">{text}</span>
</span>
</Tooltip>
);
};
export default ProtonBadge;
| 5,572
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/protonBadge/ProtonBadgeType.test.tsx
|
import { render } from '@testing-library/react';
import { ProtonBadgeType } from '@proton/components/components';
import { Recipient } from '@proton/shared/lib/interfaces';
jest.mock('@proton/components/hooks/useFeature', () => jest.fn(() => ({ feature: { Value: true } })));
describe('ProtonBadgeType', () => {
it('should show a verified badge', async () => {
const verifiedRecipient: Recipient = {
Name: 'Verified',
Address: 'verified@pm.me',
IsProton: 1,
};
const { getByTestId } = render(<ProtonBadgeType recipient={verifiedRecipient} />);
getByTestId('proton-badge');
});
it('should not show a verified badge', async () => {
const normalRecipient: Recipient = {
Name: 'Normal',
Address: 'normal@pm.me',
IsProton: 0,
};
const { queryByTestId } = render(<ProtonBadgeType recipient={normalRecipient} />);
const protonBadge = queryByTestId('proton-badge');
expect(protonBadge).toBeNull();
});
});
| 5,573
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/protonBadge/ProtonBadgeType.tsx
|
import { FeatureCode } from '@proton/components/containers';
import { useFeature } from '@proton/components/hooks';
import { Recipient } from '@proton/shared/lib/interfaces';
import VerifiedBadge from './badgeTypes/VerifiedBadge';
interface Props {
recipient: Recipient;
selected?: boolean;
}
const ProtonBadgeType = ({ recipient, selected }: Props) => {
const { feature: protonBadgeFeature } = useFeature(FeatureCode.ProtonBadge);
const canDisplayAuthenticityBadge = !!recipient.IsProton && protonBadgeFeature?.Value;
if (canDisplayAuthenticityBadge) {
return <VerifiedBadge selected={selected} />;
}
return null;
};
export default ProtonBadgeType;
| 5,574
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/protonBadge/index.ts
|
export { default as ProtonBadgeType } from './ProtonBadgeType';
| 5,575
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/protonBadge
|
petrpan-code/ProtonMail/WebClients/packages/components/components/protonBadge/badgeTypes/VerifiedBadge.tsx
|
import { c } from 'ttag';
import { BRAND_NAME } from '@proton/shared/lib/constants';
import ProtonBadge from '../ProtonBadge';
interface Props {
selected?: boolean;
}
const VerifiedBadge = ({ selected }: Props) => {
return (
<ProtonBadge
text={c('protonbadge').t`Official`}
tooltipText={c('protonbadge').t`Official email from ${BRAND_NAME}`}
selected={selected}
/>
);
};
export default VerifiedBadge;
| 5,576
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/select/Select.tsx
|
import { DetailedHTMLProps, OptionHTMLAttributes, Ref, SelectHTMLAttributes, forwardRef, useState } from 'react';
import clsx from '@proton/utils/clsx';
import { generateUID } from '../../helpers';
import Icon from '../icon/Icon';
import useInput from '../input/useInput';
import ErrorZone from '../text/ErrorZone';
export interface OptionProps extends DetailedHTMLProps<OptionHTMLAttributes<HTMLOptionElement>, HTMLOptionElement> {
value: string | number;
text: string | number;
group?: string;
disabled?: boolean;
key?: string;
}
const buildOptions = (options: OptionProps[] = [], keyPrefix = 'option') => {
return options.map(({ key, text, ...rest }, index) => (
<option key={key || `${keyPrefix}_${index}`} {...rest}>
{text}
</option>
));
};
const buildGroupedOptions = (options: OptionProps[] = []) => {
const orphanOptions = options.filter((o: OptionProps) => !o.group);
return (
<>
{buildOptions(orphanOptions)}
{Object.entries(
options.reduce<{ [key: string]: OptionProps[] }>((acc, option) => {
if (!option.group) {
return acc;
}
const { group } = option;
acc[group] = acc[group] || [];
acc[group].push(option);
return acc;
}, {})
).map(([group, options], index) => {
return (
<optgroup key={`optionGroup_${index}`} label={group}>
{buildOptions(options, `optionGroup_${index}`)}
</optgroup>
);
})}
</>
);
};
export interface Props extends DetailedHTMLProps<SelectHTMLAttributes<HTMLSelectElement>, HTMLSelectElement> {
ref?: Ref<HTMLSelectElement>; // override ref so that LegacyRef isn't used
error?: string;
isSubmitted?: boolean;
size?: number;
options: OptionProps[];
loading?: boolean;
classNameContainer?: string;
}
/**
* @deprecated please use SelectTwo instead
*/
const Select = forwardRef<HTMLSelectElement, Props>(
(
{
options,
error,
size = 1,
className = '',
multiple = false,
loading = false,
isSubmitted = false,
classNameContainer,
...rest
}: Props,
ref
) => {
const { handlers, statusClasses, status } = useInput<HTMLSelectElement>(rest);
const [uid] = useState(generateUID('select'));
const hasError = error && (status.isDirty || isSubmitted);
const hasGroup = options.some(({ group }) => group);
return (
<>
<span className={clsx(['w-full flex flex-column', classNameContainer])}>
<span className="flex relative w-full">
<select
className={clsx(['field w-full', className, statusClasses])}
size={size}
multiple={multiple}
disabled={loading || rest.disabled}
ref={ref}
{...rest}
{...handlers}
>
{hasGroup ? buildGroupedOptions(options) : buildOptions(options)}
</select>
<Icon name="chevron-down-filled" className="absolute no-pointer-events right-icon" />
</span>
{hasError && <ErrorZone id={uid}>{error}</ErrorZone>}
</span>
</>
);
}
);
export default Select;
| 5,577
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/select/index.ts
|
export { default as Select } from './Select';
| 5,578
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/selectTwo/SearchableSelect.tsx
|
import { FormEvent, KeyboardEvent, MouseEvent, ReactNode, useMemo, useRef, useState } from 'react';
import { c } from 'ttag';
import clsx from '@proton/utils/clsx';
import { Dropdown, DropdownSizeUnit } from '../dropdown';
import { DropdownSize } from '../dropdown/utils';
import { SearchInput } from '../input';
import Option, { Props as OptionProps } from '../option/Option';
import { PopperPlacement } from '../popper';
import SelectButton from './SelectButton';
import { SelectDisplayValue } from './SelectDisplayValue';
import SelectOptions from './SelectOptions';
import { defaultFilterFunction } from './helpers';
import { SelectProps } from './select';
import useSelect, { SelectProvider } from './useSelect';
export interface Props<V> extends SelectProps<V> {
search?: boolean | ((option: OptionProps<V>, keyword?: string) => void);
searchPlaceholder?: string;
noSearchResults?: ReactNode;
unstyled?: boolean;
size?: DropdownSize;
originalPlacement?: PopperPlacement;
}
const SearchableSelect = <V extends any>({
multiple = false,
children,
value,
placeholder,
isOpen: controlledOpen,
loading,
search,
searchPlaceholder,
size = { width: DropdownSizeUnit.Anchor, maxWidth: DropdownSizeUnit.Viewport },
noSearchResults = c('Select search results').t`No results found`,
onClose,
onOpen,
onChange,
renderSelected,
originalPlacement,
...rest
}: Props<V>) => {
const [searchValue, setSearchValue] = useState('');
const anchorRef = useRef<HTMLButtonElement | null>(null);
const searchContainerRef = useRef<HTMLDivElement>(null);
const searchInputRef = useRef<HTMLInputElement>(null);
const optionChildren = children.filter((child) => child.type === Option);
const optionValues = optionChildren.map((option) => option.props.value);
const select = useSelect({
isOpen: controlledOpen,
multiple,
value,
options: optionValues,
onChange,
onClose,
onOpen,
});
const {
isOpen,
selectedIndexes,
autoclose,
open,
close: handleClose,
setFocusedIndex,
handleChange,
focusNextIndex,
focusPreviousIndex,
focusedIndex,
} = select;
const close = (event?: MouseEvent<HTMLDivElement> | Event) => {
if (event?.target instanceof Node && searchContainerRef?.current?.contains(event.target)) {
return;
}
handleClose();
};
const focusSearchInput = () => {
searchInputRef?.current?.focus();
};
const handleAnchorClick = () => {
if (isOpen) {
close();
} else {
open();
setFocusedIndex(selectedIndexes?.[0] || 0);
}
};
const handleClosed = () => {
setSearchValue('');
};
const handleDropdownContentKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
switch (e.key) {
case 'Escape': {
close();
anchorRef.current?.focus();
break;
}
default:
}
};
const onSearchChange = (event: FormEvent<HTMLInputElement>) => {
setSearchValue(event.currentTarget.value);
if (!event.currentTarget.value) {
focusSearchInput();
}
};
const selectedChildren = (selectedIndexes ?? []).map((i) => optionChildren[i]);
const ariaLabel = selectedChildren?.map((child) => child.props.title).join(', ');
const filteredOptions = useMemo(() => {
if (!searchValue) {
return optionChildren;
}
const filterFunction = typeof search === 'function' ? search : defaultFilterFunction;
return optionChildren.filter((child) => filterFunction(child.props, searchValue));
}, [children, search, searchValue]);
const selectedIndexesInFilteredOptions =
selectedIndexes
?.map((index) => filteredOptions.findIndex((option) => option === optionChildren[index]))
?.filter((idx) => idx !== -1) ?? null;
const pressedDown = useRef(false);
return (
<SelectProvider {...select}>
<SelectButton isOpen={isOpen} onClick={handleAnchorClick} aria-label={ariaLabel} ref={anchorRef} {...rest}>
{renderSelected?.(value) ?? (
<SelectDisplayValue selectedChildren={selectedChildren} placeholder={placeholder} />
)}
</SelectButton>
<Dropdown
isOpen={isOpen}
onClosed={handleClosed}
anchorRef={anchorRef}
onClose={close}
autoClose={autoclose}
offset={4}
noCaret
size={size}
disableDefaultArrowNavigation={!searchValue}
originalPlacement={originalPlacement}
className={clsx([
searchContainerRef?.current && 'dropdown--is-searchable',
multiple && 'select-dropdown--togglable',
])}
>
<div onKeyDown={handleDropdownContentKeyDown}>
<div className="dropdown-search" ref={searchContainerRef}>
<SearchInput
onKeyDown={(e) => {
if (searchValue) {
return;
}
if (e.key === 'ArrowDown') {
focusNextIndex();
}
if (e.key === 'ArrowUp') {
focusPreviousIndex();
}
if (e.key === 'Tab') {
handleClose();
}
if (e.key === 'Enter') {
pressedDown.current = true;
}
}}
onKeyUp={(e) => {
if (searchValue) {
return;
}
if (e.key === 'Enter' && pressedDown.current) {
if (focusedIndex) {
handleChange({
value: optionValues[focusedIndex],
selectedIndex: focusedIndex,
});
handleClose();
}
pressedDown.current = false;
}
}}
autoFocus
ref={searchInputRef}
value={searchValue}
onInput={onSearchChange}
placeholder={searchPlaceholder}
/>
</div>
{filteredOptions.length === 0 ? (
<div className="dropdown-search-no-result text-center">{noSearchResults}</div>
) : (
<SelectOptions
disableFocusOnActive
selected={selectedIndexesInFilteredOptions}
onChange={handleChange}
>
{filteredOptions}
</SelectOptions>
)}
</div>
</Dropdown>
</SelectProvider>
);
};
export default SearchableSelect;
| 5,579
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/selectTwo/SelectButton.tsx
|
import { ComponentPropsWithRef, KeyboardEvent, forwardRef } from 'react';
import { CircleLoader } from '@proton/atoms';
import clsx from '@proton/utils/clsx';
import { DropdownCaret } from '../dropdown';
import type { IconName } from '../icon/Icon';
import { NodeOrBoolean } from '../v2/field/InputField';
interface SelectButtonProps extends Omit<ComponentPropsWithRef<'button'>, 'value'> {
unstyled?: boolean;
caretIconName?: IconName;
loading?: boolean;
error?: NodeOrBoolean;
isOpen?: boolean;
onOpen?: () => void;
}
const SelectButton = forwardRef<HTMLButtonElement, SelectButtonProps>(
({ className, unstyled, caretIconName, loading, error, isOpen, onOpen, children, ...rest }, ref) => {
const handleAnchorKeydown = (e: KeyboardEvent<HTMLButtonElement>) => {
switch (e.key) {
case ' ': {
onOpen?.();
break;
}
default:
}
};
return (
// eslint-disable-next-line jsx-a11y/role-supports-aria-props
<button
ref={ref}
type="button"
onKeyDown={handleAnchorKeydown}
aria-expanded={isOpen}
aria-busy={loading}
aria-live="assertive"
aria-atomic="true"
aria-invalid={Boolean(error)}
className={clsx([
!unstyled && 'select field',
unstyled && 'select-unstyled',
'outline-none w-full flex flex-justify-space-between flex-align-items-center flex-nowrap no-pointer-events-children',
className,
])}
{...rest}
>
<span className="flex-item-fluid text-ellipsis text-left">{children}</span>
{loading ? (
<CircleLoader className="flex-item-noshrink ml-1" />
) : (
<DropdownCaret className="flex-item-noshrink ml-1" isOpen={isOpen} />
)}
</button>
);
}
);
SelectButton.displayName = 'SelectButton';
export default SelectButton;
| 5,580
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/selectTwo/SelectDisplayValue.tsx
|
import React, { Fragment, ReactElement } from 'react';
import { Props as OptionProps } from '../option/Option';
type SelectDisplayValueProps<V> = {
placeholder?: string;
selectedChildren: ReactElement<OptionProps<V>>[];
};
export const SelectDisplayValue = <V,>({ selectedChildren, placeholder = '' }: SelectDisplayValueProps<V>) => {
const displayedValue =
selectedChildren.length > 0
? selectedChildren?.map((child, i, all) => (
<Fragment key={child.key}>
{child.props.children ?? child.props.title}
{`${i === all.length - 1 ? '' : ', '}`}
</Fragment>
))
: placeholder;
return <>{displayedValue}</>;
};
| 5,581
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/selectTwo/SelectOptions.tsx
|
import {
Children,
ComponentPropsWithoutRef,
KeyboardEvent,
ReactElement,
cloneElement,
isValidElement,
useContext,
} from 'react';
import Option, { Props as OptionProps } from '../option/Option';
import { SelectChangeEvent } from './select';
import { SelectContext } from './useSelect';
interface SelectOptionsProps<V> extends Omit<ComponentPropsWithoutRef<'ul'>, 'onChange'> {
selected: number | number[] | null;
children: ReactElement<OptionProps<V>>[];
disableFocusOnActive?: boolean;
onChange: (e: SelectChangeEvent<V>) => void;
}
const SelectOptions = <V,>({
children,
disableFocusOnActive = false,
selected,
onChange,
onKeyDown,
...rest
}: SelectOptionsProps<V>) => {
const { focusedIndex, focusPreviousIndex, focusNextIndex, close } = useContext(SelectContext);
const handleMenuKeydown = (e: KeyboardEvent<HTMLUListElement>) => {
onKeyDown?.(e);
switch (e.key) {
case 'ArrowUp': {
e.preventDefault();
focusPreviousIndex();
break;
}
case 'ArrowDown': {
e.preventDefault();
focusNextIndex();
break;
}
case 'Escape': {
e.preventDefault();
close();
break;
}
default:
}
};
const handleChange = (event: SelectChangeEvent<V>) => {
onChange?.(event);
};
const handleChildChange = (index: number) => (value: V) => {
handleChange({ value, selectedIndex: index });
};
const optionIndices = Children.toArray(children).reduce<number[]>((acc, child, index) => {
return isValidElement(child) && child.type === Option ? [...acc, index] : acc;
}, []);
const items = Children.map(children, (child, index) => {
const localIndex = optionIndices.indexOf(index);
if (optionIndices.includes(index)) {
return cloneElement(child, {
disableFocusOnActive: disableFocusOnActive,
selected: Array.isArray(selected) ? selected.includes(localIndex) : selected === localIndex,
active: focusedIndex === localIndex,
onChange: handleChildChange(localIndex),
});
}
return child;
});
return (
<ul className="unstyled m-0 p-0" onKeyDown={handleMenuKeydown} data-testid="select-list" {...rest}>
{items}
</ul>
);
};
export default SelectOptions;
| 5,582
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/selectTwo/SelectTwo.test.tsx
|
import { RenderResult, fireEvent, render, within } from '@testing-library/react';
import { Option } from '../option';
import SelectTwo from './SelectTwo';
function renderBasicSelect() {
return render(
<SelectTwo data-testid="dropdown-button">
<Option title="one" value="one" />
<Option title="two" value="two" />
<Option title="three" value="three" />
</SelectTwo>
);
}
function renderSelectWithSelectedOption() {
return render(
<SelectTwo value="two" data-testid="dropdown-button">
<Option title="one" value="one" />
<Option title="two" value="two" />
<Option title="three" value="three" />
</SelectTwo>
);
}
function getAnchor({ getByTestId }: RenderResult) {
return getByTestId('dropdown-button');
}
function getList({ getByTestId }: RenderResult) {
return getByTestId('select-list');
}
function openByClick(renderResult: RenderResult) {
fireEvent.click(getAnchor(renderResult));
}
describe('SelectTwo component', () => {
it('should open on click', () => {
const output = renderBasicSelect();
openByClick(output);
expect(getList(output)).toBeInTheDocument();
});
it('should select a value on click', () => {
const spy = jest.fn();
const output = render(
<SelectTwo onChange={spy} data-testid="dropdown-button">
<Option title="one" value="one" />
<Option title="two" value="two" />
</SelectTwo>
);
openByClick(output);
const { getByText } = output;
fireEvent.click(getByText('one'));
const [[{ value }]] = spy.mock.calls;
expect(value).toBe('one');
});
it('should render a placeholer if no value is selected', () => {
const { getByText } = render(
<SelectTwo placeholder="Placeholder" data-testid="dropdown-button">
<Option title="one" value="one" />
<Option title="two" value="two" />
</SelectTwo>
);
expect(getByText('Placeholder')).toBeTruthy();
});
it(`should open on " " (Space) keydown`, () => {
const output = renderBasicSelect();
fireEvent.keyDown(getAnchor(output), { key: ' ' });
expect(getList(output)).toBeInTheDocument();
});
it(`should select "two" when typing "t"`, () => {
const spy = jest.fn();
const output = render(
<SelectTwo onChange={spy} data-testid="dropdown-button">
<Option title="one" value="one" />
<Option title="two" value="two" />
</SelectTwo>
);
fireEvent.keyDown(getAnchor(output), { key: 't' });
const [[{ value }]] = spy.mock.calls;
expect(value).toBe('two');
});
it('should focus the first element when opened and no option is selected', () => {
const output = renderBasicSelect();
openByClick(output);
const { getByText } = output;
expect(getByText('one')).toHaveFocus();
});
it('should focus the selected element when opened and an option is selected', () => {
const output = renderSelectWithSelectedOption();
openByClick(output);
const { getByText } = within(getList(output));
expect(getByText('two')).toHaveFocus();
});
/*
* https://spectrum.chat/testing-library/general/ontransitionend~7b84288b-716e-42c3-853c-78295a92fd63
*/
// it('should close on "Escape" keydown and give focus back to anchor', () => {
// const output = renderBasicSelect();
// openByClick(output);
// fireEvent.keyDown(getList(output), { key: 'Escape' });
// expect(getList(output)).not.toBeInTheDocument();
// expect(getAnchor(output)).toHaveFocus();
// });
it(`should focus the next option on "ArrowDown" keydown`, () => {
const output = renderBasicSelect();
openByClick(output);
fireEvent.keyDown(getList(output), { key: 'ArrowDown' });
const { getByText } = within(getList(output));
expect(getByText('two')).toHaveFocus();
});
it(`should focus the previous option on "ArrowUp" keydown`, () => {
const output = renderSelectWithSelectedOption();
openByClick(output);
fireEvent.keyDown(getList(output), { key: 'ArrowUp' });
const { getByText } = within(getList(output));
expect(getByText('one')).toHaveFocus();
});
/*
* https://spectrum.chat/testing-library/general/ontransitionend~7b84288b-716e-42c3-853c-78295a92fd63
*/
// it('should close the select and focus the anchor when pressing "Shift+Tab" given that the first element is selected', () => {
// const output = renderBasicSelect();
// openByClick(output);
// fireEvent.keyDown(getList(output), { key: 'Tab', shiftKey: true });
// expect(getList(output)).not.toBeInTheDocument();
// expect(getAnchor(output)).toHaveFocus();
// });
// it('should close the select and focus the anchor when pressing "Shift" given that the last element is selected', async () => {
// const output = renderBasicSelect();
// openByClick(output);
// fireEvent.keyDown(getList(output), { key: 'Tab' });
// fireEvent.keyDown(getList(output), { key: 'Tab' });
// fireEvent.keyDown(getList(output), { key: 'Tab' });
// expect(getList(output)).not.toBeInTheDocument();
// expect(getAnchor(output)).toHaveFocus();
// });
it('should focus the element most closely matching typed keyboard input', () => {
const output = renderBasicSelect();
openByClick(output);
const list = getList(output);
fireEvent.keyDown(list, { key: 't' });
const { getByText } = within(list);
expect(getByText('two')).toHaveFocus();
});
it('should clear the current typed input after a given amount of ms and match the new input after the delay', async () => {
const output = render(
<SelectTwo clearSearchAfter={800} data-testid="dropdown-button">
<Option title="one" value="one" />
<Option title="two" value="two" />
<Option title="three" value="three" />
</SelectTwo>
);
openByClick(output);
const list = getList(output);
fireEvent.keyDown(list, { key: 't' });
const { getByText } = within(list);
expect(getByText('two')).toHaveFocus();
await new Promise((resolve) => setTimeout(resolve, 1000));
fireEvent.keyDown(list, { key: 'o' });
expect(getByText('one')).toHaveFocus();
});
it('continues the typed input from the last keystroke if the delay is small enough', () => {
const output = renderBasicSelect();
openByClick(output);
const list = getList(output);
fireEvent.keyDown(list, { key: 't' });
const { getByText } = within(list);
expect(getByText('two')).toHaveFocus();
fireEvent.keyDown(list, { key: 'h' });
expect(getByText('three')).toHaveFocus();
});
it('supports the search feature even with complex values given that "getSearchableValue" is supplied', () => {
type V = { label: string; amount: number };
const getSearchableValue = ({ label }: V) => label;
const output = render(
<SelectTwo getSearchableValue={getSearchableValue} data-testid="dropdown-button">
<Option title="one" value={{ label: 'one' }} />
<Option title="two" value={{ label: 'two' }} />
<Option title="three" value={{ label: 'three' }} />
</SelectTwo>
);
openByClick(output);
const list = getList(output);
fireEvent.keyDown(list, { key: 't' });
fireEvent.keyDown(list, { key: 'w' });
const { getByText } = output;
expect(getByText('two')).toHaveFocus();
});
it('supports multiple selection mode', () => {
const onChangeSpy = jest.fn();
const output = render(
<SelectTwo data-testid="dropdown-button" multiple value={['one', 'two']} onChange={onChangeSpy}>
<Option title="one" value="one" />
<Option title="two" value="two" />
<Option title="three" value="three" />
</SelectTwo>
);
openByClick(output);
expect(output.getByText('one')).toHaveClass('dropdown-item--is-selected');
expect(output.getByText('two')).toHaveClass('dropdown-item--is-selected');
expect(output.getByText('three')).not.toHaveClass('dropdown-item--is-selected');
fireEvent.click(output.getByText('three'));
expect(onChangeSpy).toBeCalledWith({ selectedIndex: 2, value: ['one', 'two', 'three'] });
});
it('supports multiple selection mode with complex values', () => {
const onChangeSpy = jest.fn();
const options = [
{ label: 'one', key: 1 },
{ label: 'two', key: 2 },
{ label: 'three', key: 3 },
];
const output = render(
<SelectTwo data-testid="dropdown-button" multiple value={[options[0]]} onChange={onChangeSpy}>
{options.map((option) => (
<Option title={option.label} value={option} key={option.key} />
))}
</SelectTwo>
);
openByClick(output);
expect(output.getByText('one', { selector: 'button' })).toHaveClass('dropdown-item--is-selected');
expect(output.getByText('two', { selector: 'button' })).not.toHaveClass('dropdown-item--is-selected');
expect(output.getByText('three', { selector: 'button' })).not.toHaveClass('dropdown-item--is-selected');
fireEvent.click(output.getByText('three'));
expect(onChangeSpy).toBeCalledWith({ selectedIndex: 2, value: [options[0], options[2]] });
});
});
| 5,583
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/selectTwo/SelectTwo.tsx
|
import { KeyboardEvent, MutableRefObject, useEffect, useMemo, useRef, useState } from 'react';
import { normalize } from '@proton/shared/lib/helpers/string';
import clsx from '@proton/utils/clsx';
import Dropdown, { DropdownProps } from '../dropdown/Dropdown';
import { DropdownSizeUnit } from '../dropdown/utils';
import type { IconName } from '../icon/Icon';
import Option from '../option/Option';
import { PopperPlacement } from '../popper';
import SelectButton from './SelectButton';
import { SelectDisplayValue } from './SelectDisplayValue';
import SelectOptions from './SelectOptions';
import { SelectProps } from './select';
import useSelect, { SelectProvider } from './useSelect';
export interface Props<V> extends SelectProps<V> {
/**
* Optionally allows to remove the border around the select. Use for example in inputs
*/
unstyled?: boolean;
/**
* Optionally allows different icons as caret
*/
caretIconName?: IconName;
/**
* Milliseconds after which to clear the current user input
* (the input is used for highlighting match based on keyboard input)
*/
clearSearchAfter?: number;
/**
* In case you're providing complex values to your options, you can
* provide a function to return a string given one of your complex
* value items. This is optional however if you do not provide it and
* your values are complex, the search feature will be disabled for
* that instance of the Select.
*/
size?: DropdownProps['size'];
originalPlacement?: PopperPlacement;
anchorRef?: MutableRefObject<HTMLButtonElement | null>;
getSearchableValue?: (value: V) => string;
}
const defaultSize = { width: DropdownSizeUnit.Anchor, maxWidth: DropdownSizeUnit.Viewport } as const;
const SelectTwo = <V extends any>({
multiple = false,
unstyled,
caretIconName,
children,
value,
placeholder,
isOpen: controlledOpen,
clearSearchAfter = 500,
size = defaultSize,
originalPlacement,
loading,
anchorRef: maybeAnchorRef,
onClose,
onOpen,
onChange,
onValue,
getSearchableValue,
renderSelected,
...rest
}: Props<V>) => {
const anchorRef = useRef<HTMLButtonElement | null>(null);
const [search, setSearch] = useState('');
const searchClearTimeout = useRef<number | undefined>(undefined);
const optionChildren = children.filter((child) => child.type === Option);
const optionValues = optionChildren.map((child) => child.props.value);
const select = useSelect({
isOpen: controlledOpen,
multiple,
value,
options: optionValues,
onChange,
onValue,
onOpen,
onClose,
});
const { isOpen, selectedIndexes, autoclose, open, close, setFocusedIndex, handleChange } = select;
/*
* Natural search-ability determined by whether or not all option values
* from the passed children are strings, there's also "unnatural" search-
* ability if the prop "getSearchableValue" is passed
*
* Another valid condition for the natural search-ability of the options
* is whether or not they all have a "title" attribute
*/
const [allOptionChildrenAreStrings, allOptionsHaveTitles] = useMemo(
() => [
optionChildren.every((child) => typeof child.props.children === 'string'),
optionChildren.every((child) => Boolean(child.props.title)),
],
[optionChildren]
);
const isNaturallySearchable = allOptionChildrenAreStrings || allOptionsHaveTitles;
const isSearchable = isNaturallySearchable || Boolean(getSearchableValue);
const searchableItems = useMemo(() => {
if (isNaturallySearchable) {
return allOptionChildrenAreStrings
? (optionChildren.map((child) => child.props.children) as string[])
: optionChildren.map((child) => child.props.title);
}
if (getSearchableValue) {
return optionValues.map(getSearchableValue);
}
return [];
}, [allOptionChildrenAreStrings, children]);
useEffect(() => {
if (!search || !isSearchable) {
return;
}
window.clearTimeout(searchClearTimeout.current);
searchClearTimeout.current = window.setTimeout(() => {
setSearch('');
}, clearSearchAfter);
const normalizedSearch = normalize(search);
const indexOfMatchedOption = searchableItems.findIndex((v) => normalize(v).startsWith(normalizedSearch));
if (indexOfMatchedOption !== -1) {
if (isOpen) {
setFocusedIndex(indexOfMatchedOption);
} else {
const matchedValue = optionValues[indexOfMatchedOption];
onChange?.({
value: matchedValue,
selectedIndex: indexOfMatchedOption,
});
onValue?.(matchedValue);
}
}
}, [search]);
const handleAnchorClick = () => {
if (isOpen) {
close();
} else {
open();
}
};
const handleKeydown = (e: KeyboardEvent<HTMLElement>) => {
const { key } = e;
if (key === 'Escape') {
close();
anchorRef.current?.focus();
return;
}
if (key === ' ') {
open();
return;
}
const isAlphanumeric = /^[A-Za-z0-9]$/.test(key);
if (isAlphanumeric && isSearchable) {
setSearch((s) => s + key);
}
};
const selectedChildren = (selectedIndexes ?? []).map((i) => optionChildren[i]);
const ariaLabel = selectedChildren?.map((child) => child.props.title).join(', ');
const allowOptionToggling = multiple && optionChildren.length > 1;
return (
<SelectProvider {...select}>
<SelectButton
unstyled={unstyled}
caretIconName={caretIconName}
isOpen={isOpen}
onOpen={open}
onClick={handleAnchorClick}
onKeyDown={handleKeydown}
aria-label={ariaLabel}
ref={anchorRef}
{...rest}
>
{renderSelected?.(value) ?? (
<SelectDisplayValue selectedChildren={selectedChildren} placeholder={placeholder} />
)}
</SelectButton>
<Dropdown
isOpen={isOpen}
anchorRef={maybeAnchorRef || anchorRef}
onClose={close}
autoClose={autoclose}
offset={4}
noCaret
size={size}
originalPlacement={originalPlacement}
disableDefaultArrowNavigation
className={clsx(['select-dropdown', allowOptionToggling && 'select-dropdown--togglable'])}
>
<SelectOptions selected={selectedIndexes} onKeyDown={handleKeydown} onChange={handleChange}>
{children}
</SelectOptions>
</Dropdown>
</SelectProvider>
);
};
export default SelectTwo;
| 5,584
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/selectTwo/helpers.ts
|
import { normalize } from '@proton/shared/lib/helpers/string';
import { Props as OptionProps } from '../option/Option';
export const includesString = (str1: string, str2: string) => normalize(str1, true).includes(normalize(str2, true));
export const arrayIncludesString = (arrayToSearch: string[], keyword: string) =>
arrayToSearch.some((str) => includesString(str, keyword));
export const defaultFilterFunction = <V>(option: OptionProps<V>, keyword: string) =>
(option.title && includesString(option.title, keyword)) ||
(option.searchStrings && arrayIncludesString(option.searchStrings, keyword));
| 5,585
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/selectTwo/index.ts
|
export { default as SelectTwo } from './SelectTwo';
export { default as SearchableSelect } from './SearchableSelect';
export * from './SelectTwo';
| 5,586
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/selectTwo/select.ts
|
import { ComponentPropsWithoutRef, ReactElement, ReactNode } from 'react';
import { Props as OptionProps } from '../option/Option';
import { NodeOrBoolean } from '../v2/field/InputField';
export type SelectChangeEvent<V> = {
value: V;
selectedIndex: number;
};
export interface SelectProps<V>
extends Omit<ComponentPropsWithoutRef<'button'>, 'value' | 'onClick' | 'onChange' | 'onKeyDown' | 'aria-label'> {
value?: V;
/**
* Enable multiple mode, allowing selection of multiple values.
* In this mode, the value prop the value prop must be an array.
*/
multiple?: boolean;
/**
* Optionally allows controlling the Select's open state
*/
isOpen?: boolean;
/**
* Children Options of the Select, have to be of type Option
* (or something that implements the same interface)
*/
children: ReactElement<OptionProps<V>>[];
loading?: boolean;
error?: NodeOrBoolean;
onChange?: (e: SelectChangeEvent<V>) => void;
onValue?: (value: V) => void;
onClose?: () => void;
onOpen?: () => void;
/**
* Render function to render the displayed value inside the select's
* anchor. If null is returned, will fall back to the internal implementation.
*/
renderSelected?: (selected?: V) => ReactNode;
}
export function isValidMultiMode<V>(value: any, multiple: boolean): value is V & any[] {
if (!multiple) {
return false;
}
if (value !== undefined && !Array.isArray(value)) {
/* eslint-disable-next-line no-console */
console.warn('[SelectTwo] Incorrect usage : if using multiple mode, value must be an array');
return false;
}
return true;
}
| 5,587
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/selectTwo/useSelect.tsx
|
import { ReactNode, createContext, useMemo, useState } from 'react';
import useControlled from '@proton/hooks/useControlled';
import { SelectChangeEvent, isValidMultiMode } from './select';
interface UseSelectOptions<V> {
multiple: boolean;
value?: V;
options: V[];
isOpen?: boolean;
onChange?: (e: SelectChangeEvent<V>) => void;
onValue?: (value: V) => void;
onClose?: () => void;
onOpen?: () => void;
}
interface UseSelectOutput<V> {
isOpen: boolean;
focusedIndex: number | null;
selectedIndexes: number[];
autoclose: boolean;
open: () => void;
close: () => void;
setFocusedIndex: (index: number) => void;
focusPreviousIndex: () => void;
focusNextIndex: () => void;
handleChange: (e: SelectChangeEvent<V>) => void;
}
const useSelect = <V,>({
multiple,
value: maybeValue,
options,
isOpen: controlledOpen,
onOpen,
onClose,
onChange,
onValue,
}: UseSelectOptions<V>): UseSelectOutput<V> => {
const value = multiple && maybeValue === undefined ? [] : maybeValue;
const isMulti = isValidMultiMode<V>(value, multiple);
const [isOpen = false, setIsOpen] = useControlled(controlledOpen, false);
const [focusedIndex, setFocusedIndex] = useState<UseSelectOutput<V>['focusedIndex']>(null);
/**
* multi mode specifics :
* - we want to disable dropdown autoclose on click to allowing selecting multiple options
* - if we only have a single option in multi mode, auto closing should be re-enabled
*/
const autoclose = !multiple || options.length <= 1;
const selectedIndexes = useMemo<number[]>(
() =>
(isMulti ? value : [value])
.filter((val) => val !== undefined)
.map((val) => options.findIndex((option) => option === val))
.filter((idx) => idx !== -1),
[options, value]
);
const open = () => {
setIsOpen(true);
onOpen?.();
setFocusedIndex(selectedIndexes?.[0] || 0);
};
const close = () => {
setIsOpen(false);
onClose?.();
};
const focusPreviousIndex = () => {
if (focusedIndex !== null && focusedIndex !== 0) {
setFocusedIndex(focusedIndex - 1);
}
};
const focusNextIndex = () => {
if (focusedIndex !== null && focusedIndex !== options.length - 1) {
setFocusedIndex(focusedIndex + 1);
}
};
const handleChange: UseSelectOutput<V>['handleChange'] = (e) => {
const nextValue: V = (() => {
if (isMulti) {
const isSelected = value.some((selectedValue) => e.value === selectedValue);
return (isSelected
? value.filter((selectedValue) => selectedValue !== e.value)
: [...value, e.value]) as any as V;
}
return e.value;
})();
e.value = nextValue;
onChange?.(e);
onValue?.(nextValue);
};
return {
open,
close,
isOpen,
autoclose,
focusedIndex,
setFocusedIndex,
focusPreviousIndex,
focusNextIndex,
handleChange,
selectedIndexes,
};
};
export default useSelect;
/*
* The purpose of this provider is merely to pass the value returned from
* useSelect down the tree for any composed children to consume.
* As far as I'm aware there is no context provider api in pure hook fashion
* so we have to use a component here.
*
* That being said, since it's really part of useSelect, less the api inconvenience,
* I've chosen to define it inside this hook's definition file.
*/
export const SelectContext = createContext({} as UseSelectOutput<any>);
interface SelectProviderProps<V> extends UseSelectOutput<V> {
children: ReactNode;
}
export const SelectProvider = <V,>({ children, ...rest }: SelectProviderProps<V>) => {
return <SelectContext.Provider value={rest}>{children}</SelectContext.Provider>;
};
| 5,588
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/shortcuts/ShortcutsSectionView.tsx
|
import { Kbd } from '@proton/atoms';
import clsx from '@proton/utils/clsx';
interface Shortcut {
name: string;
keys: string | string[];
}
interface Props {
name: string;
shortcuts: Shortcut[];
}
const ShortcutsSectionView = ({ name, shortcuts }: Props) => {
return (
<div className="mb-8">
<h2 className="h5 mb-2">{name}</h2>
{shortcuts.length > 0 && (
<ul className="unstyled mt-4 list-2columns-no-break">
{shortcuts.map(({ name, keys }) => (
<li key={name} className="flex flex-align-items-center flex-justify-space-between mb-2">
<span>{name}</span>
{typeof keys === 'string' ? (
<Kbd shortcut={keys} />
) : (
<span>
{keys.map((k: string, i: number) => (
<Kbd key={`${name} - ${k}`} shortcut={k} className={clsx([i > 0 && 'ml-2'])}>
{k}
</Kbd>
))}
</span>
)}
</li>
))}
</ul>
)}
</div>
);
};
export default ShortcutsSectionView;
| 5,589
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/shortcuts/index.ts
|
export { default as ShortcutsSectionView } from './ShortcutsSectionView';
| 5,590
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/sidebar/Hamburger.tsx
|
import { c } from 'ttag';
import { Button, ButtonProps } from '@proton/atoms';
import Icon from '../icon/Icon';
interface Props extends ButtonProps {
onToggle?: () => void;
expanded?: boolean;
sidebarId?: string;
}
const Hamburger = ({ sidebarId, expanded = true, onToggle, ...rest }: Props) => {
return (
<Button
shape="ghost"
color="weak"
className="hamburger md:hidden no-print mr-2"
aria-expanded={expanded === false ? false : undefined}
aria-controls={sidebarId}
onClick={onToggle}
{...rest}
title={expanded ? c('Action').t`Close navigation` : c('Action').t`Open navigation`}
icon
>
<Icon
size={16}
name={expanded ? 'cross' : 'hamburger'}
alt={expanded ? c('Action').t`Close navigation` : c('Action').t`Open navigation`}
/>
</Button>
);
};
export default Hamburger;
| 5,591
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/sidebar/SettingsListItem.tsx
|
import { ReactNode } from 'react';
import { c } from 'ttag';
import { NotificationDot } from '@proton/atoms';
import { ThemeColor } from '@proton/colors';
import { IconName } from '../icon/Icon';
import { SidebarListItem, SidebarListItemContent, SidebarListItemContentIcon, SidebarListItemLink } from './index';
interface Props {
to: string;
icon: IconName;
notification?: ThemeColor;
children: ReactNode;
}
const SettingsListItem = ({ to, icon, children, notification }: Props) => {
return (
<SidebarListItem>
<SidebarListItemLink to={to}>
<SidebarListItemContent
left={<SidebarListItemContentIcon name={icon} />}
right={
notification && <NotificationDot color={notification} alt={c('Info').t`Attention required`} />
}
>
{children}
</SidebarListItemContent>
</SidebarListItemLink>
</SidebarListItem>
);
};
export default SettingsListItem;
| 5,592
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/sidebar/Sidebar.tsx
|
import { ComponentPropsWithoutRef, ReactNode, useMemo, useRef } from 'react';
import { c } from 'ttag';
import { getAppName } from '@proton/shared/lib/apps/helper';
import { APPS, APP_NAMES, SHARED_UPSELL_PATHS, UPSELL_COMPONENT } from '@proton/shared/lib/constants';
import { isElectronOnMac } from '@proton/shared/lib/helpers/desktop';
import humanSize from '@proton/shared/lib/helpers/humanSize';
import { hasMailProfessional, hasNewVisionary, hasVisionary } from '@proton/shared/lib/helpers/subscription';
import { addUpsellPath, getUpsellRefFromApp } from '@proton/shared/lib/helpers/upsell';
import clsx from '@proton/utils/clsx';
import percentage from '@proton/utils/percentage';
import { UserDropdown, useActiveBreakpoint } from '../..';
import { useConfig, useSubscription, useUser } from '../../hooks';
import { useFocusTrap } from '../focus';
import { SettingsLink } from '../link';
import { getMeterColor } from '../progress';
import { Tooltip } from '../tooltip';
import Hamburger from './Hamburger';
import SidebarStorageMeter from './SidebarStorageMeter';
interface Props extends ComponentPropsWithoutRef<'div'> {
app?: APP_NAMES;
logo?: ReactNode;
expanded?: boolean;
onToggleExpand?: () => void;
primary?: ReactNode;
children?: ReactNode;
version?: ReactNode;
storageGift?: ReactNode;
hasAppLinks?: boolean;
appsDropdown: ReactNode;
contactsButton?: ReactNode;
/**
* Extra content that will be rendered below the storage meter and version.
*/
extraFooter?: ReactNode;
/**
* If `true`, the sidebar children container will grow to the maximum
* available size.
*
* This is the default behavior, set this to `false` if you want the footer
* to stick to the content.
*
* @default true
*/
growContent?: boolean;
}
const Sidebar = ({
app,
expanded = false,
appsDropdown,
onToggleExpand,
hasAppLinks = true,
logo,
primary,
children,
version,
storageGift,
contactsButton,
extraFooter,
growContent = true,
...rest
}: Props) => {
const rootRef = useRef<HTMLDivElement>(null);
const focusTrapProps = useFocusTrap({
active: expanded,
rootRef,
});
const { APP_NAME } = useConfig();
const [user] = useUser();
const [subscription] = useSubscription();
const { UsedSpace, MaxSpace, isMember, isSubUser } = user;
const spacePercentage = percentage(MaxSpace, UsedSpace);
const { isNarrow } = useActiveBreakpoint();
const isElectron = isElectronOnMac();
const upsellRef = getUpsellRefFromApp({
app: APP_NAME,
feature: SHARED_UPSELL_PATHS.STORAGE,
component: UPSELL_COMPONENT.BUTTON,
fromApp: app,
});
const canAddStorage = useMemo(() => {
if (!subscription) {
return false;
}
if (isSubUser) {
return false;
}
if (isMember) {
return false;
}
if (hasNewVisionary(subscription) || hasVisionary(subscription) || hasMailProfessional(subscription)) {
return false;
}
return true;
}, [subscription, user]);
const storageText = (
<>
<span
className={clsx(['used-space text-bold', `color-${getMeterColor(spacePercentage)}`])}
style={{ '--signal-success': 'initial' }}
>
{humanSize(UsedSpace)}
</span>
/ <span className="max-space">{humanSize(MaxSpace)}</span>
</>
);
return (
<>
<div
ref={rootRef}
className={clsx('sidebar flex flex-nowrap flex-column no-print outline-none', isElectron && 'mt-3')}
data-expanded={expanded}
{...rest}
{...focusTrapProps}
>
<Hamburger
expanded={expanded}
onToggle={onToggleExpand}
className="md:hidden flex-item-noshrink absolute right mr-5 mt-2 opacity-0 focus:opacity-100 bg-norm"
/>
<h1 className="sr-only">{getAppName(APP_NAME)}</h1>
<div className="logo-container hidden md:flex flex-item-noshrink flex-justify-space-between flex-align-items-center flex-nowrap">
{logo}
<div className="hidden md:block">{appsDropdown}</div>
</div>
{isNarrow && (
<div className="px-3 flex-item-noshrink md:hidden">
<UserDropdown app={APP_NAME} hasAppLinks={hasAppLinks} />
</div>
)}
{primary ? <div className="px-3 pb-2 flex-item-noshrink hidden md:block">{primary}</div> : null}
<div className="mt-1 md:mt-0" aria-hidden="true" />
<div
className={clsx(
growContent ? 'flex-item-fluid' : 'flex-item-nogrow',
'flex-nowrap flex flex-column overflow-overlay pb-2 md:mt-2'
)}
>
{contactsButton}
{children}
</div>
{APP_NAME !== APPS.PROTONVPN_SETTINGS ? (
<div className="flex-item-noshrink app-infos px-3 mt-2">
<SidebarStorageMeter
label={`${c('Storage').t`Your current storage:`} ${humanSize(UsedSpace)} / ${humanSize(
MaxSpace
)}`}
value={Math.ceil(spacePercentage)}
/>
<div className="flex flex-nowrap flex-justify-space-between py-2">
<span>
{canAddStorage ? (
<Tooltip title={c('Storage').t`Upgrade storage`}>
<SettingsLink
path={addUpsellPath('/upgrade', upsellRef)}
className="app-infos-storage text-no-decoration text-xs m-0"
>
{storageText}
</SettingsLink>
</Tooltip>
) : (
<span className="app-infos-storage text-xs m-0">{storageText}</span>
)}
{storageGift}
</span>
<span className="app-infos-compact">{version}</span>
</div>
{extraFooter}
</div>
) : (
<div className="border-top">
<div className="text-center py-2 px-3">{version}</div>
</div>
)}
</div>
{expanded ? <div className="sidebar-backdrop" onClick={onToggleExpand}></div> : undefined}
</>
);
};
export default Sidebar;
| 5,593
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/sidebar/SidebarBackButton.tsx
|
import { c } from 'ttag';
import { ButtonLike } from '@proton/atoms';
import { Icon } from '../icon';
import AppLink, { AppLinkProps } from '../link/AppLink';
const SidebarBackButton = ({ children, ...rest }: AppLinkProps) => {
return (
<ButtonLike
as={AppLink}
size="large"
color="weak"
shape="solid"
fullWidth
className="flex flex-align-items-center flex-justify-center flex-nowrap gap-2"
{...rest}
>
<Icon name="arrow-left" className="on-rtl-mirror flex-item-noshrink" />
<span className="text-ellipsis">{children ? children : c('Navigation').t`Back`}</span>
</ButtonLike>
);
};
export default SidebarBackButton;
| 5,594
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/sidebar/SidebarContactItem.tsx
|
import React from 'react';
import { c } from 'ttag';
import SidebarListItemContent from './SidebarListItemContent';
import SidebarListItemContentIcon from './SidebarListItemContentIcon';
interface Props {
onClick: () => void;
}
const SidebarContactItem = ({ onClick }: Props) => {
return (
<div className="navigation-item h-auto flex-item-noshrink px-3 mb-4 mt-2 md:hidden">
<button type="button" onClick={onClick} className="navigation-link">
<SidebarListItemContent left={<SidebarListItemContentIcon name="users" />}>
<span>{c('Header').t`Contacts`}</span>
</SidebarListItemContent>
</button>
</div>
);
};
export default SidebarContactItem;
| 5,595
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/sidebar/SidebarItemContent.tsx
|
import { ReactNode } from 'react';
import Icon, { IconName, IconSize } from '../icon/Icon';
interface Props {
icon?: IconName;
iconColor?: string;
iconSize?: IconSize;
text?: ReactNode;
title?: string;
aside?: ReactNode;
}
const SidebarItemContent = ({ icon, iconColor, iconSize = 16, title, text, aside }: Props) => {
return (
<span className="flex flex-nowrap w-full flex-align-items-center gap-2" title={title}>
{icon && (
<Icon
color={iconColor}
name={icon}
size={iconSize}
className="navigation-icon flex-item-noshrink flex-item-centered-vert"
/>
)}
<span className="flex-item-fluid text-ellipsis max-w-full">{text}</span>
{aside && <span className="flex flex-align-items-center">{aside}</span>}
</span>
);
};
export default SidebarItemContent;
| 5,596
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/sidebar/SidebarList.tsx
|
import { HTMLAttributes, ReactNode } from 'react';
import clsx from '@proton/utils/clsx';
interface Props extends HTMLAttributes<HTMLUListElement> {
listClassName?: string;
className?: string;
children?: ReactNode;
}
const SidebarList = ({ className, listClassName = 'navigation-list', children, ...rest }: Props) => {
return (
<ul className={clsx('unstyled my-0', listClassName, className)} {...rest}>
{children}
</ul>
);
};
export const SubSidebarList = ({ children, ...rest }: Props) => {
return (
<SidebarList listClassName="navigation-sublist" {...rest}>
{children}
</SidebarList>
);
};
export default SidebarList;
| 5,597
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/sidebar/SidebarListItem.tsx
|
import { LiHTMLAttributes } from 'react';
import clsx from '@proton/utils/clsx';
interface Props extends LiHTMLAttributes<HTMLLIElement> {
itemClassName?: string;
}
const SidebarListItem = ({
className = '',
itemClassName = 'navigation-item w-full px-3 mb-0.5',
children,
...rest
}: Props) => {
return (
<li className={clsx([itemClassName, className])} {...rest}>
{children}
</li>
);
};
export const SubSidebarListItem = (props: Props) => {
return <SidebarListItem itemClassName="navigation-subitem" {...props} />;
};
export default SidebarListItem;
| 5,598
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/sidebar/SidebarListItemButton.tsx
|
import { ButtonHTMLAttributes, ReactNode } from 'react';
import clsx from '@proton/utils/clsx';
export interface Props extends ButtonHTMLAttributes<HTMLButtonElement> {
children: ReactNode;
}
const SidebarListItemButton = ({ children, className, ...rest }: Props) => {
return (
<button className={clsx(['navigation-link w-full text-left', className])} type="button" {...rest}>
{children}
</button>
);
};
export default SidebarListItemButton;
| 5,599
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.