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/drawer
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/views/DrawerSettingsView.tsx
|
import { ReactNode } from 'react';
import { c } from 'ttag';
import DrawerView, { SelectedDrawerOption } from '@proton/components/components/drawer/views/DrawerView';
import DefaultQuickSettings from '@proton/components/components/drawer/views/quickSettings/DefaultQuickSettings';
import './quickSettings/QuickSettings.scss';
interface Props {
customAppSettings?: ReactNode;
}
const DrawerSettingsView = ({ customAppSettings }: Props) => {
const tab: SelectedDrawerOption = {
text: c('Title').t`Settings`,
value: 'settings',
};
const defaultSettings = (
<div className="p-4 flex flex-column gap-2 scroll-if-needed">
<DefaultQuickSettings />
</div>
);
return (
<DrawerView
tab={tab}
content={customAppSettings ? customAppSettings : defaultSettings}
id="drawer-app-proton-settings"
className="quickSettings"
/>
);
};
export default DrawerSettingsView;
| 5,300
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/views/DrawerView.tsx
|
import { AnimationEvent, HTMLAttributes, ReactNode } from 'react';
import DrawerHeaderTitleDropdown from '@proton/components/components/drawer/views/DrawerHeaderTitleDropdown';
import { DrawerAppFooter, DrawerAppHeader } from '@proton/components/containers';
import clsx from '@proton/utils/clsx';
export interface SelectedDrawerOption {
text: string;
value: string;
}
interface Props extends Omit<HTMLAttributes<HTMLElement>, 'content'> {
tab: SelectedDrawerOption;
onSelectDrawerOption?: (option: SelectedDrawerOption) => void;
options?: SelectedDrawerOption[];
content: ReactNode;
footerButtons?: JSX.Element[];
onAnimationEnd?: () => void;
}
const DrawerView = ({
options,
tab,
onSelectDrawerOption,
content,
footerButtons,
onAnimationEnd,
className,
...rest
}: Props) => {
const drawerHeaderTitle = options ? (
<DrawerHeaderTitleDropdown title={tab.text} options={options} onClickOption={onSelectDrawerOption} />
) : (
tab.text
);
// The opening animation is creating flickers when we want to autofocus an input
// We need to perform the focus action once the animation has ended
const handleOnAnimationEnd = ({ animationName }: AnimationEvent) => {
if (animationName.includes('drawer-app-view')) {
onAnimationEnd?.();
}
};
return (
<div
className={clsx('drawer-app-view h-full w-full flex flex-column', className)}
onAnimationEnd={handleOnAnimationEnd}
{...rest}
>
<DrawerAppHeader title={drawerHeaderTitle} />
<div className="flex-item-fluid contacts-widget w-full">{content}</div>
{footerButtons && <DrawerAppFooter buttons={footerButtons} />}
</div>
);
};
export default DrawerView;
| 5,301
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/views
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/views/quickSettings/DefaultQuickSettings.tsx
|
import { ChangeEvent } from 'react';
import { c } from 'ttag';
import { Info, Toggle, Tooltip } from '@proton/components/components';
import { ThemeCards, useTheme } from '@proton/components/containers';
import ThemeSyncModeDropdown from '@proton/components/containers/themes/ThemeSyncModeDropdown';
import { useEarlyAccess, useNotifications } from '@proton/components/hooks';
import { useLoading } from '@proton/hooks';
import { BRAND_NAME } from '@proton/shared/lib/constants';
import { QuickSettingsReminders } from '@proton/shared/lib/drawer/interfaces';
import { wait } from '@proton/shared/lib/helpers/promise';
import { ColorScheme, PROTON_THEMES_MAP, ThemeModeSetting, getThemes } from '@proton/shared/lib/themes/themes';
import QuickSettingsRemindersSection from './QuickSettingsRemindersSection';
import QuickSettingsSection from './QuickSettingsSection';
import QuickSettingsSectionHeadline from './QuickSettingsSectionHeadline';
import QuickSettingsSectionRow from './QuickSettingsSectionRow';
interface Props {
inAppReminders?: QuickSettingsReminders[];
}
const DefaultQuickSettings = ({ inAppReminders }: Props) => {
const { information, settings, setTheme, setAutoTheme } = useTheme();
const themes = getThemes();
const { createNotification } = useNotifications();
const earlyAccess = useEarlyAccess();
const [betaToggleLoading, betaToggleWithLoading] = useLoading(false);
const handleChangeEarlyAccess = async (e: ChangeEvent<HTMLInputElement>) => {
await earlyAccess.update(e.target.checked);
const run = async () => {
await wait(800);
window.location.reload();
};
void betaToggleWithLoading(run());
};
return (
<>
<QuickSettingsSection className="pb-4">
<div>
{settings.Mode === ThemeModeSetting.Auto ? (
<>
<QuickSettingsSectionHeadline>{c('Label').t`Theme`}</QuickSettingsSectionHeadline>
</>
) : (
<>
<QuickSettingsSectionHeadline>
{c('Label').t`Theme`}:
<span
className="color-weak ml-1 text-no-bold"
data-testid="drawer-quick-settings:current-theme"
>
{PROTON_THEMES_MAP[information.theme].label}
</span>
</QuickSettingsSectionHeadline>
</>
)}
</div>
{
<QuickSettingsSectionRow
label={c('Label').t`Sync with system`}
labelInfo={
<Info
title={c('Tooltip')
.t`Automatically switch between your preferred themes for day and night in sync with your system’s day and night modes`}
/>
}
action={
<Toggle
id="themeSyncToggle"
className="ml-6"
checked={settings.Mode === ThemeModeSetting.Auto}
onChange={(e) => setAutoTheme(e.target.checked)}
data-testid="drawer-quick-settings:auto-theme-toggle"
/>
}
/>
}
{settings.Mode === ThemeModeSetting.Auto ? (
<div className="flex-no-min-children flex-column gap-4 mt-1">
<ThemeSyncModeDropdown
mode="light"
list={themes}
themeIdentifier={settings.LightTheme}
onChange={(themeType) => {
setTheme(themeType, ThemeModeSetting.Light);
createNotification({ text: c('Success').t`Preference saved` });
}}
active={information.colorScheme === ColorScheme.Light}
className="flex-item-noflex"
/>
<ThemeSyncModeDropdown
mode="dark"
list={themes}
themeIdentifier={settings.DarkTheme}
onChange={(themeType) => {
setTheme(themeType, ThemeModeSetting.Dark);
createNotification({ text: c('Success').t`Preference saved` });
}}
active={information.colorScheme === ColorScheme.Dark}
className="flex-item-noflex"
/>
</div>
) : (
<ThemeCards
list={themes}
themeIdentifier={information.theme}
size="medium"
onChange={(themeType) => {
setTheme(themeType);
createNotification({ text: c('Success').t`Preference saved` });
}}
/>
)}
</QuickSettingsSection>
<Tooltip
title={c('Info')
.t`Try new ${BRAND_NAME} features, updates and products before they are released to the public. This will reload the application`}
>
{/* additional div needed for tooltip */}
<div className="w-full flex-item-noshrink">
<QuickSettingsSection>
<QuickSettingsSectionRow
label={c('Label').t`Beta Access`}
action={
<Toggle
id="toggle-early-access"
loading={betaToggleLoading}
checked={earlyAccess.value}
onChange={handleChangeEarlyAccess}
data-testid="drawer-quick-settings:beta-access-toggle"
/>
}
/>
</QuickSettingsSection>
</div>
</Tooltip>
<QuickSettingsRemindersSection inAppReminders={inAppReminders} />
</>
);
};
export default DefaultQuickSettings;
| 5,302
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/views
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/views/quickSettings/DrawerAllSettingsView.tsx
|
import { c } from 'ttag';
import ButtonLike from '@proton/atoms/Button/ButtonLike';
import { SettingsLink } from '@proton/components/components';
import { useConfig } from '@proton/components/hooks';
const DrawerAllSettingsView = () => {
const { APP_NAME } = useConfig();
return (
<ButtonLike
as={SettingsLink}
path="/"
app={APP_NAME}
data-testid="drawer-quick-settings:all-settings-button"
className="w-full"
color="norm"
shape="outline"
>{c('Title').t`All settings`}</ButtonLike>
);
};
export default DrawerAllSettingsView;
| 5,303
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/views
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/views/quickSettings/QuickSettings.scss
|
.quickSettings {
background-color: var(--background-lowered, var(--bg-weak));
.header--drawer,
.footer {
background-color: var(--background-lowered, var(--bg-weak));
}
}
| 5,304
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/views
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/views/quickSettings/QuickSettingsButton.tsx
|
import { ReactNode, Ref, forwardRef } from 'react';
interface Props {
children: ReactNode;
onClick: () => void;
}
const QuickSettingsButton = ({ onClick, children, ...rest }: Props, ref: Ref<HTMLButtonElement>) => {
return (
<button
onClick={onClick}
type="button"
className="color-weak text-no-decoration hover:text-underline flex flex-nowrap flex-justify-center text-sm mx-auto"
ref={ref}
{...rest}
>
{children}
</button>
);
};
export default forwardRef(QuickSettingsButton);
| 5,305
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/views
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/views/quickSettings/QuickSettingsButtonSection.tsx
|
import { ReactNode } from 'react';
import clsx from '@proton/utils/clsx';
interface Props {
children: ReactNode;
className?: string;
}
const QuickSettingsButtonSection = ({ children, className }: Props) => {
return (
<div
className={clsx(
'quickSettingsButtonSection mt-auto w-full flex-no-min-children flex-column flex-item-noshrink flex-justify-center gap-2',
className
)}
>
{children}
</div>
);
};
export default QuickSettingsButtonSection;
| 5,306
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/views
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/views/quickSettings/QuickSettingsMain.tsx
|
import { ReactNode } from 'react';
import { Scroll } from '@proton/atoms/Scroll';
import './QuickSettings.scss';
interface Props {
children: ReactNode;
}
const QuickSettingsMain = ({ children }: Props) => {
return (
<Scroll>
<div className="h-full p-3 pt-0.5 flex-no-min-children flex-column flex-nowrap flex-align-items-start gap-3">
{children}
</div>
</Scroll>
);
};
export default QuickSettingsMain;
| 5,307
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/views
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/views/quickSettings/QuickSettingsReminder.tsx
|
import { c } from 'ttag';
import { Button } from '@proton/atoms/Button';
import { ThemeColor } from '@proton/colors/types';
import { Icon } from '@proton/components/components';
import { QuickSettingsReminders } from '@proton/shared/lib/drawer/interfaces';
import clsx from '@proton/utils/clsx';
interface Props {
reminder: QuickSettingsReminders;
}
const QuickSettingsReminder = ({ reminder }: Props) => {
return (
<Button key={reminder.text} shape="ghost" fullWidth className="py-2 px-3" onClick={reminder.callback}>
<span className="flex flex-align-items-center gap-2">
{reminder.icon && (
<span className={clsx('flex flex-item-noshrink', reminder.color && `color-${reminder.color}`)}>
<Icon name={reminder.icon} alt={c('Action').t`Attention required`} />
</span>
)}
<span
className={clsx(
'flex-item-fluid text-left text-ellipsis',
reminder.color === ThemeColor.Danger && 'color-danger'
)}
>
{reminder.text}
</span>
</span>
</Button>
);
};
export default QuickSettingsReminder;
| 5,308
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/views
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/views/quickSettings/QuickSettingsRemindersSection.tsx
|
import { useMemo } from 'react';
import { useSettingsLink } from '@proton/components/components';
import QuickSettingsReminder from '@proton/components/components/drawer/views/quickSettings/QuickSettingsReminder';
import QuickSettingsSection from '@proton/components/components/drawer/views/quickSettings/QuickSettingsSection';
import { useRecoveryNotification } from '@proton/components/hooks';
import { QuickSettingsReminders } from '@proton/shared/lib/drawer/interfaces';
import isTruthy from '@proton/utils/isTruthy';
interface Props {
inAppReminders?: QuickSettingsReminders[];
}
const QuickSettingsRemindersSection = ({ inAppReminders = [] }: Props) => {
const goToSettings = useSettingsLink();
const insideDropdownRecoveryNotification = useRecoveryNotification(false);
const reminders: QuickSettingsReminders[] = useMemo(() => {
const recoveryNotificationReminder: QuickSettingsReminders | undefined = insideDropdownRecoveryNotification
? {
text: insideDropdownRecoveryNotification.text,
icon: 'exclamation-circle-filled',
color: insideDropdownRecoveryNotification.color,
callback: () => goToSettings(insideDropdownRecoveryNotification.path),
testID: 'recovery',
}
: undefined;
return [...inAppReminders, recoveryNotificationReminder].filter(isTruthy);
}, [insideDropdownRecoveryNotification, inAppReminders]);
if (reminders.length === 0) {
return null;
}
return (
<QuickSettingsSection>
{reminders.map((reminder) => {
return (
<QuickSettingsReminder
reminder={reminder}
key={reminder.text}
data-testid={`drawer-quick-settings:${reminder.testID}-button`}
/>
);
})}
</QuickSettingsSection>
);
};
export default QuickSettingsRemindersSection;
| 5,309
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/views
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/views/quickSettings/QuickSettingsSection.scss
|
@import '~@proton/styles/scss/lib';
.quickSettingsSection {
background-color: var(--background-elevated, var(--bg-norm));
min-block-size: rem(40);
}
| 5,310
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/views
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/views/quickSettings/QuickSettingsSection.tsx
|
import { ReactNode } from 'react';
import clsx from '@proton/utils/clsx';
import './QuickSettingsSection.scss';
interface Props {
children: ReactNode;
className?: string;
}
const QuickSettingsSection = ({ children, className }: Props) => {
return (
<div
className={clsx(
'quickSettingsSection w-full flex-no-min-children flex-column gap-2 flex-item-noshrink flex-justify-center px-4 py-2 rounded-lg shadow-norm',
className
)}
>
{children}
</div>
);
};
export default QuickSettingsSection;
| 5,311
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/views
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/views/quickSettings/QuickSettingsSectionHeadline.tsx
|
import { ReactNode } from 'react';
interface Props {
children: ReactNode;
}
const QuickSettingsSectionHeadline = ({ children }: Props) => {
return <h3 className="flex-item-fluid text-rg text-bold mt-1">{children}</h3>;
};
export default QuickSettingsSectionHeadline;
| 5,312
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/views
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/views/quickSettings/QuickSettingsSectionRow.scss
|
@import '~@proton/styles/scss/lib';
@import '~@proton/styles/scss/base/interactive';
.quickSettingsSectionRow {
min-block-size: rem(32);
&:not(:only-child) {
padding-block: var(--space-1);
}
&-action {
.toggle-label {
line-height: 0;
}
}
.select-unstyled {
@extend .interactive-pseudo-protrude;
@extend .interactive--no-background;
color: var(--link-norm);
position: relative;
outline: none !important;
&:hover {
color: var(--link-hover);
}
&[aria-expanded='true'],
&:focus-visible {
color: var(--link-active);
}
}
}
| 5,313
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/views
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/views/quickSettings/QuickSettingsSectionRow.tsx
|
import { ReactNode } from 'react';
import './QuickSettingsSectionRow.scss';
interface Props {
label: string;
labelInfo?: ReactNode;
action: ReactNode;
}
const QuickSettingsSectionRow = ({ label, labelInfo, action }: Props) => {
return (
<label className="quickSettingsSectionRow flex flex-nowrap flex-justify-space-between flex-align-items-center gap-2 w-full">
<span className="flex flex-align-items-center gap-2">
<span className="flex-item-fluid text-left text-ellipsis">{label}</span>
{labelInfo}
</span>
<span className="quickSettingsSectionRow-action flex-item-noshrink">{action}</span>
</label>
);
};
export default QuickSettingsSectionRow;
| 5,314
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/views
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drawer/views/quickSettings/index.ts
|
export { default as DefaultQuickSettings } from './DefaultQuickSettings';
export { default as QuickSettingsMain } from './QuickSettingsMain';
export { default as QuickSettingsSection } from './QuickSettingsSection';
export { default as QuickSettingsButton } from './QuickSettingsButton';
export { default as QuickSettingsButtonSection } from './QuickSettingsButtonSection';
export { default as QuickSettingsSectionRow } from './QuickSettingsSectionRow';
export { default as QuickSettingsSectionHeadline } from './QuickSettingsSectionHeadline';
| 5,315
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drive
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drive/revisions/RevisionsUpgradeBanner.tsx
|
import { c } from 'ttag';
import { ButtonLike } from '@proton/atoms';
import { AppLink } from '@proton/components';
import { APPS } from '@proton/shared/lib/constants';
const RevisionsUpgradeBanner = () => {
return (
<div
className="bg-weak p-4 rounded flex flex-align-items-center flex-justify-space-between"
data-testid="revisions-upgrade-banner"
>
<p className="mx-0 my-1">{c('Info').t`Your plan is limited to 10 versions for up to 7 days`}</p>
<ButtonLike
className="my-1"
as={AppLink}
to="/drive/upgrade"
toApp={APPS.PROTONACCOUNT}
color="norm"
size="small"
>{c('Action').t`Upgrade`}</ButtonLike>
</div>
);
};
export default RevisionsUpgradeBanner;
| 5,316
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drive
|
petrpan-code/ProtonMail/WebClients/packages/components/components/drive/revisions/index.ts
|
export { default as RevisionsUpgradeBanner } from './RevisionsUpgradeBanner';
| 5,317
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/dropdown/Dropdown.test.tsx
|
import { ReactNode, useRef, useState } from 'react';
import { fireEvent, render } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { DropdownProps, DropdownSizeUnit } from '@proton/components/components';
import Dropdown from './Dropdown';
import DropdownButton from './DropdownButton';
const Test = ({
children,
dropdownProps,
...rest
}: {
children: ReactNode;
dropdownProps?: any;
[key: string]: any;
}) => {
const anchorRef = useRef<HTMLButtonElement>(null);
const [open, setOpen] = useState(false);
return (
<>
<DropdownButton
ref={anchorRef}
isOpen={open}
onClick={() => {
setOpen(true);
}}
{...rest}
>
Open
</DropdownButton>
<Dropdown
isOpen={open}
anchorRef={anchorRef}
onClose={() => {
setOpen(false);
}}
{...dropdownProps}
>
{children}
</Dropdown>
</>
);
};
describe('<Dropdown />', () => {
it('should show a dropdown when opened', async () => {
const { getByTestId, queryByTestId } = render(
<Test data-testid="dropdown-open">
<div data-testid="dropdown-inner">Hello world</div>
</Test>
);
expect(queryByTestId('dropdown-inner')).toBeNull();
await userEvent.click(getByTestId('dropdown-open'));
expect(getByTestId('dropdown-inner')).toBeVisible();
});
it('should auto close when open', async () => {
const { getByTestId, queryByTestId } = render(
<div>
<div data-testid="outside">outside dropdown</div>
<Test data-testid="dropdown-open" dropdownProps={{ 'data-testid': 'dropdown' }}>
<div data-testid="dropdown-inner">Hello world</div>
</Test>
</div>
);
await userEvent.click(getByTestId('dropdown-open'));
expect(getByTestId('dropdown')).toBeVisible();
await userEvent.click(getByTestId('outside'));
fireEvent.animationEnd(getByTestId('dropdown'), { animationName: 'anime-dropdown-out' });
expect(queryByTestId('dropdown-test')).toBeNull();
});
describe('dropdown size', () => {
const Test = (props: { size: DropdownProps['size'] }) => {
const ref = useRef<HTMLDivElement>(null);
return (
<Dropdown anchorRef={ref} isOpen={true} data-testid="dropdown" {...props}>
hello
</Dropdown>
);
};
it('should should set initial on viewport max size', async () => {
const { getByTestId } = render(
<Test size={{ maxWidth: DropdownSizeUnit.Viewport, maxHeight: DropdownSizeUnit.Viewport }} />
);
expect(getByTestId('dropdown')).toHaveStyle('--custom-max-width: initial; --custom-max-height: initial');
});
it('should should set custom max height', async () => {
const { getByTestId } = render(<Test size={{ maxWidth: DropdownSizeUnit.Viewport, maxHeight: '13em' }} />);
expect(getByTestId('dropdown')).toHaveStyle('--custom-max-width: initial; --custom-max-height: 13em');
});
it('should should set custom height', async () => {
const { getByTestId } = render(
<Test size={{ height: '15px', maxWidth: DropdownSizeUnit.Viewport, maxHeight: '13em' }} />
);
expect(getByTestId('dropdown')).toHaveStyle(
'--height: 15px; --custom-max-width: initial; --custom-max-height: 13em'
);
});
it('should should set custom width', async () => {
const { getByTestId } = render(
<Test
size={{
width: '13px',
height: '15px',
maxWidth: '13em',
maxHeight: DropdownSizeUnit.Viewport,
}}
/>
);
expect(getByTestId('dropdown')).toHaveStyle(
'--width: 13px; --height: 15px; --custom-max-width: 13em; --custom-max-height: initial'
);
});
});
});
| 5,318
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/dropdown/Dropdown.tsx
|
import {
AnimationEvent,
CSSProperties,
HTMLAttributes,
MouseEvent as ReactMouseEvent,
ReactNode,
RefObject,
useEffect,
useRef,
useState,
} from 'react';
import { c } from 'ttag';
import { useCombinedRefs } from '@proton/hooks';
import { dropdownRootClassName } from '@proton/shared/lib/busy';
import clsx from '@proton/utils/clsx';
import noop from '@proton/utils/noop';
import { HotkeyTuple, useDropdownArrowNavigation, useElementRect, useHotkeys, useIsClosing } from '../../hooks';
import { useFocusTrap } from '../focus';
import { PopperPlacement, PopperPosition, allPopperPlacements, usePopper } from '../popper';
import Portal from '../portal/Portal';
import { DropdownSize, DropdownSizeUnit, getHeightValue, getMaxSizeValue, getProp, getWidthValue } from './utils';
interface ContentProps extends HTMLAttributes<HTMLDivElement> {
ref?: RefObject<HTMLDivElement>;
}
export interface DropdownProps extends HTMLAttributes<HTMLDivElement> {
anchorRef: RefObject<HTMLElement>;
anchorPosition?: PopperPosition | null;
children: ReactNode;
className?: string;
style?: CSSProperties;
onClose?: (event?: ReactMouseEvent<HTMLDivElement> | Event) => void;
onClosed?: () => void;
onContextMenu?: (event: ReactMouseEvent<HTMLDivElement, MouseEvent>) => void;
originalPlacement?: PopperPlacement;
disableFocusTrap?: boolean;
isOpen?: boolean;
size?: DropdownSize;
noCaret?: boolean;
adaptiveForTouchScreens?: boolean;
availablePlacements?: PopperPlacement[];
offset?: number;
autoClose?: boolean;
autoCloseOutside?: boolean;
autoCloseOutsideAnchor?: boolean;
contentProps?: ContentProps;
disableDefaultArrowNavigation?: boolean;
}
const Dropdown = ({
anchorRef,
anchorPosition,
children,
className,
style,
originalPlacement = 'bottom',
availablePlacements = allPopperPlacements,
offset = 8,
onClose = noop,
onClosed,
onContextMenu = noop,
isOpen = false,
size,
noCaret = false,
adaptiveForTouchScreens = true,
disableFocusTrap = false,
autoClose = true,
autoCloseOutside = true,
autoCloseOutsideAnchor = true,
contentProps,
disableDefaultArrowNavigation = false,
...rest
}: DropdownProps) => {
const [popperEl, setPopperEl] = useState<HTMLDivElement | null>(null);
const anchorRect = useElementRect(isOpen && size?.width === DropdownSizeUnit.Anchor ? anchorRef : null);
const {
floating,
position,
arrow,
placement,
availableSize: varAvailableSize,
} = usePopper({
reference:
anchorPosition || anchorPosition === null
? {
mode: 'position',
value: anchorPosition,
anchor: anchorRef.current,
}
: {
mode: 'element',
value: anchorRef.current,
},
isOpen,
originalPlacement,
availablePlacements,
availableSize: true,
offset,
});
/*
* It seems that inputs of type radio trigger a synthetic click event when navigating them via keyboard.
* For the use-case where we want to auto-close the dropdown but not close the dropdown
* when navigating radio inputs inside of the dropdown, we can verify clientX & ClientY of the MouseEvent
* as the synthetically generated click event contains 0 for these value.
*/
const handleClickContent = (event: ReactMouseEvent<HTMLDivElement>) => {
const isRealClick = event.clientX !== 0 && event.clientY !== 0;
if (isRealClick && autoClose) {
onClose(event);
}
};
const rootRef = useRef<HTMLDivElement>(null);
const combinedDropdownRef = useCombinedRefs<HTMLDivElement>(rootRef, setPopperEl, floating);
const contentRef = useRef<HTMLDivElement>(null);
const combinedContentRef = useCombinedRefs(contentRef, contentProps?.ref);
const [contentRect, setContentRect] = useState<DOMRect | undefined>();
const focusTrapProps = useFocusTrap({ rootRef, active: isOpen && !disableFocusTrap, enableInitialFocus: false });
const { shortcutHandlers: arrowNavigationShortcutHandlers } = useDropdownArrowNavigation({
rootRef,
});
const defaultShortcutHandlers: HotkeyTuple = [
'Escape',
(e) => {
e.stopPropagation();
onClose?.();
},
];
const hotkeyTuples = disableDefaultArrowNavigation
? [defaultShortcutHandlers]
: [...arrowNavigationShortcutHandlers, defaultShortcutHandlers];
useHotkeys(rootRef, hotkeyTuples, {
dependencies: [isOpen, !disableDefaultArrowNavigation],
});
useEffect(() => {
if (!isOpen) {
return;
}
const handleClickOutside = ({ target }: MouseEvent) => {
const targetNode = target as HTMLElement;
const anchorEl = anchorRef.current;
// Do nothing if clicking ref's element or descendent elements
if (
!autoCloseOutside ||
(autoCloseOutsideAnchor && anchorEl?.contains(targetNode)) ||
popperEl?.contains(targetNode) ||
targetNode.dataset?.ignoreClose
) {
return;
}
onClose();
};
/*
* In iOS Safari 12 (and maybe below), given the following scenario:
* Html <input /> nested inside of a <label /> with connecting "for" attributes
*
* The behaviour on click inside said label seems to be the following:
* Emit one click event with the target of the clicked element (imagine an icon inside
* an input field for example, e.g. PhoneCountrySelect input)
* Emit a second click event seemingly coming from and with the target being the input
* element which is linked to the label via the "for" attribute OR whichever input
* element is the first to appear in the children of the label.
*
* This behaviour causes the check for a click on the anchor element not to work if the
* anchor element is a child of the label but not the input itself. A dropdown is
* immediately closed as soon as opened because there are two click events emitted, one
* of which claims to not have been emitted from the anchor element.
*
* I'm assuming that bubbling is a fully synchronous operation here. Given this, delaying
* the attachement of this click-outside event-listener to a later call-stack seems to deal
* with this issue (as it can't listen to it's own bubbled click event any longer).
*/
const timeoutId = setTimeout(() => {
document.addEventListener('dropdownclose', onClose);
document.addEventListener('click', handleClickOutside, { capture: true });
}, 0);
return () => {
clearTimeout(timeoutId);
document.removeEventListener('dropdownclose', onClose);
document.removeEventListener('click', handleClickOutside, { capture: true });
};
}, [isOpen, autoCloseOutside, onClose, anchorRef.current, popperEl]);
const [isClosing, isClosed, setIsClosed] = useIsClosing(isOpen);
const popperClassName = clsx([
dropdownRootClassName,
`dropdown--${placement}`,
isClosing && `is-dropdown-out`,
noCaret && 'dropdown--no-caret',
adaptiveForTouchScreens && 'adaptive-for-touch-screens',
className,
'outline-none',
]);
if (isClosed && !isOpen) {
return null;
}
const varPosition = {
'--top': `${position.top}px`,
'--left': `${position.left}px`,
};
const varSize = {
...getProp('--width', getWidthValue(size?.width, anchorRect, contentRect)),
...getProp('--height', getHeightValue(size?.height, anchorRect, contentRect)),
};
const varMaxSize = {
...getProp('--custom-max-width', getMaxSizeValue(size?.maxWidth)),
...getProp('--custom-max-height', getMaxSizeValue(size?.maxHeight)),
};
const rootStyle = {
...style,
...varPosition,
...varMaxSize,
...varAvailableSize,
...varSize,
...arrow,
};
return (
<Portal>
<div
ref={combinedDropdownRef}
style={rootStyle}
role="dialog"
className={popperClassName}
onClick={handleClickContent}
onAnimationEnd={({ animationName }: AnimationEvent) => {
if (animationName.includes('anime-dropdown-out') && isClosing) {
setIsClosed();
setContentRect(undefined);
onClosed?.();
}
if (animationName.includes('anime-dropdown-in') && isOpen && contentRef.current && !contentRect) {
const contentClientRect = contentRef.current?.getBoundingClientRect();
setContentRect(contentClientRect);
}
}}
onContextMenu={onContextMenu}
data-testid="dropdown-button"
{...rest}
{...focusTrapProps}
>
{/* Backdrop button, meant to override 'autoClose' option on mobile */}
<div
role="button"
tabIndex={0}
data-ignore-close="true"
className="dropdown-backdrop"
title={c('Action').t`Close`}
onClick={onClose}
>
<span className="sr-only">{c('Action').t`Close`}</span>
</div>
<div
{...contentProps}
ref={combinedContentRef}
className={clsx(['dropdown-content', contentProps?.className])}
>
{children}
</div>
</div>
</Portal>
);
};
export default Dropdown;
| 5,319
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/dropdown/DropdownActions.tsx
|
import { MouseEvent, ReactNode } from 'react';
import { c } from 'ttag';
import { Button, ButtonProps } from '@proton/atoms';
import clsx from '@proton/utils/clsx';
import ButtonGroup from '../button/ButtonGroup';
import { Icon, IconName } from '../icon';
import { Info } from '../link';
import DropdownMenu from './DropdownMenu';
import DropdownMenuButton, { Props as DropdownMenuButtonProps } from './DropdownMenuButton';
import SimpleDropdown from './SimpleDropdown';
const wrapTooltip = (text: string | ReactNode, tooltip?: string) => {
if (!tooltip) {
return text;
}
if (typeof text !== 'string') {
return text;
}
return (
<>
<span className="mr-2">{text}</span>
<Info title={tooltip} />
</>
);
};
export interface DropdownActionProps extends DropdownMenuButtonProps {
key?: string;
text: string | ReactNode;
tooltip?: string;
onClick?: (e: MouseEvent<HTMLButtonElement>) => void;
}
export interface Props extends ButtonProps {
loading?: boolean;
disabled?: boolean;
list?: DropdownActionProps[];
className?: string;
autoFocus?: boolean;
iconName?: IconName;
}
const DropdownActions = ({
loading = false,
disabled = false,
list = [],
className = '',
autoFocus = false,
size,
iconName,
...restButtonProps
}: Props) => {
if (!list.length) {
return null;
}
const [{ text, tooltip, ...restProps }, ...restList] = list;
if (list.length === 1) {
return (
<Button
size={size}
loading={loading}
disabled={disabled}
className={className}
{...restProps}
{...restButtonProps}
>
{wrapTooltip(text, tooltip)}
</Button>
);
}
if (iconName) {
return (
<SimpleDropdown
as={Button}
icon
size={size}
autoFocus={autoFocus}
originalPlacement="bottom-end"
disabled={disabled}
loading={loading}
className={clsx(['flex-item-noshrink', className])}
title={c('Title').t`Open actions dropdown`}
data-testid="dropdownActions:dropdown"
content={<Icon name={iconName} alt={c('Title').t`Open actions dropdown`} />}
hasCaret={false}
{...restButtonProps}
>
<DropdownMenu>
{list.map(({ text, tooltip, ...restProps }, index) => {
return (
<DropdownMenuButton className="text-left" key={index} {...restProps}>
{wrapTooltip(text, tooltip)}
</DropdownMenuButton>
);
})}
</DropdownMenu>
</SimpleDropdown>
);
}
return (
<ButtonGroup size={size}>
<Button disabled={disabled || loading} className={className} {...restProps} {...restButtonProps}>
{wrapTooltip(text, tooltip)}
</Button>
<SimpleDropdown
as={Button}
icon
autoFocus={autoFocus}
originalPlacement="bottom-end"
disabled={disabled}
loading={loading}
className={clsx(['flex-item-noshrink', className])}
title={c('Title').t`Open actions dropdown`}
data-testid="dropdownActions:dropdown"
>
<DropdownMenu>
{restList.map(({ text, tooltip, ...restProps }, index) => {
return (
<DropdownMenuButton className="text-left" key={index} {...restProps}>
{wrapTooltip(text, tooltip)}
</DropdownMenuButton>
);
})}
</DropdownMenu>
</SimpleDropdown>
</ButtonGroup>
);
};
export default DropdownActions;
| 5,320
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/dropdown/DropdownButton.tsx
|
import { ElementType, ReactElement, forwardRef } from 'react';
import { PolymorphicPropsWithRef } from 'react-polymorphic-types';
import { Button, CircleLoader } from '@proton/atoms';
import clsx from '@proton/utils/clsx';
import DropdownCaret from './DropdownCaret';
interface OwnProps {
loading?: boolean;
caretClassName?: string;
hasCaret?: boolean;
isOpen?: boolean;
}
export type DropdownButtonProps<E extends ElementType> = PolymorphicPropsWithRef<OwnProps, E>;
const defaultElement = Button;
const DropdownButtonBase = <E extends ElementType = typeof defaultElement>(
{
children,
className,
hasCaret = false,
isOpen = false,
caretClassName = '',
loading = false,
disabled,
as,
...rest
}: DropdownButtonProps<E>,
ref: typeof rest.ref
) => {
const Element: ElementType = as || defaultElement;
return (
<Element
ref={ref}
aria-expanded={isOpen}
aria-busy={loading}
disabled={loading ? true : disabled}
data-testid="dropdown-button"
className={clsx([children && hasCaret && 'flex flex-align-items-center flex-nowrap', className])}
{...rest}
>
{children}
{loading && (
<span className="button-loader-container">
<CircleLoader />
</span>
)}
{hasCaret && (
<DropdownCaret
className={clsx(['flex-item-noshrink', children ? ' ml-1' : '', caretClassName])}
isOpen={isOpen}
/>
)}
</Element>
);
};
const DropdownButton: <E extends ElementType = typeof defaultElement>(
props: DropdownButtonProps<E>
) => ReactElement | null = forwardRef(DropdownButtonBase);
export default DropdownButton;
| 5,321
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/dropdown/DropdownCaret.tsx
|
import clsx from '@proton/utils/clsx';
import Icon, { IconName, IconSize } from '../icon/Icon';
interface Props {
className?: string;
isOpen?: boolean;
size?: IconSize;
iconName?: IconName;
}
const DropdownCaret = ({ className, isOpen, size = 16, iconName = 'chevron-down-filled' }: Props) => {
return <Icon className={clsx([isOpen && 'rotateX-180', className])} size={size} name={iconName} />;
};
export default DropdownCaret;
| 5,322
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/dropdown/DropdownMenu.tsx
|
import { Children, ComponentPropsWithoutRef, Ref, isValidElement } from 'react';
import clsx from '@proton/utils/clsx';
interface DropdownMenuProps extends ComponentPropsWithoutRef<'ul'> {
listRef?: Ref<HTMLUListElement>;
}
const DropdownMenu = ({ children, className = '', listRef, ...rest }: DropdownMenuProps) => {
return (
<ul className={clsx(['unstyled my-0', className])} ref={listRef} {...rest}>
{Children.toArray(children).map((child, i) => {
return isValidElement(child) ? (
<li
className={clsx([
'dropdown-item',
child.props.actionType === 'delete' && 'dropdown-item--delete',
child.props.liClassName,
])}
key={child.key || i}
>
{child}
</li>
) : null;
})}
</ul>
);
};
export default DropdownMenu;
| 5,323
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/dropdown/DropdownMenuButton.tsx
|
import { ComponentPropsWithRef, forwardRef } from 'react';
import { CircleLoader } from '@proton/atoms';
import clsx from '@proton/utils/clsx';
export interface Props extends Omit<ComponentPropsWithRef<'button'>, 'color'> {
loading?: boolean;
isSelected?: boolean;
/*
* Used by DropdownMenu to add CSS classes to the parent li
*/
liClassName?: string;
actionType?: 'delete';
'data-testid'?: string;
}
const DropdownMenuButton = forwardRef<HTMLButtonElement, Props>(
(
{
className = '',
isSelected,
disabled,
loading,
children,
liClassName, // eslint-disable-line no-unused-vars, @typescript-eslint/no-unused-vars
actionType, // eslint-disable-line no-unused-vars, @typescript-eslint/no-unused-vars
...rest
},
ref
) => {
return (
<button
ref={ref}
type="button"
disabled={disabled || loading}
className={clsx([
'dropdown-item-button w-full px-4 py-2',
isSelected && 'dropdown-item--is-selected',
className,
])}
aria-busy={loading}
{...rest}
>
{loading ? (
<div className="flex flex-align-items-center flex-nowrap">
<span className="flex-item-fluid text-ellipsis">{children}</span>
<CircleLoader className="flex-item-noshrink" />
</div>
) : (
children
)}
</button>
);
}
);
DropdownMenuButton.displayName = 'DropdownMenuButton';
export default DropdownMenuButton;
| 5,324
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/dropdown/DropdownMenuContainer.tsx
|
import { ReactNode, Ref, forwardRef } from 'react';
import clsx from '@proton/utils/clsx';
import DropdownMenuButton, { Props as DropdownMenuButtonProps } from './DropdownMenuButton';
export interface Props extends DropdownMenuButtonProps {
buttonContent?: ReactNode;
extraContent?: ReactNode;
buttonRef?: Ref<HTMLButtonElement>;
className?: string;
buttonClassName?: string;
}
const DropdownMenuContainer = (
{ buttonContent, extraContent, buttonRef, className, buttonClassName, ...rest }: Props,
ref: Ref<HTMLDivElement>
) => {
return (
<div
ref={ref}
className={clsx([
'dropdown-item-container flex flex-justify-space-between flex-nowrap relative',
className,
])}
>
<DropdownMenuButton ref={buttonRef} className={clsx(['increase-click-surface', buttonClassName])} {...rest}>
{buttonContent}
</DropdownMenuButton>
{extraContent || null}
</div>
);
};
export default forwardRef(DropdownMenuContainer);
| 5,325
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/dropdown/DropdownMenuLink.tsx
|
import { ElementType } from 'react';
import { PolymorphicPropsWithoutRef } from 'react-polymorphic-types';
import { Href } from '@proton/atoms';
import clsx from '@proton/utils/clsx';
interface DropdownMenuLinkOwnProps {}
export type DropdownMenuLinkProps<E extends ElementType> = PolymorphicPropsWithoutRef<DropdownMenuLinkOwnProps, E>;
const defaultElement = Href;
const DropdownMenuLink = <E extends ElementType = typeof defaultElement>({
className = '',
children,
as,
...rest
}: DropdownMenuLinkProps<E>) => {
const Element: ElementType = as || defaultElement;
return (
<Element {...rest} className={clsx(['dropdown-item-link w-full px-4 py-2 block text-no-decoration', className])}>
{children}
</Element>
);
};
export default DropdownMenuLink;
| 5,326
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/dropdown/SimpleDropdown.tsx
|
import {
ElementType,
ForwardedRef,
HTMLAttributes,
MouseEventHandler,
ReactNode,
RefObject,
forwardRef,
useState,
} from 'react';
import { useCombinedRefs } from '@proton/hooks';
import { generateUID } from '../../helpers';
import { usePopperAnchor } from '../popper';
import Dropdown, { DropdownProps } from './Dropdown';
import DropdownButton, { DropdownButtonProps } from './DropdownButton';
interface ContentProps extends HTMLAttributes<HTMLDivElement> {
ref?: RefObject<HTMLDivElement>;
}
interface OwnProps<E extends ElementType> {
hasCaret?: boolean;
content?: ReactNode;
children?: ReactNode;
disableDefaultArrowNavigation?: boolean;
onClick?: MouseEventHandler<E>;
onToggle?: (isOpen: boolean) => void;
contentProps?: ContentProps;
autoClose?: DropdownProps['autoClose'];
originalPlacement?: DropdownProps['originalPlacement'];
dropdownClassName?: DropdownProps['className'];
dropdownStyle?: DropdownProps['style'];
dropdownSize?: DropdownProps['size'];
}
export type Props<T extends ElementType> = DropdownButtonProps<T> & OwnProps<T>;
const SimpleDropdownBase = <E extends ElementType>(
{
content,
children,
originalPlacement,
autoClose,
hasCaret = true,
dropdownClassName,
dropdownStyle,
contentProps,
disableDefaultArrowNavigation = false,
onClick,
onToggle,
as,
dropdownSize,
...rest
}: Props<E>,
ref: ForwardedRef<Element>
) => {
const [uid] = useState(generateUID('dropdown'));
const { anchorRef, isOpen, toggle, close } = usePopperAnchor<HTMLButtonElement>(onToggle);
const handleClick: MouseEventHandler<E> = !!onClick
? (e) => {
onClick(e);
toggle();
}
: toggle;
const Element: ElementType | undefined = as || undefined;
return (
<>
<DropdownButton
as={Element}
{...rest}
ref={useCombinedRefs(ref, anchorRef)}
isOpen={isOpen}
onClick={handleClick}
hasCaret={hasCaret}
>
{content}
</DropdownButton>
<Dropdown
id={uid}
originalPlacement={originalPlacement}
autoClose={autoClose}
isOpen={isOpen}
anchorRef={anchorRef as unknown as any}
onClose={close}
className={dropdownClassName}
style={dropdownStyle}
disableDefaultArrowNavigation={disableDefaultArrowNavigation}
size={dropdownSize}
{...contentProps}
>
{children}
</Dropdown>
</>
);
};
const SimpleDropdown = forwardRef(SimpleDropdownBase);
export default SimpleDropdown;
| 5,327
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/dropdown/index.ts
|
export { default as DropdownActions } from './DropdownActions';
export { default as DropdownMenu } from './DropdownMenu';
export { default as DropdownMenuButton } from './DropdownMenuButton';
export { default as DropdownButton } from './DropdownButton';
export { default as DropdownCaret } from './DropdownCaret';
export { default as DropdownMenuLink } from './DropdownMenuLink';
export { default as Dropdown } from './Dropdown';
export * from './Dropdown';
export * from './DropdownButton';
export { default as SimpleDropdown } from './SimpleDropdown';
export { default as DropdownMenuContainer } from './DropdownMenuContainer';
export { DropdownSizeUnit } from './utils';
| 5,328
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/dropdown/utils.ts
|
enum UnitSuffix {
px = 'px',
em = 'em',
rem = 'rem',
}
export enum DropdownSizeUnit {
Anchor = 'anchor',
Static = 'static',
Dynamic = 'dynamic',
Viewport = 'viewport',
}
export type Unit = `${number}${UnitSuffix}`;
export interface DropdownSize {
width?: Exclude<DropdownSizeUnit, DropdownSizeUnit.Viewport> | Unit;
height?: Exclude<DropdownSizeUnit, DropdownSizeUnit.Viewport | DropdownSizeUnit.Anchor> | Unit;
maxWidth?: DropdownSizeUnit.Viewport | Unit;
maxHeight?: DropdownSizeUnit.Viewport | Unit;
}
const getValue = (value: number | undefined, unit: keyof typeof UnitSuffix) => {
if (value === undefined) {
return;
}
return `${value}${unit}`;
};
export const getMaxSizeValue = (value: DropdownSize['maxWidth'] | Unit | undefined) => {
if (value === undefined) {
return;
}
return value === DropdownSizeUnit.Viewport ? 'initial' : value;
};
export const getWidthValue = (
width: DropdownSize['width'] | undefined,
anchorRect: DOMRect | null | undefined,
contentRect: DOMRect | null | undefined
) => {
if (width === undefined || width === DropdownSizeUnit.Static) {
return getValue(contentRect?.width, 'px');
}
if (width === DropdownSizeUnit.Anchor) {
return getValue(anchorRect?.width, 'px');
}
if (width === DropdownSizeUnit.Dynamic) {
return;
}
return width;
};
export const getHeightValue = (
height: DropdownSize['height'] | undefined,
anchorRect: DOMRect | null | undefined,
contentRect: DOMRect | null | undefined
) => {
if (height === undefined || height === DropdownSizeUnit.Static) {
return getValue(contentRect?.height, 'px');
}
if (height === DropdownSizeUnit.Dynamic) {
return;
}
return height;
};
export const getProp = (prop: string, value: string | undefined) => {
if (value === undefined) {
return;
}
return { [prop]: value };
};
| 5,329
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/dropzone/Dropzone.scss
|
@import '~@proton/styles/scss/lib';
.dropzone {
&--bordered {
border: 1px dashed var(--border-norm);
}
&-content {
background-color: var(--background-norm);
&--hovered {
z-index: $layer-dropzone;
}
&--embedded {
inset: 1px; // For border width
position: fixed;
}
&--transparent {
&::before {
content: '';
position: absolute;
inset: 0;
opacity: 0.95;
background-color: var(--background-norm);
z-index: -1; // We want the pseudo element to be behind the element to use it as a "transparent" background
}
border: none;
border-radius: 0;
background-color: transparent;
}
&--flashy {
&::before {
content: '';
position: absolute;
inset: 0;
opacity: 0.07;
background-color: var(--primary);
border: inherit;
border-radius: inherit;
}
border: 1px solid var(--primary);
color: var(--primary);
}
&--white {
// In some places (e.g. the composer), we want the background to be white whatever the theme
background-color: white;
}
}
}
| 5,330
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/dropzone/Dropzone.tsx
|
import { ComponentPropsWithoutRef, DragEvent as ReactDragEvent, ReactNode, cloneElement } from 'react';
import { isDragFile } from '@proton/components/components';
import { useDragOver } from '@proton/components/hooks';
import DropzoneContent from './DropzoneContent';
import './Dropzone.scss';
export type DropzoneSize = 'small' | 'medium' | 'large';
export type DropzoneShape = 'norm' | 'transparent' | 'flashy' | 'white' | 'invisible';
export interface DropzoneProps extends Omit<ComponentPropsWithoutRef<'div'>, 'onDrop'> {
/**
* Action to trigger when dropping files on top of the dropzone
*/
onDrop: (files: File[]) => void;
/**
* Content to display when no hover
*/
children: JSX.Element;
/**
* Custom content to show when dragging over the Dropzone
*/
customContent?: ReactNode;
/**
* Dropzone's size : small | medium | large
*/
size?: DropzoneSize;
/**
* Dropzone has a border
*/
border?: boolean;
/**
* Dropzone's border is rounded
*/
rounded?: boolean;
/**
* Dropzone's shade : norm | transparent | flashy | white | invisible
*/
shape?: DropzoneShape;
/**
* Dropzone is always on dragOver state, content is always displayed
*/
showDragOverState?: boolean;
/**
* Dropzone has no dragOver state, and onDrop cannot be triggered
*/
disabled?: boolean;
/**
* Prevents setting the Dropzone's children div to position "relative"
*/
isStatic?: boolean;
/**
* Title displayed under the illustration in "large" Dropzones (without custom content). Default text is "Drop to import"
*/
contentTitle?: string;
/**
* Sub text displayed under the illustration in Dropzones (without custom content).
* Default text is "Drop file here to upload" for "small" and "medium" Dropzones,
* and "Your files will be encrypted and then saved" for "large" Dropzones
*/
contentSubText?: string;
}
const Dropzone = ({
className,
children,
customContent,
onDrop,
disabled = false,
showDragOverState = false,
size = 'medium',
rounded = true,
border = true,
shape = 'norm',
isStatic = false,
contentTitle,
contentSubText,
...rest
}: DropzoneProps) => {
const handleDrop = (event: ReactDragEvent) => {
if (!disabled) {
onDrop([...event.dataTransfer.files]);
}
};
const [hovering, dragProps] = useDragOver(isDragFile, 'move', { onDrop: handleDrop });
const isInvisible = shape === 'invisible';
// We need to display the dropzone content when:
// - We are on dragOver state
// - We force to always display the dragOver state
// BUT, we don't want to show it when:
// - Dropzone is completely disabled
// - The dropzone is invisible (we always show the children)
const shouldDisplayDropzoneContent = (hovering || showDragOverState) && !disabled && !isInvisible;
const dropzoneContent = shouldDisplayDropzoneContent ? (
<DropzoneContent
border={border}
className={className}
customContent={customContent}
rounded={rounded}
shape={shape}
size={size}
contentTitle={contentTitle}
contentSubText={contentSubText}
/>
) : null;
/**
* Warning:
* To display this dropzone we had two solutions
* 1. Add a container, wrapping the child and the content
* 2. Clone the element and update some props
*
* The first solution is easier to implement and to use, however in some cases (mostly CSS), adding this container could break the UI
* The developer would then need to do tricky CSS manipulation in order to get a working dropzone.
*
* To avoid having a container div which would contain the children and the content, we clone the children element.
* However, the Dropzone children might need some configuration to work properly:
* Because we're adding the dropzone content as a new children, and we're adding some props to the children element,
* you'll need to spread the rest operator in the wrapping div AND render the children.
*/
return cloneElement(children, {
...children.props,
...dragProps,
...rest,
style:
shouldDisplayDropzoneContent && !isStatic
? { position: 'relative', ...children.props.style }
: { ...children.props.style },
children: (
<>
{children.props.children}
{dropzoneContent}
</>
),
});
};
export default Dropzone;
| 5,331
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/dropzone/DropzoneContent.tsx
|
import { c } from 'ttag';
import dragAndDrop from '@proton/styles/assets/img/illustrations/drag-and-drop-img.svg';
import clsx from '@proton/utils/clsx';
import { DropzoneProps } from './Dropzone';
export interface DropzoneContentProps
extends Pick<
DropzoneProps,
'size' | 'shape' | 'rounded' | 'border' | 'customContent' | 'className' | 'contentTitle' | 'contentSubText'
> {
/** Embedded in iframe */
embedded?: boolean;
}
const DropzoneContent = ({
border,
className,
customContent,
rounded,
shape,
size,
embedded = false,
contentTitle = c('Info').t`Drop to import`,
contentSubText,
}: DropzoneContentProps) => {
const isSmallDropView = size === 'small';
const isLargeDropView = size === 'large';
const isTransparentShape = shape === 'transparent';
const isFlashyShape = shape === 'flashy';
const isWhite = shape === 'white';
const getSubText = () => {
if (contentSubText) {
return contentSubText;
} else {
if (isLargeDropView) {
return c('Info').t`Your files will be encrypted and then saved`;
} else {
return c('Info').t`Drop file here to upload`;
}
}
};
const subText = getSubText();
/** Prefix css classes with `proton-` for iframe embedded situation */
const prefixClasses = (classes: string) =>
embedded
? classes
.split(' ')
.map((className) => `proton-${className}`)
.join(' ')
: classes;
return (
<div
className={clsx(
'dropzone-content dropzone-content--hovered',
prefixClasses('flex flex-justify-center flex-align-items-center'),
embedded ? 'dropzone-content--embedded' : 'h-full w-full absolute-cover',
rounded && prefixClasses('rounded-xl'),
border && 'dropzone--bordered',
isTransparentShape && 'dropzone-content--transparent',
isFlashyShape && 'dropzone-content--flashy',
isWhite && 'dropzone-content--white',
className
)}
>
{customContent ? (
customContent
) : (
<div className={prefixClasses('text-center')}>
{!isSmallDropView && (
<img src={dragAndDrop} alt="" aria-hidden="true" className={prefixClasses('mb-4')} />
)}
{isLargeDropView ? (
<p className={prefixClasses('mb-0 mt-5')}>
<span className={prefixClasses('text-xl text-bold')}>{contentTitle}</span>
<br />
<span className={!isFlashyShape ? prefixClasses('color-weak') : undefined}>{subText}</span>
</p>
) : (
<p className={clsx(prefixClasses('m-0'), !isFlashyShape && prefixClasses('color-weak'))}>
{subText}
</p>
)}
</div>
)}
</div>
);
};
export default DropzoneContent;
| 5,332
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/dropzone/helpers.ts
|
import { DragEvent, DragEventHandler } from 'react';
export const isDragFile = (event: DragEvent) => event.dataTransfer?.types?.includes('Files');
export const onlyDragFiles = (eventHandler: DragEventHandler) => (event: DragEvent) => {
if (isDragFile(event)) {
return eventHandler(event);
}
};
| 5,333
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/dropzone/index.ts
|
export { default as Dropzone } from './Dropzone';
export * from './helpers';
| 5,334
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editableText/EditableText.js
|
import { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import { c } from 'ttag';
import { Button } from '@proton/atoms/';
import useToggle from '../../hooks/useToggle';
import { Icon } from '../icon';
import Input from '../input/Input';
const EditableText = ({ icon = 'pen', onSubmit, initialText = '', children, readOnly = false, ...rest }) => {
const [inputValue, setInputValue] = useState(initialText);
const { state: editing, toggle: toggleEditing, set: setEditing } = useToggle();
useEffect(() => {
if (editing) {
setInputValue(initialText);
}
}, [editing, initialText]);
const submit = (value) => {
onSubmit(value);
setEditing(false);
};
const handleFormSubmit = (e) => {
e.preventDefault();
submit(inputValue);
};
const handleChangeInputValue = ({ target }) => setInputValue(target.value);
return editing ? (
<form className="flex" onSubmit={handleFormSubmit}>
{children ? (
children({ submit, toggleEditing })
) : (
<>
<div className="flex">
<Input autoFocus value={inputValue} onChange={handleChangeInputValue} {...rest} />
</div>
<Button icon type="submit" className="ml-2" title={c('Action').t`Confirm`}>
<Icon name="checkmark" alt={c('Action').t`Confirm`} />
</Button>
</>
)}
<Button icon onClick={toggleEditing} className="ml-2" title={c('Action').t`Close`}>
<Icon name="cross" alt={c('Action').t`Close`} />
</Button>
</form>
) : (
<>
{initialText === null ? '--' : initialText}
{!readOnly && (
<Button icon onClick={toggleEditing} className="ml-2" title={c('Action').t`Toggle edit`}>
<Icon name={icon} />
</Button>
)}
</>
);
};
EditableText.propTypes = {
onSubmit: PropTypes.func.isRequired,
initialText: PropTypes.string,
readOnly: PropTypes.bool,
children: PropTypes.func,
icon: PropTypes.string,
small: PropTypes.bool,
};
export default EditableText;
| 5,335
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editableText/index.ts
|
export { default as EditableText } from './EditableText';
| 5,336
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/Editor.tsx
|
import { RefObject, useCallback } from 'react';
import { Dropzone } from '@proton/components/components';
import { ToolbarConfig } from '@proton/components/components/editor/helpers/getToolbarConfig';
import { MailSettings } from '@proton/shared/lib/interfaces';
import clsx from '@proton/utils/clsx';
import noop from '@proton/utils/noop';
import { DropzoneContentProps } from '../dropzone/DropzoneContent';
import { EDITOR_DEFAULT_METADATA } from './constants';
import { EditorActions, EditorMetadata, SetEditorToolbarConfig } from './interface';
import DefaultFontModal from './modals/DefaultFontModal';
import InsertImageModal from './modals/InsertImageModal';
import InsertLinkModal from './modals/InsertLinkModal/InsertLinkModal';
import PlainTextEditor from './plainTextEditor/PlainTextEditor';
import RoosterEditor from './rooster/RoosterEditor';
import EditorToolbar from './toolbar/Toolbar';
interface Props {
className?: string;
editorToolbarClassname?: string;
editorClassname?: string;
metadata?: Partial<EditorMetadata>;
onChange: (value: string) => void;
showBlockquoteToggle?: boolean;
onBlockquoteToggleClick?: () => void;
disabled?: boolean;
onReady: (editorActions: EditorActions) => void;
simple?: boolean;
onFocus?: () => void;
onAddAttachments?: (files: File[]) => void;
/**
* Are used for editor default font value
* It's optionnal but if passed it should be passed
* at same time component is first rendered
*/
mailSettings?: MailSettings;
isPlainText?: boolean;
openEmojiPickerRef: RefObject<() => void>;
toolbarConfig?: ToolbarConfig;
setToolbarConfig: SetEditorToolbarConfig;
modalLink: any;
modalImage: any;
modalDefaultFont: any;
hasToolbar?: boolean;
hasDropzone?: boolean;
}
const DROPZONE_COMPOSER_SETTINGS: DropzoneContentProps = {
shape: 'white',
border: true,
rounded: true,
};
const Editor = ({
className,
editorClassname,
editorToolbarClassname,
metadata: metadataProp,
onChange = noop,
simple,
onFocus = noop,
disabled = false,
onReady = noop,
showBlockquoteToggle,
onBlockquoteToggleClick = noop,
onAddAttachments,
mailSettings,
isPlainText,
openEmojiPickerRef,
toolbarConfig,
setToolbarConfig,
modalLink,
modalImage,
modalDefaultFont,
hasToolbar = true,
hasDropzone = true,
}: Props) => {
/**
* Set to true when editor setContent is called by parent components
* in order to prevent onChange callback
*/
const metadata: EditorMetadata = { ...EDITOR_DEFAULT_METADATA, ...metadataProp };
const onPasteImage = useCallback(
(imageFile: File) => {
if (metadata.supportImages) {
onAddAttachments?.([imageFile]);
}
},
[onAddAttachments, metadata.supportImages]
);
const plaintextEditor = <PlainTextEditor onChange={onChange} onReady={onReady} onFocus={onFocus} />;
return (
<>
<div
className={clsx([
className,
simple && 'simple-editor',
'editor w-full h-full rounded flex flex-column-reverse flex-item-fluid',
])}
>
<div
className={clsx([
'h-full flex-item-fluid flex flex-column relative',
disabled && 'editor--disabled',
isPlainText ? '' : 'composer-content--rich-edition',
editorClassname,
])}
>
{metadata.isPlainText ? (
!!onAddAttachments ? (
<Dropzone onDrop={onAddAttachments}>{plaintextEditor}</Dropzone>
) : (
plaintextEditor
)
) : (
<RoosterEditor
onChange={onChange}
onReady={onReady}
showBlockquoteToggle={showBlockquoteToggle}
onBlockquoteToggleClick={onBlockquoteToggleClick}
setToolbarConfig={setToolbarConfig}
onPasteImage={onPasteImage}
showModalLink={modalLink.showCallback}
onFocus={onFocus}
mailSettings={mailSettings}
className={simple ? 'border rounded' : ''}
openEmojiPicker={() => openEmojiPickerRef.current?.()}
dropzone={hasDropzone ? DROPZONE_COMPOSER_SETTINGS : undefined}
onAddAttachments={onAddAttachments}
/>
)}
</div>
{hasToolbar && (
<EditorToolbar
config={toolbarConfig}
metadata={metadata}
mailSettings={mailSettings}
className={editorToolbarClassname}
openEmojiPickerRef={openEmojiPickerRef}
simple={simple}
/>
)}
</div>
<div
onSubmit={(e) => {
e.stopPropagation();
}}
>
{modalDefaultFont.render && metadata.supportDefaultFontSelector && (
<DefaultFontModal {...modalDefaultFont.props} {...modalDefaultFont.modalsStateProps} />
)}
{modalImage.render && <InsertImageModal {...modalImage.props} {...modalImage.modalsStateProps} />}
{modalLink.render && modalLink.props && (
<InsertLinkModal {...modalLink.props} modalStateProps={modalLink.modalsStateProps} />
)}
</div>
</>
);
};
export default Editor;
| 5,337
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/constants.ts
|
import { c } from 'ttag';
import { DIRECTION } from '@proton/shared/lib/mail/mailSettings';
import { EditorMetadata } from './interface';
/**
* Can be unique because set inside iframe
*/
export const ROOSTER_EDITOR_WRAPPER_ID = 'rooster-editor-wrapper';
export const ROOSTER_EDITOR_ID = 'rooster-editor';
export const EDITOR_BLOCKQUOTE_TOGGLE_CONTAINER_ID = 'proton-editor-toggle-container';
export const EDITOR_DROPZONE = 'proton-editor-dropzone';
/**
* Rooster snapshot max size limit
* Source : https://github.com/microsoft/roosterjs/blob/a27dcb9a28092d2b160b27bcb8456b751e5309e2/packages/roosterjs-editor-core/lib/corePlugins/UndoPlugin.ts#L23
*/
export const ROOSTER_SNAPSHOTS_MAX_SIZE = 1e7;
/**
* List of iframe events to bubble
*/
export const IFRAME_EVENTS_LIST: Event['type'][] = [
'dragenter',
'dragleave',
'dragover',
'drop',
'keydown',
'click',
'input',
];
type FontFace =
| 'GEORGIA'
| 'ARIAL'
| 'HELVETICA'
| 'MONOSPACE'
| 'TAHOMA'
| 'VERDANA'
| 'TIMES_NEW_ROMAN'
| 'TREBUCHET_MS';
/**
* Used in composer font selector
*/
export const FONT_FACES: Record<FontFace, { id: string; label: string; value: string }> = {
GEORGIA: {
id: 'Georgia',
label: 'Georgia',
value: 'Georgia, serif',
},
ARIAL: {
id: 'Arial',
label: 'Arial',
value: 'Arial, sans-serif',
},
HELVETICA: {
id: 'Helvetica',
label: 'Helvetica',
value: 'Helvetica, sans-serif',
},
MONOSPACE: {
id: 'Menlo, Consolas, Courier New, Monospace',
label: 'Monospace',
value: 'Menlo, Consolas, Courier New, Monospace',
},
TAHOMA: {
id: 'Tahoma, sans-serif',
label: 'Tahoma',
value: 'Tahoma, sans-serif',
},
VERDANA: {
id: 'Verdana',
label: 'Verdana',
value: 'Verdana, sans-serif',
},
TIMES_NEW_ROMAN: {
id: 'Times New Roman',
label: 'Times New Roman',
value: 'Times New Roman, serif',
},
TREBUCHET_MS: {
id: 'Trebuchet MS',
label: 'Trebuchet MS',
value: 'Trebuchet MS, sans-serif',
},
};
export const DEFAULT_FONT_FACE = FONT_FACES.ARIAL.value;
export enum FONT_SIZES {
'10px' = '7.5pt',
'12px' = '9pt',
'14px' = '10.5pt',
'16px' = '12pt',
'18px' = '13.5pt',
'20px' = '15pt',
'22px' = '16.5pt',
'24px' = '18pt',
'26px' = '19.5pt',
}
export const DEFAULT_FONT_SIZE = 14;
export const DEFAULT_FONT_COLOR = '#000000';
export const DEFAULT_BACKGROUND = '#FFFFFF';
export const FONT_COLORNAMES = {
/* white */
'#FFFFFF': () => c('color').t`white`,
'#DADADA': () => c('color').t`gainsboro`,
'#B5B5B5': () => c('color').t`philippine silver`,
'#909090': () => c('color').t`philippine gray`,
'#6B6B6B': () => c('color').t`dim gray`,
'#464646': () => c('color').t`outer space`,
'#000000': () => c('color').t`black`,
/* magenta */
'#F6CBCB': () => c('color').t`light red`,
'#EC9798': () => c('color').t`ruddy pink`,
'#E36667': () => c('color').t`light carmine pink`,
'#ED4139': () => c('color').t`cinnabar`,
'#CF3932': () => c('color').t`persian red`,
'#9A2B25': () => c('color').t`vivid auburn`,
'#681D19': () => c('color').t`persian plum`,
/* blue */
'#CDE1F2': () => c('color').t`azureish white`,
'#9CC3E5': () => c('color').t`pale cerulean`,
'#6CA6D9': () => c('color').t`blue-gray`,
'#3B83C2': () => c('color').t`cyan-blue azure`,
'#2A47F6': () => c('color').t`palatinate blue`,
'#145390': () => c('color').t`dark cerulean`,
'#0F3A62': () => c('color').t`dark midnight blue`,
/* green */
'#D7EAD3': () => c('color').t`pastel gray`,
'#B3D6A9': () => c('color').t`light moss green`,
'#8FC380': () => c('color').t`pistachio`,
'#77F241': () => c('color').t`kiwi`,
'#66A657': () => c('color').t`apple`,
'#3A762B': () => c('color').t`japanese laurel`,
'#29501F': () => c('color').t`mughal green`,
/* yellow */
'#FFF2CD': () => c('color').t`blanched almond`,
'#FEE59C': () => c('color').t`caramel`,
'#FCD86F': () => c('color').t`dandelion`,
'#FDF84E': () => c('color').t`lemon yellow`,
'#F2C246': () => c('color').t`maize`,
'#BE8F35': () => c('color').t`satin sheen gold`,
'#7F6124': () => c('color').t`field drab`,
} as const;
export const FONT_COLORS = Object.keys(FONT_COLORNAMES) as string[];
export const HEADER_CLASS = 'h4';
export const DEFAULT_LINK = '';
export const DEFAULT_IMAGE = '';
export const RGB_REGEX = /rgb\((\d+)\s*,\s*(\d+),\s*(\d+)\)/;
export const EMBEDDABLE_TYPES = ['image/gif', 'image/jpeg', 'image/png', 'image/bmp'];
export const EDITOR_DEFAULT_METADATA: EditorMetadata = {
supportImages: true,
supportPlainText: false,
supportDefaultFontSelector: false,
isPlainText: false,
supportRightToLeft: false,
rightToLeft: DIRECTION.LEFT_TO_RIGHT,
blockquoteExpanded: true,
setBlockquoteExpanded: undefined,
};
| 5,338
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/helpers.ts
|
import { DEFAULT_FONT_FACE, DEFAULT_FONT_SIZE } from './constants';
import { getFontFaceValueFromId } from './helpers/fontFace';
export interface FontData {
FontFace: string | null;
FontSize: number | null;
}
/**
* Helper used because of Squire problems to handle correctly default fonts
* TODO : Remove patches arround this issue
*/
export const defaultFontStyle = (fontData: FontData | undefined): string => {
let { FontFace, FontSize } = fontData || {};
FontFace = !FontFace ? DEFAULT_FONT_FACE : getFontFaceValueFromId(FontFace) || DEFAULT_FONT_FACE;
FontSize = !FontSize ? DEFAULT_FONT_SIZE : FontSize;
const stylesArray = [`font-family: ${FontFace};`, `font-size: ${FontSize}px;`];
return stylesArray.join(' ');
};
| 5,339
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/index.ts
|
export { default as Editor } from './Editor';
export * from './interface';
| 5,340
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/interface.ts
|
import { Dispatch, SetStateAction } from 'react';
import { IEditor, PluginEvent } from 'roosterjs-editor-types';
import { DIRECTION } from '@proton/shared/lib/mail/mailSettings';
export interface EditorMetadata {
supportImages: boolean;
supportPlainText: boolean;
supportDefaultFontSelector: boolean;
isPlainText: boolean;
supportRightToLeft: boolean;
rightToLeft: DIRECTION;
blockquoteExpanded: boolean;
setBlockquoteExpanded: Dispatch<SetStateAction<boolean>> | undefined;
}
/**
* External editor actions returned to parent component
*/
export interface EditorActions {
focus: () => void;
setContent: (content: string, triggerAutoSave?: boolean) => void;
getContent: () => string;
insertImage?: (url: string, attrs?: { [key: string]: string }) => void;
clearUndoHistory?: () => void;
/** Meant to be used at startup */
setTextDirection?: (direction: DIRECTION) => void;
/** Tells if Editor is unmounted */
isDisposed: () => boolean;
showModalLink?: () => void;
openEmojiPicker?: () => void;
scroll?: (scrollToOption: ScrollToOptions) => void;
}
export type OnEditorEventListened = (editorEvent: PluginEvent, editor: IEditor) => void;
export type SetEditorToolbarConfig = (editorInstance: IEditor | undefined) => void;
| 5,341
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/helpers/fontFace.ts
|
import { FONT_FACES } from '@proton/components/components/editor/constants';
/**
* getFontFaceValueFromId
* @param fontFaceId font face id saved in user settings
* @returns font face value to display in editor
*/
export const getFontFaceValueFromId = (fontFaceId: string | null | undefined): string | undefined =>
Object.values(FONT_FACES).find((font) => font.id === fontFaceId)?.value;
/**
* getFontFaceIdFromValue
* @param fontFaceValue font face value front FONT_FACE constant
* @returns font face id to save in user settings
*/
export const getFontFaceIdFromValue = (fontFaceValue: string): string | undefined =>
Object.values(FONT_FACES).find((font) => font.value === fontFaceValue)?.id;
| 5,342
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/helpers/getToolbarConfig.ts
|
import { Alignment, FormatState, IEditor } from 'roosterjs-editor-types';
import { getRoosterDirection } from '@proton/components/components/editor/rooster/helpers/initRoosterEditor';
import { Optional } from '@proton/shared/lib/interfaces';
import { DIRECTION } from '@proton/shared/lib/mail/mailSettings';
import { DEFAULT_BACKGROUND, DEFAULT_FONT_COLOR } from '../constants';
import { ModalDefaultFontProps, ModalImageProps, ModalLinkProps } from '../hooks/interface';
import { EditorMetadata } from '../interface';
import { Emoji } from '../toolbar/ToolbarEmojiDropdown';
import rgbToHex from './rgbToHex';
interface ItemToggle {
isActive: boolean;
toggle: () => void;
}
interface ItemValue<T = string> {
value: T;
setValue: (nextValue: T) => void;
}
interface ItemModal {
showModal: () => void;
}
export interface ToolbarConfig {
bold: ItemToggle;
italic: ItemToggle;
underline: ItemToggle;
strikethrough: ItemToggle;
fontFace: Optional<ItemValue, 'value'>;
fontSize: Optional<ItemValue, 'value'>;
fontColor: ItemValue;
defaultFont: ItemModal;
backgroundColor: ItemValue;
unorderedList: ItemToggle;
orderedList: ItemToggle;
alignment: Pick<ItemValue<Alignment>, 'setValue'>;
blockquote: ItemToggle;
link: ItemModal;
image: ItemModal;
formatting: {
clear: () => void;
};
textDirection: Pick<ItemValue<DIRECTION>, 'setValue'>;
emoji: {
insert: (emoji: Emoji) => void;
};
}
interface Options {
showModalLink: (options: ModalLinkProps) => void;
showModalImage: (options: ModalImageProps) => void;
showModalDefaultFont: (options: ModalDefaultFontProps) => void;
onChangeMetadata: ((metadataChange: Partial<EditorMetadata>) => void) | undefined;
onAddAttachments: ((files: File[]) => void) | undefined;
}
const cleanRoosterFont = (font: string | undefined) => font?.replaceAll('"', '');
export const getToolbarConfig = async (editorInstance: IEditor | undefined, options: Options) => {
const {
clearFormat,
createLink,
getFormatState,
insertImage,
removeLink,
setAlignment,
setBackgroundColor,
setDirection,
setFontName,
setFontSize,
setTextColor,
toggleBlockQuote,
toggleBold,
toggleBullet,
toggleItalic,
toggleNumbering,
toggleUnderline,
toggleStrikethrough
} = await import(/* webpackChunkName: "roosterjs", webpackPreload: true */ 'roosterjs');
if (!editorInstance || editorInstance.isDisposed()) {
return;
}
let formatState: FormatState;
try {
formatState = getFormatState(editorInstance);
} catch {
// in tests, it can happen that the (JSDom) window is closed as the format state is being read
return;
}
const config: ToolbarConfig = {
bold: {
isActive: !!formatState.isBold,
toggle: () => {
toggleBold(editorInstance);
},
},
italic: {
isActive: !!formatState.isItalic,
toggle: () => {
toggleItalic(editorInstance);
},
},
underline: {
isActive: !!formatState.isUnderline,
toggle: () => {
toggleUnderline(editorInstance);
},
},
strikethrough: {
isActive: !!formatState.isStrikeThrough,
toggle: () => {
toggleStrikethrough(editorInstance);
},
},
fontFace: {
value: cleanRoosterFont(formatState.fontName),
setValue: (nextFontFace) => {
setFontName(editorInstance, nextFontFace);
},
},
fontSize: {
value: formatState.fontSize,
setValue: (nextFontSize) => {
setFontSize(editorInstance, nextFontSize);
},
},
defaultFont: {
showModal: () => {
options.showModalDefaultFont({
onChange: (nextFontFace, nextFontSize) => {
setFontSize(editorInstance, `${nextFontSize}px`);
setFontName(editorInstance, nextFontFace);
},
});
},
},
fontColor: {
value: rgbToHex(formatState.textColor) || DEFAULT_FONT_COLOR,
setValue: (nextColor) => {
setTextColor(editorInstance, nextColor);
},
},
backgroundColor: {
value: rgbToHex(formatState.backgroundColor) || DEFAULT_BACKGROUND,
setValue: (nextColor) => {
setBackgroundColor(editorInstance, nextColor);
},
},
unorderedList: {
isActive: !!formatState.isBullet,
toggle: () => {
toggleBullet(editorInstance);
},
},
orderedList: {
isActive: !!formatState.isNumbering,
toggle: () => {
toggleNumbering(editorInstance);
},
},
alignment: {
setValue: (nextAlignement) => {
setAlignment(editorInstance, nextAlignement);
},
},
blockquote: {
isActive: !!formatState.isBlockQuote,
toggle: () => {
toggleBlockQuote(editorInstance);
},
},
link: {
showModal: () => {
options.showModalLink({ editor: editorInstance, createLink });
},
},
image: {
showModal: () => {
options.showModalImage({
onAddImages: (images) => {
if (options.onAddAttachments) {
options.onAddAttachments(images);
} else {
images.forEach((image) => {
insertImage(editorInstance, image);
});
}
},
onAddUrl: (url) => {
const imageNode = document.createElement('img');
imageNode.src = url;
imageNode.classList.add('proton-embedded');
editorInstance.insertNode(imageNode);
},
});
},
},
formatting: {
clear: () => {
clearFormat(editorInstance);
removeLink(editorInstance);
},
},
textDirection: {
setValue: (nextDirection) => {
setDirection(editorInstance, getRoosterDirection(nextDirection));
options.onChangeMetadata?.({ rightToLeft: nextDirection });
},
},
emoji: {
insert: (emoji) => {
editorInstance.insertContent(emoji.native);
},
},
};
return config;
};
| 5,343
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/helpers/rgbToHex.ts
|
import tinycolor from 'tinycolor2';
const rgbToHex = (rgb = '') => {
const color = tinycolor(rgb);
if (!color) {
return;
}
return color.toHexString();
};
export default rgbToHex;
| 5,344
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/hooks/interface.ts
|
import { IEditor } from 'roosterjs-editor-types';
export interface ModalLinkProps {
editor: IEditor;
createLink: (editor: IEditor, link: string, altText?: string, displayText?: string) => void;
}
export interface ModalImageProps {
onAddUrl: (url: string) => void;
onAddImages: (files: File[]) => void;
}
export interface ModalDefaultFontProps {
onChange: (nextFontFace: string, nextFontSize: number) => void;
}
| 5,345
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/hooks/useEditorModal.tsx
|
import { useCallback, useState } from 'react';
import { useModalState } from '../../../components';
function useEditorModal<P>() {
const [modalsStateProps, openModal, render] = useModalState();
const [modalProps, setModalProps] = useState<P>();
const showModal = useCallback((props: P) => {
setModalProps(props);
openModal(true);
}, []);
return { showCallback: showModal, props: modalProps, modalsStateProps, render };
}
export default useEditorModal;
| 5,346
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/hooks/useToolbar.tsx
|
import { useRef } from 'react';
import { EditorMetadata } from '@proton/components/components';
import {
ModalDefaultFontProps,
ModalImageProps,
ModalLinkProps,
} from '@proton/components/components/editor/hooks/interface';
import useEditorModal from '@proton/components/components/editor/hooks/useEditorModal';
import useToolbarConfig from '@proton/components/components/editor/hooks/useToolbarConfig';
interface Props {
onChangeMetadata?: (metadataChange: Partial<EditorMetadata>) => void;
onAddAttachments?: (files: File[]) => void;
}
export const useToolbar = ({ onChangeMetadata, onAddAttachments }: Props) => {
const modalLink = useEditorModal<ModalLinkProps>();
const modalImage = useEditorModal<ModalImageProps>();
const modalDefaultFont = useEditorModal<ModalDefaultFontProps>();
const openEmojiPickerRef = useRef<() => void>(null);
const [toolbarConfig, setToolbarConfig] = useToolbarConfig({
showModalImage: modalImage.showCallback,
showModalLink: modalLink.showCallback,
showModalDefaultFont: modalDefaultFont.showCallback,
onChangeMetadata,
onAddAttachments,
});
return { openEmojiPickerRef, toolbarConfig, setToolbarConfig, modalLink, modalDefaultFont, modalImage };
};
| 5,347
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/hooks/useToolbarConfig.tsx
|
import { useCallback, useState } from 'react';
import useIsMounted from '@proton/hooks/useIsMounted';
import { ToolbarConfig, getToolbarConfig } from '../helpers/getToolbarConfig';
import { EditorMetadata, SetEditorToolbarConfig } from '../interface';
import { ModalDefaultFontProps, ModalImageProps, ModalLinkProps } from './interface';
interface Props {
showModalLink: (options: ModalLinkProps) => void;
showModalImage: (options: ModalImageProps) => void;
showModalDefaultFont: (options: ModalDefaultFontProps) => void;
onChangeMetadata: ((metadataChange: Partial<EditorMetadata>) => void) | undefined;
onAddAttachments: ((files: File[]) => void) | undefined;
}
const useToolbarConfig = (props: Props): [ToolbarConfig | undefined, SetEditorToolbarConfig] => {
const [toolbarConfig, setToolbarConfig] = useState<ToolbarConfig>();
const isMounted = useIsMounted();
const setConfigCallback = useCallback<SetEditorToolbarConfig>(
(editorInstance) => {
void getToolbarConfig(editorInstance, props).then((toolbarConfig) => {
// Do not set state if component is unmounted
if (!isMounted()) {
return;
}
setToolbarConfig(toolbarConfig);
});
},
[props]
);
return [toolbarConfig, setConfigCallback];
};
export default useToolbarConfig;
| 5,348
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/modals/DefaultFontModal.tsx
|
import React, { useState } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { updateFontFace, updateFontSize } from '@proton/shared/lib/api/mailSettings';
import { Form, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader } from '../../../components';
import FontFaceSelect from '../../../containers/layouts/FontFaceSelect';
import FontSizeSelect from '../../../containers/layouts/FontSizeSelect';
import { useApi, useEventManager, useMailSettings, useNotifications } from '../../../hooks';
import { DEFAULT_FONT_FACE, DEFAULT_FONT_SIZE } from '../constants';
import { getFontFaceIdFromValue, getFontFaceValueFromId } from '../helpers/fontFace';
interface Props {
onClose?: () => void;
onChange?: (nextFontFace: string, nextFontSize: number) => void;
}
const DefaultFontModal = ({ onChange, onClose, ...rest }: Props) => {
const api = useApi();
const [settings] = useMailSettings();
const [fontFace, setFontFace] = useState(getFontFaceValueFromId(settings?.FontFace) || DEFAULT_FONT_FACE);
const [fontSize, setFontSize] = useState(settings?.FontSize || DEFAULT_FONT_SIZE);
const [loading, setLoading] = useState(false);
const { createNotification } = useNotifications();
const { call } = useEventManager();
const changedFontFace = fontFace !== settings?.FontFace;
const changedFontSize = fontSize !== settings?.FontSize;
const somethingChanged = changedFontFace || changedFontSize;
const notifyPreferenceSaved = () => createNotification({ text: c('Success').t`Preference saved` });
const onSubmit = async () => {
setLoading(true);
if (changedFontFace) {
const fontFaceId = getFontFaceIdFromValue(fontFace);
if (fontFaceId) {
await api(updateFontFace(fontFaceId));
}
}
if (changedFontSize) {
await api(updateFontSize(fontSize));
}
if (somethingChanged) {
await call();
notifyPreferenceSaved();
}
onChange?.(fontFace, fontSize);
setLoading(false);
onClose?.();
};
return (
<ModalTwo onSubmit={onSubmit} onClose={onClose} as={Form} size="small" {...rest}>
<ModalTwoHeader title={c('Update font modal').t`Update default font and size`} />
<ModalTwoContent>
<div>
<div className="flex flex-row">
<div className="mr-4">
<FontFaceSelect
id="fontFace"
fontFace={fontFace}
onChange={setFontFace}
loading={loading}
/>
</div>
<div>
<FontSizeSelect
id="fontSize"
fontSize={fontSize}
onChange={setFontSize}
loading={loading}
/>
</div>
</div>
<p>
<span className="color-weak">{c('Update font modal')
.t`Your default font will look like following:`}</span>
<br />
<span className="mt-0" style={{ fontFamily: fontFace, fontSize: `${fontSize}px` }}>{c(
'Update font modal'
).t`Today is a good day to write an email`}</span>
</p>
</div>
</ModalTwoContent>
<ModalTwoFooter>
<Button type="reset" onClick={onClose}>{c('Action').t`Cancel`}</Button>
<Button color="norm" type="submit" disabled={!somethingChanged}>{c('Action').t`Update`}</Button>
</ModalTwoFooter>
</ModalTwo>
);
};
export default DefaultFontModal;
| 5,349
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/modals/InsertImageModal.tsx
|
import { ChangeEvent, useCallback, useEffect, useState } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { isValidHttpUrl } from '@proton/shared/lib/helpers/url';
import debounce from '@proton/utils/debounce';
import { generateUID } from '../../../helpers';
import { PrimaryButton } from '../../button';
import FileButton from '../../button/FileButton';
import { Form } from '../../form';
import Input from '../../input/Input';
import Label from '../../label/Label';
import { ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader } from '../../modalTwo';
enum ImageState {
Initial,
Loading,
Error,
Ok,
}
interface Props {
onAddUrl?: (url: string) => void;
onAddImages?: (files: File[]) => void;
onClose?: () => void;
}
const InsertImageModal = ({ onAddUrl, onAddImages, onClose, ...rest }: Props) => {
const [uid] = useState(generateUID('editor-image-modal'));
const [imageSrc, setImageSrc] = useState<string>();
const [imageState, setImageState] = useState(ImageState.Initial);
const [isImageLoading, setIsImageLoading] = useState(false);
const handleSuccess = () => {
setImageState(ImageState.Ok);
setIsImageLoading(false);
};
const handleError = () => {
setImageState(ImageState.Error);
setIsImageLoading(false);
};
// Check if the image url is valid
const checkImageUrl = (url: string) => {
if (!isValidHttpUrl(url)) {
setImageState(ImageState.Error);
} else {
setIsImageLoading(true);
const image = new Image();
image.onload = () => handleSuccess();
image.onerror = () => handleError();
image.src = url;
}
};
const debouncedCheckImage = useCallback(
debounce((url) => {
checkImageUrl(url);
}, 200),
[]
);
useEffect(() => {
if (imageSrc) {
debouncedCheckImage(imageSrc);
}
}, [imageSrc]);
const handleChange = async (event: ChangeEvent<HTMLInputElement>) => {
setImageSrc(event.target.value);
};
const handleSubmit = () => {
onAddUrl?.(imageSrc as string);
onClose?.();
};
const handleAddFiles = (files: File[]) => {
onAddImages?.(files);
onClose?.();
};
return (
<ModalTwo size="large" as={Form} onSubmit={handleSubmit} onClose={onClose} {...rest}>
<ModalTwoHeader title={c('Info').t`Insert image`} onSubmit={handleSubmit} />
<ModalTwoContent>
<div className="mb-4">
<div className="flex flex-nowrap on-mobile-flex-column">
<Label htmlFor={`editor-image-address-${uid}`}>{c('Info').t`Add image URL`}</Label>
<div className="flex-item-fluid">
<Input
id={`editor-image-address-${uid}`}
type="text"
autoComplete="off"
placeholder={c('Info').t`Image URL`}
error={imageState === ImageState.Error ? c('Info').t`Not a valid URL` : undefined}
onChange={handleChange}
data-testid="insert-image:url"
autoFocus
/>
</div>
</div>
</div>
<div className="flex flex-nowrap mb-4 on-mobile-flex-column">
<Label htmlFor={`editor-image-upload-${uid}`}>{c('Info').t`Upload picture`}</Label>
<div className="flex-item-fluid" data-testid="insert-image:upload">
<FileButton
id={`editor-image-upload-${uid}`}
className="inline-flex relative flex-align-items-center"
onAddFiles={handleAddFiles}
>
{c('Action').t`Upload picture`}
</FileButton>
</div>
</div>
</ModalTwoContent>
<ModalTwoFooter>
<Button type="reset" data-testid="insert-image:cancel" onClick={onClose}>{c('Action')
.t`Cancel`}</Button>
<PrimaryButton
type="submit"
disabled={imageState !== ImageState.Ok}
data-testid="insert-image:save"
loading={isImageLoading}
>
{c('Action').t`Save`}
</PrimaryButton>
</ModalTwoFooter>
</ModalTwo>
);
};
export default InsertImageModal;
| 5,350
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/modals
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/modals/InsertLinkModal/InsertLinkModal.tsx
|
import { useMemo } from 'react';
import { SelectionRangeTypes } from 'roosterjs-editor-types';
import { ModalStateProps } from '../../../modalTwo';
import { ModalLinkProps } from '../../hooks/interface';
import InsertLinkModalComponent from './InsertLinkModalComponent';
interface Props extends ModalLinkProps {
modalStateProps: ModalStateProps;
}
export type InsertLinkSelectionType = 'text-with-img' | 'img' | 'text' | 'empty';
const InsertLinkModal = ({ editor, createLink, modalStateProps }: Props) => {
const values = useMemo(() => {
if (editor.isDisposed()) {
return;
}
if (!editor.hasFocus()) {
editor.focus();
}
const selectionRangeFragment = editor.getSelectionRange()?.cloneContents();
const selectionRangeEx = editor.getSelectionRangeEx();
const cursorLinkElement = (editor.getElementAtCursor('a[href]') as HTMLLinkElement) || undefined;
return {
selectionRangeEx,
selectionRangeFragment,
cursorLinkElement,
};
}, []);
const { selectionType, href, title } = useMemo(() => {
const hasTextContent = values?.selectionRangeFragment?.textContent;
const hasImage = values?.selectionRangeFragment?.querySelector('img');
const href = values?.cursorLinkElement?.getAttribute('href') || undefined;
const title = values?.cursorLinkElement?.getAttribute('title') || undefined;
const selectionType: InsertLinkSelectionType = (() => {
if (hasTextContent && hasImage) {
return 'text-with-img';
}
if ((!hasTextContent && hasImage) || values?.selectionRangeEx.type === SelectionRangeTypes.ImageSelection) {
return 'img';
}
if (hasTextContent && !hasImage) {
return 'text';
}
return 'empty';
})();
return {
selectionType,
href,
title,
};
}, [values]);
const handleSubmit = (url: string, altAttribute: string | undefined, textToDisplay?: string | undefined) => {
createLink(editor, url, altAttribute, textToDisplay);
};
return (
<InsertLinkModalComponent
modalStateProps={modalStateProps}
onSubmit={handleSubmit}
selectionType={selectionType}
title={values?.selectionRangeFragment?.textContent || values?.cursorLinkElement?.textContent || title || ''}
url={href}
/>
);
};
export default InsertLinkModal;
| 5,351
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/modals
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/modals/InsertLinkModal/InsertLinkModalComponent.tsx
|
import { ChangeEvent, useRef, useState } from 'react';
import { c } from 'ttag';
import { Button, Href, Input } from '@proton/atoms';
import { useMailSettings } from '@proton/components/hooks';
import { LINK_TYPES } from '@proton/shared/lib/constants';
import { addLinkPrefix, linkToType } from '@proton/shared/lib/helpers/url';
import { useLinkHandler } from '../../../../hooks/useLinkHandler';
import { PrimaryButton } from '../../../button';
import Field from '../../../container/Field';
import Row from '../../../container/Row';
import { Form } from '../../../form';
import Label from '../../../label/Label';
import { ModalStateProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader } from '../../../modalTwo';
import { Option } from '../../../option';
import { SelectTwo } from '../../../selectTwo';
import { InsertLinkSelectionType } from './InsertLinkModal';
export interface InsertLinkModalProps {
modalStateProps: ModalStateProps;
onSubmit: (url: string, altAttribute: string | undefined, textToDisplay?: string) => void;
selectionType: InsertLinkSelectionType;
title: string;
url?: string;
}
const InsertLinkModalComponent = ({
modalStateProps,
onSubmit,
selectionType,
title,
url: initialUrl,
}: InsertLinkModalProps) => {
const [mailSettings] = useMailSettings();
const modalContentRef = useRef<HTMLDivElement>(null);
const [type, setType] = useState(linkToType(initialUrl) || LINK_TYPES.WEB);
const [url, setUrl] = useState(initialUrl || '');
const [label, setLabel] = useState<string>(title);
const hasImageInSelection = ['text-with-img', 'img'].includes(selectionType);
// if image only url is required
// if text label and url are required
const canSubmit = hasImageInSelection ? !!url : !!(label && url);
const { modal: linkModal } = useLinkHandler(modalContentRef, mailSettings);
const typesOptions = [
{ value: LINK_TYPES.WEB, text: c('Info').t`Web URL` },
{ value: LINK_TYPES.EMAIL, text: c('Info').t`Email address` },
{ value: LINK_TYPES.PHONE, text: c('Info').t`Phone number` },
];
const i18n = {
[LINK_TYPES.WEB]: {
label: c('Info').t`URL link`,
placeholder: c('Placeholder').t`Link`,
},
[LINK_TYPES.EMAIL]: {
label: c('Info').t`Email address`,
placeholder: c('Placeholder').t`Email address`,
},
[LINK_TYPES.PHONE]: {
label: c('Info').t`Phone number`,
placeholder: c('Placeholder').t`Phone number`,
},
};
const handleUrlChange = (event: ChangeEvent<HTMLInputElement>) => {
setUrl(event.target.value);
if (url === label && !hasImageInSelection) {
setLabel(event.target.value);
}
};
const handleSubmit = () => {
onSubmit(addLinkPrefix(url, type), label, !hasImageInSelection ? label : undefined);
modalStateProps.onClose();
};
return (
<>
<ModalTwo as={Form} onSubmit={handleSubmit} size="large" {...modalStateProps}>
<ModalTwoHeader title={url ? c('Info').t`Edit link` : c('Info').t`Insert link`} />
<ModalTwoContent>
<div ref={modalContentRef}>
<div className="mb-4">{c('Info')
.t`Please select the type of link you want to insert and fill in all the fields.`}</div>
<Row>
<Label htmlFor="link-modal-type" className="flex flex-column">
{c('Info').t`Link type`}
</Label>
<Field>
<SelectTwo
id="link-modal-type"
value={type}
onChange={({ value }) => {
setType(value);
}}
>
{typesOptions.map((option) => (
<Option key={option.value} value={option.value} title={option.text} />
))}
</SelectTwo>
</Field>
</Row>
<Row>
<Label htmlFor="link-modal-url" className="flex flex-column">
{i18n[type].label}
</Label>
<Field>
<Input
id="link-modal-url"
value={url}
onChange={handleUrlChange}
placeholder={i18n[type].placeholder}
required
autoFocus
title={c('Info').t`Please fill out this field.`}
/>
</Field>
</Row>
{selectionType !== 'text-with-img' && (
<Row>
<Label htmlFor="link-modal-label" className="flex flex-column">
{selectionType === 'img'
? c('Info').t`Image description`
: c('Info').t`Text to display`}
</Label>
<Field>
<Input
id="link-modal-label"
value={label}
onChange={(event: ChangeEvent<HTMLInputElement>) =>
setLabel(event.target.value)
}
placeholder={c('Placeholder').t`Text`}
required={selectionType !== 'img'}
title={c('Info').t`Please fill out this field.`}
/>
</Field>
</Row>
)}
{!hasImageInSelection && (
<Row>
<Label>{c('Info').t`Test link`}</Label>
<Field className="pt-2 text-ellipsis">
{url && label ? (
<Href href={addLinkPrefix(url, type)} title={label}>
{label}
</Href>
) : (
<span className="placeholder">{c('Placeholder')
.t`Please insert link first`}</span>
)}
</Field>
</Row>
)}
</div>
</ModalTwoContent>
<ModalTwoFooter>
<Button onClick={modalStateProps.onClose} data-testid="insert-link:cancel">
{c('Action').t`Cancel`}
</Button>
<PrimaryButton type="submit" disabled={!canSubmit}>
{c('Action').t`Insert`}
</PrimaryButton>
</ModalTwoFooter>
</ModalTwo>
{linkModal}
</>
);
};
export default InsertLinkModalComponent;
| 5,352
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/plainTextEditor/PlainTextEditor.tsx
|
import { ChangeEvent, ReactNode, useEffect, useRef } from 'react';
import useIsMounted from '@proton/hooks/useIsMounted';
import { EditorActions } from '../interface';
interface Props {
onChange: (value: string) => void;
onReady: (editorActions: EditorActions) => void;
onFocus: () => void;
// Needed for dropzone
children?: ReactNode;
}
const PlainTextEditor = ({ onFocus, onReady, onChange, children, ...rest }: Props) => {
const textareaRef = useRef<HTMLTextAreaElement>(null);
const isMountedCallback = useIsMounted();
useEffect(() => {
const actions: EditorActions = {
focus: () => {
textareaRef.current?.focus();
},
getContent: () => {
return textareaRef.current?.value || '';
},
setContent: (value: string) => {
if (textareaRef.current) {
textareaRef.current.value = value;
// setTimeout is needed for Firefox
// I guess setting the value is async and we have to release the thread before touching to the selection
setTimeout(() => textareaRef.current?.setSelectionRange(0, 0));
}
},
isDisposed: () => isMountedCallback() === false || !textareaRef.current,
scroll: (scrollToOption: ScrollToOptions) => {
textareaRef.current?.scrollTo?.(scrollToOption);
},
};
onReady(actions);
}, []);
return (
<div className="w-full h-full pt-2 pb-4 px-2" {...rest}>
<textarea
className="w-full h-full"
ref={textareaRef}
onFocus={onFocus}
onChange={(event: ChangeEvent<HTMLTextAreaElement>) => {
onChange(event.target.value);
}}
data-testid="editor-textarea"
/>
{children}
</div>
);
};
export default PlainTextEditor;
| 5,353
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/rooster/BlockquoteToggle.tsx
|
import { c } from 'ttag';
import { Icon } from '@proton/components';
interface Props {
show: boolean | undefined;
onClick: (() => void) | undefined;
}
const BlockquoteToggle = ({ show = false, onClick = () => {} }: Props) =>
show ? (
<button className="proton-toggle-button inline-flex" type="button" onClick={onClick} id="ellipsis">
<Icon name="three-dots-horizontal" size={14} className="m-auto" />
<span className="proton-sr-only">{c('Info').t`Show original message`}</span>
</button>
) : null;
export default BlockquoteToggle;
| 5,354
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/rooster/RoosterEditor.scss
|
@import '~@proton/styles/scss/lib';
.simple-editor.editor {
overflow: hidden;
min-block-size: 14em;
}
.editor {
&:hover {
border-color: var(--field-hover);
}
.editor-toolbar-button {
position: relative;
padding-block: 0.3em;
padding-inline: 0.4em;
min-block-size: 2em;
border-radius: var(--border-radius-sm);
}
.composer-toolbar-fontDropDown {
flex-shrink: 1;
& > span {
display: flex;
& > * {
min-inline-size: 0;
}
}
}
}
// .editor-toolbar {
// border-block-end: 1px solid var(--border-norm);
// }
.editor-toolbar-separator {
border-inline-start: 1px solid var(--border-norm);
}
.editor-squire-wrapper {
.placeholder {
// The point is to match exactly Squire text content and position
font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif;
font-size: rem(14);
line-height: 1.65;
// margin-inline-start: rem(8);
margin-block-start: rem(8);
color: grey;
}
}
.editor-toolbar-dropdown {
ul {
margin: 0;
}
button {
padding-inline: 0.5em;
box-shadow: unset;
}
.dropdown-item-container {
border: unset;
box-shadow: unset;
}
// "default" button
.button-ghost-weak {
&:focus-visible {
border-color: var(--interaction-norm-contrast);
}
}
}
.editor-toolbar-dropdown .color-selector-container {
--color-item-size: #{em(28)};
--color-grid-items: 7;
}
.editor--disabled::after {
content: '';
position: absolute;
inset: 0;
background-color: var(--background-weak);
border-radius: var(--border-radius-md);
}
.editor-toolbar-more-menu .dropdown-item.dropdown-item--no-separator {
border-block-start: none;
}
.editor-toolbar-button {
padding: 0.4em;
& > span {
margin-inline: 0;
inline-size: 100%;
display: flex;
align-items: center;
& > .mr-2 {
flex: 1 1 0px;
text-align: start;
display: inline-flex;
}
}
.editor-toolbar-icon {
color: var(--text-norm);
}
}
.editor-toolbar-more-dropdown {
.editor-toolbar-icon {
inline-size: em(16);
block-size: em(16);
}
}
| 5,355
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/rooster/RoosterEditor.tsx
|
import { useRef } from 'react';
import { createPortal } from 'react-dom';
import { c } from 'ttag';
import { MailSettings } from '@proton/shared/lib/interfaces';
import clsx from '@proton/utils/clsx';
import DropzoneContent, { DropzoneContentProps } from '../../dropzone/DropzoneContent';
import { EDITOR_BLOCKQUOTE_TOGGLE_CONTAINER_ID, EDITOR_DROPZONE } from '../constants';
import { ModalLinkProps } from '../hooks/interface';
import { EditorActions, SetEditorToolbarConfig } from '../interface';
import BlockquoteToggle from './BlockquoteToggle';
import useBubbleIframeEvents from './hooks/useBubbleIframeEvents';
import useComposerDrag from './hooks/useComposerDrag';
import useInitRooster from './hooks/useInitRooster';
import useOnEditorChange from './hooks/useOnEditorChange';
import './RoosterEditor.scss';
interface Props {
onChange?: (value: string) => void;
showBlockquoteToggle?: boolean;
onBlockquoteToggleClick?: () => void;
onReady: (editorActions: EditorActions) => void;
setToolbarConfig: SetEditorToolbarConfig;
onPasteImage: (image: File) => void;
mailSettings?: MailSettings;
showModalLink: (props: ModalLinkProps) => void;
onFocus?: () => void;
className?: string;
openEmojiPicker: () => void;
dropzone?: DropzoneContentProps;
onAddAttachments?: (files: File[]) => void;
}
const RoosterEditor = ({
onChange,
onReady,
showBlockquoteToggle,
onBlockquoteToggleClick,
setToolbarConfig,
onPasteImage,
showModalLink,
onFocus,
mailSettings,
className,
openEmojiPicker,
dropzone,
onAddAttachments,
}: Props) => {
const iframeRef = useRef<HTMLIFrameElement>(null);
const onEditorChangeCallback = useOnEditorChange({
setToolbarConfig,
onChange,
});
useInitRooster({
iframeRef,
initialContent: '',
onReady,
onEditorChange: onEditorChangeCallback,
showModalLink,
onFocus,
mailSettings,
onPasteImage,
openEmojiPicker,
});
useBubbleIframeEvents(iframeRef);
const isDragging = useComposerDrag(iframeRef, onAddAttachments);
const blockquoteContainer = iframeRef.current?.contentDocument?.getElementById(
EDITOR_BLOCKQUOTE_TOGGLE_CONTAINER_ID
);
const dropzoneContainer =
dropzone && isDragging ? iframeRef.current?.contentDocument?.getElementById(EDITOR_DROPZONE) : undefined;
return (
<>
<div
className={clsx([
'editor-wrapper fill w-full h-full scroll-if-needed flex-item-fluid flex flex-column relative',
className,
])}
>
<iframe
ref={iframeRef}
title={c('Title').t`Email composer`}
frameBorder="0"
className="w-full h-full flex-item-fluid"
data-testid="rooster-iframe"
/>
</div>
{blockquoteContainer &&
createPortal(
<BlockquoteToggle show={showBlockquoteToggle} onClick={onBlockquoteToggleClick} />,
blockquoteContainer
)}
{dropzoneContainer ? createPortal(<DropzoneContent {...dropzone} embedded />, dropzoneContainer) : null}
</>
);
};
export default RoosterEditor;
| 5,356
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/rooster/RoosterEditorIframe.raw.scss
|
@use 'sass:math';
@import '~@proton/styles/scss/lib';
@import '~@proton/styles/scss/base/custom-properties/init';
@import '~@proton/styles/scss/base/custom-properties/optionals';
@import '~@proton/components/components/dropzone/Dropzone';
.proton {
&-h-full {
block-size: 100%;
}
&-w-full {
inline-size: 100%;
}
&-flex {
display: flex;
flex-wrap: wrap;
}
&-flex-justify-center {
justify-content: center;
}
&-flex-align-items-center {
align-items: center;
}
&-rounded-xl {
border-radius: var(--border-radius-xl);
}
&-text-xl {
font-size: 18em;
}
&-text-bold {
font-weight: var(--font-weight-bold);
}
&-text-center {
text-align: center;
}
&-color-weak {
color: var(--text-weak);
}
&-m-0 {
margin: 0;
}
&-mb-0 {
margin-block-end: 0;
}
&-mt-5 {
margin-block-start: 1.5em;
}
&-hidden {
display: none;
}
&-sr-only {
border: 0;
clip: rect(0 0 0 0);
block-size: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
inline-size: 1px;
inset-block-start: 0; // needed for Safari dumb and 💩 behaviour
}
}
// custom scroll
body:not(.isDarkMode) {
--scrollbar-thumb-color: rgb(0 0 0 / 0.35);
--scrollbar-thumb-hover-color: rgb(0 0 0 / 0.5);
}
body.isDarkMode {
--scrollbar-thumb-color: rgb(255 255 255 / 0.2);
--scrollbar-thumb-hover-color: rgb(255 255 255 / 0.5);
}
html:not(.feature-scrollbars-off) {
* {
scrollbar-width: thin;
scrollbar-color: var(--scrollbar-thumb-color) transparent;
}
*::-webkit-scrollbar {
inline-size: 0.625rem; /* 10px */
block-size: 0.625rem;
}
*::-webkit-scrollbar-thumb {
border: 0.125rem solid transparent; /* 2px */
background-clip: padding-box;
border-radius: 0.313rem; /* 5px */
background-color: var(--scrollbar-thumb-color, rgb(0 0 0 / 0.35));
}
*::-webkit-scrollbar-track {
background-color: transparent;
}
*::-webkit-scrollbar-thumb:horizontal:hover,
*::-webkit-scrollbar-thumb:vertical:hover {
background-color: var(--scrollbar-thumb-hover-color, rgb(0 0 0 / 0.5));
}
*::-webkit-scrollbar-corner {
visibility: hidden;
}
}
html {
block-size: 100%;
cursor: text;
/* Introduce `--setting-font-size` to make the font size setting possible. */
/* chosen size * browser default size / app default size * 100% / browser default size */
font-size: calc(var(--setting-font-size) * #{math.div(16, 14) * math.div(100%, 16)});
}
@mixin reduce-motion {
*,
*::before,
*::after {
// Using values greater than 0 to have animation events still triggering
animation-delay: 1ms !important;
animation-duration: 0.001ms !important;
animation-iteration-count: 1 !important;
// This magic value is needed because of https://bugs.webkit.org/show_bug.cgi?id=242510
// which affects visibility changes on Safari (iOS + MacOS) when reduce motion is
// enabled in accessibility settings. Even though transitions are not involved.
transition-duration: 0.01ms !important;
}
}
@include media('reduced-motion') {
@include reduce-motion;
}
.feature-animations-off {
@include reduce-motion;
}
body {
box-sizing: border-box;
font-family: system-ui, sans-serif;
font-size: 0.875rem; /* 14 */
line-height: 1.5; // Need to be bigger so that we don't have jumps when adding emojis
color: black;
background: white;
/* to fix, CSS var are not passing through the iframe */
word-wrap: break-word;
margin: 0;
}
body a {
// force blue even for :visited
color: blue;
}
#proton-editor-container {
display: flex;
flex-direction: column;
justify-content: space-between;
block-size: 100%;
}
#rooster-editor-wrapper {
flex-grow: 1;
display: flex;
flex-direction: column;
justify-content: space-between;
}
#rooster-editor {
flex: 1;
outline: none;
padding: 0.5rem;
}
#proton-editor-toggle-container {
flex-shrink: 0;
}
blockquote {
padding-block: 0;
padding-inline: 1rem 0;
margin: 0;
border-inline-start: 4px solid #e5e5e5;
}
blockquote blockquote blockquote {
padding-inline-start: 0;
margin-inline-start: 0;
border: none;
}
.icon-14p {
inline-size: 14px;
block-size: 14px;
}
.proton-toggle-button {
display: inline-block;
padding-block: rem(4);
padding-inline: rem(8);
margin: 1em;
margin-inline-start: 0.5em;
box-shadow: inset 0 0 0 1px silver;
border: none;
border-radius: 8px;
outline: none;
background-color: transparent;
text-align: center;
transition:
0.15s cubic-bezier(0.22, 1, 0.36, 1),
background-position 0s;
&:hover,
&:focus,
&:focus-within &.is-hover &:active,
&.is-active,
&[aria-expanded='true']:not([aria-controls]) {
text-decoration: none;
box-shadow: inset 0 0 0 2px silver;
background-color: transparent;
}
}
@supports selector(:focus-visible) {
.proton-toggle-button {
outline: unset;
}
}
.proton-embedded:not([src]) {
position: relative;
min-block-size: 38px;
border: 1px solid;
border-color: #444 #ccc #ccc #444;
}
.proton-embedded:not([src], [alt]) {
background-position-x: 50%;
}
.proton-embedded[alt]:not([src])::after {
position: absolute;
inset: 0;
content: ' ' attr(alt);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
padding-block: 10px 0;
padding-inline: 20px 0;
color: rgb(0 0 0 / 0.5);
}
/* see embedded.scss rules */
.proton-embedded:not([width], [style*='width']) {
max-inline-size: 100%;
min-inline-size: 38px;
}
.protonmail_quote {
position: relative;
}
ul,
ol {
/**
* Overrides app reset in order to get back to native browser spacing
* Fix issue when ordered list has more than 10 items
*/
padding-inline-start: em(40);
margin-block: 0;
}
li {
list-style-position: outside;
}
// Handle outlook https://github.com/ProtonMail/Angular/issues/6711
p.MsoNormal,
li.MsoNormal,
div.MsoNormal {
margin: 0;
}
| 5,357
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/rooster
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/rooster/helpers/getRoosterEditorActions.ts
|
import { RefObject } from 'react';
import { IEditor } from 'roosterjs-editor-types';
import { DIRECTION } from '@proton/shared/lib/mail/mailSettings';
import { EditorActions } from '../../interface';
/**
* @param editorInstance
* @returns set of external actions
*/
const getRoosterEditorActions = (
editorInstance: IEditor,
iframeRef: RefObject<HTMLIFrameElement>,
clearUndoHistory: () => void,
setTextDirection: (direction: DIRECTION) => void,
showModalLink: () => void,
openEmojiPicker: () => void
): EditorActions => {
return {
getContent() {
return editorInstance.getContent();
},
isDisposed() {
return editorInstance.isDisposed();
},
setContent(value: string) {
editorInstance.setContent(value);
},
focus() {
if (editorInstance.isDisposed()) {
return;
}
// Helps passing tests (JSDOM issue)
try {
iframeRef.current?.focus();
editorInstance.focus();
} catch (e) {
console.error(e);
}
},
insertImage(url: string, attrs: { [key: string]: string } = {}) {
const imageNode = document.createElement('img');
Object.entries(attrs).forEach(([key, value]) => {
imageNode.setAttribute(key, value);
});
imageNode.src = url;
imageNode.classList.add('proton-embedded');
editorInstance.insertNode(imageNode);
editorInstance.triggerContentChangedEvent();
},
clearUndoHistory,
setTextDirection,
showModalLink,
openEmojiPicker,
};
};
export default getRoosterEditorActions;
| 5,358
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/rooster
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/rooster/helpers/initRoosterEditor.ts
|
import { RefObject } from 'react';
import { DefaultFormat, Direction, EditorPlugin, IEditor } from 'roosterjs-editor-types';
import { isMac } from '@proton/shared/lib/helpers/browser';
import { MailSettings } from '@proton/shared/lib/interfaces';
import { DIRECTION } from '@proton/shared/lib/mail/mailSettings';
import {
DEFAULT_BACKGROUND,
DEFAULT_FONT_COLOR,
DEFAULT_FONT_FACE,
DEFAULT_FONT_SIZE,
ROOSTER_SNAPSHOTS_MAX_SIZE,
} from '../../constants';
import { getFontFaceValueFromId } from '../../helpers/fontFace';
import { ModalLinkProps } from '../../hooks/interface';
import { EditorActions, OnEditorEventListened } from '../../interface';
import EditorCustomPastePlugin from '../plugins/EditorCustomPastePlugin';
import EditorEventListener from '../plugins/EditorEventListener';
import UndoSnapshots from '../plugins/UndoSnapshots';
import getRoosterEditorActions from './getRoosterEditorActions';
interface Options {
onEditorEvent: OnEditorEventListened;
initialContent?: string;
showModalLink: (props: ModalLinkProps) => void;
iframeRef: RefObject<HTMLIFrameElement>;
mailSettings?: MailSettings;
onPasteImage: (image: File) => void;
openEmojiPicker: () => void;
}
interface InitRoosterReturns {
editor: IEditor;
actions: EditorActions;
}
export const getRoosterDirection = (direction: DIRECTION) =>
direction === DIRECTION.RIGHT_TO_LEFT ? Direction.RightToLeft : Direction.LeftToRight;
export const initRoosterEditor = async (element: HTMLDivElement, options: Options): Promise<InitRoosterReturns> => {
const {
ContentEdit,
Paste,
HyperLink,
Editor,
CutPasteListChain,
ExperimentalFeatures,
createSnapshots,
addSnapshot,
canMoveCurrentSnapshot,
canUndoAutoComplete,
clearProceedingSnapshots,
moveCurrentSnapshot,
setDirection,
createLink,
} = await import(/* webpackChunkName: "roosterjs", webpackPreload: true */ 'roosterjs');
const plugins: EditorPlugin[] = [
new ContentEdit({
indentWhenAltShiftRight: !isMac(),
outdentWhenAltShiftLeft: !isMac(),
}),
new Paste(),
new CutPasteListChain(),
new HyperLink(),
new EditorEventListener(options.onEditorEvent),
new EditorCustomPastePlugin(options.onPasteImage),
];
const fontSize = options.mailSettings?.FontSize ? `${options.mailSettings.FontSize}px` : `${DEFAULT_FONT_SIZE}px`;
const fontFamily = (() => {
if (options.mailSettings?.FontFace) {
return getFontFaceValueFromId(options.mailSettings.FontFace) || DEFAULT_FONT_FACE;
}
return DEFAULT_FONT_FACE;
})();
const defaultFormat: DefaultFormat = {
bold: false,
fontFamily,
fontSize,
textColor: DEFAULT_FONT_COLOR,
backgroundColor: DEFAULT_BACKGROUND,
};
if (element === null) {
throw new Error('Ref should be provided to instanciate the editor');
}
// Create custom undoSnapshotService in order to be able to clear snapshots
const undoSnapshotService = new UndoSnapshots(createSnapshots(ROOSTER_SNAPSHOTS_MAX_SIZE), {
addSnapshot,
canMoveCurrentSnapshot,
canUndoAutoComplete,
clearProceedingSnapshots,
createSnapshots,
moveCurrentSnapshot,
});
const editor = new Editor(element, {
plugins,
defaultFormat,
initialContent: options.initialContent,
undoSnapshotService,
experimentalFeatures: [ExperimentalFeatures.AutoFormatList],
});
const actions = getRoosterEditorActions(
editor,
options.iframeRef,
() => {
undoSnapshotService.clearSnapshots();
},
(direction: DIRECTION) => {
setDirection(editor, getRoosterDirection(direction));
},
() => {
options.showModalLink?.({ editor, createLink });
},
options.openEmojiPicker
);
return { editor, actions };
};
| 5,359
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/rooster
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/rooster/hooks/useBubbleIframeEvents.ts
|
import { RefObject, useCallback, useEffect } from 'react';
import { cloneEvent, isKeyboardEvent } from '@proton/shared/lib/helpers/events';
import { KeyboardKey } from '@proton/shared/lib/interfaces';
import { isValidShortcut } from '@proton/shared/lib/shortcuts/helpers';
import { editorShortcuts } from '@proton/shared/lib/shortcuts/mail';
import { IFRAME_EVENTS_LIST, ROOSTER_EDITOR_WRAPPER_ID } from '../../constants';
const PAGE_EVENTS = [KeyboardKey.PageUp, KeyboardKey.PageDown];
/**
* Calls event.preventDefault on matched events
* Because events occuring inside an iframe can show prompts in browsers (ex : pressing crtl+s)
* we need some specific event management here
*/
const preventKeyboardEvents = (event: Event) => {
if (isKeyboardEvent(event)) {
Object.values(editorShortcuts).forEach((shortcut) => {
if (
isValidShortcut(shortcut, event) ||
// Need to wait for this issue to be fixed
// https://bugs.chromium.org/p/chromium/issues/detail?id=890248
PAGE_EVENTS.includes(event.key as KeyboardKey)
) {
event.preventDefault();
}
});
}
};
const canDispatchEvent = (event: Event): boolean => {
if (isKeyboardEvent(event)) {
// Cancel tab keyboard event dispatch for
// keeping native focus management behavior
if (event.key.toLowerCase() === 'tab') {
return false;
}
}
return true;
};
/**
* Trigger some events manually because of Iframe stopping bubbling.
* @param iframeRef
*/
const useBubbleIframeEvents = (iframeRef: RefObject<HTMLIFrameElement>) => {
const handleBubble = useCallback((event: Event) => {
const canDispatch = canDispatchEvent(event);
preventKeyboardEvents(event);
if (canDispatch) {
const clonedEvent = cloneEvent(event);
iframeRef.current?.dispatchEvent(clonedEvent);
}
}, []);
useEffect(() => {
const iframeRoosterDiv = iframeRef.current?.contentDocument?.getElementById(ROOSTER_EDITOR_WRAPPER_ID);
if (!iframeRoosterDiv) {
return;
}
IFRAME_EVENTS_LIST.forEach((eventName) => {
iframeRoosterDiv.addEventListener(eventName, handleBubble);
});
return () => {
IFRAME_EVENTS_LIST.forEach((eventName) => {
iframeRoosterDiv.removeEventListener(eventName, handleBubble);
});
};
}, []);
};
export default useBubbleIframeEvents;
| 5,360
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/rooster
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/rooster/hooks/useComposerDrag.ts
|
import { RefObject, useEffect, useRef, useState } from 'react';
export const isDragFile = (event: DragEvent) => event.dataTransfer?.types.includes('Files');
const useComposerDrag = (iframeRef: RefObject<HTMLIFrameElement>, onAddAttachments?: (files: File[]) => void) => {
const counter = useRef(0);
const [dragStatus, setDragState] = useState<'inside' | 'outside'>('outside');
useEffect(() => {
const iframeDoc = iframeRef.current?.contentDocument;
if (!iframeDoc || !onAddAttachments) {
return;
}
const handleDragEnter = (event: DragEvent) => {
if (isDragFile(event)) {
counter.current = counter.current + 1;
setDragState('inside');
}
};
iframeDoc?.addEventListener('dragenter', handleDragEnter);
const handleDragLeave = (event: DragEvent) => {
if (isDragFile(event)) {
counter.current = counter.current - 1;
if (counter.current === 0) {
setDragState('outside');
}
}
};
iframeDoc?.addEventListener('dragleave', handleDragLeave);
const handleDragOver = (event: DragEvent) => {
if (isDragFile(event)) {
if (event.dataTransfer?.effectAllowed === 'all') {
event.dataTransfer.dropEffect = 'move';
}
event.preventDefault();
}
};
iframeDoc?.addEventListener('dragover', handleDragOver);
const handleDrop = (event: DragEvent) => {
if (isDragFile(event)) {
event.preventDefault();
// reset drag state to display the composer content
counter.current = 0;
setDragState('outside');
if (event.dataTransfer?.files && onAddAttachments) {
onAddAttachments([...event.dataTransfer.files]);
}
}
};
iframeDoc?.addEventListener('drop', handleDrop);
return () => {
iframeDoc.removeEventListener('dragenter', handleDragEnter);
iframeDoc.removeEventListener('dragleave', handleDragLeave);
iframeDoc.removeEventListener('dragover', handleDragOver);
iframeDoc.removeEventListener('drop', handleDrop);
};
}, []);
return dragStatus === 'inside';
};
export default useComposerDrag;
| 5,361
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/rooster
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/rooster/hooks/useInitRooster.ts
|
import { RefObject, useCallback, useEffect, useRef } from 'react';
import { IEditor } from 'roosterjs-editor-types';
import { useSyncIframeStyles, useTheme } from '@proton/components/containers';
import useIsMounted from '@proton/hooks/useIsMounted';
import { MailSettings } from '@proton/shared/lib/interfaces';
import {
EDITOR_BLOCKQUOTE_TOGGLE_CONTAINER_ID,
EDITOR_DROPZONE,
ROOSTER_EDITOR_ID,
ROOSTER_EDITOR_WRAPPER_ID,
} from '../../constants';
import { ModalLinkProps } from '../../hooks/interface';
import { EditorActions, OnEditorEventListened } from '../../interface';
import { initRoosterEditor } from '../helpers/initRoosterEditor';
import iframeCss from '../RoosterEditorIframe.raw.scss';
interface Props {
/**
* Container ref on which rooster instanciate
*/
iframeRef: RefObject<HTMLIFrameElement>;
onReady: (editorActions: EditorActions) => void;
onFocus?: () => void;
/**
* Notifies editor events
*/
onEditorChange: OnEditorEventListened;
initialContent?: string;
mailSettings?: MailSettings;
showModalLink: (props: ModalLinkProps) => void;
onPasteImage: (image: File) => void;
openEmojiPicker: () => void;
}
const useInitRooster = ({
iframeRef,
onReady,
onEditorChange,
initialContent,
showModalLink,
onFocus,
mailSettings,
onPasteImage,
openEmojiPicker,
}: Props) => {
const editorRef = useRef<IEditor>();
const isMounted = useIsMounted();
const theme = useTheme();
const themeCSSVariables = theme.information.style;
useSyncIframeStyles(iframeRef.current?.contentWindow?.document.documentElement, document.documentElement);
const initRooster = useCallback(async () => {
const iframe = iframeRef.current as HTMLIFrameElement;
const iframeDocument = iframe.contentWindow?.document as Document;
iframeDocument.open();
iframeDocument.write(`
<head>
<style>
${iframeCss}
${themeCSSVariables}
.proton-embedded:not([src]){
background: url('/assets/img/icons/broken-img.png') no-repeat 0 50% white;
}
.proton-embedded[alt]:not([src])::after {
background: url('/assets/img/icons/broken-img.png') no-repeat 0 50% white;
}
</style>
</head>
<body>
<svg class='proton-hidden'>
<g id='ic-file-shapes'>
<path fill-rule='evenodd' d='M13 13a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1h5v2.5A1.5 1.5 0 0 0 10.5 6H13v7Zm-.414-8L10 2.414V4.5a.5.5 0 0 0 .5.5h2.086ZM2 3a2 2 0 0 1 2-2h5.172a2 2 0 0 1 1.414.586l2.828 2.828A2 2 0 0 1 14 5.828V13a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V3Zm3 8v1h1v-1H5Zm-.5-1a.5.5 0 0 0-.5.5v2a.5.5 0 0 0 .5.5h2a.5.5 0 0 0 .5-.5v-2a.5.5 0 0 0-.5-.5h-2Z'/>
<path fill-rule='evenodd' d='M9.5 9a.5.5 0 1 0 0-1 .5.5 0 0 0 0 1Zm0 1a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Z'/>
</g>
<g id='ic-cross-circle'>
<path fill-rule='evenodd' d='M8 14A6 6 0 1 0 8 2a6 6 0 0 0 0 12Zm0 1A7 7 0 1 0 8 1a7 7 0 0 0 0 14Z'/>
<path fill-rule='evenodd' d='M5.146 5.146a.5.5 0 0 1 .708 0L8 7.293l2.146-2.147a.5.5 0 0 1 .708.708L8.707 8l2.147 2.146a.5.5 0 0 1-.708.708L8 8.707l-2.146 2.147a.5.5 0 0 1-.708-.708L7.293 8 5.146 5.854a.5.5 0 0 1 0-.708Z'/>
</g>
<g id='ic-three-dots-horizontal'>
<path d='M4 8a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z'/>
<path d='M9 8a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z'/>
<path d='M14 8a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z'/>
</g>
</svg>
<div id='proton-editor-container'>
<div id='${ROOSTER_EDITOR_WRAPPER_ID}'>
<div id='${ROOSTER_EDITOR_ID}' ></div>
<div id='${EDITOR_BLOCKQUOTE_TOGGLE_CONTAINER_ID}' ></div>
</div>
</div>
<div id='${EDITOR_DROPZONE}' />
</body>
`);
iframeDocument.close();
const editorDiv = iframeDocument.getElementById(ROOSTER_EDITOR_ID) as HTMLDivElement;
const { editor, actions } = await initRoosterEditor(editorDiv, {
onEditorEvent: onEditorChange,
initialContent,
showModalLink,
iframeRef,
mailSettings,
onPasteImage,
openEmojiPicker,
});
// Prevent setState execution in case component is unmounted
if (!isMounted()) {
return;
}
onReady(actions);
return editor;
}, []);
useEffect(() => {
const isEditorReady = editorRef.current !== undefined;
if (isEditorReady) {
return;
}
const onEditorClick = () => {
editorRef.current?.focus();
onFocus?.();
};
void initRooster()
.then((editorInstance) => {
editorRef.current = editorInstance;
})
.then(() => {
const editorWrapper = iframeRef.current?.contentDocument?.getElementById(ROOSTER_EDITOR_WRAPPER_ID);
editorWrapper?.addEventListener('click', onEditorClick);
});
return () => {
editorRef.current?.dispose();
const editorWrapper = iframeRef.current?.contentDocument?.getElementById(ROOSTER_EDITOR_WRAPPER_ID);
editorWrapper?.removeEventListener('click', onEditorClick);
};
}, []);
};
export default useInitRooster;
| 5,362
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/rooster
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/rooster/hooks/useOnEditorChange.ts
|
import { useCallback } from 'react';
import { IEditor, PluginEvent, PluginEventType } from 'roosterjs-editor-types';
import useIsMounted from '@proton/hooks/useIsMounted';
import debounce from '@proton/utils/debounce';
import { SetEditorToolbarConfig } from '../../interface';
const EVENTS_TO_TRIGGER_ONCHANGE = [PluginEventType.Input, PluginEventType.ContentChanged];
const TOOLBAR_EDITOR_EVENTS = [
undefined,
PluginEventType.EditorReady,
PluginEventType.Input,
PluginEventType.MouseUp,
PluginEventType.ContentChanged,
PluginEventType.KeyUp,
PluginEventType.PendingFormatStateChanged,
];
interface Props {
setToolbarConfig: SetEditorToolbarConfig;
onChange: ((value: string) => void) | undefined;
}
const useOnEditorChange = ({ setToolbarConfig, onChange }: Props) => {
const isMountedCallback = useIsMounted();
const debouncedSetToolbarConfig = useCallback(
debounce((editor: IEditor) => {
if (!isMountedCallback()) {
return;
}
setToolbarConfig(editor);
}, 100),
[setToolbarConfig, isMountedCallback]
);
const onChangeCallback = useCallback(
(editorEvent: PluginEvent, editor: IEditor) => {
const { eventType } = editorEvent;
if (TOOLBAR_EDITOR_EVENTS.includes(eventType as any)) {
debouncedSetToolbarConfig(editor);
}
if (EVENTS_TO_TRIGGER_ONCHANGE.includes(editorEvent.eventType as any)) {
const content = editor.getContent();
onChange?.(content);
}
},
[onChange]
);
return onChangeCallback;
};
export default useOnEditorChange;
| 5,363
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/rooster
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/rooster/plugins/EditorCustomPastePlugin.ts
|
/* eslint-disable class-methods-use-this */
import { getPasteSource, wrap } from 'roosterjs-editor-dom';
import {
AttributeCallbackMap,
BeforePasteEvent,
EditorPlugin,
IEditor,
KnownPasteSourceType,
PluginEvent,
PluginEventType,
} from 'roosterjs-editor-types';
import { transformLinkify } from '@proton/shared/lib/mail/transformLinkify';
import { EMBEDDABLE_TYPES } from '../../constants';
/**
* Handles custom behavior when pasting content on top of the current rooster paste plugin
*/
class EditorCustomPastePlugin implements EditorPlugin {
private editor: IEditor | undefined;
private onPasteImage: ((image: File) => void) | undefined;
constructor(onPasteImage: (image: File) => void) {
this.editor = undefined;
this.onPasteImage = onPasteImage;
}
getName() {
return 'EditorCustomPastePlugin';
}
initialize(editor: IEditor) {
this.editor = editor;
}
dispose() {}
onPluginEvent(event: PluginEvent) {
if (!this.editor || event.eventType !== PluginEventType.BeforePaste) {
return;
}
this.updateSanitizingOptions(event);
this.linkifyPlainTextContent(event);
this.handlePasteImage(event);
}
private validateLink(link: string, htmlElement: HTMLElement) {
const PROTOCOLS = ['http:', 'https:', 'mailto:'];
let url;
try {
url = new URL(link);
} catch {
url = undefined;
}
if (url && PROTOCOLS.includes(url.protocol)) {
return link;
}
htmlElement.removeAttribute('href');
return '';
}
private updateSanitizingOptions(event: BeforePasteEvent) {
const callbackMap: AttributeCallbackMap = {
href: (link: string, element: HTMLElement) => this.validateLink(link, element),
};
event.sanitizingOption.attributeCallbacks = callbackMap;
event.sanitizingOption.additionalAllowedAttributes = ['bgcolor'];
event.sanitizingOption.additionalTagReplacements = {
INPUT: null,
TEXTAREA: null,
FORM: null,
};
}
private handlePasteImage(event: BeforePasteEvent) {
const {
clipboardData: { image, rawHtml },
} = event;
/**
* When pasting content from Word or OneNote, there are multiple clipboardDate.types and an image inside the event.
* So be careful if you want to base yourself on those ones
*
* Be careful to check those 3 points:
* - Image should exist
* - RawHTML should be null or contain a single image
* - Image type should contain an allowed type
*/
if (
image &&
(rawHtml === null || getPasteSource(event, true) === KnownPasteSourceType.SingleImage) &&
EMBEDDABLE_TYPES.includes(image.type)
) {
// we replace pasted content by empty string
event.fragment.textContent = '';
const pasteImage = this.onPasteImage;
if (pasteImage) {
this.editor?.focus();
// Need to wait to focus before pasting
setTimeout(() => {
pasteImage(image);
}, 0);
}
}
}
private linkifyPlainTextContent(event: BeforePasteEvent) {
const isPlainTextContent =
event.clipboardData.text &&
event.clipboardData.types.length === 1 &&
event.clipboardData.types[0] === 'text/plain';
if (!isPlainTextContent) {
return;
}
const text = event.clipboardData.text;
// Clear textContent in order to force rooster paste fragment
event.fragment.textContent = '';
const NBSP_HTML = '\u00A0';
const fragment = event.fragment;
// Paste text
text.split('\n').forEach((line, index, lines) => {
line = line
.replace(/^ /g, NBSP_HTML)
.replace(/\r/g, '')
.replace(/ {2}/g, ' ' + NBSP_HTML);
const span = document.createElement('span');
span.innerHTML = transformLinkify({ content: line });
/**
* There are three possible scenarios:
* 1. Single line: Paste as is
* 2. Two lines: Add <br> between the lines
* 3. Three or more lines:
* - For first and last line, paste as is.
* - For middle lines, wrap with DIV, and add <br> if it's an empty line.
*/
if (lines.length == 2 && index == 0) {
// 1 of 2 lines scenario, add BR
fragment.appendChild(span);
fragment.appendChild(document.createElement('br'));
} else if (index > 0 && index < lines.length - 1) {
// Middle line of >=3 lines scenario, wrap with DIV
fragment.appendChild(wrap(line == '' ? document.createElement('br') : span));
} else {
// All others, paste as it is
fragment.appendChild(span);
}
});
}
}
export default EditorCustomPastePlugin;
| 5,364
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/rooster
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/rooster/plugins/EditorEventListener.ts
|
/* eslint-disable class-methods-use-this */
import { EditorPlugin, IEditor, PluginEvent } from 'roosterjs-editor-types';
import { OnEditorEventListened } from '../../interface';
/**
* This pluggin is here to dispatch editorEvents
*/
class EditorEventListener implements EditorPlugin {
private onChange: OnEditorEventListened;
private editor: IEditor | undefined;
constructor(onChange: OnEditorEventListened) {
this.onChange = onChange;
this.editor = undefined;
}
getName() {
return 'EditorEventListener';
}
initialize(editor: IEditor) {
this.editor = editor;
}
dispose() {}
onPluginEvent(e: PluginEvent) {
if (!this.editor) {
return;
}
this.onChange(e, this.editor);
}
}
export default EditorEventListener;
| 5,365
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/rooster
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/rooster/plugins/UndoSnapshots.ts
|
import { Snapshots, UndoSnapshotsService } from 'roosterjs-editor-types';
import { ROOSTER_SNAPSHOTS_MAX_SIZE } from '../../constants';
interface Functions {
addSnapshot: (snapshots: Snapshots, snapshot: string, isAutoCompleteSnapshot: boolean) => void;
canMoveCurrentSnapshot: (snapshots: Snapshots, step: number) => boolean;
moveCurrentSnapshot: (snapshots: Snapshots, step: number) => string | null;
clearProceedingSnapshots: (snapshots: Snapshots) => void;
canUndoAutoComplete: (snapshots: Snapshots) => boolean;
createSnapshots: (maxSize: number) => Snapshots;
}
export default class UndoSnapshots implements UndoSnapshotsService {
constructor(private snapshots: Snapshots, private functions: Functions) {}
public canMove(delta: number): boolean {
return this.functions.canMoveCurrentSnapshot(this.snapshots, delta);
}
public move(delta: number): string {
const result = this.functions.moveCurrentSnapshot(this.snapshots, delta);
// @ts-expect-error implemented UndoSnapshotsService typing should be updated in order to accept null
return result;
}
public addSnapshot(snapshot: string, isAutoCompleteSnapshot: boolean) {
this.functions.addSnapshot(this.snapshots, snapshot, isAutoCompleteSnapshot);
}
public clearRedo() {
this.functions.clearProceedingSnapshots(this.snapshots);
}
public canUndoAutoComplete() {
return this.functions.canUndoAutoComplete(this.snapshots);
}
public clearSnapshots() {
this.snapshots = this.functions.createSnapshots(ROOSTER_SNAPSHOTS_MAX_SIZE);
}
}
| 5,366
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/toolbar/Toolbar.tsx
|
import { Ref, Suspense, lazy } from 'react';
import { c } from 'ttag';
import { Vr } from '@proton/atoms';
import { ErrorBoundary } from '@proton/components/containers';
import { COMPOSER_TOOLBAR_ICON_SIZE } from '@proton/shared/lib/constants';
import { MailSettings } from '@proton/shared/lib/interfaces';
import clsx from '@proton/utils/clsx';
import { useActiveBreakpoint } from '../../../hooks';
import { ButtonGroup } from '../../button';
import Icon from '../../icon/Icon';
import { DEFAULT_FONT_SIZE } from '../constants';
import { ToolbarConfig } from '../helpers/getToolbarConfig';
import { EditorMetadata } from '../interface';
import ToolbarAlignmentDropdown from './ToolbarAlignmentDropdown';
import ToolbarButton from './ToolbarButton';
import ToolbarColorsDropdown from './ToolbarColorsDropdown';
import ToolbarFontFaceDropdown from './ToolbarFontFaceDropdown';
import ToolbarFontSizeDropdown from './ToolbarFontSizeDropdown';
import ToolbarMoreDropdown from './ToolbarMoreDropdown';
const ToolbarEmojiDropdown = lazy(
() => import(/* webpackChunkName: "ToolbarEmojiDropdown" */ './ToolbarEmojiDropdown')
);
interface ToolbarProps {
config: ToolbarConfig | undefined;
metadata: EditorMetadata;
mailSettings?: MailSettings;
className?: string;
openEmojiPickerRef: Ref<() => void>;
simple?: boolean;
}
const Toolbar = ({ config, metadata, mailSettings, openEmojiPickerRef, className, simple }: ToolbarProps) => {
const { isNarrow } = useActiveBreakpoint();
const showMoreDropdown = metadata.supportRightToLeft || metadata.supportPlainText || isNarrow;
if (metadata.isPlainText) {
return null;
}
if (!config) {
return null;
}
return (
<ButtonGroup className={clsx(['editor-toolbar overflow-hidden mb-2', className])}>
<ToolbarFontFaceDropdown
value={config.fontFace.value}
setValue={config.fontFace.setValue}
onClickDefault={config.defaultFont.showModal}
defaultValue={mailSettings?.FontFace}
showDefaultFontSelector={metadata.supportDefaultFontSelector}
/>
<ToolbarFontSizeDropdown
value={config.fontSize.value}
setValue={config.fontSize.setValue}
onClickDefault={config.defaultFont.showModal}
defaultValue={`${mailSettings?.FontSize || DEFAULT_FONT_SIZE}px`}
showDefaultFontSelector={metadata.supportDefaultFontSelector}
/>
<ToolbarColorsDropdown
fontColor={config.fontColor.value}
setFontColor={config.fontColor.setValue}
bgColor={config.backgroundColor.value}
setBgColor={config.backgroundColor.setValue}
/>
<>
<ToolbarButton
onClick={config.bold.toggle}
aria-pressed={config.bold.isActive}
className={clsx(['flex-item-noshrink', config.bold.isActive && 'is-active'])}
title={c('Action').t`Bold`}
data-testid="editor-bold"
>
<Icon
name="text-bold"
size={COMPOSER_TOOLBAR_ICON_SIZE}
className="m-auto"
alt={c('Action').t`Bold`}
/>
</ToolbarButton>
<ToolbarButton
onClick={config.italic.toggle}
aria-pressed={config.italic.isActive}
className={clsx(['flex-item-noshrink', config.italic.isActive && 'is-active'])}
title={c('Action').t`Italic`}
data-testid="editor-italic"
>
<Icon
name="text-italic"
size={COMPOSER_TOOLBAR_ICON_SIZE}
className="m-auto"
alt={c('Action').t`Italic`}
/>
</ToolbarButton>
<ToolbarButton
onClick={config.underline.toggle}
aria-pressed={config.underline.isActive}
className={clsx(['flex-item-noshrink', config.underline.isActive && 'is-active'])}
title={c('Action').t`Underline`}
data-testid="editor-underline"
>
<Icon
name="text-underline"
size={COMPOSER_TOOLBAR_ICON_SIZE}
className="m-auto"
alt={c('Action').t`Underline`}
/>
</ToolbarButton>
<ToolbarButton
onClick={config.strikethrough.toggle}
aria-pressed={config.strikethrough.isActive}
className={clsx(['flex-item-noshrink', config.strikethrough.isActive && 'is-active'])}
title={c('Action').t`Strikethrough`}
data-testid="editor-strikethrough"
>
<Icon
name="text-strikethrough"
size={COMPOSER_TOOLBAR_ICON_SIZE}
className="m-auto"
alt={c('Action').t`Strikethrough`}
/>
</ToolbarButton>
</>
{!isNarrow ? (
<>
<ToolbarButton
onClick={config.unorderedList.toggle}
aria-pressed={config.unorderedList.isActive}
className={clsx(['flex-item-noshrink', config.unorderedList.isActive && 'is-active'])}
title={c('Action').t`Unordered list`}
data-testid="editor-unordered-list"
>
<Icon
name="list-bullets"
size={COMPOSER_TOOLBAR_ICON_SIZE}
className="m-auto on-rtl-mirror"
alt={c('Action').t`Unordered list`}
/>
</ToolbarButton>
<ToolbarButton
onClick={config.orderedList.toggle}
aria-pressed={config.orderedList.isActive}
className={clsx(['flex-item-noshrink', config.orderedList.isActive && 'is-active'])}
title={c('Action').t`Ordered list`}
data-testid="editor-ordered-list"
>
<Icon
name="list-numbers"
size={COMPOSER_TOOLBAR_ICON_SIZE}
className="m-auto on-rtl-mirror"
alt={c('Action').t`Ordered list`}
/>
</ToolbarButton>
<Vr aria-hidden="true" />
<ToolbarAlignmentDropdown setAlignment={config.alignment.setValue} />
{!simple && (
<>
<Vr aria-hidden="true" />{' '}
<ErrorBoundary component={() => null}>
<Suspense fallback={null}>
<ToolbarEmojiDropdown onInsert={config.emoji.insert} openRef={openEmojiPickerRef} />
</Suspense>
</ErrorBoundary>
</>
)}
<ToolbarButton
onClick={config.blockquote.toggle}
aria-pressed={config.blockquote.isActive}
className={clsx(['flex-item-noshrink', config.blockquote.isActive && 'is-active'])}
title={c('Action').t`Quote`}
data-testid="editor-quote"
>
<Icon
name="text-quote"
size={COMPOSER_TOOLBAR_ICON_SIZE}
className="m-auto"
alt={c('Action').t`Quote`}
/>
</ToolbarButton>
<ToolbarButton
onClick={config.link.showModal}
className="flex-item-noshrink"
title={c('Action').t`Insert link`}
data-testid="editor-insert-link"
>
<Icon
name="link"
size={COMPOSER_TOOLBAR_ICON_SIZE}
className="m-auto"
alt={c('Action').t`Insert link`}
/>
</ToolbarButton>
<ToolbarButton
onClick={config.formatting.clear}
className="flex-item-noshrink"
title={c('Action').t`Clear all formatting`}
data-testid="editor-clear-formatting"
>
<Icon
name="eraser"
size={COMPOSER_TOOLBAR_ICON_SIZE}
className="m-auto"
alt={c('Action').t`Clear all formatting`}
/>
</ToolbarButton>
{simple && metadata.supportImages && (
<>
<Vr aria-hidden="true" />
<ToolbarButton
onClick={config.image.showModal}
className="flex-item-noshrink"
title={c('Action').t`Insert image`}
>
<Icon
name="file-image"
size={COMPOSER_TOOLBAR_ICON_SIZE}
className="m-auto"
alt={c('Action').t`Insert image`}
/>
</ToolbarButton>
</>
)}
</>
) : null}
{showMoreDropdown && <ToolbarMoreDropdown config={config} metadata={metadata} isNarrow={isNarrow} />}
</ButtonGroup>
);
};
export default Toolbar;
| 5,367
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/toolbar/ToolbarAlignmentDropdown.tsx
|
import { Alignment } from 'roosterjs-editor-types';
import { c } from 'ttag';
import { COMPOSER_TOOLBAR_ICON_SIZE } from '@proton/shared/lib/constants';
import DropdownMenu from '../../dropdown/DropdownMenu';
import DropdownMenuButton from '../../dropdown/DropdownMenuButton';
import Icon from '../../icon/Icon';
import ToolbarDropdown from './ToolbarDropdown';
interface Props {
setAlignment: (nextAlignment: Alignment) => void;
}
const ToolbarAlignmentDropdown = ({ setAlignment }: Props) => (
<ToolbarDropdown
content={<Icon name="text-align-left" size={COMPOSER_TOOLBAR_ICON_SIZE} alt={c('Action').t`Alignment`} />}
className="flex-item-noshrink"
data-testid="editor-alignment"
title={c('Action').t`Alignment`}
>
<DropdownMenu>
<DropdownMenuButton
className="text-left flex flex-nowrap flex-align-items-center"
onClick={() => setAlignment(Alignment.Left)}
data-testid="editor-alignment-left"
>
<Icon name="text-align-left" />
<span className="ml-2 my-auto flex-item-fluid">{c('Info').t`Align left`}</span>
</DropdownMenuButton>
<DropdownMenuButton
className="text-left flex flex-nowrap flex-align-items-center"
onClick={() => setAlignment(Alignment.Center)}
data-testid="editor-alignment-center"
>
<Icon name="text-align-center" />
<span className="ml-2 my-auto flex-item-fluid">{c('Info').t`Center`}</span>
</DropdownMenuButton>
<DropdownMenuButton
className="text-left flex flex-nowrap flex-align-items-center"
onClick={() => setAlignment(Alignment.Right)}
data-testid="editor-alignment-right"
>
<Icon name="text-align-right" />
<span className="ml-2 my-auto flex-item-fluid">{c('Info').t`Align right`}</span>
</DropdownMenuButton>
</DropdownMenu>
</ToolbarDropdown>
);
export default ToolbarAlignmentDropdown;
| 5,368
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/toolbar/ToolbarButton.tsx
|
import { ButtonHTMLAttributes, DetailedHTMLProps } from 'react';
import clsx from '@proton/utils/clsx';
import Tooltip from '../../tooltip/Tooltip';
const ToolbarButton = ({
children,
disabled = false,
className = '',
title,
onClick,
...rest
}: DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>) => (
<Tooltip title={title}>
<button
type="button"
disabled={disabled}
className={clsx(['editor-toolbar-button interactive-pseudo-inset m-0 flex', className])}
onClick={onClick}
{...rest}
>
{children}
</button>
</Tooltip>
);
export default ToolbarButton;
| 5,369
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/toolbar/ToolbarColorsDropdown.tsx
|
import { useState } from 'react';
import { c } from 'ttag';
import { DropdownSizeUnit } from '@proton/components/components';
import { COMPOSER_TOOLBAR_ICON_SIZE } from '@proton/shared/lib/constants';
import ColorSelector from '../../color/ColorSelector';
import Icon from '../../icon/Icon';
import { Tabs } from '../../tabs';
import { FONT_COLORNAMES } from '../constants';
import ToolbarDropdown from './ToolbarDropdown';
interface Props {
fontColor: string;
bgColor: string;
setFontColor: (nextColor: string) => void;
setBgColor: (nextColor: string) => void;
}
const ToolbarColorsDropdown = ({ fontColor, bgColor, setFontColor, setBgColor }: Props) => {
const [tabIndex, setTabIndex] = useState(0);
const colors = Object.entries(FONT_COLORNAMES).map(([value, getLabel]) => ({ value, label: getLabel() }));
const tabs = [
{
title: c('Info').t`Text color`,
content: <ColorSelector selected={fontColor} onChange={setFontColor} colors={colors} />,
},
{
title: c('Info').t`Background color`,
content: <ColorSelector selected={bgColor} onChange={setBgColor} colors={colors} />,
},
];
return (
<ToolbarDropdown
dropdownSize={{ maxWidth: DropdownSizeUnit.Viewport, maxHeight: DropdownSizeUnit.Viewport }}
content={<Icon name="circle-half-filled" size={COMPOSER_TOOLBAR_ICON_SIZE} alt={c('Action').t`Color`} />}
className="flex-item-noshrink"
data-testid="editor-font-color"
title={c('Action').t`Color`}
>
<div className="p-4">
<Tabs tabs={tabs} value={tabIndex} onChange={setTabIndex} />
</div>
</ToolbarDropdown>
);
};
export default ToolbarColorsDropdown;
| 5,370
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/toolbar/ToolbarDropdown.tsx
|
import { ReactNode, Ref, forwardRef, useImperativeHandle, useState } from 'react';
import clsx from '@proton/utils/clsx';
import { PopperPlacement } from '../../../components/popper';
import { generateUID } from '../../../helpers';
import Dropdown, { DropdownProps } from '../../dropdown/Dropdown';
import DropdownButton, { DropdownButtonProps } from '../../dropdown/DropdownButton';
import { usePopperAnchor } from '../../popper';
import Tooltip from '../../tooltip/Tooltip';
interface Props extends Omit<DropdownButtonProps<'button'>, 'title' | 'content'> {
autoClose?: boolean;
autoCloseOutside?: boolean;
title?: string;
className?: string;
content?: ReactNode;
children: ReactNode;
onOpen?: () => void;
dropdownSize?: DropdownProps['size'];
disabled?: boolean;
originalPlacement?: PopperPlacement;
hasCaret?: boolean;
}
export interface ToolbarDropdownAction {
close: () => void;
open: () => void;
}
const ToolbarDropdown = (
{
title,
content,
className,
children,
onOpen,
dropdownSize,
autoClose = true,
autoCloseOutside = true,
disabled = false,
originalPlacement = 'bottom',
hasCaret = false,
...rest
}: Props,
ref: Ref<ToolbarDropdownAction>
) => {
const [uid] = useState(generateUID('dropdown'));
const { anchorRef, isOpen, toggle, close, open } = usePopperAnchor<HTMLButtonElement>();
const handleClick = () => {
if (!isOpen) {
onOpen?.();
}
toggle();
};
useImperativeHandle(ref, () => ({ close, open }), [close, open]);
return (
<>
<Tooltip title={title}>
<DropdownButton
as="button"
type="button"
ref={anchorRef}
isOpen={isOpen}
onClick={handleClick}
hasCaret={hasCaret}
disabled={disabled}
caretClassName="editor-toolbar-icon"
className={clsx([
'editor-toolbar-button interactive-pseudo-inset composer-toolbar-fontDropDown max-w-full flex flex-align-items-center flex-nowrap',
className,
])}
title={title}
{...rest}
>
{content}
</DropdownButton>
</Tooltip>
<Dropdown
id={uid}
autoClose={autoClose}
autoCloseOutside={autoCloseOutside}
originalPlacement={originalPlacement}
isOpen={isOpen}
size={dropdownSize}
anchorRef={anchorRef}
onClose={close}
className="editor-toolbar-dropdown"
>
{children}
</Dropdown>
</>
);
};
export default forwardRef(ToolbarDropdown);
| 5,371
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/toolbar/ToolbarEmojiDropdown.raw.scss
|
section#root {
background-color: var(--background-norm);
.sticky {
background-color: var(--background-norm);
}
.search input[type='search'] {
background-color: var(--background-norm);
}
}
| 5,372
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/toolbar/ToolbarEmojiDropdown.scss
|
// Forcing dropdown size unless dropdown positioning is panicking
/* stylelint-disable */
em-emoji-picker {
/* stylelint-enable */
block-size: 22rem;
inline-size: 20rem;
}
| 5,373
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/toolbar/ToolbarEmojiDropdown.tsx
|
import { Ref, useEffect, useImperativeHandle, useRef } from 'react';
import data from '@emoji-mart/data';
import { Picker } from 'emoji-mart';
import { c } from 'ttag';
import { DropdownSizeUnit, Icon } from '@proton/components/components';
import { COMPOSER_TOOLBAR_ICON_SIZE } from '@proton/shared/lib/constants';
import clsx from '@proton/utils/clsx';
import { useTheme } from '../../../containers/themes';
import ToolbarDropdown, { ToolbarDropdownAction } from './ToolbarDropdown';
import emojiPickerCss from './ToolbarEmojiDropdown.raw.scss';
import './ToolbarEmojiDropdown.scss';
export interface Emoji {
id: string;
name: string;
native: string;
unified: string;
keywords: string[];
shortcodes: string;
emoticons: string[];
aliases: string[];
}
const EmojiPicker = (props: any) => {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
const picker = new Picker({ ...props, data, ref });
// Inject custom CSS inside the custom elements of the emoji picker
const style = document.createElement('style');
style.innerHTML = emojiPickerCss;
picker.shadowRoot?.appendChild(style);
}, []);
return <div ref={ref} />;
};
interface Props {
onInsert: (emoji: Emoji) => void;
openRef: Ref<() => void>;
className?: string;
}
const ToolbarEmojiDropdown = ({ onInsert, openRef, className }: Props) => {
const dropdownRef = useRef<ToolbarDropdownAction>(null);
const theme = useTheme();
const handleSelect = (emoji: Emoji) => {
onInsert(emoji);
dropdownRef.current?.close();
};
useImperativeHandle(openRef, () => {
return () => {
dropdownRef.current?.open();
};
});
return (
<ToolbarDropdown
ref={dropdownRef}
dropdownSize={{ maxWidth: DropdownSizeUnit.Viewport, maxHeight: DropdownSizeUnit.Viewport }}
content={<Icon name="emoji" size={COMPOSER_TOOLBAR_ICON_SIZE} alt={c('Action').t`Emoji`} />}
className={clsx(['flex-item-noshrink', className])}
title={c('Action').t`Emoji`}
autoClose={false}
autoCloseOutside={true}
data-testid="editor-emoji-picker"
>
<EmojiPicker
autoFocus="true"
onEmojiSelect={handleSelect}
theme={theme.information.dark ? 'dark' : 'light'}
set="native"
skinTonePosition="none"
previewPosition="none"
perLine={8}
/>
</ToolbarDropdown>
);
};
export default ToolbarEmojiDropdown;
| 5,374
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/toolbar/ToolbarFontFaceDropdown.test.tsx
|
import { fireEvent, render } from '@testing-library/react';
import { DEFAULT_FONT_FACE, FONT_FACES } from '../constants';
import { getFontFaceIdFromValue } from '../helpers/fontFace';
import ToolbarFontFaceDropdown from './ToolbarFontFaceDropdown';
describe('Toolbar font face dropdown', () => {
it('Should display default font value when no values', () => {
const { getByTestId } = render(
<ToolbarFontFaceDropdown
defaultValue={null}
setValue={() => {}}
onClickDefault={() => {}}
showDefaultFontSelector
/>
);
const selectedValue = getByTestId('editor-toolbar:font-face:selected-value');
const defaultFontFaceID = getFontFaceIdFromValue(DEFAULT_FONT_FACE);
// To be "Arial"
expect(selectedValue.innerHTML).toBe(defaultFontFaceID);
});
it('Should display fonts dropdown on click', () => {
const { getByTestId } = render(
<ToolbarFontFaceDropdown
defaultValue={null}
setValue={() => {}}
onClickDefault={() => {}}
showDefaultFontSelector
/>
);
const input = getByTestId('editor-toolbar:font-face:selected-value');
fireEvent.click(input);
Object.values(FONT_FACES).forEach(({ id }) => {
expect(getByTestId(`editor-toolbar:font-face:dropdown-item:${id}`)).toBeInTheDocument();
});
});
it('Should display "default font" button in dropdown', () => {
const { getByTestId } = render(
<ToolbarFontFaceDropdown
defaultValue={null}
setValue={() => {}}
onClickDefault={() => {}}
showDefaultFontSelector
/>
);
const input = getByTestId('editor-toolbar:font-face:selected-value');
fireEvent.click(input);
const defaultFontFaceID = getFontFaceIdFromValue(DEFAULT_FONT_FACE);
expect(getByTestId(`editor-toolbar:font-face:dropdown-item:${defaultFontFaceID}`)).toBeInTheDocument();
expect(getByTestId(`editor-toolbar:font-face:dropdown-item:${defaultFontFaceID}:default`)).toBeInTheDocument();
});
});
| 5,375
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/toolbar/ToolbarFontFaceDropdown.tsx
|
import { useEffect, useState } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import { MailSettings } from '@proton/shared/lib/interfaces';
import clsx from '@proton/utils/clsx';
import { Badge } from '../../badge';
import { DropdownMenu, DropdownMenuContainer } from '../../dropdown';
import { DEFAULT_FONT_FACE, FONT_FACES } from '../constants';
import { getFontFaceIdFromValue, getFontFaceValueFromId } from '../helpers/fontFace';
import ToolbarDropdown from './ToolbarDropdown';
interface Props {
/** Font value of current text selection */
value?: string;
setValue: (font: string) => void;
/** DefaultValue is a FONT_FACES.font.id */
defaultValue: MailSettings['FontFace'] | undefined;
onClickDefault: () => void;
showDefaultFontSelector?: boolean;
}
const getFontLabel = (font: string): string | undefined => {
const lowerFont = font.toLowerCase();
const fonts = Object.values(FONT_FACES);
const search = fonts.find(({ value }) => lowerFont === value.toLowerCase());
return search?.label;
};
const hasFont = (font: string): boolean => {
const lowerFont = font.toLowerCase();
const fonts = Object.values(FONT_FACES);
return fonts.some(({ value }) => lowerFont === value.toLowerCase());
};
const displayDefaultFontButton = (
defaultFontID: MailSettings['FontFace'] | undefined,
fontId: string,
canDisplayButton: boolean
) => {
if (!canDisplayButton) {
return false;
}
const defaultId = defaultFontID || getFontFaceIdFromValue(DEFAULT_FONT_FACE);
const canDisplay = defaultId === fontId;
return canDisplay;
};
const ToolbarFontFaceDropdown = ({ value, setValue, defaultValue, onClickDefault, showDefaultFontSelector }: Props) => {
const defaultFontFaceValue = getFontFaceValueFromId(defaultValue);
const [computedValue, setComputedValue] = useState(value || DEFAULT_FONT_FACE);
const onChange = (nextFont: string) => {
setComputedValue(nextFont);
setValue(nextFont);
};
// Value changes when we move cursor to another place.
// We reflect those changes to the computed value
useEffect(() => {
if (!value || !hasFont(value) || value === computedValue) {
return;
}
if (value) {
setComputedValue(value);
}
}, [value]);
// defaultFontFaceValue changes when we select a new default value
// We reflect those changes to the computedValue
useEffect(() => {
if (defaultFontFaceValue) {
setComputedValue(defaultFontFaceValue);
}
}, [defaultFontFaceValue]);
return (
<ToolbarDropdown
originalPlacement="bottom-start"
className="composer-toolbar-fontDropDown flex-item-fluid text-right flex no-scroll"
title={c('Action').t`Font`}
data-testid="editor-font-face"
content={
<span
data-testid="editor-toolbar:font-face:selected-value"
className="text-ellipsis text-left max-w-full"
style={{ display: 'inline-block', fontFamily: computedValue.toString() }}
>
{getFontLabel(computedValue)}
</span>
}
>
<DropdownMenu>
{Object.values(FONT_FACES).map(({ label: fontLabel, value: fontValue, id: fontId }) => (
<DropdownMenuContainer
key={fontId}
data-testid={`editor-toolbar:font-face:dropdown-item:${fontId}`}
className={clsx([fontValue === value && 'dropdown-item--is-selected'])}
buttonClassName="text-left"
aria-pressed={fontValue === value}
isSelected={fontValue === value}
onClick={() => onChange(fontValue)}
style={{ fontFamily: fontValue }}
buttonContent={<span className="pr-2">{fontLabel}</span>}
extraContent={
displayDefaultFontButton(defaultValue, fontId, !!showDefaultFontSelector) ? (
<div className="flex px-2 flex-item-noshrink">
<Button
color="weak"
shape="ghost"
className="inline-flex flex-align-self-center text-no-decoration relative"
onClick={onClickDefault}
data-testid={`editor-toolbar:font-face:dropdown-item:${fontId}:default`}
>
<Badge className="color-info">{c('Font Face Default').t`Default`}</Badge>
</Button>
</div>
) : null
}
/>
))}
</DropdownMenu>
</ToolbarDropdown>
);
};
export default ToolbarFontFaceDropdown;
| 5,376
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/toolbar/ToolbarFontSizeDropdown.tsx
|
import { useEffect, useState } from 'react';
import { c } from 'ttag';
import { Button } from '@proton/atoms';
import clsx from '@proton/utils/clsx';
import { Badge } from '../../badge';
import { DropdownMenu, DropdownMenuContainer } from '../../dropdown';
import { FONT_SIZES } from '../constants';
import ToolbarDropdown from './ToolbarDropdown';
interface Props {
value?: string;
setValue: (nextFontSize: string) => void;
onClickDefault: () => void;
defaultValue: string;
showDefaultFontSelector: boolean;
}
const hasValue = (valueInPt: string): string | undefined => {
return Object.entries(FONT_SIZES).find(([, ptValue]) => ptValue === valueInPt)?.[0];
};
const getCorrespondingValueInPt = (valueInPx: string): string | undefined => {
return Object.entries(FONT_SIZES).find(([pxValue]) => pxValue === valueInPx)?.[1];
};
const ToolbarFontSizeDropdown = ({ setValue, value, onClickDefault, defaultValue, showDefaultFontSelector }: Props) => {
const [computedValue, setComputedValue] = useState(value || defaultValue);
const selectedValue = hasValue(computedValue) || computedValue;
const onChange = (nextFontSizeInPt: string) => {
setComputedValue(nextFontSizeInPt);
setValue(nextFontSizeInPt);
};
useEffect(() => {
if (value === computedValue) {
return;
}
if (value) {
setComputedValue(value);
}
}, [value]);
useEffect(() => {
const correspondingValue = getCorrespondingValueInPt(defaultValue);
if (correspondingValue) {
setComputedValue(correspondingValue);
}
}, [defaultValue]);
return (
<ToolbarDropdown
originalPlacement="bottom-start"
content={selectedValue}
className="flex-item-noshrink"
data-testid="editor-font-size"
title={c('Action').t`Size`}
>
<DropdownMenu>
{Object.entries(FONT_SIZES).map(([sizeInPx, sizeInPt]) => (
<DropdownMenuContainer
key={sizeInPt}
className={clsx([sizeInPt === value && 'dropdown-item--is-selected'])}
buttonClassName="text-left"
aria-pressed={sizeInPt === value}
isSelected={sizeInPt === value}
onClick={() => {
onChange(sizeInPt);
}}
data-testid={`editor-font-size-${sizeInPx}`}
buttonContent={<span>{sizeInPx}</span>}
extraContent={
sizeInPx === defaultValue && showDefaultFontSelector ? (
<div className="flex px-2 flex-item-noshrink">
<Button
color="weak"
shape="ghost"
className="inline-flex flex-align-self-center text-no-decoration relative"
onClick={onClickDefault}
>
<Badge className="color-info">{c('Font Size Default').t`Default`}</Badge>
</Button>
</div>
) : null
}
/>
))}
</DropdownMenu>
</ToolbarDropdown>
);
};
export default ToolbarFontSizeDropdown;
| 5,377
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor
|
petrpan-code/ProtonMail/WebClients/packages/components/components/editor/toolbar/ToolbarMoreDropdown.tsx
|
import { Alignment } from 'roosterjs-editor-types';
import { c } from 'ttag';
import { COMPOSER_TOOLBAR_ICON_SIZE } from '@proton/shared/lib/constants';
import { DIRECTION } from '@proton/shared/lib/mail/mailSettings';
import DropdownMenu from '../../dropdown/DropdownMenu';
import DropdownMenuButton from '../../dropdown/DropdownMenuButton';
import Icon from '../../icon/Icon';
import { ToolbarConfig } from '../helpers/getToolbarConfig';
import { EditorMetadata } from '../interface';
import ToolbarDropdown from './ToolbarDropdown';
const getClassname = (status: boolean) => (status ? undefined : 'visibility-hidden');
interface Props {
metadata: EditorMetadata;
isNarrow?: boolean;
config: ToolbarConfig;
}
const ToolbarMoreDropdown = ({ metadata, isNarrow = false, config }: Props) => (
<ToolbarDropdown
content={<Icon name="three-dots-horizontal" size={COMPOSER_TOOLBAR_ICON_SIZE} alt={c('Action').t`More`} />}
className="flex-item-noshrink ml-auto editor-toolbar-more-dropdown"
title={c('Action').t`More`}
data-testid="editor-toolbar-more"
hasCaret={false}
>
<DropdownMenu className="editor-toolbar-more-menu flex-item-noshrink">
{!isNarrow && metadata.supportImages && (
<DropdownMenuButton
key={17}
className="text-left flex flex-nowrap flex-align-items-center"
onClick={() => config.image.showModal()}
data-testid="editor-insert-image"
>
<Icon name="checkmark" className="visibility-hidden" />
<span className="ml-2 my-auto flex-item-fluid">{c('Action').t`Insert image`}</span>
</DropdownMenuButton>
)}
{isNarrow && [
<DropdownMenuButton
key={12}
className="text-left flex flex-nowrap flex-align-items-center"
onClick={config.unorderedList.toggle}
>
<Icon name="checkmark" className={getClassname(config.unorderedList.isActive)} />
<span className="ml-2 my-auto flex-item-fluid">{c('Action').t`Unordered list`}</span>
<Icon name="list-bullets" className="mr-2" />
</DropdownMenuButton>,
<DropdownMenuButton
key={13}
className="text-left flex flex-nowrap flex-align-items-center"
onClick={config.orderedList.toggle}
>
<Icon name="checkmark" className={getClassname(config.orderedList.isActive)} />
<span className="ml-2 my-auto flex-item-fluid">{c('Action').t`Ordered list`}</span>
<Icon name="list-numbers" className="mr-2" />
</DropdownMenuButton>,
<div className="dropdown-item-hr" key="hr-1" />,
<DropdownMenuButton
key={8}
className="text-left flex flex-nowrap flex-align-items-center"
onClick={() => config.alignment.setValue(Alignment.Left)}
>
<Icon name="checkmark" className="visibility-hidden" />
<span className="ml-2 my-auto flex-item-fluid">{c('Action').t`Align left`}</span>
<Icon name="text-align-left" className="mr-2" />
</DropdownMenuButton>,
<DropdownMenuButton
key={9}
className="text-left flex flex-nowrap flex-align-items-center"
onClick={() => config.alignment.setValue(Alignment.Center)}
>
<Icon name="checkmark" className="visibility-hidden" />
<span className="ml-2 my-auto flex-item-fluid">{c('Action').t`Align center`}</span>
<Icon name="text-align-center" className="mr-2" />
</DropdownMenuButton>,
<DropdownMenuButton
key={10}
className="text-left flex flex-nowrap flex-align-items-center"
onClick={() => config.alignment.setValue(Alignment.Center)}
>
<Icon name="checkmark" className="visibility-hidden" />
<span className="ml-2 my-auto flex-item-fluid">{c('Action').t`Align right`}</span>
<Icon name="text-align-right" className="mr-2" />
</DropdownMenuButton>,
<div className="dropdown-item-hr" key="hr-2" />,
<DropdownMenuButton
key={14}
className="text-left flex flex-nowrap flex-align-items-center"
onClick={config.blockquote.toggle}
>
<Icon name="checkmark" className={getClassname(config.blockquote.isActive)} />
<span className="ml-2 my-auto flex-item-fluid">{c('Action').t`Quote`}</span>
<Icon name="text-quote" className="mr-2" />
</DropdownMenuButton>,
<DropdownMenuButton
key={15}
className="text-left flex flex-nowrap flex-align-items-center"
onClick={config.link.showModal}
>
<Icon name="checkmark" className="visibility-hidden" />
<span className="ml-2 my-auto flex-item-fluid">{c('Action').t`Insert link`}</span>
<Icon name="link" className="mr-2" />
</DropdownMenuButton>,
<DropdownMenuButton
key={16}
className="text-left flex flex-nowrap flex-align-items-center"
onClick={() => config.formatting.clear()}
>
<Icon name="checkmark" className="visibility-hidden" />
<span className="ml-2 my-auto flex-item-fluid">{c('Action').t`Clear all formatting`}</span>
<Icon name="eraser" className="mr-2" />
</DropdownMenuButton>,
<div className="dropdown-item-hr" key="hr-3" />,
metadata.supportImages && [
<DropdownMenuButton
key={17}
className="text-left flex flex-nowrap flex-align-items-center"
onClick={() => config.image.showModal()}
>
<Icon name="checkmark" className="visibility-hidden" />
<span className="ml-2 my-auto flex-item-fluid">{c('Action').t`Insert image`}</span>
<Icon name="file-image" className="mr-2" />
</DropdownMenuButton>,
(metadata.supportRightToLeft || metadata.supportPlainText) && (
<div className="dropdown-item-hr" key="hr-4" />
),
],
]}
{metadata.supportRightToLeft &&
!metadata.isPlainText && [
<DropdownMenuButton
key={1}
className="text-left flex flex-nowrap flex-align-items-center"
onClick={() => config.textDirection.setValue(DIRECTION.LEFT_TO_RIGHT)}
data-testid="editor-left-to-right"
>
<Icon
name="checkmark"
className={getClassname(metadata.rightToLeft === DIRECTION.LEFT_TO_RIGHT)}
/>
<span className="ml-2 my-auto flex-item-fluid">{c('Info').t`Left to Right`}</span>
</DropdownMenuButton>,
<DropdownMenuButton
key={2}
className="text-left flex flex-nowrap flex-align-items-center"
onClick={() => config.textDirection.setValue(DIRECTION.RIGHT_TO_LEFT)}
data-testid="editor-right-to-left"
>
<Icon
name="checkmark"
className={getClassname(metadata.rightToLeft === DIRECTION.RIGHT_TO_LEFT)}
/>
<span className="ml-2 my-auto flex-item-fluid">{c('Info').t`Right to Left`}</span>
</DropdownMenuButton>,
]}
</DropdownMenu>
</ToolbarDropdown>
);
export default ToolbarMoreDropdown;
| 5,378
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/electron/ElectronDraggeableHeader.scss
|
.electron-draggeable-header {
-webkit-app-region: drag;
user-select: none;
z-index: 200;
--h-custom: 1.75rem;
}
.header button {
-webkit-app-region: no-drag;
}
| 5,379
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/electron/ElectronDraggeableHeader.tsx
|
import './ElectronDraggeableHeader.scss';
const ElectronDraggeableHeader = () => {
return <div className="electron-draggeable-header absolute-cover h-custom" />;
};
export default ElectronDraggeableHeader;
| 5,380
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/electron/ElectronDraggeableHeaderWrapper.tsx
|
import { isElectronOnMac } from '@proton/shared/lib/helpers/desktop';
import ElectronDraggeableHeader from './ElectronDraggeableHeader';
/**
* This component adds a drageable area at the top of the windows
* if the client is using an Electron application on macOS.
* Only macOS because we display the title bar on Windows.
*
* The drageable area is in a separate component so it can be used
* at places where Unleash is not yet available (e.g. the login page or some error pages).
*/
const ElectronDraggeableHeaderWrapper = () => {
const isElectronOnMacComputers = isElectronOnMac();
if (!isElectronOnMacComputers) {
return null;
}
return <ElectronDraggeableHeader />;
};
export default ElectronDraggeableHeaderWrapper;
| 5,381
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/ellipsis/MiddleEllipsis.tsx
|
import { HTMLProps, useEffect, useMemo, useRef, useState } from 'react';
import clsx from '@proton/utils/clsx';
import { Tooltip } from '../tooltip';
interface Props extends HTMLProps<HTMLSpanElement> {
text: string;
/**
* number of characters you want to keep at the end: 6 will give “blablabla…bla.bla’”
*/
charsToDisplayEnd?: number;
className?: string;
/**
* when you embed it into something with title/tooltip, you might not want to display it
*/
displayTitle?: Boolean;
/**
* When text is too long, tooltip can be used to show the full text.
*/
displayTooltip?: Boolean;
/**
* Unless you REALLY know what you are doing (if you're using this component on RTL content ONLY for example)
* leave this value to ltr, otherwise you can update it
*/
direction?: string;
}
const MiddleEllipsis = ({
text,
className = '',
displayTitle = true,
displayTooltip = false,
charsToDisplayEnd = 6,
direction = 'ltr',
...rest
}: Props) => {
const [start, end] = useMemo(() => {
// Split text per characters and not bytes. For example, 👋🌍😊🐶 with
// charsToDisplayEnd=3 would end up being 👋🌍� and �🐶 with simple
// string slice. With array slice (because string iterator iterates per
// characters), the results is as expected 👋 and 🌍😊🐶.
// Note this doesn't work with all unicodes. For example, flags have
// six bytes and even that is not handled properly by string iterator.
return [[...text].slice(0, -charsToDisplayEnd).join(''), [...text].slice(-charsToDisplayEnd).join('')];
}, [text]);
const ref = useRef<HTMLSpanElement>(null);
const [tooltipTitle, setTooltipTitle] = useState<string | null>(null);
useEffect(() => {
if (!displayTooltip || !ref.current) {
return;
}
const textIsTooLong = ref.current.offsetWidth < ref.current.scrollWidth;
if (textIsTooLong) {
setTooltipTitle(text);
} else {
setTooltipTitle(null);
}
});
return (
<Tooltip title={tooltipTitle} originalPlacement="bottom">
<span
aria-label={text}
title={displayTitle ? text : undefined}
className={clsx(['inline-flex flex-nowrap max-w-full', className])}
dir={direction}
{...rest}
>
{start && (
<span ref={ref} className="text-ellipsis text-pre" aria-hidden="true">
{start}
</span>
)}
<span className="flex-item-noshrink text-pre" aria-hidden="true">
{end}
</span>
</span>
</Tooltip>
);
};
export default MiddleEllipsis;
| 5,382
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/ellipsis/index.ts
|
export { default as MiddleEllipsis } from './MiddleEllipsis';
| 5,383
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/fileIcon/FileIcon.tsx
|
import {
isAudio,
isExcel,
isFont,
isICS,
isImage,
isPDF,
isSupportedText,
isVideo,
} from '@proton/shared/lib/helpers/mimetype';
import clsx from '@proton/utils/clsx';
import MimeIcon, { MimeIconProps, MimeName } from '../icon/MimeIcon';
const iconsMap: { [mimeType: string]: MimeName } = {
Folder: 'folder',
'application/octet-stream': 'unknown', // Default mimetype when the real one cannot be detected.
'application/x-rar-compressed': 'zip',
'application/x-zip-compressed': 'zip',
'application/zip': 'zip',
'application/x-7z-compressed': 'zip', // .7z — 7-Zip compressed file
'application/x-arj': 'zip', // .arj — ARJ compressed file
'application/x-debian-package': 'zip', // .deb — Debian software package file
'application/x-redhat-package-manager': 'zip', // .rpm
'application/x-rpm': 'zip', // .rpm
'application/vnd.rar': 'zip', // .rar – RAR file
'application/gzip': 'zip', // .tar.gz — Tarball compressed file
'application/x-gzip': 'zip', // .tar.gz — Tarball compressed file
'application/x-compress': 'zip', // .z — Z compressed file
'application/vnd.apple.installer+xml': 'zip', // .pkg
'application/msword': 'doc',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'doc',
'application/vnd.ms-powerpoint': 'ppt', // .ppt/.pps
'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'ppt',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xls', // .xlsm - Microsoft Excel file
'application/vnd.oasis.opendocument.spreadsheet': 'xls', // .ods — OpenOffice Calc spreadsheet file
'application/vnd.oasis.opendocument.presentation': 'ppt', // .ods — OpenOffice Calc presentation file
'application/xliff+xml': 'xml',
'application/xml': 'xml',
'text/html': 'xml', // .html/.htm
'application/xhtml+xml': 'xml', // .xhtml
'application/pgp-keys': 'keytrust',
'application/rtf': 'text',
'application/x-tex': 'text',
'application/vnd.oasis.opendocument.text': 'text',
'application/vnd.wordperfect': 'text',
'application/vnd.ms-fontobject': 'font',
'application/font-sfnt': 'font', // ttf
'application/vnd.oasis.opendocument.formula-template': 'font', // otf
'application/vnd.apple.pages': 'pages',
'application/vnd.apple.numbers': 'numbers',
'application/vnd.apple.keynote': 'keynote',
};
const getIconName = (mimeType: string) => {
let name: MimeName = 'unknown';
if (iconsMap[mimeType]) {
name = iconsMap[mimeType];
} else if (isImage(mimeType)) {
name = 'image';
} else if (mimeType === 'text/xml') {
// Exception for XML to use it's own icon and not fallback as text
name = 'xml';
} else if (isICS(mimeType)) {
name = 'calendar';
} else if (isSupportedText(mimeType)) {
name = 'text';
} else if (isPDF(mimeType)) {
name = 'pdf';
} else if (isVideo(mimeType)) {
name = 'video';
} else if (isAudio(mimeType)) {
name = 'sound';
} else if (isFont(mimeType)) {
name = 'font';
} else if (isExcel(mimeType)) {
name = 'xls';
}
return name;
};
interface Props extends Omit<MimeIconProps, 'name'> {
mimeType: string;
}
/**
* Component to render SVG file icons.
* It's wrapper around MimeIcon component which finds the proper icon
* name based on the mime type.
*/
const FileIcon = ({ mimeType, className, ...rest }: Props) => {
const name = getIconName(mimeType);
return <MimeIcon name={name} className={clsx(['flex-item-noshrink', className])} {...rest} />;
};
export default FileIcon;
| 5,384
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/fileIcon/index.ts
|
export { default as FileIcon } from './FileIcon';
| 5,385
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/fileNameDisplay/FileNameDisplay.tsx
|
import { HTMLProps } from 'react';
import { splitExtension } from '@proton/shared/lib/helpers/file';
import { rtlSanitize } from '@proton/shared/lib/helpers/string';
import { MiddleEllipsis } from '../ellipsis';
const CHARACTERS_BEFORE_EXTENSION = 3;
interface Props extends HTMLProps<HTMLSpanElement> {
text?: string;
className?: string;
charsToDisplayEnd?: number;
}
const FileNameDisplay = ({ text = '', className, charsToDisplayEnd = 6, ...rest }: Props) => {
const sanitized = rtlSanitize(text);
const [, extension] = splitExtension(sanitized);
const extensionOffset =
extension.length < charsToDisplayEnd ? extension.length + CHARACTERS_BEFORE_EXTENSION : charsToDisplayEnd;
return (
<MiddleEllipsis
charsToDisplayEnd={extensionOffset}
className={className}
text={sanitized}
displayTitle={false}
displayTooltip
{...rest}
/>
);
};
export default FileNameDisplay;
| 5,386
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/fileNameDisplay/index.ts
|
export { default as FileNameDisplay } from './FileNameDisplay';
| 5,387
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/focus/index.ts
|
export { default as useFocusTrap } from './useFocusTrap';
| 5,388
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/focus/useFocusTrap.test.tsx
|
import { ReactNode, useRef, useState } from 'react';
import { fireEvent, render, waitFor } from '@testing-library/react';
import useFocusTrap from './useFocusTrap';
describe('FocusTrap', () => {
let initialFocus: HTMLElement;
beforeEach(() => {
initialFocus = document.createElement('button');
document.body.appendChild(initialFocus);
initialFocus.focus();
});
afterEach(() => {
document.body.removeChild(initialFocus);
});
it('should not focus the first focusable element', () => {
const Component = () => {
const rootRef = useRef<HTMLDivElement>(null);
const props = useFocusTrap({ rootRef });
return (
<div ref={rootRef} {...props}>
<input data-testid="auto-focus" />
</div>
);
};
const { getByTestId } = render(<Component />);
expect(getByTestId('auto-focus')).not.toHaveFocus();
});
it('should focus the root element if initial setting is off', () => {
const Component = () => {
const rootRef = useRef<HTMLDivElement>(null);
const props = useFocusTrap({ rootRef, enableInitialFocus: false });
return (
<div ref={rootRef} {...props} data-testid="root-focus">
<input data-testid="auto-focus" />
</div>
);
};
const { getByTestId } = render(<Component />);
expect(getByTestId('root-focus')).toHaveFocus();
});
it('should respect autoFocus in children', () => {
const Component = () => {
const rootRef = useRef<HTMLDivElement>(null);
const props = useFocusTrap({ rootRef });
return (
<div ref={rootRef} {...props}>
<input />
<input autoFocus data-testid="auto-focus" />
</div>
);
};
const { getByTestId } = render(<Component />);
expect(getByTestId('auto-focus')).toHaveFocus();
});
it('should set tabIndex on root if there are focusable elements', () => {
const Component = () => {
const rootRef = useRef<HTMLDivElement>(null);
const props = useFocusTrap({ rootRef });
return (
<div ref={rootRef} {...props} data-testid="root">
<button autoFocus />
</div>
);
};
const { getByTestId } = render(<Component />);
expect(getByTestId('root')).toHaveAttribute('tabIndex', '-1');
});
it('should focus first fallback if requested', () => {
const Component = () => {
const rootRef = useRef<HTMLDivElement>(null);
const props = useFocusTrap({ rootRef });
return (
<div ref={rootRef} {...props} data-testid="root">
<div data-testid="div" data-focus-trap-fallback="0" tabIndex={-1} />
<button data-testid="button" />
</div>
);
};
const { getByTestId } = render(<Component />);
expect(getByTestId('div')).toHaveFocus();
});
it('should set tabIndex on root when active', () => {
const Component = () => {
const [active, setActive] = useState(false);
const rootRef = useRef<HTMLDivElement>(null);
const props = useFocusTrap({ active, rootRef });
return (
<div ref={rootRef} {...props} data-testid="root">
<button data-testid="button" autoFocus onClick={() => setActive(!active)} />
</div>
);
};
const { getByTestId } = render(<Component />);
expect(getByTestId('root')).not.toHaveAttribute('tabIndex', '-1');
const openerButton = getByTestId('button');
openerButton.click();
expect(getByTestId('root')).toHaveAttribute('tabIndex', '-1');
openerButton.click();
expect(getByTestId('root')).not.toHaveAttribute('tabIndex', '-1');
});
it('should set tabIndex on root if there are no focusable elements', () => {
const Component = () => {
const rootRef = useRef<HTMLDivElement>(null);
const props = useFocusTrap({ rootRef });
return (
<div ref={rootRef} {...props} data-testid="root">
<div>No focusable element</div>
</div>
);
};
const { getByTestId } = render(<Component />);
expect(getByTestId('root')).toHaveAttribute('tabIndex', '-1');
});
it('should not restore focus if closed by click', async () => {
const Component = () => {
const [open, setOpen] = useState(false);
const rootRef = useRef<HTMLDivElement>(null);
const props = useFocusTrap({ rootRef, active: open });
return (
<div>
<button data-testid="button" onClick={() => setOpen(true)} />
{open && (
<div {...props} ref={rootRef}>
<button data-testid="close" onClick={() => setOpen(false)} />
<input autoFocus data-testid="input" />
</div>
)}
</div>
);
};
const { getByTestId } = render(<Component />);
const openerButton = getByTestId('button');
openerButton.focus();
fireEvent.mouseUp(openerButton);
fireEvent.click(openerButton);
expect(getByTestId('input')).toHaveFocus();
const closeButton = getByTestId('close');
fireEvent.mouseUp(closeButton);
fireEvent.click(closeButton);
await waitFor(() => {
expect(openerButton).not.toHaveFocus();
});
});
it('should restore focus if closed by keyboard', async () => {
const Component = () => {
const [open, setOpen] = useState(false);
const rootRef = useRef<HTMLDivElement>(null);
const props = useFocusTrap({ rootRef, active: open });
return (
<div>
<button data-testid="button" onClick={() => setOpen(true)} />
{open && (
<div {...props} ref={rootRef}>
<input autoFocus data-testid="input" onKeyDown={() => setOpen(false)} />
</div>
)}
</div>
);
};
const { getByTestId } = render(<Component />);
const openerButton = getByTestId('button');
openerButton.focus();
fireEvent.mouseUp(openerButton);
fireEvent.click(openerButton);
expect(getByTestId('input')).toHaveFocus();
fireEvent.keyDown(getByTestId('input'), { key: 'Esc' });
await waitFor(() => {
expect(openerButton).toHaveFocus();
});
});
// TODO: Broken with latest jsdom
it.skip('should not restore focus when another trap overrides it', async () => {
const Dropdown = ({ open, children }: { open: boolean; children: ReactNode }) => {
const rootRef = useRef<HTMLDivElement>(null);
const props = useFocusTrap({ rootRef, active: open });
return (
<>
{open && (
<div {...props} ref={rootRef}>
{children}
</div>
)}
</>
);
};
const Component = () => {
const [open, setOpen] = useState(false);
const [open2nd, setOpen2nd] = useState(false);
return (
<div>
<button data-testid="button1" onClick={() => setOpen(!open)} />
<Dropdown open={open}>
<input autoFocus data-testid="input1" />
</Dropdown>
<button data-testid="button2" onClick={() => setOpen2nd(!open2nd)} />
<Dropdown open={open2nd}>
<input autoFocus data-testid="input2" />
</Dropdown>
</div>
);
};
const { getByTestId } = render(<Component />);
const openerButton = getByTestId('button1');
openerButton.focus();
openerButton.click();
await waitFor(() => {
expect(getByTestId('input1')).toHaveFocus();
});
const openerButton2 = getByTestId('button2');
openerButton2.focus();
openerButton2.click();
await waitFor(() => {
expect(getByTestId('input2')).toHaveFocus();
});
openerButton.click();
await waitFor(() => {
expect(getByTestId('input2')).toHaveFocus();
});
openerButton2.click();
await waitFor(() => {
expect(openerButton2).toHaveFocus();
});
});
it('should contain focus when tabbing', async () => {
const Component = () => {
const rootRef = useRef<HTMLDivElement>(null);
const props = useFocusTrap({ rootRef });
return (
<div>
<button data-testid="outside-1" />
<div {...props} ref={rootRef} data-testid="root">
<button data-testid="1" />
<button data-testid="2" autoFocus />
</div>
<button data-testid="outside-2" />
</div>
);
};
const { getByTestId } = render(<Component />);
expect(getByTestId('2')).toHaveFocus();
fireEvent.keyDown(getByTestId('2'), {
key: 'Tab',
});
expect(getByTestId('1')).toHaveFocus();
fireEvent.keyDown(getByTestId('1'), {
key: 'Tab',
shiftKey: true,
});
expect(getByTestId('2')).toHaveFocus();
});
it('should contain focus when elements are deleted', async () => {
jest.useFakeTimers();
const Component = () => {
const rootRef = useRef<HTMLDivElement>(null);
const [hidden, setHidden] = useState(false);
const props = useFocusTrap({ rootRef });
return (
<div {...props} ref={rootRef} data-testid="root">
{!hidden && <button data-testid="1" autoFocus onClick={() => setHidden(true)} />}
</div>
);
};
const { getByTestId } = render(<Component />);
expect(getByTestId('1')).toHaveFocus();
fireEvent.click(getByTestId('1'));
jest.runOnlyPendingTimers();
expect(getByTestId('root')).toHaveFocus();
jest.useRealTimers();
});
});
| 5,389
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/focus/useFocusTrap.tsx
|
import { MutableRefObject, useEffect, useRef, useState } from 'react';
import { FocusableElement, isFocusable, tabbable } from 'tabbable';
import { getIsIframe } from '@proton/shared/lib/helpers/browser';
const findParentElement = (el: Element | null | undefined, cb: (el: Element) => boolean) => {
let nextEl = el;
while (nextEl) {
if (cb(nextEl)) {
return nextEl;
}
nextEl = nextEl.parentElement;
}
};
export const getTargetRootElement = (start: Element | null | undefined) => {
const result = findParentElement(start, (el) => {
const htmlEl = el as HTMLElement;
return htmlEl.dataset?.focusRoot === '1';
});
return result as HTMLElement | undefined;
};
const manager = (() => {
const data: any[] = [];
const remove = (item: any) => {
const idx = data.indexOf(item);
if (idx === -1) {
return;
}
data.splice(idx, 1);
};
return {
add: (item: any) => {
data.push(item);
return () => {
remove(item);
};
},
isLast: (item: any) => (data.length ? data[data.length - 1] === item : false),
remove,
};
})();
interface Props {
rootRef: MutableRefObject<HTMLDivElement | null>;
active?: boolean;
restoreFocus?: boolean;
preventScroll?: boolean;
disableRestoreByPointer?: boolean;
enableInitialFocus?: boolean;
}
const useFocusTrap = ({
active = true,
enableInitialFocus = true,
restoreFocus = true,
preventScroll = true,
disableRestoreByPointer = true,
rootRef,
}: Props) => {
const [id] = useState({});
const nodeToRestoreRef = useRef<Element | null>(null);
const prevOpenRef = useRef(false);
const pendingRef = useRef('');
const isIframe = getIsIframe();
useEffect(() => {
prevOpenRef.current = active;
}, [active]);
if (!prevOpenRef.current && active) {
pendingRef.current = '1';
nodeToRestoreRef.current = document.activeElement;
}
useEffect(() => {
if (!active || !rootRef.current) {
return;
}
manager.add(id);
const isLastFocusTrap = () => {
return manager.isLast(id);
};
rootRef.current.removeAttribute('data-focus-pending');
pendingRef.current = '';
let isMouseDownFocusIn = false;
let mouseUpTime: number | undefined;
let keyDownTime: number | undefined;
const focusElement = (node?: FocusableElement | HTMLElement | null, fallback?: HTMLElement) => {
if (node === document.activeElement) {
return;
}
if (!node?.focus) {
focusElement(fallback);
return;
}
node.focus({ preventScroll: !!preventScroll });
};
const initFocus = (rootElement: HTMLElement) => {
const target = rootElement.querySelector('[data-focus-trap-fallback]');
if (!target) {
focusElement(rootElement);
return;
}
focusElement(target as HTMLElement, rootElement);
};
const handleFocusIn = (event: FocusEvent) => {
const { current: rootElement } = rootRef;
if (!rootElement || !isLastFocusTrap() || !document.hasFocus()) {
return;
}
const targetRootElement = getTargetRootElement(document.activeElement);
// A new focus trap is going to become active, but has not yet triggered its useEffect, abort.
if (targetRootElement?.dataset?.focusPending) {
return;
}
// Focus is already in this root.
if (targetRootElement === rootElement) {
return;
}
if (isMouseDownFocusIn) {
isMouseDownFocusIn = false;
return;
}
event.stopImmediatePropagation();
initFocus(rootElement);
};
const handleKeyDown = (event: KeyboardEvent) => {
keyDownTime = Date.now();
if (!isLastFocusTrap() || event.key !== 'Tab' || !rootRef.current) {
return;
}
const { current: rootElement } = rootRef;
const tabbableElements = tabbable(rootElement, { includeContainer: false });
if (tabbableElements.length === 0) {
focusElement(rootElement);
return;
}
const firstTabbableNode = tabbableElements[0];
const lastTabbableNode = tabbableElements[tabbableElements.length - 1];
if (event.shiftKey && event.target === firstTabbableNode) {
event.preventDefault();
focusElement(lastTabbableNode, rootElement);
}
if (!event.shiftKey && event.target === lastTabbableNode) {
event.preventDefault();
focusElement(firstTabbableNode, rootElement);
}
};
const contain = (root: HTMLDivElement) => {
// In the case where the app is inside an iframe, the focus trap can block the parent app to take the focus
// So it becomes impossible to use inputs for example
// In that case, iframe side, we see that the active element is the iframe body
// So if we see that the activeElement is the root body, it means we want to take the focus outside the iframe
const isFocusedElementOutsideFrame = root.ownerDocument.body === document.activeElement && isIframe;
// If the current focused element is not in this root. E.g. no autoFocus
// and the focused element is inside the frame, we can focus the element
if (!root.contains(document.activeElement) && !isFocusedElementOutsideFrame) {
// If the first tabbable element should not be focused, fall back to the container
if (!enableInitialFocus) {
focusElement(root);
} else {
initFocus(root);
}
}
};
// Unfortunately browsers don't trigger any focus related events when focus is lost
// because for example the element was deleted or the new element is not focusable.
// https://bugzilla.mozilla.org/show_bug.cgi?id=559561
// Instead, we look for if the active element was restored to the body.
// This idea was stolen from material ui.
const containIntervalHandle = window.setInterval(() => {
if (document.activeElement?.tagName === 'BODY' && isLastFocusTrap() && rootRef.current) {
contain(rootRef.current);
}
}, 100);
contain(rootRef.current);
const handleMouseDown = () => {
isMouseDownFocusIn = true;
};
const handleMouseUp = () => {
isMouseDownFocusIn = false;
mouseUpTime = Date.now();
};
document.addEventListener('mousedown', handleMouseDown, true);
document.addEventListener('mouseup', handleMouseUp, true);
document.addEventListener('focusin', handleFocusIn, true);
document.addEventListener('keydown', handleKeyDown, true);
return () => {
window.clearInterval(containIntervalHandle);
document.removeEventListener('focusin', handleFocusIn, true);
document.removeEventListener('keydown', handleKeyDown, true);
document.removeEventListener('mousedown', handleMouseDown, true);
document.removeEventListener('mouseup', handleMouseUp, true);
manager.remove(id);
const currentActiveElement = document.activeElement;
const targetRootElement = getTargetRootElement(currentActiveElement);
const isFocusInAnotherRoot = targetRootElement && targetRootElement !== rootRef.current;
const isFocusInThisRoot = targetRootElement && targetRootElement === rootRef.current;
const isCurrentActiveElementFocusable = currentActiveElement && isFocusable(currentActiveElement);
// Determine if this focus trap became inactive because of a pointer action, or if it was closed by 'esc'
const isClosedByPointer = (mouseUpTime || 0) > (keyDownTime || 0);
const nodeToRestore = nodeToRestoreRef.current as HTMLElement | undefined;
nodeToRestoreRef.current = null;
if (
!restoreFocus ||
(disableRestoreByPointer && isClosedByPointer) ||
!nodeToRestore ||
isFocusInAnotherRoot ||
(!isFocusInThisRoot && isCurrentActiveElementFocusable)
) {
return;
}
nodeToRestore.focus?.();
};
}, [active]);
return active
? {
...(pendingRef.current && { 'data-focus-pending': pendingRef.current }),
'data-focus-root': '1',
tabIndex: -1,
}
: {
'data-focus-root': '1',
};
};
export default useFocusTrap;
| 5,390
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/footer/Footer.tsx
|
import { HTMLAttributes, ReactNode } from 'react';
import clsx from '@proton/utils/clsx';
export interface Props extends HTMLAttributes<HTMLDivElement> {
children?: ReactNode;
className?: string;
}
const Footer = ({ children, className, ...rest }: Props) => {
return (
<footer className={clsx(['footer flex flex-nowrap reset4print', className])} {...rest}>
{children}
</footer>
);
};
export default Footer;
| 5,391
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/form/Form.tsx
|
import { ComponentPropsWithoutRef, createContext } from 'react';
interface FormOwnProps {
dense?: boolean;
}
export const FormContext = createContext<FormOwnProps>({});
export type FormProps = ComponentPropsWithoutRef<'form'> & FormOwnProps;
const Form = ({ dense, ...props }: FormProps) => {
return (
<FormContext.Provider value={{ dense }}>
<form
method="post"
{...props}
onSubmit={(event) => {
event.preventDefault();
props.onSubmit?.(event);
}}
/>
</FormContext.Provider>
);
};
export default Form;
| 5,392
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/form/index.ts
|
export { default as Form } from './Form';
export * from './Form';
| 5,393
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/globalLoader/GlobalLoader.tsx
|
import { useContext } from 'react';
import { Loader } from '../loader';
import { GlobalLoaderTasksContext } from './GlobalLoaderProvider';
const GlobalLoader = () => {
const [task] = useContext(GlobalLoaderTasksContext) || [];
if (!task) {
return null;
}
const { text } = task.options;
return (
<div
className="fixed flex absolute-center-x bg-norm color-weak p-2 rounded top-custom global-loader"
style={{ '--top-custom': '1.5em' }}
>
<Loader size="small" className="flex" />
{text && <span className="ml-2">{text}</span>}
</div>
);
};
export default GlobalLoader;
| 5,394
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/globalLoader/GlobalLoaderProvider.tsx
|
import { ReactNode, createContext, useCallback, useMemo, useReducer } from 'react';
export interface TaskOptions {
text?: string;
}
export interface Task {
promise: Promise<any>;
options: TaskOptions;
}
type Action = { type: 'addPendingTask'; payload: Task } | { type: 'resolvePendingTask'; payload: Task };
const reducer = (state: Task[], action: Action) => {
switch (action.type) {
case 'addPendingTask':
return [...state, action.payload];
case 'resolvePendingTask':
return state.filter((task) => task !== action.payload);
default:
return state;
}
};
const useGlobalLoaderProvider = () => {
const [tasks, dispatch] = useReducer(reducer, []);
const addPendingTask = useCallback(<T,>(promise: Promise<T>, options: TaskOptions): [Promise<T>, Task] => {
const task = { options, promise };
dispatch({ type: 'addPendingTask', payload: task });
return [
promise.finally(() => {
dispatch({ type: 'resolvePendingTask', payload: task });
}),
task,
];
}, []);
return {
tasks,
addPendingTask,
};
};
export const GlobalLoaderTasksContext = createContext<Task[] | null>(null);
export const GlobalLoaderContext = createContext<{
addPendingTask: <T>(promise: Promise<T>, options: TaskOptions) => [Promise<T>, Task];
} | null>(null);
interface Props {
children: ReactNode;
}
const GlobalLoaderProvider = ({ children }: Props) => {
const { addPendingTask, tasks } = useGlobalLoaderProvider();
const globalLoader = useMemo(() => ({ addPendingTask }), [addPendingTask]);
return (
<GlobalLoaderTasksContext.Provider value={tasks}>
<GlobalLoaderContext.Provider value={globalLoader}>{children}</GlobalLoaderContext.Provider>
</GlobalLoaderTasksContext.Provider>
);
};
export default GlobalLoaderProvider;
| 5,395
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/globalLoader/index.tsx
|
export { default as GlobalLoader } from './GlobalLoader';
export { default as GlobalLoaderProvider } from './GlobalLoaderProvider';
export { default as useGlobalLoader } from './useGlobalLoader';
| 5,396
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/globalLoader/useGlobalLoader.ts
|
import { useContext } from 'react';
import { GlobalLoaderContext, TaskOptions } from './GlobalLoaderProvider';
type WithGlobalLoading = <T>(promise: Promise<T>) => Promise<T>;
function useGlobalLoader(defaultTaskOptions: TaskOptions = {}): WithGlobalLoading {
const globalLoader = useContext(GlobalLoaderContext);
if (!globalLoader) {
throw new Error('Trying to use uninitialized GlobalLoaderContext');
}
const withGlobalLoader = <T>(promise: Promise<T>, options: TaskOptions = defaultTaskOptions) => {
const [taskPromise] = globalLoader.addPendingTask(promise, options);
return taskPromise;
};
return withGlobalLoader;
}
export default useGlobalLoader;
| 5,397
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/header/Header.tsx
|
import { HTMLAttributes, ReactNode } from 'react';
import clsx from '@proton/utils/clsx';
export interface Props extends HTMLAttributes<HTMLDivElement> {
children?: ReactNode;
className?: string;
}
const Header = ({ children, className, ...rest }: Props) => {
return (
<header className={clsx(['header flex flex-nowrap reset4print', className])} {...rest}>
{children}
</header>
);
};
export default Header;
| 5,398
|
0
|
petrpan-code/ProtonMail/WebClients/packages/components/components
|
petrpan-code/ProtonMail/WebClients/packages/components/components/icon/ContactKeyWarningIcon.tsx
|
import { c } from 'ttag';
import { PublicKeyReference } from '@proton/crypto';
import { getEmailMismatchWarning } from '@proton/shared/lib/keys/publicKeys';
import WarningIcon from './WarningIcon';
interface Props {
publicKey: PublicKeyReference;
emailAddress: string;
isInternal: boolean;
supportsEncryption?: boolean;
className?: string;
}
const ContactKeyWarningIcon = ({ publicKey, emailAddress, isInternal, supportsEncryption, className }: Props) => {
if (!emailAddress) {
return null;
}
const encryptionWarnings =
supportsEncryption === false ? [c('PGP key encryption warning').t`Key cannot be used for encryption`] : [];
const emailWarnings = getEmailMismatchWarning(publicKey, emailAddress, isInternal);
const warnings = encryptionWarnings.concat(emailWarnings);
if (!warnings.length) {
return null;
}
return <WarningIcon warning={warnings.join(' • ')} className={className} />;
};
export default ContactKeyWarningIcon;
| 5,399
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.