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/autocomplete/AutocompleteList.tsx
|
import { Children, MouseEvent, ReactElement, RefObject, cloneElement } from 'react';
import { c, msgid } from 'ttag';
import { Dropdown, DropdownSizeUnit } from '../dropdown';
import { Props as OptionProps } from '../option/Option';
import { verticalPopperPlacements } from '../popper/utils';
interface Props<V> {
id: string;
children: ReactElement<OptionProps<V>>[];
onClose: () => void;
isOpen: boolean;
highlightedIndex: number;
anchorRef: RefObject<HTMLElement>;
}
const AutocompleteList = <V,>({ id, children, onClose, isOpen, highlightedIndex, anchorRef }: Props<V>) => {
const items = Children.map(children, (child, index) => {
return cloneElement(child, {
active: highlightedIndex === index,
});
});
const handleListMouseDown = (e: MouseEvent<HTMLUListElement>) => {
/*
* prevent blurs on the input field triggered by a mousedown
* since otherwise you can't select an option from the list
* before blur is triggered
*/
e.preventDefault();
};
return (
<>
<span className="sr-only" id={`${id}-autocomplete-suggest-text`}>
{c('Hint')
.t`Use Up and Down keys to access and browse suggestions after input. Press Enter to confirm your choice, or Escape to close the suggestions box.`}
</span>
<div className="sr-only" aria-atomic="true" aria-live="assertive">
{c('Hint').ngettext(
msgid`Found ${items.length} suggestion, use keyboard to navigate.`,
`Found ${items.length} suggestions, use keyboard to navigate.`,
items.length
)}
</div>
<Dropdown
autoClose={false}
autoCloseOutside={false}
isOpen={items.length > 0 && isOpen}
anchorRef={anchorRef}
onClose={onClose}
offset={4}
noCaret
availablePlacements={verticalPopperPlacements}
size={{
width: DropdownSizeUnit.Anchor,
height: DropdownSizeUnit.Dynamic,
maxWidth: DropdownSizeUnit.Viewport,
}}
disableFocusTrap
disableDefaultArrowNavigation
>
<ul id={id} className="unstyled m-0 p-0" onMouseDown={handleListMouseDown}>
{items}
</ul>
</Dropdown>
</>
);
};
export default AutocompleteList;
| 5,200
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/autocomplete/SimpleAutocomplete.tsx
|
import Autocomplete, { Props as AutocompleteProps } from './Autocomplete';
interface Props extends Omit<AutocompleteProps<string>, 'getData' | 'onSelect'> {}
const id = <T,>(x: T) => x;
const SimpleAutocomplete = ({ value = '', ...rest }: Props) => {
return <Autocomplete {...rest} value={value} onSelect={rest.onChange} getData={id} />;
};
export default SimpleAutocomplete;
| 5,201
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/autocomplete/index.ts
|
export * from './useAutocomplete';
export { default as AutocompleteSuggestions } from './AutocompleteList';
export { default as Autocomplete } from './Autocomplete';
export { default as SimpleAutocomplete } from './SimpleAutocomplete';
export { default as AutocompleteList } from './AutocompleteList';
| 5,202
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/autocomplete/useAutocomplete.ts
|
import { KeyboardEvent, RefObject, useEffect, useMemo, useState } from 'react';
import { MatchChunk, escapeRegex, getMatches } from '@proton/shared/lib/helpers/regex';
import { normalize } from '@proton/shared/lib/helpers/string';
import { useHotkeys } from '../../hooks';
export interface DataWithMatches<T> {
option: T;
chunks: MatchChunk[];
text: string;
}
export const useAutocompleteFilter = <V>(
value: string,
options: V[],
getData: (v: V) => string,
limit = 20,
searchMinLength = -1
): DataWithMatches<V>[] => {
return useMemo(() => {
if (!Array.isArray(options)) {
return [];
}
const normalizedSearchText = normalize(value, true);
// Only begin searching after this length
if (searchMinLength > 0 && value.length < searchMinLength) {
return [];
}
const result = [];
for (let i = 0; i < options.length; i++) {
if (result.length === limit) {
break;
}
const option = options[i];
const text = getData(option);
const normalizedText = normalize(text, true);
const regex = new RegExp(escapeRegex(normalizedSearchText), 'gi');
const chunks = getMatches(regex, normalizedText);
if ((searchMinLength === 0 && normalizedSearchText.length === 0) || chunks.length > 0) {
result.push({
text,
option,
chunks,
});
}
}
return result;
}, [value, options, getData]);
};
interface UseAutocompleteProps<V> {
id: string;
onSelect: (value: V) => void;
options: DataWithMatches<V>[];
input: string;
inputRef: RefObject<HTMLInputElement>;
}
export const useAutocomplete = <T>({ id, options, onSelect, input, inputRef }: UseAutocompleteProps<T>) => {
const [highlightedIndex, setHighlightedIndex] = useState(0);
const [isOpen, setIsOpen] = useState(false);
const goToPreviousOption = () => {
setHighlightedIndex((currentHighlightedIndex) =>
currentHighlightedIndex === 0 ? currentHighlightedIndex : currentHighlightedIndex - 1
);
};
const goToNextOption = () => {
setHighlightedIndex((currentHighlightedIndex) =>
currentHighlightedIndex === options.length - 1 ? currentHighlightedIndex : currentHighlightedIndex + 1
);
};
const onOpen = () => {
setIsOpen(true);
};
const onClose = () => {
setIsOpen(false);
};
useEffect(() => {
/*
* The number of items displayed in the
* dropdown as well as which set of items is displayed is
* prone to change as the value of "input" changes.
*
* Selection preservation based on index can't be reliably dealt
* with, hence we reset index highlighting to the first element
* on any input change, given that it is not "0" already.
*/
if (highlightedIndex !== 0) {
setHighlightedIndex(0);
}
}, [input]);
useHotkeys(inputRef, [
[
'Escape',
(e) => {
if (isOpen) {
e.preventDefault();
onClose();
e.stopPropagation();
}
},
],
]);
const handleInputKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
switch (e.key) {
case 'ArrowUp': {
e.preventDefault();
goToPreviousOption();
break;
}
case 'ArrowDown': {
e.preventDefault();
goToNextOption();
break;
}
case 'Tab':
case 'Enter': {
const value = options[highlightedIndex];
if (value && isOpen) {
e.preventDefault();
onSelect(value.option);
onClose();
return true;
}
break;
}
default:
onOpen();
}
};
const getOptionID = (index: number) => `${id}-${index}`;
return {
onClose,
getOptionID,
suggestionProps: {
id,
isOpen: options.length > 0 && isOpen,
onClose,
highlightedIndex,
},
inputProps: {
id,
autoComplete: 'off',
'aria-owns': id,
'aria-activedescendant': getOptionID(highlightedIndex),
'aria-autocomplete': 'list',
'aria-describedby': `${id}-autocomplete-suggest-text`,
onFocus: onOpen,
onBlur: onClose,
onKeyDown: handleInputKeyDown,
},
} as const;
};
| 5,203
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/badge/Badge.tsx
|
import { ReactNode } from 'react';
import { Href } from '@proton/atoms';
import clsx from '@proton/utils/clsx';
import Tooltip from '../tooltip/Tooltip';
const CLASSNAMES = {
default: 'badge-label-norm',
origin: 'badge-label-strong',
light: 'badge-label-weak',
primary: 'badge-label-primary',
error: 'badge-label-danger',
warning: 'badge-label-warning',
success: 'badge-label-success',
info: 'badge-label-info',
} as const;
export type BadgeType = keyof typeof CLASSNAMES;
export interface Props {
children: ReactNode;
className?: string;
tooltip?: string;
url?: string;
type?: BadgeType;
'data-testid'?: string;
}
const Badge = ({ children, type = 'default', url, tooltip, className = 'mr-2', 'data-testid': dataTestId }: Props) => {
const badge = (
<span className={clsx(CLASSNAMES[type], className)} data-testid={dataTestId}>
{children}
</span>
);
const wrappedBadge = url ? (
<Href href={url} className="text-no-decoration">
{badge}
</Href>
) : (
badge
);
if (tooltip) {
return <Tooltip title={tooltip}>{wrappedBadge}</Tooltip>;
}
return wrappedBadge;
};
export default Badge;
| 5,204
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/badge/BetaBadge.tsx
|
import { c } from 'ttag';
import Badge, { Props as BadgeProps } from './Badge';
const BetaBadge = (props: Omit<BadgeProps, 'type' | 'children' | 'tooltip'>) => {
const tooltip = c('Tooltip').t`This feature is only available on Beta`;
return (
<Badge type="origin" tooltip={tooltip} {...props}>{c('Label to inform a feature is only available on Beta')
.t`Beta`}</Badge>
);
};
export default BetaBadge;
| 5,205
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/badge/index.ts
|
export { default as Badge } from './Badge';
export { default as BetaBadge } from './BetaBadge';
| 5,206
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/banner/Banner.tsx
|
import React from 'react';
import clsx from '@proton/utils/clsx';
import { Icon, IconName } from '../icon';
export enum BannerBackgroundColor {
NORM = 'norm',
WEAK = 'weak',
STRONG = 'strong',
INFO = 'info',
WARNING = 'warning',
DANGER = 'danger',
SUCCESS = 'success',
}
export enum IconColor {
WARNING = 'warning',
DANGER = 'danger',
}
export interface BannerProps {
backgroundColor?: BannerBackgroundColor;
iconColor?: IconColor;
icon?: IconName;
action?: React.ReactNode;
children: React.ReactNode;
}
const Banner = ({ backgroundColor = BannerBackgroundColor.NORM, icon, iconColor, action, children }: BannerProps) => {
const getIcon = () => {
if (!icon) {
return null;
}
return <Icon name={icon} className={clsx(['mr-3 ml-0.5 flex-item-noshrink', `color-${iconColor}`])} />;
};
const borderColor =
backgroundColor === BannerBackgroundColor.INFO ||
backgroundColor === BannerBackgroundColor.WARNING ||
backgroundColor === BannerBackgroundColor.DANGER ||
backgroundColor === BannerBackgroundColor.SUCCESS
? `border-${backgroundColor}`
: null;
return (
<div
className={`bg-${backgroundColor} border ${borderColor} rounded px-2 py-1 mb-3 flex flex-align-items-center flex-nowrap`}
>
{getIcon()}
<span className={clsx([!!action && 'mr-4'])}>{children}</span>
{action}
</div>
);
};
export default Banner;
| 5,207
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/banner/index.ts
|
export { default as Banner } from './Banner';
| 5,208
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/breadcrumb/Breadcrumb.test.js
|
import { fireEvent, render } from '@testing-library/react';
import Breadcrumb from './Breadcrumb';
describe('Breadcrumb component', () => {
const steps = ['todo', 'doing', 'done'];
const currentStep = 1;
const getButtons = (container) => [].slice.call(container.querySelectorAll('button'));
it('should render all steps', () => {
const { container } = render(<Breadcrumb list={steps} current={currentStep} />);
const buttons = getButtons(container);
expect(buttons.length).toBe(steps.length);
});
it('should mark the second step as active', () => {
const { container } = render(<Breadcrumb list={steps} current={currentStep} />);
const buttons = getButtons(container);
expect(buttons[currentStep].getAttribute('aria-current')).toBe('step');
expect(buttons[currentStep]).toHaveAttribute('disabled');
});
it('should select the first step', () => {
const mockOnClick = jest.fn();
const { container } = render(<Breadcrumb list={steps} current={currentStep} onClick={mockOnClick} />);
const buttons = getButtons(container);
expect(mockOnClick).toHaveBeenCalledTimes(0);
fireEvent.click(buttons[0]);
expect(mockOnClick).toHaveBeenCalledTimes(1);
});
});
| 5,209
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/breadcrumb/Breadcrumb.tsx
|
import { Fragment, ReactNode } from 'react';
import clsx from '@proton/utils/clsx';
import Icon from '../icon/Icon';
interface Props {
onClick: (index: number) => void;
current: number;
list: ReactNode[];
getIsDisabled?: (index: number) => boolean;
className?: string;
}
const Breadcrumb = ({ list, current = 0, onClick, className, getIsDisabled }: Props) => {
const handleClick = (index: number) => () => {
if (onClick) {
onClick(index);
}
};
return (
<ul className={clsx(['breadcrumb-container unstyled inline-flex px-2', className])}>
{list.map((item, index) => {
const key = index.toString();
const isLast = index === list.length - 1;
const isDisabled = getIsDisabled?.(index) ?? false;
return (
<Fragment key={key}>
<li className="breadcrumb-item" key={key}>
<button
type="button"
disabled={index === current || isDisabled}
aria-current={current === index ? 'step' : false}
onClick={handleClick(index)}
key={key}
className="breadcrumb-button"
>
{item}
</button>
</li>
{!isLast && (
<li aria-hidden="true" className="inline-flex color-disabled">
<Icon size={14} className="flex-item-noshrink m-auto" name="chevron-right" />
</li>
)}
</Fragment>
);
})}
</ul>
);
};
export default Breadcrumb;
| 5,210
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/breadcrumb/index.ts
|
export { default as Breadcrumb } from './Breadcrumb';
| 5,211
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/button/ButtonGroup.tsx
|
import {
Children,
ComponentPropsWithoutRef,
Fragment,
ReactElement,
ReactNode,
cloneElement,
forwardRef,
isValidElement,
} from 'react';
import { Vr } from '@proton/atoms';
import { ThemeColor } from '@proton/colors';
import clsx from '@proton/utils/clsx';
export type Color = `${ThemeColor.Norm | ThemeColor.Weak}`;
export type Shape = 'solid' | 'outline' | 'ghost';
export type Size = 'small' | 'medium' | 'large';
export interface Props extends ComponentPropsWithoutRef<'div'> {
children: ReactNode;
color?: Color;
shape?: Shape;
size?: Size;
separators?: boolean;
removeBackgroundColorOnGroup?: Boolean;
}
const ButtonGroup = forwardRef<HTMLDivElement, Props>(
(
{
children,
separators = true,
color = 'weak',
shape = 'outline',
size = 'medium',
removeBackgroundColorOnGroup = false,
className = '',
...rest
},
ref
) => {
const childrenWithSeparators = Children.toArray(children)
.filter((x): x is ReactElement => x !== null && isValidElement(x))
.map((child, index, array) => {
const clonedChild = cloneElement(child, { group: true, size, color, shape });
if (index === array.length - 1) {
return clonedChild;
}
return (
// eslint-disable-next-line react/no-array-index-key
<Fragment key={clonedChild.key || index}>
{clonedChild}
{separators && <Vr aria-hidden="true" />}
</Fragment>
);
});
return (
<div
className={clsx(
'button-group',
`button-group-${shape}-${color}`,
`button-group-${size}`,
removeBackgroundColorOnGroup && 'button-group--no-bg-color',
className
)}
ref={ref}
{...rest}
>
{childrenWithSeparators}
</div>
);
}
);
ButtonGroup.displayName = 'ButtonGroup';
export default ButtonGroup;
| 5,212
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/button/Copy.tsx
|
import { MouseEvent, Ref, forwardRef } from 'react';
import { c } from 'ttag';
import { Button, ButtonLikeShape, ButtonProps } from '@proton/atoms';
import { textToClipboard } from '@proton/shared/lib/helpers/browser';
import { Icon } from '../icon';
import { Tooltip } from '../tooltip';
interface Props extends ButtonProps {
value: string;
className?: string;
onCopy?: () => void;
tooltipText?: string;
shape?: ButtonLikeShape;
}
const Copy = (
{ children, value, onCopy, tooltipText, shape = 'outline', ...rest }: Props,
ref: Ref<HTMLButtonElement>
) => {
const handleClick = (e: MouseEvent<HTMLButtonElement>) => {
e.stopPropagation();
textToClipboard(value, e.currentTarget);
onCopy?.();
};
return (
<Tooltip title={tooltipText || c('Label').t`Copy`}>
<Button icon color="weak" shape={shape} ref={ref} {...rest} onClick={handleClick}>
{children || <Icon name="squares" alt={c('Label').t`Copy`} />}
</Button>
</Tooltip>
);
};
export default forwardRef<HTMLButtonElement, Props>(Copy);
| 5,213
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/button/ErrorButton.tsx
|
import { Ref, forwardRef } from 'react';
import { Button, ButtonProps } from '@proton/atoms';
export type ErrorButtonProps = Omit<ButtonProps, 'color'>;
const ErrorButton = (props: ErrorButtonProps, ref: Ref<HTMLButtonElement>) => {
return <Button color="danger" ref={ref} {...props} />;
};
export default forwardRef<HTMLButtonElement, ErrorButtonProps>(ErrorButton);
| 5,214
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/button/FileButton.scss
|
@import '~@proton/styles/scss/lib';
.file-button {
position: relative;
overflow: hidden;
display: inline-block;
// hack to save space for the hover halo on the button
padding: 5px;
margin: -5px;
input[type='file'] {
position: absolute;
opacity: 0;
visibility: hidden;
z-index: -1;
}
input[type='file']:focus + .button-solid-norm {
--button-hover-background-color: var(--interaction-norm-hover);
--button-hover-text-color: var(--interaction-norm-contrast);
}
input[type='file']:focus + .button-solid-weak {
--button-hover-background-color: var(--interaction-weak-hover);
--button-hover-text-color: var(--interaction-weak-contrast);
}
input[type='file']:active + .button-solid-norm {
--button-active-background-color: var(--interaction-norm-active);
--button-active-text-color: var(--interaction-norm-contrast);
}
input[type='file']:active + .button-solid-weak {
--button-active-background-color: var(--interaction-weak-active);
--button-active-text-color: var(--interaction-weak-contrast);
}
}
| 5,215
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/button/FileButton.tsx
|
import {
ChangeEvent,
DetailedHTMLProps,
InputHTMLAttributes,
KeyboardEvent,
ReactNode,
Ref,
forwardRef,
useRef,
} from 'react';
import { ButtonLike } from '@proton/atoms';
import { useCombinedRefs } from '@proton/hooks';
import clsx from '@proton/utils/clsx';
import './FileButton.scss';
interface Props extends DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement> {
className?: string;
disabled?: boolean;
onAddFiles: (files: File[]) => void;
children?: ReactNode;
}
const FileButton = ({ onAddFiles, disabled, className, children, ...rest }: Props, ref: Ref<HTMLInputElement>) => {
const inputRef = useRef<HTMLInputElement>(null);
const combinedRef = useCombinedRefs(inputRef, ref);
const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
const input = event.target;
if (input.files) {
onAddFiles([...input.files]);
input.value = '';
}
};
const handleKey = (event: KeyboardEvent) => {
if (event.key === 'Enter' || event.key === ' ') {
inputRef.current?.click();
}
};
return (
<div className="file-button flex">
<ButtonLike
icon
as="label"
role="button"
tabIndex={0}
className={clsx([disabled && 'is-disabled', className])}
onKeyDown={handleKey}
>
{children}
<input ref={combinedRef} type="file" multiple onChange={handleChange} {...rest} />
</ButtonLike>
</div>
);
};
export default forwardRef<HTMLInputElement, Props>(FileButton);
| 5,216
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/button/FloatingButton.tsx
|
import { Ref, forwardRef } from 'react';
import { Button, ButtonProps } from '@proton/atoms';
import clsx from '@proton/utils/clsx';
interface Props extends ButtonProps {
title?: string;
className?: string;
}
const FloatingButton = ({ children, title, className, ...rest }: Props, ref: Ref<HTMLButtonElement>) => {
return (
<Button color="norm" className={clsx(['fab flex', className])} ref={ref} {...rest}>
{children}
</Button>
);
};
export default forwardRef<HTMLButtonElement, Props>(FloatingButton);
| 5,217
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/button/InlineLinkButton.tsx
|
import { ComponentPropsWithRef, Ref, forwardRef } from 'react';
import clsx from '@proton/utils/clsx';
type InlineLinkButtonProps = ComponentPropsWithRef<'button'>;
const InlineLinkButton = forwardRef<HTMLButtonElement, InlineLinkButtonProps>(
({ children, className = '', ...rest }: InlineLinkButtonProps, ref: Ref<HTMLButtonElement>) => {
return (
<button
type="button"
className={clsx(['link link-focus align-baseline text-left', className])}
ref={ref}
{...rest}
>
{children}
</button>
);
}
);
export default InlineLinkButton;
| 5,218
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/button/PrimaryButton.tsx
|
import { Ref, forwardRef } from 'react';
import { Button, ButtonProps } from '@proton/atoms';
export type PrimaryButtonProps = Omit<ButtonProps, 'color'>;
const PrimaryButton = (props: PrimaryButtonProps, ref: Ref<HTMLButtonElement>) => {
return <Button color="norm" ref={ref} {...props} />;
};
export default forwardRef<HTMLButtonElement, PrimaryButtonProps>(PrimaryButton);
| 5,219
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/button/TwitterButton.scss
|
.twitter-button {
--button-default-background-color: rgb(29 155 240);
--button-hover-background-color: rgb(26 140 216);
--button-active-background-color: rgb(23 124 192);
--button-default-text-color: white;
--button-hover-text-color: white;
--button-active-text-color: white;
}
| 5,220
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/button/TwitterButton.tsx
|
import { forwardRef } from 'react';
import { ButtonLike, Href, HrefProps } from '@proton/atoms';
import './TwitterButton.scss';
interface Props extends Pick<HrefProps, 'href' | 'target'> {
children: React.ReactNode;
}
const TwitterButton = forwardRef<HTMLAnchorElement, Props>((props, ref) => (
<ButtonLike ref={ref} as={Href} className="twitter-button" shape="solid" {...props} />
));
TwitterButton.displayName = 'TwitterButton';
export default TwitterButton;
| 5,221
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/button/UnderlineButton.tsx
|
import { Ref, forwardRef } from 'react';
import { Button, ButtonProps } from '@proton/atoms';
export type UnderlineButtonProps = Omit<ButtonProps, 'shape'>;
const UnderlineButton = (props: UnderlineButtonProps, ref: Ref<HTMLButtonElement>) => {
return <Button shape="underline" color="norm" ref={ref} {...props} />;
};
export default forwardRef<HTMLButtonElement, UnderlineButtonProps>(UnderlineButton);
| 5,222
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/button/index.ts
|
export { default as Copy } from './Copy';
export { default as ErrorButton } from './ErrorButton';
export { default as FloatingButton } from './FloatingButton';
export { default as InlineLinkButton } from './InlineLinkButton';
export { default as PrimaryButton } from './PrimaryButton';
export { default as ButtonGroup } from './ButtonGroup';
export { default as UnderlineButton } from './UnderlineButton';
export { default as FileButton } from './FileButton';
export { default as TwitterButton } from './TwitterButton';
| 5,223
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/button
|
petrpan-code/ProtonMail/WebClients/packages/components/components/button/PromotionButton/PromotionButton.scss
|
@use 'sass:math';
@import '~@proton/styles/scss/lib';
.button-promotion {
--upgrade-color-stop-1: #fd4baf;
--upgrade-color-stop-2: #22d8ff;
position: relative;
border: 0;
block-size: rem(36);
> span {
z-index: 2;
}
&.button-small {
block-size: rem(28);
}
&.button-large {
block-size: rem(44);
}
&::before,
&::after {
content: '';
position: absolute;
inset: 1px;
z-index: 1;
background-color: var(--background-norm);
border-radius: calc(var(--border-radius-md) - 1px);
}
&::after {
opacity: 0;
z-index: 0;
}
&:hover,
&:focus-visible {
&::before {
background-color: var(--interaction-weak-minor-2);
}
&::after {
opacity: 1;
}
}
&:not([class*='ghost']),
&.button-for-icon:hover,
&.button-for-icon:focus-visible {
background: linear-gradient(to right, var(--upgrade-color-stop-1) 0%, var(--upgrade-color-stop-2) 100%);
color: var(--text-norm);
}
&--upgrade {
block-size: rem(20);
padding-inline: rem(6);
padding-block: rem(3);
border-radius: var(--border-radius-sm);
&::before {
border-radius: calc(var(--border-radius-sm) - 1px);
}
}
&--icon-gradient {
linearGradient {
--color-stop-1: var(--upgrade-color-stop-1);
--color-stop-2: var(--upgrade-color-stop-2);
}
}
}
| 5,224
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/button
|
petrpan-code/ProtonMail/WebClients/packages/components/components/button/PromotionButton/PromotionButton.tsx
|
import { ElementType, ForwardedRef, ReactElement, forwardRef } from 'react';
import { PolymorphicPropsWithRef } from 'react-polymorphic-types';
import ButtonLike, { ButtonLikeProps } from '@proton/atoms/Button/ButtonLike';
import { CircleLoader } from '@proton/atoms/CircleLoader';
import { Icon, IconName, IconSize } from '@proton/components/components';
import { useActiveBreakpoint } from '@proton/components/hooks';
import useUid from '@proton/components/hooks/useUid';
import clsx from '@proton/utils/clsx';
import './PromotionButton.scss';
type ButtonButtonLikeProps = ButtonLikeProps<'button'>;
interface OwnProps extends Omit<ButtonLikeProps<'button'>, 'as' | 'ref'> {
iconName?: IconName;
icon?: boolean;
iconGradient?: boolean;
upsell?: boolean;
shape?: ButtonButtonLikeProps['shape'];
className?: string;
loading?: boolean;
responsive?: boolean;
}
export type PromotionButtonProps<E extends ElementType> = PolymorphicPropsWithRef<OwnProps, E>;
const defaultElement = ButtonLike;
const PromotionButtonBase = <E extends ElementType = typeof defaultElement>(
{
children,
iconName,
icon,
iconGradient = true,
shape = 'outline',
upsell,
as,
className,
loading,
responsive = true,
...rest
}: PromotionButtonProps<E>,
ref: ForwardedRef<Element>
) => {
let iconSize: IconSize | undefined;
const { isDesktop } = useActiveBreakpoint();
switch (true) {
case icon && upsell:
iconSize = 16;
break;
default:
iconSize = 20;
break;
}
if (responsive && !isDesktop) {
shape = 'ghost';
icon = true;
}
const Element: ElementType = as || defaultElement;
const uid = useUid('linear-gradient');
return (
<ButtonLike
as={Element}
ref={ref}
type="button"
icon={icon}
color="weak"
shape={shape}
className={clsx(
'button-promotion',
iconGradient && 'button-promotion--icon-gradient',
upsell && 'button-promotion--upgrade',
className
)}
{...rest}
>
<span
className={clsx(
'relative flex flex-nowrap flex-align-items-center gap-2',
responsive && isDesktop ? 'w-full' : undefined
)}
>
{iconName && (
<Icon
name={iconName}
className="flex-item-noshrink"
size={iconSize}
style={{ fill: `url(#${uid}) var(--text-norm)` }}
/>
)}
<span className={clsx(icon ? 'sr-only' : 'block flex-item-noshrink')}>{children}</span>
{loading && <CircleLoader />}
</span>
{iconName && iconGradient ? (
<svg aria-hidden="true" focusable="false" className="sr-only">
<linearGradient id={uid}>
<stop offset="0%" stopColor="var(--color-stop-1)" />
<stop offset="100%" stopColor="var(--color-stop-2)" />
</linearGradient>
</svg>
) : undefined}
</ButtonLike>
);
};
const PromotionButton: <E extends ElementType = typeof defaultElement>(
props: PromotionButtonProps<E>
) => ReactElement | null = forwardRef(PromotionButtonBase);
export default PromotionButton;
| 5,225
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/button
|
petrpan-code/ProtonMail/WebClients/packages/components/components/button/PromotionButton/index.ts
|
export { default as PromotionButton } from './PromotionButton';
| 5,226
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/calendarEventDateHeader/CalendarEventDateHeader.test.tsx
|
import { render, screen } from '@testing-library/react';
import { enUS, pt } from 'date-fns/locale';
import { CalendarEventDateHeader } from './index';
describe('CalendarEventDateHeader', () => {
describe('should format properly all-day events', () => {
it('for single-day events', () => {
render(
<CalendarEventDateHeader
startDate={new Date(Date.UTC(2021, 10, 2))}
endDate={new Date(Date.UTC(2021, 10, 3))}
isAllDay
hasFakeUtcDates
formatOptions={{ locale: enUS }}
/>
);
expect(screen.getByText(/Nov/)).toHaveTextContent('Tue, Nov 2, 2021');
});
it('for multi-day events', () => {
render(
<CalendarEventDateHeader
startDate={new Date(2021, 10, 2)}
endDate={new Date(2021, 10, 3)}
isAllDay
hasModifiedAllDayEndDate
formatOptions={{ locale: enUS }}
/>
);
expect(screen.getByText(/Nov/)).toHaveTextContent('Tue, Nov 2, 2021–Wed, Nov 3, 2021');
});
});
describe('should format properly part-day events', () => {
it('for single-day events', () => {
render(
<CalendarEventDateHeader
startDate={new Date(2021, 10, 2, 12, 0)}
endDate={new Date(2021, 10, 2, 16, 30)}
isAllDay={false}
formatOptions={{ locale: enUS }}
/>
);
expect(screen.getByText(/Nov/)).toHaveTextContent('Tue, Nov 2, 2021, 12:00 PM–4:30 PM');
});
it('for multi-day events', () => {
render(
<CalendarEventDateHeader
startDate={new Date(Date.UTC(2021, 10, 2, 12, 0))}
endDate={new Date(Date.UTC(2021, 10, 3, 0, 30))}
isAllDay={false}
hasFakeUtcDates
formatOptions={{ locale: enUS }}
/>
);
expect(screen.getByText(/Nov/)).toHaveTextContent('Tue, Nov 2, 2021 12:00 PM–Wed, Nov 3, 2021 12:30 AM');
});
});
describe('should format in other locales', () => {
it('for all-day events', () => {
render(
<CalendarEventDateHeader
startDate={new Date(Date.UTC(2021, 10, 2))}
endDate={new Date(Date.UTC(2021, 10, 2))}
isAllDay
hasFakeUtcDates
hasModifiedAllDayEndDate
formatOptions={{ locale: pt }}
/>
);
expect(screen.getByText(/nov/)).toHaveTextContent('ter, 2 de nov de 2021');
});
it('for part-day events', () => {
render(
<CalendarEventDateHeader
startDate={new Date(2021, 10, 2, 12, 0)}
endDate={new Date(2021, 10, 2, 16, 30)}
isAllDay={false}
formatOptions={{ locale: pt }}
/>
);
expect(screen.getByText(/nov/)).toHaveTextContent('ter, 2 de nov de 2021, 12:00–16:30');
});
});
});
| 5,227
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/calendarEventDateHeader/CalendarEventDateHeader.tsx
|
import { DetailedHTMLProps, HTMLAttributes } from 'react';
import { format } from 'date-fns';
import { addDays } from '@proton/shared/lib/date-fns-utc';
import formatUTC, { Options } from '@proton/shared/lib/date-fns-utc/format';
import { dateLocale } from '@proton/shared/lib/i18n';
import { EnDash } from '../text';
interface Props extends DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement> {
startDate: Date;
endDate: Date;
isAllDay: boolean;
formatDate?: (date: Date) => string;
formatTime?: (date: Date) => string;
hasFakeUtcDates?: boolean;
hasModifiedAllDayEndDate?: boolean;
formatOptions?: Options;
}
const CalendarEventDateHeader = ({
startDate,
endDate,
isAllDay,
formatDate: maybeFormatDate,
formatTime: maybeFormatTime,
hasFakeUtcDates = false,
hasModifiedAllDayEndDate = false,
formatOptions: maybeFormatOptions,
...rest
}: Props) => {
const formatOptions = maybeFormatOptions || { locale: dateLocale };
const formatDate = (date: Date) => {
if (maybeFormatDate) {
return maybeFormatDate(date);
}
if (hasFakeUtcDates) {
return formatUTC(date, 'ccc, PP', formatOptions);
}
return format(date, 'ccc, PP', formatOptions);
};
const formatTime = (date: Date) => {
if (maybeFormatTime) {
return maybeFormatTime(date);
}
if (hasFakeUtcDates) {
return formatUTC(date, 'p', formatOptions);
}
return format(date, 'p', formatOptions);
};
const dateStart = formatDate(startDate);
const dateEnd = formatDate(isAllDay && !hasModifiedAllDayEndDate ? addDays(endDate, -1) : endDate);
if (isAllDay) {
if (dateStart === dateEnd) {
return <div {...rest}>{dateStart}</div>;
}
return (
<div {...rest}>
{dateStart}
<EnDash />
{dateEnd}
</div>
);
}
const [timeStart, timeEnd] = [startDate, endDate].map((date) => formatTime(date));
if (dateStart === dateEnd) {
return (
<div {...rest}>
{dateStart}
{', '}
<span className="inline-block">
{timeStart}
<EnDash />
{timeEnd}
</span>
</div>
);
}
return (
<div {...rest}>
{dateStart} {timeStart}
<EnDash />
{dateEnd} {timeEnd}
</div>
);
};
export default CalendarEventDateHeader;
| 5,228
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/calendarEventDateHeader/index.ts
|
export { default as CalendarEventDateHeader } from './CalendarEventDateHeader';
| 5,229
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/calendarSelect/CalendarSelect.scss
|
@import '~@proton/styles/scss/lib';
.calendar-select-color {
inline-size: var(--calendar-select-color-size, #{rem(12)});
block-size: var(--calendar-select-color-size, #{rem(12)});
box-sizing: content-box;
border-radius: 50%;
display: inline-flex;
@include media('screen') {
outline: rem(2) solid var(--background-norm);
}
&--large {
--calendar-select-color-size: #{rem(20)};
}
&--bordered {
--calendar-select-color-size: #{rem(10)};
border: 1px solid;
}
}
| 5,230
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/calendarSelect/CalendarSelect.tsx
|
import { ComponentPropsWithoutRef } from 'react';
import { CalendarSelectOption } from '@proton/shared/lib/interfaces/calendar';
import { Option } from '../option';
import { SelectTwo } from '../selectTwo';
import { SelectChangeEvent } from '../selectTwo/select';
import CalendarSelectIcon from './CalendarSelectIcon';
interface Props
extends Omit<ComponentPropsWithoutRef<'button'>, 'value' | 'onClick' | 'onChange' | 'onKeyDown' | 'aria-label'> {
calendarID: string;
options: CalendarSelectOption[];
onChange: (e: SelectChangeEvent<string>) => void;
displayColor?: boolean;
freeze?: boolean;
}
const CalendarSelect = ({ calendarID, options, onChange, displayColor = true, freeze = true, ...rest }: Props) => {
if (freeze && options.length === 1) {
const { name, color } = options[0];
return (
<div className="field border-none flex flex-nowrap flex-align-items-center pl-0">
{displayColor && <CalendarSelectIcon color={color} className="flex-item-noshrink mr-3" />}
<span className="text-ellipsis">{name}</span>
</div>
);
}
return (
<SelectTwo value={calendarID} onChange={onChange} {...rest}>
{options.map(({ id, name, color }) => (
<Option key={id} value={id} title={name}>
<div className="flex flex-nowrap flex-align-items-center">
{displayColor && <CalendarSelectIcon color={color} className="flex-item-noshrink mr-3" />}
<div className="text-ellipsis">{name}</div>
</div>
</Option>
))}
</SelectTwo>
);
};
export default CalendarSelect;
| 5,231
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/calendarSelect/CalendarSelectIcon.tsx
|
import clsx from '@proton/utils/clsx';
import './CalendarSelect.scss';
interface Props {
color: string;
className?: string;
large?: boolean;
border?: boolean;
}
const CalendarSelectIcon = ({ color, className, large, border }: Props) => {
return (
<div
className={clsx([
'calendar-select-color',
large && 'calendar-select-color--large',
border && 'calendar-select-color--bordered',
className,
])}
style={{ [border ? 'borderColor' : 'backgroundColor']: color }}
/>
);
};
export default CalendarSelectIcon;
| 5,232
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/checklist/CheckList.tsx
|
import type { CSSProperties } from 'react';
import { c } from 'ttag';
import { BRAND_NAME, MAIL_APP_NAME } from '@proton/shared/lib/constants';
import accountLoginSmall from '@proton/styles/assets/img/illustrations/checklist-account-login-small.svg';
import accountLogin from '@proton/styles/assets/img/illustrations/checklist-account-login.svg';
import appStoreSmall from '@proton/styles/assets/img/illustrations/checklist-app-store-small.svg';
import appStore from '@proton/styles/assets/img/illustrations/checklist-app-store.svg';
import gmailForwardSmall from '@proton/styles/assets/img/illustrations/checklist-gmail-forward-small.svg';
import gmailForward from '@proton/styles/assets/img/illustrations/checklist-gmail-forward.svg';
import protectInboxSmall from '@proton/styles/assets/img/illustrations/checklist-protect-inbox-small.svg';
import protectInbox from '@proton/styles/assets/img/illustrations/checklist-protect-inbox.svg';
import { Tooltip } from '../tooltip';
import CheckListItem from './CheckListItem';
interface CheckListItemProps {
smallVariant?: boolean;
done?: boolean;
disabled?: boolean;
style?: CSSProperties;
onClick?: () => void;
'data-testid'?: string;
}
export const CheckListProtectInbox = ({
smallVariant = false,
onClick,
done = false,
style,
disabled = false,
'data-testid': dataTestId,
}: CheckListItemProps) => {
// translator: This text is in bold inside the sentence "Discover how our privacy features protect you"
const strongText = <strong>{c('Get started checklist instructions').t`privacy features`}</strong>;
// translator: The whole sentence is "Discover how our privacy features protect you" with privacy feature in bold
const text = c('Get started checklist instructions').jt`Discover how our ${strongText} protect you`;
const smallText = c('Get started checklist instructions').t`Discover privacy features`;
return (
<CheckListItem
largeIcon={protectInbox}
smallIcon={protectInboxSmall}
text={smallVariant ? smallText : text}
onClick={onClick}
smallVariant={smallVariant}
style={style}
done={done}
disabled={disabled}
data-testid={dataTestId}
/>
);
};
export const CheckListGmailForward = ({
smallVariant = false,
onClick,
done = false,
style,
disabled = false,
'data-testid': dataTestId,
isInMaintenance,
}: CheckListItemProps & { isInMaintenance: boolean }) => {
// translator: This text is in bold inside the sentence "Set up auto-forwarding from Gmail"
const strongText = <strong>{c('Get started checklist instructions').t`auto-forwarding`}</strong>;
// translator: The whole sentence is "Set up auto-forwarding from Gmail" with "auto-forwarding" in bold
const text = c('Get started checklist instructions').jt`Set up ${strongText} from Gmail`;
const smallText = c('Get started checklist instructions').t`Auto-forward Gmail`;
const item = (
<CheckListItem
largeIcon={gmailForward}
smallIcon={gmailForwardSmall}
text={smallVariant ? smallText : text}
onClick={onClick}
smallVariant={smallVariant}
style={style}
done={done}
disabled={disabled || isInMaintenance}
data-testid={dataTestId}
/>
);
if (isInMaintenance) {
return (
<Tooltip title={c('Get started checklist instructions').t`This feature is currently unavailable`}>
<div>{item}</div>
</Tooltip>
);
}
return item;
};
export const CheckListAccountLogin = ({
smallVariant = false,
onClick,
done = false,
style,
disabled = false,
'data-testid': dataTestId,
}: CheckListItemProps) => {
// translator: This text is in bold inside the sentence "Change account logins to your Proton address"
const strongText = <strong>{c('Get started checklist instructions').t`account logins`}</strong>;
// translator: The whole sentence is "Change account logins to your Proton address" with "account logins" in bold
const text = c('Get started checklist instructions').jt`Change ${strongText} to your ${BRAND_NAME} address`;
const smallText = c('Get started checklist instructions').t`Update your logins`;
return (
<CheckListItem
largeIcon={accountLogin}
smallIcon={accountLoginSmall}
text={smallVariant ? smallText : text}
onClick={onClick}
smallVariant={smallVariant}
style={style}
done={done}
disabled={disabled}
data-testid={dataTestId}
/>
);
};
export const CheckListMobileStores = ({
smallVariant = false,
onClick,
done = false,
style,
disabled = false,
'data-testid': dataTestId,
}: CheckListItemProps) => {
const strongText = <strong>{c('Get started checklist instructions').t`${MAIL_APP_NAME} app`}</strong>;
// translator: The whole sentence is "Get the ProtonMail app on Google Play or App Store", where "Proton Mail app" is in bold
const text = c('Get started checklist instructions').jt`Get the ${strongText} on Android or iOS`;
const smallText = c('Get started checklist instructions').t`Get the App`;
return (
<CheckListItem
largeIcon={appStore}
smallIcon={appStoreSmall}
text={smallVariant ? smallText : text}
onClick={onClick}
smallVariant={smallVariant}
style={style}
done={done}
disabled={disabled}
data-testid={dataTestId}
/>
);
};
| 5,233
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/checklist/CheckListItem.scss
|
.checkList-item {
min-block-size: 3rem;
background: linear-gradient(
81.4deg,
var(--optional-promotion-background-start),
var(--optional-promotion-background-end)
);
}
| 5,234
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/checklist/CheckListItem.test.tsx
|
import { fireEvent } from '@testing-library/react';
import { render } from '@proton/components/containers/contacts/tests/render';
import CheckListItem from './CheckListItem';
const checklistItemProps = {
largeIcon: 'largeIcon',
smallIcon: 'smallIcon',
text: 'text',
onClick: jest.fn(),
smallVariant: false,
done: false,
};
describe('ChecklistItem', () => {
it('Should trigger onclick when clicked', async () => {
const onClick = jest.fn();
const { getByRole } = render(<CheckListItem {...checklistItemProps} onClick={onClick} />, false);
const item = getByRole('button');
fireEvent.click(item);
expect(onClick).toHaveBeenCalled();
});
it('Should not trigger onclick when disabled', async () => {
const onClick = jest.fn();
const { getByRole } = render(<CheckListItem {...checklistItemProps} onClick={onClick} disabled />, false);
const item = getByRole('button');
fireEvent.click(item);
expect(onClick).not.toHaveBeenCalled();
});
it('Should trigger onclick when done', async () => {
const onClick = jest.fn();
const { getByRole } = render(<CheckListItem {...checklistItemProps} onClick={onClick} done />, false);
const item = getByRole('button');
fireEvent.click(item);
expect(onClick).toHaveBeenCalled();
});
it('Should use the largeIcon when smallVariant is false', async () => {
const { getByTestId } = render(<CheckListItem {...checklistItemProps} />, false);
const icon = getByTestId('checklist-item-icon-large');
expect(icon).toBeTruthy();
});
it('Should use the smallIcon when smallVariant is true', async () => {
const { getByTestId } = render(<CheckListItem {...checklistItemProps} smallVariant />, false);
const icon = getByTestId('checklist-item-icon-small');
expect(icon).toBeTruthy();
});
});
| 5,235
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/checklist/CheckListItem.tsx
|
import { CSSProperties } from 'react';
import Icon, { IconSize } from '@proton/components/components/icon/Icon';
import clsx from '@proton/utils/clsx';
import './CheckListItem.scss';
interface Props {
largeIcon: string;
smallIcon: string;
text: string | string[];
onClick?: () => void;
smallVariant: boolean;
style?: CSSProperties;
disabled?: boolean;
done: boolean;
'data-testid'?: string;
}
const CheckListItem = ({
largeIcon,
smallIcon,
text,
onClick,
smallVariant,
style,
done,
disabled,
'data-testid': dataTestId,
}: Props) => {
const getIconSize = () => {
let iconSize: IconSize = 16;
if (done) {
iconSize = smallVariant ? 12 : 20;
}
return iconSize;
};
return (
<button
disabled={disabled}
onClick={() => onClick?.()}
className={clsx(
'flex flex-nowrap flex-align-items-center text-left checkList-item border-none',
onClick !== undefined && !disabled ? 'cursor-pointer' : 'cursor-default',
smallVariant ? 'p-0 text-sm color-norm p-2 mb-0.5 w-full' : 'px-4 py-3 rounded-lg gap-3',
disabled && 'opacity-50'
)}
style={{
...style,
color: smallVariant ? 'var(--text-norm)' : 'var(--optional-promotion-text-color)',
}}
data-testid={dataTestId}
>
<img
className={clsx('w-custom h-custom flex-item-noshrink', done && 'opacity-50')}
src={smallVariant ? smallIcon : largeIcon}
style={{
'--w-custom': smallVariant ? '1.75rem' : '5.5rem',
'--h-custom': smallVariant ? '1.5rem' : '3rem',
}}
alt=""
data-testid={smallVariant ? 'checklist-item-icon-small' : 'checklist-item-icon-large'}
/>
<span className={clsx('flex-item-fluid px-2', done && 'opacity-50')}>{text}</span>
<div
className={clsx(
'w-custom h-custom flex flex-align-self-center',
done && 'bg-primary rounded-50 flex flex-align-items-center flex-justify-center flex-item-noshrink'
)}
style={{
'--h-custom': smallVariant || !done ? '1rem' : '1.5rem',
'--w-custom': smallVariant || !done ? '1rem' : '1.5rem',
}}
>
<Icon name={done ? 'checkmark' : 'chevron-right'} size={getIconSize()} />
</div>
</button>
);
};
export default CheckListItem;
| 5,236
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/checklist/index.ts
|
export * from './CheckList';
export { default as CheckListItem } from './CheckListItem';
| 5,237
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/collapsible/Collapsible.test.tsx
|
import { render } from '@testing-library/react';
import Collapsible from './Collapsible';
import CollapsibleContent from './CollapsibleContent';
import CollapsibleHeader from './CollapsibleHeader';
// test accessibility?
describe('<Collapsible />', () => {
it('renders only the header by default', () => {
const { getByTestId } = render(
<Collapsible>
<CollapsibleHeader>Header</CollapsibleHeader>
<CollapsibleContent>Content</CollapsibleContent>
</Collapsible>
);
const header = getByTestId('collapsible-header');
const content = getByTestId('collapsible-content');
expect(header.textContent).toBe('Header');
expect(content).not.toBeVisible();
});
it('renders content when expandByDefault is true', () => {
const { getByTestId } = render(
<Collapsible expandByDefault>
<CollapsibleHeader>Header</CollapsibleHeader>
<CollapsibleContent>Content</CollapsibleContent>
</Collapsible>
);
const content = getByTestId('collapsible-content');
expect(content.textContent).toBe('Content');
expect(content).toBeVisible();
});
it('toggles content when header is clicked', () => {
const { getByTestId } = render(
<Collapsible>
<CollapsibleHeader>Header</CollapsibleHeader>
<CollapsibleContent>Content</CollapsibleContent>
</Collapsible>
);
const header = getByTestId('collapsible-header');
const content = getByTestId('collapsible-content');
expect(content).not.toBeVisible();
header.click();
expect(content).toBeVisible();
header.click();
expect(content).not.toBeVisible();
});
});
| 5,238
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/collapsible/Collapsible.tsx
|
import { Children, ElementType, useState } from 'react';
import { PolymorphicPropsWithoutRef } from 'react-polymorphic-types';
import { generateUID } from '../../helpers';
import CollapsibleContext, { CollapsibleContextValue } from './CollapsibleContext';
export interface CollapsibleOwnProps {
/**
* Disables the collapsible component
*/
disabled?: boolean;
/**
* Shows content by default if true.
*/
expandByDefault?: boolean;
}
export type CollapsibleProps<E extends ElementType> = PolymorphicPropsWithoutRef<CollapsibleOwnProps, E>;
const defaultElement = 'div';
const Collapsible = <E extends ElementType = typeof defaultElement>({
disabled = false,
expandByDefault = false,
children: childrenProp,
as,
...rest
}: CollapsibleProps<E>) => {
const [isExpanded, setIsExpanded] = useState(expandByDefault);
const [header, content] = Children.toArray(childrenProp);
const contentId = generateUID('collapsible');
const headerId = generateUID('collapsible');
const toggle = () => {
setIsExpanded((prevState) => !prevState);
};
const contextValue: CollapsibleContextValue = {
isExpanded,
disabled,
toggle,
headerId,
contentId,
};
const Element: ElementType = as || defaultElement;
return (
<CollapsibleContext.Provider value={contextValue}>
<Element {...rest}>
{header}
{content}
</Element>
</CollapsibleContext.Provider>
);
};
export default Collapsible;
| 5,239
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/collapsible/CollapsibleContent.tsx
|
import { ElementType, useContext } from 'react';
import { PolymorphicPropsWithoutRef } from 'react-polymorphic-types';
import CollapsibleContext from './CollapsibleContext';
export interface CollapsibleContentOwnProps {}
export type CollapsibleContentProps<E extends ElementType> = PolymorphicPropsWithoutRef<CollapsibleContentOwnProps, E>;
const defaultElement = 'div';
const CollapsibleContent = <E extends ElementType = typeof defaultElement>({
as,
...rest
}: CollapsibleContentProps<E>) => {
const { isExpanded, contentId, headerId } = useContext(CollapsibleContext);
const Element: ElementType = as || defaultElement;
return (
<Element
{...rest}
id={contentId}
role="region"
aria-labelledby={headerId}
hidden={!isExpanded}
aria-hidden={!isExpanded}
data-testid="collapsible-content"
/>
);
};
export default CollapsibleContent;
| 5,240
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/collapsible/CollapsibleContext.tsx
|
import { createContext } from 'react';
export interface CollapsibleContextValue {
isExpanded: boolean;
disabled?: boolean;
toggle: () => void;
headerId: string;
contentId: string;
}
const CollapsibleContext = createContext({} as CollapsibleContextValue);
export default CollapsibleContext;
| 5,241
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/collapsible/CollapsibleHeader.scss
|
.collapsible-header {
&--clickable {
cursor: pointer;
}
}
| 5,242
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/collapsible/CollapsibleHeader.tsx
|
import { ElementType, ReactNode, useContext } from 'react';
import { PolymorphicPropsWithoutRef } from 'react-polymorphic-types';
import clsx from '@proton/utils/clsx';
import CollapsibleContext from './CollapsibleContext';
import './CollapsibleHeader.scss';
export interface CollapsibleHeaderOwnProps {
/**
* Component to append to the end of the header
*/
suffix?: ReactNode;
/**
* Disables the header content from growing to fill available space.
*/
disableFullWidth?: boolean;
/**
* Restricts the toggle click to only the expand icon.
*/
disableContainerToggle?: boolean;
}
export type CollapsibleHeaderProps<E extends ElementType> = PolymorphicPropsWithoutRef<CollapsibleHeaderOwnProps, E>;
const defaultElement = 'header';
const CollapsibleHeader = <E extends ElementType = typeof defaultElement>({
suffix,
disableFullWidth,
disableContainerToggle,
className,
children,
onClick,
as,
...rest
}: CollapsibleHeaderProps<E>) => {
const { toggle, headerId, disabled } = useContext(CollapsibleContext);
const handleContainerClick = () => {
if (disabled) {
return;
}
if (!disableContainerToggle) {
toggle();
}
onClick?.();
};
const Element: ElementType = as || defaultElement;
return (
<Element
disabled={disabled}
{...rest}
onClick={handleContainerClick}
className={clsx(
className,
'flex flex-nowrap flex-align-items-center',
disabled && 'no-pointer-events',
!disabled && !disableContainerToggle && 'collapsible-header--clickable'
)}
>
<div
id={headerId}
className={clsx(!disableFullWidth && 'flex-item-fluid')}
data-testid="collapsible-header"
>
{children}
</div>
{suffix && <div className="flex flex-item-noshrink ml-2">{suffix}</div>}
</Element>
);
};
export default CollapsibleHeader;
| 5,243
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/collapsible/CollapsibleHeaderButton.tsx
|
import { useContext } from 'react';
import { c } from 'ttag';
import { Button, ButtonProps } from '@proton/atoms';
import { Tooltip } from '../tooltip';
import CollapsibleContext from './CollapsibleContext';
export interface CollapsibleHeaderButtonProps extends ButtonProps {
/**
* Icon tooltip text used when content is collapsed and can be expanded.
*/
expandText?: string;
/**
* Icon tooltip text used when content is expanded and can be collapsed.
*/
collapseText?: string;
}
const CollapsibleHeaderButton = ({
expandText = c('Collapsible tooltip').t`Expand`,
collapseText = c('Collapsible tooltip').t`Collapse`,
children,
disabled,
onClick,
...rest
}: CollapsibleHeaderButtonProps) => {
const { isExpanded, toggle, headerId, contentId, disabled: contextDisabled } = useContext(CollapsibleContext);
const tooltipText = isExpanded ? collapseText : expandText;
const handleButtonClick = (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
e.stopPropagation();
e.preventDefault();
toggle();
onClick?.(e);
};
return (
<Tooltip title={tooltipText}>
<Button
{...rest}
disabled={disabled || contextDisabled}
aria-expanded={isExpanded}
aria-describedby={headerId}
aria-controls={contentId}
onClick={handleButtonClick}
>
{children}
<span className="sr-only">{tooltipText}</span>
</Button>
</Tooltip>
);
};
export default CollapsibleHeaderButton;
| 5,244
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/collapsible/CollapsibleHeaderIconButton.scss
|
.collapsible-header-icon-button {
&[aria-expanded='true'] svg {
transform: rotateX(180deg);
}
}
| 5,245
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/collapsible/CollapsibleHeaderIconButton.tsx
|
import clsx from '@proton/utils/clsx';
import CollapsibleHeaderButton, { CollapsibleHeaderButtonProps } from './CollapsibleHeaderButton';
import './CollapsibleHeaderIconButton.scss';
export interface CollapsibleHeaderIconButtonProps extends Omit<CollapsibleHeaderButtonProps, 'icon'> {}
/**
* Icon button which rotates the icon by 180° when collapsible is toggled.
*/
const CollapsibleHeaderIconButton = ({ children, className, ...rest }: CollapsibleHeaderIconButtonProps) => {
return (
<CollapsibleHeaderButton
className={clsx('collapsible-header-icon-button', className)}
shape="ghost"
color="weak"
{...rest}
icon
>
{children}
</CollapsibleHeaderButton>
);
};
export default CollapsibleHeaderIconButton;
| 5,246
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/collapsible/index.ts
|
export { default as Collapsible } from './Collapsible';
export * from './Collapsible';
export { default as CollapsibleHeader } from './CollapsibleHeader';
export * from './CollapsibleHeader';
export { default as CollapsibleContent } from './CollapsibleContent';
export * from './CollapsibleContent';
export { default as CollapsibleHeaderButton } from './CollapsibleHeaderButton';
export * from './CollapsibleHeaderButton';
export { default as CollapsibleHeaderIconButton } from './CollapsibleHeaderIconButton';
export * from './CollapsibleHeaderIconButton';
| 5,247
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/collapsingBreadcrumbs/Breadcrumb.tsx
|
import { LiHTMLAttributes, ReactNode, Ref, forwardRef } from 'react';
import { Button } from '@proton/atoms/';
import clsx from '@proton/utils/clsx';
interface Props extends Omit<LiHTMLAttributes<HTMLLIElement>, 'onClick'> {
title?: string;
children: ReactNode;
active?: boolean;
noShrink?: boolean;
onClick?: () => void;
}
const Breadcrumb = (
{ title, children, onClick, active, noShrink, className, ...rest }: Props,
ref: Ref<HTMLLIElement>
) => {
const textClass = clsx([
'text-pre p-1 m-0 text-ellipsis no-pointer-events-children',
active ? 'text-strong' : 'color-weak',
]);
return (
<li
{...rest}
ref={ref}
className={clsx(['collapsing-breadcrumb', noShrink && 'collapsing-breadcrumb--no-shrink', className])}
>
{onClick ? (
<Button shape="ghost" color="weak" title={title} onClick={onClick} className={textClass}>
{children}
</Button>
) : (
<span title={title} className={textClass}>
{children}
</span>
)}
</li>
);
};
export default forwardRef<HTMLLIElement, Props>(Breadcrumb);
| 5,248
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/collapsingBreadcrumbs/CollapsedBreadcrumbs.tsx
|
import { useMemo, useRef } from 'react';
import { omit } from '@proton/shared/lib/helpers/object';
import clsx from '@proton/utils/clsx';
import { generateUID } from '../../helpers';
import Dropdown from '../dropdown/Dropdown';
import DropdownMenu from '../dropdown/DropdownMenu';
import DropdownMenuButton from '../dropdown/DropdownMenuButton';
import { usePopperAnchor } from '../popper';
import Breadcrumb from './Breadcrumb';
import { BreadcrumbInfo } from './interfaces';
interface Props {
breadcrumbs: BreadcrumbInfo[];
}
function CollapsedBreadcrumb({ breadcrumbs }: Props) {
const uid = useMemo(() => generateUID('dropdown'), []);
const { anchorRef, isOpen, toggle, open, close } = usePopperAnchor<HTMLLIElement>();
const closeTimeout = useRef<any>();
const mouseEnterCounter = useRef(0);
const closeWithTimeout = () => {
clearTimeout(closeTimeout.current);
mouseEnterCounter.current = 0;
closeTimeout.current = setTimeout(() => {
close();
}, 1000);
};
const handleDragLeave = () => {
mouseEnterCounter.current -= 1;
if (mouseEnterCounter.current <= 0) {
closeWithTimeout();
}
};
const handleDragEnter = () => {
clearTimeout(closeTimeout.current);
mouseEnterCounter.current += 1;
if (!isOpen) {
open();
}
};
return (
<>
<Breadcrumb
ref={anchorRef}
onClick={toggle}
onDragEnter={handleDragEnter}
onDragLeave={handleDragLeave}
className={isOpen ? 'collapsed-breadcrumb-active' : ''}
>
...
</Breadcrumb>
<Dropdown
id={uid}
isOpen={isOpen}
anchorRef={anchorRef}
originalPlacement="bottom-start"
onClose={close}
onDragLeave={handleDragLeave}
onDragEnter={handleDragEnter}
onDrop={closeWithTimeout}
>
<DropdownMenu>
{breadcrumbs.map((breadcrumb) => {
const {
key,
text,
highlighted,
collapsedText = breadcrumb.text,
...breadcrumbProps
} = breadcrumb;
return (
<DropdownMenuButton
{...omit(breadcrumbProps, ['noShrink'])}
className={clsx([
'flex text-left flex-nowrap no-pointer-events-children',
highlighted && 'text-strong',
])}
title={text}
key={key}
>
{typeof collapsedText === 'string' ? (
<span title={collapsedText} className="text-ellipsis">
{collapsedText}
</span>
) : (
collapsedText
)}
</DropdownMenuButton>
);
})}
</DropdownMenu>
</Dropdown>
</>
);
}
export default CollapsedBreadcrumb;
| 5,249
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/collapsingBreadcrumbs/CollapsingBreadcrumbs.tsx
|
import { Fragment, useMemo } from 'react';
import { omit } from '@proton/shared/lib/helpers/object';
import clsx from '@proton/utils/clsx';
import useActiveBreakpoint from '../../hooks/useActiveBreakpoint';
import Icon from '../icon/Icon';
import Breadcrumb from './Breadcrumb';
import CollapsedBreadcrumbs from './CollapsedBreadcrumbs';
import { BreadcrumbInfo } from './interfaces';
export type GroupedBreadcrumbs = (BreadcrumbInfo | BreadcrumbInfo[])[];
interface Props {
className?: string;
breadcrumbs: BreadcrumbInfo[];
}
const CollapsingBreadcrumbs = ({ breadcrumbs, className }: Props) => {
const { isTinyMobile, isDesktop } = useActiveBreakpoint();
const groupedBreadcrumbs = useMemo(
() =>
breadcrumbs.reduce((grouped, breadcrumb, i, arr) => {
// In wider spaces, first breadcrumb is always visible
if (!isTinyMobile && i === 0) {
return [breadcrumb];
}
const secondToLast = arr.length - 2;
const last = arr.length - 1;
// Last is always visible, on larger screens also second to last
if (i === last || (isDesktop && i === secondToLast)) {
return [...grouped, breadcrumb];
}
const lastGrouped = grouped.length - 1;
const group = grouped[lastGrouped];
// All others are grouped (shown as dropdown)
return group instanceof Array
? [...grouped.slice(0, lastGrouped), [...group, breadcrumb]]
: [...grouped, [breadcrumb]];
}, [] as GroupedBreadcrumbs),
[breadcrumbs, isTinyMobile, isDesktop]
);
return (
<ul className={clsx(['collapsing-breadcrumbs unstyled', className])} data-testid="collapsing-breadcrumbs">
{groupedBreadcrumbs.map((group, i, arr) => {
const { key, text, richText, highlighted, ...breadcrumbProps } =
group instanceof Array ? group[0] : group;
const isLast = i === arr.length - 1;
// Don't group single breadcrumbs, that would look stupid
return (
<Fragment key={key}>
{group instanceof Array && group.length > 1 ? (
<CollapsedBreadcrumbs breadcrumbs={group} />
) : (
<Breadcrumb
title={text}
{...omit(breadcrumbProps, ['collapsedText'])}
active={isLast || highlighted}
>
{richText || text}
</Breadcrumb>
)}
{!isLast && (
<li className="on-rtl-mirror flex-item-noshrink" aria-hidden="true">
<Icon size={16} name="chevron-right" />
</li>
)}
</Fragment>
);
})}
</ul>
);
};
export default CollapsingBreadcrumbs;
| 5,250
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/collapsingBreadcrumbs/index.ts
|
export { default as CollapsingBreadcrumbs } from './CollapsingBreadcrumbs';
| 5,251
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/collapsingBreadcrumbs/interfaces.ts
|
import { HTMLAttributes, ReactNode } from 'react';
export interface BreadcrumbInfo
extends Omit<HTMLAttributes<HTMLButtonElement | HTMLLIElement>, 'children' | 'onClick'> {
key: string | number;
text: string;
richText?: ReactNode;
collapsedText?: ReactNode;
noShrink?: boolean;
highlighted?: boolean;
onClick?: () => void;
}
| 5,252
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/color/ColorSelector.tsx
|
import tinycolor from 'tinycolor2';
import { c } from 'ttag';
import { genAccentShades } from '@proton/colors';
import useInstance from '@proton/hooks/useInstance';
import generateUID from '@proton/shared/lib/helpers/generateUID';
import capitalize from '@proton/utils/capitalize';
import clsx from '@proton/utils/clsx';
interface Props {
selected: string;
onChange: (color: string) => void;
className?: string;
colors: { value: string; label?: string }[];
inline?: boolean;
autoFocus?: boolean;
}
const ColorSelector = ({ selected, onChange, className, colors, inline = false, autoFocus }: Props) => {
const uid = useInstance(() => generateUID('color-selector'));
return (
<ul
aria-label={c('Label').t`Colors`}
className={clsx([
'color-selector-container unstyled m-0',
inline && 'color-selector-container-inline',
className,
])}
>
{colors.map(({ value: color, label }) => {
const isSelected = selected?.toLowerCase() === color?.toLowerCase();
const [base, hover, selectedColor] = genAccentShades(tinycolor(color)).map((c) => c.toHexString());
return (
<li key={color}>
<label
className={clsx(['color-selector-item', isSelected && 'is-selected'])}
style={{
color,
'--color-selector-base': base,
'--color-selector-strong': hover,
'--color-selector-intense': selectedColor,
}}
title={capitalize(label) || color}
>
<input
type="radio"
name={uid}
value={color}
className="color-selector-input"
data-testid={`color-selector:${color}`}
onChange={() => onChange(color)}
autoFocus={autoFocus ? isSelected : undefined}
/>
<span className="sr-only">{label || color}</span>
</label>
</li>
);
})}
</ul>
);
};
export default ColorSelector;
| 5,253
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/color/index.ts
|
export { default as ColorSelector } from './ColorSelector';
| 5,254
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/commander/Commander.scss
|
@import '~@proton/styles/scss/lib';
.commander {
// cleanup a bit modal
&-modal {
--size: 30rem;
margin-block-start: 2em;
.modal-two-content {
padding-inline: 0;
--margin: 0;
}
}
&-search-wrapper,
&-results-wrapper {
padding-inline: var(--space-1);
}
}
| 5,255
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/commander/Commander.tsx
|
import { useMemo, useRef, useState } from 'react';
import { c, msgid } from 'ttag';
import { Button, Kbd, Scroll } from '@proton/atoms';
import { Icon, IconName, InputFieldTwo } from '@proton/components';
import { normalize } from '@proton/shared/lib/helpers/string';
import clsx from '@proton/utils/clsx';
import { DropdownMenuButton } from '../dropdown';
import { Form } from '../form';
import { ModalProps, ModalTwo } from '../modalTwo';
import { Mark } from '../text';
import './Commander.scss';
export interface CommanderItemInterface {
icon: IconName;
value: string;
label: string;
shortcuts?: string[];
action: () => void;
}
interface Props extends ModalProps {
list: CommanderItemInterface[];
onClose: () => void;
}
const Commander = ({ onClose, list, ...rest }: Props) => {
const [value, setValue] = useState('');
const inputRef = useRef<HTMLInputElement>(null);
const cleanValue = normalize(value);
const [active, setActive] = useState(0);
const filteredList = useMemo(() => {
if (cleanValue.length) {
return list.filter((item) => {
const cleanItemLabel = normalize(item.label);
const cleanItemValue = normalize(item.value);
return cleanItemLabel.includes(cleanValue) || cleanItemValue.includes(cleanValue);
});
}
return list;
}, [cleanValue, list]);
const handleChange = ({ target }: React.ChangeEvent<HTMLInputElement>) => {
setValue(target.value);
setActive(0);
};
const handleClear = () => {
setValue('');
inputRef.current?.focus();
setActive(0);
};
const handleKeyDown = ({ key }: React.KeyboardEvent<HTMLInputElement>) => {
if (key === 'ArrowDown') {
setActive((active) => (active + 1) % filteredList.length);
}
if (key === 'ArrowUp') {
setActive((active) => (active - 1 + filteredList.length) % filteredList.length);
}
if (key === 'Escape') {
onClose();
}
};
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const item = filteredList[active];
if (item) {
filteredList[active].action();
onClose();
}
};
return (
<ModalTwo
className="commander-modal"
size="small"
as={Form}
onClose={onClose}
onSubmit={handleSubmit}
enableCloseWhenClickOutside
{...rest}
>
<div className="flex flex-column flex-nowrap h-full">
<div className="border-bottom commander-search-wrapper py-1 flex-item-noshrink">
<label className="sr-only" htmlFor="commander-search-input">
{c('Label').t`Type a command...`}
</label>
<InputFieldTwo
unstyled
dense
autoFocus
bigger
autoComplete="off"
className="commander-search-input"
inputClassName="h3"
type="search"
id="commander-search-input"
placeholder={c('Placeholder').t`Type a command…`}
ref={inputRef}
value={value}
onChange={handleChange}
onKeyDown={handleKeyDown}
prefix={<Icon name="magnifier" size={18} alt={c('action').t`Search messages`} />}
suffix={
<Button
type="button"
shape="ghost"
color="weak"
size="small"
className="rounded-sm"
title={c('Action').t`Clear`}
onClick={handleClear}
>
{c('Action').t`Clear`}
</Button>
}
/>
</div>
{value !== '' && (
<span className="sr-only" aria-atomic="true" aria-live="polite">
{c('info').ngettext(
msgid`${filteredList.length} command found.`,
`${filteredList.length} commands found.`,
filteredList.length
)}
</span>
)}
<div className="commander-results-wrapper">
<Scroll className="overflow-hidden">
{filteredList.length ? (
<>
<ul className="unstyled mt-2">
{filteredList.map((item, index) => (
<li className="dropdown-item" key={item.value}>
<DropdownMenuButton
onClick={() => {
item.action();
onClose();
}}
isSelected={active === index}
className="w-full flex flex-align-items-center flex-justify-space-between text-left p-3"
>
<span className="flex flex-align-items-center text-left text-pre">
<Icon name={item.icon} className="mr-4" />
<Mark value={value}>{item.label}</Mark>
</span>
<span className="ml-1">
{item.shortcuts &&
item.shortcuts.map((shortcut, i) => (
<Kbd
key={shortcut}
shortcut={shortcut}
className={clsx([i > 0 && 'ml-2'])}
/>
))}
</span>
</DropdownMenuButton>
</li>
))}
</ul>
</>
) : (
<p className="m-4">{c('Info').t`No results found`}</p>
)}
</Scroll>
</div>
</div>
</ModalTwo>
);
};
export default Commander;
| 5,256
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/commander/index.ts
|
export { default as Commander } from './Commander';
export * from './Commander';
| 5,257
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/confirmActionModal/ConfirmActionModal.tsx
|
import React, { ReactNode, useState } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import {
ModalSize,
ModalStateProps,
ModalTwo,
ModalTwoContent,
ModalTwoFooter,
ModalTwoHeader,
useModalTwo,
} from '@proton/components';
export interface ConfirmActionModalProps {
message: string | ReactNode;
canUndo?: boolean;
actionType?: 'danger' | 'norm';
onCancel?: () => void;
onSubmit?: () => Promise<void | unknown>;
title?: string;
cancelText?: ReactNode;
submitText?: ReactNode;
loading?: boolean;
className?: string;
size?: ModalSize;
}
export const ConfirmActionModal = ({
cancelText = c('Action').t`Cancel`,
submitText = c('Action').t`Submit`,
loading,
title,
onClose,
onCancel,
onSubmit,
size = 'large',
message,
actionType = 'danger',
canUndo = false,
...modalProps
}: ConfirmActionModalProps & ModalStateProps) => {
const [submitLoading, setSubmitLoading] = useState(false);
const isLoading = loading || submitLoading;
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (onSubmit) {
setSubmitLoading(true);
await onSubmit().catch(() => undefined);
setSubmitLoading(false);
}
onClose();
};
return (
<ModalTwo
as="form"
disableCloseOnEscape={loading}
onClose={onClose}
onReset={onClose}
onSubmit={handleSubmit}
size={size}
{...modalProps}
>
<ModalTwoHeader closeButtonProps={{ disabled: loading }} title={title} />
<ModalTwoContent>
{message}
<br />
{!canUndo && c('Info').t`You cannot undo this action.`}
</ModalTwoContent>
<ModalTwoFooter>
<Button type="reset" onClick={onCancel} disabled={isLoading}>
{cancelText}
</Button>
<Button type="submit" loading={isLoading} shape="solid" color={actionType}>
{submitText}
</Button>
</ModalTwoFooter>
</ModalTwo>
);
};
export const useConfirmActionModal = () => {
return useModalTwo<ConfirmActionModalProps, void>(ConfirmActionModal, false);
};
| 5,258
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/confirmActionModal/index.ts
|
export * from './ConfirmActionModal';
| 5,259
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/confirmSignOutModal/ConfirmSignOutModal.tsx
|
import { useState } from 'react';
import { c } from 'ttag';
import { Button, Href } from '@proton/atoms';
import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url';
import { User } from '@proton/shared/lib/interfaces';
import { getHasRecoveryMessage } from '@proton/shared/lib/recoveryFile/deviceRecovery';
import { PrivateAuthenticationStore } from '../../containers';
import { Checkbox } from '../input';
import { Label } from '../label';
import { Prompt, PromptProps } from '../prompt';
export const shouldShowConfirmSignOutModal = ({
user,
authentication,
}: {
user: User;
authentication: PrivateAuthenticationStore;
}) => {
const hasEnabledDeviceBasedRecovery = authentication.getTrusted();
return hasEnabledDeviceBasedRecovery || getHasRecoveryMessage(user.ID);
};
interface Props extends Omit<PromptProps, 'title' | 'buttons' | 'children'> {
onSignOut: (clearData: boolean) => void;
}
const ConfirmSignOutModal = ({ onSignOut, onClose, ...rest }: Props) => {
const [clearData, setClearData] = useState(false);
return (
<Prompt
title={c('Title').t`Sign out`}
buttons={[
<Button
color="norm"
onClick={() => {
onSignOut(clearData);
onClose?.();
}}
>
{c('Action').t`Sign out`}
</Button>,
<Button onClick={onClose}>{c('Action').t`Cancel`}</Button>,
]}
{...rest}
>
<p className="mt-0">
{c('Info').t`Recovery information will remain on this device unless you select to delete it.`}
</p>
<div className="flex flex-row flex-align-items-start">
<Checkbox
id="delete-recovery-storage"
className="mt-2 mr-2"
checked={clearData}
onChange={() => setClearData(!clearData)}
/>
<div className="flex-item-fluid">
<Label htmlFor="delete-recovery-storage" className="block">
{c('Label').jt`Delete recovery-related information.`}{' '}
<Href href={getKnowledgeBaseUrl('/trusted-device/recovery/')}>{c('Link').t`What’s this?`}</Href>
</Label>
</div>
</div>
</Prompt>
);
};
export default ConfirmSignOutModal;
| 5,260
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/confirmSignOutModal/index.ts
|
export { default as ConfirmSignOutModal } from './ConfirmSignOutModal';
export * from './ConfirmSignOutModal';
| 5,261
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/container/Block.js
|
import PropTypes from 'prop-types';
import clsx from '@proton/utils/clsx';
const Block = ({ children, className = '' }) => {
return <div className={clsx(['mb-4', className])}>{children}</div>;
};
Block.propTypes = {
children: PropTypes.node,
className: PropTypes.string,
};
export default Block;
| 5,262
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/container/Bordered.tsx
|
import { ComponentPropsWithoutRef, Ref, forwardRef } from 'react';
import clsx from '@proton/utils/clsx';
type Props = ComponentPropsWithoutRef<'div'>;
const Bordered = ({ children, className: classNameProp, ...rest }: Props, ref: Ref<HTMLDivElement>) => {
const className = clsx(classNameProp, 'border p-4 mb-4');
return (
<div ref={ref} className={className} {...rest}>
{children}
</div>
);
};
export default forwardRef<HTMLDivElement, Props>(Bordered);
| 5,263
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/container/Details.tsx
|
import { ComponentPropsWithRef, Ref, forwardRef, useRef } from 'react';
type Props = ComponentPropsWithRef<'details'>;
const Details = ({ children, className, onToggle, open, ...props }: Props, ref: Ref<HTMLDetailsElement>) => {
const initialToggle = useRef(true);
return (
<details
className={className}
ref={ref}
open={open}
onToggle={(e) => {
// onToggle is invoked even with the first mount if the details
// are opened by default. We don't want that.
if (initialToggle.current) {
initialToggle.current = false;
if (open) {
return;
}
}
onToggle?.(e);
}}
{...props}
>
{children}
</details>
);
};
export default forwardRef<HTMLDetailsElement, Props>(Details);
| 5,264
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/container/EditableSection.tsx
|
import { DetailedHTMLProps, HTMLAttributes, ReactNode } from 'react';
import clsx from '@proton/utils/clsx';
interface Props extends DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement> {
children?: ReactNode;
className?: string;
}
const EditableSection = ({ children, className = '', ...rest }: Props) => {
return (
<div className={clsx(['w-full md:w-auto editable-section-container', className])} {...rest}>
{children}
</div>
);
};
export default EditableSection;
| 5,265
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/container/Field.js
|
import PropTypes from 'prop-types';
const Field = ({ children, className }) => {
return <div className={['field-container', className].filter(Boolean).join(' ')}>{children}</div>;
};
Field.propTypes = {
children: PropTypes.node,
className: PropTypes.string,
};
export default Field;
| 5,266
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/container/Row.tsx
|
import { DetailedHTMLProps, HTMLAttributes, ReactNode } from 'react';
import clsx from '@proton/utils/clsx';
interface Props extends DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement> {
children?: ReactNode;
className?: string;
collapseOnMobile?: boolean;
}
const Row = ({ children, className = '', collapseOnMobile = true, ...rest }: Props) => {
return (
<div
className={clsx(['flex flex-nowrap mb-4', collapseOnMobile && 'on-mobile-flex-column', className])}
{...rest}
>
{children}
</div>
);
};
export default Row;
| 5,267
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/container/Summary.tsx
|
import { HTMLProps, ReactNode } from 'react';
import Icon from '../icon/Icon';
interface Props extends HTMLProps<HTMLElement> {
children: ReactNode;
}
const Summary = ({ children, ...rest }: Props) => (
// Safari can't set up summary tag as a flex container, tsssss... https://bugs.webkit.org/show_bug.cgi?id=190065
<summary {...rest}>
<div className="flex flex-nowrap">
<Icon name="chevron-down" className="summary-caret mr-1 mt-1 flex-item-noshrink" />
<div className="flex-item-fluid">{children}</div>
</div>
</summary>
);
export default Summary;
| 5,268
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/container/index.ts
|
export { default as Bordered } from './Bordered';
export { default as Block } from './Block';
export { default as Row } from './Row';
export { default as EditableSection } from './EditableSection';
export { default as Field } from './Field';
export { default as Details } from './Details';
export { default as Summary } from './Summary';
| 5,269
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/contextMenu/ContextMenu.tsx
|
import { ReactNode, RefObject, useEffect, useState } from 'react';
import { generateUID } from '../../helpers';
import { Dropdown, DropdownProps } from '../dropdown';
import { PopperPosition, cornerPopperPlacements } from '../popper';
export interface ContextMenuProps {
anchorRef: RefObject<HTMLElement>;
isOpen: boolean;
children: ReactNode;
position?: PopperPosition;
close: () => void;
autoClose?: boolean;
size?: DropdownProps['size'];
}
const ContextMenu = ({ anchorRef, children, isOpen, position, close, autoClose = true, size }: ContextMenuProps) => {
const [uid] = useState(generateUID('context-menu'));
useEffect(() => {
if (!isOpen) {
return;
}
const handleContextMenu = () => {
if (autoClose) {
close();
}
};
document.addEventListener('contextmenu', handleContextMenu, { capture: true });
return () => {
document.removeEventListener('contextmenu', handleContextMenu, { capture: true });
};
}, [isOpen, autoClose, close]);
return (
<Dropdown
id={uid}
isOpen={isOpen}
anchorRef={anchorRef}
anchorPosition={position || null}
availablePlacements={cornerPopperPlacements}
noCaret
autoCloseOutsideAnchor={false}
originalPlacement="bottom-start"
offset={1}
onClose={close}
onContextMenu={(e) => e.stopPropagation()}
size={size}
>
{children}
</Dropdown>
);
};
export default ContextMenu;
| 5,270
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/contextMenu/ContextMenuButton.tsx
|
import { DropdownMenuButton } from '../dropdown';
import { Icon, IconName } from '../icon';
interface Props {
name: string;
icon: IconName;
testId?: string;
action: () => void;
}
const ContextMenuButton = ({ name, icon, testId, action }: Props) => {
return (
<DropdownMenuButton
key={name}
onContextMenu={(e) => e.stopPropagation()}
className="flex flex-align-items-center flex-nowrap text-left"
onClick={(e) => {
e.stopPropagation();
action();
}}
data-testid={testId}
>
<Icon className="mr-2 flex-item-noshrink" name={icon} />
{name}
</DropdownMenuButton>
);
};
export default ContextMenuButton;
| 5,271
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/contextMenu/ContextSeparator.tsx
|
import clsx from '@proton/utils/clsx';
export interface Props {
className?: string;
}
const ContextSeparator = ({ className = '', ...rest }: Props) => {
return <hr className={clsx(['m-0', className])} {...rest} />;
};
export default ContextSeparator;
| 5,272
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/contextMenu/index.ts
|
export { default as ContextMenu } from './ContextMenu';
export { default as ContextSeparator } from './ContextSeparator';
export { default as ContextMenuButton } from './ContextMenuButton';
| 5,273
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/country/CountrySelect.helpers.test.ts
|
import {
CountryOption,
PRESELECTED_COUNTRY_OPTION_SUFFIX,
divideSortedCountries,
getAllDropdownOptions,
getCleanCountryCode,
groupCountriesByStartingLetter,
optionToPreselectedOption,
} from '@proton/components/components/country/helpers';
const countryOptions: CountryOption[] = [
{ countryName: 'France', countryCode: 'fr' },
{ countryName: 'Switzerland', countryCode: 'ch' },
{ countryName: 'Australia', countryCode: 'au' },
{ countryName: 'Finland', countryCode: 'fi' },
];
const groupedCountries = {
A: [{ countryName: 'Australia', countryCode: 'au' }],
F: [
{ countryName: 'France', countryCode: 'fr' },
{ countryName: 'Finland', countryCode: 'fi' },
],
S: [{ countryName: 'Switzerland', countryCode: 'ch' }],
};
const dropdownOptions = [
{ type: 'divider', text: 'A' },
{ type: 'country', countryName: 'Australia', countryCode: 'au' },
{ type: 'divider', text: 'F' },
{ type: 'country', countryName: 'France', countryCode: 'fr' },
{ type: 'country', countryName: 'Finland', countryCode: 'fi' },
{ type: 'divider', text: 'S' },
{ type: 'country', countryName: 'Switzerland', countryCode: 'ch' },
];
describe('CountrySelect helpers', () => {
describe('groupCountriesByStartingLetter', () => {
it('should group countries options by their starting letters', () => {
expect(groupCountriesByStartingLetter(countryOptions)).toEqual(groupedCountries);
});
});
describe('divideSortedCountries', () => {
it('should create dropdown options split by dividers', () => {
expect(divideSortedCountries(groupedCountries)).toEqual(dropdownOptions);
});
});
describe('getCountryDropdownOptions', () => {
it('should return expected dropdown options', () => {
expect(getAllDropdownOptions(countryOptions)).toEqual(dropdownOptions);
});
it('should return dropdown options with pre-selected options', () => {
const preSelectedOption: CountryOption = { countryName: 'France', countryCode: 'fr' };
const expected = [
{ type: 'divider', text: 'Based on your time zone' },
{ type: 'country', countryName: 'France', countryCode: 'fr-preselected' },
...dropdownOptions,
];
expect(getAllDropdownOptions(countryOptions, preSelectedOption)).toEqual(expected);
});
it('should return dropdown options with pre-selected options and divider text', () => {
const dividerText = 'Whatever';
const preSelectedOption: CountryOption = { countryName: 'France', countryCode: 'fr' };
const expected = [
{ type: 'divider', text: dividerText },
{ type: 'country', countryName: 'France', countryCode: 'fr-preselected' },
...dropdownOptions,
];
expect(getAllDropdownOptions(countryOptions, preSelectedOption, dividerText)).toEqual(expected);
});
});
describe('getCleanCountryCode', () => {
it('cleans the pre-selected suffix', () => {
expect(getCleanCountryCode(`fr${PRESELECTED_COUNTRY_OPTION_SUFFIX}`)).toEqual('fr');
});
it('returns the country code if no suffix is present', () => {
expect(getCleanCountryCode('ch')).toEqual('ch');
});
});
describe('optionToPreselectedOption', () => {
it('should add `-preselected` suffix to option countryCode', () => {
expect(optionToPreselectedOption({ countryName: 'France', countryCode: 'fr' })).toEqual({
countryName: 'France',
countryCode: 'fr-preselected',
});
});
it('should return option as it is if already suffixed', () => {
expect(optionToPreselectedOption({ countryName: 'France', countryCode: 'fr-preselected' })).toEqual({
countryName: 'France',
countryCode: 'fr-preselected',
});
});
});
});
| 5,274
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/country/CountrySelect.tsx
|
import { useCallback, useMemo, useState } from 'react';
import { c } from 'ttag';
import generateUID from '@proton/atoms/generateUID';
import { InputFieldTwo, Option, SearchableSelect } from '@proton/components/components';
import {
CountryOption,
PRESELECTED_COUNTRY_OPTION_SUFFIX,
getAllDropdownOptions,
getCleanCountryCode,
getIsCountryOption,
isPreselectedOption,
optionToPreselectedOption,
} from '@proton/components/components/country/helpers';
import { Props as OptionProps } from '@proton/components/components/option/Option';
import { getFlagSvg } from '@proton/components/components/v2/phone/flagSvgs';
import { defaultFilterFunction } from '../selectTwo/helpers';
/**
* Filter options based on the search string and their option disabled state.
* If an option is disabled, it's a divider, and we don't want to display it
*/
const countryFilterFunction = (option: OptionProps<string>, keyword?: string) =>
keyword &&
defaultFilterFunction(option, keyword) &&
!option.disabled &&
!option.value.endsWith(PRESELECTED_COUNTRY_OPTION_SUFFIX);
interface Props {
/**
* Country options to list in the dropdown
*/
options: CountryOption[];
/**
* Pre-selected country option (or suggestion) that will be displayed at the top of the dropdown
*/
preSelectedOption?: CountryOption;
/**
* Pre-selected country option divider text
* Default one is "Based on your time zone"
*/
preSelectedOptionDivider?: string;
/**
* Default select value
*/
value?: CountryOption;
onSelectCountry?: (value: string) => void;
error?: string;
hint?: string;
disabled?: boolean;
}
const CountrySelect = ({
options,
preSelectedOptionDivider,
preSelectedOption,
value,
onSelectCountry,
error,
hint,
disabled,
}: Props) => {
const [selectedCountryOption, setSelectedCountryOption] = useState<CountryOption | undefined>(
value || (preSelectedOption ? optionToPreselectedOption(preSelectedOption) : undefined)
);
const { dropdownOptions, countryOptions } = useMemo(() => {
const dropdownOptions = getAllDropdownOptions(options, preSelectedOption, preSelectedOptionDivider);
const countryOptions = dropdownOptions.filter(getIsCountryOption);
return { dropdownOptions, countryOptions };
}, [options, preSelectedOption, preSelectedOptionDivider]);
const handleSelectOption = useCallback(
({ value }: { value: string }) => {
const selectedOption = countryOptions.find(({ countryCode }) => countryCode === value);
setSelectedCountryOption(selectedOption);
onSelectCountry?.(getCleanCountryCode(value));
},
[countryOptions, onSelectCountry]
);
const optionsComponents = useMemo(
() =>
dropdownOptions.map((option) => {
if (option.type === 'country') {
return (
<Option
key={generateUID(option.countryName)}
value={option.countryCode}
title={option.countryName}
data-testid={
isPreselectedOption(option.countryCode)
? 'preselected-country-select-option'
: 'country-select-option'
}
>
<span>
<img
className="flex-item-noshrink mr-2"
alt=""
src={getFlagSvg(getCleanCountryCode(option.countryCode))}
width="30"
height="20"
/>
<span>{option.countryName}</span>
</span>
</Option>
);
} else {
return (
<Option key={generateUID('divider')} value={option.text} title={option.text} disabled>
<span className="text-sm">{option.text}</span>
</Option>
);
}
}),
[dropdownOptions]
);
return (
<InputFieldTwo
id="countrySelect"
as={SearchableSelect<string>}
placeholder={c('Placeholder').t`Please select a country`}
label={c('Label').t`Country`}
value={selectedCountryOption?.countryCode}
onChange={handleSelectOption}
search={countryFilterFunction}
error={error}
aria-describedby="countrySelect"
noSearchResults={
<>
<span className="text-bold">{c('Select search results').t`No results found`}</span>
<br />
<span className="text-sm">{c('Select search results')
.t`Check your spelling or select a country from the list.`}</span>
</>
}
hint={hint}
data-testid="country-select"
disabled={disabled}
>
{optionsComponents}
</InputFieldTwo>
);
};
export default CountrySelect;
| 5,275
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/country/helpers.ts
|
import { c } from 'ttag';
import { SimpleMap } from '@proton/shared/lib/interfaces';
export interface CountryOption {
countryCode: string;
countryName: string;
}
interface DropdownCountryOption {
type: 'country';
countryName: string;
countryCode: string;
}
interface DropdownDividerOption {
type: 'divider';
text: string;
}
export type DropdownOption = DropdownCountryOption | DropdownDividerOption;
export const getIsCountryOption = (option: DropdownOption): option is DropdownCountryOption => {
return !!(option as DropdownCountryOption).countryCode;
};
export const PRESELECTED_COUNTRY_OPTION_SUFFIX = '-preselected';
export const isPreselectedOption = (code: string) => code.endsWith(PRESELECTED_COUNTRY_OPTION_SUFFIX);
export const getCleanCountryCode = (code: string) => {
return isPreselectedOption(code) ? code.slice(0, -PRESELECTED_COUNTRY_OPTION_SUFFIX.length) : code;
};
/**
* Transform a standard country option to a preselected option, suffixing it with `-preselected` to make it non searchable and focused on modal open.
* @param option Option to transform
*
* Example, given
* { countryName: 'France', countryCode: 'fr' },
*
* The function will return
* { countryName: 'France', countryCode: 'fr-preselected' },
*/
export const optionToPreselectedOption = (option: CountryOption): CountryOption => {
if (option.countryCode.endsWith(PRESELECTED_COUNTRY_OPTION_SUFFIX)) {
return option;
}
return {
// adding a suffix here to make this option non searchable. The ideal solution would be to have an object here
countryCode: `${option.countryCode}${PRESELECTED_COUNTRY_OPTION_SUFFIX}`,
countryName: option.countryName,
};
};
/**
* Group all countries by their starting letter in an object with the first letter as the key
* @param countries Country options to sort
*
* Example, given
* [
* {countryName: 'France', countryCode: 'fr'},
* {countryName: 'Switzerland', countryCode: 'ch'},
* ]
*
* The function will return
* {
* F: [
* {countryName: 'France', countryCode: 'fr'},
* ],
* S: [
* {countryName: 'Switzerland', countryCode: 'ch'},
* ]
* }
*/
export const groupCountriesByStartingLetter = (countries: CountryOption[]) => {
return countries.reduce<{ [key: string]: CountryOption[] }>((acc, country) => {
const startingLetter = country.countryName[0].toUpperCase();
if (!acc[startingLetter]) {
acc[startingLetter] = [];
}
acc[startingLetter].push(country);
return acc;
}, {});
};
/**
* Flatten grouped countries and divide them by a divider option
* @param groupedCountries grouped countries to flatten and split by dividers
*
* Example, given
* {
* F: [
* {countryName: 'France', countryCode: 'fr'},
* ],
* S: [
* {countryName: 'Switzerland', countryCode: 'ch'},
* ]
* }
*
* The function will return
* [
* {type: 'divider', text: 'F'},
* {type: 'country', countryName: 'France', countryCode: 'fr'},
*
* {type: 'divider', text: 'S'},
* {type: 'country', countryName: 'Switzerland', countryCode: 'ch'},
* ]
*/
export const divideSortedCountries = (groupedCountries: SimpleMap<CountryOption[]>) => {
const sortedCountryKeys = Object.keys(groupedCountries).sort((a, b) => a.localeCompare(b));
const flatAndDividedArray: DropdownOption[] = [{ type: 'divider', text: sortedCountryKeys[0] }];
sortedCountryKeys.forEach((letter, i) => {
const countries = groupedCountries[letter];
if (!countries) {
return;
}
const countryOptions: DropdownCountryOption[] = countries.map(({ countryCode, countryName }) => ({
type: 'country',
countryName,
countryCode,
}));
flatAndDividedArray.push(...countryOptions, { type: 'divider', text: sortedCountryKeys[i + 1] });
});
flatAndDividedArray.pop();
return flatAndDividedArray;
};
/**
* Get Country dropdown options.
* Returns an array of DropdownOption, displaying the optional pre-selected option at the top,
* and splitting options with dividers based on their first letter
* @param options: country options to display
* @param preSelectedOption: (optional) pre-selected option that will be the first one displayed in the dropdown
* @param preSelectedOptionDivider: (optional) pre-selected option label displayed on top of the option
* @returns DropdownOption[]
*
* Example, given
* options = [
* {countryName: 'France', countryCode: 'fr'},
* {countryName: 'Switzerland', countryCode: 'ch'},
* {countryName: 'Australia', countryCode: 'au'},
* {countryName: 'Austria', countryCode: 'at'},
* ]
* preSelectedOption = {countryName: 'France', countryCode: 'fr'}
*
* The function will return
* [
* // pre-selected option
* {type: 'divider', text: 'Based on your time zone'},
* {type: 'country', countryName: 'France', countryCode: 'fr'},
*
* {type: 'divider', text: 'A'},
* {type: 'country', countryName: 'Australia', countryCode 'au'},
* {type: 'country', countryName: 'Austria', countryCode: 'at'},
*
* {type: 'divider', text: 'F'},
* {type: 'country', countryName: 'France', countryCode: 'fr'},
*
* {type: 'divider', text: 'S'},
* {type: 'country', countryName: 'Switzerland', countryCode: 'ch'},
* ]
*/
export const getAllDropdownOptions = (
options: CountryOption[],
preSelectedOption?: CountryOption,
preSelectedOptionDivider = c('Country select label').t`Based on your time zone`
) => {
const preselected: DropdownOption[] = preSelectedOption
? [
{ type: 'divider', text: preSelectedOptionDivider },
{
type: 'country',
...optionToPreselectedOption(preSelectedOption),
},
]
: [];
// Group all countries by their starting letter
const sortedCountries = groupCountriesByStartingLetter(options);
// Flatten the object and add their dividers
const allCountries = divideSortedCountries(sortedCountries);
return [...preselected, ...allCountries];
};
| 5,276
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/dialog/Dialog.tsx
|
import { HTMLAttributes, Ref, forwardRef } from 'react';
type Props = HTMLAttributes<HTMLDialogElement>;
const Dialog = forwardRef((props: Props, ref: Ref<HTMLDialogElement>) => <dialog ref={ref} {...props} />);
Dialog.displayName = 'Dialog';
export default Dialog;
| 5,277
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/downloadClientCard/DownloadClientCard.tsx
|
import { ReactNode } from 'react';
import { c } from 'ttag';
import { Button, ButtonLike, Href } from '@proton/atoms';
import { ButtonGroup } from '../button';
import { DropdownMenu, SimpleDropdown } from '../dropdown';
import { Icon, IconName } from '../icon';
interface Props {
title: string;
link: string;
icon: IconName;
items?: ReactNode[];
}
const DownloadClientCard = ({ title, link, items, icon }: Props) => {
const downloadButton = (
<ButtonLike as={Href} href={link}>
{c('Action').t`Download`}
<span className="sr-only">{title}</span>
</ButtonLike>
);
return (
<div
className="border rounded-lg flex flex-column flex-align-items-center flex-justify-center min-w-custom p-8"
style={{ '--min-w-custom': '13.5rem' }}
>
<Icon className="mb-2" size={60} name={icon} />
<div className="mb-6">{title}</div>
{!items ? (
downloadButton
) : (
<ButtonGroup>
{downloadButton}
<SimpleDropdown
icon
as={Button}
originalPlacement="bottom-end"
title={c('Title').t`Open actions dropdown`}
>
<DropdownMenu>{items}</DropdownMenu>
</SimpleDropdown>
</ButtonGroup>
)}
</div>
);
};
export default DownloadClientCard;
| 5,278
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/downloadClientCard/index.ts
|
export { default as DownloadClientCard } from './DownloadClientCard';
| 5,279
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/dragMoveContainer/DragMoveContainer.tsx
|
import { ReactNode } from 'react';
interface Props {
children: ReactNode;
}
const DragMoveContainer = ({ children }: Props) => (
<div className="color-norm text-bold bg-norm p-4 border rounded">{children}</div>
);
export default DragMoveContainer;
| 5,280
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/dragMoveContainer/index.ts
|
export { default as DragMoveContainer } from './DragMoveContainer';
| 5,281
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/DrawerApp.scss
|
@import '~@proton/styles/scss/lib';
:root {
--drawer-width: #{rem(0)}; // unit needed for calc()
}
.drawer-is-open {
--drawer-width: #{rem(300)};
}
.drawer-app {
inline-size: var(--drawer-width);
&-inner {
animation: 0.5s easing(ease-out-quart) anime-drawer-app-inner forwards;
@keyframes anime-drawer-app-inner {
from {
opacity: 0;
transform: translate3d(5em, 0, 0);
}
to {
opacity: 1;
transform: translate3d(0, 0, 0);
}
}
}
&-view {
animation: 0.5s easing(ease-out-quart) anime-drawer-app-view forwards;
@keyframes anime-drawer-app-view {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
}
// Between 681 and 1280 px, the widget has to be displayed on top of the rest of the UI
@include media('<=#{em($breakpoint-for-drawer, 16)}') {
position: absolute;
inset-inline-end: 0;
block-size: 100%;
z-index: $layer-drawer; // Need to be on top of the mail content, but not modals
box-shadow: var(--shadow-lifted);
}
@include media('<=small') {
inline-size: 100vw;
}
// We want to be able to use contacts even under 680px in a larger view
// So we hide the drawer-app container only if the app in view is not contact
&--hide-on-mobile {
@include media('<=small') {
display: none;
}
}
}
| 5,282
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/DrawerApp.tsx
|
import { ReactNode, useLayoutEffect } from 'react';
import { c } from 'ttag';
import DrawerContactView from '@proton/components/components/drawer/views/DrawerContactView';
import DrawerSettingsView from '@proton/components/components/drawer/views/DrawerSettingsView';
import { ErrorBoundary, StandardErrorPage } from '@proton/components/containers';
import { CustomAction } from '@proton/components/containers/contacts/widget/types';
import { DRAWER_NATIVE_APPS } from '@proton/shared/lib/drawer/interfaces';
import { Recipient } from '@proton/shared/lib/interfaces';
import clsx from '@proton/utils/clsx';
import { useDrawer } from '../../hooks';
import DrawerContactModals from './DrawerContactModals';
import './DrawerApp.scss';
interface Props {
/**
* Shared
*/
customAppSettings?: ReactNode;
/**
* Mail specific
*/
onCompose?: (recipients: Recipient[], attachments: File[]) => void;
onMailTo?: (src: string) => void;
/**
* Calendar specific
*/
contactCustomActions?: CustomAction[];
}
const DrawerApp = ({ customAppSettings, onCompose, onMailTo, contactCustomActions }: Props) => {
const { appInView, iframeSrcMap } = useDrawer();
useLayoutEffect(() => {
if (appInView !== undefined) {
document.body.classList.add('drawer-is-open');
}
return () => {
document.body.classList.remove('drawer-is-open');
};
}, [appInView]);
return (
<>
<DrawerContactModals />
<aside
className={clsx([
'drawer-app border-left border-weak bg-norm overflow-hidden no-print',
!appInView && 'hidden',
appInView !== DRAWER_NATIVE_APPS.CONTACTS && 'drawer-app--hide-on-mobile',
])}
>
<ErrorBoundary component={<StandardErrorPage />}>
<div className="drawer-app-inner h-full w-full">
{Object.entries(iframeSrcMap)
.filter(([, src]) => src)
.map(([app, src]) => (
<iframe
key={app}
id={`drawer-app-iframe-${app}`}
className={clsx(['drawer-app-view h-full w-full', appInView !== app && 'hidden'])}
src={src}
title={c('Info').t`Calendar side panel`}
allow="clipboard-read; clipboard-write"
/>
))}
{appInView === DRAWER_NATIVE_APPS.CONTACTS && (
<DrawerContactView
onCompose={onCompose}
onMailTo={onMailTo}
customActions={contactCustomActions}
/>
)}
{appInView === DRAWER_NATIVE_APPS.QUICK_SETTINGS && (
<DrawerSettingsView customAppSettings={customAppSettings} />
)}
</div>
</ErrorBoundary>
</aside>
</>
);
};
export default DrawerApp;
| 5,283
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/DrawerContactModals.tsx
|
import { useEffect, useRef } from 'react';
import { useContactModals } from '@proton/components/containers/contacts/hooks/useContactModals';
import { useDrawer } from '@proton/components/hooks/drawer';
import { getIsDrawerPostMessage, postMessageToIframe } from '@proton/shared/lib/drawer/helpers';
import { DRAWER_APPS, DRAWER_EVENTS } from '@proton/shared/lib/drawer/interfaces';
const DrawerContactModals = () => {
const { iframeSrcMap } = useDrawer();
const {
modals: contactModals,
onDetails,
onEdit,
} = useContactModals({
onChange: () => {
if (iframeSrcMap) {
Object.keys(iframeSrcMap).map((app) => {
postMessageToIframe({ type: DRAWER_EVENTS.CALL_EVENT_MANAGER_FROM_OUTSIDE }, app as DRAWER_APPS);
});
}
},
});
/**
* We need to store callbacks inside a ref because of the useEffect below.
*/
const onDetailsRef = useRef(onDetails);
const onEditRef = useRef(onEdit);
useEffect(() => {
onDetailsRef.current = onDetails;
onEditRef.current = onEdit;
});
useEffect(() => {
const handleReceived = async (event: MessageEvent) => {
if (!getIsDrawerPostMessage(event)) {
return;
}
switch (event.data.type) {
case DRAWER_EVENTS.OPEN_CONTACT_MODAL:
if ('contactID' in event.data.payload) {
const { contactID } = event.data.payload;
onDetailsRef.current(contactID);
}
if ('vCardContact' in event.data.payload) {
const { vCardContact } = event.data.payload;
onEditRef.current({ vCardContact });
}
break;
default:
break;
}
};
window.addEventListener('message', handleReceived);
return () => {
window.removeEventListener('message', handleReceived);
};
}, []);
return contactModals;
};
export default DrawerContactModals;
| 5,284
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/DrawerSidebar.scss
|
@import '~@proton/styles/scss/lib';
.drawer-sidebar {
min-inline-size: rem(46);
overflow-x: hidden;
overflow-y: auto;
&-button {
block-size: rem(36);
inline-size: rem(36);
border: 1px solid transparent;
background-color: var(--interaction-default);
display: flex;
align-items: center;
justify-content: center;
animation: anime-sidebar-button-appear-in 0.5s calc(var(--index, 0) * 75ms) easing(ease-out-quint) both;
@keyframes anime-sidebar-button-appear-in {
from {
translate: 1em;
opacity: 0;
}
to {
translate: 0;
opacity: 1;
}
}
&:hover,
&:focus {
background-color: var(--interaction-default-hover);
}
&:active,
&.is-active {
.user-initials {
background-color: var(--interaction-default-active);
}
}
&--notification {
.notification-dot {
inline-size: rem(8);
block-size: rem(8);
position: absolute;
inset-inline-end: rem(8);
inset-block-start: rem(8);
}
}
}
&--hide-on-tablet {
@include media('<=#{em($breakpoint-for-drawer, 16)}') {
display: none;
}
}
}
| 5,285
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/DrawerSidebar.tsx
|
import { ReactElement, cloneElement, useEffect } from 'react';
import { c } from 'ttag';
import clsx from '@proton/utils/clsx';
import { useDrawer, useTheme } from '../..';
import './DrawerSidebar.scss';
interface Props {
buttons: ReactElement[];
}
const DrawerSidebar = ({ buttons }: Props) => {
const { setDrawerSidebarMounted, showDrawerSidebar } = useDrawer();
const hasSidebar = buttons.length > 0;
const theme = useTheme();
const isProminent = theme.information.prominentHeader;
useEffect(() => {
setDrawerSidebarMounted(true);
}, []);
useEffect(() => {
setDrawerSidebarMounted(true);
}, []);
if (!hasSidebar || !showDrawerSidebar) {
return null;
}
// Adding keys to buttons
const clonedButtons = buttons.map((button, index) =>
cloneElement(button, { key: button.key || `sidebar-button-${index}`, style: { '--index': index } })
);
return (
<nav
aria-label={c('Landmarks').t`Side panel`}
className={clsx('drawer-sidebar hidden md:inline no-print', isProminent && 'ui-prominent')}
>
<span className="flex flex-column flex-align-items-center py-3 h-full">
<div className="flex flex-column flex-align-items-center gap-5">{clonedButtons}</div>
</span>
</nav>
);
};
export default DrawerSidebar;
| 5,286
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/DrawerVisibilityButton.scss
|
@import '~@proton/styles/scss/lib';
.drawer-visibility-control {
position: absolute;
z-index: $layer-upper;
inset-block-end: rem(8);
inset-inline-end: 0;
inline-size: rem(46); // same as the drawer sidebar size
block-size: rem(46);
background-color: transparent;
transition: translate 0.15s easing(ease-out-quint);
&--show {
translate: 40%;
&:hover,
&:focus-within {
translate: rem(9);
}
}
&--show &-button {
position: relative;
border-start-end-radius: 0;
border-end-end-radius: 0;
// To enlarge the click area
&::before {
position: absolute;
content: '';
inset-inline-start: -1em;
inset-inline-end: 0;
inset-block: -0.5em;
}
}
&--hide {
// not needed for now
}
@include media('print') {
display: none;
}
}
| 5,287
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/DrawerVisibilityButton.tsx
|
import { MutableRefObject } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms/Button';
import { Icon, Tooltip } from '@proton/components/components';
import { useApi, useDrawer } from '@proton/components/hooks';
import { updateHideDrawer } from '@proton/shared/lib/api/settings';
import { DRAWER_VISIBILITY } from '@proton/shared/lib/interfaces';
import clsx from '@proton/utils/clsx';
import './DrawerVisibilityButton.scss';
interface Props {
spotlightSeenRef?: MutableRefObject<boolean>;
}
const DrawerVisibilityButton = ({ spotlightSeenRef }: Props) => {
const api = useApi();
const { showDrawerSidebar, setShowDrawerSidebar } = useDrawer();
/**
* Set the showDrawerSidebar value by hand instead of using the setting
* so that when the user clicks on the button, the update is instantaneous
*/
const handleClick = () => {
if (spotlightSeenRef && !spotlightSeenRef?.current) {
spotlightSeenRef.current = true;
}
setShowDrawerSidebar(!showDrawerSidebar);
return api(updateHideDrawer(showDrawerSidebar ? DRAWER_VISIBILITY.HIDE : DRAWER_VISIBILITY.SHOW));
};
const tooltipText = showDrawerSidebar ? c('Tooltip').t`Hide side panel` : c('Tooltip').t`Show side panel`;
return (
<Tooltip title={tooltipText} originalPlacement="left">
<span
className={clsx(
'drawer-visibility-control hidden md:flex',
showDrawerSidebar
? 'drawer-visibility-control--hide'
: 'drawer-visibility-control--show ui-standard'
)}
>
<Button
className={clsx('m-auto drawer-visibility-control-button', showDrawerSidebar && 'color-weak')}
size="small"
shape={showDrawerSidebar ? 'ghost' : 'solid'}
color="weak"
icon
onClick={handleClick}
aria-expanded={showDrawerSidebar}
>
<Icon
name={showDrawerSidebar ? 'chevron-right' : 'chevron-left'}
alt={c('Action').t`Show side panel`}
/>
</Button>
</span>
</Tooltip>
);
};
export default DrawerVisibilityButton;
| 5,288
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/index.ts
|
export { default as DrawerApp } from './DrawerApp';
export { default as DrawerSidebar } from './DrawerSidebar';
export { default as CalendarDrawerAppButton } from './drawerAppButtons/CalendarDrawerAppButton';
export { default as ContactDrawerAppButton } from './drawerAppButtons/ContactDrawerAppButton';
export { default as QuickSettingsAppButton } from './drawerAppButtons/QuickSettingsAppButton';
| 5,289
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/drawerAppButtons/CalendarDrawerAppButton.tsx
|
import { c } from 'ttag';
import DrawerAppButton, { Props } from '@proton/components/components/drawer/drawerAppButtons/DrawerAppButton';
import { useDrawer } from '@proton/components/hooks';
import useDynamicMonthDay from '@proton/components/hooks/useDynamicMonthDay';
import { APPS, CALENDAR_APP_NAME } from '@proton/shared/lib/constants';
import { Optional } from '@proton/shared/lib/interfaces';
import { CalendarDrawerLogo } from '../drawerIcons';
const CalendarDrawerAppButton = ({
onClick,
...rest
}: Optional<Omit<Props, 'tooltipText' | 'buttonContent'>, 'onClick'>) => {
const { toggleDrawerApp } = useDrawer();
const monthDay = useDynamicMonthDay();
const handleClick = () => {
onClick?.();
toggleDrawerApp({ app: APPS.PROTONCALENDAR })();
};
return (
<DrawerAppButton
key="toggle-calendar-drawer-app-button"
tooltipText={CALENDAR_APP_NAME}
data-testid="calendar-drawer-app-button:calendar-icon"
buttonContent={<CalendarDrawerLogo monthDay={monthDay} />}
onClick={handleClick}
alt={c('Action').t`Toggle Calendar app`}
aria-controls="drawer-app-iframe-proton-calendar"
{...rest}
/>
);
};
export default CalendarDrawerAppButton;
| 5,290
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/drawerAppButtons/ContactDrawerAppButton.tsx
|
import { c } from 'ttag';
import DrawerAppButton, { Props } from '@proton/components/components/drawer/drawerAppButtons/DrawerAppButton';
import { useDrawer } from '@proton/components/hooks';
import { DRAWER_NATIVE_APPS } from '@proton/shared/lib/drawer/interfaces';
import { Optional } from '@proton/shared/lib/interfaces';
import { ContactsDrawerLogo } from '../drawerIcons';
const ContactDrawerAppButton = ({
onClick,
...rest
}: Optional<Omit<Props, 'tooltipText' | 'buttonContent'>, 'onClick'>) => {
const { toggleDrawerApp } = useDrawer();
const handleClick = () => {
onClick?.();
toggleDrawerApp({ app: DRAWER_NATIVE_APPS.CONTACTS })();
};
return (
<DrawerAppButton
key="toggle-contacts-drawer-app-button"
tooltipText={c('Title').t`Contacts`}
data-testid="contacts-drawer-app-button:contacts-icon"
buttonContent={<ContactsDrawerLogo />}
onClick={handleClick}
alt={c('Action').t`Toggle Contact app`}
aria-controls="drawer-app-proton-contact"
{...rest}
/>
);
};
export default ContactDrawerAppButton;
| 5,291
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/drawerAppButtons/DrawerAppButton.tsx
|
import { ComponentPropsWithRef, ReactNode } from 'react';
import { c } from 'ttag';
import { NotificationDot } from '@proton/atoms/NotificationDot';
import { ThemeColor } from '@proton/colors/types';
import { PopperPlacement, Tooltip } from '@proton/components/components';
import clsx from '@proton/utils/clsx';
export interface Props extends ComponentPropsWithRef<'button'> {
tooltipText: string;
tooltipPlacement?: PopperPlacement;
buttonContent: ReactNode;
onClick: () => void;
/** If specified, renders an sr-only element for screenreaders */
alt?: string;
notificationDotColor?: ThemeColor;
}
const DrawerAppButton = ({
tooltipText,
buttonContent,
onClick,
alt,
notificationDotColor,
tooltipPlacement = 'left',
...rest
}: Props) => {
const button = (
<button
className={clsx(
'drawer-sidebar-button rounded flex interactive no-pointer-events-children relative',
notificationDotColor && 'drawer-sidebar-button--notification'
)}
type="button"
onClick={onClick}
{...rest}
>
{buttonContent}
{notificationDotColor && (
<NotificationDot
className="top right notification-dot--top-right"
color={notificationDotColor}
alt={c('Action').t`Attention required`}
/>
)}
{alt ? <span className="sr-only">{alt}</span> : null}
</button>
);
return (
<Tooltip title={tooltipText} originalPlacement={tooltipPlacement}>
{button}
</Tooltip>
);
};
export default DrawerAppButton;
| 5,292
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/drawerAppButtons/QuickSettingsAppButton.tsx
|
import { c } from 'ttag';
import { ThemeColor } from '@proton/colors/types';
import { Icon } from '@proton/components/components';
import DrawerAppButton, { Props } from '@proton/components/components/drawer/drawerAppButtons/DrawerAppButton';
import { useDrawer } from '@proton/components/hooks';
import useQuickSettingsReminders from '@proton/components/hooks/drawer/useQuickSettingsReminders';
import { DRAWER_NATIVE_APPS } from '@proton/shared/lib/drawer/interfaces';
import { Optional } from '@proton/shared/lib/interfaces';
const QuickSettingsAppButton = ({ onClick }: Optional<Omit<Props, 'tooltipText' | 'buttonContent'>, 'onClick'>) => {
const { toggleDrawerApp } = useDrawer();
const reminders = useQuickSettingsReminders();
const notificationDotColor = [ThemeColor.Danger, ThemeColor.Warning].find((color) => reminders.includes(color));
const handleClick = () => {
onClick?.();
toggleDrawerApp({ app: DRAWER_NATIVE_APPS.QUICK_SETTINGS })();
};
return (
<DrawerAppButton
key="toggle-settings-drawer-app-button"
tooltipText={c('Title').t`Settings`}
tooltipPlacement="bottom"
data-testid="settings-drawer-app-button:settings-icon"
buttonContent={<Icon name="cog-drawer" size={20} />}
onClick={handleClick}
alt={c('Action').t`Toggle settings`}
aria-controls="drawer-app-proton-settings"
notificationDotColor={notificationDotColor}
/>
);
};
export default QuickSettingsAppButton;
| 5,293
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/drawerIcons/CalendarDrawerLogo.tsx
|
import './DrawerIcons.scss';
interface Props {
monthDay: number;
}
const CalendarDrawerLogo = ({ monthDay }: Props) => {
return (
<svg
width="28"
height="28"
viewBox="0 0 28 28"
fill="none"
xmlns="http://www.w3.org/2000/svg"
focusable="false"
aria-hidden="true"
role="img"
>
<path d="M10 11H20V18.5C20 19.8807 18.8807 21 17.5 21H10V11Z" fill="white"></path>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M4 7C4 5.89543 4.89543 5 6 5H22C23.1046 5 24 5.89543 24 7V21C24 22.1046 23.1046 23 22 23H6C4.89543 23 4 22.1046 4 21V7Z"
fill="url(#paint0_linear_20431_3019)"
/>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M4 7C4 5.89543 4.89543 5 6 5H22C23.1046 5 24 5.89543 24 7V21C24 22.1046 23.1046 23 22 23H6C4.89543 23 4 22.1046 4 21V7Z"
fill="url(#paint1_radial_20431_3019)"
/>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M6 5C4.89543 5 4 5.89543 4 7V8H18.5C19.3284 8 20 8.67157 20 9.5V23H22C23.1046 23 24 22.1046 24 21V7C24 5.89543 23.1046 5 22 5H6Z"
fill="url(#paint2_linear_20431_3019)"
/>
{/* <path d="M10.2037 18.36C11.5637 18.36 12.6137 17.58 12.6137 16.42C12.6137 15.37 11.8737 14.86 11.3037 14.73V14.71C11.7337 14.58 12.3837 14.07 12.3837 13.16C12.3837 12.06 11.4737 11.33 10.1737 11.33C8.51367 11.33 7.87367 12.54 7.82367 13.37H9.13367C9.19367 12.88 9.52367 12.46 10.1637 12.46C10.7137 12.46 11.1337 12.79 11.1337 13.33C11.1337 13.88 10.7137 14.2 9.88367 14.2H9.41367V15.33H9.98367C10.8237 15.33 11.3537 15.65 11.3537 16.26C11.3537 16.84 10.8837 17.23 10.2037 17.23C9.53367 17.23 9.09367 16.82 8.98367 16.28H7.62367C7.71367 17.48 8.70367 18.36 10.2037 18.36ZM13.3554 12.55V13.85L14.7054 12.9V18.25H15.9754V11.43H14.9654L13.3554 12.55Z" fill="white" /> */}
<text x="7" y="19" textAnchor="middle" className="drawer-icons__calendar__day">
<tspan x="12" dy="0">
{monthDay}
</tspan>
</text>
<defs>
<linearGradient
id="paint0_linear_20431_3019"
x1="14"
y1="-2.19145"
x2="15.6098"
y2="18.8353"
gradientUnits="userSpaceOnUse"
>
<stop offset="0.988738" stopColor="#6D4AFF" />
</linearGradient>
<radialGradient
id="paint1_radial_20431_3019"
cx="0"
cy="0"
r="1"
gradientUnits="userSpaceOnUse"
gradientTransform="translate(17.6207 -4.1875) rotate(108.899) scale(30.7846 38.4447)"
>
<stop offset="0.556057" stopColor="#54B7FF" stopOpacity="0" />
<stop offset="0.994421" stopColor="#54B7FF" />
</radialGradient>
<linearGradient
id="paint2_linear_20431_3019"
x1="27.75"
y1="34.25"
x2="2.31473"
y2="-8.97937"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#C8E8FF" />
<stop offset="0.410661" stopColor="#BDAEFF" />
<stop offset="0.774813" stopColor="#6D4AFF" />
</linearGradient>
</defs>
</svg>
);
};
export default CalendarDrawerLogo;
| 5,294
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/drawerIcons/ContactsDrawerLogo.tsx
|
const CalendarDrawerLogo = () => {
return (
<svg
width="28"
height="28"
fill="none"
xmlns="http://www.w3.org/2000/svg"
focusable="false"
aria-hidden="true"
role="img"
>
<path d="M24 8a3 3 0 0 0-3-3H8v18h13a3 3 0 0 0 3-3V8Z" fill="url(#a)" />
<path d="M24 8a3 3 0 0 0-3-3H8v18h13a3 3 0 0 0 3-3V8Z" fill="url(#b)" />
<path d="M8 5H7a3 3 0 0 0-3 3v12a3 3 0 0 0 3 3h1V5Z" fill="url(#c)" />
<path
d="M15.765 10.874c0 1.034-.81 1.873-1.81 1.873-.998 0-1.809-.839-1.809-1.873 0-1.035.81-1.874 1.81-1.874s1.81.839 1.81 1.874Zm-5.59 4.951c-.524.979.194 2.175 1.269 2.175h5.024c1.075 0 1.793-1.204 1.268-2.175-.735-1.38-2.156-2.308-3.78-2.308-1.624 0-3.045.937-3.78 2.308Zm9.225 1.228h-1.053c.18-.398.193-.875-.04-1.307a4.422 4.422 0 0 0-1.343-1.529c.25-.074.512-.114.783-.114 1.069 0 2.004.61 2.487 1.519.346.638-.127 1.43-.834 1.43Zm-1.653-3.456c.658 0 1.19-.552 1.19-1.233 0-.68-.532-1.232-1.19-1.232-.657 0-1.19.551-1.19 1.232 0 .681.533 1.233 1.19 1.233Z"
fill="#fff"
/>
<defs>
<linearGradient id="a" x1="14.893" y1="6" x2="14.893" y2="22" gradientUnits="userSpaceOnUse">
<stop stopColor="#FFB341" />
<stop offset="1" stopColor="#EE7C3E" />
</linearGradient>
<linearGradient id="c" x1="5.5" y1="4" x2="5.5" y2="24" gradientUnits="userSpaceOnUse">
<stop stopColor="#EF8A41" />
<stop offset="1" stopColor="#CE5B36" />
</linearGradient>
<radialGradient
id="b"
cx="0"
cy="0"
r="1"
gradientUnits="userSpaceOnUse"
gradientTransform="matrix(0 6 -5.91964 0 15 14)"
>
<stop stopColor="#EE7C3E" />
<stop offset="1" stopColor="#EE7C3E" stopOpacity="0" />
</radialGradient>
</defs>
</svg>
);
};
export default CalendarDrawerLogo;
| 5,295
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/drawerIcons/DrawerIcons.scss
|
.drawer-icons__calendar__day {
font-size: 0.67em;
font-weight: var(--font-weight-semibold);
fill: white;
text-align: center;
}
| 5,296
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/drawerIcons/index.ts
|
export { default as CalendarDrawerLogo } from './CalendarDrawerLogo';
export { default as ContactsDrawerLogo } from './ContactsDrawerLogo';
| 5,297
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/views/DrawerContactView.tsx
|
import { useRef, useState } from 'react';
import { c } from 'ttag';
import { EasySwitchProvider } from '@proton/activation';
import { Button } from '@proton/atoms/Button';
import { PrimaryButton } from '@proton/components/components';
import DrawerView, { SelectedDrawerOption } from '@proton/components/components/drawer/views/DrawerView';
import { useModalTwo } from '@proton/components/components/modalTwo/useModalTwo';
import { useContactModals } from '@proton/components/containers';
import { useContactMergeModals } from '@proton/components/containers/contacts/hooks/useContactMergeModals';
import ContactImportModal from '@proton/components/containers/contacts/import/ContactImportModal';
import ContactsWidgetContainer from '@proton/components/containers/contacts/widget/ContactsWidgetContainer';
import ContactsWidgetGroupsContainer from '@proton/components/containers/contacts/widget/ContactsWidgetGroupsContainer';
import ContactsWidgetSettingsContainer from '@proton/components/containers/contacts/widget/ContactsWidgetSettingsContainer';
import { CONTACT_WIDGET_TABS, CustomAction } from '@proton/components/containers/contacts/widget/types';
import { useUser } from '@proton/components/hooks';
import useDrawerContactFocus from '@proton/components/hooks/useDrawerContactFocus';
import { Recipient } from '@proton/shared/lib/interfaces';
import noop from '@proton/utils/noop';
export enum CONTACT_TAB {
CONTACT = 'contact',
CONTACT_GROUP = 'contact-group',
SETTINGS = 'settings',
}
interface Props {
onCompose?: (recipients: Recipient[], attachments: File[]) => void;
onMailTo?: (src: string) => void;
customActions?: CustomAction[];
}
const DrawerContactView = ({ onCompose, onMailTo = noop, customActions = [] }: Props) => {
const [{ hasPaidMail }] = useUser();
const searchInputRef = useRef<HTMLInputElement>(null);
const options: SelectedDrawerOption[] = [
{ text: c('Title').t`Contacts`, value: CONTACT_TAB.CONTACT },
{ text: c('Title').t`Groups`, value: CONTACT_TAB.CONTACT_GROUP },
{ text: c('Title').t`Settings`, value: CONTACT_TAB.SETTINGS },
];
const [tab, setTab] = useState<SelectedDrawerOption>(options[0]);
const [importModal, onImport] = useModalTwo<void, void>(ContactImportModal, false);
const { modals: mergeModals, onMerge } = useContactMergeModals();
const { onFocusSearchInput } = useDrawerContactFocus(searchInputRef, tab);
const {
modals,
onDetails,
onEdit,
onDelete,
onExport,
onGroupDetails,
onGroupEdit,
onGroupDelete,
onUpgrade,
onSelectEmails,
onLimitReached,
} = useContactModals({ onMailTo, onCompose });
const handleDetails = (contactID: string) => {
void onDetails(contactID);
};
const handleAddContactGroup = () => {
if (hasPaidMail) {
onGroupEdit({});
} else {
onUpgrade();
}
};
const actionIncludes = (tab: CONTACT_WIDGET_TABS) => (customAction: CustomAction) =>
customAction.tabs.includes(tab);
const getContent = (tab: CONTACT_TAB) => {
switch (tab) {
case CONTACT_TAB.CONTACT:
return (
<ContactsWidgetContainer
onCompose={onCompose}
customActions={customActions.filter(actionIncludes(CONTACT_WIDGET_TABS.CONTACTS))}
onDetails={handleDetails}
onEdit={onEdit}
onDelete={onDelete}
onImport={onImport}
onMerge={onMerge}
onGroupDetails={onGroupDetails}
onGroupEdit={onGroupEdit}
onUpgrade={onUpgrade}
onSelectEmails={onSelectEmails}
onLimitReached={onLimitReached}
isDrawer
searchInputRef={searchInputRef}
/>
);
case CONTACT_TAB.CONTACT_GROUP:
return (
<ContactsWidgetGroupsContainer
onCompose={onCompose}
onImport={onImport}
customActions={customActions.filter(actionIncludes(CONTACT_WIDGET_TABS.GROUPS))}
onDetails={onGroupDetails}
onEdit={onGroupEdit}
onDelete={onGroupDelete}
onUpgrade={onUpgrade}
isDrawer
/>
);
case CONTACT_TAB.SETTINGS:
return <ContactsWidgetSettingsContainer onImport={onImport} onExport={onExport} />;
}
};
const getFooterButtons = (tab: CONTACT_TAB) => {
switch (tab) {
case CONTACT_TAB.CONTACT:
return [
<PrimaryButton
data-testid="contacts:add-contact"
key="footer-button-1"
onClick={() => onEdit({})}
>{c('Action').t`Add contact`}</PrimaryButton>,
<Button key="footer-button-2" onClick={() => onImport()}>{c('Action').t`Import contacts`}</Button>,
];
case CONTACT_TAB.CONTACT_GROUP:
return [
<PrimaryButton
data-testid="groups:add-group"
key="footer-button-1"
onClick={() => handleAddContactGroup()}
>{c('Action').t`Add new group`}</PrimaryButton>,
];
case CONTACT_TAB.SETTINGS:
return undefined;
}
};
return (
<EasySwitchProvider>
<DrawerView
tab={tab}
onSelectDrawerOption={setTab}
options={options}
content={getContent(tab.value as CONTACT_TAB)}
footerButtons={getFooterButtons(tab.value as CONTACT_TAB)}
onAnimationEnd={onFocusSearchInput}
id="drawer-app-proton-contact"
/>
{modals}
{importModal}
{mergeModals}
</EasySwitchProvider>
);
};
export default DrawerContactView;
| 5,298
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/views/DrawerHeaderTitleDropdown.tsx
|
import {
Dropdown,
DropdownButton,
DropdownMenu,
DropdownMenuButton,
usePopperAnchor,
} from '@proton/components/components';
import { SelectedDrawerOption } from '@proton/components/components/drawer/views/DrawerView';
import clsx from '@proton/utils/clsx';
interface Props {
title: string;
options: SelectedDrawerOption[];
onClickOption?: (value: SelectedDrawerOption) => void;
}
const DrawerHeaderTitleDropdown = ({ title, options, onClickOption }: Props) => {
const { anchorRef, isOpen, toggle, close } = usePopperAnchor<HTMLButtonElement>();
return (
<>
<DropdownButton
type="button"
ref={anchorRef}
isOpen={isOpen}
onClick={toggle}
hasCaret
shape="ghost"
size="small"
className={clsx(['drawer-header-button'])}
data-testid="drawer-app-header-actions:dropdown"
>
{title}
</DropdownButton>
<Dropdown isOpen={isOpen} anchorRef={anchorRef} onClose={close}>
<DropdownMenu className="flex-item-noshrink">
{options.map((option, index) => (
<DropdownMenuButton
className="text-left flex flex-nowrap flex-align-items-center"
onClick={() => onClickOption?.(option)}
key={index}
data-testid={`drawer-app-header-actions:${option.text}`}
>
<span className="ml-2 my-auto flex-item-fluid">{option.text}</span>
</DropdownMenuButton>
))}
</DropdownMenu>
</Dropdown>
</>
);
};
export default DrawerHeaderTitleDropdown;
| 5,299
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.