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/upsell/modal
petrpan-code/ProtonMail/WebClients/packages/components/components/upsell/modal/types/FiltersUpsellModal.tsx
import { c } from 'ttag'; import { ModalStateProps, UpsellModal } from '@proton/components/components'; import { APP_UPSELL_REF_PATH, MAIL_UPSELL_PATHS, UPSELL_COMPONENT } from '@proton/shared/lib/constants'; import { getUpsellRef } from '@proton/shared/lib/helpers/upsell'; interface Props { modalProps: ModalStateProps; /** * Needed in a "Dropdown" scenario because we want to close the dropdown after closing the upsell modal */ onCloseCustomAction?: () => void; isSettings?: boolean; } const FiltersUpsellModal = ({ modalProps, onCloseCustomAction, isSettings = false }: Props) => { const upsellRef = getUpsellRef({ app: APP_UPSELL_REF_PATH.MAIL_UPSELL_REF_PATH, component: UPSELL_COMPONENT.MODAL, feature: MAIL_UPSELL_PATHS.UNLIMITED_FILTERS, isSettings, }); return ( <UpsellModal title={c('Title').t`Save time with email filters`} description={c('Description') .t`Unlock unlimited filters that sort your inbox for you and more premium features when you upgrade.`} modalProps={modalProps} upsellRef={upsellRef} features={['more-storage', 'more-email-addresses', 'unlimited-folders-and-labels', 'custom-email-domains']} onClose={onCloseCustomAction} /> ); }; export default FiltersUpsellModal;
5,700
0
petrpan-code/ProtonMail/WebClients/packages/components/components/upsell/modal
petrpan-code/ProtonMail/WebClients/packages/components/components/upsell/modal/types/LabelsUpsellModal.tsx
import { c } from 'ttag'; import { ModalStateProps, UpsellModal } from '@proton/components/components'; import { APP_UPSELL_REF_PATH, MAIL_UPSELL_PATHS, UPSELL_COMPONENT } from '@proton/shared/lib/constants'; import { getUpsellRef } from '@proton/shared/lib/helpers/upsell'; interface Props { modalProps: ModalStateProps; feature: MAIL_UPSELL_PATHS.UNLIMITED_FOLDERS | MAIL_UPSELL_PATHS.UNLIMITED_LABELS; /** * Needed in a "Dropdown" scenario because we want to close the dropdown after closing the upsell modal */ onCloseCustomAction?: () => void; isSettings?: boolean; } const LabelsUpsellModal = ({ modalProps, onCloseCustomAction, feature, isSettings = false }: Props) => { const upsellRef = getUpsellRef({ app: APP_UPSELL_REF_PATH.MAIL_UPSELL_REF_PATH, component: UPSELL_COMPONENT.MODAL, feature, isSettings, }); return ( <UpsellModal title={c('Title').t`Keep your inbox organized`} description={c('Description') .t`Unlock unlimited folders, labels and more premium features when you upgrade.`} modalProps={modalProps} upsellRef={upsellRef} features={['more-storage', 'more-email-addresses', 'unlimited-folders-and-labels', 'custom-email-domains']} onClose={onCloseCustomAction} /> ); }; export default LabelsUpsellModal;
5,701
0
petrpan-code/ProtonMail/WebClients/packages/components/components/upsell/modal
petrpan-code/ProtonMail/WebClients/packages/components/components/upsell/modal/types/PmMeUpsellModal.tsx
import { c } from 'ttag'; import { ModalStateProps, UpsellModal } from '@proton/components/components'; import { APP_UPSELL_REF_PATH, MAIL_UPSELL_PATHS, UPSELL_COMPONENT } from '@proton/shared/lib/constants'; import { getUpsellRef } from '@proton/shared/lib/helpers/upsell'; interface Props { modalProps: ModalStateProps; } const FiltersUpsellModal = ({ modalProps }: Props) => { const upsellRef = getUpsellRef({ app: APP_UPSELL_REF_PATH.MAIL_UPSELL_REF_PATH, component: UPSELL_COMPONENT.MODAL, feature: MAIL_UPSELL_PATHS.SHORT_ADDRESS, isSettings: true, }); return ( <UpsellModal title={c('Title').t`Activate @pm.me`} description={c('Description').t`Unlock shorter email addresses and other premium features by upgrading.`} modalProps={modalProps} upsellRef={upsellRef} features={['more-storage', 'more-email-addresses', 'unlimited-folders-and-labels', 'custom-email-domains']} /> ); }; export default FiltersUpsellModal;
5,702
0
petrpan-code/ProtonMail/WebClients/packages/components/components
petrpan-code/ProtonMail/WebClients/packages/components/components/v2/index.ts
export { default as DateInputTwo } from './input/DateInputTwo'; export { default as TotpInput } from './input/TotpInput'; export { default as TextAreaTwo } from './input/TextArea'; export { default as PhoneInput } from './phone/LazyPhoneInput'; export { default as PasswordInputTwo } from './input/PasswordInput'; export { default as InputFieldTwo } from './field/InputField'; export { default as useFormErrors } from './useFormErrors'; export { default as AddressesAutocompleteTwo } from './addressesAutocomplete/AddressesAutocomplete';
5,703
0
petrpan-code/ProtonMail/WebClients/packages/components/components
petrpan-code/ProtonMail/WebClients/packages/components/components/v2/useFormErrors.ts
import { useEffect, useRef, useState } from 'react'; import { flushSync } from 'react-dom'; import { errorClassName } from '../v2/field/InputField'; const useFormErrors = () => { const [, rerender] = useState<any>(); const errorsMapRef = useRef<string[]>([]); const isSubmittedRef = useRef(false); const errors: string[] = []; useEffect(() => { errorsMapRef.current = errors; }); useEffect(() => { return () => { errorsMapRef.current = []; }; }, []); return { reset: () => { isSubmittedRef.current = false; errorsMapRef.current = []; rerender({}); }, onFormSubmit: (element?: HTMLElement) => { isSubmittedRef.current = true; if (element) { flushSync(() => { rerender({}); }); element?.querySelector(`.${errorClassName}`)?.scrollIntoView(); } else { rerender({}); } const oldErrors = errorsMapRef.current; return !oldErrors.some((value) => !!value); }, validator: (validations: string[]) => { const error = validations.reduce((acc, x) => acc || x, ''); errors.push(error); return isSubmittedRef.current ? error : ''; }, }; }; export default useFormErrors;
5,704
0
petrpan-code/ProtonMail/WebClients/packages/components/components/v2
petrpan-code/ProtonMail/WebClients/packages/components/components/v2/addressesAutocomplete/AddressesAutocomplete.tsx
import { KeyboardEvent, RefObject, forwardRef, useCallback, useMemo, useRef, useState } from 'react'; import { Input } from '@proton/atoms'; import { useCombinedRefs } from '@proton/hooks'; import { canonicalizeEmail } from '@proton/shared/lib/helpers/email'; import { Recipient } from '@proton/shared/lib/interfaces'; import { ContactEmail, ContactGroup } from '@proton/shared/lib/interfaces/contacts'; import { SimpleMap } from '@proton/shared/lib/interfaces/utils'; import { handleRecipientInputChange, inputToRecipient, splitBySeparator } from '@proton/shared/lib/mail/recipient'; import clsx from '@proton/utils/clsx'; import noop from '@proton/utils/noop'; import { AddressesAutocompleteItem, GroupsWithContactsMap, getContactGroupsAutocompleteItems, getContactsAutocompleteItems, getNumberOfMembersCount, getNumberOfMembersText, getRecipientFromAutocompleteItem, } from '../../addressesAutocomplete/helper'; import { AutocompleteList, useAutocomplete, useAutocompleteFilter } from '../../autocomplete'; import Icon from '../../icon/Icon'; import { Option } from '../../option'; import { Marks } from '../../text'; import InputField, { InputFieldProps } from '../field/InputField'; interface Props extends Omit<InputFieldProps<typeof Input>, 'value' | 'onChange'> { id: string; onKeyDown?: (e: KeyboardEvent<HTMLInputElement>) => void; onAddRecipients: (recipients: Recipient[]) => void; recipients: Recipient[]; anchorRef?: RefObject<HTMLElement>; contactEmails?: ContactEmail[]; contactGroups?: ContactGroup[]; contactEmailsMap?: SimpleMap<ContactEmail>; groupsWithContactsMap?: GroupsWithContactsMap; hasEmailPasting?: boolean; hasAddOnBlur?: boolean; limit?: number; onAddInvalidEmail?: () => void; validate?: (email: string) => string | void; onChange?: (value: string) => void; compact?: boolean; excludedEmails?: string[]; } const AddressesAutocompleteTwo = forwardRef<HTMLInputElement, Props>( ( { contactEmails, contactEmailsMap, contactGroups, groupsWithContactsMap, id, onKeyDown, recipients, onAddRecipients, anchorRef, hasEmailPasting = false, hasAddOnBlur = false, limit = 20, onAddInvalidEmail, onChange, validate = noop, compact, excludedEmails = [], ...rest }: Props, ref ) => { const [input, setInput] = useState(''); const [emailError, setEmailError] = useState(''); const inputRef = useRef<HTMLInputElement>(null); const rootRef = useRef<HTMLDivElement>(null); const [recipientsByAddress, recipientsByGroup] = useMemo(() => { return recipients.reduce<[Set<string>, Set<string>]>( (acc, { Address, Group }) => { if (Address) { acc[0].add(canonicalizeEmail(Address)); } if (Group) { acc[1].add(Group); } return acc; }, [new Set(), new Set()] ); }, [recipients]); const isGroupEmpty = (groupID: string) => { return groupsWithContactsMap ? (groupsWithContactsMap[groupID]?.contacts.length || 0) <= 0 : false; }; const filteredContactEmails = useMemo( () => contactEmails?.filter(({ Email }) => !excludedEmails.includes(Email)), [contactEmails, excludedEmails] ); const contactsAutocompleteItems = useMemo(() => { return [ ...getContactsAutocompleteItems( filteredContactEmails, ({ Email }) => !recipientsByAddress.has(canonicalizeEmail(Email)) && !validate(Email) ), ...getContactGroupsAutocompleteItems( contactGroups, ({ Path, ID }) => !recipientsByGroup.has(Path) && !isGroupEmpty(ID) ), ]; }, [filteredContactEmails, contactGroups, recipientsByAddress, recipientsByGroup]); const options = [...contactsAutocompleteItems]; const safeAddRecipients = (newRecipients: Recipient[]) => { const recipients = newRecipients.filter(({ Address }) => { return !validate(Address || ''); }); if (!recipients.length) { return; } onAddRecipients(recipients); }; const handleAddRecipient = (newRecipients: Recipient[]) => { setInput(''); setEmailError(''); safeAddRecipients(newRecipients); }; const handleAddRecipientFromInput = (input: string) => { const trimmedInput = input.trim(); if (!trimmedInput.length) { setInput(''); return; } const inputs = splitBySeparator(trimmedInput); const recipients = inputs.map((input) => inputToRecipient(input)); const { validRecipients, invalidRecipients, errors } = recipients.reduce<{ validRecipients: Recipient[]; invalidRecipients: Recipient[]; errors: string[]; }>( (acc, recipient) => { const error = validate(recipient.Address || ''); if (error) { acc.errors.push(error); acc.invalidRecipients.push(recipient); } else { acc.validRecipients.push(recipient); } return acc; }, { validRecipients: [], invalidRecipients: [], errors: [] } ); handleAddRecipient(validRecipients); if (errors.length) { onAddInvalidEmail?.(); setEmailError(errors[0]); setInput(invalidRecipients.map(({ Address }) => Address).join(', ')); } }; const handleSelect = (item: AddressesAutocompleteItem) => { handleAddRecipient(getRecipientFromAutocompleteItem(contactEmails, item)); }; const getData = useCallback((value) => { return value.label; }, []); const filteredOptions = useAutocompleteFilter(input, options, getData, limit, 1); // If a group name is equal to the search input, we want to display it as the first option const exactNameGroup = filteredOptions.find( ({ option: { label, type } }) => label === input && type === 'group' ); // Put the group at the first place if found const filteredAndSortedOptions = exactNameGroup ? [exactNameGroup, ...filteredOptions.filter(({ option: { label } }) => label !== input)] : filteredOptions; const { getOptionID, inputProps, suggestionProps } = useAutocomplete<AddressesAutocompleteItem>({ id, options: filteredOptions, onSelect: handleSelect, input, inputRef, }); const handleInputChange = (newValue: string) => { handleRecipientInputChange(newValue, hasEmailPasting, onAddRecipients, setInput); }; return ( <> <InputField {...rest} {...inputProps} dense ref={useCombinedRefs(ref, inputRef)} rootRef={rootRef} value={input} onValue={(value: string) => { handleInputChange(value.trimStart()); onChange?.(value); }} onKeyDown={(event: KeyboardEvent<HTMLInputElement>) => { setEmailError(''); // If the default key down handler did not take care of this, add another layer if (!inputProps.onKeyDown(event)) { if (event.key === 'Enter') { handleAddRecipientFromInput(input); event.preventDefault(); } } onKeyDown?.(event); }} onBlur={() => { inputProps.onBlur(); if (hasAddOnBlur) { handleAddRecipientFromInput(input); } }} className={clsx([rest.className, compact && 'border-none'])} style={{ ...(compact ? { height: 'auto', minHeight: 'auto' } : {}), ...(rest.style ? rest.style : {}), }} error={emailError} /> <AutocompleteList anchorRef={anchorRef || rootRef} {...suggestionProps}> {filteredAndSortedOptions.map(({ chunks, text, option }, index) => { return ( <Option key={option.key} id={getOptionID(index)} title={ option.type === 'group' ? `${option.label} ${getNumberOfMembersText( option.value.ID, groupsWithContactsMap )}` : option.label } value={option} disableFocusOnActive onChange={handleSelect} > {option.type === 'group' ? ( <div className="flex flex-nowrap flex-flex-align-items-center"> <Icon name="circle-filled" color={option.value.Color} size={12} className="mr-2 flex-item-noshrink flex-item-centered-vert" /> <span className="mr-2 text-ellipsis"> <Marks chunks={chunks}>{text}</Marks> </span> <span className="color-weak text-no-wrap"> {getNumberOfMembersCount(option.value.ID, groupsWithContactsMap)} </span> </div> ) : ( <Marks chunks={chunks}>{text}</Marks> )} </Option> ); })} </AutocompleteList> </> ); } ); AddressesAutocompleteTwo.displayName = 'AddressesAutocompleteTwo'; export default AddressesAutocompleteTwo;
5,705
0
petrpan-code/ProtonMail/WebClients/packages/components/components/v2
petrpan-code/ProtonMail/WebClients/packages/components/components/v2/field/InputField.test.tsx
import { render } from '@testing-library/react'; import InputFieldTwo from './InputField'; const ComponentWithDefaultTestId = (props: any) => { return ( <div data-testid="foo" {...props}> bar </div> ); }; describe('input field test', () => { it('should not override default data-testid', () => { const { getByTestId } = render(<InputFieldTwo as={ComponentWithDefaultTestId} />); expect(getByTestId('foo')).toBeVisible(); }); it('should let data-testid be defined', () => { const { getByTestId, queryByTestId } = render( <InputFieldTwo data-testid="bar" as={ComponentWithDefaultTestId} /> ); expect(getByTestId('bar')).toBeVisible(); expect(queryByTestId('foo')).toBeNull(); }); });
5,706
0
petrpan-code/ProtonMail/WebClients/packages/components/components/v2
petrpan-code/ProtonMail/WebClients/packages/components/components/v2/field/InputField.tsx
import React, { ElementType, ForwardedRef, ReactElement, ReactNode, Ref, forwardRef, useContext, useRef, useState, } from 'react'; import { PolymorphicPropsWithRef } from 'react-polymorphic-types'; import { isFocusable } from 'tabbable'; import { Input } from '@proton/atoms'; import useInstance from '@proton/hooks/useInstance'; import clsx from '@proton/utils/clsx'; import { FormContext } from '../../../components'; import { generateUID } from '../../../helpers'; import Icon from '../../icon/Icon'; import { Tooltip } from '../../tooltip'; export type NodeOrBoolean = ReactNode | boolean; // TODO: Add required child props to the as component /* interface RequiredChildProps { id?: string; error: ErrorProp; disabled?: boolean; disableChange?: boolean; } */ export interface InputFieldOwnProps { label?: ReactNode; hint?: ReactNode; assistiveText?: ReactNode; disabled?: boolean; disabledOnlyField?: boolean; bigger?: boolean; dense?: boolean; id?: string; error?: NodeOrBoolean; warning?: NodeOrBoolean; rootClassName?: string; rootStyle?: React.CSSProperties; rootRef?: Ref<HTMLDivElement>; labelContainerClassName?: string; assistContainerClassName?: string; inputContainerClassName?: string; 'data-testid'?: string; } export type InputFieldProps<E extends ElementType> = PolymorphicPropsWithRef<InputFieldOwnProps, E>; export const errorClassName = 'field-two--invalid'; const defaultElement = Input; const InputFieldBase = <E extends ElementType = typeof defaultElement>( { label, hint, assistiveText, rootRef, disabled, disabledOnlyField, bigger, dense: denseProp, error, id: idProp, rootClassName, rootStyle, labelContainerClassName, assistContainerClassName, inputContainerClassName, warning, suffix, as, 'data-testid': dataTestId, ...rest }: InputFieldProps<E>, ref: ForwardedRef<Element> ) => { const [isFocused, setIsFocused] = useState(false); const { dense } = useContext(FormContext) || {}; const id = useInstance(() => idProp || generateUID()); const assistiveUid = useInstance(() => generateUID()); const labelRef = useRef<HTMLLabelElement>(null); const isDense = denseProp || dense; const classes = { root: clsx([ 'field-two-container', isDense && 'field-two--dense', disabled && 'field-two--disabled', disabledOnlyField && 'field-two--disabled-only-field', Boolean(error) && errorClassName, Boolean(warning) && !error && 'field-two--warning', bigger && 'field-two--bigger', rootClassName, ]), labelContainer: clsx([ 'field-two-label-container flex flex-justify-space-between flex-nowrap flex-align-items-end gap-2', labelContainerClassName, ]), inputContainer: clsx(['field-two-input-container relative', inputContainerClassName]), assistContainer: clsx([ 'field-two-assist flex flex-nowrap flex-align-items-start', isDense && 'sr-only', assistContainerClassName, ]), }; const labelElement = label && <span className="field-two-label">{label}</span>; const hintElement = hint && <span className="field-two-hint ml-auto">{hint}</span>; const errorElement = error && typeof error !== 'boolean' && ( <> <Icon name="exclamation-circle-filled" className="flex-item-noshrink mr-1" /> <span data-testid={dataTestId ? `error-${dataTestId}` : undefined}>{error}</span> </> ); const warningElement = warning && typeof warning !== 'boolean' && ( <> <Icon name="exclamation-circle-filled" className="flex-item-noshrink mr-1" /> <span data-testid={dataTestId ? `warning-${dataTestId}` : undefined}>{warning}</span> </> ); const getSuffix = () => { const denseSuffix = (() => { if (isDense && (error || warning)) { const { tooltipType, iconClassName, title } = error ? { tooltipType: 'error' as const, iconClassName: 'color-danger', title: error } : { tooltipType: 'warning' as const, iconClassName: 'color-warning', title: warning }; // Force open it if the condition is true, otherwise leave it as undefined for the default handlers to deal with it const isTooltipOpen = isFocused && !rest.value ? true : undefined; return ( <Tooltip openDelay={0} closeDelay={250} longTapDelay={0} title={title} type={tooltipType} originalPlacement="top-end" isOpen={isTooltipOpen} > <span className="flex flex-item-noshrink p-1"> <Icon name="exclamation-circle-filled" className={iconClassName} /> </span> </Tooltip> ); } })(); if (!denseSuffix && !suffix) { return undefined; } return ( <> {denseSuffix} {suffix} </> ); }; const Element: ElementType = as || defaultElement; // Even if it's undefined we don't want to define the attribute since it will override spreading of rest. const testIdProps = dataTestId ? { 'data-testid': dataTestId, } : undefined; return ( <div className={classes.root} style={rootStyle} onFocus={() => { setIsFocused(true); }} onBlur={() => { setIsFocused(false); }} ref={rootRef} > {label || hint ? ( <label htmlFor={id} className={classes.labelContainer} ref={labelRef}> {labelElement} {hintElement} </label> ) : ( <label htmlFor={id} ref={labelRef} className="hidden" /> )} <div className={classes.inputContainer}> <Element ref={ref} id={id} error={error} disabled={disabled} aria-describedby={assistiveUid} {...rest} {...testIdProps} suffix={getSuffix()} /> </div> <div className={classes.assistContainer} id={assistiveUid} onClick={(e) => { // Ignore if it's empty or if the clicked target is focusable. if ( (e.currentTarget === e.target && e.currentTarget.matches(':empty')) || isFocusable(e.target as Element) ) { return; } // Simulates this div being wrapped in a label. Clicks on the label element to trigger the normal // click handler which the label would trigger. labelRef.current?.click(); }} > {errorElement || warningElement || (!error && !warning && assistiveText)} </div> </div> ); }; /* export because of https://github.com/storybookjs/storybook/issues/9511 https://github.com/styleguidist/react-docgen-typescript/issues/314 https://github.com/styleguidist/react-docgen-typescript/issues/215 */ export const InputField: <E extends ElementType = typeof defaultElement>( props: InputFieldProps<E> ) => ReactElement | null = forwardRef(InputFieldBase); export default InputField;
5,707
0
petrpan-code/ProtonMail/WebClients/packages/components/components/v2
petrpan-code/ProtonMail/WebClients/packages/components/components/v2/input/DateInputTwo.tsx
import { ChangeEvent, FocusEvent, useEffect, useMemo, useState } from 'react'; import { Locale, addDays, format, parse } from 'date-fns'; import { c } from 'ttag'; import { Input, InputProps } from '@proton/atoms'; import { dateLocale } from '@proton/shared/lib/i18n'; import { generateUID } from '../../../helpers'; import { useHotkeys } from '../../../hooks'; import Dropdown from '../../dropdown/Dropdown'; import LocalizedMiniCalendar from '../../miniCalendar/LocalizedMiniCalendar'; import { usePopperAnchor } from '../../popper'; const toFormatted = (value: Date, locale: Locale) => { return format(value, 'PP', { locale }); }; const fromFormatted = (value: string, locale: Locale) => { return parse(value, 'PP', new Date(), { locale }); }; const getTemporaryInputFromValue = (value: Date | undefined) => { return value ? toFormatted(value, dateLocale) : ''; }; const DEFAULT_MIN = new Date(1900, 0, 1); const DEFAULT_MAX = new Date(2200, 0, 1); interface Props extends Omit<InputProps, 'min' | 'max' | 'value' | 'onChange'> { displayWeekNumbers?: boolean; weekStartsOn?: 0 | 2 | 1 | 6 | 5 | 4 | 3; value?: Date; placeholder?: string; defaultDate?: Date; min?: Date; max?: Date; onChange: (value: Date | undefined) => void; // In some cases we want to prevent the 'reset' of the value, if value > max or < min preventValueReset?: boolean; fromFormatter?: (value: string, locale: Locale) => Date; toFormatter?: (value: Date, locale: Locale) => string; hasToday?: boolean; } const DateInputTwo = ({ value, defaultDate, placeholder, autoFocus, onChange, onFocus, onBlur, displayWeekNumbers, weekStartsOn, min = DEFAULT_MIN, max = DEFAULT_MAX, preventValueReset = false, fromFormatter = fromFormatted, toFormatter = toFormatted, hasToday = true, ...rest }: Props) => { const [uid] = useState(generateUID('dropdown')); const { anchorRef, isOpen, open, close } = usePopperAnchor<HTMLInputElement>(); const [temporaryInput, setTemporaryInput] = useState<string>(''); const [showTemporary, setShowTemporary] = useState<boolean>(false); useEffect(() => { setTemporaryInput(getTemporaryInputFromValue(value)); }, [value ? +value : undefined]); const currentInput = useMemo(() => { return value ? toFormatter(value, dateLocale) : ''; }, [value ? +value : undefined]); const temporaryValue = useMemo(() => { if (!temporaryInput) { return; } try { const newDate = fromFormatter(temporaryInput, dateLocale); if (newDate < min || newDate > max) { /* There are some cases where we do not want to reset the value so that we are able to tell the user * he made a mistake, by displaying an error. */ if (preventValueReset) { return newDate; } return; } if (Number.isNaN(+newDate)) { return; } return newDate; // eslint-disable-next-line no-empty } catch (e: any) {} }, [temporaryInput]); const actualDefaultDate = useMemo(() => defaultDate || new Date(), [defaultDate]); const actualValue = temporaryValue || value || actualDefaultDate; const parseAndTriggerChange = () => { const oldTemporaryInput = temporaryInput; // Before the new date is set, the input is reset to the old date in case the onChange handler rejects the change, // or it's an invalid date that couldn't be parsed setTemporaryInput(getTemporaryInputFromValue(value)); // Allow a valid parsed date value, or undefined to reset. if (temporaryValue || !oldTemporaryInput) { onChange(temporaryValue); } }; const handleFocusInput = (event: FocusEvent<HTMLInputElement>) => { onFocus?.(event); open(); setShowTemporary(true); setTemporaryInput(currentInput); }; const handleBlurInput = (event: FocusEvent<HTMLInputElement>) => { onBlur?.(event); parseAndTriggerChange(); close(); setShowTemporary(false); setTemporaryInput(''); }; useHotkeys(anchorRef, [ [ 'Escape', (e) => { if (isOpen) { e.preventDefault(); e.stopPropagation(); parseAndTriggerChange(); close(); } }, ], [ 'Enter', (e) => { parseAndTriggerChange(); if (isOpen) { e.preventDefault(); e.stopPropagation(); close(); } else { e.preventDefault(); e.stopPropagation(); open(); } }, ], [ 'ArrowDown', (e) => { if (isOpen) { e.preventDefault(); e.stopPropagation(); setTemporaryInput(toFormatted(addDays(actualValue, -1), dateLocale)); } }, ], [ 'ArrowUp', (e) => { if (isOpen) { e.preventDefault(); e.stopPropagation(); setTemporaryInput(toFormatted(addDays(actualValue, 1), dateLocale)); } }, ], ]); const handleClickDate = (newDate: Date) => { setTemporaryInput(toFormatted(newDate, dateLocale)); setTimeout(() => anchorRef.current?.blur()); }; const handleInputChange = ({ target: { value } }: ChangeEvent<HTMLInputElement>) => { setTemporaryInput(value); }; const placeholderInLocale = useMemo(() => { return toFormatted(actualDefaultDate, dateLocale); }, [dateLocale, defaultDate]); return ( <> <Input type="text" ref={anchorRef} onFocus={handleFocusInput} onBlur={handleBlurInput} value={showTemporary ? temporaryInput : currentInput} onChange={handleInputChange} placeholder={ placeholder !== undefined ? placeholder : `${c('Placeholder').t`E.g., `}${placeholderInLocale}` } autoFocus={autoFocus} {...rest} /> <Dropdown disableFocusTrap autoClose={false} autoCloseOutside={false} id={uid} isOpen={isOpen} anchorRef={anchorRef} onClose={close} disableDefaultArrowNavigation > <LocalizedMiniCalendar date={actualValue} min={min} max={max} onSelectDate={handleClickDate} displayWeekNumbers={displayWeekNumbers} weekStartsOn={weekStartsOn} fixedSize hasToday={hasToday} preventLeaveFocus /> </Dropdown> </> ); }; export default DateInputTwo;
5,708
0
petrpan-code/ProtonMail/WebClients/packages/components/components/v2
petrpan-code/ProtonMail/WebClients/packages/components/components/v2/input/PasswordInput.tsx
import { Ref, forwardRef, useState } from 'react'; import { c } from 'ttag'; import { Button, Input, InputProps } from '@proton/atoms'; import Icon from '../../icon/Icon'; type PasswordType = 'password' | 'text'; interface Props extends Omit<InputProps, 'type'> { defaultType?: PasswordType; } const PasswordInputTwoBase = ( { disabled, suffix, defaultType = 'password', ...rest }: Props, ref: Ref<HTMLInputElement> ) => { const [type, setType] = useState<PasswordType>(defaultType); const toggle = () => { setType(type === 'password' ? 'text' : 'password'); }; return ( <Input autoComplete="off" autoCapitalize="off" autoCorrect="off" spellCheck="false" {...rest} ref={ref} type={type} disabled={disabled} suffix={ <> {suffix} <Button title={type === 'password' ? c('Label').t`Reveal password` : c('Label').t`Hide password`} className="inline-flex flex-item-noshrink" tabIndex={-1} disabled={disabled} onClick={toggle} shape="ghost" size="small" icon > <Icon className="m-auto" name={type === 'password' ? 'eye' : 'eye-slash'} /> </Button> </> } /> ); }; const PasswordInputTwo = forwardRef(PasswordInputTwoBase); export default PasswordInputTwo;
5,709
0
petrpan-code/ProtonMail/WebClients/packages/components/components/v2
petrpan-code/ProtonMail/WebClients/packages/components/components/v2/input/TextArea.tsx
import { ComponentPropsWithRef, ReactNode, Ref, forwardRef, useEffect, useRef } from 'react'; import { useCombinedRefs } from '@proton/hooks'; import clsx from '@proton/utils/clsx'; import useAutoGrow from '../../../hooks/useAutoGrow'; export interface TextAreaTwoProps extends Omit<ComponentPropsWithRef<'textarea'>, 'prefix'> { error?: ReactNode | boolean; disableChange?: boolean; rows?: number; minRows?: number; autoGrow?: boolean; unstyled?: boolean; onValue?: (value: string) => void; } const TextAreaTwo = (props: TextAreaTwoProps, ref: Ref<HTMLTextAreaElement>) => { const textAreaRef = useRef<HTMLTextAreaElement>(null); const { error, className: classNameProp, onValue, disableChange, rows: maxRows = 5, minRows = 1, autoGrow = false, unstyled, ...rest } = props; const className = clsx([ classNameProp, 'w-full textarea', Boolean(unstyled) && 'unstyled', Boolean(error) && 'error', ]); const { rows, updateTextArea } = useAutoGrow({ maxRows, minRows, autoGrow }); useEffect(() => { if (textAreaRef.current) { updateTextArea?.(textAreaRef.current); } }, [updateTextArea]); return ( <textarea aria-invalid={!!error} {...rest} ref={useCombinedRefs(textAreaRef, ref)} onChange={(e) => { if (disableChange) { return; } onValue?.(e.target.value); rest.onChange?.(e); updateTextArea?.(textAreaRef.current); }} rows={rows} className={className} /> ); }; export default forwardRef<HTMLTextAreaElement, TextAreaTwoProps>(TextAreaTwo);
5,710
0
petrpan-code/ProtonMail/WebClients/packages/components/components/v2
petrpan-code/ProtonMail/WebClients/packages/components/components/v2/input/TotpInput.test.tsx
import { useRef, useState } from 'react'; import { fireEvent, render } from '@testing-library/react'; import TotpInput from './TotpInput'; const EMPTY = ' '; const expectValues = (value: string, inputNodes: NodeListOf<HTMLInputElement>) => { value.split('').forEach((value, i) => { expect(inputNodes[i].value).toBe(value.replace(EMPTY, '')); }); }; describe('TotpInput component', () => { it('should display 6 inputs with a totp code', () => { const { container } = render(<TotpInput value="123456" onValue={() => {}} length={6} />); const inputNodes = container.querySelectorAll('input'); expect(inputNodes.length).toBe(6); expectValues('123456', inputNodes); }); it('should display 4 inputs with a partial totp code with invalid values', () => { const { container } = render(<TotpInput value="a12b" onValue={() => {}} length={4} />); const inputNodes = container.querySelectorAll('input'); expect(inputNodes.length).toBe(4); expectValues(' 12 ', inputNodes); }); it('should display 4 inputs with a partial totp code', () => { const { container } = render(<TotpInput value="12" onValue={() => {}} length={4} />); const inputNodes = container.querySelectorAll('input'); expect(inputNodes.length).toBe(4); expectValues('12 ', inputNodes); }); it('should display 3 inputs with partial alphabet value', () => { const { container } = render(<TotpInput value="1a" onValue={() => {}} length={3} type="alphabet" />); const inputNodes = container.querySelectorAll('input'); expect(inputNodes.length).toBe(3); expectValues('1a ', inputNodes); }); it('should not move focus when entering an invalid value', () => { const Test = () => { const [value, setValue] = useState('1'); return <TotpInput value={value} onValue={setValue} length={4} />; }; const { container } = render(<Test />); const inputNodes = container.querySelectorAll('input'); inputNodes[0].focus(); fireEvent.change(inputNodes[0], { target: { value: 'a' } }); expectValues('1 ', inputNodes); expect(inputNodes[0]).toHaveFocus(); fireEvent.change(inputNodes[0], { target: { value: '' } }); expectValues(' ', inputNodes); expect(inputNodes[0]).toHaveFocus(); fireEvent.change(inputNodes[0], { target: { value: 'a' } }); expectValues(' ', inputNodes); expect(inputNodes[0]).toHaveFocus(); }); it('should move focus to the next input when entering a value in the 1st input', () => { const Test = () => { const [value, setValue] = useState(''); return <TotpInput value={value} onValue={setValue} length={4} />; }; const { container } = render(<Test />); const inputNodes = container.querySelectorAll('input'); fireEvent.change(inputNodes[0], { target: { value: '1' } }); expectValues('1 ', inputNodes); expect(inputNodes[1]).toHaveFocus(); }); it('should move focus to the next input when entering a value in the 2nd input', () => { const Test = () => { const [value, setValue] = useState(''); return <TotpInput value={value} onValue={setValue} length={4} />; }; const { container } = render(<Test />); const inputNodes = container.querySelectorAll('input'); fireEvent.change(inputNodes[1], { target: { value: '1' } }); expectValues(' 1 ', inputNodes); expect(inputNodes[2]).toHaveFocus(); }); it('should move focus to the previous input when removing a value', () => { const Test = () => { const [value, setValue] = useState('123'); return <TotpInput value={value} onValue={setValue} length={4} />; }; const { container } = render(<Test />); const inputNodes = container.querySelectorAll('input'); expectValues('123 ', inputNodes); expect(inputNodes[1].value).toBe('2'); inputNodes[1].focus(); fireEvent.change(inputNodes[1], { target: { value: '' } }); expectValues('1 3 ', inputNodes); expect(inputNodes[1]).toHaveFocus(); fireEvent.keyDown(inputNodes[1], { key: 'Backspace' }); expectValues(' 3 ', inputNodes); expect(inputNodes[0]).toHaveFocus(); }); it('should remove the previous value when hitting backspace on left-most selection', () => { const Test = () => { const [value, setValue] = useState('123'); return <TotpInput value={value} onValue={setValue} length={4} />; }; const { container } = render(<Test />); const inputNodes = container.querySelectorAll('input'); inputNodes[1].selectionStart = 0; inputNodes[1].selectionEnd = 0; expectValues('123', inputNodes); fireEvent.keyDown(inputNodes[1], { key: 'Backspace' }); expectValues(' 23', inputNodes); expect(inputNodes[1].value).toBe('2'); expect(inputNodes[0].value).toBe(''); expect(inputNodes[0]).toHaveFocus(); }); it('should go to the next input when entering the same value', () => { const Test = () => { const [value, setValue] = useState('123'); return <TotpInput value={value} onValue={setValue} length={4} />; }; const { container } = render(<Test />); const inputNodes = container.querySelectorAll('input'); fireEvent.input(inputNodes[1], { target: { value: '2' } }); expectValues('123', inputNodes); expect(inputNodes[2]).toHaveFocus(); }); it('should move focus when pasting', () => { const Test = () => { const [value, setValue] = useState(''); return <TotpInput autoFocus value={value} onValue={setValue} length={4} />; }; const { container } = render(<Test />); const inputNodes = container.querySelectorAll('input'); expect(inputNodes[0]).toHaveFocus(); fireEvent.paste(inputNodes[0], { clipboardData: { getData: () => '32' } }); expect(inputNodes[2]).toHaveFocus(); expectValues('32 ', inputNodes); fireEvent.paste(inputNodes[1], { clipboardData: { getData: () => '32' } }); expect(inputNodes[3]).toHaveFocus(); expectValues('332 ', inputNodes); fireEvent.paste(inputNodes[0], { clipboardData: { getData: () => '7654321' } }); expect(inputNodes[3]).toHaveFocus(); expectValues('7654', inputNodes); }); it('should accept all values when pasting or changing multiple values', () => { const Test = () => { const [value, setValue] = useState('123'); return <TotpInput value={value} onValue={setValue} length={4} />; }; const { container } = render(<Test />); const inputNodes = container.querySelectorAll('input'); expectValues('123 ', inputNodes); fireEvent.paste(inputNodes[0], { clipboardData: { getData: () => '321' } }); expectValues('321 ', inputNodes); expect(inputNodes[3]).toHaveFocus(); fireEvent.paste(inputNodes[1], { clipboardData: { getData: () => '4321' } }); expectValues('3432', inputNodes); expect(inputNodes[3]).toHaveFocus(); fireEvent.change(inputNodes[1], { target: { value: '9876' } }); expectValues('3987', inputNodes); expect(inputNodes[3]).toHaveFocus(); }); describe('Autofocus behaviours', () => { const Test = (options: { autoFocus: boolean; initialValue: string }) => { const focusRef = useRef<HTMLInputElement>(null); const [value, setValue] = useState(options.initialValue); return ( <TotpInput value={value} onValue={setValue} length={4} ref={focusRef} autoFocus={options.autoFocus} /> ); }; it('should not focus inputs if not autofocused & empty value', () => { const { container } = render(<Test autoFocus={false} initialValue="" />); const inputNodes = container.querySelectorAll('input'); inputNodes.forEach((input) => expect(input).not.toHaveFocus()); }); it('should not focus inputs if not autofocused & initial value', () => { const { container } = render(<Test autoFocus={false} initialValue="123" />); const inputNodes = container.querySelectorAll('input'); inputNodes.forEach((input) => expect(input).not.toHaveFocus()); }); it('should focus first input when autofocused & empty value', () => { const { container } = render(<Test autoFocus initialValue="" />); const inputNodes = container.querySelectorAll('input'); expect(inputNodes[0]).toHaveFocus(); }); it('should focus correct input when autofocused & initial value', () => { const { container } = render(<Test autoFocus initialValue="12" />); const inputNodes = container.querySelectorAll('input'); expect(inputNodes[2]).toHaveFocus(); }); it('should focus last input when autofocused & initial value outgrows TOTP length', () => { const { container } = render(<Test autoFocus initialValue="123456789" />); const inputNodes = container.querySelectorAll('input'); expect(inputNodes[3]).toHaveFocus(); }); }); });
5,711
0
petrpan-code/ProtonMail/WebClients/packages/components/components/v2
petrpan-code/ProtonMail/WebClients/packages/components/components/v2/input/TotpInput.tsx
import { ChangeEvent, ForwardRefRenderFunction, Fragment, KeyboardEvent, MutableRefObject, ReactNode, forwardRef, useEffect, useMemo, useRef, } from 'react'; import { c } from 'ttag'; import { Input } from '@proton/atoms'; import useElementRect from '../../../hooks/useElementRect'; const getIsValidValue = (value: string, type: TotpInputProps['type']) => { if (type === 'number') { return /[0-9]/.test(value); } return /[0-9A-Za-z]/.test(value); }; interface TotpInputProps { length: number; value: string; id?: string; error?: ReactNode | boolean; onValue: (value: string) => void; type?: 'number' | 'alphabet'; inputType?: string; disableChange?: boolean; autoFocus?: boolean; autoComplete?: 'one-time-code'; } const size = { padding: 12, fontSize: 24, width: 48, minWidth: 34, height: 56, elementMargin: 12, dividerMargin: 24, }; const ratios = { elementMargin: size.elementMargin / size.width, dividerMargin: size.dividerMargin / size.width, fontSize: size.fontSize / size.width, height: size.height / size.width, }; const space = ' '; const TotpInput: ForwardRefRenderFunction<HTMLInputElement, TotpInputProps> = ( { value = '', length, onValue, id, type = 'number', inputType, disableChange, autoFocus, autoComplete, error, }: TotpInputProps, focusRef ) => { const divRef = useRef<HTMLDivElement>(null); const rect = useElementRect(divRef); const list = useMemo(() => [...Array(length).keys()], [length]); const splitValues = value.split(''); const values = list.map((_, i) => { const value = splitValues[i]?.[0] || space; if (!getIsValidValue(value, type)) { return space; } return value; }); const refArray = useRef<(HTMLInputElement | null)[]>([]); const focus = (i: number) => { const el = refArray.current?.[i]; el?.focus?.(); }; useEffect(() => { if (refArray.current.length !== list.length) { refArray.current = refArray.current.slice(0, list.length); } }, [list.length]); const handleMultipleValues = (multipleValues: string, i: number) => { const result = multipleValues .slice(0, list.length - i) .split('') .filter((pastedValue) => { const value = pastedValue[0]; return getIsValidValue(value, type); }); if (!result.length) { return; } const newValues = [...values]; newValues.splice(i, result.length, ...result); focus(Math.min(i + result.length, length - 1)); onValue(newValues.join('')); }; const centerIndex = Math.round(list.length / 2); const focusIndex = Math.min(value.trim().length, length - 1); const maxInputWidth = Math.floor(Math.max((rect?.width || 0) / length, size.minWidth)); const marginWidth = Math.floor(maxInputWidth * ratios.elementMargin); const dividerWidth = Math.floor(maxInputWidth * ratios.dividerMargin); const numberOfInputsWithMargin = (length - 2) / length; const marginWidthPerInput = Math.floor(marginWidth * numberOfInputsWithMargin); const dividerWidthPerInput = Math.floor(dividerWidth / length); const inputWidth = maxInputWidth - marginWidthPerInput - dividerWidthPerInput; const inputHeight = Math.floor(inputWidth * ratios.height); const fontSize = Math.floor(inputWidth * ratios.fontSize); // Force LTR because it's recommended to enter digits in this order return ( <div className="flex flex-nowrap" dir="ltr" ref={divRef}> {list.map((_, i) => { const value = values[i].trim(); const isValidValue = getIsValidValue(value, type); const digit = i + 1; return ( // eslint-disable-next-line react/no-array-index-key <Fragment key={i}> {i === centerIndex && ( <div style={{ minWidth: `${dividerWidth}px`, width: `${dividerWidth}px`, }} /> )} <Input autoFocus={i === focusIndex ? autoFocus : undefined} id={(() => { if (!id) { return; } if (i === 0) { return id; } return `${id}-${i}`; })()} containerProps={{ style: { width: `${inputWidth}px`, minWidth: `${inputWidth}px`, height: `${inputHeight}px`, fontSize: `${fontSize}px`, ...(i !== length - 1 && i !== centerIndex - 1 ? { marginRight: `${marginWidth}px` } : undefined), }, }} type={inputType ?? (type === 'number' ? 'tel' : 'text')} inputMode={type === 'number' ? 'numeric' : undefined} inputClassName="text-center p-0 flex-item-noshrink" error={error} aria-label={c('Info').t`Enter verification code. Digit ${digit}.`} autoComplete={i === 0 ? autoComplete : undefined} autoCapitalize="off" autoCorrect="off" spellCheck="false" ref={(ref) => { refArray.current[i] = ref; if (focusRef && focusIndex === i) { (focusRef as MutableRefObject<HTMLInputElement | null>).current = ref; } }} value={value} onFocus={(event) => { event.currentTarget.select(); }} onPaste={(event) => { handleMultipleValues(event.clipboardData?.getData('text/plain') || '', i); event.preventDefault(); }} onKeyDown={(event: KeyboardEvent<HTMLInputElement>) => { switch (event.key) { case 'ArrowLeft': event.preventDefault(); focus(i - 1); break; case 'ArrowRight': event.preventDefault(); focus(i + 1); break; case 'Backspace': if (disableChange) { return; } // onChange doesn't trigger on empty values, or when backspacing the left-most selection const targetIndex = i - 1; if ( targetIndex >= 0 && (event.currentTarget.selectionStart !== 0 || event.currentTarget.selectionEnd !== 0) ) { return; } event.preventDefault(); const newValues = [...values]; newValues[targetIndex] = space; focus(targetIndex); onValue(newValues.join('')); break; } }} onInput={(event: ChangeEvent<HTMLInputElement>) => { if (disableChange) { return; } // onChange won't trigger if the values are the same if (event.target.value === value) { focus(i + 1); } }} onChange={(event) => { if (disableChange) { return; } if (event.target.value.length > 1) { handleMultipleValues(event.target.value, i); return; } const newValue = event.target.value.length === 1 ? event.target.value[0] : space; const isNewValueValid = getIsValidValue(newValue, type); if (!isNewValueValid && newValue !== space) { return; } const removedValidValue = isValidValue && newValue === space; if (removedValidValue || isNewValueValid) { const newValues = [...values]; newValues[i] = newValue; if (isNewValueValid) { focus(i + 1); } onValue(newValues.join('')); } }} /> </Fragment> ); })} </div> ); }; export default forwardRef(TotpInput);
5,712
0
petrpan-code/ProtonMail/WebClients/packages/components/components/v2
petrpan-code/ProtonMail/WebClients/packages/components/components/v2/phone/LazyPhoneInput.tsx
import { Ref, Suspense, forwardRef, lazy } from 'react'; import Loader from '../../loader/Loader'; import { Props as PhoneInputProps, Props } from './PhoneInput'; const PhoneInput = lazy(() => import(/* webpackChunkName: "PhoneInput", webpackPreload: true */ './PhoneInput')); const LazyPhoneInputBase = (props: PhoneInputProps, ref: Ref<HTMLInputElement>) => { return ( <Suspense fallback={<Loader />}> <PhoneInput {...props} ref={ref} /> </Suspense> ); }; const LazyPhoneInput = forwardRef<HTMLInputElement, Props>(LazyPhoneInputBase); export default LazyPhoneInput;
5,713
0
petrpan-code/ProtonMail/WebClients/packages/components/components/v2
petrpan-code/ProtonMail/WebClients/packages/components/components/v2/phone/PhoneCountrySelect.tsx
import { Ref, useRef, useState } from 'react'; import { AutoSizer, CellMeasurer, CellMeasurerCache, List } from 'react-virtualized'; import { c } from 'ttag'; import { Input } from '@proton/atoms'; import { generateUID } from '@proton/components/helpers'; import { normalize } from '@proton/shared/lib/helpers/string'; import { Dropdown, DropdownButton } from '../../dropdown'; import { Icon } from '../../icon'; import CountrySelectRow from './PhoneCountrySelectRow'; import { CountryOptionData } from './helper'; interface Props { options: CountryOptionData[]; value?: CountryOptionData; embedded?: boolean; onChange: (newValue: CountryOptionData) => void; onClosed?: (isFromSelection: boolean) => void; } const cache = new CellMeasurerCache({ defaultHeight: 100, fixedWidth: true, keyMapper: () => 0, }); const CountrySelect = ({ value, options, onChange, embedded, onClosed }: Props) => { const anchorRef = useRef<HTMLButtonElement>(null); const [isOpen, setIsOpen] = useState(false); const [search, setSearch] = useState(''); const normalizedSearch = normalize(search, true); const filteredOptions = options.filter(({ countryName }) => { return normalize(countryName, true).includes(normalizedSearch); }); const selectedIndex = !value ? 0 : filteredOptions.indexOf(value); const pickRef = useRef(false); const handleChange = (value: CountryOptionData) => { onChange(value); setIsOpen(false); pickRef.current = true; }; const uid = generateUID('phone-number-prefix'); return ( <> <span className="sr-only" id={uid}>{c('Info').t`Country code`}</span> <DropdownButton as="button" type="button" isOpen={isOpen} hasCaret onClick={() => { pickRef.current = false; setIsOpen(!isOpen); }} className="unstyled flex-align-self-stretch my-1 pr-2 border-right" ref={anchorRef} caretClassName="my-auto" aria-live="assertive" aria-atomic="true" aria-label={value?.countryName} aria-describedby={uid} > <span className="flex mr-2"> {!value ? ( <Icon name="globe" className="align-middle inline-flex" /> ) : ( <img role="presentation" alt={value.countryName} src={value.countryFlag} width="30" height="30" className="align-middle inline-flex" /> )} </span> <span className="min-w-custom inline-flex" style={{ '--min-w-custom': '3em' }} dir="ltr"> +{value ? value.countryCallingCode : '00'} </span> </DropdownButton> <Dropdown isOpen={isOpen} anchorRef={anchorRef} onClose={() => { pickRef.current = false; setIsOpen(false); }} onClosed={() => { setSearch(''); onClosed?.(pickRef.current); }} offset={4} autoClose={false} noCaret disableDefaultArrowNavigation onKeyDown={(e) => { const { key } = e; switch (key) { case 'Enter': { e.preventDefault(); pickRef.current = true; setIsOpen(false); break; } case 'ArrowUp': { e.preventDefault(); const newIndex = selectedIndex - 1; onChange(filteredOptions[Math.max(newIndex, 0)]); break; } case 'ArrowDown': { e.preventDefault(); const newIndex = selectedIndex + 1; onChange(filteredOptions[Math.min(newIndex, filteredOptions.length - 1)]); break; } default: break; } }} > <form name="search" className="p-4"> <Input id="search-keyword" value={search} onValue={setSearch} autoFocus={!embedded} placeholder="Country" prefix={<Icon name="magnifier" alt={c('Action').t`Search countries`} />} /> </form> <div className="h-custom min-w-custom" style={{ '--h-custom': '20em', '--min-w-custom': '18em' }}> {!filteredOptions.length ? ( <div className="pl-4" role="alert">{c('Info').t`No results found`}</div> ) : ( <AutoSizer> {({ height, width }) => ( <List height={height} width={width} rowHeight={cache.rowHeight} className="unstyled m-0 p-0 scroll-if-needed" scrollToIndex={selectedIndex < 0 ? 0 : selectedIndex} rowCount={filteredOptions.length} rowRenderer={({ index, key, parent, style }) => { return ( <CellMeasurer cache={cache} columnIndex={0} key={key} rowIndex={index} parent={parent} > {({ registerChild }) => ( <CountrySelectRow ref={registerChild as Ref<HTMLDivElement>} data={filteredOptions[index]} value={value} key={key} style={style} onChange={handleChange} /> )} </CellMeasurer> ); }} /> )} </AutoSizer> )} </div> </Dropdown> </> ); }; export default CountrySelect;
5,714
0
petrpan-code/ProtonMail/WebClients/packages/components/components/v2
petrpan-code/ProtonMail/WebClients/packages/components/components/v2/phone/PhoneCountrySelectRow.tsx
import { Ref, forwardRef } from 'react'; import clsx from '@proton/utils/clsx'; import { DropdownMenuButton } from '../../dropdown'; import { CountryOptionData } from './helper'; interface Props { data: CountryOptionData; style: any; value?: CountryOptionData; onChange: (data: CountryOptionData) => void; } const CountrySelectRow = ({ data, style, value, onChange }: Props, ref?: Ref<HTMLDivElement>) => { return ( <div className="dropdown-item" style={style} ref={ref} role="row"> <DropdownMenuButton isSelected={false} className={clsx(['block w-full text-ellipsis text-left outline-none flex', data === value && 'active'])} title={data.countryName} onClick={() => { onChange(data); }} > <img className="flex-item-noshrink" alt="" src={data.countryFlag} width="30" height="20" /> <span className="flex-item-fluid pl-2 text-ellipsis">{data.countryName}</span> <span className="flex-item-noshrink text-bold">+{data.countryCallingCode}</span> </DropdownMenuButton> </div> ); }; export default forwardRef<HTMLDivElement, Props>(CountrySelectRow);
5,715
0
petrpan-code/ProtonMail/WebClients/packages/components/components/v2
petrpan-code/ProtonMail/WebClients/packages/components/components/v2/phone/PhoneInput.test.tsx
import { useState } from 'react'; import { fireEvent, render } from '@testing-library/react'; import PhoneInput from './PhoneInput'; import { getCountryFromNumber, getCursorPosition, getSpecificCountry } from './helper'; const Test = ({ initialValue, defaultCountry }: { initialValue: string; defaultCountry?: string }) => { const [value, setValue] = useState(initialValue); return <PhoneInput defaultCountry={defaultCountry} data-testid="input" value={value} onChange={setValue} />; }; const getCountry = (el: HTMLElement) => { return el.getAttribute('aria-label'); }; jest.mock('./flagSvgs', () => { return { getFlagSvg: () => true, }; }); jest.mock('react-virtualized', () => { const ReactVirtualized = jest.requireActual('react-virtualized'); return { ...ReactVirtualized, // @ts-ignore AutoSizer: ({ children }) => children({ height: 1000, width: 1000 }), }; }); interface TestCommands { input?: string; select?: string; expectation: { value: string; country: string | null }; } const runTest = (testCommands: TestCommands[]) => { const { getByTestId, getByRole, getByPlaceholderText, getByTitle } = render( <Test initialValue="" defaultCountry="US" /> ); const inputEl = getByTestId('input') as HTMLInputElement; const buttonEl = getByRole('button') as HTMLButtonElement; testCommands.forEach(({ input, select, expectation: { value, country } }) => { if (select !== undefined) { fireEvent.click(buttonEl); const searchEl = getByPlaceholderText('Country'); fireEvent.change(searchEl, { target: { value: select } }); const rowEl = getByTitle(select); fireEvent.click(rowEl); } if (input !== undefined) { fireEvent.change(inputEl, { target: { value: input } }); } expect(inputEl.value).toBe(value); expect(getCountry(buttonEl)).toBe(country); }); }; describe('PhoneInput', () => { it('should format input', () => { const spy = jest.fn(); const { getByTestId, getByRole, rerender } = render( <PhoneInput value="+41781234567" data-testid="input" onChange={spy} /> ); const input = getByTestId('input') as HTMLInputElement; const button = getByRole('button') as HTMLButtonElement; expect(input.value).toBe('78 123 45 67'); expect(getCountry(button)).toBe('Switzerland'); rerender(<PhoneInput data-testid="input" value="+410782354666" onChange={spy} />); expect(input.value).toBe('78 235 46 66'); expect(getCountry(button)).toBe('Switzerland'); rerender(<PhoneInput data-testid="input" value="+1613123" onChange={spy} />); expect(input.value).toBe('613 123'); expect(getCountry(button)).toBe('Canada'); rerender(<PhoneInput data-testid="input" value="+1631123" onChange={spy} />); expect(input.value).toBe('631 123'); expect(getCountry(button)).toBe('United States'); }); it('format as user enters text', () => { runTest([ { input: '631', expectation: { value: '631', country: 'United States' } }, { input: '6311', expectation: { value: '631 1', country: 'United States' } }, { input: '631', expectation: { value: '631', country: 'United States' } }, { input: '613', expectation: { value: '613', country: 'Canada' } }, { input: '6131', expectation: { value: '613 1', country: 'Canada' } }, { input: '61', expectation: { value: '61', country: 'Canada' } }, { input: '', expectation: { value: '', country: 'Canada' } }, { input: '6', expectation: { value: '6', country: 'Canada' } }, { input: '63', expectation: { value: '63', country: 'Canada' } }, { input: '631', expectation: { value: '631', country: 'United States' } }, ]); }); it('change country if entering with country calling code', () => { runTest([ { input: '', expectation: { value: '', country: 'United States' } }, { input: '+41', expectation: { value: '+41', country: 'Switzerland' } }, { input: '+417', expectation: { value: '+41 7', country: 'Switzerland' } }, { input: '+41781', expectation: { value: '+41 78 1', country: 'Switzerland' } }, { input: '', expectation: { value: '', country: 'Switzerland' } }, { input: '78', expectation: { value: '78', country: 'Switzerland' } }, { input: '781', expectation: { value: '78 1', country: 'Switzerland' } }, ]); }); it('change country selecting from dropdown', () => { runTest([ { input: '', expectation: { value: '', country: 'United States' } }, { select: 'Canada', expectation: { value: '', country: 'Canada' } }, { input: '6', expectation: { value: '6', country: 'Canada' } }, { input: '61', expectation: { value: '61', country: 'Canada' } }, { input: '613', expectation: { value: '613', country: 'Canada' } }, { select: 'Bahamas', expectation: { value: '', country: 'Bahamas' } }, { input: '6', expectation: { value: '6', country: 'Bahamas' } }, { input: '61', expectation: { value: '61', country: 'Bahamas' } }, { input: '613', expectation: { value: '613', country: 'Canada' } }, { input: '631', expectation: { value: '631', country: 'United States' } }, { select: 'Canada', expectation: { value: '', country: 'Canada' } }, ]); }); it('reset and remember country', () => { runTest([ { input: '', expectation: { value: '', country: 'United States' } }, { input: '+', expectation: { value: '+', country: null } }, { input: '+4', expectation: { value: '+4', country: null } }, { input: '+41', expectation: { value: '+41', country: 'Switzerland' } }, { input: '', expectation: { value: '', country: 'Switzerland' } }, { input: '+', expectation: { value: '+', country: null } }, ]); }); it('should get a country from a number', () => { expect(getCountryFromNumber('+')).toEqual(''); expect(getCountryFromNumber('+1')).toEqual('US'); expect(getCountryFromNumber('+11')).toEqual('US'); expect(getCountryFromNumber('+111')).toEqual('US'); expect(getCountryFromNumber('+12')).toEqual('US'); expect(getCountryFromNumber('3')).toEqual(''); expect(getCountryFromNumber('2')).toEqual(''); expect(getCountryFromNumber('1')).toEqual(''); expect(getCountryFromNumber('+41')).toEqual('CH'); expect(getCountryFromNumber('+411')).toEqual('CH'); expect(getCountryFromNumber('+411')).toEqual('CH'); expect(getCountryFromNumber('+42')).toEqual(''); expect(getCountryFromNumber('+320')).toEqual('BE'); }); it('should get a more specific country from a number', () => { expect(getSpecificCountry('', '1', 'US')).toEqual(['US', 0]); expect(getSpecificCountry('613', '1', 'US')).toEqual(['CA', 3]); expect(getSpecificCountry('631', '1', 'US')).toEqual(['US', 0]); expect(getSpecificCountry('787', '1', 'US')).toEqual(['PR', 3]); expect(getSpecificCountry('7', '7', 'RU')).toEqual(['KZ', 1]); expect(getSpecificCountry('', '7', 'KZ')).toEqual(['KZ', 0]); }); it('should get cursor at position', () => { [ { digit: 1, value: '1', expectation: 1 }, { digit: 2, value: '1', expectation: 1 }, { digit: 0, value: '1----2', expectation: 0 }, { digit: 0, value: '--1--', expectation: 1 }, { digit: 0, value: '--1', expectation: 1 }, { digit: 0, value: '--12', expectation: 1 }, { digit: 0, value: '--1-2-', expectation: 1 }, { digit: 1, value: '--1-2-', expectation: 3 }, { digit: 1, value: '--1----2', expectation: 6 }, { digit: 0, value: '--1----2', expectation: 1 }, ].forEach(({ digit, value, expectation }) => { expect(getCursorPosition(digit, value)).toEqual(expectation); }); }); it('should format input for CH', () => { const { getByTestId } = render(<Test defaultCountry="CH" initialValue="" data-testid="input" />); const input = getByTestId('input') as HTMLInputElement; expect(input.value).toBe(''); fireEvent.change(input, { target: { value: '1' } }); expect(input.value).toBe('1'); }); it('should format input for US', () => { const { getByTestId } = render(<Test defaultCountry="US" initialValue="" data-testid="input" />); const input = getByTestId('input') as HTMLInputElement; expect(input.value).toBe(''); fireEvent.change(input, { target: { value: '1' } }); expect(input.value).toBe('1'); }); });
5,716
0
petrpan-code/ProtonMail/WebClients/packages/components/components/v2
petrpan-code/ProtonMail/WebClients/packages/components/components/v2/phone/PhoneInput.tsx
import { Ref, forwardRef, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'; import { Input, InputProps } from '@proton/atoms'; import useCombinedRefs from '@proton/hooks/useCombinedRefs'; import clsx from '@proton/utils/clsx'; import useRightToLeft from '../../../containers/rightToLeft/useRightToLeft'; import PhoneCountrySelect from './PhoneCountrySelect'; import { getCountries, getCountryFromNumber, getCursorPosition, getExamplePlaceholder, getFormattedValue, getNumberWithCountryCode, getNumberWithoutCountryCode, getSafeCountryCallingCode, getSpecificCountry, getSpecificMaxLength, getTrimmedString, } from './helper'; const usePreviousValue = <T,>(value: T) => { const ref = useRef<T>(); useEffect(() => { ref.current = value; }, [value]); return ref.current; }; export interface Props extends Omit<InputProps, 'type' | 'value' | 'onChange'> { value: string; defaultCountry?: string; embedded?: boolean; onChange: (value: string) => void; } const PhoneInputBase = ( { value: actualValue = '', defaultCountry = 'US', embedded, onChange, onValue, ...rest }: Props, ref: Ref<HTMLInputElement> ) => { const inputRef = useRef<HTMLInputElement>(null); const selectionRef = useRef<number | null>(null); const oldSpecificCountryLengthRef = useRef<number>(0); const [isCountryCallingCodeMode, setIsCountryCallingCodeMode] = useState(false); const [oldCountry, setOldCountry] = useState(defaultCountry); const trimmedValue = getTrimmedString(actualValue); const previousTrimmedValue = usePreviousValue(trimmedValue); const oldCountryCallingCode = getSafeCountryCallingCode(oldCountry); const valueWithCountryCallingCode = getNumberWithCountryCode(trimmedValue, oldCountryCallingCode); const countryCodeFromValue = getCountryFromNumber(valueWithCountryCallingCode); const countryCallingCodeFromValue = getSafeCountryCallingCode(countryCodeFromValue); const valueWithoutCountryCallingCode = getNumberWithoutCountryCode( valueWithCountryCallingCode, countryCallingCodeFromValue ); const [valueCountryCodeSpecific, foundLength] = getSpecificCountry( valueWithoutCountryCallingCode, countryCallingCodeFromValue, oldCountryCallingCode === countryCallingCodeFromValue && valueWithoutCountryCallingCode.length < oldSpecificCountryLengthRef.current ? oldCountry : countryCodeFromValue ); const placeholder = getNumberWithoutCountryCode( getExamplePlaceholder(valueCountryCodeSpecific), countryCallingCodeFromValue ); const formattedValue = getFormattedValue(valueWithCountryCallingCode).trim(); const formattedValueInMode = isCountryCallingCodeMode ? formattedValue : getNumberWithoutCountryCode(formattedValue, countryCallingCodeFromValue); const countryCode = (() => { // 1. Going from '' -> '+' === remove country const isNullToPlus = previousTrimmedValue === '' && trimmedValue === '+'; if (isNullToPlus) { return ''; } // 2. No country and going from '+' -> '' === add back default country const isEmptyCountryToNull = previousTrimmedValue === '+' && trimmedValue === '' && oldCountry === ''; if (isEmptyCountryToNull) { return defaultCountry; } // 3. Guess country from number return valueCountryCodeSpecific || oldCountry; })(); useLayoutEffect(() => { if (trimmedValue === '+') { setOldCountry(''); return; } // Setting from country select if (trimmedValue !== '') { oldSpecificCountryLengthRef.current = foundLength; } setOldCountry(countryCode); }, [countryCode]); useLayoutEffect(() => { const inputEl = inputRef.current; const selection = selectionRef.current; if (!inputEl || selection === null) { return; } const i = getCursorPosition(selection, formattedValueInMode); inputEl.selectionStart = i; inputEl.selectionEnd = i; selectionRef.current = null; }); const countries = useMemo(() => getCountries(), []); const selectedValue = countries.find((data) => data.countryCode === countryCode); const [isRTL] = useRightToLeft(); // we force dir="ltr" in all cases, because otherwise phone number will be displayed // in reverse in RTL languages, which is not recommended return ( <Input {...rest} type="tel" value={formattedValueInMode} ref={useCombinedRefs(inputRef, ref)} placeholder={placeholder} dir="ltr" containerProps={{ dir: 'ltr' }} className={clsx([isRTL ? 'text-right' : null])} prefix={ <PhoneCountrySelect embedded={embedded} value={selectedValue} options={countries} onChange={(newSelectedValue) => { oldSpecificCountryLengthRef.current = getSpecificMaxLength( getSafeCountryCallingCode(newSelectedValue.countryCode), newSelectedValue.countryCode ); setIsCountryCallingCodeMode(false); setOldCountry(newSelectedValue.countryCode); onChange(''); }} onClosed={(isFromSelection) => { if (isFromSelection) { inputRef.current?.focus(); } }} /> } onChange={(event) => { const { target, target: { value: newStringValue }, } = event; selectionRef.current = getTrimmedString(newStringValue.slice(0, target.selectionEnd || 0)).length; const newTrimmedValue = getTrimmedString(newStringValue); setIsCountryCallingCodeMode(newTrimmedValue[0] === '+'); const newValue = !newTrimmedValue.length ? '' : getNumberWithCountryCode(newTrimmedValue, countryCallingCodeFromValue); onChange(newValue); }} /> ); }; const PhoneInput = forwardRef<HTMLInputElement, Props>(PhoneInputBase); export default PhoneInput;
5,717
0
petrpan-code/ProtonMail/WebClients/packages/components/components/v2
petrpan-code/ProtonMail/WebClients/packages/components/components/v2/phone/data.ts
import { c } from 'ttag'; interface LeadingNumbers { countryCode: string; areaCodes: string[]; } export const callingCodeToLeading: { [key: string]: LeadingNumbers[] | undefined } = { '1': [ { countryCode: 'AG', areaCodes: ['268'], }, { countryCode: 'AI', areaCodes: ['264'], }, { countryCode: 'AS', areaCodes: ['684'], }, { countryCode: 'BB', areaCodes: ['246'], }, { countryCode: 'BM', areaCodes: ['441'], }, { countryCode: 'BS', areaCodes: ['242'], }, { countryCode: 'CA', areaCodes: [ '204', '226', '236', '249', '250', '263', '289', '306', '343', '354', '365', '367', '368', '382', '387', '403', '416', '418', '428', '431', '437', '438', '450', '584', '468', '474', '506', '514', '519', '548', '579', '581', '584', '587', '604', '613', '639', '647', '672', '683', '705', '709', '742', '753', '778', '780', '782', '807', '819', '825', '867', '873', '902', '905', ], }, { countryCode: 'DM', areaCodes: ['767'], }, { countryCode: 'DO', areaCodes: ['809', '829', '849'], }, { countryCode: 'GD', areaCodes: ['473'], }, { countryCode: 'GU', areaCodes: ['671'], }, { countryCode: 'JM', areaCodes: ['876', '658'], }, { countryCode: 'KN', areaCodes: ['869'], }, { countryCode: 'KY', areaCodes: ['345'], }, { countryCode: 'LC', areaCodes: ['758'], }, { countryCode: 'MP', areaCodes: ['670'], }, { countryCode: 'MS', areaCodes: ['664'], }, { countryCode: 'PR', areaCodes: ['787', '939'], }, { countryCode: 'SX', areaCodes: ['721'], }, { countryCode: 'TC', areaCodes: ['649'], }, { countryCode: 'TT', areaCodes: ['868'], }, { countryCode: 'VC', areaCodes: ['784'], }, { countryCode: 'VG', areaCodes: ['284'], }, { countryCode: 'VI', areaCodes: ['340'], }, ], '7': [ { countryCode: 'KZ', areaCodes: ['33', '7'], }, ], '39': [ { countryCode: 'VA', areaCodes: ['06698'], }, ], '44': [ { countryCode: 'GG', areaCodes: ['1481', '7781', '7839', '7911'], }, { countryCode: 'IM', areaCodes: ['1624', '74576', '7524', '7924', '7624'], }, { countryCode: 'JE', areaCodes: ['1534', '7509', '7700', '7797', '7829', '7937'], }, ], '47': [ { countryCode: 'SJ', areaCodes: ['79'], }, ], '61': [ { countryCode: 'CC', areaCodes: ['89162'], }, { countryCode: 'CX', areaCodes: ['89164'], }, ], '212': [ { countryCode: 'EH', areaCodes: ['5288', '5289'], }, ], '262': [ { countryCode: 'YT', areaCodes: ['269', '639'], }, ], '358': [ { countryCode: 'AX', areaCodes: ['18'], }, ], '599': [ { countryCode: 'BQ', areaCodes: ['3', '4', '7'], }, ], }; export const getCountryMap = (): { [key: string]: string | undefined } => ({ AB: c('Country name').t`Abkhazia`, AC: c('Country name').t`Ascension Island`, AD: c('Country name').t`Andorra`, AE: c('Country name').t`United Arab Emirates`, AF: c('Country name').t`Afghanistan`, AG: c('Country name').t`Antigua and Barbuda`, AI: c('Country name').t`Anguilla`, AL: c('Country name').t`Albania`, AM: c('Country name').t`Armenia`, AO: c('Country name').t`Angola`, AQ: c('Country name').t`Antarctica`, AR: c('Country name').t`Argentina`, AS: c('Country name').t`American Samoa`, AT: c('Country name').t`Austria`, AU: c('Country name').t`Australia`, AW: c('Country name').t`Aruba`, AX: c('Country name').t`Åland Islands`, AZ: c('Country name').t`Azerbaijan`, BA: c('Country name').t`Bosnia and Herzegovina`, BB: c('Country name').t`Barbados`, BD: c('Country name').t`Bangladesh`, BE: c('Country name').t`Belgium`, BF: c('Country name').t`Burkina Faso`, BG: c('Country name').t`Bulgaria`, BH: c('Country name').t`Bahrain`, BI: c('Country name').t`Burundi`, BJ: c('Country name').t`Benin`, BL: c('Country name').t`Saint Barthélemy`, BM: c('Country name').t`Bermuda`, BN: c('Country name').t`Brunei Darussalam`, BO: c('Country name').t`Bolivia`, BQ: c('Country name').t`Bonaire, Sint Eustatius and Saba`, BR: c('Country name').t`Brazil`, BS: c('Country name').t`Bahamas`, BT: c('Country name').t`Bhutan`, BV: c('Country name').t`Bouvet Island`, BW: c('Country name').t`Botswana`, BY: c('Country name').t`Belarus`, BZ: c('Country name').t`Belize`, CA: c('Country name').t`Canada`, CC: c('Country name').t`Cocos (Keeling) Islands`, CD: c('Country name').t`Congo, Democratic Republic of the`, CF: c('Country name').t`Central African Republic`, CG: c('Country name').t`Congo`, CH: c('Country name').t`Switzerland`, CI: c('Country name').t`Côte d'Ivoire`, CK: c('Country name').t`Cook Islands`, CL: c('Country name').t`Chile`, CM: c('Country name').t`Cameroon`, CN: c('Country name').t`China`, CO: c('Country name').t`Colombia`, CR: c('Country name').t`Costa Rica`, CU: c('Country name').t`Cuba`, CV: c('Country name').t`Cape Verde`, CW: c('Country name').t`Curaçao`, CX: c('Country name').t`Christmas Island`, CY: c('Country name').t`Cyprus`, CZ: c('Country name').t`Czech Republic`, DE: c('Country name').t`Germany`, DJ: c('Country name').t`Djibouti`, DK: c('Country name').t`Denmark`, DM: c('Country name').t`Dominica`, DO: c('Country name').t`Dominican Republic`, DZ: c('Country name').t`Algeria`, EC: c('Country name').t`Ecuador`, EE: c('Country name').t`Estonia`, EG: c('Country name').t`Egypt`, EH: c('Country name').t`Western Sahara`, ER: c('Country name').t`Eritrea`, ES: c('Country name').t`Spain`, ET: c('Country name').t`Ethiopia`, FI: c('Country name').t`Finland`, FJ: c('Country name').t`Fiji`, FK: c('Country name').t`Falkland Islands`, FM: c('Country name').t`Federated States of Micronesia`, FO: c('Country name').t`Faroe Islands`, FR: c('Country name').t`France`, GA: c('Country name').t`Gabon`, GB: c('Country name').t`United Kingdom`, GD: c('Country name').t`Grenada`, GE: c('Country name').t`Georgia`, GF: c('Country name').t`French Guiana`, GG: c('Country name').t`Guernsey`, GH: c('Country name').t`Ghana`, GI: c('Country name').t`Gibraltar`, GL: c('Country name').t`Greenland`, GM: c('Country name').t`Gambia`, GN: c('Country name').t`Guinea`, GP: c('Country name').t`Guadeloupe`, GQ: c('Country name').t`Equatorial Guinea`, GR: c('Country name').t`Greece`, GS: c('Country name').t`South Georgia and the South Sandwich Islands`, GT: c('Country name').t`Guatemala`, GU: c('Country name').t`Guam`, GW: c('Country name').t`Guinea-Bissau`, GY: c('Country name').t`Guyana`, HK: c('Country name').t`Hong Kong`, HM: c('Country name').t`Heard Island and McDonald Islands`, HN: c('Country name').t`Honduras`, HR: c('Country name').t`Croatia`, HT: c('Country name').t`Haiti`, HU: c('Country name').t`Hungary`, ID: c('Country name').t`Indonesia`, IE: c('Country name').t`Ireland`, IL: c('Country name').t`Israel`, IM: c('Country name').t`Isle of Man`, IN: c('Country name').t`India`, IO: c('Country name').t`British Indian Ocean Territory`, IQ: c('Country name').t`Iraq`, IR: c('Country name').t`Iran`, IS: c('Country name').t`Iceland`, IT: c('Country name').t`Italy`, JE: c('Country name').t`Jersey`, JM: c('Country name').t`Jamaica`, JO: c('Country name').t`Jordan`, JP: c('Country name').t`Japan`, KE: c('Country name').t`Kenya`, KG: c('Country name').t`Kyrgyzstan`, KH: c('Country name').t`Cambodia`, KI: c('Country name').t`Kiribati`, KM: c('Country name').t`Comoros`, KN: c('Country name').t`Saint Kitts and Nevis`, KP: c('Country name').t`North Korea`, KR: c('Country name').t`South Korea`, KW: c('Country name').t`Kuwait`, KY: c('Country name').t`Cayman Islands`, KZ: c('Country name').t`Kazakhstan`, LA: c('Country name').t`Laos`, LB: c('Country name').t`Lebanon`, LC: c('Country name').t`Saint Lucia`, LI: c('Country name').t`Liechtenstein`, LK: c('Country name').t`Sri Lanka`, LR: c('Country name').t`Liberia`, LS: c('Country name').t`Lesotho`, LT: c('Country name').t`Lithuania`, LU: c('Country name').t`Luxembourg`, LV: c('Country name').t`Latvia`, LY: c('Country name').t`Libya`, MA: c('Country name').t`Morocco`, MC: c('Country name').t`Monaco`, MD: c('Country name').t`Moldova`, ME: c('Country name').t`Montenegro`, MF: c('Country name').t`Saint Martin (French Part)`, MG: c('Country name').t`Madagascar`, MH: c('Country name').t`Marshall Islands`, MK: c('Country name').t`North Macedonia`, ML: c('Country name').t`Mali`, MM: c('Country name').t`Myanmar`, MN: c('Country name').t`Mongolia`, MO: c('Country name').t`Macao`, MP: c('Country name').t`Northern Mariana Islands`, MQ: c('Country name').t`Martinique`, MR: c('Country name').t`Mauritania`, MS: c('Country name').t`Montserrat`, MT: c('Country name').t`Malta`, MU: c('Country name').t`Mauritius`, MV: c('Country name').t`Maldives`, MW: c('Country name').t`Malawi`, MX: c('Country name').t`Mexico`, MY: c('Country name').t`Malaysia`, MZ: c('Country name').t`Mozambique`, NA: c('Country name').t`Namibia`, NC: c('Country name').t`New Caledonia`, NE: c('Country name').t`Niger`, NF: c('Country name').t`Norfolk Island`, NG: c('Country name').t`Nigeria`, NI: c('Country name').t`Nicaragua`, NL: c('Country name').t`Netherlands`, NO: c('Country name').t`Norway`, NP: c('Country name').t`Nepal`, NR: c('Country name').t`Nauru`, NU: c('Country name').t`Niue`, NZ: c('Country name').t`New Zealand`, OM: c('Country name').t`Oman`, OS: c('Country name').t`South Ossetia`, PA: c('Country name').t`Panama`, PE: c('Country name').t`Peru`, PF: c('Country name').t`French Polynesia`, PG: c('Country name').t`Papua New Guinea`, PH: c('Country name').t`Philippines`, PK: c('Country name').t`Pakistan`, PL: c('Country name').t`Poland`, PM: c('Country name').t`Saint Pierre and Miquelon`, PN: c('Country name').t`Pitcairn`, PR: c('Country name').t`Puerto Rico`, PS: c('Country name').t`Palestine`, PT: c('Country name').t`Portugal`, PW: c('Country name').t`Palau`, PY: c('Country name').t`Paraguay`, QA: c('Country name').t`Qatar`, RE: c('Country name').t`Reunion`, RO: c('Country name').t`Romania`, RS: c('Country name').t`Serbia`, RU: c('Country name').t`Russia`, RW: c('Country name').t`Rwanda`, SA: c('Country name').t`Saudi Arabia`, SB: c('Country name').t`Solomon Islands`, SC: c('Country name').t`Seychelles`, SD: c('Country name').t`Sudan`, SE: c('Country name').t`Sweden`, SG: c('Country name').t`Singapore`, SH: c('Country name').t`Saint Helena`, SI: c('Country name').t`Slovenia`, SJ: c('Country name').t`Svalbard and Jan Mayen`, SK: c('Country name').t`Slovakia`, SL: c('Country name').t`Sierra Leone`, SM: c('Country name').t`San Marino`, SN: c('Country name').t`Senegal`, SO: c('Country name').t`Somalia`, SR: c('Country name').t`Suriname`, SS: c('Country name').t`South Sudan`, ST: c('Country name').t`Sao Tome and Principe`, SV: c('Country name').t`El Salvador`, SX: c('Country name').t`Sint Maarten`, SY: c('Country name').t`Syria`, SZ: c('Country name').t`Eswatini`, TA: c('Country name').t`Tristan da Cunha`, TC: c('Country name').t`Turks and Caicos Islands`, TD: c('Country name').t`Chad`, TF: c('Country name').t`French Southern Territories`, TG: c('Country name').t`Togo`, TH: c('Country name').t`Thailand`, TJ: c('Country name').t`Tajikistan`, TK: c('Country name').t`Tokelau`, TL: c('Country name').t`Timor-Leste`, TM: c('Country name').t`Turkmenistan`, TN: c('Country name').t`Tunisia`, TO: c('Country name').t`Tonga`, TR: c('Country name').t`Turkey`, TT: c('Country name').t`Trinidad and Tobago`, TV: c('Country name').t`Tuvalu`, TW: c('Country name').t`Taiwan`, TZ: c('Country name').t`Tanzania`, UA: c('Country name').t`Ukraine`, UG: c('Country name').t`Uganda`, UM: c('Country name').t`United States Minor Outlying Islands`, US: c('Country name').t`United States`, UY: c('Country name').t`Uruguay`, UZ: c('Country name').t`Uzbekistan`, VA: c('Country name').t`Holy See (Vatican City State)`, VC: c('Country name').t`Saint Vincent and the Grenadines`, VE: c('Country name').t`Venezuela`, VG: c('Country name').t`Virgin Islands, British`, VI: c('Country name').t`Virgin Islands, U.S.`, VN: c('Country name').t`Vietnam`, VU: c('Country name').t`Vanuatu`, WF: c('Country name').t`Wallis and Futuna`, WS: c('Country name').t`Samoa`, XK: c('Country name').t`Kosovo`, YE: c('Country name').t`Yemen`, YT: c('Country name').t`Mayotte`, ZA: c('Country name').t`South Africa`, ZM: c('Country name').t`Zambia`, ZW: c('Country name').t`Zimbabwe`, ZZ: c('Country name').t`International`, });
5,718
0
petrpan-code/ProtonMail/WebClients/packages/components/components/v2
petrpan-code/ProtonMail/WebClients/packages/components/components/v2/phone/flagSvgs.ts
const flags = require.context('@proton/styles/assets/img/flags', true, /.svg$/); const flagsMap = flags.keys().reduce<Partial<{ [key: string]: () => string }>>((acc, key) => { acc[key] = () => flags(key); return acc; }, {}); export const getFlagSvg = (abbreviation: string) => { const key = `./${abbreviation.toUpperCase()}.svg`; if (!flagsMap[key]) { return; } return flagsMap[key]?.(); };
5,719
0
petrpan-code/ProtonMail/WebClients/packages/components/components/v2
petrpan-code/ProtonMail/WebClients/packages/components/components/v2/phone/helper.ts
import examples from 'libphonenumber-js/examples.mobile.json'; import metadata from 'libphonenumber-js/metadata.min.json'; import parsePhoneNumberFromString, { AsYouType, CountryCode, formatIncompletePhoneNumber, getCountryCallingCode, getExampleNumber, } from 'libphonenumber-js/min'; import isTruthy from '@proton/utils/isTruthy'; import { callingCodeToLeading, getCountryMap } from './data'; import { getFlagSvg } from './flagSvgs'; export const getTrimmedString = (string: string) => { // Handle (123) -> (123 const slicedValue = string.match(/\([\d]+$/) ? string.slice(0, -1) : string; // Remove everything except numbers and + const trimmedString = slicedValue.replace(/[^0-9+]+/g, ''); if (!trimmedString.length) { return ''; } // Remove all + in case there are multiple return trimmedString[0] + trimmedString.slice(1).replace(/\+/g, ''); }; export const getSafeCountryCallingCode = (country: string) => { try { return getCountryCallingCode(country as CountryCode) as string; } catch (e: any) { return ''; } }; export const getCountryFromCallingCode = (callingCode: string) => { const countries = metadata.country_calling_codes[callingCode]; if (!countries || countries.length === 0) { return; } if (countries.length === 1) { return countries[0]; } return countries[0]; }; export const getNumberWithCountryCode = (value: string, countryCallingCode: string) => { if (value.includes('+')) { return value; } if (!countryCallingCode) { return value; } return `+${countryCallingCode}${value}`; }; export const getExamplePlaceholder = (country: string) => { const example = getExampleNumber(country as CountryCode, examples); if (!example) { return ''; } return example.formatInternational(); }; export const getNumberWithoutCountryCode = (value: string, countryCallingCode: string) => { return value.replace(`+${countryCallingCode}`, '').trim(); }; export const getCountryFromNumber = (value: string) => { const asYouType = new AsYouType(); asYouType.input(value); const result = asYouType.getNumber(); if (result) { return result.country || getCountryFromCallingCode(result.countryCallingCode as string) || ''; } const country = asYouType.getCountry(); if (country) { return country; } const callingCode = asYouType.getCallingCode(); if (callingCode) { const country = getCountryFromCallingCode(callingCode); if (country) { return country; } } if (!value.length) { return ''; } if (value[0] === '+') { const callingCode = value.slice(1); const country = getCountryFromCallingCode(callingCode); if (country) { return country; } } return ''; }; export interface CountryOptionData { countryCode: string; countryName: string; countryCallingCode: string; countryFlag: string; } export const getCountries = (): CountryOptionData[] => { const countryMap = getCountryMap(); return Object.keys(metadata.countries) .map((countryCode): CountryOptionData | undefined => { const countryCallingCode = getSafeCountryCallingCode(countryCode as CountryCode); const countryName = countryMap[countryCode]; const countryFlag = getFlagSvg(countryCode); if (!countryFlag || !countryName || !countryCallingCode) { return; } return { countryCode, countryName, countryCallingCode, countryFlag, }; }) .filter(isTruthy) .sort((a, b) => a.countryName.localeCompare(b.countryName)); }; export const getCursorPosition = (digitIndex: number, value: string) => { const regex = /[\d+]/; let n = 0; let i = 0; for (; i < value.length; ++i) { if (value[i].match(regex)) { if (n++ >= digitIndex) { break; } } } if (!value[i - 1]?.match(regex)) { i -= 1; } return Math.max(0, Math.min(i, value.length)); }; export const getFormattedValue = (number: string) => { const result = parsePhoneNumberFromString(number); if (result && result.isValid()) { return result.formatInternational(); } return formatIncompletePhoneNumber(number); }; export const getSpecificCountry = ( value: string, countryCallingCode: string, countryCode: string ): [string, number] => { const leadings = callingCodeToLeading[countryCallingCode]; if (!leadings) { return [countryCode, 0]; } return leadings.reduce( (acc, { countryCode, areaCodes }) => { const result = areaCodes.find((areaCode) => value.startsWith(areaCode)); if (result && result.length >= acc[1]) { return [countryCode, result.length]; } return acc; }, [countryCode, 0] ); }; export const getSpecificMaxLength = (countryCallingCode: string, countryCode: string) => { const leadings = callingCodeToLeading[countryCallingCode] || []; const areaCodes = leadings.find((leading) => { return countryCode === leading.countryCode; })?.areaCodes || []; return areaCodes.reduce((acc, cur) => { return Math.max(acc, cur.length); }, 0); };
5,720
0
petrpan-code/ProtonMail/WebClients/packages/components/components
petrpan-code/ProtonMail/WebClients/packages/components/components/version/AppVersion.tsx
import { c } from 'ttag'; import { APPS_CONFIGURATION } from '@proton/shared/lib/constants'; import { getAppVersion } from '../../helpers'; import { useConfig, useEarlyAccess } from '../../hooks'; import { useModalState } from '../modalTwo'; import { Tooltip } from '../tooltip'; import ChangelogModal from './ChangelogModal'; interface Props { appName?: string; appVersion?: string; changelog?: string; } const envMap = { alpha: 'α', beta: 'β', relaunch: 'δ', }; const AppVersion = ({ appVersion: maybeAppVersion, appName: maybeAppName, changelog }: Props) => { const { APP_NAME, APP_VERSION, DATE_VERSION } = useConfig(); const { currentEnvironment } = useEarlyAccess(); const [changelogModal, setChangelogModalOpen, render] = useModalState(); const appName = maybeAppName || APPS_CONFIGURATION[APP_NAME]?.name; const appVersion = getAppVersion(maybeAppVersion || APP_VERSION); const className = 'app-infos-version text-xs m-0'; const title = DATE_VERSION; const children = ( <> <span className="app-infos-name mr-1">{appName}</span> <span className="app-infos-number" data-testid="app-infos:release-notes"> {appVersion} {currentEnvironment && envMap[currentEnvironment] && ` ${envMap[currentEnvironment]}`} </span> </> ); if (!changelog) { return ( <span title={title} className={className}> {children} </span> ); } return ( <> {render && <ChangelogModal {...changelogModal} changelog={changelog} />} <Tooltip title={c('Storage').t`Release notes`}> <button type="button" data-testid="app-infos:release-notes-button" onClick={() => setChangelogModalOpen(true)} title={title} className={className} > {children} </button> </Tooltip> </> ); }; export default AppVersion;
5,721
0
petrpan-code/ProtonMail/WebClients/packages/components/components
petrpan-code/ProtonMail/WebClients/packages/components/components/version/ChangeLogModal.scss
@import '~@proton/styles/scss/lib'; .modal-content-inner-changelog { h1 { font-size: em(map-get($title-sizes, 'h2')); } h2, h3 { margin-block-end: 0.5em; font-size: em(map-get($title-sizes, 'h4')); } ul { margin-block-start: 0.5em; } }
5,722
0
petrpan-code/ProtonMail/WebClients/packages/components/components
petrpan-code/ProtonMail/WebClients/packages/components/components/version/ChangelogModal.tsx
import { useState } from 'react'; import markdownit from 'markdown-it'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { getAppVersion } from '../../helpers'; import { ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, ModalProps, } from '../modalTwo'; import './ChangeLogModal.scss'; const md = markdownit('default', { breaks: true, linkify: true, }); const defaultRender = md.renderer.rules.link_open || function render(tokens, idx, options, env, self) { return self.renderToken(tokens, idx, options); }; md.renderer.rules.link_open = (tokens, idx, options, env, self) => { tokens[idx].attrPush(['target', '_blank']); return defaultRender(tokens, idx, options, env, self); }; interface Props extends ModalProps { changelog?: string; } const ChangelogModal = ({ changelog = '', ...rest }: Props) => { const [html] = useState(() => { const modifiedChangelog = changelog.replace(/\[(\d+\.\d+\.\d+[^\]]*)]/g, (match, capture) => { return `[${getAppVersion(capture)}]`; }); return { __html: md.render(modifiedChangelog), }; }); return ( <Modal size="large" data-testid="changelog-modal" {...rest}> <ModalHeader title={c('Title').t`What's new`} /> <ModalContent> <div className="modal-content-inner-changelog" dangerouslySetInnerHTML={html} dir="ltr" lang="en" /> </ModalContent> <ModalFooter> <Button data-testid="changelog-modal:close" onClick={rest.onClose}>{c('Action').t`Close`}</Button> </ModalFooter> </Modal> ); }; export default ChangelogModal;
5,723
0
petrpan-code/ProtonMail/WebClients/packages/components/components
petrpan-code/ProtonMail/WebClients/packages/components/components/version/index.ts
export { default as AppVersion } from './AppVersion'; export { default as ChangelogModal } from './ChangelogModal';
5,724
0
petrpan-code/ProtonMail/WebClients/packages/components/components
petrpan-code/ProtonMail/WebClients/packages/components/components/videoInstructions/VideoInstructions.scss
.video-player-replay-button { background: var(--backdrop-norm); opacity: 0; transition: opacity 0.6s ease; appearance: none; pointer-events: none; &.video-ended { opacity: 1; pointer-events: auto; } }
5,725
0
petrpan-code/ProtonMail/WebClients/packages/components/components
petrpan-code/ProtonMail/WebClients/packages/components/components/videoInstructions/VideoInstructions.tsx
import { useRef, useState } from 'react'; import { c } from 'ttag'; import clsx from '@proton/utils/clsx'; import { Icon } from '../icon'; import './VideoInstructions.scss'; export interface VideoSource { format: string; src: string; } const VideoInstructions = ({ children, ...rest }: React.ComponentPropsWithoutRef<'video'>) => { const [videoEnded, setVideoEnded] = useState(false); const videoRef = useRef<HTMLVideoElement>(null); const onEnd = () => { setVideoEnded(true); }; const replayVideo = () => { setVideoEnded(false); videoRef.current?.play(); }; return ( <div className="text-center mb-4 relative"> <video preload="auto" playsInline ref={videoRef} className="max-w-full rounded" autoPlay muted onEnded={onEnd} {...rest} > {children} </video> <button title={c('Video control').t`Click to replay the video`} type="button" className={clsx([ 'absolute-cover rounded w-full flex flex-align-items-center flex-justify-center', 'video-player-replay-button', videoEnded && 'video-ended', ])} onClick={replayVideo} > <Icon name="arrow-rotate-right" size={56} color="white" alt={c('Video control').t`Replay video`} /> </button> </div> ); }; export default VideoInstructions;
5,726
0
petrpan-code/ProtonMail/WebClients/packages/components/components
petrpan-code/ProtonMail/WebClients/packages/components/components/videoInstructions/index.ts
export { default as VideoInstructions } from './VideoInstructions';
5,727
0
petrpan-code/ProtonMail/WebClients/packages/components/components
petrpan-code/ProtonMail/WebClients/packages/components/components/wizard/Wizard.tsx
import clsx from '@proton/utils/clsx'; import Icon from '../icon/Icon'; interface Props { // current step step: number; // steps steps: string[]; // hide text for steps hideText?: boolean; } const Wizard = ({ step = 0, steps = [], hideText = false }: Props) => { return ( <div className={clsx([ 'wizard-container relative pt-0 pb-4 mb-4', hideText && 'wizard-container--no-text-displayed', ])} > <ul className="wizard mt-0 unstyled flex flex-nowrap flex-justify-space-between"> {steps.map((text = '', index) => { return ( <li key={index.toString()} className={clsx(['wizard-item', index < step && 'is-complete'])} aria-current={index === step ? 'step' : undefined} title={text} > <span className="wizard-marker flex"> {index < step && ( <Icon name="checkmark" size={12} className="upper-layer m-auto wizard-marker-icon" /> )} </span> </li> ); })} </ul> {hideText === false && ( <ul className="unstyled flex flex-nowrap m-0"> {steps.map((text = '', index) => { return ( <li key={`wizard-label-${index.toString()}`} className={clsx(['wizard-label', index < step && 'is-complete'])} aria-current={index === step ? 'step' : undefined} > <span>{text}</span> </li> ); })} </ul> )} </div> ); }; export default Wizard;
5,728
0
petrpan-code/ProtonMail/WebClients/packages/components/components
petrpan-code/ProtonMail/WebClients/packages/components/components/wizard/index.ts
export { default as Wizards } from './Wizard';
5,729
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/containers/index.ts
export * from './account'; export * from './addresses'; export * from './api'; export * from './app'; export * from './authentication'; export * from './autoReply'; export * from './banner'; export * from './bridge'; export * from './cache'; export * from './calendar'; export * from './challenge'; export * from './compatibilityCheck'; export * from './config'; export * from './contacts'; export * from './domains'; export * from './drawer'; export * from './drive'; export * from './emailPrivacy'; export * from './error'; export * from './eventManager'; export * from './experiments'; export * from './features'; export * from './feedback'; export * from './filePreview'; export * from './filters'; export * from './general'; export * from './gmailSyncModal'; export * from './heading'; export * from './illustration'; export * from './importExportApp'; export * from './invoices'; export * from './items'; export * from './keyTransparency'; export * from './keys'; export * from './labels'; export * from './layout'; export * from './layouts'; export * from './login'; export * from './logs'; export * from './mail'; export * from './members'; export * from './messages'; export * from './mnemonic'; export * from './modals'; export * from './notification'; export * from './notifications'; export * from './offers'; export * from './onboarding'; export * from './organization'; export * from './otherMailPreferences'; export * from './overview'; export * from './password'; export * from './paymentMethods'; export * from './payments'; export * from './privacy'; export * from './recovery'; export * from './referral'; export * from './rightToLeft'; export * from './security'; export * from './sentinel'; export * from './sessions'; export * from './smtp'; export * from './support'; export * from './themes'; export * from './topBanners'; export * from './verification'; export * from './vpn'; export * from './unleash';
5,730
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/AccessibilitySection.tsx
import { c } from 'ttag'; import { BRAND_NAME } from '@proton/shared/lib/constants'; import { MotionModeSetting, ThemeFeatureSetting, ThemeFontFaceSetting, ThemeFontSizeSettingMap, getThemeFontFaceEntries, getThemeFontSizeEntries, } from '@proton/shared/lib/themes/themes'; import clsx from '@proton/utils/clsx'; import { Info, Option, SelectTwo, Toggle, Tooltip, useNotifications } from '../..'; import { useTheme } from '../themes/ThemeProvider'; import { SettingsLayout, SettingsLayoutLeft, SettingsLayoutRight, SettingsParagraph, SettingsSection } from './index'; const themeFontFaceEntries = getThemeFontFaceEntries(); const themeFontSizeEntries = getThemeFontSizeEntries(); const AccessibilitySection = () => { const { information, settings, setFeature, setFontSize, setFontFace } = useTheme(); const { createNotification } = useNotifications(); const notifyPreferenceSaved = () => createNotification({ text: c('Success').t`Preference saved` }); const reduceMotion = information.motionMode === MotionModeSetting.Reduce; return ( <SettingsSection> <SettingsParagraph>{c('Info') .t`Improve your ${BRAND_NAME} experience by adapting the application to your needs.`}</SettingsParagraph> <SettingsLayout> <SettingsLayoutLeft> <label htmlFor="fontFaceSelect" className="text-semibold"> {c('Label').t`Font family`} </label> </SettingsLayoutLeft> <SettingsLayoutRight> <SelectTwo id="fontFaceSelect" value={settings.FontFace} onValue={(value) => { setFontFace(value); notifyPreferenceSaved(); }} > {themeFontFaceEntries.map(([id, { label: getLabel, value }]) => { const label = getLabel(); if (id === ThemeFontFaceSetting.DYSLEXIC) { return ( <Option key={id} title={label} value={id}> <svg className="inline-block h-custom fill-currentcolor align-middle" style={{ '--h-custom': '1em' }} viewBox="0 0 122.33 15.55" > <path d="M0 6c0-4.12 2.1-6 5.35-6s5.44 1.71 5.34 6c-.1 4.1-1.32 6.16-5.34 6.14C1.67 12.11 0 10.11 0 6Zm9.03.15c0-2.41-1.41-4.87-3.68-4.87s-3.7 2.46-3.7 4.87 1.43 3.03 3.7 3.03 3.68-.64 3.68-3.03Zm7.84 8.64-1.81.11 1.12-6.29-.22-4.13h1.26l.25 1.05a2.54 2.54 0 0 1 2.45-1.34c1.86.06 3.14 1.47 3.14 3.78s-.92 4.17-3.14 4.17c-1.12 0-2.07-.45-2.45-1.36l-.6 4.01Zm3.24-9.48c-1.16 0-2.27.91-2.27 2.4s1.01 2.35 2.34 2.35 1.71-.87 1.65-2.35c-.06-1.48-.56-2.4-1.72-2.4Zm7.67 2.6c0 1.33.91 2.14 2.89 2.35 1.04.11 1.7 0 2.77-.46v1.74c-.91.39-1.82.59-2.82.59-2.44 0-4.12-1.53-4.12-3.95.1-2.51 1.6-4.37 3.91-4.37 1.57.13 2.98 1.18 3.43 3.71l-6.06.39Zm4.66-1.51c-.14-.85-.57-1.75-2.03-1.65-1.43.1-2.45 1.16-2.45 2.09l4.48-.43Zm11.69 5.53h-1.95l.15-4.61c.04-1.36-.38-2-1.5-2-1.54 0-2.02 1.09-1.96 2.35l.2 4.26H37l.56-7.65h.92l.24.62c.66-.31 1.19-.77 2.25-.77 1.75 0 2.7 1.26 2.84 3.28l.31 4.52ZM49.07.04h3.22c4.47 0 6.23 3.08 6.63 6.01.69 4.96-3.28 5.88-6.63 5.88h-3.22V.04Zm3.53 8.88c3.99 0 4.58-1.12 4.27-3.21-.25-1.78-1.09-3.78-4.27-3.78h-1.88v6.99h1.88Zm11.48 4.82h.88c1.08 0 2.87-1.11 2.17-2.55l-3.47-7.1h1.33l3.14 5.34 1.64-5.34h1.34l-1.95 8.32c-.52 2.23-2.82 3.14-3.94 3.14h-1.15v-1.81Zm14.85-8.66c-.87-.11-1.19-.08-1.68-.11-1.81 0-2.03.52-2.02 1.15.01.45.94.87 2.16 1.25 2.31.71 2.72 1.3 2.72 2.4 0 1.93-1.08 2.37-3.19 2.37-2.56 0-2.73-.42-3.35-.88l1.37-1.55c.81.31 1.15.39 2 .46.49.04 1.41.1 1.41-.7 0-.45-.85-.73-1.83-.92-.63-.1-2.34-.52-2.34-2.35 0-1.02.49-2.27 2.91-2.27.94 0 1.78.18 2.48.34l-.64.84ZM84.2.95h1.19a57.03 57.03 0 0 0-.45 9.43h1.67l.22 1.55h-3.22c-.17-1.55.01-7.09.59-10.98Zm6.65 6.96c0 1.33.91 2.14 2.89 2.35 1.04.11 1.7 0 2.77-.46v1.74c-.91.39-1.82.59-2.82.59-2.44 0-4.12-1.53-4.12-3.95.1-2.51 1.6-4.37 3.91-4.37 1.57.13 2.98 1.18 3.43 3.71l-6.06.39Zm4.66-1.51c-.14-.85-.57-1.75-2.03-1.65-1.43.1-2.45 1.16-2.45 2.09l4.48-.43Zm10.23 5.53-1.86-2.89-2.14 2.89h-2.09l3.38-4.19-2.37-3.66h1.62l1.74 2.45 1.97-2.45h1.55l-2.69 3.63 2.98 4.22h-2.1Zm5.8-7.71h1.12c-.1 2.31-.1 5.03.32 7.72h-1.85c.18-2.69.41-4.61.41-7.72Zm.15-2.93h.84l.21 1.6h-1.26l.21-1.6Zm9.58 4.1a5.66 5.66 0 0 0-1.47-.21c-1.36.01-2.23.84-2.23 2.93a2.41 2.41 0 0 0 3.45 2.06l1.32 1.43c-.66.39-1.54.49-2.4.43-2.9-.2-3.78-1.46-3.78-3.92 0-2.77.99-4.03 3.36-4.09a6.9 6.9 0 0 1 1.75.17v1.2Z" /> </svg> <span className="sr-only">{label}</span> </Option> ); } return ( <Option key={id} title={label} value={id} className={clsx(!value && 'apply-font')} style={value ? { fontFamily: value } : { '--setting-font-family': 'initial' }} /> ); })} </SelectTwo> </SettingsLayoutRight> </SettingsLayout> <SettingsLayout> <SettingsLayoutLeft> <label htmlFor="fontSizeSelect" className="text-semibold"> {c('Label').t`Font size`} </label> </SettingsLayoutLeft> <SettingsLayoutRight> <SelectTwo id="fontSizeSelect" value={settings.FontSize} onValue={(value) => { setFontSize(value); notifyPreferenceSaved(); }} renderSelected={(selected) => { if (selected === undefined) { return null; } const label = ThemeFontSizeSettingMap[selected]?.label() || ''; return <>{label}</>; }} > {themeFontSizeEntries.map(([id, { label: getLabel, value }]) => { const label = getLabel(); return ( <Option key={id} className={clsx('flex flex-nowrap flex-align-items-center gap-2 py-0 h-custom')} style={{ '--h-custom': '2.5rem', }} title={label} value={id} > <span className="flex-item-noshrink w-custom text-center text-nowrap text-bold" style={{ fontSize: `${value / 14}em`, '--w-custom': '1.5rem', }} > Aa </span> <span className="flex-item-fluid">{label}</span> </Option> ); })} </SelectTwo> </SettingsLayoutRight> </SettingsLayout> <SettingsLayout className="py-1"> <SettingsLayoutLeft> <label htmlFor="scrollbarsToggle" className="text-semibold align-top"> <span className="mr-2">{c('Label').t`Default scrollbars`}</span> <Info title={c('Tooltip') .t`Use your browser’s default scrollbars. These are typically larger and easier to use`} /> </label> </SettingsLayoutLeft> <SettingsLayoutRight className="pt-1"> <Toggle id="scrollbarsToggle" checked={information.features.scrollbars} onChange={(e) => { setFeature(ThemeFeatureSetting.SCROLLBARS_OFF, e.target.checked); notifyPreferenceSaved(); }} /> </SettingsLayoutRight> </SettingsLayout> <SettingsLayout className="py-1"> <SettingsLayoutLeft> <label htmlFor="animationsToggle" className={clsx('text-semibold align-top', reduceMotion && 'color-weak')} > <span className="mr-2">{c('Label').t`Disable animations`}</span> <Info title={c('Tooltip').t`When enabled, animations and transitions will not show`} /> </label> </SettingsLayoutLeft> <SettingsLayoutRight className="pt-1"> <Tooltip title={ reduceMotion ? c('Tooltip').t`The reduce motion setting is already enabled on this device` : undefined } closeDelay={0} openDelay={0} > <span className="inline-flex"> <Toggle id="animationsToggle" checked={reduceMotion ? true : information.features.animations} disabled={reduceMotion} onChange={(e) => { setFeature(ThemeFeatureSetting.ANIMATIONS_OFF, e.target.checked); notifyPreferenceSaved(); }} /> </span> </Tooltip> </SettingsLayoutRight> </SettingsLayout> </SettingsSection> ); }; export default AccessibilitySection;
5,731
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/ChangePasswordModal.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { PASSWORD_WRONG_ERROR } from '@proton/shared/lib/api/auth'; import { updatePrivateKeyRoute } from '@proton/shared/lib/api/keys'; import { lockSensitiveSettings, unlockPasswordChanges } from '@proton/shared/lib/api/user'; import innerMutatePassword from '@proton/shared/lib/authentication/mutate'; import { BRAND_NAME, MAIL_APP_NAME } from '@proton/shared/lib/constants'; import { confirmPasswordValidator, passwordLengthValidator, requiredValidator, } from '@proton/shared/lib/helpers/formValidators'; import { Address } from '@proton/shared/lib/interfaces'; import { generateKeySaltAndPassphrase } from '@proton/shared/lib/keys'; import { getUpdateKeysPayload } from '@proton/shared/lib/keys/changePassword'; import { srpVerify } from '@proton/shared/lib/srp'; import noop from '@proton/utils/noop'; import { Form, InputFieldTwo, ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, ModalProps, PasswordInputTwo, SettingsLink, useFormErrors, } from '../../components'; import { useApi, useAuthentication, useBeforeUnload, useEventManager, useGetAddressKeys, useGetAddresses, useGetOrganizationKeyRaw, useGetUserKeys, useNotifications, useUser, } from '../../hooks'; import { GenericError } from '../error'; import AuthModal from '../password/AuthModal'; import { handleChangeLoginPassword } from './changePasswordHelper'; export enum MODES { CHANGE_ONE_PASSWORD_MODE = 1, CHANGE_TWO_PASSWORD_MAILBOX_MODE = 2, CHANGE_TWO_PASSWORD_LOGIN_MODE = 3, SWITCH_ONE_PASSWORD = 4, SWITCH_TWO_PASSWORD = 5, } interface Inputs { oldPassword: string; newPassword: string; confirmPassword: string; totp: string; } interface Errors { loginError: string; fatalError: boolean; persistError?: boolean; } const DEFAULT_ERRORS: Errors = { loginError: '', fatalError: false, }; interface ModalProperties { title: string; description?: JSX.Element | null; labels: { newPassword: string; confirmPassword: string; }; close?: string; submit?: string; onSubmit?: () => Promise<void>; } interface Props extends ModalProps { mode: MODES; onSessionRecovery?: () => void; onSuccess?: () => void; } const ChangePasswordModal = ({ mode, onSessionRecovery, onSuccess, onClose, ...rest }: Props) => { const api = useApi(); const { call, stop, start } = useEventManager(); const authentication = useAuthentication(); const { createNotification } = useNotifications(); const getOrganizationKeyRaw = useGetOrganizationKeyRaw(); const getUserKeys = useGetUserKeys(); const getAddressKeys = useGetAddressKeys(); const getAddresses = useGetAddresses(); const { validator, onFormSubmit, reset } = useFormErrors(); const lockAndClose = () => { void api(lockSensitiveSettings()); onClose?.(); }; const [User] = useUser(); const { isSubUser, isAdmin, Name, Email } = User; const [inputs, setInputs] = useState<Inputs>({ oldPassword: '', newPassword: '', confirmPassword: '', totp: '', }); const [loading, setLoading] = useState<boolean>(false); const [errors, setErrors] = useState<Errors>(DEFAULT_ERRORS); const [isSecondPhase, setSecondPhase] = useState<boolean>(false); useBeforeUnload(loading ? c('Info').t`By leaving now, changes may not be saved` : ''); const setPartialError = (object: Partial<Errors>) => setErrors((oldState) => ({ ...oldState, ...object })); const setPartialInput = (object: Partial<Inputs>) => setInputs((oldState) => ({ ...oldState, ...object })); const resetErrors = () => setErrors(DEFAULT_ERRORS); const newPasswordError = passwordLengthValidator(inputs.newPassword); const confirmPasswordError = passwordLengthValidator(inputs.confirmPassword) || confirmPasswordValidator(inputs.newPassword, inputs.confirmPassword); const validateNewPasswords = () => { if (newPasswordError || confirmPasswordError) { throw new Error('Password error'); } }; const checkLoginError = ({ data: { Code, Error } = { Code: 0, Error: '' } }) => { if (Code === PASSWORD_WRONG_ERROR) { setPartialError({ ...DEFAULT_ERRORS, loginError: Error, }); } }; const checkFatalError = (e: Error) => { if (e.name === 'NoDecryptedKeys') { setPartialError({ fatalError: true }); } }; const notifySuccess = () => { createNotification({ text: c('Success').t`Password updated` }); onSuccess?.(); }; const mutatePassword = async (keyPassword: string) => { try { await innerMutatePassword({ api, authentication, keyPassword, User, }); } catch (e: any) { // If persisting the password fails for some reason. setPartialError({ fatalError: true, persistError: true }); throw e; } }; const getModalProperties = (mode: MODES): ModalProperties => { if ([MODES.CHANGE_TWO_PASSWORD_LOGIN_MODE, MODES.CHANGE_ONE_PASSWORD_MODE].includes(mode)) { if (isSubUser) { const userName = ( <b key="user" className="text-break"> {Name} ({Email}) </b> ); return { title: c('Title').t`Change password`, description: <div className="mb-4">{c('Info').jt`Enter new password for user ${userName}.`}</div>, labels: { newPassword: c('Label').t`User's new password`, confirmPassword: c('Label').t`Confirm new password`, }, close: c('Action').t`Cancel`, submit: c('Action').t`Change password`, }; } if (mode === MODES.CHANGE_ONE_PASSWORD_MODE) { return { title: c('Title').t`Change password`, labels: { newPassword: c('Label').t`New password`, confirmPassword: c('Label').t`Confirm password`, }, }; } return { title: c('Title').t`Change login password`, labels: { newPassword: c('Label').t`New login password`, confirmPassword: c('Label').t`Confirm login password`, }, }; } throw new Error('mode not supported'); }; const { labels, description = null, title, close = undefined, submit = undefined, onSubmit, } = ((): ModalProperties => { if (mode === MODES.CHANGE_TWO_PASSWORD_LOGIN_MODE) { return { ...getModalProperties(mode), async onSubmit() { if (!onFormSubmit()) { return; } try { validateNewPasswords(); resetErrors(); setLoading(true); await handleChangeLoginPassword({ api, newPassword: inputs.newPassword }); notifySuccess(); lockAndClose(); } catch (e: any) { setLoading(false); checkLoginError(e); } }, }; } if (mode === MODES.SWITCH_TWO_PASSWORD && !isSecondPhase) { return { title: c('Title').t`Switch to two-password mode`, description: ( <div className="mb-4"> {c('Info') .t`Two-password mode uses separate passwords for login and mailbox decryption. This provides a minor security benefit in some situations, however we recommend one-password mode for most users. To switch to two password mode, first set a login password and then set a mailbox password.`} </div> ), labels: { newPassword: c('Label').t`New login password`, confirmPassword: c('Label').t`Confirm login password`, }, async onSubmit() { if (!onFormSubmit()) { return; } try { validateNewPasswords(); resetErrors(); setLoading(true); await handleChangeLoginPassword({ api, newPassword: inputs.newPassword }); setSecondPhase(true); setInputs({ newPassword: '', confirmPassword: '', totp: '', oldPassword: '', }); reset(); setLoading(false); } catch (e: any) { setLoading(false); checkLoginError(e); } }, }; } const getAddressesWithKeysList = (addresses: Address[]) => { return Promise.all( addresses.map(async (address) => { return { address, keys: await getAddressKeys(address.ID), }; }) ); }; if (mode === MODES.SWITCH_TWO_PASSWORD && isSecondPhase) { return { title: c('Title').t`Switch to two-password mode`, labels: { newPassword: c('Label').t`New mailbox password`, confirmPassword: c('Label').t`Confirm mailbox password`, }, async onSubmit() { if (!onFormSubmit()) { return; } try { // Stop the event manager to prevent race conditions stop(); const [addresses, userKeysList, organizationKey] = await Promise.all([ getAddresses(), getUserKeys(), isAdmin ? getOrganizationKeyRaw() : undefined, ]); validateNewPasswords(); resetErrors(); setLoading(true); const { passphrase: keyPassword, salt: keySalt } = await generateKeySaltAndPassphrase( inputs.newPassword ); const addressesKeys = await getAddressesWithKeysList(addresses); const updateKeysPayload = await getUpdateKeysPayload( addressesKeys, userKeysList, organizationKey?.privateKey, keyPassword, keySalt ); await api(updatePrivateKeyRoute(updateKeysPayload)); await mutatePassword(keyPassword); await call(); notifySuccess(); lockAndClose(); } catch (e: any) { setLoading(false); checkFatalError(e); } finally { start(); } }, }; } const onSubmit = async () => { if (!onFormSubmit()) { return; } try { stop(); const [addresses, userKeysList, organizationKey] = await Promise.all([ getAddresses(), getUserKeys(), isAdmin ? getOrganizationKeyRaw() : undefined, ]); /** * This is the case for a user who does not have any keys set-up. * They will be in 2-password mode, but not have any keys. * Changing to one-password mode or mailbox password is not allowed. * It's not handled better because it's a rare case. */ if (userKeysList.length === 0) { createNotification({ type: 'error', text: c('Error').t`Please generate keys before you try to change your password`, }); return; } validateNewPasswords(); resetErrors(); setLoading(true); const { passphrase: keyPassword, salt: keySalt } = await generateKeySaltAndPassphrase( inputs.newPassword ); const addressesWithKeys = await getAddressesWithKeysList(addresses); const updateKeysPayload = await getUpdateKeysPayload( addressesWithKeys, userKeysList, organizationKey?.privateKey, keyPassword, keySalt ); const routeConfig = updatePrivateKeyRoute(updateKeysPayload); if (mode === MODES.CHANGE_TWO_PASSWORD_MAILBOX_MODE) { await api(routeConfig); } else { await srpVerify({ api, credentials: { password: inputs.newPassword, totp: inputs.totp, }, config: routeConfig, }); } await mutatePassword(keyPassword); await call(); notifySuccess(); lockAndClose(); } catch (e: any) { setLoading(false); checkFatalError(e); checkLoginError(e); } finally { start(); } }; if (mode === MODES.SWITCH_ONE_PASSWORD) { return { title: c('Title').t`Switch to one-password mode`, labels: { newPassword: c('Label').t`New password`, confirmPassword: c('Label').t`Confirm password`, }, description: ( <div className="mb-4"> {c('Info') .t`${MAIL_APP_NAME} can also be used with a single password which replaces both the login and mailbox password. To switch to single password mode, enter the single password you would like to use and click Save.`} </div> ), onSubmit, }; } if (mode === MODES.CHANGE_ONE_PASSWORD_MODE) { return { ...getModalProperties(mode), onSubmit, }; } if (mode === MODES.CHANGE_TWO_PASSWORD_MAILBOX_MODE) { return { title: c('Title').t`Change mailbox password`, labels: { newPassword: c('Label').t`New mailbox password`, confirmPassword: c('Label').t`Confirm mailbox password`, }, onSubmit, }; } throw new Error('Unknown mode'); })(); const addARecoveryMethod = ( <SettingsLink key="recovery-link" path="/recovery">{ // translator: Make sure you add a recovery method so that you can get back into your account if you forget your password. c('Info').t`add a recovery method` }</SettingsLink> ); const [authed, setAuthed] = useState(false); if (!authed) { return ( <AuthModal config={unlockPasswordChanges()} {...rest} onCancel={onClose} onSuccess={async () => { setAuthed(true); }} onSessionRecovery={onSessionRecovery} /> ); } if (errors.fatalError) { const handleFatalErrorClose = () => { if (errors.persistError) { // If there was an error with persisting the session, we have no choice but to logout authentication.logout(); } lockAndClose(); }; return ( <Modal {...rest} onClose={handleFatalErrorClose}> <ModalHeader title={title} /> <ModalContent> <GenericError /> </ModalContent> <ModalFooter> <Button onClick={handleFatalErrorClose}>{close || c('Action').t`Cancel`}</Button> <Button color="norm" onClick={handleFatalErrorClose}> {submit || c('Action').t`OK`} </Button> </ModalFooter> </Modal> ); } const handleClose = loading ? noop : lockAndClose; return ( <Modal as={Form} onClose={handleClose} {...rest} onSubmit={onSubmit}> <ModalHeader title={title} /> <ModalContent> {description} <div className="mb-4"> {c('Info') .t`${BRAND_NAME}'s encryption technology means that nobody can access your password - not even us.`} </div> <div className="mb-4"> { // translator: Make sure you add a recovery method so that you can get back into your account if you forget your password. c('Info') .jt`Make sure you ${addARecoveryMethod} so that you can get back into your account if you forget your password.` } </div> <InputFieldTwo id="newPassword" label={labels.newPassword} placeholder={c('Placeholder').t`Password`} error={validator([ requiredValidator(inputs.newPassword), passwordLengthValidator(inputs.newPassword), ])} as={PasswordInputTwo} autoFocus autoComplete="new-password" value={inputs.newPassword} onValue={(value: string) => setPartialInput({ newPassword: value })} disabled={loading} /> <InputFieldTwo key={`${isSecondPhase}${labels.confirmPassword}`} id="confirmPassword" label={labels.confirmPassword} placeholder={c('Placeholder').t`Confirm`} error={validator([ requiredValidator(inputs.confirmPassword), passwordLengthValidator(inputs.confirmPassword), confirmPasswordValidator(inputs.newPassword, inputs.confirmPassword), ])} as={PasswordInputTwo} autoComplete="new-password" value={inputs.confirmPassword} onValue={(value: string) => setPartialInput({ confirmPassword: value })} disabled={loading} /> </ModalContent> <ModalFooter> <Button onClick={handleClose} disabled={loading}> {close || c('Action').t`Cancel`} </Button> <Button loading={loading} type="submit" color="norm"> {submit || c('Action').t`Save`} </Button> </ModalFooter> </Modal> ); }; export default ChangePasswordModal;
5,732
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/DeleteAccountModal.tsx
import { ChangeEvent, FormEvent, useState } from 'react'; import { c } from 'ttag'; import { Button, Href } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { leaveOrganisation } from '@proton/shared/lib/api/organization'; import { reportBug } from '@proton/shared/lib/api/reports'; import { canDelete, deleteUser, unlockPasswordChanges } from '@proton/shared/lib/api/user'; import { ACCOUNT_DELETION_REASONS, BRAND_NAME } from '@proton/shared/lib/constants'; import { emailValidator, minLengthValidator, requiredValidator } from '@proton/shared/lib/helpers/formValidators'; import { omit } from '@proton/shared/lib/helpers/object'; import { wait } from '@proton/shared/lib/helpers/promise'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { isOrganizationFamily } from '@proton/shared/lib/organization/helper'; import isTruthy from '@proton/utils/isTruthy'; import noop from '@proton/utils/noop'; import { Alert, Checkbox, ErrorButton, Form, InputFieldTwo, ModalProps, ModalTwo, ModalTwoContent, ModalTwoFooter, ModalTwoHeader, Option, SelectTwo, TextAreaTwo, useFormErrors, useModalState, } from '../../components'; import { AuthModal } from '../../containers'; import { getClientName, getReportInfo } from '../../helpers/report'; import { useApi, useAuthentication, useConfig, useEventManager, useNotifications, useOrganization, useUser, } from '../../hooks'; const { DIFFERENT_ACCOUNT, TOO_EXPENSIVE, MISSING_FEATURE, USE_OTHER_SERVICE, OTHER } = ACCOUNT_DELETION_REASONS; interface Props extends Omit<ModalProps<'form'>, 'as'> { onSuccess?: () => Promise<void>; hideHeader?: boolean; } const DeleteAccountModal = (props: Props) => { const [authModalProps, setAuthModalOpen, renderAuthModal] = useModalState(); const { createNotification } = useNotifications(); const defaultOnSuccess = async () => { createNotification({ text: c('Success').t`Account deleted. Signing out...` }); // Add an artificial delay to show the notification. await wait(2500); }; const { onSuccess = defaultOnSuccess, hideHeader = false, onClose, disableCloseOnEscape, size = 'large', ...rest } = props; const eventManager = useEventManager(); const api = useApi(); const authentication = useAuthentication(); const [{ isAdmin, Name, Email }] = useUser(); const [organization] = useOrganization(); const [loading, withLoading] = useLoading(); const [model, setModel] = useState({ check: false, reason: '', feedback: '', email: '', }); const { validator, onFormSubmit } = useFormErrors(); const { APP_NAME, APP_VERSION, CLIENT_TYPE } = useConfig(); const Client = getClientName(APP_NAME); const reasons = [ <Option title={c('Option').t`I use a different ${BRAND_NAME} account`} value={DIFFERENT_ACCOUNT} key={DIFFERENT_ACCOUNT} />, isAdmin && <Option title={c('Option').t`It's too expensive`} value={TOO_EXPENSIVE} key={TOO_EXPENSIVE} />, <Option title={c('Option').t`It's missing a key feature that I need`} value={MISSING_FEATURE} key={MISSING_FEATURE} />, <Option title={c('Option').t`I found another service that I like better`} value={USE_OTHER_SERVICE} key={USE_OTHER_SERVICE} />, <Option title={c('Option').t`My reason isn't listed`} value={OTHER} key={OTHER} />, ].filter(isTruthy); const handleSubmit = async () => { try { eventManager.stop(); await api(canDelete()); if (isAdmin) { await api( reportBug({ ...omit(getReportInfo(), ['OSArtificial']), Client, ClientVersion: APP_VERSION, ClientType: CLIENT_TYPE, Title: `[DELETION FEEDBACK] ${Name}`, Username: Name || Email, Email: model.email, Description: model.feedback, }) ); } // If a user is part of a family plan we first need to leave the organization before deleting the account. // Refreshing the event manager is necessary to update the organization state if (isOrganizationFamily(organization) && !isAdmin) { eventManager.start(); await api(leaveOrganisation()); await eventManager.call(); eventManager.stop(); } await api( deleteUser({ Reason: model.reason, Feedback: model.feedback, Email: model.email, }) ); await onSuccess?.(); onClose?.(); authentication.logout(); } catch (error: any) { eventManager.start(); throw error; } }; return ( <> {renderAuthModal && ( <AuthModal config={unlockPasswordChanges()} {...authModalProps} onCancel={undefined} onSuccess={() => { withLoading(handleSubmit()); }} /> )} <ModalTwo as={Form} onClose={hideHeader ? undefined : onClose} disableCloseOnEscape={disableCloseOnEscape || loading} size={size} onSubmit={ loading ? noop : (event: FormEvent<HTMLFormElement>) => { if (!onFormSubmit(event.currentTarget)) { return; } setAuthModalOpen(true); } } {...rest} > {!hideHeader && <ModalTwoHeader title={c('Title').t`Delete account`} />} <ModalTwoContent> <Alert className="mb-4" type="warning"> <div className="text-bold text-uppercase"> {c('Info') .t`Warning: deletion is permanent. This also removes access to all connected services and deletes all of your contacts.`} </div> <div> {c('Info').t`If you wish to combine this account with another one, do NOT delete it.`} </div> <div> <Href href={getKnowledgeBaseUrl('/combine-accounts')}>{c('Link').t`Learn more`}</Href> </div> </Alert> <InputFieldTwo rootClassName="mb-2" as={SelectTwo} label={c('Label').t`What is the main reason you are deleting your account?`} placeholder={c('Placeholder').t`Select a reason`} id="reason" autoFocus value={model.reason} onValue={(value: unknown) => setModel({ ...model, reason: value as string })} error={validator([requiredValidator(model.reason)])} disabled={loading} > {reasons} </InputFieldTwo> <InputFieldTwo id="feedback" as={TextAreaTwo} rootClassName="mt-2" rows={3} label={c('Label') .t`We are sorry to see you go. Please explain why you are leaving to help us improve.`} placeholder={c('Placeholder').t`Feedback`} value={model.feedback} onValue={(value: string) => setModel({ ...model, feedback: value })} error={validator([requiredValidator(model.feedback), minLengthValidator(model.feedback, 10)])} disabled={loading} /> <InputFieldTwo id="email" rootClassName="mt-2" label={c('Label').t`Email address`} placeholder={c('Placeholder').t`Email address`} assistiveText={c('Info').t`Please provide an email address in case we need to contact you.`} value={model.email} onValue={(value: string) => setModel({ ...model, email: value })} error={validator([requiredValidator(model.email), emailValidator(model.email)])} disabled={loading} /> <InputFieldTwo rootClassName="mt-4" id="check" as={Checkbox} error={validator([!model.check ? requiredValidator(undefined) : ''])} checked={model.check} onChange={({ target }: ChangeEvent<HTMLInputElement>) => setModel({ ...model, check: target.checked }) } disabled={loading} > {c('Label').t`Yes, I want to permanently delete this account and all its data.`} </InputFieldTwo> </ModalTwoContent> <ModalTwoFooter> <Button onClick={onClose} disabled={loading}>{c('Action').t`Cancel`}</Button> <ErrorButton loading={loading} type="submit"> {c('Action').t`Delete`} </ErrorButton> </ModalTwoFooter> </ModalTwo> </> ); }; export default DeleteAccountModal;
5,733
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/DeleteSection.tsx
import { c } from 'ttag'; import { Button, Href } from '@proton/atoms'; import { ADDRESS_TYPE, APPS, MAIL_APP_NAME, VPN_APP_NAME } from '@proton/shared/lib/constants'; import { hasMigrationDiscount, hasNewVisionary } from '@proton/shared/lib/helpers/subscription'; import { Loader } from '../../components'; import { useModalState } from '../../components/modalTwo'; import { useAddresses, useConfig, useSubscription } from '../../hooks'; import { DiscountWarningModal, NewVisionaryWarningModal } from '../payments/subscription/PlanLossWarningModal'; import DeleteAccountModal from './DeleteAccountModal'; import MozillaInfoPanel from './MozillaInfoPanel'; import SettingsParagraph from './SettingsParagraph'; const DeleteSection = () => { const [addresses, loadingAddresses] = useAddresses(); const [subscription, loadingSubscription] = useSubscription(); const { APP_NAME } = useConfig(); const [deleteAccountModalProps, setDeleteAccountModalOpen, renderDeleteAccountModal] = useModalState(); const [migrationDiscountModalProps, setMigrationDiscountModal, renderDiscountModal] = useModalState(); const [visionaryLossModalProps, setVisionaryLossModal, renderVisionaryLossModal] = useModalState(); if (loadingAddresses || loadingSubscription) { return <Loader />; } if ( APP_NAME === APPS.PROTONVPN_SETTINGS && addresses.some((address) => address.Type !== ADDRESS_TYPE.TYPE_EXTERNAL) ) { const loginLink = ( <Href key="0" href="https://account.proton.me/login?product=mail"> mail.proton.me </Href> ); return ( <SettingsParagraph> {c('Info') .jt`Your ${VPN_APP_NAME} and ${MAIL_APP_NAME} accounts are linked. To delete them both, please sign in at ${loginLink} and delete your account there.`} </SettingsParagraph> ); } if (subscription?.isManagedByMozilla) { return <MozillaInfoPanel />; } return ( <> {renderDiscountModal && ( <DiscountWarningModal type="delete" {...migrationDiscountModalProps} onConfirm={() => { if (hasNewVisionary(subscription)) { setVisionaryLossModal(true); return; } setDeleteAccountModalOpen(true); }} /> )} {renderVisionaryLossModal && ( <NewVisionaryWarningModal type="delete" {...visionaryLossModalProps} onConfirm={() => { setDeleteAccountModalOpen(true); }} /> )} {renderDeleteAccountModal && <DeleteAccountModal {...deleteAccountModalProps} />} <SettingsParagraph> {c('Info') .t`This will permanently delete your account and all of its data. You will not be able to reactivate this account.`} </SettingsParagraph> <Button color="danger" shape="outline" id="deleteButton" onClick={() => { if (hasMigrationDiscount(subscription)) { setMigrationDiscountModal(true); return; } if (hasNewVisionary(subscription)) { setVisionaryLossModal(true); return; } setDeleteAccountModalOpen(true); }} > {c('Action').t`Delete your account`} </Button> </> ); }; export default DeleteSection;
5,734
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/EditDisplayNameModal.tsx
import { FormEvent, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { updateAddress } from '@proton/shared/lib/api/addresses'; import { Address } from '@proton/shared/lib/interfaces'; import { InputFieldTwo, ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, ModalProps, useFormErrors, } from '../../components'; import { useApi, useEventManager, useNotifications } from '../../hooks'; interface Props extends ModalProps<'form'> { address: Address; } const EditDisplayNameModal = ({ address, ...rest }: Props) => { const [initialDisplayName] = useState(address.DisplayName); const [model, setModel] = useState(''); const { createNotification } = useNotifications(); const { onFormSubmit } = useFormErrors(); const [submitting, withLoading] = useLoading(); const api = useApi(); const { call } = useEventManager(); const handleSubmit = async () => { await api( updateAddress(address.ID, { DisplayName: model, Signature: address.Signature, }) ); await call(); createNotification({ text: c('Success').t`Display name updated` }); rest.onClose?.(); }; const handleClose = submitting ? undefined : rest.onClose; return ( <Modal as="form" size="small" {...rest} onSubmit={(event: FormEvent) => { event.preventDefault(); event.stopPropagation(); if (!onFormSubmit()) { return; } withLoading(handleSubmit()); }} onClose={handleClose} > <ModalHeader title={c('Title').t`Edit display name`} /> <ModalContent> {initialDisplayName && ( <div className="mb-6"> <div className="text-semibold mb-1">{c('Label').t`Current display name`}</div> <div className="text-ellipsis" title={initialDisplayName}> {initialDisplayName} </div> </div> )} <InputFieldTwo id="displayName" autoFocus value={model} maxLength={255} onValue={setModel} label={c('Label').t`New display name`} /> </ModalContent> <ModalFooter> <Button onClick={handleClose} disabled={submitting}>{c('Action').t`Cancel`}</Button> <Button color="norm" type="submit" loading={submitting}>{c('Action').t`Save`}</Button> </ModalFooter> </Modal> ); }; export default EditDisplayNameModal;
5,735
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/EditEmailSubscription.test.tsx
import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import { sub } from 'date-fns'; import { useApi, useUser, useUserSettings } from '../../hooks'; import EditEmailSubscription from './EditEmailSubscription'; jest.mock('../../hooks/useApi'); const mockedUseApi = useApi as jest.MockedFunction<any>; let mockedApi: ReturnType<typeof mockedUseApi>; jest.mock('../../hooks/useEventManager', () => () => ({ call: jest.fn() })); jest.mock('@proton/hooks/useLoading', () => () => [false, jest.fn((fn) => fn())]); jest.mock('../../hooks/useNotifications', () => () => ({ createNotification: jest.fn() })); jest.mock('../../hooks/useUser'); const mockedUseUser = useUser as jest.MockedFunction<any>; jest.mock('../../hooks/useUserSettings'); const mockedUseUserSettings = useUserSettings as jest.MockedFunction<any>; describe('EditEmailSubscription', () => { beforeEach(() => { mockedApi = jest.fn(); mockedUseApi.mockReturnValue(mockedApi); mockedUseUserSettings.mockReturnValue([{ EarlyAccess: 1, News: 0 }]); mockedUseUser.mockReturnValue([{ CreateTime: Math.floor(sub(new Date(), { weeks: 1 }).getTime() / 1000) }]); }); it('should have all expected toggles', () => { render(<EditEmailSubscription />); expect(screen.getByText('Proton important announcements')); expect(screen.getByText('Proton for Business newsletter')); expect(screen.getByText('Proton newsletter')); expect(screen.getByText('Proton beta announcements')); expect(screen.getByText('Proton offers and promotions')); expect(screen.getByText('Proton welcome emails')); expect(screen.getByText('Proton Mail and Calendar new features')); expect(screen.getByText('Proton Drive product updates')); expect(screen.getByText('Proton Pass product updates')); expect(screen.getByText('Proton VPN product updates')); }); it('should not have FEATURES toggle', () => { render(<EditEmailSubscription />); expect(screen.queryByText('Proton product announcements')).not.toBeInTheDocument(); }); it('should toggle nothing', () => { const { container } = render(<EditEmailSubscription />); const checkedToggles = container.querySelectorAll('[checked=""]'); expect(checkedToggles).toHaveLength(0); }); it('should toggle everything', () => { mockedUseUserSettings.mockReturnValue([{ EarlyAccess: 1, News: 4095 }]); const { container } = render(<EditEmailSubscription />); const checkedToggles = container.querySelectorAll('[checked=""]'); expect(checkedToggles).toHaveLength(10); }); it('should call api on update', async () => { render(<EditEmailSubscription />); const toggleContent = screen.getByText('Proton offers and promotions'); fireEvent.click(toggleContent); await waitFor(() => expect(mockedApi).toHaveBeenCalledTimes(1)); expect(mockedApi).toHaveBeenCalledWith({ data: { Features: false, Offers: true }, method: 'PATCH', url: 'core/v4/settings/news', }); }); it('should update global feature news flag when one product feature news is updated', async () => { render(<EditEmailSubscription />); const toggleContent = screen.getByText('Proton Drive product updates'); fireEvent.click(toggleContent); await waitFor(() => expect(mockedApi).toHaveBeenCalledTimes(1)); expect(mockedApi).toHaveBeenCalledWith({ data: { DriveNews: true, Features: true }, method: 'PATCH', url: 'core/v4/settings/news', }); }); describe('when user has been created more than one month ago', () => { it('should not display `welcome emails` toggle', () => { mockedUseUser.mockReturnValue([{ CreateTime: Math.floor(sub(new Date(), { weeks: 5 }).getTime() / 1000) }]); render(<EditEmailSubscription />); expect(screen.queryByText('Proton welcome emails')).toBeNull(); }); }); describe('when user is not in beta', () => { it('should not display `beta announcements` toggle', () => { mockedUseUserSettings.mockReturnValue([{ EarlyAccess: 0, News: 4095 }]); render(<EditEmailSubscription />); expect(screen.queryByText('Proton beta announcements')).toBeNull(); }); }); });
5,736
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/EditEmailSubscription.tsx
import { isBefore, sub } from 'date-fns'; import { c } from 'ttag'; import { useLoading } from '@proton/hooks'; import { patchNews } from '@proton/shared/lib/api/settings'; import { NEWSLETTER_SUBSCRIPTIONS_BITS } from '@proton/shared/lib/constants'; import { useApi, useEventManager, useNotifications, useUser, useUserSettings } from '../../hooks'; import EmailSubscriptionToggles, { NewsletterSubscriptionUpdateData } from './EmailSubscriptionToggles'; import { getEmailSubscriptions } from './constants'; const EditEmailSubscription = () => { const [user] = useUser(); const [{ News, EarlyAccess } = { News: 0, EarlyAccess: 0 }] = useUserSettings(); const { createNotification } = useNotifications(); const { call } = useEventManager(); const api = useApi(); const [loading, withLoading] = useLoading(); const handleChange = (data: NewsletterSubscriptionUpdateData) => withLoading(async () => { await api(patchNews(data)); await call(); createNotification({ text: c('Info').t`Emailing preference saved` }); }); const filteredEmailSubscription = getEmailSubscriptions().filter(({ flag }) => { switch (flag) { case NEWSLETTER_SUBSCRIPTIONS_BITS.FEATURES: // We don't want to display toggle for FEATURES news subscription as manual switch has been deprecated for this option. // INBOX_NEWS, DRIVE_NEWS & VPN_NEWS should be used instead return false; case NEWSLETTER_SUBSCRIPTIONS_BITS.ONBOARDING: // check if the user account was created more than 1 month ago return isBefore(sub(new Date(), { months: 1 }), user.CreateTime * 1000); case NEWSLETTER_SUBSCRIPTIONS_BITS.BETA: return Boolean(EarlyAccess); default: return true; } }); return ( <EmailSubscriptionToggles News={News} onChange={handleChange} disabled={loading} subscriptions={filteredEmailSubscription} /> ); }; export default EditEmailSubscription;
5,737
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/EditExternalAddressModal.tsx
import { FormEvent, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { renameExternalAddress } from '@proton/shared/lib/api/addresses'; import { getEmailParts } from '@proton/shared/lib/helpers/email'; import { confirmEmailValidator, emailValidator, requiredValidator } from '@proton/shared/lib/helpers/formValidators'; import { Address } from '@proton/shared/lib/interfaces'; import { getRenamedAddressKeys } from '@proton/shared/lib/keys'; import { InputFieldTwo, ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, ModalProps, useFormErrors, } from '../../components'; import { useApi, useEventManager, useGetUserKeys, useNotifications, useOrganizationKey } from '../../hooks'; interface Props extends ModalProps<'form'> { address: Address; } const EditExternalAddressModal = ({ address, ...rest }: Props) => { const [initialEmailAddress] = useState(address.Email); const [email, setEmail] = useState(''); const [confirmEmail, setConfirmEmail] = useState(''); const getUserKeys = useGetUserKeys(); const [organizationKey, loadingOrganizationKey] = useOrganizationKey(); const { createNotification } = useNotifications(); const { onFormSubmit, validator } = useFormErrors(); const [submitting, withLoading] = useLoading(); const api = useApi(); const { call } = useEventManager(); const handleSubmit = async () => { const userKeys = await getUserKeys(); const [Local, Domain] = getEmailParts(email); await api( renameExternalAddress(address.ID, { Local, Domain, AddressKeys: await getRenamedAddressKeys({ userKeys, addressKeys: address.Keys, organizationKey: organizationKey?.privateKey ? organizationKey : undefined, email, }), }) ); await call(); createNotification({ text: c('Success').t`Email address updated` }); rest.onClose?.(); }; const handleClose = submitting ? undefined : rest.onClose; return ( <Modal as="form" size="small" {...rest} onSubmit={(event: FormEvent) => { event.preventDefault(); event.stopPropagation(); if (loadingOrganizationKey) { return; } if (!onFormSubmit()) { return; } withLoading(handleSubmit()); }} onClose={handleClose} noValidate > <ModalHeader title={c('Title').t`Edit email address`} subline={c('Title') .t`We'll send an email to your new address with instructions on completing the change.`} /> <ModalContent> <div className="mb-4"> <div className="text-semibold mb-1">{c('Label').t`Current email`}</div> <div className="text-ellipsis rounded bg-weak px-3 py-2" title={initialEmailAddress}> {initialEmailAddress} </div> </div> <InputFieldTwo type="email" autoComplete="email" id="email" autoFocus value={email} onValue={setEmail} error={validator([requiredValidator(email), emailValidator(email)])} label={c('Label').t`New email`} /> <InputFieldTwo type="email" autoComplete="email" id="email-confirm" value={confirmEmail} onValue={setConfirmEmail} error={validator([confirmEmailValidator(email, confirmEmail)])} label={c('Label').t`Confirm email`} /> </ModalContent> <ModalFooter> <Button onClick={handleClose} disabled={submitting}>{c('Action').t`Cancel`}</Button> <Button color="norm" type="submit" loading={submitting}>{c('Action').t`Save`}</Button> </ModalFooter> </Modal> ); }; export default EditExternalAddressModal;
5,738
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/EmailSubscriptionCategories.tsx
import { c } from 'ttag'; import { NEWSLETTER_SUBSCRIPTIONS_BITS } from '@proton/shared/lib/constants'; import isTruthy from '@proton/utils/isTruthy'; import { getEmailSubscriptionsMap } from './constants/email-subscriptions'; const EmailSubscriptionCategories = ({ news }: { news: NEWSLETTER_SUBSCRIPTIONS_BITS[] }) => { const emailSubscriptionMap = getEmailSubscriptionsMap(); const categoryTitles = news .map((newsKind) => emailSubscriptionMap[newsKind]?.title) .filter((title) => isTruthy(title)); if (!categoryTitles.length) { return null; } const allCategoryTitlesExceptTheLastOne = categoryTitles.slice(0, -1).join(', '); const lastCategoryTitle = categoryTitles[categoryTitles.length - 1]; const categoriesString = categoryTitles.length > 1 ? c('Email Unsubscribe Categories').t`${allCategoryTitlesExceptTheLastOne} and ${lastCategoryTitle}` : lastCategoryTitle; return ( <span className="text-bold" key="category-title"> {categoriesString} </span> ); }; export default EmailSubscriptionCategories;
5,739
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/EmailSubscriptionSection.tsx
import { c } from 'ttag'; import { Href } from '@proton/atoms/Href'; import { BRAND_NAME } from '@proton/shared/lib/constants'; import { getStaticURL } from '@proton/shared/lib/helpers/url'; import { useSubscription } from '../../hooks'; import EditEmailSubscription from './EditEmailSubscription'; import MozillaInfoPanel from './MozillaInfoPanel'; import SettingsParagraph from './SettingsParagraph'; import SettingsSection from './SettingsSection'; const EmailSubscriptionSection = () => { const [subscription] = useSubscription(); if (subscription?.isManagedByMozilla) { return <MozillaInfoPanel />; } const blogLink = ( <Href key={`link-to-blog`} href={getStaticURL('/blog')}>{c('Link').t`visit our blog`}</Href> ); return ( <SettingsSection> <SettingsParagraph> {c('Info') .jt`To keep up with the latest development at ${BRAND_NAME} products, you can subscribe to our various emails and ${blogLink} from time to time.`} </SettingsParagraph> <EditEmailSubscription /> </SettingsSection> ); }; export default EmailSubscriptionSection;
5,740
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/EmailSubscriptionToggles.tsx
import { NEWSLETTER_SUBSCRIPTIONS, NEWSLETTER_SUBSCRIPTIONS_BITS, NEWSLETTER_SUBSCRIPTIONS_BY_BITS, } from '@proton/shared/lib/constants'; import { hasBit } from '@proton/shared/lib/helpers/bitset'; import { isGlobalFeatureNewsEnabled } from '@proton/shared/lib/helpers/newsletter'; import { Info, Toggle } from '../../components'; import { EmailSubscription, getEmailSubscriptions } from './constants/email-subscriptions'; export type NewsletterSubscriptionUpdateData = Partial<Record<NEWSLETTER_SUBSCRIPTIONS, boolean>>; export interface EmailSubscriptionCheckboxesProps { disabled: boolean; News: number; onChange: (data: NewsletterSubscriptionUpdateData) => void; subscriptions?: EmailSubscription[]; } const EmailSubscriptionToggles = ({ disabled, News, onChange, subscriptions = getEmailSubscriptions(), }: EmailSubscriptionCheckboxesProps) => { return ( <ul className="unstyled relative"> {subscriptions.map(({ id, flag, title, frequency, tooltip }) => { const isSubscribed = hasBit(News, flag); const handleChange = (flag: NEWSLETTER_SUBSCRIPTIONS_BITS) => () => { const update = { [NEWSLETTER_SUBSCRIPTIONS_BY_BITS[flag]]: !isSubscribed, }; onChange({ ...update, [NEWSLETTER_SUBSCRIPTIONS.FEATURES]: isGlobalFeatureNewsEnabled(News, update), }); }; return ( <li key={id} className="mb-4 flex flex-nowrap gap-4"> <Toggle id={id} className="flex-item-noshrink" checked={isSubscribed} disabled={disabled} onChange={handleChange(flag)} /> <label htmlFor={id} className="flex on-mobile-flex-column"> <span className="mr-1">{title}</span> {frequency && <span className="mr-1">{frequency}</span>} {tooltip && <Info title={tooltip} />} </label> </li> ); })} </ul> ); }; export default EmailSubscriptionToggles;
5,741
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/FamilyPlanSection.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { useModalState } from '@proton/components/components'; import { Loader } from '@proton/components/components/loader'; import { useAddresses, useCalendars, useOrganization, useUser } from '@proton/components/hooks'; import { isOrganizationFamily } from '@proton/shared/lib/organization/helper'; import { UsagePanel } from '../payments/subscription/panels'; import LeaveFamilyModal from './LeaveFamilyModal'; import SettingsParagraph from './SettingsParagraph'; const FamilyPlanSection = () => { const [organization, organisationLoading] = useOrganization(); const [user, userLoading] = useUser(); const [calendars, calendarsLoading] = useCalendars(); const [addresses, addressLoading] = useAddresses(); const [leaveFamilyModal, setLeaveFamilyModal, renderLeaveFamilyModal] = useModalState(); const isLoading = organisationLoading || userLoading || calendarsLoading || addressLoading; const isFamilyPlan = isOrganizationFamily(organization); return isLoading ? ( <Loader /> ) : ( <> <SettingsParagraph>{c('familyOffer_2023:Family plan') .t`You are part of ${organization.Name}.`}</SettingsParagraph> <div className="w-full md:w-1/2"> <UsagePanel addresses={addresses} calendars={calendars} organization={organization} user={user}> <Button shape="ghost" color="danger" fullWidth onClick={() => { setLeaveFamilyModal(true); }} > {isFamilyPlan ? c('familyOffer_2023:Family plan').t`Leave family plan` : c('familyOffer_2023:Family plan').t`Leave visionary plan`} </Button> </UsagePanel> </div> {renderLeaveFamilyModal && <LeaveFamilyModal organisationName={organization.Name} {...leaveFamilyModal} />} </> ); }; export default FamilyPlanSection;
5,742
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/LeaveFamilyModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { leaveOrganisation } from '@proton/shared/lib/api/organization'; import { BRAND_NAME } from '@proton/shared/lib/constants'; import { useApi, useEventManager, useNotifications } from '../..'; import { ModalStateProps, Prompt } from '../../components'; interface Props extends ModalStateProps { organisationName: string; } const LeaveFamilyModal = ({ organisationName, ...modalState }: Props) => { const [loading, withLoading] = useLoading(); const { createNotification } = useNotifications(); const api = useApi(); const { call } = useEventManager(); const handleLeave = async () => { await withLoading(api(leaveOrganisation())); modalState.onClose(); await call(); createNotification({ text: c('familyOffer_2023:Info').t`You left this plan` }); }; const handleClose = () => { if (loading) { return; } modalState.onClose(); }; return ( <Prompt {...modalState} title={c('Title').t`Leave ${organisationName}?`} footnote={c('familyOffer_2023:Family plan').t`*Only one free trial per customer.`} buttons={[ <Button color="danger" onClick={handleLeave} loading={loading}>{c('Action').t`Leave`}</Button>, <Button onClick={handleClose} disabled={loading}>{c('Action').t`Cancel`}</Button>, ]} > <p className="my-2">{c('familyOffer_2023:Family plan') .t`You will lose access to all premium features and storage space included with ${BRAND_NAME} Family.`}</p> <p className="my-2">{c('familyOffer_2023:Family plan') .t`To ease the transition, we're giving you a 30-day courtesy trial of ${BRAND_NAME} Unlimited*.`}</p> </Prompt> ); }; export default LeaveFamilyModal;
5,743
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/MozillaInfoPanel.tsx
import { c } from 'ttag'; import { Href } from '@proton/atoms'; import { Alert, Icon } from '../../components'; const MozillaInfoPanel = () => { return ( <Alert className="mb-4" type="warning"> <Icon name="exclamation-circle" /> {c('Info').t`Your subscription is managed by Mozilla. Please contact Mozilla support.`} <div> <Href href="https://support.mozilla.org/en-US/kb/protonvpn">{c('Link').t`Learn more`}</Href> </div> </Alert> ); }; export default MozillaInfoPanel;
5,744
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/PasswordsSection.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { SETTINGS_PASSWORD_MODE } from '@proton/shared/lib/interfaces'; import { Info, Loader, Toggle } from '../../components'; import useModalState from '../../components/modalTwo/useModalState'; import { useSearchParamsEffect, useUser, useUserSettings } from '../../hooks'; import ChangePasswordModal, { MODES } from './ChangePasswordModal'; import SettingsLayout from './SettingsLayout'; import SettingsLayoutLeft from './SettingsLayoutLeft'; import SettingsLayoutRight from './SettingsLayoutRight'; import SettingsSection from './SettingsSection'; import InitiateSessionRecoveryModal from './sessionRecovery/InitiateSessionRecoveryModal'; import PasswordResetAvailableAccountModal from './sessionRecovery/PasswordResetAvailableAccountModal'; import { useSessionRecoveryLocalStorage } from './sessionRecovery/SessionRecoveryLocalStorageManager'; const PasswordsSection = () => { const [user, loadingUser] = useUser(); const [userSettings, loadingUserSettings] = useUserSettings(); const [tmpPasswordMode, setTmpPasswordMode] = useState<MODES>(); const [changePasswordModal, setChangePasswordModalOpen, renderChangePasswordModal] = useModalState(); const [sessionRecoveryModal, setSessionRecoveryModalOpen, renderSessionRecoveryModal] = useModalState(); const [ sessionRecoveryPasswordResetModal, setSessionRecoveryPasswordResetModalOpen, renderSessionRecoveryPasswordResetModal, ] = useModalState(); const { dismissSessionRecoveryCancelled } = useSessionRecoveryLocalStorage(); const [skipInfoStep, setSkipInfoStep] = useState(false); const isOnePasswordMode = userSettings?.Password?.Mode === SETTINGS_PASSWORD_MODE.ONE_PASSWORD_MODE; const passwordLabel = isOnePasswordMode ? c('Title').t`Password` : c('Title').t`Login password`; const passwordButtonLabel = isOnePasswordMode ? c('Title').t`Change password` : c('Title').t`Change login password`; const changePasswordMode = isOnePasswordMode ? MODES.CHANGE_ONE_PASSWORD_MODE : MODES.CHANGE_TWO_PASSWORD_LOGIN_MODE; const loading = loadingUserSettings || loadingUser; const handleChangePassword = (mode: MODES) => { setTmpPasswordMode(mode); setChangePasswordModalOpen(true); }; useSearchParamsEffect( (params) => { if (loading) { return; } const action = params.get('action'); if (!action) { return; } if (action === 'change-password') { handleChangePassword(changePasswordMode); } else if (action === 'session-recovery-password-reset-available') { setSkipInfoStep(false); setSessionRecoveryPasswordResetModalOpen(true); } else if (action === 'session-recovery-reset-password') { setSkipInfoStep(true); setSessionRecoveryPasswordResetModalOpen(true); } params.delete('action'); return params; }, [loading] ); if (loading) { return <Loader />; } // Users without any keys setup are by default in two password mode, even if they have an address. // Don't allow them to change two-password mode. const hasTwoPasswordOption = user.Keys.length > 0; return ( <> {renderChangePasswordModal && tmpPasswordMode && ( <ChangePasswordModal mode={tmpPasswordMode} onSessionRecovery={() => { changePasswordModal.onClose(); setSessionRecoveryModalOpen(true); }} onSuccess={() => { dismissSessionRecoveryCancelled(); }} {...changePasswordModal} /> )} {renderSessionRecoveryModal && <InitiateSessionRecoveryModal {...sessionRecoveryModal} />} {renderSessionRecoveryPasswordResetModal && ( <PasswordResetAvailableAccountModal skipInfoStep={skipInfoStep} {...sessionRecoveryPasswordResetModal} /> )} <SettingsSection> <SettingsLayout> <SettingsLayoutLeft> <label htmlFor="passwordChange" className="text-semibold"> {passwordLabel} </label> </SettingsLayoutLeft> <SettingsLayoutRight> <Button onClick={() => handleChangePassword(changePasswordMode)}>{passwordButtonLabel}</Button> </SettingsLayoutRight> </SettingsLayout> {hasTwoPasswordOption && ( <> <SettingsLayout> <SettingsLayoutLeft> <label htmlFor="passwordModeToggle" className="text-semibold"> <span className="mr-2">{c('Label').t`Two-password mode`}</span> <Info url={getKnowledgeBaseUrl('/single-password')} title={c('Info') .t`Two-password mode requires two passwords: one to sign in to your account and one to decrypt your mailbox. (Advanced)`} /> </label> </SettingsLayoutLeft> <SettingsLayoutRight className="pt-2"> <Toggle loading={loadingUserSettings} checked={!isOnePasswordMode} id="passwordModeToggle" onChange={() => handleChangePassword( isOnePasswordMode ? MODES.SWITCH_TWO_PASSWORD : MODES.SWITCH_ONE_PASSWORD ) } /> </SettingsLayoutRight> </SettingsLayout> {!isOnePasswordMode && ( <SettingsLayout> <SettingsLayoutLeft> <label htmlFor="passwordModeToggle" className="text-semibold"> <span className="mr-2">{c('Label').t`Mailbox password`}</span> <Info url={getKnowledgeBaseUrl('/single-password')} /> </label> </SettingsLayoutLeft> <SettingsLayoutRight> <Button onClick={() => handleChangePassword(MODES.CHANGE_TWO_PASSWORD_MAILBOX_MODE)} > {c('Action').t`Change mailbox password`} </Button> </SettingsLayoutRight> </SettingsLayout> )} </> )} </SettingsSection> </> ); }; export default PasswordsSection;
5,745
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/SettingsLayout.scss
@import '~@proton/styles/scss/lib'; .settings-layout { display: flex; flex-wrap: nowrap; margin-block-end: 1em; @include media('<=small') { flex-direction: column; } &--stack-earlier { // value is made to address shared calendar notification issue (will be more widely addressed soon, this is a test case) @include media('<=#{em(1020, 16)}') { flex-direction: column; } } }
5,746
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/SettingsLayout.tsx
import { ComponentPropsWithoutRef } from 'react'; import clsx from '@proton/utils/clsx'; import './SettingsLayout.scss'; interface Props extends ComponentPropsWithoutRef<'div'> { className?: string; /** * stackEarlier is used when content needs to be stacked earlier than only for mobile * this is a "temporary" option, will be soon revamped with settings responsive refacto */ stackEarlier?: boolean; } const SettingsLayout = ({ className = '', stackEarlier = false, ...rest }: Props) => { return ( <div className={clsx(['settings-layout', stackEarlier && 'settings-layout--stack-earlier', className])} {...rest} /> ); }; export default SettingsLayout;
5,747
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/SettingsLayoutLeft.scss
@import '~@proton/styles/scss/lib'; .settings-layout-left { min-inline-size: em(240); inline-size: em(240); max-inline-size: em(240); padding-block-start: 0.5em; padding-inline-end: 0.5em; &--has-upsell { padding-block-start: 0.2em; } @include media('<=small') { inline-size: 100%; max-inline-size: none; margin-block-end: 0.5em; display: flex; flex-direction: column; } }
5,748
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/SettingsLayoutLeft.tsx
import { ComponentPropsWithoutRef } from 'react'; import clsx from '@proton/utils/clsx'; import './SettingsLayoutLeft.scss'; const SettingsLayoutLeft = ({ className, ...rest }: ComponentPropsWithoutRef<'div'>) => { return <div className={clsx(['settings-layout-left', className])} {...rest} />; }; export default SettingsLayoutLeft;
5,749
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/SettingsLayoutRight.scss
@import '~@proton/styles/scss/lib'; .settings-layout-right { min-inline-size: em(240); &-fixed-size { max-inline-size: em(240); @include media('<=small') { max-inline-size: 100%; } } }
5,750
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/SettingsLayoutRight.tsx
import { ComponentPropsWithoutRef } from 'react'; import clsx from '@proton/utils/clsx'; import './SettingsLayoutRight.scss'; const SettingsLayoutRight = ({ className, ...rest }: ComponentPropsWithoutRef<'div'>) => { return <div className={clsx(['settings-layout-right', className])} {...rest} />; }; export default SettingsLayoutRight;
5,751
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/SettingsPageTitle.tsx
import { HTMLAttributes } from 'react'; import clsx from '@proton/utils/clsx'; const SettingsPageTitle = ({ className, children, ...rest }: HTMLAttributes<HTMLHeadingElement>) => ( <h1 className={clsx([className, 'text-bold'])} {...rest}> {children} </h1> ); export default SettingsPageTitle;
5,752
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/SettingsParagraph.tsx
import { ComponentPropsWithoutRef } from 'react'; import clsx from '@proton/utils/clsx'; import { LearnMore, LearnMoreProps } from '../../components'; interface SettingsParagraphProps extends ComponentPropsWithoutRef<'p'> { learnMoreUrl?: string; learnMoreProps?: Omit<LearnMoreProps, 'url'>; large?: boolean; } const SettingsParagraph = ({ learnMoreUrl, learnMoreProps, className, children, large, ...rest }: SettingsParagraphProps) => { const learnMoreElement = learnMoreUrl ? ( <> <br /> <LearnMore url={learnMoreUrl} {...learnMoreProps} /> </> ) : null; return ( <p className={clsx(['color-weak mt-0 max-w-custom', className])} style={{ '--max-w-custom': large ? '57em' : '43em' }} {...rest} > {children} {learnMoreElement} </p> ); }; export default SettingsParagraph;
5,753
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/SettingsSection.tsx
import { ComponentPropsWithoutRef } from 'react'; import clsx from '@proton/utils/clsx'; const SettingsSection = ({ className, ...rest }: ComponentPropsWithoutRef<'div'>) => { return <div className={clsx(['max-w-custom', className])} style={{ '--max-w-custom': '46em' }} {...rest} />; }; export default SettingsSection;
5,754
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/SettingsSectionExtraWide.tsx
import { ComponentPropsWithoutRef } from 'react'; import clsx from '@proton/utils/clsx'; const SettingsSectionExtraWide = ({ className, ...rest }: ComponentPropsWithoutRef<'div'>) => { return <div className={clsx(['max-w-custom', className])} style={{ '--max-w-custom': '82em' }} {...rest} />; }; export default SettingsSectionExtraWide;
5,755
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/SettingsSectionTitle.tsx
import clsx from '@proton/utils/clsx'; import SubTitle, { SubTitleProps } from '../../components/title/SubTitle'; const SettingsSectionTitle = ({ className, ...rest }: SubTitleProps) => ( <SubTitle className={clsx(className, 'text-bold mb-1')} {...rest} /> ); export default SettingsSectionTitle;
5,756
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/SettingsSectionWide.tsx
import { ComponentPropsWithoutRef } from 'react'; import clsx from '@proton/utils/clsx'; const SettingsSectionWide = ({ className, ...rest }: ComponentPropsWithoutRef<'div'>) => { return <div className={clsx(['max-w-custom', className])} style={{ '--max-w-custom': '69em' }} {...rest} />; }; export default SettingsSectionWide;
5,757
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/TwoFactorSection.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { APPS } from '@proton/shared/lib/constants'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { getHasFIDO2SettingEnabled, getHasTOTPSettingEnabled } from '@proton/shared/lib/settings/twoFactor'; import { getHasFIDO2Support } from '@proton/shared/lib/webauthn/helper'; import { getId } from '@proton/shared/lib/webauthn/id'; import clsx from '@proton/utils/clsx'; import { ButtonGroup, Icon, Info, Toggle, Tooltip, useModalState } from '../../components'; import { useConfig, useNotifications, useUserSettings } from '../../hooks'; import SettingsLayout from './SettingsLayout'; import SettingsLayoutLeft from './SettingsLayoutLeft'; import SettingsLayoutRight from './SettingsLayoutRight'; import SettingsParagraph from './SettingsParagraph'; import SettingsSection from './SettingsSection'; import AddSecurityKeyModal from './fido/AddSecurityKeyModal'; import EditSecurityKeyModal from './fido/EditSecurityKeyModal'; import RemoveSecurityKeyModal from './fido/RemoveSecurityKeyModal'; import { maxSecurityKeyLength } from './fido/constants'; import DisableTOTPModal from './totp/DisableTOTPModal'; import EnableTOTPModal from './totp/EnableTOTPModal'; const defaultTmpRemove = { keys: [], type: 'all' as const }; const TwoFactorSection = () => { const { APP_NAME } = useConfig(); const [userSettings] = useUserSettings(); const { createNotification } = useNotifications(); const [enableTOTPModal, setEnableTOTPModalOpen, renderEnableTOTPModal] = useModalState(); const [disableTOTPModal, setDisableTOTPModalOpen, renderDisableTOTPModal] = useModalState(); const [addSecurityKeyModal, setAddSecurityKeyModal, renderAddSecurityKeyModal] = useModalState(); const [removeSecurityKeyModal, setRemoveSecurityKeyModal, renderRemoveSecurityKeyModal] = useModalState(); const [editSecurityKeyModal, setEditSecurityKeyModal, renderEditSecurityKeyModal] = useModalState(); const [tmpRemove, setTmpRemove] = useState<{ keys: { name: string; id: string }[]; type: 'all' | 'single' }>( defaultTmpRemove ); const [tmpEdit, setTmpEdit] = useState<{ name: string; id: string } | undefined>(undefined); const hasTOTPEnabled = getHasTOTPSettingEnabled(userSettings); const hasFIDO2Enabled = getHasFIDO2SettingEnabled(userSettings); const registeredKeys = userSettings['2FA']?.RegisteredKeys || []; const canEnableFido2 = hasTOTPEnabled; const canDisableTOTP = hasTOTPEnabled && !registeredKeys.length; const handleChangeTOTP = () => { if (hasTOTPEnabled) { if (!canDisableTOTP) { createNotification({ text: c('fido2: Error').t`Please disable 2FA via security key before disabling TOTP`, type: 'error', }); return; } setDisableTOTPModalOpen(true); } else { setEnableTOTPModalOpen(true); } }; const handleChangeKey = () => { const keys = registeredKeys.map((RegisteredKey) => ({ id: getId(RegisteredKey), name: RegisteredKey.Name })); if (hasFIDO2Enabled && keys.length) { setTmpRemove({ keys, type: 'all' }); setRemoveSecurityKeyModal(true); return; } setAddSecurityKeyModal(true); }; const twoFactorAuthLink = APP_NAME === APPS.PROTONVPN_SETTINGS ? 'https://protonvpn.com/support/two-factor-authentication' : getKnowledgeBaseUrl('/two-factor-authentication-2fa'); const hasSecurityKeySupport = getHasFIDO2Support(APP_NAME, location.hostname); return ( <SettingsSection> {renderEnableTOTPModal && <EnableTOTPModal {...enableTOTPModal} />} {renderDisableTOTPModal && <DisableTOTPModal {...disableTOTPModal} />} <SettingsParagraph> {c('Info') .t`Add another layer of security to your account. You’ll need to verify yourself with 2FA every time you sign in.`} </SettingsParagraph> <SettingsLayout> <SettingsLayoutLeft> <label htmlFor="twoFactorToggle" className="text-semibold"> <span className="mr-2">{c('Label').t`Authenticator app`}</span> <Info url={twoFactorAuthLink} title={c('Info') .t`Verify your identity with a time-based one-time password from an authenticator app`} /> </label> </SettingsLayoutLeft> <SettingsLayoutRight className="pt-2"> <Toggle checked={hasTOTPEnabled} id="twoFactorToggle" onChange={handleChangeTOTP} /> </SettingsLayoutRight> </SettingsLayout> {hasSecurityKeySupport && ( <> {renderAddSecurityKeyModal && <AddSecurityKeyModal {...addSecurityKeyModal} />} {renderRemoveSecurityKeyModal && tmpRemove.keys.length && ( <RemoveSecurityKeyModal keys={tmpRemove.keys} type={tmpRemove.type} {...removeSecurityKeyModal} onExit={() => { removeSecurityKeyModal.onExit(); setTmpRemove(defaultTmpRemove); }} /> )} {renderEditSecurityKeyModal && tmpEdit && ( <EditSecurityKeyModal id={tmpEdit.id} name={tmpEdit.name} {...editSecurityKeyModal} onExit={() => { editSecurityKeyModal.onExit(); setTmpEdit(undefined); }} /> )} <SettingsLayout> <SettingsLayoutLeft> <label htmlFor="twoFactorKeyToggle" className="text-semibold"> <span className={clsx(['mr-2', !canEnableFido2 && 'color-weak'])}> {c('fido2: Info').t`Security key`} </span> <Info url={twoFactorAuthLink} title={c('fido2: Info') .t`Verify your identity with a physical U2F or FIDO2 security key`} /> </label> </SettingsLayoutLeft> <SettingsLayoutRight className="pt-2"> <Tooltip title={ !canEnableFido2 ? c('fido2: Info') .t`To turn on 2FA via security key, you'll need to activate 2FA via authenticator app` : '' } > <span className="inline-flex"> <Toggle checked={hasFIDO2Enabled} id="twoFactorKeyToggle" onChange={handleChangeKey} disabled={!canEnableFido2} /> </span> </Tooltip> </SettingsLayoutRight> </SettingsLayout> {registeredKeys.length > 0 && ( <div className="mb-4"> <div> <Button disabled={registeredKeys.length >= maxSecurityKeyLength} onClick={() => { setAddSecurityKeyModal(true); }} className="flex flex-nowrap flex-align-items-center" > <Icon name="plus" className="mr-2" /> {c('fido2: Action').t`Add security key`} </Button> </div> <div className="mt-4 w-full"> <div className="text-bold pb-2 border-bottom"> {c('fido2: Title').t`Registered security keys`} </div> {registeredKeys.map((registeredKey) => { const id = getId(registeredKey); return ( <div key={id} className="flex flex-align-items-center py-2 border-bottom"> <div className="flex-item-fluid text-break mr-2">{registeredKey.Name}</div> <ButtonGroup size="small"> <Button icon onClick={() => { setTmpEdit({ id, name: registeredKey.Name, }); setEditSecurityKeyModal(true); }} > <Icon name="pen" /> </Button> <Button icon onClick={() => { setTmpRemove({ keys: [{ id, name: registeredKey.Name }], type: 'single', }); setRemoveSecurityKeyModal(true); }} > <Icon name="trash" /> </Button> </ButtonGroup> </div> ); })} </div> </div> )} </> )} </SettingsSection> ); }; export default TwoFactorSection;
5,758
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/UpgradeBanner.tsx
import { ReactNode } from 'react'; import { c } from 'ttag'; import { ButtonLike, Card } from '@proton/atoms'; import { PLANS } from '@proton/shared/lib/constants'; import { addUpsellPath } from '@proton/shared/lib/helpers/upsell'; import { Audience } from '@proton/shared/lib/interfaces'; import clsx from '@proton/utils/clsx'; import { SettingsLink } from '../../components'; interface Props { children: ReactNode; className?: string; audience?: Audience; free?: boolean; upsellPath?: string; } const UpgradeBanner = ({ free, className, children, audience, upsellPath }: Props) => { return ( <Card className={clsx(['flex flex-align-items-center', className])} rounded> <p className="m-0 mr-8 flex-item-fluid">{children}</p> <ButtonLike as={SettingsLink} path={(() => { if (!free && audience === Audience.B2B) { return addUpsellPath(`/dashboard?plan=${PLANS.BUNDLE_PRO}&target=compare`, upsellPath); } if (audience === Audience.B2B) { return addUpsellPath('/upgrade?business', upsellPath); } return addUpsellPath('/upgrade', upsellPath); })()} color="norm" className="mt-auto" aria-label={c('Action').t`Upgrade your plan`} >{c('Action').t`Upgrade`}</ButtonLike> </Card> ); }; export default UpgradeBanner;
5,759
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/UsernameSection.tsx
import { useState } from 'react'; import { useLocation } from 'react-router-dom'; import { c } from 'ttag'; import { Button, Card, CircleLoader, Href } from '@proton/atoms'; import useLoading from '@proton/hooks/useLoading'; import { postVerifySend } from '@proton/shared/lib/api/verify'; import { getAppHref } from '@proton/shared/lib/apps/helper'; import { stripLocalBasenameFromPathname } from '@proton/shared/lib/authentication/pathnameHelper'; import { ADDRESS_TYPE, APPS, APP_NAMES, BRAND_NAME, CALENDAR_SHORT_APP_NAME, MAIL_APP_NAME, MAIL_SHORT_APP_NAME, SETUP_ADDRESS_PATH, SSO_PATHS, } from '@proton/shared/lib/constants'; import { getIsAddressEnabled } from '@proton/shared/lib/helpers/address'; import { wait } from '@proton/shared/lib/helpers/promise'; import { stripLeadingAndTrailingSlash } from '@proton/shared/lib/helpers/string'; import { Address, AddressConfirmationState, SessionRecoveryState, UserType } from '@proton/shared/lib/interfaces'; import clsx from '@proton/utils/clsx'; import { AppLink, Badge, Icon, Info, InlineLinkButton, Tooltip, useModalState } from '../../components'; import { getVerificationSentText } from '../../containers/recovery/email/VerifyRecoveryEmailModal'; import getBoldFormattedText from '../../helpers/getBoldFormattedText'; import { useAddresses, useApi, useConfig, useIsSessionRecoveryAvailable, useNotifications, useSearchParamsEffect, useSessionRecoveryState, useUser, } from '../../hooks'; import PromotionBanner from '../banner/PromotionBanner'; import EditDisplayNameModal from './EditDisplayNameModal'; import EditExternalAddressModal from './EditExternalAddressModal'; import SettingsLayout from './SettingsLayout'; import SettingsLayoutLeft from './SettingsLayoutLeft'; import SettingsLayoutRight from './SettingsLayoutRight'; import SettingsSection from './SettingsSection'; import mailCalendar from './mail-calendar.svg'; import PasswordResetAvailableCard from './sessionRecovery/statusCards/PasswordResetAvailableCard'; import SessionRecoveryInProgressCard from './sessionRecovery/statusCards/SessionRecoveryInProgressCard'; import unverified from './unverified.svg'; interface Props { app: APP_NAMES; } const UsernameSection = ({ app }: Props) => { const { APP_NAME } = useConfig(); const api = useApi(); const [loading, withLoading] = useLoading(); const { createNotification } = useNotifications(); const [user] = useUser(); const location = useLocation(); const [addresses, loadingAddresses] = useAddresses(); const [tmpAddress, setTmpAddress] = useState<Address>(); const [modalProps, setModalOpen, renderModal] = useModalState(); const [editAddressModalProps, setEditAddressModalOpen, renderEditAddressModal] = useModalState(); const [isSessionRecoveryAvailable] = useIsSessionRecoveryAvailable(); const sessionRecoveryStatus = useSessionRecoveryState(); const primaryAddress = addresses?.find(getIsAddressEnabled); const BRAND_NAME_TWO = BRAND_NAME; const fromPath = `/${stripLeadingAndTrailingSlash(stripLocalBasenameFromPathname(location.pathname))}`; const handleSendVerificationEmail = async (destination: string) => { await wait(500); await api( postVerifySend({ Type: 'external_email', Destination: destination, }) ); createNotification({ type: 'success', text: getVerificationSentText(destination), }); }; const canEditExternalAddress = user.Type === UserType.EXTERNAL && primaryAddress?.Type === ADDRESS_TYPE.TYPE_EXTERNAL && primaryAddress.ConfirmationState === AddressConfirmationState.CONFIRMATION_NOT_CONFIRMED; useSearchParamsEffect( (params) => { if (!canEditExternalAddress || !primaryAddress) { return; } const actionParam = params.get('action'); if (!actionParam) { return; } if (actionParam === 'edit-email') { params.delete('action'); setTmpAddress(primaryAddress); setEditAddressModalOpen(true); return params; } }, [primaryAddress] ); return ( <> {renderModal && tmpAddress && <EditDisplayNameModal {...modalProps} address={tmpAddress} />} {renderEditAddressModal && tmpAddress && ( <EditExternalAddressModal {...editAddressModalProps} address={tmpAddress} /> )} <SettingsSection> {isSessionRecoveryAvailable && sessionRecoveryStatus === SessionRecoveryState.GRACE_PERIOD && ( <SessionRecoveryInProgressCard className="mb-6" /> )} {isSessionRecoveryAvailable && sessionRecoveryStatus === SessionRecoveryState.INSECURE && ( <PasswordResetAvailableCard className="mb-6" /> )} {user.Type === UserType.EXTERNAL && primaryAddress?.Type === ADDRESS_TYPE.TYPE_EXTERNAL && APP_NAME === APPS.PROTONACCOUNT && ( <div className="mb-6"> <AppLink toApp={APPS.PROTONACCOUNT} to={`${SETUP_ADDRESS_PATH}?to=${APPS.PROTONMAIL}&from=${app}&from-type=settings&from-path=${fromPath}`} className="text-no-decoration" data-testid="get-proton-address" > <PromotionBanner mode="banner" rounded contentCentered={false} icon={<img width="40" src={mailCalendar} alt="" className="flex-item-noshrink" />} description={getBoldFormattedText( c('Info') .t`**Get a ${BRAND_NAME} address** to use all ${BRAND_NAME_TWO} services including ${MAIL_SHORT_APP_NAME} and ${CALENDAR_SHORT_APP_NAME}.` )} cta={ <div className="mr-4"> <Icon name="chevron-right" size={16} /> </div> } /> </AppLink> </div> )} {canEditExternalAddress && ( <Card className="mb-8" rounded bordered={true} background={false}> <div className="h3 text-bold mb-6">{c('Info').t`Secure your ${BRAND_NAME} Account`}</div> <div className="flex gap-4 flex-nowrap flex-align-items-start"> <img className="flex-item-noshrink" width="40" height="40" src={unverified} alt="" /> <div> <div className="mb-2 text-lg text-semibold flex"> <div className="mr-2 text-ellipsis">{primaryAddress.Email}</div> <Badge type="warning">{c('Info').t`Unverified`}</Badge> </div> <div> <div className="mb-2"> {c('Info').t`Increase your account security by verifying your email address.`} </div> <Button color="norm" loading={loading} onClick={() => { withLoading(handleSendVerificationEmail(primaryAddress.Email)); }} > {c('Info').t`Resend verification email`} </Button> </div> </div> </div> </Card> )} <SettingsLayout> <SettingsLayoutLeft> <div className="text-semibold">{c('Label').t`Username`}</div> </SettingsLayoutLeft> <SettingsLayoutRight className="pt-2"> {user.Type === UserType.EXTERNAL && primaryAddress?.Type === ADDRESS_TYPE.TYPE_EXTERNAL ? ( <div> {primaryAddress.ConfirmationState === AddressConfirmationState.CONFIRMATION_CONFIRMED ? ( <div className="flex"> {primaryAddress.Email} <Tooltip title={c('Tooltip').t`Verified email address`} openDelay={0}> <Icon name="checkmark-circle-filled" size={16} className="ml-2 color-success flex-align-self-center" /> </Tooltip> </div> ) : ( <> <div className="flex"> {!canEditExternalAddress ? ( primaryAddress.Email ) : ( <> <span className="mr-2">{primaryAddress.Email}</span> <InlineLinkButton className="mr-1" onClick={() => { setTmpAddress(primaryAddress); setEditAddressModalOpen(true); }} aria-label={c('Action').t`Edit email address`} > {c('Action').t`Edit`} </InlineLinkButton> <Info className="flex-align-self-center" title={c('Info') .t`You can edit this once to ensure the correct email address for verification.`} /> </> )} </div> <div className="flex"> <Icon name="exclamation-circle-filled" size={16} className="mr-1 color-danger flex-align-self-center" /> <span className="color-weak mr-1"> {c('Info').t`Unverified email address.`} </span> </div> </> )} </div> ) : ( user.Name )} </SettingsLayoutRight> </SettingsLayout> {(primaryAddress || loadingAddresses) && ( <SettingsLayout> <SettingsLayoutLeft> <div className="text-semibold">{c('Label').t`Display name`}</div> </SettingsLayoutLeft> <SettingsLayoutRight className="pt-2"> {!primaryAddress || loadingAddresses ? ( <div className="flex flex-nowrap"> <CircleLoader /> </div> ) : ( <div className="flex flex-nowrap"> <div className={clsx( 'text-ellipsis user-select', primaryAddress.DisplayName && 'mr-2' )} > {primaryAddress.DisplayName} </div> <InlineLinkButton onClick={() => { setTmpAddress(primaryAddress); setModalOpen(true); }} aria-label={c('Action').t`Edit display name`} > {c('Action').t`Edit`} </InlineLinkButton> </div> )} </SettingsLayoutRight> </SettingsLayout> )} {APP_NAME === APPS.PROTONVPN_SETTINGS && user.Type === UserType.PROTON && ( <SettingsLayout> <SettingsLayoutLeft> <div className="text-semibold">{c('Label').t`${MAIL_APP_NAME} address`}</div> </SettingsLayoutLeft> <SettingsLayoutRight className="pt-2"> {(() => { if (loadingAddresses) { return ( <div className="flex flex-nowrap"> <CircleLoader /> </div> ); } if (primaryAddress?.Email) { return ( <div className="text-pre-wrap break user-select">{primaryAddress.Email}</div> ); } return ( <Href href={`${getAppHref(SSO_PATHS.SWITCH, APPS.PROTONACCOUNT)}?product=mail`} title={c('Info').t`Sign in to ${MAIL_APP_NAME} to activate your address`} > {c('Link').t`Not activated`} </Href> ); })()} </SettingsLayoutRight> </SettingsLayout> )} </SettingsSection> </> ); }; export default UsernameSection;
5,760
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/changePasswordHelper.ts
import { updatePassword } from '@proton/shared/lib/api/settings'; import { Api } from '@proton/shared/lib/interfaces'; import { srpVerify } from '@proton/shared/lib/srp'; export const handleChangeLoginPassword = async ({ api, newPassword }: { api: Api; newPassword: string }) => { return srpVerify({ api, credentials: { password: newPassword, }, config: updatePassword(), }); };
5,761
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/index.ts
export { default as SettingsLayout } from './SettingsLayout'; export { default as SettingsLayoutLeft } from './SettingsLayoutLeft'; export { default as SettingsLayoutRight } from './SettingsLayoutRight'; export { default as SettingsPageTitle } from './SettingsPageTitle'; export { default as SettingsParagraph } from './SettingsParagraph'; export { default as SettingsSection } from './SettingsSection'; export { default as SettingsSectionWide } from './SettingsSectionWide'; export { default as SettingsSectionExtraWide } from './SettingsSectionExtraWide'; export { default as SettingsSectionTitle } from './SettingsSectionTitle'; export { default as EmailSubscriptionToggles } from './EmailSubscriptionToggles'; export { default as EmailSubscriptionCategories } from './EmailSubscriptionCategories'; export { default as EmailSubscriptionSection } from './EmailSubscriptionSection'; export { default as EditEmailSubscription } from './EditEmailSubscription'; export { default as MozillaInfoPanel } from './MozillaInfoPanel'; export { default as UsernameSection } from './UsernameSection'; export { default as DeleteSection } from './DeleteSection'; export { default as PasswordsSection } from './PasswordsSection'; export { default as TwoFactorSection } from './TwoFactorSection'; export { default as UpgradeBanner } from './UpgradeBanner'; export { default as FamilyPlanSection } from './FamilyPlanSection'; export { default as AccessibilitySection } from './AccessibilitySection'; export { default as AuthSecurityKeyContent } from './fido/AuthSecurityKeyContent'; export { default as TotpInputs } from './totp/TotpInputs'; export * from './constants'; export * from './sessionRecovery';
5,762
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/mail-calendar.svg
<svg width="41" height="40" viewBox="0 0 41 40" fill="none" xmlns="http://www.w3.org/2000/svg"> <g clip-path="url(#clip0_324_8761)"> <g clip-path="url(#clip1_324_8761)"> <path d="M0 13.7778C0 9.48223 3.48223 6 7.77778 6H20.2222C24.5178 6 28 9.48223 28 13.7778V26.2222C28 30.5178 24.5178 34 20.2222 34H7.77778C3.48223 34 0 30.5178 0 26.2222V13.7778Z" fill="white" /> <path fill-rule="evenodd" clip-rule="evenodd" d="M16.3101 18.1095L16.311 18.1102L11.5556 23.3889L5.44446 16.6624V13.7608C5.44446 13.4276 5.8328 13.2453 6.08913 13.4582L12.8691 19.0887C13.5248 19.6332 14.4753 19.6332 15.1309 19.0887L16.3101 18.1095Z" fill="url(#paint0_linear_324_8761)" /> <path d="M18.8889 15.9678L16.3101 18.1094L16.311 18.1102L12.8965 21.1263C12.3149 21.6401 11.4455 21.653 10.8488 21.1568L5.44446 16.6623V25.2854C5.44446 26.263 6.23697 26.9999 7.21457 26.9999L18.8889 26.9999L20.1111 21.5116L18.8889 15.9678Z" fill="url(#paint1_radial_324_8761)" /> <path fill-rule="evenodd" clip-rule="evenodd" d="M18.8889 15.97V27L20.7855 27C21.7631 27 22.5556 26.2075 22.5556 25.2299V13.7608C22.5556 13.4276 22.1672 13.2453 21.9109 13.4582L18.8889 15.97Z" fill="url(#paint2_linear_324_8761)" /> </g> <path d="M25 22C25 20.8954 25.8954 20 27 20H39C40.1046 20 41 20.8954 41 22V32C41 33.1046 40.1046 34 39 34H27C25.8954 34 25 33.1046 25 32V22Z" fill="url(#paint3_linear_324_8761)" /> <path d="M25 22C25 20.8954 25.8954 20 27 20H39C40.1046 20 41 20.8954 41 22V32C41 33.1046 40.1046 34 39 34H27C25.8954 34 25 33.1046 25 32V22Z" fill="url(#paint4_radial_324_8761)" /> <path d="M25 22H36.5C37.3284 22 38 22.6716 38 23.5V34H39C40.1046 34 41 33.1046 41 32V22C41 20.8954 40.1046 20 39 20H27C25.8954 20 25 20.8954 25 22Z" fill="url(#paint5_linear_324_8761)" /> <path d="M29.8833 31.099C31.1073 31.099 32.0523 30.397 32.0523 29.353C32.0523 28.408 31.3863 27.949 30.8733 27.832V27.814C31.2603 27.697 31.8453 27.238 31.8453 26.419C31.8453 25.429 31.0263 24.772 29.8563 24.772C28.3623 24.772 27.7863 25.861 27.7413 26.608H28.9203C28.9743 26.167 29.2713 25.789 29.8473 25.789C30.3423 25.789 30.7203 26.086 30.7203 26.572C30.7203 27.067 30.3423 27.355 29.5953 27.355H29.1723V28.372H29.6853C30.4413 28.372 30.9183 28.66 30.9183 29.209C30.9183 29.731 30.4953 30.082 29.8833 30.082C29.2803 30.082 28.8843 29.713 28.7853 29.227H27.5613C27.6423 30.307 28.5333 31.099 29.8833 31.099Z" fill="white" /> <path d="M32.7198 25.87V27.04L33.9348 26.185V31H35.0778V24.862H34.1688L32.7198 25.87Z" fill="white" /> </g> <defs> <linearGradient id="paint0_linear_324_8761" x1="11.8654" y1="23.482" x2="6.12664" y2="3.54646" gradientUnits="userSpaceOnUse" > <stop stop-color="#E3D9FF" /> <stop offset="1" stop-color="#7341FF" /> </linearGradient> <radialGradient id="paint1_radial_324_8761" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(20.0472 17.3182) scale(17.1039 16.0409)" > <stop offset="0.5561" stop-color="#6D4AFF" /> <stop offset="0.9944" stop-color="#AA8EFF" /> </radialGradient> <linearGradient id="paint2_linear_324_8761" x1="28.0893" y1="35.8386" x2="14.9771" y2="7.43767" gradientUnits="userSpaceOnUse" > <stop offset="0.271" stop-color="#E3D9FF" /> <stop offset="1" stop-color="#7341FF" /> </linearGradient> <linearGradient id="paint3_linear_324_8761" x1="33" y1="14.4067" x2="34.2177" y2="30.766" gradientUnits="userSpaceOnUse" > <stop offset="0.988738" stop-color="#6D4AFF" /> </linearGradient> <radialGradient id="paint4_radial_324_8761" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(35.8966 12.8542) rotate(109.399) scale(24.0163 30.6627)" > <stop offset="0.556057" stop-color="#54B7FF" stop-opacity="0" /> <stop offset="0.994421" stop-color="#54B7FF" /> </radialGradient> <linearGradient id="paint5_linear_324_8761" x1="44" y1="42.75" x2="24.4917" y2="8.64669" gradientUnits="userSpaceOnUse" > <stop stop-color="#C8E8FF" /> <stop offset="0.410661" stop-color="#BDAEFF" /> <stop offset="0.774813" stop-color="#6D4AFF" /> </linearGradient> <clipPath id="clip0_324_8761"> <rect width="41" height="28" fill="white" transform="translate(0 6)" /> </clipPath> <clipPath id="clip1_324_8761"> <rect width="28" height="28" fill="white" transform="translate(0 6)" /> </clipPath> </defs> </svg>
5,763
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/unverified.svg
<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg"> <g clip-path="url(#clip0_183_11316)"> <path d="M20.0003 36C28.837 36 36.0005 28.8366 36.0005 20C36.0005 11.1634 28.837 4 20.0003 4C11.1636 4 4 11.1634 4 20C4 28.8366 11.1636 36 20.0003 36Z" fill="white" /> <path d="M20.0003 36C28.837 36 36.0005 28.8366 36.0005 20C36.0005 11.1634 28.837 4 20.0003 4C11.1636 4 4 11.1634 4 20C4 28.8366 11.1636 36 20.0003 36Z" fill="url(#paint0_linear_183_11316)" fill-opacity="0.2" /> <path fill-rule="evenodd" clip-rule="evenodd" d="M26 16.9326C26 20.2463 23.3137 22.9326 20 22.9326C16.6863 22.9326 14 20.2463 14 16.9326C14 13.6189 16.6863 10.9326 20 10.9326C23.3137 10.9326 26 13.6189 26 16.9326ZM20.0003 36C24.5761 36 28.7032 34.0792 31.6195 31C28.7032 27.9208 24.5761 26 20.0003 26C15.4245 26 11.2973 27.9208 8.38107 31C11.2973 34.0792 15.4245 36 20.0003 36Z" fill="url(#paint1_linear_183_11316)" /> <g opacity="0.3" filter="url(#filter0_f_183_11316)"> <path fill-rule="evenodd" clip-rule="evenodd" d="M34.9706 14.3403C33.3501 10.0564 29.9436 6.65008 25.6596 5.02979C25.2365 5.93145 25 6.93813 25 8.00003C25 11.866 28.134 15 32 15C33.0621 15 34.0689 14.7635 34.9706 14.3403Z" fill="#1C008A" /> </g> <path d="M40 7C40 3.13401 36.866 2.73984e-07 33 6.11959e-07C29.134 9.49935e-07 26 3.13401 26 7C26 10.866 29.134 14 33 14C36.866 14 40 10.866 40 7Z" fill="url(#paint2_linear_183_11316)" /> <path d="M32 2.98148C32 2.43942 32.4394 2 32.9815 2C33.5235 2 33.963 2.43942 33.963 2.98148V7.01852C33.963 7.56058 33.5235 8 32.9815 8C32.4394 8 32 7.56058 32 7.01852V2.98148Z" fill="white" /> <circle cx="33" cy="10" r="1" fill="white" /> </g> <defs> <filter id="filter0_f_183_11316" x="21" y="1.02979" width="17.9706" height="17.9702" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB" > <feFlood flood-opacity="0" result="BackgroundImageFix" /> <feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape" /> <feGaussianBlur stdDeviation="2" result="effect1_foregroundBlur_183_11316" /> </filter> <linearGradient id="paint0_linear_183_11316" x1="21.5388" y1="-6.76923" x2="30.4617" y2="34.1539" gradientUnits="userSpaceOnUse" > <stop stop-color="#ECAAFF" /> <stop offset="1" stop-color="#6A48F6" /> </linearGradient> <linearGradient id="paint1_linear_183_11316" x1="21.1175" y1="2.49648" x2="28.602" y2="34.3175" gradientUnits="userSpaceOnUse" > <stop stop-color="#ECAAFF" /> <stop offset="1" stop-color="#6A48F6" /> </linearGradient> <linearGradient id="paint2_linear_183_11316" x1="33" y1="1.40493" x2="33" y2="19.5846" gradientUnits="userSpaceOnUse" > <stop stop-color="#FA5284" /> <stop offset="1" stop-color="#DC3251" /> </linearGradient> <clipPath id="clip0_183_11316"> <rect width="40" height="40" fill="white" /> </clipPath> </defs> </svg>
5,764
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/account
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/constants/email-subscriptions.ts
import { c } from 'ttag'; import { BRAND_NAME, CALENDAR_SHORT_APP_NAME, DRIVE_APP_NAME, MAIL_APP_NAME, NEWSLETTER_SUBSCRIPTIONS_BITS, PASS_APP_NAME, VPN_APP_NAME, } from '@proton/shared/lib/constants'; import { toMap } from '@proton/shared/lib/helpers/object'; export interface EmailSubscription { id: string; title: string; flag: NEWSLETTER_SUBSCRIPTIONS_BITS; frequency?: string; tooltip?: string; } export const getEmailSubscriptions: () => EmailSubscription[] = () => [ { id: 'announcements', flag: NEWSLETTER_SUBSCRIPTIONS_BITS.ANNOUNCEMENTS, title: c('Label for news').t`${BRAND_NAME} important announcements`, frequency: c('Frequency of news').t`(2-4 emails per year)`, }, { id: 'features', flag: NEWSLETTER_SUBSCRIPTIONS_BITS.FEATURES, title: c('Label for news').t`${BRAND_NAME} product announcements`, frequency: c('Frequency of news').t`(1-2 emails per month)`, }, { id: 'business', flag: NEWSLETTER_SUBSCRIPTIONS_BITS.BUSINESS, title: c('Label for news').t`${BRAND_NAME} for Business newsletter`, frequency: c('Frequency of news').t`(1 email per month)`, }, { id: 'newsletter', flag: NEWSLETTER_SUBSCRIPTIONS_BITS.NEWSLETTER, title: c('Label for news').t`${BRAND_NAME} newsletter`, frequency: c('Frequency of news').t`(1 email per month)`, tooltip: c('Tooltip for news') .t`Get the latest privacy news and what is going on in the ${BRAND_NAME} universe`, }, { id: 'beta', flag: NEWSLETTER_SUBSCRIPTIONS_BITS.BETA, title: c('Label for news').t`${BRAND_NAME} beta announcements`, frequency: c('Frequency of news').t`(1-2 emails per month)`, }, { id: 'offers', flag: NEWSLETTER_SUBSCRIPTIONS_BITS.OFFERS, title: c('Label for news').t`${BRAND_NAME} offers and promotions`, frequency: c('Frequency of news').t`(1 email per quarter)`, }, { id: 'onboarding', flag: NEWSLETTER_SUBSCRIPTIONS_BITS.ONBOARDING, title: c('Label for news').t`${BRAND_NAME} welcome emails`, frequency: c('Frequency of news').t`(during your first month)`, }, { id: 'user_survey', flag: NEWSLETTER_SUBSCRIPTIONS_BITS.USER_SURVEY, title: c('Label for news').t`${BRAND_NAME} user survey`, tooltip: c('Tooltip for news').t`Participate in surveys to improve ${BRAND_NAME} services`, }, { id: 'news_product_inbox', flag: NEWSLETTER_SUBSCRIPTIONS_BITS.INBOX_NEWS, title: c('Label for news').t`${MAIL_APP_NAME} and ${CALENDAR_SHORT_APP_NAME} new features`, frequency: c('Frequency of news').t`(1 email per month)`, }, { id: 'news_product_drive', flag: NEWSLETTER_SUBSCRIPTIONS_BITS.DRIVE_NEWS, title: c('Label for news').t`${DRIVE_APP_NAME} product updates`, frequency: c('Frequency of news').t`(4-6 emails per year)`, }, { id: 'news_product_pass', flag: NEWSLETTER_SUBSCRIPTIONS_BITS.PASS_NEWS, title: c('Label for news').t`${PASS_APP_NAME} product updates`, frequency: c('Frequency of news').t`(4-6 emails per year)`, }, { id: 'news_product_vpn', flag: NEWSLETTER_SUBSCRIPTIONS_BITS.VPN_NEWS, title: c('Label for news').t`${VPN_APP_NAME} product updates`, frequency: c('Frequency of news').t`(4-6 emails per year)`, }, ]; export const getEmailSubscriptionsMap = () => toMap(getEmailSubscriptions(), 'flag');
5,765
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/account
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/constants/index.ts
export * from './email-subscriptions';
5,766
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/account
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/fido/AddSecurityKeyModal.tsx
import { FormEvent, useRef, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import RegisterSecurityKeyContent from '@proton/components/containers/account/fido/RegisterSecurityKeyContent'; import { useLoading } from '@proton/hooks'; import { getSecurityKeyChallenge, registerSecurityKey } from '@proton/shared/lib/api/settings'; import { lockSensitiveSettings, unlockPasswordChanges } from '@proton/shared/lib/api/user'; import { requiredValidator } from '@proton/shared/lib/helpers/formValidators'; import { captureMessage } from '@proton/shared/lib/helpers/sentry'; import { RegisterCredentialsPayload, getCreatePayload } from '@proton/shared/lib/webauthn/create'; import { RegisterCredentials } from '@proton/shared/lib/webauthn/interface'; import physicalKeyRegistered from '@proton/styles/assets/img/illustrations/physical-key-registered.svg'; import { Checkbox, Form, Info, InputFieldTwo, ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, ModalProps, useFormErrors, } from '../../../components'; import { useApi, useErrorHandler, useEventManager } from '../../../hooks'; import AuthModal from '../../password/AuthModal'; import { maxSecurityKeyNameLength } from './constants'; enum Steps { Tutorial, Name, Ok, } const RegisteredContent = () => { return ( <> <div className="flex flex-justify-center mt-4 mb-6 relative"> <img src={physicalKeyRegistered} alt={c('fido2: Info').t`Security key`} /> </div> <div className="text-center">{c('fido2: Info').t`Your two-factor authentication key is ready to use.`}</div> </> ); }; const AddSecurityKeyModal = ({ onClose, ...rest }: ModalProps) => { const [step, setStep] = useState(Steps.Tutorial); const [behind, setBehind] = useState(false); const [loading, withLoading] = useLoading(); const normalApi = useApi(); const errorHandler = useErrorHandler(); const silentApi = <T,>(config: any) => normalApi<T>({ ...config, silence: true }); const { call } = useEventManager(); const { validator, onFormSubmit, reset } = useFormErrors(); const [name, setName] = useState(''); const [fidoError, setFidoError] = useState(false); const registrationPayloadRef = useRef<RegisterCredentialsPayload>(); const [allowPlatformKeys, setAllowPlatformKeys] = useState(false); const getRegistrationPayload = () => { const run = async () => { let response: RegisterCredentials; try { response = await silentApi<RegisterCredentials>(getSecurityKeyChallenge(!allowPlatformKeys)); } catch (e) { errorHandler(e); return; } try { setFidoError(false); setBehind(true); registrationPayloadRef.current = await getCreatePayload(response); setBehind(false); } catch (error) { setFidoError(true); setBehind(false); captureMessage('Security key registration', { level: 'error', extra: { error }, }); // Purposefully logging the error for somewhat easier debugging console.error(error); return; } reset(); setStep(Steps.Name); }; void withLoading(run()); }; const handleRegister = () => { const payload = registrationPayloadRef.current; if (!payload) { throw new Error('Missing payload ref'); } const run = async () => { try { await silentApi(registerSecurityKey({ ...payload, Name: name })); await silentApi(lockSensitiveSettings()); await call(); } catch (e) { errorHandler(e); return; } reset(); setStep(Steps.Ok); }; void withLoading(run()); }; const [authed, setAuthed] = useState(false); if (!authed) { return ( <AuthModal config={unlockPasswordChanges()} {...rest} onCancel={onClose} onSuccess={async () => { setAuthed(true); reset(); }} prioritised2FAItem="totp" /> ); } const handleClose = () => { void silentApi(lockSensitiveSettings()); onClose?.(); }; return ( <Modal as={Form} onSubmit={(event: FormEvent<HTMLFormElement>) => { if (step === Steps.Tutorial) { getRegistrationPayload(); return; } if (!onFormSubmit(event.currentTarget)) { return; } if (step === Steps.Name) { handleRegister(); } }} onClose={handleClose} size="small" behind={behind} {...rest} > <ModalHeader title={(() => { if (step === Steps.Ok) { return c('fido2: Title').t`Security key registered`; } if (step === Steps.Name) { return c('fido2: Title').t`Name your security key`; } return c('fido2: Title').t`Register your security key`; })()} /> <ModalContent> {step === Steps.Tutorial && ( <RegisterSecurityKeyContent error={fidoError} checkbox={ <> <Checkbox id="allow-platform-keys" checked={allowPlatformKeys} onChange={(e) => setAllowPlatformKeys(e.target.checked)} > {c('fido2: Info').t`Allow platform keys`} </Checkbox> <Info className="ml-1" title={c('fido2: Info') .t`Allows you to register built-in security keys (like Windows Hello, Face ID, Touch ID, or internal TPMs)`} /> </> } /> )} {step === Steps.Name && ( <> <InputFieldTwo autoFocus maxLength={maxSecurityKeyNameLength} label={c('fido2: Label').t`Key name`} error={validator([requiredValidator(name)])} value={name} onValue={setName} /> <div>{c('fido2: Info').t`Add a name to identify your security key with.`}</div> </> )} {step === Steps.Ok && <RegisteredContent />} </ModalContent> {step === Steps.Ok ? ( <ModalFooter> <div /> <Button onClick={handleClose} color="norm"> {c('Action').t`Done`} </Button> </ModalFooter> ) : ( <ModalFooter> <Button onClick={handleClose} disabled={loading}> {c('Action').t`Cancel`} </Button> <Button loading={loading} type="submit" color="norm"> {c('Action').t`Continue`} </Button> </ModalFooter> )} </Modal> ); }; export default AddSecurityKeyModal;
5,767
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/account
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/fido/AuthSecurityKeyContent.tsx
import { c } from 'ttag'; import { Href } from '@proton/atoms'; import { BRAND_NAME } from '@proton/shared/lib/constants'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import physicalKey from '@proton/styles/assets/img/illustrations/physical-key.svg'; import Banner, { BannerBackgroundColor } from '../../../components/banner/Banner'; const AuthSecurityKeyContent = ({ error }: { error?: boolean }) => { return ( <> <div className="flex flex-justify-center mt-4 mb-6"> <img src={physicalKey} alt={c('fido2: Info').t`Security key`} /> </div> <div> {c('fido2: Info').t`Insert a security key linked to your ${BRAND_NAME} Account.`} <br /> <Href href={getKnowledgeBaseUrl('/two-factor-authentication-2fa')}>{c('Info').t`Learn more`}</Href> </div> {error && ( <div className="mt-4"> <Banner icon="exclamation-circle" backgroundColor={BannerBackgroundColor.WEAK}> {c('fido2: Error') .t`Something went wrong authenticating with your security key. Please try again.`} </Banner> </div> )} </> ); }; export default AuthSecurityKeyContent;
5,768
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/account
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/fido/EditSecurityKeyModal.tsx
import { FormEvent, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { renameSecurityKey } from '@proton/shared/lib/api/settings'; import { requiredValidator } from '@proton/shared/lib/helpers/formValidators'; import { Form, InputFieldTwo, ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, ModalProps, useFormErrors, } from '../../../components'; import { useApi, useErrorHandler, useEventManager, useNotifications } from '../../../hooks'; import { maxSecurityKeyNameLength } from './constants'; interface Props extends ModalProps { id: string; name: string; } const EditSecurityKeyModal = ({ id, name, onClose, ...rest }: Props) => { const [loading, withLoading] = useLoading(); const normalApi = useApi(); const errorHandler = useErrorHandler(); const silentApi = <T,>(config: any) => normalApi<T>({ ...config, silence: true }); const { call } = useEventManager(); const { validator, onFormSubmit } = useFormErrors(); const [newName, setNewName] = useState(name); const { createNotification } = useNotifications(); const handleUpdate = () => { const run = async () => { try { await silentApi(renameSecurityKey(id, { Name: newName })); await call(); createNotification({ text: c('fido2: Info').t`Security key updated`, }); onClose?.(); } catch (e) { errorHandler(e); return; } }; withLoading(run()); }; return ( <Modal as={Form} onSubmit={(event: FormEvent<HTMLFormElement>) => { if (!onFormSubmit(event.currentTarget)) { return; } handleUpdate(); }} onClose={onClose} size="small" {...rest} > <ModalHeader title={c('fido2: Title').t`Name your security key`} /> <ModalContent> <InputFieldTwo autoFocus maxLength={maxSecurityKeyNameLength} label={c('fido2: Label').t`Key name`} error={validator([requiredValidator(newName)])} value={newName} onValue={setNewName} /> </ModalContent> <ModalFooter> <Button onClick={onClose} disabled={loading}> {c('Action').t`Cancel`} </Button> <Button loading={loading} type="submit" color="norm"> {c('Action').t`Save`} </Button> </ModalFooter> </Modal> ); }; export default EditSecurityKeyModal;
5,769
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/account
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/fido/RegisterSecurityKeyContent.tsx
import { ReactNode } from 'react'; import { c } from 'ttag'; import { CircleLoader } from '@proton/atoms'; import physicalKey from '@proton/styles/assets/img/illustrations/physical-key.svg'; import Banner, { BannerBackgroundColor } from '../../../components/banner/Banner'; interface Props { loading?: boolean; error?: boolean; checkbox: ReactNode; } const RegisterSecurityKeyContent = ({ loading, error, checkbox }: Props) => { return ( <> <div className="flex flex-justify-center mt-4 mb-6 relative"> {loading && ( <div className="text-center absolute absolute-center"> <CircleLoader className="color-primary" /> </div> )} <img className={loading ? 'visibility-hidden' : undefined} src={physicalKey} alt={c('fido2: Info').t`Security key`} /> </div> <div>{c('fido2: Info').t`Insert your security key into your device's USB port.`}</div> {checkbox && <div className="mt-2">{checkbox}</div>} {error && ( <div className="mt-4"> <Banner icon="exclamation-circle" backgroundColor={BannerBackgroundColor.WEAK}> {c('fido2: Error').t`Something went wrong registering your security key. Please try again.`} </Banner> </div> )} </> ); }; export default RegisterSecurityKeyContent;
5,770
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/account
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/fido/RemoveSecurityKeyModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { removeSecurityKey } from '@proton/shared/lib/api/settings'; import { lockSensitiveSettings, unlockPasswordChanges } from '@proton/shared/lib/api/user'; import noop from '@proton/utils/noop'; import { ModalProps, Prompt, useModalState } from '../../../components'; import { useApi, useEventManager, useNotifications } from '../../../hooks'; import AuthModal from '../../password/AuthModal'; interface Key { id: string; name: string; } interface Props extends ModalProps { type: 'single' | 'all'; keys: Key[]; } const RemoveSecurityKeyModal = ({ onClose, type, keys, ...rest }: Props) => { const [loading, withLoading] = useLoading(); const api = useApi(); const { call } = useEventManager(); const [authModalProps, setAuthModalOpen, renderAuthModal] = useModalState(); const { createNotification } = useNotifications(); const name = ( <span className="text-bold text-break" key="name"> {keys[0].name} </span> ); return ( <> {renderAuthModal && ( <AuthModal config={unlockPasswordChanges()} {...authModalProps} onCancel={undefined} onSuccess={async () => { await Promise.all( keys.map((key) => { return api(removeSecurityKey(key.id)).catch(noop); }) ); await api(lockSensitiveSettings()); await withLoading( call().then(() => { if (type === 'single') { createNotification({ text: c('fido2: Info').t`Security key removed` }); } else if (type === 'all') { createNotification({ text: c('fido2: Info').t`2FA via security key disabled` }); } onClose?.(); }) ); }} /> )} <Prompt {...rest} title={ type === 'all' ? c('fido2: Title').t`Disable 2FA via security key?` : c('fido2: Title').t`Delete security key?` } onClose={onClose} buttons={[ <Button loading={loading} color="danger" onClick={() => { setAuthModalOpen(true); }} > {type === 'all' && c('Action').t`Disable`} {type === 'single' && c('fido2: Action').t`Delete key`} </Button>, <Button disabled={loading} onClick={onClose}> {c('Action').t`Cancel`} </Button>, ]} > {type === 'all' && c('fido2: Info').t`This will delete all security keys linked to your account.`} {type === 'single' && c('fido2: Info').jt`Are you sure you want to delete security key ${name}?`} </Prompt> </> ); }; export default RemoveSecurityKeyModal;
5,771
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/account
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/fido/constants.ts
export const maxSecurityKeyNameLength = 128; export const maxSecurityKeyLength = 10;
5,772
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/account
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/sessionRecovery/ConfirmSessionRecoveryCancellationModal.tsx
import { useEffect, useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import useLoading from '@proton/hooks/useLoading'; import metrics, { observeApiError } from '@proton/metrics'; import { abortSessionRecovery } from '@proton/shared/lib/api/sessionRecovery'; import { requiredValidator } from '@proton/shared/lib/helpers/formValidators'; import { srpAuth } from '@proton/shared/lib/srp'; import noop from '@proton/utils/noop'; import { Form, InputFieldTwo, ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, ModalProps, PasswordInputTwo, useFormErrors, } from '../../../components'; import { useApi, useEventManager, useNotifications, useUser } from '../../../hooks'; import { useSessionRecoveryLocalStorage } from './SessionRecoveryLocalStorageManager'; interface Props extends ModalProps { onBack?: () => void; } const ConfirmSessionRecoveryCancellationModal = ({ onBack, onClose, ...rest }: Props) => { const api = useApi(); const [user] = useUser(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const { validator, onFormSubmit } = useFormErrors(); const [password, setPassword] = useState(''); const [submitting, withSubmitting] = useLoading(); const { dismissSessionRecoveryCancelled } = useSessionRecoveryLocalStorage(); useEffect(() => { metrics.core_session_recovery_cancellation_modal_load_total.increment({ step: 'confirm' }); }, []); const handleSubmit = () => { if (submitting || !onFormSubmit()) { return; } const run = async () => { try { await srpAuth({ api, credentials: { password, }, config: abortSessionRecovery(), }); await call(); dismissSessionRecoveryCancelled(); createNotification({ text: c('session_recovery:cancellation:notification').t`Password reset cancelled`, showCloseButton: false, }); metrics.core_session_recovery_abort_total.increment({ status: 'success', }); onClose?.(); } catch (error) { observeApiError(error, (status) => metrics.core_session_recovery_abort_total.increment({ status, }) ); } }; void withSubmitting(run()); }; const handleClose = submitting ? noop : onClose; return ( <Modal as={Form} onSubmit={handleSubmit} onClose={handleClose} disableCloseOnEscape={!!onBack} size="small" {...rest} > <ModalHeader title={c('session_recovery:cancellation:title').t`Cancel password reset?`} subline={user.Email} hasClose={!onBack} /> <ModalContent> <p>{c('session_recovery:cancellation:info') .t`Enter your current password to cancel the password reset process. No other changes will take effect.`}</p> <InputFieldTwo id="password" bigger label={c('Label').t`Password`} error={validator([requiredValidator(password)])} as={PasswordInputTwo} disableChange={submitting} autoComplete="current-password" value={password} onValue={setPassword} autoFocus /> </ModalContent> <ModalFooter> {onBack ? ( <Button onClick={onBack} disabled={submitting}>{c('Action').t`Back`}</Button> ) : ( <Button onClick={onClose} disabled={submitting}>{c('Action').t`Close`}</Button> )} <Button color="danger" type="submit" loading={submitting}> {c('session_recovery:cancellation:action').t`Cancel password reset`} </Button> </ModalFooter> </Modal> ); }; export default ConfirmSessionRecoveryCancellationModal;
5,773
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/account
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/sessionRecovery/InitiateSessionRecoveryModal.tsx
import { useEffect, useState } from 'react'; import { c } from 'ttag'; import { Button, ButtonLike } from '@proton/atoms'; import getBoldFormattedText from '@proton/components/helpers/getBoldFormattedText'; import useLoading from '@proton/hooks/useLoading'; import metrics, { observeApiError } from '@proton/metrics'; import { initiateSessionRecovery } from '@proton/shared/lib/api/sessionRecovery'; import noop from '@proton/utils/noop'; import { ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, ModalProps, SettingsLink, } from '../../../components'; import { useApi, useEventManager, useHasRecoveryMethod, useNotifications, useUser } from '../../../hooks'; import SessionRecoveryResetConfirmedPrompt from './SessionRecoveryResetConfirmedPrompt'; import sessionRecoveryIllustration from './session-recovery-illustration.svg'; enum STEP { PROMPT, RESET_CONFIRMED, } interface Props extends ModalProps { confirmedStep?: boolean; } const InitiateSessionRecoveryModal = ({ confirmedStep = false, onClose, ...rest }: Props) => { const [user] = useUser(); const api = useApi(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const [hasRecoveryMethod] = useHasRecoveryMethod(); const [step, setStep] = useState<STEP>(STEP.PROMPT); const [submitting, withSubmitting] = useLoading(); useEffect(() => { const metricsStep = (() => { if (step === STEP.PROMPT) { return 'prompt'; } if (step === STEP.RESET_CONFIRMED) { return 'confirmed'; } })(); if (!metricsStep) { return; } metrics.core_session_recovery_initiation_modal_load_total.increment({ step: metricsStep, }); }, [step]); if (step === STEP.RESET_CONFIRMED) { return <SessionRecoveryResetConfirmedPrompt open={rest.open} onClose={onClose} />; } const handleInitiateSessionRecovery = async () => { try { await api(initiateSessionRecovery()); await call(); createNotification({ text: c('session_recovery:initiation:notification').t`Password reset confirmed`, showCloseButton: false, }); metrics.core_session_recovery_initiation_total.increment({ status: 'success', }); if (confirmedStep) { setStep(STEP.RESET_CONFIRMED); } else { onClose?.(); } } catch (error) { observeApiError(error, (status) => metrics.core_session_recovery_initiation_total.increment({ status, }) ); } }; const handleClose = submitting ? noop : onClose; return ( <Modal onClose={handleClose} {...rest}> <ModalHeader title={c('session_recovery:initiation:title').t`Request password reset?`} subline={user.Email} /> <ModalContent> <div className="flex flex-justify-center"> <img src={sessionRecoveryIllustration} alt="" /> </div> <p> {getBoldFormattedText( c('session_recovery:initiation:info') .t`For security reasons, you’ll have to wait **72 hours** before you can change your password.` )} </p> {hasRecoveryMethod && ( <p> {getBoldFormattedText( c('session_recovery:initiation:info') .t`If you have a **recovery method** set up, try account recovery instead. This will allow you to change your password straight away.` )} </p> )} </ModalContent> <ModalFooter> {hasRecoveryMethod ? ( <ButtonLike as={SettingsLink} path="/recovery" onClick={onClose} disabled={submitting}> {c('session_recovery:initiation:action').t`Use recovery method`} </ButtonLike> ) : ( <Button onClick={onClose}>{c('Action').t`Cancel`}</Button> )} <Button onClick={() => withSubmitting(handleInitiateSessionRecovery())} loading={submitting} color="danger" > {c('session_recovery:initiation:action').t`Request password reset`} </Button> </ModalFooter> </Modal> ); }; export default InitiateSessionRecoveryModal;
5,774
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/account
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/sessionRecovery/PasswordResetAvailableAccountModal.tsx
import { ReactNode, useEffect, useState } from 'react'; import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms'; import { useIsSessionRecoveryInitiatedByCurrentSession, useSessionRecoveryInsecureTimeRemaining, } from '@proton/components/hooks/useSessionRecovery'; import metrics, { observeApiError } from '@proton/metrics'; import { consumeSessionRecovery } from '@proton/shared/lib/api/sessionRecovery'; import { lockSensitiveSettings } from '@proton/shared/lib/api/user'; import innerMutatePassword from '@proton/shared/lib/authentication/mutate'; import { BRAND_NAME } from '@proton/shared/lib/constants'; import { confirmPasswordValidator, passwordLengthValidator, requiredValidator, } from '@proton/shared/lib/helpers/formValidators'; import { generateKeySaltAndPassphrase, getHasMigratedAddressKeys } from '@proton/shared/lib/keys'; import { getArmoredPrivateUserKeys, getEncryptedArmoredOrganizationKey } from '@proton/shared/lib/keys/changePassword'; import { srpVerify } from '@proton/shared/lib/srp'; import noop from '@proton/utils/noop'; import { Form, InputFieldTwo, ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, ModalProps, PasswordInputTwo, useFormErrors, } from '../../../components'; import { useApi, useAuthentication, useErrorHandler, useEventManager, useGetAddresses, useGetOrganizationKeyRaw, useGetUserKeys, useNotifications, useUser, } from '../../../hooks'; import ConfirmSessionRecoveryCancellationModal from './ConfirmSessionRecoveryCancellationModal'; import passwordResetIllustration from './password-reset-illustration.svg'; enum STEP { INFO, PASSWORD, CONFIRM_CANCELLATION, } interface Props extends ModalProps { skipInfoStep?: boolean; } const PasswordResetAvailableAccountModal = ({ skipInfoStep = false, onClose, ...rest }: Props) => { const [user] = useUser(); const api = useApi(); const { call, stop, start } = useEventManager(); const getOrganizationKeyRaw = useGetOrganizationKeyRaw(); const getUserKeys = useGetUserKeys(); const getAddresses = useGetAddresses(); const [loading, setLoading] = useState(false); const { validator, onFormSubmit } = useFormErrors(); const errorHandler = useErrorHandler(); const { createNotification } = useNotifications(); const authentication = useAuthentication(); const [newPassword, setNewPassword] = useState(''); const [confirmPassword, setConfirmPassword] = useState(''); const [step, setStep] = useState(skipInfoStep ? STEP.PASSWORD : STEP.INFO); const isSessionRecoveryInitiatedByCurrentSession = useIsSessionRecoveryInitiatedByCurrentSession(); const timeRemaining = useSessionRecoveryInsecureTimeRemaining(); useEffect(() => { const metricsStep = (() => { if (step === STEP.INFO) { return 'info'; } if (step === STEP.PASSWORD) { return 'password'; } if (step === STEP.CONFIRM_CANCELLATION) { return 'confirm_cancellation'; } })(); if (!metricsStep) { return; } metrics.core_session_recovery_password_reset_available_account_modal_load_total.increment({ step: metricsStep, }); }, [step]); if (timeRemaining === null) { return null; } if (step === STEP.CONFIRM_CANCELLATION) { return ( <ConfirmSessionRecoveryCancellationModal open={rest.open} onClose={onClose} onBack={() => setStep(STEP.INFO)} /> ); } const infoSubline = timeRemaining.inDays === 0 ? c('session_recovery:available:info').ngettext( msgid`This permission expires in ${timeRemaining.inHours} hour`, `This permission expires in ${timeRemaining.inHours} hours`, timeRemaining.inHours ) : c('session_recovery:available:info').ngettext( msgid`This permission expires in ${timeRemaining.inDays} day`, `This permission expires in ${timeRemaining.inDays} days`, timeRemaining.inDays ); const boldEmail = ( <b key="bold-user-email" className="text-break"> {user.Email} </b> ); const boldDaysRemaining = ( <b key="bold-days-remaining"> {timeRemaining.inDays === 0 ? c('session_recovery:available:info').ngettext( msgid`${timeRemaining.inHours} hour`, `${timeRemaining.inHours} hours`, timeRemaining.inHours ) : c('session_recovery:available:info').ngettext( msgid`${timeRemaining.inDays} day`, `${timeRemaining.inDays} days`, timeRemaining.inDays )} </b> ); if (!isSessionRecoveryInitiatedByCurrentSession) { return ( <Modal onClose={onClose} {...rest}> <ModalHeader title={c('session_recovery:available:title').t`Reset your password`} subline={infoSubline} /> <ModalContent> <> <div className="flex flex-justify-center"> <img src={passwordResetIllustration} alt="" /> </div> <div> {c('session_recovery:available:info') .jt`You can now change your password for the account ${boldEmail} freely for ${boldDaysRemaining}.`} </div> <div> {c('session_recovery:available:info') .t`Please go to the signed-in device (in the session where the request was initiated) to change your password.`} </div> </> </ModalContent> <ModalFooter> <Button onClick={() => setStep(STEP.CONFIRM_CANCELLATION)}>{c('session_recovery:available:action') .t`Cancel reset`}</Button> <Button color="norm" onClick={onClose}> {c('Action').t`Ok`} </Button> </ModalFooter> </Modal> ); } const { as, onSubmit, title, subline, content, footer, }: { as?: typeof Form; onSubmit?: () => void; title: string; subline?: string; content: ReactNode; footer: ReactNode; } = (() => { if (step === STEP.INFO) { return { title: c('session_recovery:available:title').t`Reset your password`, subline: infoSubline, content: ( <> <div className="flex flex-justify-center"> <img src={passwordResetIllustration} alt="" /> </div> <div> {c('session_recovery:available:info') .jt`You can now change your password for the account ${boldEmail} freely for ${boldDaysRemaining}.`} </div> </> ), footer: ( <> <Button onClick={() => setStep(STEP.CONFIRM_CANCELLATION)}> {c('session_recovery:available:action').t`Cancel reset`} </Button> <Button color="norm" onClick={() => setStep(STEP.PASSWORD)}> {c('session_recovery:available:action').t`Reset password`} </Button> </> ), }; } if (step === STEP.PASSWORD) { const handleSubmit = async () => { if (!onFormSubmit()) { return; } setLoading(true); try { stop(); const [addresses, userKeysList, organizationKey] = await Promise.all([ getAddresses(), getUserKeys(), user.isAdmin ? getOrganizationKeyRaw() : undefined, ]); /** * This is the case for a user who does not have any keys set-up. * They will be in 2-password mode, but not have any keys. * Changing to one-password mode or mailbox password is not allowed. * It's not handled better because it's a rare case. */ if (userKeysList.length === 0) { throw new Error( c('session_recovery:available:error') .t`Please generate keys before you try to change your password` ); } const hasMigratedAddressKeys = getHasMigratedAddressKeys(addresses); if (!hasMigratedAddressKeys) { throw new Error( c('session_recovery:available:error') .t`Account recovery not available for legacy address keys` ); } const { passphrase: keyPassword, salt: keySalt } = await generateKeySaltAndPassphrase(newPassword); const [armoredUserKeys, armoredOrganizationKey] = await Promise.all([ getArmoredPrivateUserKeys(userKeysList, keyPassword), getEncryptedArmoredOrganizationKey(organizationKey?.privateKey, keyPassword), ]); await srpVerify({ api, credentials: { password: newPassword, }, config: consumeSessionRecovery({ UserKeys: armoredUserKeys, KeySalt: keySalt, OrganizationKey: armoredOrganizationKey, }), }); await innerMutatePassword({ api, authentication, keyPassword, User: user, }); await call(); createNotification({ text: c('session_recovery:available:notification').t`Password saved`, showCloseButton: false, }); void api(lockSensitiveSettings()); metrics.core_session_recovery_consume_total.increment({ status: 'success', }); onClose?.(); } catch (error) { errorHandler(error); observeApiError(error, (status) => metrics.core_session_recovery_consume_total.increment({ status, }) ); } finally { setLoading(false); start(); } }; return { as: Form, onSubmit: handleSubmit, title: c('Title').t`Change password`, content: ( <> <div className="mb-4"> { // translator: full sentence "Proton's encryption technology means that nobody can access your password - not even us." c('Info') .jt`${BRAND_NAME}'s encryption technology means that nobody can access your password - not even us.` } </div> <InputFieldTwo id="newPassword" label={c('Label').t`New password`} error={validator([requiredValidator(newPassword), passwordLengthValidator(newPassword)])} as={PasswordInputTwo} autoFocus autoComplete="new-password" value={newPassword} onValue={(value: string) => setNewPassword(value)} disabled={loading} /> <InputFieldTwo id="confirmPassword" label={c('Label').t`Confirm password`} error={validator([ requiredValidator(confirmPassword), passwordLengthValidator(confirmPassword), confirmPasswordValidator(newPassword, confirmPassword), ])} as={PasswordInputTwo} autoComplete="new-password" value={confirmPassword} onValue={(value: string) => setConfirmPassword(value)} disabled={loading} /> </> ), footer: ( <> {skipInfoStep ? ( <Button disabled={loading} onClick={onClose}> {c('Action').t`Close`} </Button> ) : ( <Button disabled={loading} onClick={() => setStep(STEP.INFO)}> {c('Action').t`Back`} </Button> )} <Button color="norm" loading={loading} type="submit"> {c('Action').t`Save`} </Button> </> ), }; } throw new Error('Step not found'); })(); return ( <Modal as={as} onSubmit={onSubmit} onClose={loading ? noop : onClose} {...rest} size="small"> <ModalHeader title={title} subline={subline} /> <ModalContent>{content}</ModalContent> <ModalFooter>{footer}</ModalFooter> </Modal> ); }; export default PasswordResetAvailableAccountModal;
5,775
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/account
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/sessionRecovery/PasswordResetAvailableProductModal.tsx
import { useState } from 'react'; import { c, msgid } from 'ttag'; import { Button, ButtonLike } from '@proton/atoms'; import { useSessionRecoveryInsecureTimeRemaining } from '@proton/components/hooks/useSessionRecovery'; import { ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, ModalProps, SettingsLink, } from '../../../components'; import { useUser } from '../../../hooks'; import ConfirmSessionRecoveryCancellationModal from './ConfirmSessionRecoveryCancellationModal'; import passwordResetIllustration from './password-reset-illustration.svg'; enum STEP { INFO, CONFIRM_CANCELLATION, } const PasswordResetAvailableProductModal = ({ ...rest }: ModalProps) => { const [user] = useUser(); const [step, setStep] = useState(STEP.INFO); const timeRemaining = useSessionRecoveryInsecureTimeRemaining(); if (timeRemaining === null) { return null; } if (step === STEP.CONFIRM_CANCELLATION) { return ( <ConfirmSessionRecoveryCancellationModal open={rest.open} onClose={rest.onClose} onBack={() => setStep(STEP.INFO)} /> ); } const infoSubline = timeRemaining.inDays === 0 ? c('session_recovery:available:info').ngettext( msgid`This permission expires in ${timeRemaining.inHours} hour`, `This permission expires in ${timeRemaining.inHours} hours`, timeRemaining.inHours ) : c('session_recovery:available:info').ngettext( msgid`This permission expires in ${timeRemaining.inDays} day`, `This permission expires in ${timeRemaining.inDays} days`, timeRemaining.inDays ); const boldEmail = ( <b key="bold-user-email" className="text-break"> {user.Email} </b> ); const boldDaysRemaining = ( <b key="bold-days-remaining"> {timeRemaining.inDays === 0 ? c('session_recovery:available:info').ngettext( msgid`${timeRemaining.inHours} hour`, `${timeRemaining.inHours} hours`, timeRemaining.inHours ) : c('session_recovery:available:info').ngettext( msgid`${timeRemaining.inDays} day`, `${timeRemaining.inDays} days`, timeRemaining.inDays )} </b> ); return ( <Modal {...rest}> <ModalHeader title={c('session_recovery:available:title').t`Reset your password`} subline={infoSubline} /> <ModalContent> <> <div className="flex flex-justify-center"> <img src={passwordResetIllustration} alt="" /> </div> <div> {c('session_recovery:available:info') .jt`You can now change your password for the account ${boldEmail} freely during the next ${boldDaysRemaining}.`} </div> </> </ModalContent> <ModalFooter> <Button onClick={() => setStep(STEP.CONFIRM_CANCELLATION)}>{c('session_recovery:available:action') .t`Cancel reset`}</Button> <ButtonLike as={SettingsLink} path="/account-password?action=session-recovery-reset-password" color="norm" > {c('session_recovery:available:action').t`Set new password`} </ButtonLike> </ModalFooter> </Modal> ); }; export default PasswordResetAvailableProductModal;
5,776
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/account
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/sessionRecovery/SessionRecoveryInProgressModal.tsx
import { ReactNode, useState } from 'react'; import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms'; import { ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, ModalProps, SettingsLink, } from '../../../components'; import { useSessionRecoveryGracePeriodHoursRemaining, useUser } from '../../../hooks'; import ConfirmSessionRecoveryCancellationModal from './ConfirmSessionRecoveryCancellationModal'; import SessionRecoveryInProgressModalIllustration from './SessionRecoveryInProgressModalIllustration'; import { useSessionRecoveryLocalStorage } from './SessionRecoveryLocalStorageManager'; enum STEP { INFO, CONFIRM_CANCELLATION, } const SessionRecoveryInProgressModal = ({ onClose, ...rest }: ModalProps) => { const [user] = useUser(); const [step, setStep] = useState(STEP.INFO); const { confirmSessionRecoveryInProgress } = useSessionRecoveryLocalStorage(); const gracePeriodHoursRemaining = useSessionRecoveryGracePeriodHoursRemaining(); if (!user.AccountRecovery || gracePeriodHoursRemaining === null) { return null; } if (step === STEP.CONFIRM_CANCELLATION) { return ( <ConfirmSessionRecoveryCancellationModal open={rest.open} onClose={onClose} onBack={() => setStep(STEP.INFO)} /> ); } const { title, content, footer }: { title: string; content: ReactNode; footer: ReactNode } = (() => { const boldEmail = ( <> <br /> <b key="bold-user-email" className="text-break"> {user.Email} </b> </> ); if (step === STEP.INFO) { const boldTimeLeft = ( <b key="bold-time-left"> { // translator: Full sentence is "To make sure it’s really you trying to reset your password, we wait 72 hours before approving requests. You can change your password in XX more hours." c('session_recovery:in_progress:info').ngettext( msgid`${gracePeriodHoursRemaining} more hour`, `${gracePeriodHoursRemaining} more hours`, gracePeriodHoursRemaining ) } </b> ); const viewRequest = ( <SettingsLink key="view-request-link" path="/account-password" onClick={onClose}> {c('session_recovery:in_progress:link').t`View request`} </SettingsLink> ); return { title: c('session_recovery:in_progress:title').t`Password reset requested`, content: ( <> <div className="flex flex-justify-center"> <SessionRecoveryInProgressModalIllustration hoursRemaining={gracePeriodHoursRemaining} /> </div> <p> { // translator: Full sentence is "We received a password reset request for account@proton.me." c('session_recovery:in_progress:info') .jt`We received a password reset request for ${boldEmail}.` } <br /> </p> <p> { // translator: Full sentence is "To make sure it’s really you trying to reset your password, we wait 72 hours before approving requests. You can change your password in XX more hours." c('session_recovery:in_progress:info') .jt`To make sure it’s really you trying to reset your password, we wait 72 hours before approving requests. You can change your password in ${boldTimeLeft}. ${viewRequest}` } </p> <p>{c('session_recovery:in_progress:info') .t`If you didn’t ask to reset your password, cancel this request now.`}</p> </> ), footer: ( <> <Button onClick={() => setStep(STEP.CONFIRM_CANCELLATION)}> { // translator: The request here refers to a password reset request. So clicking this button will cancel the password reset request. c('session_recovery:in_progress:action').t`Cancel request` } </Button> <Button color="norm" onClick={() => { confirmSessionRecoveryInProgress(); onClose?.(); }} > {c('session_recovery:in_progress:action').t`Got it`} </Button> </> ), }; } throw new Error(`Step ${step} not implemented`); })(); return ( <Modal onClose={onClose} {...rest}> <ModalHeader title={title} /> <ModalContent>{content}</ModalContent> <ModalFooter>{footer}</ModalFooter> </Modal> ); }; export default SessionRecoveryInProgressModal;
5,777
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/account
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/sessionRecovery/SessionRecoveryInProgressModalIllustration.tsx
const SessionRecoveryInProgressModalIllustration = ({ hoursRemaining }: { hoursRemaining: number }) => { return ( <svg width="276" height="156" viewBox="0 0 276 156" fill="none" xmlns="http://www.w3.org/2000/svg"> <g clip-path="url(#clip0_33_17820)"> <path d="M216 135H60V42.8255C60 37.9715 63.8331 34 68.5179 34H207.482C212.167 34 216 37.9715 216 42.8255V135Z" fill="#372580" /> <path d="M209 135H67V43.1579C67 41.9673 67.9222 41 69.0572 41H206.872C208.007 41 208.929 41.9673 208.929 43.1579V135H209Z" fill="white" /> <path d="M233.075 138H42.9252C41.2842 138 40 136.629 40 134.876V133.124C40 131.371 41.2842 130 42.9252 130H233.075C234.716 130 236 131.371 236 133.124V134.876C236 136.629 234.644 138 233.075 138Z" fill="#EAE8E5" /> <path d="M147.591 134H128.409C125.934 134 124 132.175 124 130H152C152 132.175 150.066 134 147.591 134Z" fill="#D1CFCD" /> <path d="M79.7 86C79.7 81.9683 82.9683 78.7 87 78.7H189C193.032 78.7 196.3 81.9683 196.3 86V96C196.3 100.032 193.032 103.3 189 103.3H87C82.9683 103.3 79.7 100.032 79.7 96V86Z" fill="white" stroke="#F0ECE6" stroke-width="1.4" /> <path d="M94.476 90.6552H92.262L93.8256 89.0869C93.9094 88.9865 93.9526 88.8583 93.9467 88.7277C93.9408 88.597 93.8862 88.4733 93.7937 88.3808C93.7013 88.2884 93.5775 88.2338 93.4469 88.2279C93.3162 88.222 93.1881 88.2652 93.0876 88.3489L91.5194 89.9172V87.7032C91.5194 87.5642 91.4642 87.4309 91.3659 87.3327C91.2676 87.2344 91.1344 87.1792 90.9954 87.1792C90.8564 87.1792 90.7231 87.2344 90.6249 87.3327C90.5266 87.4309 90.4714 87.5642 90.4714 87.7032V89.9172L88.9077 88.3489C88.8616 88.2915 88.8038 88.2445 88.7382 88.2108C88.6726 88.1772 88.6007 88.1578 88.5271 88.1538C88.4535 88.1498 88.3799 88.1614 88.311 88.1877C88.2422 88.2141 88.1797 88.2547 88.1276 88.3068C88.0755 88.3589 88.0349 88.4214 88.0085 88.4902C87.9822 88.559 87.9706 88.6327 87.9746 88.7063C87.9786 88.7799 87.998 88.8518 88.0316 88.9174C88.0653 88.983 88.1123 89.0407 88.1697 89.0869L89.738 90.6552H87.524C87.385 90.6552 87.2517 90.7104 87.1535 90.8087C87.0552 90.9069 87 91.0402 87 91.1792C87 91.3182 87.0552 91.4514 87.1535 91.5497C87.2517 91.648 87.385 91.7032 87.524 91.7032H89.738L88.1697 93.2715C88.1138 93.3181 88.0683 93.3758 88.0359 93.441C88.0036 93.5063 87.9852 93.5775 87.9819 93.6502C87.9786 93.7229 87.9905 93.7955 88.0168 93.8634C88.0432 93.9313 88.0833 93.9929 88.1348 94.0444C88.1863 94.0958 88.2479 94.136 88.3158 94.1624C88.3837 94.1887 88.4563 94.2006 88.529 94.1973C88.6017 94.194 88.6729 94.1756 88.7382 94.1433C88.8034 94.1109 88.8611 94.0654 88.9077 94.0095L90.4714 92.4412V94.6552C90.4714 94.7942 90.5266 94.9275 90.6249 95.0257C90.7231 95.124 90.8564 95.1792 90.9954 95.1792C91.1344 95.1792 91.2676 95.124 91.3659 95.0257C91.4642 94.9275 91.5194 94.7942 91.5194 94.6552V92.4412L93.0876 94.0095C93.1343 94.0654 93.192 94.1109 93.2572 94.1433C93.3224 94.1756 93.3937 94.194 93.4664 94.1973C93.5391 94.2006 93.6117 94.1887 93.6796 94.1624C93.7475 94.136 93.8091 94.0958 93.8606 94.0444C93.912 93.9929 93.9522 93.9313 93.9786 93.8634C94.0049 93.7955 94.0168 93.7229 94.0135 93.6502C94.0102 93.5775 93.9918 93.5063 93.9595 93.441C93.9271 93.3758 93.8816 93.3181 93.8256 93.2715L92.262 91.7032H94.476C94.615 91.7032 94.7483 91.648 94.8465 91.5497C94.9448 91.4514 95 91.3182 95 91.1792C95 91.0402 94.9448 90.9069 94.8465 90.8087C94.7483 90.7104 94.615 90.6552 94.476 90.6552Z" fill="#706D6B" /> <path d="M110.143 90.6552H107.929L109.492 89.0869C109.576 88.9865 109.619 88.8583 109.613 88.7277C109.608 88.597 109.553 88.4733 109.46 88.3808C109.368 88.2884 109.244 88.2338 109.114 88.2279C108.983 88.222 108.855 88.2652 108.754 88.3489L107.186 89.9172V87.7032C107.186 87.5642 107.131 87.4309 107.033 87.3327C106.934 87.2344 106.801 87.1792 106.662 87.1792C106.523 87.1792 106.39 87.2344 106.292 87.3327C106.193 87.4309 106.138 87.5642 106.138 87.7032V89.9172L104.574 88.3489C104.528 88.2915 104.471 88.2445 104.405 88.2108C104.339 88.1772 104.267 88.1578 104.194 88.1538C104.12 88.1498 104.047 88.1614 103.978 88.1877C103.909 88.2141 103.846 88.2547 103.794 88.3068C103.742 88.3589 103.702 88.4214 103.675 88.4902C103.649 88.559 103.637 88.6327 103.641 88.7063C103.645 88.7799 103.665 88.8518 103.698 88.9174C103.732 88.983 103.779 89.0407 103.836 89.0869L105.405 90.6552H103.191C103.052 90.6552 102.918 90.7104 102.82 90.8087C102.722 90.9069 102.667 91.0402 102.667 91.1792C102.667 91.3182 102.722 91.4514 102.82 91.5497C102.918 91.648 103.052 91.7032 103.191 91.7032H105.405L103.836 93.2715C103.781 93.3181 103.735 93.3758 103.703 93.441C103.67 93.5063 103.652 93.5775 103.649 93.6502C103.645 93.7229 103.657 93.7955 103.684 93.8634C103.71 93.9313 103.75 93.9929 103.802 94.0444C103.853 94.0958 103.915 94.136 103.983 94.1624C104.05 94.1887 104.123 94.2006 104.196 94.1973C104.268 94.194 104.34 94.1756 104.405 94.1433C104.47 94.1109 104.528 94.0654 104.574 94.0095L106.138 92.4412V94.6552C106.138 94.7942 106.193 94.9275 106.292 95.0257C106.39 95.124 106.523 95.1792 106.662 95.1792C106.801 95.1792 106.934 95.124 107.033 95.0257C107.131 94.9275 107.186 94.7942 107.186 94.6552V92.4412L108.754 94.0095C108.801 94.0654 108.859 94.1109 108.924 94.1433C108.989 94.1756 109.06 94.194 109.133 94.1973C109.206 94.2006 109.278 94.1887 109.346 94.1624C109.414 94.136 109.476 94.0958 109.527 94.0444C109.579 93.9929 109.619 93.9313 109.645 93.8634C109.672 93.7955 109.684 93.7229 109.68 93.6502C109.677 93.5775 109.659 93.5063 109.626 93.441C109.594 93.3758 109.548 93.3181 109.492 93.2715L107.929 91.7032H110.143C110.282 91.7032 110.415 91.648 110.513 91.5497C110.612 91.4514 110.667 91.3182 110.667 91.1792C110.667 91.0402 110.612 90.9069 110.513 90.8087C110.415 90.7104 110.282 90.6552 110.143 90.6552Z" fill="#706D6B" /> <path d="M125.809 90.6552H123.595L125.159 89.0869C125.243 88.9865 125.286 88.8583 125.28 88.7277C125.274 88.597 125.219 88.4733 125.127 88.3808C125.035 88.2884 124.911 88.2338 124.78 88.2279C124.649 88.222 124.521 88.2652 124.421 88.3489L122.853 89.9172V87.7032C122.853 87.5642 122.797 87.4309 122.699 87.3327C122.601 87.2344 122.468 87.1792 122.329 87.1792C122.19 87.1792 122.056 87.2344 121.958 87.3327C121.86 87.4309 121.805 87.5642 121.805 87.7032V89.9172L120.241 88.3489C120.195 88.2915 120.137 88.2445 120.071 88.2108C120.006 88.1772 119.934 88.1578 119.86 88.1538C119.787 88.1498 119.713 88.1614 119.644 88.1877C119.575 88.2141 119.513 88.2547 119.461 88.3068C119.409 88.3589 119.368 88.4214 119.342 88.4902C119.315 88.559 119.304 88.6327 119.308 88.7063C119.312 88.7799 119.331 88.8518 119.365 88.9174C119.399 88.983 119.446 89.0407 119.503 89.0869L121.071 90.6552H118.857C118.718 90.6552 118.585 90.7104 118.487 90.8087C118.388 90.9069 118.333 91.0402 118.333 91.1792C118.333 91.3182 118.388 91.4514 118.487 91.5497C118.585 91.648 118.718 91.7032 118.857 91.7032H121.071L119.503 93.2715C119.447 93.3181 119.402 93.3758 119.369 93.441C119.337 93.5063 119.318 93.5775 119.315 93.6502C119.312 93.7229 119.324 93.7955 119.35 93.8634C119.376 93.9313 119.417 93.9929 119.468 94.0444C119.52 94.0958 119.581 94.136 119.649 94.1624C119.717 94.1887 119.79 94.2006 119.862 94.1973C119.935 94.194 120.006 94.1756 120.071 94.1433C120.137 94.1109 120.194 94.0654 120.241 94.0095L121.805 92.4412V94.6552C121.805 94.7942 121.86 94.9275 121.958 95.0257C122.056 95.124 122.19 95.1792 122.329 95.1792C122.468 95.1792 122.601 95.124 122.699 95.0257C122.797 94.9275 122.853 94.7942 122.853 94.6552V92.4412L124.421 94.0095C124.468 94.0654 124.525 94.1109 124.59 94.1433C124.656 94.1756 124.727 94.194 124.8 94.1973C124.872 94.2006 124.945 94.1887 125.013 94.1624C125.081 94.136 125.142 94.0958 125.194 94.0444C125.245 93.9929 125.285 93.9313 125.312 93.8634C125.338 93.7955 125.35 93.7229 125.347 93.6502C125.343 93.5775 125.325 93.5063 125.293 93.441C125.26 93.3758 125.215 93.3181 125.159 93.2715L123.595 91.7032H125.809C125.948 91.7032 126.082 91.648 126.18 91.5497C126.278 91.4514 126.333 91.3182 126.333 91.1792C126.333 91.0402 126.278 90.9069 126.18 90.8087C126.082 90.7104 125.948 90.6552 125.809 90.6552Z" fill="#706D6B" /> <path d="M141.476 90.6552H139.262L140.826 89.0869C140.909 88.9865 140.953 88.8583 140.947 88.7277C140.941 88.597 140.886 88.4733 140.794 88.3808C140.701 88.2884 140.578 88.2338 140.447 88.2279C140.316 88.222 140.188 88.2652 140.088 88.3489L138.519 89.9172V87.7032C138.519 87.5642 138.464 87.4309 138.366 87.3327C138.268 87.2344 138.134 87.1792 137.995 87.1792C137.856 87.1792 137.723 87.2344 137.625 87.3327C137.527 87.4309 137.471 87.5642 137.471 87.7032V89.9172L135.908 88.3489C135.862 88.2915 135.804 88.2445 135.738 88.2108C135.673 88.1772 135.601 88.1578 135.527 88.1538C135.453 88.1498 135.38 88.1614 135.311 88.1877C135.242 88.2141 135.18 88.2547 135.128 88.3068C135.075 88.3589 135.035 88.4214 135.009 88.4902C134.982 88.559 134.971 88.6327 134.975 88.7063C134.979 88.7799 134.998 88.8518 135.032 88.9174C135.065 88.983 135.112 89.0407 135.17 89.0869L136.738 90.6552H134.524C134.385 90.6552 134.252 90.7104 134.153 90.8087C134.055 90.9069 134 91.0402 134 91.1792C134 91.3182 134.055 91.4514 134.153 91.5497C134.252 91.648 134.385 91.7032 134.524 91.7032H136.738L135.17 93.2715C135.114 93.3181 135.068 93.3758 135.036 93.441C135.004 93.5063 134.985 93.5775 134.982 93.6502C134.979 93.7229 134.99 93.7955 135.017 93.8634C135.043 93.9313 135.083 93.9929 135.135 94.0444C135.186 94.0958 135.248 94.136 135.316 94.1624C135.384 94.1887 135.456 94.2006 135.529 94.1973C135.602 94.194 135.673 94.1756 135.738 94.1433C135.803 94.1109 135.861 94.0654 135.908 94.0095L137.471 92.4412V94.6552C137.471 94.7942 137.527 94.9275 137.625 95.0257C137.723 95.124 137.856 95.1792 137.995 95.1792C138.134 95.1792 138.268 95.124 138.366 95.0257C138.464 94.9275 138.519 94.7942 138.519 94.6552V92.4412L140.088 94.0095C140.134 94.0654 140.192 94.1109 140.257 94.1433C140.322 94.1756 140.394 94.194 140.466 94.1973C140.539 94.2006 140.612 94.1887 140.68 94.1624C140.747 94.136 140.809 94.0958 140.861 94.0444C140.912 93.9929 140.952 93.9313 140.979 93.8634C141.005 93.7955 141.017 93.7229 141.014 93.6502C141.01 93.5775 140.992 93.5063 140.959 93.441C140.927 93.3758 140.882 93.3181 140.826 93.2715L139.262 91.7032H141.476C141.615 91.7032 141.748 91.648 141.847 91.5497C141.945 91.4514 142 91.3182 142 91.1792C142 91.0402 141.945 90.9069 141.847 90.8087C141.748 90.7104 141.615 90.6552 141.476 90.6552Z" fill="#706D6B" /> <path d="M157.143 90.6552H154.929L156.492 89.0869C156.576 88.9865 156.619 88.8583 156.613 88.7277C156.608 88.597 156.553 88.4733 156.46 88.3808C156.368 88.2884 156.244 88.2338 156.114 88.2279C155.983 88.222 155.855 88.2652 155.754 88.3489L154.186 89.9172V87.7032C154.186 87.5642 154.131 87.4309 154.033 87.3327C153.934 87.2344 153.801 87.1792 153.662 87.1792C153.523 87.1792 153.39 87.2344 153.292 87.3327C153.193 87.4309 153.138 87.5642 153.138 87.7032V89.9172L151.574 88.3489C151.528 88.2915 151.471 88.2445 151.405 88.2108C151.339 88.1772 151.267 88.1578 151.194 88.1538C151.12 88.1498 151.047 88.1614 150.978 88.1877C150.909 88.2141 150.846 88.2547 150.794 88.3068C150.742 88.3589 150.702 88.4214 150.675 88.4902C150.649 88.559 150.637 88.6327 150.641 88.7063C150.645 88.7799 150.665 88.8518 150.698 88.9174C150.732 88.983 150.779 89.0407 150.836 89.0869L152.405 90.6552H150.191C150.052 90.6552 149.918 90.7104 149.82 90.8087C149.722 90.9069 149.667 91.0402 149.667 91.1792C149.667 91.3182 149.722 91.4514 149.82 91.5497C149.918 91.648 150.052 91.7032 150.191 91.7032H152.405L150.836 93.2715C150.781 93.3181 150.735 93.3758 150.703 93.441C150.67 93.5063 150.652 93.5775 150.649 93.6502C150.645 93.7229 150.657 93.7955 150.684 93.8634C150.71 93.9313 150.75 93.9929 150.802 94.0444C150.853 94.0958 150.915 94.136 150.983 94.1624C151.05 94.1887 151.123 94.2006 151.196 94.1973C151.268 94.194 151.34 94.1756 151.405 94.1433C151.47 94.1109 151.528 94.0654 151.574 94.0095L153.138 92.4412V94.6552C153.138 94.7942 153.193 94.9275 153.292 95.0257C153.39 95.124 153.523 95.1792 153.662 95.1792C153.801 95.1792 153.934 95.124 154.033 95.0257C154.131 94.9275 154.186 94.7942 154.186 94.6552V92.4412L155.754 94.0095C155.801 94.0654 155.859 94.1109 155.924 94.1433C155.989 94.1756 156.06 94.194 156.133 94.1973C156.206 94.2006 156.278 94.1887 156.346 94.1624C156.414 94.136 156.476 94.0958 156.527 94.0444C156.579 93.9929 156.619 93.9313 156.645 93.8634C156.672 93.7955 156.684 93.7229 156.68 93.6502C156.677 93.5775 156.659 93.5063 156.626 93.441C156.594 93.3758 156.548 93.3181 156.492 93.2715L154.929 91.7032H157.143C157.282 91.7032 157.415 91.648 157.513 91.5497C157.612 91.4514 157.667 91.3182 157.667 91.1792C157.667 91.0402 157.612 90.9069 157.513 90.8087C157.415 90.7104 157.282 90.6552 157.143 90.6552Z" fill="#706D6B" /> <path d="M172.809 90.6552H170.595L172.159 89.0869C172.243 88.9865 172.286 88.8583 172.28 88.7277C172.274 88.597 172.219 88.4733 172.127 88.3808C172.035 88.2884 171.911 88.2338 171.78 88.2279C171.649 88.222 171.521 88.2652 171.421 88.3489L169.853 89.9172V87.7032C169.853 87.5642 169.797 87.4309 169.699 87.3327C169.601 87.2344 169.468 87.1792 169.329 87.1792C169.19 87.1792 169.056 87.2344 168.958 87.3327C168.86 87.4309 168.805 87.5642 168.805 87.7032V89.9172L167.241 88.3489C167.195 88.2915 167.137 88.2445 167.071 88.2108C167.006 88.1772 166.934 88.1578 166.86 88.1538C166.787 88.1498 166.713 88.1614 166.644 88.1877C166.575 88.2141 166.513 88.2547 166.461 88.3068C166.409 88.3589 166.368 88.4214 166.342 88.4902C166.315 88.559 166.304 88.6327 166.308 88.7063C166.312 88.7799 166.331 88.8518 166.365 88.9174C166.399 88.983 166.446 89.0407 166.503 89.0869L168.071 90.6552H165.857C165.718 90.6552 165.585 90.7104 165.487 90.8087C165.388 90.9069 165.333 91.0402 165.333 91.1792C165.333 91.3182 165.388 91.4514 165.487 91.5497C165.585 91.648 165.718 91.7032 165.857 91.7032H168.071L166.503 93.2715C166.447 93.3181 166.402 93.3758 166.369 93.441C166.337 93.5063 166.318 93.5775 166.315 93.6502C166.312 93.7229 166.324 93.7955 166.35 93.8634C166.376 93.9313 166.417 93.9929 166.468 94.0444C166.52 94.0958 166.581 94.136 166.649 94.1624C166.717 94.1887 166.79 94.2006 166.862 94.1973C166.935 94.194 167.006 94.1756 167.071 94.1433C167.137 94.1109 167.194 94.0654 167.241 94.0095L168.805 92.4412V94.6552C168.805 94.7942 168.86 94.9275 168.958 95.0257C169.056 95.124 169.19 95.1792 169.329 95.1792C169.468 95.1792 169.601 95.124 169.699 95.0257C169.797 94.9275 169.853 94.7942 169.853 94.6552V92.4412L171.421 94.0095C171.468 94.0654 171.525 94.1109 171.59 94.1433C171.656 94.1756 171.727 94.194 171.8 94.1973C171.872 94.2006 171.945 94.1887 172.013 94.1624C172.081 94.136 172.142 94.0958 172.194 94.0444C172.245 93.9929 172.285 93.9313 172.312 93.8634C172.338 93.7955 172.35 93.7229 172.347 93.6502C172.343 93.5775 172.325 93.5063 172.293 93.441C172.26 93.3758 172.215 93.3181 172.159 93.2715L170.595 91.7032H172.809C172.948 91.7032 173.082 91.648 173.18 91.5497C173.278 91.4514 173.333 91.3182 173.333 91.1792C173.333 91.0402 173.278 90.9069 173.18 90.8087C173.082 90.7104 172.948 90.6552 172.809 90.6552Z" fill="#706D6B" /> <path d="M188.476 90.6552H186.262L187.826 89.0869C187.909 88.9865 187.953 88.8583 187.947 88.7277C187.941 88.597 187.886 88.4733 187.794 88.3808C187.701 88.2884 187.578 88.2338 187.447 88.2279C187.316 88.222 187.188 88.2652 187.088 88.3489L185.519 89.9172V87.7032C185.519 87.5642 185.464 87.4309 185.366 87.3327C185.268 87.2344 185.134 87.1792 184.995 87.1792C184.856 87.1792 184.723 87.2344 184.625 87.3327C184.527 87.4309 184.471 87.5642 184.471 87.7032V89.9172L182.908 88.3489C182.862 88.2915 182.804 88.2445 182.738 88.2108C182.673 88.1772 182.601 88.1578 182.527 88.1538C182.453 88.1498 182.38 88.1614 182.311 88.1877C182.242 88.2141 182.18 88.2547 182.128 88.3068C182.075 88.3589 182.035 88.4214 182.009 88.4902C181.982 88.559 181.971 88.6327 181.975 88.7063C181.979 88.7799 181.998 88.8518 182.032 88.9174C182.065 88.983 182.112 89.0407 182.17 89.0869L183.738 90.6552H181.524C181.385 90.6552 181.252 90.7104 181.153 90.8087C181.055 90.9069 181 91.0402 181 91.1792C181 91.3182 181.055 91.4514 181.153 91.5497C181.252 91.648 181.385 91.7032 181.524 91.7032H183.738L182.17 93.2715C182.114 93.3181 182.068 93.3758 182.036 93.441C182.004 93.5063 181.985 93.5775 181.982 93.6502C181.979 93.7229 181.99 93.7955 182.017 93.8634C182.043 93.9313 182.083 93.9929 182.135 94.0444C182.186 94.0958 182.248 94.136 182.316 94.1624C182.384 94.1887 182.456 94.2006 182.529 94.1973C182.602 94.194 182.673 94.1756 182.738 94.1433C182.803 94.1109 182.861 94.0654 182.908 94.0095L184.471 92.4412V94.6552C184.471 94.7942 184.527 94.9275 184.625 95.0257C184.723 95.124 184.856 95.1792 184.995 95.1792C185.134 95.1792 185.268 95.124 185.366 95.0257C185.464 94.9275 185.519 94.7942 185.519 94.6552V92.4412L187.088 94.0095C187.134 94.0654 187.192 94.1109 187.257 94.1433C187.322 94.1756 187.394 94.194 187.466 94.1973C187.539 94.2006 187.612 94.1887 187.68 94.1624C187.747 94.136 187.809 94.0958 187.861 94.0444C187.912 93.9929 187.952 93.9313 187.979 93.8634C188.005 93.7955 188.017 93.7229 188.014 93.6502C188.01 93.5775 187.992 93.5063 187.959 93.441C187.927 93.3758 187.882 93.3181 187.826 93.2715L186.262 91.7032H188.476C188.615 91.7032 188.748 91.648 188.847 91.5497C188.945 91.4514 189 91.3182 189 91.1792C189 91.0402 188.945 90.9069 188.847 90.8087C188.748 90.7104 188.615 90.6552 188.476 90.6552Z" fill="#706D6B" /> <path d="M14 69C14 58.5066 22.5066 50 33 50C43.4934 50 52 58.5066 52 69V88H33C22.5066 88 14 79.4934 14 69Z" fill="url(#paint0_linear_33_17820)" /> <path fill-rule="evenodd" clip-rule="evenodd" d="M37.9455 63.2756V65.1182H39.8177C40.4581 65.1182 41 65.6142 41 66.252V75.8661C41 76.4803 40.4828 77 39.8177 77H27.1823C26.5419 77 26 76.5039 26 75.8661V66.252C26 65.6379 26.5172 65.1182 27.1823 65.1182H29.0293V63.2756C29.0293 60.9134 31.0244 59 33.4874 59C35.9505 59 37.9455 60.9134 37.9455 63.2756ZM36.0683 63.2756V65.1182H30.9558V63.2756C30.9558 61.5748 32.3101 60.824 33.512 60.824C34.714 60.824 36.0683 61.5748 36.0683 63.2756ZM33.5 68C34.3333 68 35 68.6696 35 69.5065C35 70.0804 34.6905 70.5826 34.2143 70.8217L34.8333 73.5H32.1667L32.7857 70.8217C32.3095 70.5587 32 70.0804 32 69.5065C32 68.6696 32.6667 68 33.5 68Z" fill="white" /> <g opacity="0.2" filter="url(#filter0_f_33_17820)"> <path d="M119 95C119 85.0589 127.059 77 137 77H139C148.941 77 157 85.0589 157 95C157 104.941 148.941 113 139 113H137C127.059 113 119 104.941 119 95Z" fill="#1F1548" /> </g> <rect x="114" y="63" width="48" height="48" rx="24" fill="url(#paint1_linear_33_17820)" /> <g filter="url(#filter1_i_33_17820)"> <circle cx="138" cy="87" r="20" fill="url(#paint2_linear_33_17820)" /> </g> <path d="M138.455 75V87.1129L133 93.5455" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" /> <rect x="142" y="96" width="26" height="21" rx="5.83333" fill="url(#paint3_linear_33_17820)" /> <text x="147" y="111" fontWeight={800} font-size="13" fill="white"> {hoursRemaining} </text> </g> <defs> <filter id="filter0_f_33_17820" x="109.3" y="67.3" width="57.4" height="55.4" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB" > <feFlood flood-opacity="0" result="BackgroundImageFix" /> <feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape" /> <feGaussianBlur stdDeviation="4.85" result="effect1_foregroundBlur_33_17820" /> </filter> <filter id="filter1_i_33_17820" x="118" y="67" width="40" height="40.3333" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB" > <feFlood flood-opacity="0" result="BackgroundImageFix" /> <feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape" /> <feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha" /> <feOffset dy="0.333333" /> <feGaussianBlur stdDeviation="0.166667" /> <feComposite in2="hardAlpha" operator="arithmetic" k2="-1" k3="1" /> <feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.16 0" /> <feBlend mode="normal" in2="shape" result="effect1_innerShadow_33_17820" /> </filter> <linearGradient id="paint0_linear_33_17820" x1="37.0714" y1="50" x2="17.2885" y2="93.4808" gradientUnits="userSpaceOnUse" > <stop stop-color="#FFD66C" /> <stop offset="1" stop-color="#FF8E4F" /> </linearGradient> <linearGradient id="paint1_linear_33_17820" x1="187" y1="34.5" x2="126.5" y2="124.5" gradientUnits="userSpaceOnUse" > <stop offset="0.217324" stop-color="white" /> <stop offset="0.621556" stop-color="#ECEAE6" /> <stop offset="0.936658" stop-color="#BEBBB9" /> </linearGradient> <linearGradient id="paint2_linear_33_17820" x1="138" y1="67" x2="138" y2="107" gradientUnits="userSpaceOnUse" > <stop stop-color="#8F8F8F" /> <stop offset="1" /> </linearGradient> <linearGradient id="paint3_linear_33_17820" x1="155" y1="91.7045" x2="155" y2="117.955" gradientUnits="userSpaceOnUse" > <stop stop-color="#FFA693" /> <stop offset="1" stop-color="#F43D5E" /> </linearGradient> <clipPath id="clip0_33_17820"> <rect width="276" height="156" fill="white" /> </clipPath> </defs> </svg> ); }; export default SessionRecoveryInProgressModalIllustration;
5,778
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/account
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/sessionRecovery/SessionRecoveryLocalStorageManager.tsx
import { ReactNode, useEffect } from 'react'; import { createContext, useContext } from 'react'; import { useLocalState, useSessionRecoveryState, useUser } from '@proton/components/hooks'; import { removeItem } from '@proton/shared/lib/helpers/storage'; import { SessionRecoveryState } from '@proton/shared/lib/interfaces'; interface SRContext { hasDismissedSessionRecoveryCancelled: boolean; dismissSessionRecoveryCancelled: () => void; hasConfirmedSessionRecoveryInProgress: boolean; confirmSessionRecoveryInProgress: () => void; } const defaultSRContext: SRContext = { hasDismissedSessionRecoveryCancelled: false, dismissSessionRecoveryCancelled: () => {}, hasConfirmedSessionRecoveryInProgress: false, confirmSessionRecoveryInProgress: () => {}, }; const SessionRecoveryContext = createContext<SRContext>(defaultSRContext); export const useSessionRecoveryLocalStorage = () => useContext(SessionRecoveryContext); interface Props { children: ReactNode; } const useHasDismissedSessionRecoveryCancelled = () => { const [user] = useUser(); const cancelledLocalStorageKey = `sr--cancelled:${user.ID}`; const [hasDismissed, setHasDismissed] = useLocalState(false, cancelledLocalStorageKey); const sessionRecoveryState = useSessionRecoveryState(); const isCancelled = sessionRecoveryState === SessionRecoveryState.CANCELLED; useEffect(() => { if (!isCancelled) { // Clear up local storage removeItem(cancelledLocalStorageKey); setHasDismissed(false); } }, [isCancelled]); return { hasDismissedSessionRecoveryCancelled: hasDismissed, dismissSessionRecoveryCancelled: () => { setHasDismissed(true); }, }; }; const useHasConfirmedSessionRecoveryInProgress = () => { const [user] = useUser(); const confirmedLocalStorageKey = `sr--confirmed:${user.ID}`; const [hasConfirmed, setHasConfirmed] = useLocalState(false, confirmedLocalStorageKey); const sessionRecoveryState = useSessionRecoveryState(); const isGracePeriod = sessionRecoveryState === SessionRecoveryState.GRACE_PERIOD; useEffect(() => { if (!isGracePeriod) { // Clear up local storage when not in grace period removeItem(confirmedLocalStorageKey); } }, [isGracePeriod]); return { hasConfirmedSessionRecoveryInProgress: hasConfirmed, confirmSessionRecoveryInProgress: () => { setHasConfirmed(true); }, }; }; const SessionRecoveryLocalStorageManager = ({ children }: Props) => { const { hasDismissedSessionRecoveryCancelled, dismissSessionRecoveryCancelled } = useHasDismissedSessionRecoveryCancelled(); const { hasConfirmedSessionRecoveryInProgress, confirmSessionRecoveryInProgress } = useHasConfirmedSessionRecoveryInProgress(); const value: SRContext = { hasDismissedSessionRecoveryCancelled, dismissSessionRecoveryCancelled, hasConfirmedSessionRecoveryInProgress, confirmSessionRecoveryInProgress, }; return <SessionRecoveryContext.Provider value={value}>{children}</SessionRecoveryContext.Provider>; }; export default SessionRecoveryLocalStorageManager;
5,779
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/account
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/sessionRecovery/SessionRecoveryResetConfirmedPrompt.tsx
import { c, msgid } from 'ttag'; import { ButtonLike } from '@proton/atoms/Button'; import { Prompt, useSessionRecoveryGracePeriodHoursRemaining } from '@proton/components'; import { SettingsLink } from '@proton/components/components'; const SessionRecoveryResetConfirmedPrompt = ({ open, onClose }: { open?: boolean; onClose?: () => void }) => { const gracePeriodHoursRemaining = useSessionRecoveryGracePeriodHoursRemaining(); if (gracePeriodHoursRemaining === null) { return null; } const accountAndPasswordSectionLink = ( <SettingsLink key="account-and-password-section-link" path="/account-password" onClick={onClose}>{ // translator: full sentence "You can check the status of your request at any time in the account and password section of the settings." c('session_recovery:initiation:link').t`account and password section` }</SettingsLink> ); return ( <Prompt title={c('session_recovery:initiation:title').ngettext( msgid`You'll be able to reset your password in ${gracePeriodHoursRemaining} hour`, `You'll be able to reset your password in ${gracePeriodHoursRemaining} hours`, gracePeriodHoursRemaining )} open={open} buttons={[ <ButtonLike as={SettingsLink} path="/account-password" onClick={onClose}> {c('session_recovery:initiation:action').t`Got it`} </ButtonLike>, ]} > <p>{c('session_recovery:initiation:info') .t`We will contact you again when the password reset is available.`}</p> <p> { // translator: full sentence "You can check the status of your request at any time in the account and password section of the settings." c('session_recovery:initiation:info') .jt`You can check the status of your request at any time in the ${accountAndPasswordSectionLink} of the settings.` } </p> </Prompt> ); }; export default SessionRecoveryResetConfirmedPrompt;
5,780
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/account
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/sessionRecovery/SessionRecoverySignOutConfirmPrompt.tsx
import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { Prompt, SettingsLink } from '@proton/components/components'; import { useSessionRecoveryGracePeriodHoursRemaining, useSessionRecoveryState } from '@proton/components/hooks'; import { SessionRecoveryState } from '@proton/shared/lib/interfaces'; const GracePeriodText = () => { const gracePeriodHoursRemaining = useSessionRecoveryGracePeriodHoursRemaining(); if (gracePeriodHoursRemaining === null) { return null; } const boldTimeLeft = ( <b key="bold-time-left"> { // translator: Full sentence is "You will be able to reset your password in XX hours." c('session_recovery:sign_out:info').ngettext( msgid`${gracePeriodHoursRemaining} hour`, `${gracePeriodHoursRemaining} hours`, gracePeriodHoursRemaining ) } </b> ); return ( <> <p> { // translator: Full sentence is "You will be able to reset your password in XX hours." c('session_recovery:sign_out:info').jt`You will be able to reset your password in ${boldTimeLeft}.` } </p> <p>{c('session_recovery:sign_out:info') .t`If you sign out before you reset your password, you could lose access to your account.`}</p> </> ); }; interface Props { onClose: () => void; onSignOut: () => void; open: boolean; } const SessionRecoverySignOutConfirmPrompt = ({ onClose, onSignOut, open }: Props) => { const sessionRecoveryState = useSessionRecoveryState(); const passwordReset = ( <SettingsLink key="password-reset-link" path="/account-password" onClick={onClose}> { // translator: Full sentence "Password reset is now available." c('session_recovery:sign_out:link').t`Password reset` } </SettingsLink> ); return ( <Prompt open={open} onClose={onClose} title={c('session_recovery:sign_out:title').t`Sign out without password reset?`} buttons={[ <Button color="danger" onClick={() => { onClose(); onSignOut(); }} > {c('session_recovery:sign_out:action').t`Sign out`} </Button>, <Button onClick={onClose}>{c('session_recovery:sign_out:action').t`Stay signed in`}</Button>, ]} > {sessionRecoveryState === SessionRecoveryState.GRACE_PERIOD && <GracePeriodText />} {sessionRecoveryState === SessionRecoveryState.INSECURE && ( <> <p> { // translator: Full sentence "Password reset is now available." c('session_recovery:sign_out:info').jt`${passwordReset} is now available.` } </p> <p> {c('session_recovery:sign_out:info') .t`If you sign out without resetting your password, you could lose access to your account.`} </p> </> )} </Prompt> ); }; export default SessionRecoverySignOutConfirmPrompt;
5,781
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/account
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/sessionRecovery/index.ts
export { default as PasswordResetAvailableAccountModal } from './PasswordResetAvailableAccountModal'; export { default as PasswordResetAvailableProductModal } from './PasswordResetAvailableProductModal'; export { default as SessionRecoveryInProgressModal } from './SessionRecoveryInProgressModal';
5,782
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/account
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/sessionRecovery/password-reset-illustration.svg
<svg width="276" height="156" viewBox="0 0 276 156" fill="none" xmlns="http://www.w3.org/2000/svg"> <g clip-path="url(#clip0_42_23582)"> <path d="M216 135H60V42.8255C60 37.9715 63.8331 34 68.5179 34H207.482C212.167 34 216 37.9715 216 42.8255V135Z" fill="#372580" /> <path d="M209 135H67V43.1579C67 41.9673 67.9222 41 69.0572 41H206.872C208.007 41 208.929 41.9673 208.929 43.1579V135H209Z" fill="white" /> <path d="M233.075 138H42.9252C41.2842 138 40 136.629 40 134.876V133.124C40 131.371 41.2842 130 42.9252 130H233.075C234.716 130 236 131.371 236 133.124V134.876C236 136.629 234.644 138 233.075 138Z" fill="#EAE8E5" /> <path d="M147.591 134H128.409C125.934 134 124 132.175 124 130H152C152 132.175 150.066 134 147.591 134Z" fill="#D1CFCD" /> <mask id="mask0_42_23582" style="mask-type: alpha" maskUnits="userSpaceOnUse" x="91" y="34" width="125" height="78" > <path d="M216 34L104.02 34L91.9998 112L216 89.5068V34Z" fill="#C4C4C4" /> </mask> <g mask="url(#mask0_42_23582)"> <g opacity="0.2" filter="url(#filter0_f_42_23582)"> <path d="M183 25H230.399V72C204.442 72 183 50.9574 183 25Z" fill="#221548" /> </g> </g> <path d="M79.7 86C79.7 81.9683 82.9683 78.7 87 78.7H189C193.032 78.7 196.3 81.9683 196.3 86V96C196.3 100.032 193.032 103.3 189 103.3H87C82.9683 103.3 79.7 100.032 79.7 96V86Z" fill="white" stroke="#F0ECE6" stroke-width="1.4" /> <path d="M94.476 90.6557H92.262L93.8256 89.0874C93.9094 88.987 93.9526 88.8588 93.9467 88.7282C93.9408 88.5975 93.8862 88.4738 93.7937 88.3813C93.7013 88.2889 93.5775 88.2343 93.4469 88.2284C93.3162 88.2225 93.1881 88.2657 93.0876 88.3494L91.5194 89.9177V87.7037C91.5194 87.5647 91.4642 87.4314 91.3659 87.3332C91.2676 87.2349 91.1344 87.1797 90.9954 87.1797C90.8564 87.1797 90.7231 87.2349 90.6249 87.3332C90.5266 87.4314 90.4714 87.5647 90.4714 87.7037V89.9177L88.9077 88.3494C88.8616 88.292 88.8038 88.2449 88.7382 88.2113C88.6726 88.1777 88.6007 88.1582 88.5271 88.1543C88.4535 88.1503 88.3799 88.1619 88.311 88.1882C88.2422 88.2146 88.1797 88.2551 88.1276 88.3073C88.0755 88.3594 88.0349 88.4219 88.0085 88.4907C87.9822 88.5595 87.9706 88.6332 87.9746 88.7068C87.9786 88.7804 87.998 88.8523 88.0316 88.9179C88.0653 88.9835 88.1123 89.0412 88.1697 89.0874L89.738 90.6557H87.524C87.385 90.6557 87.2517 90.7109 87.1535 90.8092C87.0552 90.9074 87 91.0407 87 91.1797C87 91.3186 87.0552 91.4519 87.1535 91.5502C87.2517 91.6485 87.385 91.7037 87.524 91.7037H89.738L88.1697 93.2719C88.1138 93.3186 88.0683 93.3763 88.0359 93.4415C88.0036 93.5068 87.9852 93.578 87.9819 93.6507C87.9786 93.7234 87.9905 93.796 88.0168 93.8639C88.0432 93.9318 88.0833 93.9934 88.1348 94.0449C88.1863 94.0963 88.2479 94.1365 88.3158 94.1629C88.3837 94.1892 88.4563 94.2011 88.529 94.1978C88.6017 94.1945 88.6729 94.1761 88.7382 94.1438C88.8034 94.1114 88.8611 94.0659 88.9077 94.01L90.4714 92.4417V94.6557C90.4714 94.7947 90.5266 94.928 90.6249 95.0262C90.7231 95.1245 90.8564 95.1797 90.9954 95.1797C91.1344 95.1797 91.2676 95.1245 91.3659 95.0262C91.4642 94.928 91.5194 94.7947 91.5194 94.6557V92.4417L93.0876 94.01C93.1343 94.0659 93.192 94.1114 93.2572 94.1438C93.3224 94.1761 93.3937 94.1945 93.4664 94.1978C93.5391 94.2011 93.6117 94.1892 93.6796 94.1629C93.7475 94.1365 93.8091 94.0963 93.8606 94.0449C93.912 93.9934 93.9522 93.9318 93.9786 93.8639C94.0049 93.796 94.0168 93.7234 94.0135 93.6507C94.0102 93.578 93.9918 93.5068 93.9595 93.4415C93.9271 93.3763 93.8816 93.3186 93.8256 93.2719L92.262 91.7037H94.476C94.615 91.7037 94.7483 91.6485 94.8465 91.5502C94.9448 91.4519 95 91.3186 95 91.1797C95 91.0407 94.9448 90.9074 94.8465 90.8092C94.7483 90.7109 94.615 90.6557 94.476 90.6557Z" fill="#706D6B" /> <path d="M110.143 90.6557H107.929L109.492 89.0874C109.576 88.987 109.619 88.8588 109.613 88.7282C109.608 88.5975 109.553 88.4738 109.46 88.3813C109.368 88.2889 109.244 88.2343 109.114 88.2284C108.983 88.2225 108.855 88.2657 108.754 88.3494L107.186 89.9177V87.7037C107.186 87.5647 107.131 87.4314 107.033 87.3332C106.934 87.2349 106.801 87.1797 106.662 87.1797C106.523 87.1797 106.39 87.2349 106.292 87.3332C106.193 87.4314 106.138 87.5647 106.138 87.7037V89.9177L104.574 88.3494C104.528 88.292 104.471 88.2449 104.405 88.2113C104.339 88.1777 104.267 88.1582 104.194 88.1543C104.12 88.1503 104.047 88.1619 103.978 88.1882C103.909 88.2146 103.846 88.2551 103.794 88.3073C103.742 88.3594 103.702 88.4219 103.675 88.4907C103.649 88.5595 103.637 88.6332 103.641 88.7068C103.645 88.7804 103.665 88.8523 103.698 88.9179C103.732 88.9835 103.779 89.0412 103.836 89.0874L105.405 90.6557H103.191C103.052 90.6557 102.918 90.7109 102.82 90.8092C102.722 90.9074 102.667 91.0407 102.667 91.1797C102.667 91.3186 102.722 91.4519 102.82 91.5502C102.918 91.6485 103.052 91.7037 103.191 91.7037H105.405L103.836 93.2719C103.781 93.3186 103.735 93.3763 103.703 93.4415C103.67 93.5068 103.652 93.578 103.649 93.6507C103.645 93.7234 103.657 93.796 103.684 93.8639C103.71 93.9318 103.75 93.9934 103.802 94.0449C103.853 94.0963 103.915 94.1365 103.983 94.1629C104.05 94.1892 104.123 94.2011 104.196 94.1978C104.268 94.1945 104.34 94.1761 104.405 94.1438C104.47 94.1114 104.528 94.0659 104.574 94.01L106.138 92.4417V94.6557C106.138 94.7947 106.193 94.928 106.292 95.0262C106.39 95.1245 106.523 95.1797 106.662 95.1797C106.801 95.1797 106.934 95.1245 107.033 95.0262C107.131 94.928 107.186 94.7947 107.186 94.6557V92.4417L108.754 94.01C108.801 94.0659 108.859 94.1114 108.924 94.1438C108.989 94.1761 109.06 94.1945 109.133 94.1978C109.206 94.2011 109.278 94.1892 109.346 94.1629C109.414 94.1365 109.476 94.0963 109.527 94.0449C109.579 93.9934 109.619 93.9318 109.645 93.8639C109.672 93.796 109.684 93.7234 109.68 93.6507C109.677 93.578 109.659 93.5068 109.626 93.4415C109.594 93.3763 109.548 93.3186 109.492 93.2719L107.929 91.7037H110.143C110.282 91.7037 110.415 91.6485 110.513 91.5502C110.612 91.4519 110.667 91.3186 110.667 91.1797C110.667 91.0407 110.612 90.9074 110.513 90.8092C110.415 90.7109 110.282 90.6557 110.143 90.6557Z" fill="#706D6B" /> <path d="M125.809 90.6557H123.595L125.159 89.0874C125.243 88.987 125.286 88.8588 125.28 88.7282C125.274 88.5975 125.219 88.4738 125.127 88.3813C125.035 88.2889 124.911 88.2343 124.78 88.2284C124.649 88.2225 124.521 88.2657 124.421 88.3494L122.853 89.9177V87.7037C122.853 87.5647 122.797 87.4314 122.699 87.3332C122.601 87.2349 122.468 87.1797 122.329 87.1797C122.19 87.1797 122.056 87.2349 121.958 87.3332C121.86 87.4314 121.805 87.5647 121.805 87.7037V89.9177L120.241 88.3494C120.195 88.292 120.137 88.2449 120.071 88.2113C120.006 88.1777 119.934 88.1582 119.86 88.1543C119.787 88.1503 119.713 88.1619 119.644 88.1882C119.575 88.2146 119.513 88.2551 119.461 88.3073C119.409 88.3594 119.368 88.4219 119.342 88.4907C119.315 88.5595 119.304 88.6332 119.308 88.7068C119.312 88.7804 119.331 88.8523 119.365 88.9179C119.399 88.9835 119.446 89.0412 119.503 89.0874L121.071 90.6557H118.857C118.718 90.6557 118.585 90.7109 118.487 90.8092C118.388 90.9074 118.333 91.0407 118.333 91.1797C118.333 91.3186 118.388 91.4519 118.487 91.5502C118.585 91.6485 118.718 91.7037 118.857 91.7037H121.071L119.503 93.2719C119.447 93.3186 119.402 93.3763 119.369 93.4415C119.337 93.5068 119.318 93.578 119.315 93.6507C119.312 93.7234 119.324 93.796 119.35 93.8639C119.376 93.9318 119.417 93.9934 119.468 94.0449C119.52 94.0963 119.581 94.1365 119.649 94.1629C119.717 94.1892 119.79 94.2011 119.862 94.1978C119.935 94.1945 120.006 94.1761 120.071 94.1438C120.137 94.1114 120.194 94.0659 120.241 94.01L121.805 92.4417V94.6557C121.805 94.7947 121.86 94.928 121.958 95.0262C122.056 95.1245 122.19 95.1797 122.329 95.1797C122.468 95.1797 122.601 95.1245 122.699 95.0262C122.797 94.928 122.853 94.7947 122.853 94.6557V92.4417L124.421 94.01C124.468 94.0659 124.525 94.1114 124.59 94.1438C124.656 94.1761 124.727 94.1945 124.8 94.1978C124.872 94.2011 124.945 94.1892 125.013 94.1629C125.081 94.1365 125.142 94.0963 125.194 94.0449C125.245 93.9934 125.285 93.9318 125.312 93.8639C125.338 93.796 125.35 93.7234 125.347 93.6507C125.343 93.578 125.325 93.5068 125.293 93.4415C125.26 93.3763 125.215 93.3186 125.159 93.2719L123.595 91.7037H125.809C125.948 91.7037 126.082 91.6485 126.18 91.5502C126.278 91.4519 126.333 91.3186 126.333 91.1797C126.333 91.0407 126.278 90.9074 126.18 90.8092C126.082 90.7109 125.948 90.6557 125.809 90.6557Z" fill="#706D6B" /> <path d="M141.476 90.6557H139.262L140.826 89.0874C140.909 88.987 140.953 88.8588 140.947 88.7282C140.941 88.5975 140.886 88.4738 140.794 88.3813C140.701 88.2889 140.578 88.2343 140.447 88.2284C140.316 88.2225 140.188 88.2657 140.088 88.3494L138.519 89.9177V87.7037C138.519 87.5647 138.464 87.4314 138.366 87.3332C138.268 87.2349 138.134 87.1797 137.995 87.1797C137.856 87.1797 137.723 87.2349 137.625 87.3332C137.527 87.4314 137.471 87.5647 137.471 87.7037V89.9177L135.908 88.3494C135.862 88.292 135.804 88.2449 135.738 88.2113C135.673 88.1777 135.601 88.1582 135.527 88.1543C135.453 88.1503 135.38 88.1619 135.311 88.1882C135.242 88.2146 135.18 88.2551 135.128 88.3073C135.075 88.3594 135.035 88.4219 135.009 88.4907C134.982 88.5595 134.971 88.6332 134.975 88.7068C134.979 88.7804 134.998 88.8523 135.032 88.9179C135.065 88.9835 135.112 89.0412 135.17 89.0874L136.738 90.6557H134.524C134.385 90.6557 134.252 90.7109 134.153 90.8092C134.055 90.9074 134 91.0407 134 91.1797C134 91.3186 134.055 91.4519 134.153 91.5502C134.252 91.6485 134.385 91.7037 134.524 91.7037H136.738L135.17 93.2719C135.114 93.3186 135.068 93.3763 135.036 93.4415C135.004 93.5068 134.985 93.578 134.982 93.6507C134.979 93.7234 134.99 93.796 135.017 93.8639C135.043 93.9318 135.083 93.9934 135.135 94.0449C135.186 94.0963 135.248 94.1365 135.316 94.1629C135.384 94.1892 135.456 94.2011 135.529 94.1978C135.602 94.1945 135.673 94.1761 135.738 94.1438C135.803 94.1114 135.861 94.0659 135.908 94.01L137.471 92.4417V94.6557C137.471 94.7947 137.527 94.928 137.625 95.0262C137.723 95.1245 137.856 95.1797 137.995 95.1797C138.134 95.1797 138.268 95.1245 138.366 95.0262C138.464 94.928 138.519 94.7947 138.519 94.6557V92.4417L140.088 94.01C140.134 94.0659 140.192 94.1114 140.257 94.1438C140.322 94.1761 140.394 94.1945 140.466 94.1978C140.539 94.2011 140.612 94.1892 140.68 94.1629C140.747 94.1365 140.809 94.0963 140.861 94.0449C140.912 93.9934 140.952 93.9318 140.979 93.8639C141.005 93.796 141.017 93.7234 141.014 93.6507C141.01 93.578 140.992 93.5068 140.959 93.4415C140.927 93.3763 140.882 93.3186 140.826 93.2719L139.262 91.7037H141.476C141.615 91.7037 141.748 91.6485 141.847 91.5502C141.945 91.4519 142 91.3186 142 91.1797C142 91.0407 141.945 90.9074 141.847 90.8092C141.748 90.7109 141.615 90.6557 141.476 90.6557Z" fill="#706D6B" /> <path d="M157.143 90.6557H154.929L156.492 89.0874C156.576 88.987 156.619 88.8588 156.613 88.7282C156.608 88.5975 156.553 88.4738 156.46 88.3813C156.368 88.2889 156.244 88.2343 156.114 88.2284C155.983 88.2225 155.855 88.2657 155.754 88.3494L154.186 89.9177V87.7037C154.186 87.5647 154.131 87.4314 154.033 87.3332C153.934 87.2349 153.801 87.1797 153.662 87.1797C153.523 87.1797 153.39 87.2349 153.292 87.3332C153.193 87.4314 153.138 87.5647 153.138 87.7037V89.9177L151.574 88.3494C151.528 88.292 151.471 88.2449 151.405 88.2113C151.339 88.1777 151.267 88.1582 151.194 88.1543C151.12 88.1503 151.047 88.1619 150.978 88.1882C150.909 88.2146 150.846 88.2551 150.794 88.3073C150.742 88.3594 150.702 88.4219 150.675 88.4907C150.649 88.5595 150.637 88.6332 150.641 88.7068C150.645 88.7804 150.665 88.8523 150.698 88.9179C150.732 88.9835 150.779 89.0412 150.836 89.0874L152.405 90.6557H150.191C150.052 90.6557 149.918 90.7109 149.82 90.8092C149.722 90.9074 149.667 91.0407 149.667 91.1797C149.667 91.3186 149.722 91.4519 149.82 91.5502C149.918 91.6485 150.052 91.7037 150.191 91.7037H152.405L150.836 93.2719C150.781 93.3186 150.735 93.3763 150.703 93.4415C150.67 93.5068 150.652 93.578 150.649 93.6507C150.645 93.7234 150.657 93.796 150.684 93.8639C150.71 93.9318 150.75 93.9934 150.802 94.0449C150.853 94.0963 150.915 94.1365 150.983 94.1629C151.05 94.1892 151.123 94.2011 151.196 94.1978C151.268 94.1945 151.34 94.1761 151.405 94.1438C151.47 94.1114 151.528 94.0659 151.574 94.01L153.138 92.4417V94.6557C153.138 94.7947 153.193 94.928 153.292 95.0262C153.39 95.1245 153.523 95.1797 153.662 95.1797C153.801 95.1797 153.934 95.1245 154.033 95.0262C154.131 94.928 154.186 94.7947 154.186 94.6557V92.4417L155.754 94.01C155.801 94.0659 155.859 94.1114 155.924 94.1438C155.989 94.1761 156.06 94.1945 156.133 94.1978C156.206 94.2011 156.278 94.1892 156.346 94.1629C156.414 94.1365 156.476 94.0963 156.527 94.0449C156.579 93.9934 156.619 93.9318 156.645 93.8639C156.672 93.796 156.684 93.7234 156.68 93.6507C156.677 93.578 156.659 93.5068 156.626 93.4415C156.594 93.3763 156.548 93.3186 156.492 93.2719L154.929 91.7037H157.143C157.282 91.7037 157.415 91.6485 157.513 91.5502C157.612 91.4519 157.667 91.3186 157.667 91.1797C157.667 91.0407 157.612 90.9074 157.513 90.8092C157.415 90.7109 157.282 90.6557 157.143 90.6557Z" fill="#706D6B" /> <path d="M172.809 90.6557H170.595L172.159 89.0874C172.243 88.987 172.286 88.8588 172.28 88.7282C172.274 88.5975 172.219 88.4738 172.127 88.3813C172.035 88.2889 171.911 88.2343 171.78 88.2284C171.649 88.2225 171.521 88.2657 171.421 88.3494L169.853 89.9177V87.7037C169.853 87.5647 169.797 87.4314 169.699 87.3332C169.601 87.2349 169.468 87.1797 169.329 87.1797C169.19 87.1797 169.056 87.2349 168.958 87.3332C168.86 87.4314 168.805 87.5647 168.805 87.7037V89.9177L167.241 88.3494C167.195 88.292 167.137 88.2449 167.071 88.2113C167.006 88.1777 166.934 88.1582 166.86 88.1543C166.787 88.1503 166.713 88.1619 166.644 88.1882C166.575 88.2146 166.513 88.2551 166.461 88.3073C166.409 88.3594 166.368 88.4219 166.342 88.4907C166.315 88.5595 166.304 88.6332 166.308 88.7068C166.312 88.7804 166.331 88.8523 166.365 88.9179C166.399 88.9835 166.446 89.0412 166.503 89.0874L168.071 90.6557H165.857C165.718 90.6557 165.585 90.7109 165.487 90.8092C165.388 90.9074 165.333 91.0407 165.333 91.1797C165.333 91.3186 165.388 91.4519 165.487 91.5502C165.585 91.6485 165.718 91.7037 165.857 91.7037H168.071L166.503 93.2719C166.447 93.3186 166.402 93.3763 166.369 93.4415C166.337 93.5068 166.318 93.578 166.315 93.6507C166.312 93.7234 166.324 93.796 166.35 93.8639C166.376 93.9318 166.417 93.9934 166.468 94.0449C166.52 94.0963 166.581 94.1365 166.649 94.1629C166.717 94.1892 166.79 94.2011 166.862 94.1978C166.935 94.1945 167.006 94.1761 167.071 94.1438C167.137 94.1114 167.194 94.0659 167.241 94.01L168.805 92.4417V94.6557C168.805 94.7947 168.86 94.928 168.958 95.0262C169.056 95.1245 169.19 95.1797 169.329 95.1797C169.468 95.1797 169.601 95.1245 169.699 95.0262C169.797 94.928 169.853 94.7947 169.853 94.6557V92.4417L171.421 94.01C171.468 94.0659 171.525 94.1114 171.59 94.1438C171.656 94.1761 171.727 94.1945 171.8 94.1978C171.872 94.2011 171.945 94.1892 172.013 94.1629C172.081 94.1365 172.142 94.0963 172.194 94.0449C172.245 93.9934 172.285 93.9318 172.312 93.8639C172.338 93.796 172.35 93.7234 172.347 93.6507C172.343 93.578 172.325 93.5068 172.293 93.4415C172.26 93.3763 172.215 93.3186 172.159 93.2719L170.595 91.7037H172.809C172.948 91.7037 173.082 91.6485 173.18 91.5502C173.278 91.4519 173.333 91.3186 173.333 91.1797C173.333 91.0407 173.278 90.9074 173.18 90.8092C173.082 90.7109 172.948 90.6557 172.809 90.6557Z" fill="#706D6B" /> <path d="M188.476 90.6557H186.262L187.826 89.0874C187.909 88.987 187.953 88.8588 187.947 88.7282C187.941 88.5975 187.886 88.4738 187.794 88.3813C187.701 88.2889 187.578 88.2343 187.447 88.2284C187.316 88.2225 187.188 88.2657 187.088 88.3494L185.519 89.9177V87.7037C185.519 87.5647 185.464 87.4314 185.366 87.3332C185.268 87.2349 185.134 87.1797 184.995 87.1797C184.856 87.1797 184.723 87.2349 184.625 87.3332C184.527 87.4314 184.471 87.5647 184.471 87.7037V89.9177L182.908 88.3494C182.862 88.292 182.804 88.2449 182.738 88.2113C182.673 88.1777 182.601 88.1582 182.527 88.1543C182.453 88.1503 182.38 88.1619 182.311 88.1882C182.242 88.2146 182.18 88.2551 182.128 88.3073C182.075 88.3594 182.035 88.4219 182.009 88.4907C181.982 88.5595 181.971 88.6332 181.975 88.7068C181.979 88.7804 181.998 88.8523 182.032 88.9179C182.065 88.9835 182.112 89.0412 182.17 89.0874L183.738 90.6557H181.524C181.385 90.6557 181.252 90.7109 181.153 90.8092C181.055 90.9074 181 91.0407 181 91.1797C181 91.3186 181.055 91.4519 181.153 91.5502C181.252 91.6485 181.385 91.7037 181.524 91.7037H183.738L182.17 93.2719C182.114 93.3186 182.068 93.3763 182.036 93.4415C182.004 93.5068 181.985 93.578 181.982 93.6507C181.979 93.7234 181.99 93.796 182.017 93.8639C182.043 93.9318 182.083 93.9934 182.135 94.0449C182.186 94.0963 182.248 94.1365 182.316 94.1629C182.384 94.1892 182.456 94.2011 182.529 94.1978C182.602 94.1945 182.673 94.1761 182.738 94.1438C182.803 94.1114 182.861 94.0659 182.908 94.01L184.471 92.4417V94.6557C184.471 94.7947 184.527 94.928 184.625 95.0262C184.723 95.1245 184.856 95.1797 184.995 95.1797C185.134 95.1797 185.268 95.1245 185.366 95.0262C185.464 94.928 185.519 94.7947 185.519 94.6557V92.4417L187.088 94.01C187.134 94.0659 187.192 94.1114 187.257 94.1438C187.322 94.1761 187.394 94.1945 187.466 94.1978C187.539 94.2011 187.612 94.1892 187.68 94.1629C187.747 94.1365 187.809 94.0963 187.861 94.0449C187.912 93.9934 187.952 93.9318 187.979 93.8639C188.005 93.796 188.017 93.7234 188.014 93.6507C188.01 93.578 187.992 93.5068 187.959 93.4415C187.927 93.3763 187.882 93.3186 187.826 93.2719L186.262 91.7037H188.476C188.615 91.7037 188.748 91.6485 188.847 91.5502C188.945 91.4519 189 91.3186 189 91.1797C189 91.0407 188.945 90.9074 188.847 90.8092C188.748 90.7109 188.615 90.6557 188.476 90.6557Z" fill="#706D6B" /> <g opacity="0.3" filter="url(#filter1_f_42_23582)"> <path d="M120 93.1797C120 88.7614 123.582 85.1797 128 85.1797H149C153.418 85.1797 157 88.7614 157 93.1797V105.267C157 109.686 153.418 113.267 149 113.267H128C123.582 113.267 120 109.686 120 105.267V93.1797Z" fill="#1F1548" /> </g> <path fill-rule="evenodd" clip-rule="evenodd" d="M153.447 69.9995V66.2627C153.447 57.8605 146.65 51.0547 138.26 51.0547C129.87 51.0547 123.073 57.8605 123.073 66.2627V79.428H128.02V66.2627C128.02 60.2131 132.303 55.9242 138.344 55.9242C144.385 55.9242 148.668 60.2131 148.668 66.2627V69.9995H153.447Z" fill="#706D6B" /> <path d="M156.213 110.829H120.355C118.538 110.829 117 109.359 117 107.469V78.9809C117 77.161 118.468 75.6211 120.355 75.6211H156.213C158.03 75.6211 159.568 77.091 159.568 78.9809V107.469C159.568 109.289 158.1 110.829 156.213 110.829Z" fill="url(#paint0_linear_42_23582)" /> <path d="M142.653 89.5504C142.653 87.1005 140.696 85.1406 138.249 85.1406C135.803 85.1406 133.845 87.1005 133.845 89.5504C133.845 91.2303 134.754 92.6302 136.152 93.4002L134.335 101.24H142.163L140.346 93.4002C141.744 92.7002 142.653 91.2303 142.653 89.5504Z" fill="#3D3C3A" /> <path d="M52 70C52 58.954 43.046 50 32 50C20.954 50 12 58.954 12 70C12 81.046 20.954 90 32 90C37.314 90 52 90 52 90C52 90 52 75.732 52 70Z" fill="url(#paint1_linear_42_23582)" /> <path fill-rule="evenodd" clip-rule="evenodd" d="M29.988 63.7175C32.278 61.4275 35.9909 61.4275 38.281 63.7175C40.571 66.0076 40.571 69.7205 38.281 72.0106C36.6529 73.6387 34.3057 74.1093 32.2619 73.4225L31.3701 74.3142H29.5272L29.5272 76.1571H27.6843L27.6843 77.3484C27.6843 77.7083 27.3926 78 27.0328 78H23.9985V74.5841C23.9985 74.4113 24.0672 74.2456 24.1894 74.1234L28.5761 69.7367C27.8893 67.6928 28.3599 65.3456 29.988 63.7175ZM35.4794 67.8699C36.2253 67.8699 36.83 67.2652 36.83 66.5193C36.83 65.7734 36.2253 65.1687 35.4794 65.1687C34.7334 65.1687 34.1287 65.7734 34.1287 66.5193C34.1287 67.2652 34.7334 67.8699 35.4794 67.8699Z" fill="white" /> <path d="M241 32C241 18.7452 230.255 8 217 8C203.745 8 193 18.7452 193 32C193 45.2548 203.745 56 217 56C230.255 56 241 45.2548 241 32Z" fill="url(#paint2_linear_42_23582)" /> <path fill-rule="evenodd" clip-rule="evenodd" d="M212.343 23.9885C213.545 22.7103 215.198 21.9926 216.922 22.0001C218.64 22.0003 220.288 22.7069 221.503 23.9646C222.718 25.2225 223.4 26.9285 223.4 28.7074V28.726L223.399 28.7445C223.314 29.6513 223.26 30.2323 223.236 30.699C223.151 32.3864 223.622 34.0759 224.503 35.5179L224.513 35.5343L224.821 36.1723C225.391 37.3528 224.531 38.7233 223.22 38.7233H210.669C209.344 38.7233 208.485 37.325 209.083 36.1424L209.392 35.5318L209.4 35.5192C210.24 34.1321 210.672 32.5082 210.613 30.8878C210.594 30.3825 210.538 29.765 210.444 28.744L210.442 28.7274L210.442 28.7107C210.428 26.9342 211.114 25.2286 212.343 23.9885Z" fill="white" /> <path d="M214.733 39.8184C214.733 41.0234 215.71 42.0002 216.915 42.0002C218.12 42.0002 219.097 41.0234 219.097 39.8184H214.733Z" fill="white" /> </g> <defs> <filter id="filter0_f_42_23582" x="156.3" y="-1.7" width="100.799" height="100.4" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB" > <feFlood flood-opacity="0" result="BackgroundImageFix" /> <feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape" /> <feGaussianBlur stdDeviation="13.35" result="effect1_foregroundBlur_42_23582" /> </filter> <filter id="filter1_f_42_23582" x="110.3" y="75.4797" width="56.4" height="47.4879" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB" > <feFlood flood-opacity="0" result="BackgroundImageFix" /> <feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape" /> <feGaussianBlur stdDeviation="4.85" result="effect1_foregroundBlur_42_23582" /> </filter> <linearGradient id="paint0_linear_42_23582" x1="138.284" y1="75.6211" x2="138.284" y2="110.829" gradientUnits="userSpaceOnUse" > <stop stop-color="#FFE26D" /> <stop offset="1" stop-color="#FFA16D" /> </linearGradient> <linearGradient id="paint1_linear_42_23582" x1="30.0769" y1="36.5385" x2="18.9231" y2="87.6923" gradientUnits="userSpaceOnUse" > <stop stop-color="#ECAAFF" /> <stop offset="1" stop-color="#6A48F6" /> </linearGradient> <linearGradient id="paint2_linear_42_23582" x1="217" y1="12.8169" x2="217" y2="75.1472" gradientUnits="userSpaceOnUse" > <stop stop-color="#FA5284" /> <stop offset="1" stop-color="#DC3251" /> </linearGradient> <clipPath id="clip0_42_23582"> <rect width="276" height="156" fill="white" /> </clipPath> </defs> </svg>
5,783
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/account
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/sessionRecovery/session-recovery-cancelled-illustration.svg
<svg width="152" height="100" viewBox="0 0 152 100" fill="none" xmlns="http://www.w3.org/2000/svg"> <g clip-path="url(#clip0_37_18240)"> <path fill-rule="evenodd" clip-rule="evenodd" d="M50.5089 20H101.491C105.638 20 109 23.404 109 27.603V92.397C109 96.596 105.638 100 101.491 100H50.5089C46.3618 100 43 96.596 43 92.397V27.603C43 23.404 46.3618 20 50.5089 20ZM69 27H83C83.5774 27 84 26.5948 84 26C84 25.4052 83.5774 25 83 25H69C68.4226 25 68 25.5 68 26C68 26.5 68.4226 27 69 27Z" fill="#F5F4F2" /> <mask id="mask0_37_18240" style="mask-type: alpha" maskUnits="userSpaceOnUse" x="43" y="20" width="66" height="80" > <path fill-rule="evenodd" clip-rule="evenodd" d="M50.5089 20H101.491C105.638 20 109 23.404 109 27.603V92.397C109 96.596 105.638 100 101.491 100H50.5089C46.3618 100 43 96.596 43 92.397V27.603C43 23.404 46.3618 20 50.5089 20ZM69 27.0137H83C83.5774 27.0137 84 26.6085 84 26.0137C84 25.4189 83.5774 25.0137 83 25.0137H69C68.4226 25.0137 68 25.4189 68 26.0137C68 26.6085 68.4226 27.0137 69 27.0137Z" fill="#F5F4F2" /> </mask> <g mask="url(#mask0_37_18240)"> <g opacity="0.25" filter="url(#filter0_f_37_18240)"> <path d="M96.9922 6.49805L119.325 22.1278V59.0405L116.868 57.6133C104.564 50.4682 96.9922 37.3153 96.9922 23.0873V6.49805Z" fill="#221548" /> </g> </g> <path d="M51 84.8865C51 83.2923 52.2923 82 53.8865 82H98.1135C99.7077 82 101 83.2923 101 84.8865V89.1135C101 90.7077 99.7077 92 98.1135 92H53.8865C52.2923 92 51 90.7077 51 89.1135V84.8865Z" fill="white" /> <path d="M68 26C68 25.4477 68.4477 25 69 25H83C83.5523 25 84 25.4477 84 26C84 26.5523 83.5523 27 83 27H69C68.4477 27 68 26.5523 68 26Z" fill="#E4E4E4" /> <circle cx="60.5264" cy="87" r="1" fill="#140D4B" /> <circle cx="73.123" cy="87" r="1" fill="#140D4B" /> <circle cx="85.7207" cy="87" r="1" fill="#140D4B" /> <circle cx="66.8247" cy="87" r="1" fill="#140D4B" /> <circle cx="79.4219" cy="87" r="1" fill="#140D4B" /> <circle cx="92.0186" cy="87" r="1" fill="#140D4B" /> <path d="M76 65.5583C84.8366 65.5583 92 58.4938 92 49.7792C92 41.0646 84.8366 34 76 34C67.1634 34 60 41.0646 60 49.7792C60 58.4938 67.1634 65.5583 76 65.5583Z" fill="url(#paint0_linear_37_18240)" /> <path d="M76.1905 53.1232C79.5616 53.1232 82.2945 50.3942 82.2945 47.0279C82.2945 43.6616 79.5616 40.9326 76.1905 40.9326C72.8193 40.9326 70.0864 43.6616 70.0864 47.0279C70.0864 50.3942 72.8193 53.1232 76.1905 53.1232Z" fill="#F5F4F2" /> <path d="M76.1902 65.9997C80.6919 65.9997 84.7359 64.1711 87.6353 61.1996C84.9648 57.8091 80.8445 55.6758 76.1902 55.6758C71.5359 55.6758 67.4156 57.8472 64.7451 61.1996C67.6445 64.133 71.6885 65.9997 76.1902 65.9997Z" fill="#F5F4F2" /> <path d="M57 74C57 72.8954 57.8954 72 59 72H93C94.1046 72 95 72.8954 95 74C95 75.1046 94.1046 76 93 76H59C57.8954 76 57 75.1046 57 74Z" fill="#D1CFCD" /> <path d="M0 61C0 50.5066 8.50659 42 19 42C29.4934 42 38 50.5066 38 61V80H19C8.50659 80 0 71.4934 0 61Z" fill="url(#paint1_linear_37_18240)" /> <path fill-rule="evenodd" clip-rule="evenodd" d="M23.9455 55.2756V57.1182H25.8177C26.4581 57.1182 27 57.6142 27 58.252V67.8661C27 68.4803 26.4828 69 25.8177 69H13.1823C12.5419 69 12 68.5039 12 67.8661V58.252C12 57.6379 12.5172 57.1182 13.1823 57.1182H15.0293V55.2756C15.0293 52.9134 17.0244 51 19.4874 51C21.9505 51 23.9455 52.9134 23.9455 55.2756ZM22.0683 55.2756V57.1182H16.9558V55.2756C16.9558 53.5748 18.3101 52.824 19.512 52.824C20.714 52.824 22.0683 53.5748 22.0683 55.2756ZM19.5 60C20.3333 60 21 60.6696 21 61.5065C21 62.0804 20.6905 62.5826 20.2143 62.8217L20.8333 65.5H18.1667L18.7857 62.8217C18.3095 62.5587 18 62.0804 18 61.5065C18 60.6696 18.6667 60 19.5 60Z" fill="white" /> <path d="M149.956 7.44773L127.859 0.440761C125.998 -0.14692 124.002 -0.14692 122.141 0.440761L100.044 7.44773C98.9092 7.80938 98.0924 8.84912 98.0471 10.0697C97.7294 18.5233 98.2739 51.2978 124.546 59.9322C124.864 60.0226 125.181 60.0226 125.454 59.9322C151.726 51.2978 152.271 18.5233 151.953 10.0697C151.908 8.84912 151.091 7.80938 149.956 7.44773Z" fill="url(#paint2_linear_37_18240)" /> <path d="M125.46 40C132.087 40 137.46 34.6274 137.46 28C137.46 21.3726 132.087 16 125.46 16C118.833 16 113.46 21.3726 113.46 28C113.46 34.6274 118.833 40 125.46 40Z" fill="white" /> <path fill-rule="evenodd" clip-rule="evenodd" d="M131.221 24.2536C131.54 24.5917 131.54 25.1398 131.221 25.4779L124.363 32.7464C124.044 33.0845 123.527 33.0845 123.208 32.7464L119.699 29.0271C119.38 28.6891 119.38 28.1409 119.699 27.8028C120.018 27.4647 120.535 27.4647 120.854 27.8028L123.786 30.91L130.066 24.2536C130.385 23.9155 130.902 23.9155 131.221 24.2536Z" fill="#372580" /> </g> <defs> <filter id="filter0_f_37_18240" x="85.6799" y="-4.81421" width="44.9575" height="75.1665" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB" > <feFlood flood-opacity="0" result="BackgroundImageFix" /> <feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape" /> <feGaussianBlur stdDeviation="5.65613" result="effect1_foregroundBlur_37_18240" /> </filter> <linearGradient id="paint0_linear_37_18240" x1="77.5385" y1="23.3794" x2="86.2277" y2="63.7879" gradientUnits="userSpaceOnUse" > <stop stop-color="#ECAAFF" /> <stop offset="1" stop-color="#6A48F6" /> </linearGradient> <linearGradient id="paint1_linear_37_18240" x1="23.0714" y1="42" x2="3.28846" y2="85.4808" gradientUnits="userSpaceOnUse" > <stop stop-color="#FFD66C" /> <stop offset="1" stop-color="#FF8E4F" /> </linearGradient> <linearGradient id="paint2_linear_37_18240" x1="127.799" y1="-4.375" x2="128.11" y2="60" gradientUnits="userSpaceOnUse" > <stop stop-color="#2AF091" /> <stop offset="1" stop-color="#00C5A1" /> </linearGradient> <clipPath id="clip0_37_18240"> <rect width="152" height="100" fill="white" /> </clipPath> </defs> </svg>
5,784
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/account
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/sessionRecovery/session-recovery-illustration.svg
<svg width="276" height="156" viewBox="0 0 276 156" fill="none" xmlns="http://www.w3.org/2000/svg"> <g clip-path="url(#clip0_1278_63681)"> <path d="M216 135H60V42.8255C60 37.9715 63.8331 34 68.5179 34H207.482C212.167 34 216 37.9715 216 42.8255V135Z" fill="#372580" /> <path d="M209 135H67V43.1579C67 41.9673 67.9222 41 69.0572 41H206.872C208.007 41 208.929 41.9673 208.929 43.1579V135H209Z" fill="white" /> <path d="M233.075 138H42.9252C41.2842 138 40 136.629 40 134.876V133.124C40 131.371 41.2842 130 42.9252 130H233.075C234.716 130 236 131.371 236 133.124V134.876C236 136.629 234.644 138 233.075 138Z" fill="#EAE8E5" /> <path d="M147.591 134H128.409C125.934 134 124 132.175 124 130H152C152 132.175 150.066 134 147.591 134Z" fill="#D1CFCD" /> <path d="M79.7 86C79.7 81.9683 82.9683 78.7 87 78.7H189C193.032 78.7 196.3 81.9683 196.3 86V96C196.3 100.032 193.032 103.3 189 103.3H87C82.9683 103.3 79.7 100.032 79.7 96V86Z" fill="white" stroke="#F0ECE6" stroke-width="1.4" /> <path d="M94.476 90.6552H92.262L93.8256 89.0869C93.9094 88.9865 93.9526 88.8583 93.9467 88.7277C93.9408 88.597 93.8862 88.4733 93.7937 88.3808C93.7013 88.2884 93.5775 88.2338 93.4469 88.2279C93.3162 88.222 93.1881 88.2652 93.0876 88.3489L91.5194 89.9172V87.7032C91.5194 87.5642 91.4642 87.4309 91.3659 87.3327C91.2676 87.2344 91.1344 87.1792 90.9954 87.1792C90.8564 87.1792 90.7231 87.2344 90.6249 87.3327C90.5266 87.4309 90.4714 87.5642 90.4714 87.7032V89.9172L88.9077 88.3489C88.8616 88.2915 88.8038 88.2445 88.7382 88.2108C88.6726 88.1772 88.6007 88.1578 88.5271 88.1538C88.4535 88.1498 88.3799 88.1614 88.311 88.1877C88.2422 88.2141 88.1797 88.2547 88.1276 88.3068C88.0755 88.3589 88.0349 88.4214 88.0085 88.4902C87.9822 88.559 87.9706 88.6327 87.9746 88.7063C87.9786 88.7799 87.998 88.8518 88.0316 88.9174C88.0653 88.983 88.1123 89.0407 88.1697 89.0869L89.738 90.6552H87.524C87.385 90.6552 87.2517 90.7104 87.1535 90.8087C87.0552 90.9069 87 91.0402 87 91.1792C87 91.3182 87.0552 91.4514 87.1535 91.5497C87.2517 91.648 87.385 91.7032 87.524 91.7032H89.738L88.1697 93.2715C88.1138 93.3181 88.0683 93.3758 88.0359 93.441C88.0036 93.5063 87.9852 93.5775 87.9819 93.6502C87.9786 93.7229 87.9905 93.7955 88.0168 93.8634C88.0432 93.9313 88.0833 93.9929 88.1348 94.0444C88.1863 94.0958 88.2479 94.136 88.3158 94.1624C88.3837 94.1887 88.4563 94.2006 88.529 94.1973C88.6017 94.194 88.6729 94.1756 88.7382 94.1433C88.8034 94.1109 88.8611 94.0654 88.9077 94.0095L90.4714 92.4412V94.6552C90.4714 94.7942 90.5266 94.9275 90.6249 95.0257C90.7231 95.124 90.8564 95.1792 90.9954 95.1792C91.1344 95.1792 91.2676 95.124 91.3659 95.0257C91.4642 94.9275 91.5194 94.7942 91.5194 94.6552V92.4412L93.0876 94.0095C93.1343 94.0654 93.192 94.1109 93.2572 94.1433C93.3224 94.1756 93.3937 94.194 93.4664 94.1973C93.5391 94.2006 93.6117 94.1887 93.6796 94.1624C93.7475 94.136 93.8091 94.0958 93.8606 94.0444C93.912 93.9929 93.9522 93.9313 93.9786 93.8634C94.0049 93.7955 94.0168 93.7229 94.0135 93.6502C94.0102 93.5775 93.9918 93.5063 93.9595 93.441C93.9271 93.3758 93.8816 93.3181 93.8256 93.2715L92.262 91.7032H94.476C94.615 91.7032 94.7483 91.648 94.8465 91.5497C94.9448 91.4514 95 91.3182 95 91.1792C95 91.0402 94.9448 90.9069 94.8465 90.8087C94.7483 90.7104 94.615 90.6552 94.476 90.6552Z" fill="#706D6B" /> <path d="M110.143 90.6552H107.928L109.492 89.0869C109.576 88.9865 109.619 88.8583 109.613 88.7277C109.607 88.597 109.553 88.4733 109.46 88.3808C109.368 88.2884 109.244 88.2338 109.113 88.2279C108.983 88.222 108.855 88.2652 108.754 88.3489L107.186 89.9172V87.7032C107.186 87.5642 107.131 87.4309 107.032 87.3327C106.934 87.2344 106.801 87.1792 106.662 87.1792C106.523 87.1792 106.39 87.2344 106.291 87.3327C106.193 87.4309 106.138 87.5642 106.138 87.7032V89.9172L104.574 88.3489C104.528 88.2915 104.47 88.2445 104.405 88.2108C104.339 88.1772 104.267 88.1578 104.194 88.1538C104.12 88.1498 104.046 88.1614 103.978 88.1877C103.909 88.2141 103.846 88.2547 103.794 88.3068C103.742 88.3589 103.701 88.4214 103.675 88.4902C103.649 88.559 103.637 88.6327 103.641 88.7063C103.645 88.7799 103.665 88.8518 103.698 88.9174C103.732 88.983 103.779 89.0407 103.836 89.0869L105.405 90.6552H103.19C103.052 90.6552 102.918 90.7104 102.82 90.8087C102.722 90.9069 102.667 91.0402 102.667 91.1792C102.667 91.3182 102.722 91.4514 102.82 91.5497C102.918 91.648 103.052 91.7032 103.19 91.7032H105.405L103.836 93.2715C103.78 93.3181 103.735 93.3758 103.702 93.441C103.67 93.5063 103.652 93.5775 103.648 93.6502C103.645 93.7229 103.657 93.7955 103.683 93.8634C103.71 93.9313 103.75 93.9929 103.801 94.0444C103.853 94.0958 103.914 94.136 103.982 94.1624C104.05 94.1887 104.123 94.2006 104.195 94.1973C104.268 94.194 104.339 94.1756 104.405 94.1433C104.47 94.1109 104.528 94.0654 104.574 94.0095L106.138 92.4412V94.6552C106.138 94.7942 106.193 94.9275 106.291 95.0257C106.39 95.124 106.523 95.1792 106.662 95.1792C106.801 95.1792 106.934 95.124 107.032 95.0257C107.131 94.9275 107.186 94.7942 107.186 94.6552V92.4412L108.754 94.0095C108.801 94.0654 108.859 94.1109 108.924 94.1433C108.989 94.1756 109.06 94.194 109.133 94.1973C109.206 94.2006 109.278 94.1887 109.346 94.1624C109.414 94.136 109.476 94.0958 109.527 94.0444C109.579 93.9929 109.619 93.9313 109.645 93.8634C109.671 93.7955 109.683 93.7229 109.68 93.6502C109.677 93.5775 109.658 93.5063 109.626 93.441C109.594 93.3758 109.548 93.3181 109.492 93.2715L107.928 91.7032H110.143C110.281 91.7032 110.415 91.648 110.513 91.5497C110.611 91.4514 110.667 91.3182 110.667 91.1792C110.667 91.0402 110.611 90.9069 110.513 90.8087C110.415 90.7104 110.281 90.6552 110.143 90.6552Z" fill="#706D6B" /> <path d="M125.81 90.6552H123.595L125.159 89.0869C125.243 88.9865 125.286 88.8583 125.28 88.7277C125.274 88.597 125.22 88.4733 125.127 88.3808C125.035 88.2884 124.911 88.2338 124.78 88.2279C124.65 88.222 124.522 88.2652 124.421 88.3489L122.853 89.9172V87.7032C122.853 87.5642 122.798 87.4309 122.699 87.3327C122.601 87.2344 122.468 87.1792 122.329 87.1792C122.19 87.1792 122.057 87.2344 121.958 87.3327C121.86 87.4309 121.805 87.5642 121.805 87.7032V89.9172L120.241 88.3489C120.195 88.2915 120.137 88.2445 120.072 88.2108C120.006 88.1772 119.934 88.1578 119.861 88.1538C119.787 88.1498 119.713 88.1614 119.645 88.1877C119.576 88.2141 119.513 88.2547 119.461 88.3068C119.409 88.3589 119.368 88.4214 119.342 88.4902C119.316 88.559 119.304 88.6327 119.308 88.7063C119.312 88.7799 119.332 88.8518 119.365 88.9174C119.399 88.983 119.446 89.0407 119.503 89.0869L121.072 90.6552H118.857C118.719 90.6552 118.585 90.7104 118.487 90.8087C118.389 90.9069 118.333 91.0402 118.333 91.1792C118.333 91.3182 118.389 91.4514 118.487 91.5497C118.585 91.648 118.719 91.7032 118.857 91.7032H121.072L119.503 93.2715C119.447 93.3181 119.402 93.3758 119.369 93.441C119.337 93.5063 119.319 93.5775 119.315 93.6502C119.312 93.7229 119.324 93.7955 119.35 93.8634C119.377 93.9313 119.417 93.9929 119.468 94.0444C119.52 94.0958 119.581 94.136 119.649 94.1624C119.717 94.1887 119.79 94.2006 119.862 94.1973C119.935 94.194 120.006 94.1756 120.072 94.1433C120.137 94.1109 120.195 94.0654 120.241 94.0095L121.805 92.4412V94.6552C121.805 94.7942 121.86 94.9275 121.958 95.0257C122.057 95.124 122.19 95.1792 122.329 95.1792C122.468 95.1792 122.601 95.124 122.699 95.0257C122.798 94.9275 122.853 94.7942 122.853 94.6552V92.4412L124.421 94.0095C124.468 94.0654 124.526 94.1109 124.591 94.1433C124.656 94.1756 124.727 94.194 124.8 94.1973C124.873 94.2006 124.945 94.1887 125.013 94.1624C125.081 94.136 125.143 94.0958 125.194 94.0444C125.246 93.9929 125.286 93.9313 125.312 93.8634C125.338 93.7955 125.35 93.7229 125.347 93.6502C125.344 93.5775 125.325 93.5063 125.293 93.441C125.261 93.3758 125.215 93.3181 125.159 93.2715L123.595 91.7032H125.81C125.948 91.7032 126.082 91.648 126.18 91.5497C126.278 91.4514 126.333 91.3182 126.333 91.1792C126.333 91.0402 126.278 90.9069 126.18 90.8087C126.082 90.7104 125.948 90.6552 125.81 90.6552Z" fill="#706D6B" /> <path d="M141.476 90.6552H139.262L140.826 89.0869C140.909 88.9865 140.953 88.8583 140.947 88.7277C140.941 88.597 140.886 88.4733 140.794 88.3808C140.701 88.2884 140.578 88.2338 140.447 88.2279C140.316 88.222 140.188 88.2652 140.088 88.3489L138.519 89.9172V87.7032C138.519 87.5642 138.464 87.4309 138.366 87.3327C138.268 87.2344 138.134 87.1792 137.995 87.1792C137.856 87.1792 137.723 87.2344 137.625 87.3327C137.527 87.4309 137.471 87.5642 137.471 87.7032V89.9172L135.908 88.3489C135.862 88.2915 135.804 88.2445 135.738 88.2108C135.673 88.1772 135.601 88.1578 135.527 88.1538C135.453 88.1498 135.38 88.1614 135.311 88.1877C135.242 88.2141 135.18 88.2547 135.128 88.3068C135.075 88.3589 135.035 88.4214 135.009 88.4902C134.982 88.559 134.971 88.6327 134.975 88.7063C134.979 88.7799 134.998 88.8518 135.032 88.9174C135.065 88.983 135.112 89.0407 135.17 89.0869L136.738 90.6552H134.524C134.385 90.6552 134.252 90.7104 134.153 90.8087C134.055 90.9069 134 91.0402 134 91.1792C134 91.3182 134.055 91.4514 134.153 91.5497C134.252 91.648 134.385 91.7032 134.524 91.7032H136.738L135.17 93.2715C135.114 93.3181 135.068 93.3758 135.036 93.441C135.004 93.5063 134.985 93.5775 134.982 93.6502C134.979 93.7229 134.99 93.7955 135.017 93.8634C135.043 93.9313 135.083 93.9929 135.135 94.0444C135.186 94.0958 135.248 94.136 135.316 94.1624C135.384 94.1887 135.456 94.2006 135.529 94.1973C135.602 94.194 135.673 94.1756 135.738 94.1433C135.803 94.1109 135.861 94.0654 135.908 94.0095L137.471 92.4412V94.6552C137.471 94.7942 137.527 94.9275 137.625 95.0257C137.723 95.124 137.856 95.1792 137.995 95.1792C138.134 95.1792 138.268 95.124 138.366 95.0257C138.464 94.9275 138.519 94.7942 138.519 94.6552V92.4412L140.088 94.0095C140.134 94.0654 140.192 94.1109 140.257 94.1433C140.322 94.1756 140.394 94.194 140.466 94.1973C140.539 94.2006 140.612 94.1887 140.68 94.1624C140.747 94.136 140.809 94.0958 140.861 94.0444C140.912 93.9929 140.952 93.9313 140.979 93.8634C141.005 93.7955 141.017 93.7229 141.014 93.6502C141.01 93.5775 140.992 93.5063 140.959 93.441C140.927 93.3758 140.882 93.3181 140.826 93.2715L139.262 91.7032H141.476C141.615 91.7032 141.748 91.648 141.847 91.5497C141.945 91.4514 142 91.3182 142 91.1792C142 91.0402 141.945 90.9069 141.847 90.8087C141.748 90.7104 141.615 90.6552 141.476 90.6552Z" fill="#706D6B" /> <path d="M157.143 90.6552H154.928L156.492 89.0869C156.576 88.9865 156.619 88.8583 156.613 88.7277C156.607 88.597 156.553 88.4733 156.46 88.3808C156.368 88.2884 156.244 88.2338 156.113 88.2279C155.983 88.222 155.855 88.2652 155.754 88.3489L154.186 89.9172V87.7032C154.186 87.5642 154.131 87.4309 154.032 87.3327C153.934 87.2344 153.801 87.1792 153.662 87.1792C153.523 87.1792 153.39 87.2344 153.291 87.3327C153.193 87.4309 153.138 87.5642 153.138 87.7032V89.9172L151.574 88.3489C151.528 88.2915 151.47 88.2445 151.405 88.2108C151.339 88.1772 151.267 88.1578 151.194 88.1538C151.12 88.1498 151.046 88.1614 150.978 88.1877C150.909 88.2141 150.846 88.2547 150.794 88.3068C150.742 88.3589 150.701 88.4214 150.675 88.4902C150.649 88.559 150.637 88.6327 150.641 88.7063C150.645 88.7799 150.665 88.8518 150.698 88.9174C150.732 88.983 150.779 89.0407 150.836 89.0869L152.405 90.6552H150.19C150.052 90.6552 149.918 90.7104 149.82 90.8087C149.722 90.9069 149.667 91.0402 149.667 91.1792C149.667 91.3182 149.722 91.4514 149.82 91.5497C149.918 91.648 150.052 91.7032 150.19 91.7032H152.405L150.836 93.2715C150.78 93.3181 150.735 93.3758 150.702 93.441C150.67 93.5063 150.652 93.5775 150.648 93.6502C150.645 93.7229 150.657 93.7955 150.683 93.8634C150.71 93.9313 150.75 93.9929 150.801 94.0444C150.853 94.0958 150.914 94.136 150.982 94.1624C151.05 94.1887 151.123 94.2006 151.195 94.1973C151.268 94.194 151.339 94.1756 151.405 94.1433C151.47 94.1109 151.528 94.0654 151.574 94.0095L153.138 92.4412V94.6552C153.138 94.7942 153.193 94.9275 153.291 95.0257C153.39 95.124 153.523 95.1792 153.662 95.1792C153.801 95.1792 153.934 95.124 154.032 95.0257C154.131 94.9275 154.186 94.7942 154.186 94.6552V92.4412L155.754 94.0095C155.801 94.0654 155.859 94.1109 155.924 94.1433C155.989 94.1756 156.06 94.194 156.133 94.1973C156.206 94.2006 156.278 94.1887 156.346 94.1624C156.414 94.136 156.476 94.0958 156.527 94.0444C156.579 93.9929 156.619 93.9313 156.645 93.8634C156.671 93.7955 156.683 93.7229 156.68 93.6502C156.677 93.5775 156.658 93.5063 156.626 93.441C156.594 93.3758 156.548 93.3181 156.492 93.2715L154.928 91.7032H157.143C157.281 91.7032 157.415 91.648 157.513 91.5497C157.611 91.4514 157.667 91.3182 157.667 91.1792C157.667 91.0402 157.611 90.9069 157.513 90.8087C157.415 90.7104 157.281 90.6552 157.143 90.6552Z" fill="#706D6B" /> <path d="M172.81 90.6552H170.595L172.159 89.0869C172.243 88.9865 172.286 88.8583 172.28 88.7277C172.274 88.597 172.22 88.4733 172.127 88.3808C172.035 88.2884 171.911 88.2338 171.78 88.2279C171.65 88.222 171.522 88.2652 171.421 88.3489L169.853 89.9172V87.7032C169.853 87.5642 169.798 87.4309 169.699 87.3327C169.601 87.2344 169.468 87.1792 169.329 87.1792C169.19 87.1792 169.057 87.2344 168.958 87.3327C168.86 87.4309 168.805 87.5642 168.805 87.7032V89.9172L167.241 88.3489C167.195 88.2915 167.137 88.2445 167.072 88.2108C167.006 88.1772 166.934 88.1578 166.861 88.1538C166.787 88.1498 166.713 88.1614 166.645 88.1877C166.576 88.2141 166.513 88.2547 166.461 88.3068C166.409 88.3589 166.368 88.4214 166.342 88.4902C166.316 88.559 166.304 88.6327 166.308 88.7063C166.312 88.7799 166.332 88.8518 166.365 88.9174C166.399 88.983 166.446 89.0407 166.503 89.0869L168.072 90.6552H165.857C165.719 90.6552 165.585 90.7104 165.487 90.8087C165.389 90.9069 165.333 91.0402 165.333 91.1792C165.333 91.3182 165.389 91.4514 165.487 91.5497C165.585 91.648 165.719 91.7032 165.857 91.7032H168.072L166.503 93.2715C166.447 93.3181 166.402 93.3758 166.369 93.441C166.337 93.5063 166.319 93.5775 166.315 93.6502C166.312 93.7229 166.324 93.7955 166.35 93.8634C166.377 93.9313 166.417 93.9929 166.468 94.0444C166.52 94.0958 166.581 94.136 166.649 94.1624C166.717 94.1887 166.79 94.2006 166.862 94.1973C166.935 94.194 167.006 94.1756 167.072 94.1433C167.137 94.1109 167.195 94.0654 167.241 94.0095L168.805 92.4412V94.6552C168.805 94.7942 168.86 94.9275 168.958 95.0257C169.057 95.124 169.19 95.1792 169.329 95.1792C169.468 95.1792 169.601 95.124 169.699 95.0257C169.798 94.9275 169.853 94.7942 169.853 94.6552V92.4412L171.421 94.0095C171.468 94.0654 171.526 94.1109 171.591 94.1433C171.656 94.1756 171.727 94.194 171.8 94.1973C171.873 94.2006 171.945 94.1887 172.013 94.1624C172.081 94.136 172.143 94.0958 172.194 94.0444C172.246 93.9929 172.286 93.9313 172.312 93.8634C172.338 93.7955 172.35 93.7229 172.347 93.6502C172.344 93.5775 172.325 93.5063 172.293 93.441C172.261 93.3758 172.215 93.3181 172.159 93.2715L170.595 91.7032H172.81C172.948 91.7032 173.082 91.648 173.18 91.5497C173.278 91.4514 173.333 91.3182 173.333 91.1792C173.333 91.0402 173.278 90.9069 173.18 90.8087C173.082 90.7104 172.948 90.6552 172.81 90.6552Z" fill="#706D6B" /> <path d="M188.476 90.6552H186.262L187.826 89.0869C187.909 88.9865 187.953 88.8583 187.947 88.7277C187.941 88.597 187.886 88.4733 187.794 88.3808C187.701 88.2884 187.578 88.2338 187.447 88.2279C187.316 88.222 187.188 88.2652 187.088 88.3489L185.519 89.9172V87.7032C185.519 87.5642 185.464 87.4309 185.366 87.3327C185.268 87.2344 185.134 87.1792 184.995 87.1792C184.856 87.1792 184.723 87.2344 184.625 87.3327C184.527 87.4309 184.471 87.5642 184.471 87.7032V89.9172L182.908 88.3489C182.862 88.2915 182.804 88.2445 182.738 88.2108C182.673 88.1772 182.601 88.1578 182.527 88.1538C182.453 88.1498 182.38 88.1614 182.311 88.1877C182.242 88.2141 182.18 88.2547 182.128 88.3068C182.075 88.3589 182.035 88.4214 182.009 88.4902C181.982 88.559 181.971 88.6327 181.975 88.7063C181.979 88.7799 181.998 88.8518 182.032 88.9174C182.065 88.983 182.112 89.0407 182.17 89.0869L183.738 90.6552H181.524C181.385 90.6552 181.252 90.7104 181.153 90.8087C181.055 90.9069 181 91.0402 181 91.1792C181 91.3182 181.055 91.4514 181.153 91.5497C181.252 91.648 181.385 91.7032 181.524 91.7032H183.738L182.17 93.2715C182.114 93.3181 182.068 93.3758 182.036 93.441C182.004 93.5063 181.985 93.5775 181.982 93.6502C181.979 93.7229 181.99 93.7955 182.017 93.8634C182.043 93.9313 182.083 93.9929 182.135 94.0444C182.186 94.0958 182.248 94.136 182.316 94.1624C182.384 94.1887 182.456 94.2006 182.529 94.1973C182.602 94.194 182.673 94.1756 182.738 94.1433C182.803 94.1109 182.861 94.0654 182.908 94.0095L184.471 92.4412V94.6552C184.471 94.7942 184.527 94.9275 184.625 95.0257C184.723 95.124 184.856 95.1792 184.995 95.1792C185.134 95.1792 185.268 95.124 185.366 95.0257C185.464 94.9275 185.519 94.7942 185.519 94.6552V92.4412L187.088 94.0095C187.134 94.0654 187.192 94.1109 187.257 94.1433C187.322 94.1756 187.394 94.194 187.466 94.1973C187.539 94.2006 187.612 94.1887 187.68 94.1624C187.747 94.136 187.809 94.0958 187.861 94.0444C187.912 93.9929 187.952 93.9313 187.979 93.8634C188.005 93.7955 188.017 93.7229 188.014 93.6502C188.01 93.5775 187.992 93.5063 187.959 93.441C187.927 93.3758 187.882 93.3181 187.826 93.2715L186.262 91.7032H188.476C188.615 91.7032 188.748 91.648 188.847 91.5497C188.945 91.4514 189 91.3182 189 91.1792C189 91.0402 188.945 90.9069 188.847 90.8087C188.748 90.7104 188.615 90.6552 188.476 90.6552Z" fill="#706D6B" /> <mask id="mask0_1278_63681" style="mask-type: alpha" maskUnits="userSpaceOnUse" x="67" y="41" width="142" height="94" > <path d="M209 135H67V43.1579C67 41.9673 67.9222 41 69.0572 41H206.872C208.007 41 208.929 41.9673 208.929 43.1579V135H209Z" fill="white" /> </mask> <g mask="url(#mask0_1278_63681)"> <g opacity="0.2" filter="url(#filter0_f_1278_63681)"> <path d="M236.037 68.981L225.028 88.0498L203.009 88.0498L192 68.981L203.009 49.9121L225.028 49.9121L236.037 68.981Z" fill="#221548" /> </g> </g> <path d="M14 76C14 65.5066 22.5066 57 33 57C43.4934 57 52 65.5066 52 76V95H33C22.5066 95 14 86.4934 14 76Z" fill="url(#paint0_linear_1278_63681)" /> <path fill-rule="evenodd" clip-rule="evenodd" d="M37.9455 70.2756V72.1182H39.8177C40.4581 72.1182 41 72.6142 41 73.252V82.8661C41 83.4803 40.4828 84 39.8177 84H27.1823C26.5419 84 26 83.5039 26 82.8661V73.252C26 72.6379 26.5172 72.1182 27.1823 72.1182H29.0293V70.2756C29.0293 67.9134 31.0244 66 33.4874 66C35.9505 66 37.9455 67.9134 37.9455 70.2756ZM36.0683 70.2756V72.1182H30.9558V70.2756C30.9558 68.5748 32.3101 67.824 33.512 67.824C34.714 67.824 36.0683 68.5748 36.0683 70.2756ZM33.5 75C34.3333 75 35 75.6696 35 76.5065C35 77.0804 34.6905 77.5826 34.2143 77.8217L34.8333 80.5H32.1667L32.7857 77.8217C32.3095 77.5587 32 77.0804 32 76.5065C32 75.6696 32.6667 75 33.5 75Z" fill="white" /> <g opacity="0.2" filter="url(#filter1_f_1278_63681)"> <path d="M119 95C119 85.0589 127.059 77 137 77H139C148.941 77 157 85.0589 157 95C157 104.941 148.941 113 139 113H137C127.059 113 119 104.941 119 95Z" fill="#1F1548" /> </g> <g filter="url(#filter2_d_1278_63681)"> <rect x="114" y="63" width="48" height="48" rx="24" fill="url(#paint1_linear_1278_63681)" /> </g> <g filter="url(#filter3_i_1278_63681)"> <circle cx="138" cy="87" r="20" fill="url(#paint2_linear_1278_63681)" /> </g> <path d="M138.455 75V87.1129L133 93.5455" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" /> <path d="M238.719 63.525C239.39 64.716 239.39 66.1834 238.719 67.3745L229.34 84.025C228.67 85.216 227.43 85.9497 226.088 85.9497H207.331C205.989 85.9497 204.749 85.216 204.078 84.025L194.699 67.3745C194.029 66.1834 194.029 64.716 194.699 63.525L204.078 46.8745C204.749 45.6834 205.989 44.9497 207.331 44.9497L226.088 44.9497C227.43 44.9497 228.67 45.6834 229.34 46.8745L238.719 63.525Z" fill="url(#paint3_linear_1278_63681)" /> <path d="M217.639 53.2009C216.852 53.2009 216.215 53.8618 216.215 54.6769V63.6805C216.215 63.8979 216.045 64.0741 215.835 64.0741C215.625 64.0741 215.455 63.8979 215.455 63.6805V55.6609C215.455 54.8458 214.818 54.1849 214.031 54.1849C213.245 54.1849 212.607 54.8458 212.607 55.6609V64.7137C212.607 64.9311 212.437 65.1073 212.228 65.1073C212.018 65.1073 211.848 64.9311 211.848 64.7137V58.5145C211.848 57.6994 211.21 57.0385 210.424 57.0385C209.638 57.0385 209 57.6994 209 58.5145V71.9953H209.018C209.26 75.2435 211.88 77.8009 215.075 77.8009C219.506 77.8009 222.206 77.7999 216.505 77.8009C221.28 77.8009 222.591 75.522 224.408 72.6057L224.41 72.6038C224.554 72.372 224.701 72.136 224.853 71.8969L227.423 67.292C227.925 66.3915 227.627 65.2401 226.758 64.7203C225.89 64.2004 224.779 64.5089 224.277 65.4093L223.113 67.5003C222.991 67.7183 222.67 67.629 222.67 67.3773V56.4973C222.67 55.6822 222.032 55.0213 221.246 55.0213C220.459 55.0213 219.822 55.6822 219.822 56.4973V63.6805C219.822 63.8979 219.652 64.0741 219.442 64.0741C219.232 64.0741 219.062 63.8979 219.062 63.6805V54.6769C219.062 53.8618 218.425 53.2009 217.639 53.2009Z" fill="white" /> </g> <defs> <filter id="filter0_f_1278_63681" x="180.53" y="38.4425" width="66.9768" height="61.0769" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB" > <feFlood flood-opacity="0" result="BackgroundImageFix" /> <feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape" /> <feGaussianBlur stdDeviation="5.73481" result="effect1_foregroundBlur_1278_63681" /> </filter> <filter id="filter1_f_1278_63681" x="109.3" y="67.3" width="57.4" height="55.4" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB" > <feFlood flood-opacity="0" result="BackgroundImageFix" /> <feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape" /> <feGaussianBlur stdDeviation="4.85" result="effect1_foregroundBlur_1278_63681" /> </filter> <filter id="filter2_d_1278_63681" x="114" y="63" width="48.5" height="48.5" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB" > <feFlood flood-opacity="0" result="BackgroundImageFix" /> <feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha" /> <feOffset dx="0.5" dy="0.5" /> <feComposite in2="hardAlpha" operator="out" /> <feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.05 0" /> <feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_1278_63681" /> <feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_1278_63681" result="shape" /> </filter> <filter id="filter3_i_1278_63681" x="118" y="67" width="40" height="40.3333" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB" > <feFlood flood-opacity="0" result="BackgroundImageFix" /> <feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape" /> <feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha" /> <feOffset dy="0.333333" /> <feGaussianBlur stdDeviation="0.166667" /> <feComposite in2="hardAlpha" operator="arithmetic" k2="-1" k3="1" /> <feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.16 0" /> <feBlend mode="normal" in2="shape" result="effect1_innerShadow_1278_63681" /> </filter> <linearGradient id="paint0_linear_1278_63681" x1="37.0714" y1="57" x2="17.2885" y2="100.481" gradientUnits="userSpaceOnUse" > <stop stop-color="#FFD66C" /> <stop offset="1" stop-color="#FF8E4F" /> </linearGradient> <linearGradient id="paint1_linear_1278_63681" x1="187" y1="34.5" x2="126.5" y2="124.5" gradientUnits="userSpaceOnUse" > <stop offset="0.217324" stop-color="white" /> <stop offset="0.621556" stop-color="#ECEAE6" /> <stop offset="0.936658" stop-color="#BEBBB9" /> </linearGradient> <linearGradient id="paint2_linear_1278_63681" x1="138" y1="67" x2="138" y2="107" gradientUnits="userSpaceOnUse"> <stop stop-color="#8F8F8F" /> <stop offset="1" /> </linearGradient> <linearGradient id="paint3_linear_1278_63681" x1="237.372" y1="65.4497" x2="190.88" y2="65.4497" gradientUnits="userSpaceOnUse" > <stop stop-color="#FF7171" /> <stop offset="1" stop-color="#E63757" /> </linearGradient> <clipPath id="clip0_1278_63681"> <rect width="276" height="156" fill="white" /> </clipPath> </defs> </svg>
5,785
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/sessionRecovery
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/sessionRecovery/statusCards/PasswordResetAvailableCard.tsx
import { format } from 'date-fns'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { dateLocale } from '@proton/shared/lib/i18n'; import clsx from '@proton/utils/clsx'; import { useModalState } from '../../../../components'; import { useUser } from '../../../../hooks'; import ConfirmSessionRecoveryCancellationModal from '../ConfirmSessionRecoveryCancellationModal'; import PasswordResetAvailableAccountModal from '../PasswordResetAvailableAccountModal'; import SessionRecoveryStatusTitle from './SessionRecoveryStatusTitle'; import handWarningIcon from './hand-warning-icon.svg'; import lockIcon from './lock-tick-icon.svg'; interface Props { className?: string; } const PasswordResetAvailableCard = ({ className }: Props) => { const [user] = useUser(); const [ sessionRecoveryPasswordResetModal, setSessionRecoveryPasswordResetModalOpen, renderSessionRecoveryPasswordResetModal, ] = useModalState(); const [confirmCancelModalProps, setConfirmCancelModalOpen, renderConfirmCancelModal] = useModalState(); if (!user.AccountRecovery) { return null; } const endDate = new Date(user.AccountRecovery.EndTime * 1000); const formattedDate = format(endDate, 'PP', { locale: dateLocale }); const boldDate = <b key="bold-date">{formattedDate}</b>; return ( <> {renderSessionRecoveryPasswordResetModal && ( <PasswordResetAvailableAccountModal {...sessionRecoveryPasswordResetModal} /> )} {renderConfirmCancelModal && <ConfirmSessionRecoveryCancellationModal {...confirmCancelModalProps} />} <div className={clsx('max-w-custom rounded-lg border', className)} style={{ '--max-w-custom': '46em' }}> <div className="p-6 border-bottom border-weak"> <SessionRecoveryStatusTitle status="available" /> </div> <div className="p-6 border-bottom border-weak sm:flex flex-align-items-start flex-nowrap"> <img className="mb-2 sm:mb-0 sm:mr-4 flex-item-noshrink" src={lockIcon} alt="" /> <div> <h3 className="mb-1 text-bold text-lg">{c('session_recovery:available:info') .t`You can now reset your password`}</h3> <div>{c('session_recovery:available:info') .jt`You can reset your password until ${boldDate}.`}</div> <Button className="mt-4 w-full sm:w-auto" onClick={() => setSessionRecoveryPasswordResetModalOpen(true)} color="norm" shape="outline" > {c('session_recovery:available:action').t`Reset password`} </Button> </div> </div> <div className="p-6 sm:flex flex-align-items-start flex-nowrap"> <img className="mb-2 sm:mb-0 sm:mr-4 flex-item-noshrink" src={handWarningIcon} alt="" /> <div> <h3 className="mb-1 text-bold text-lg">{c('session_recovery:available:info') .t`Didn’t make this request?`}</h3> <div className="mb-4"> {c('session_recovery:available:info') .t`If you didn’t ask to reset your password, cancel the request now.`} </div> <Button className="w-full sm:w-auto" onClick={() => setConfirmCancelModalOpen(true)} color="danger" shape="outline" > {c('session_recovery:available:action').t`Cancel password reset`} </Button> </div> </div> </div> </> ); }; export default PasswordResetAvailableCard;
5,786
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/sessionRecovery
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/sessionRecovery/statusCards/SessionRecoveryInProgressCard.tsx
import { format } from 'date-fns'; import { c, msgid } from 'ttag'; import { Button } from '@proton/atoms'; import { dateLocale } from '@proton/shared/lib/i18n'; import clsx from '@proton/utils/clsx'; import { useModalState } from '../../../../components'; import { useSessionRecoveryGracePeriodHoursRemaining, useUser } from '../../../../hooks'; import ConfirmSessionRecoveryCancellationModal from '../ConfirmSessionRecoveryCancellationModal'; import SessionRecoveryStatusTitle from './SessionRecoveryStatusTitle'; import handWarningIcon from './hand-warning-icon.svg'; import lockIcon from './lock-icon.svg'; interface Props { className?: string; } const SessionRecoveryInProgressCard = ({ className }: Props) => { const [user] = useUser(); const gracePeriodHoursRemaining = useSessionRecoveryGracePeriodHoursRemaining(); const [confirmCancelModalProps, setConfirmCancelModalOpen, renderConfirmCancelModal] = useModalState(); if (!user.AccountRecovery || gracePeriodHoursRemaining === null) { return null; } const endDate = new Date(user.AccountRecovery.EndTime * 1000); const formattedDate = format(endDate, 'PP', { locale: dateLocale }); const boldDate = ( <b key="bold-date" data-testid="session_recovery:from_date"> {formattedDate} </b> ); return ( <> {renderConfirmCancelModal && <ConfirmSessionRecoveryCancellationModal {...confirmCancelModalProps} />} <div className={clsx('max-w-custom rounded-lg border', className)} style={{ '--max-w-custom': '46em' }} data-testid="session_recovery:request_section" > <div className="p-6 border-bottom border-weak"> <SessionRecoveryStatusTitle status="pending" /> </div> <div className="p-6 border-bottom border-weak sm:flex flex-align-items-start flex-nowrap"> <img className="mb-2 sm:mb-0 sm:mr-4 flex-item-noshrink" src={lockIcon} alt="" /> <div> <h3 className="text-bold text-lg"> {c('session_recovery:in_progress:info').ngettext( msgid`You can change your password in ${gracePeriodHoursRemaining} hour`, `You can change your password in ${gracePeriodHoursRemaining} hours`, gracePeriodHoursRemaining )} </h3> <div> {c('session_recovery:in_progress:info') .jt`Password reset available from ${boldDate}. This gives you time to cancel any fraudulent requests.`} </div> </div> </div> <div className="p-6 sm:flex flex-align-items-start flex-nowrap"> <img className="mb-2 sm:mb-0 sm:mr-4 flex-item-noshrink" src={handWarningIcon} alt="" /> <div> <h3 className="text-bold text-lg">{c('session_recovery:in_progress:info') .t`Didn’t make this request?`}</h3> <div className="mb-4"> {c('session_recovery:in_progress:info') .t`If you didn’t ask to reset your password, cancel the request now.`} </div> <Button className="w-full sm:w-auto" onClick={() => setConfirmCancelModalOpen(true)} color="danger" shape="outline" > {c('session_recovery:in_progress:action').t`Cancel password reset`} </Button> </div> </div> </div> </> ); }; export default SessionRecoveryInProgressCard;
5,787
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/sessionRecovery
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/sessionRecovery/statusCards/SessionRecoveryStatusTitle.tsx
import { c } from 'ttag'; import { useUser } from '@proton/components/hooks'; import clsx from '@proton/utils/clsx'; interface Props { status: 'pending' | 'available'; } const SessionRecoveryStatusTitle = ({ status }: Props) => { const [user] = useUser(); const { statusText, backgroundClass } = (() => { if (status === 'pending') { return { statusText: c('session_recovery:status:info').t`Pending`, backgroundClass: 'bg-warning', }; } return { statusText: c('session_recovery:status:info').t`Available`, backgroundClass: 'bg-primary', }; })(); return ( <> <div className="flex flex-nowrap flex-align-items-baseline"> <h2 className="h3 text-bold mr-2">{c('session_recovery:status:title').t`Password reset request`}</h2> <span className={clsx( backgroundClass, 'flex-item-noshrink text-uppercase text-sm text-semibold rounded-sm px-1 text-nowrap mt-1.5' )} > {statusText} </span> </div> <div className="color-weak" data-testid="session_recovery:user_email"> {user.Email} </div> </> ); }; export default SessionRecoveryStatusTitle;
5,788
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/sessionRecovery
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/sessionRecovery/statusCards/hand-warning-icon.svg
<svg width="48" height="48" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M42.9663 22.2096C43.606 23.3175 43.606 24.6825 42.9663 25.7904L35.0337 39.5301C34.394 40.638 33.2119 41.3205 31.9326 41.3205L16.0674 41.3205C14.7881 41.3205 13.606 40.638 12.9663 39.5301L5.03368 25.7904C4.39404 24.6825 4.39404 23.3175 5.03368 22.2096L12.9663 8.46987C13.606 7.36198 14.7881 6.67949 16.0674 6.67949L31.9326 6.67949C33.2119 6.67949 34.394 7.36198 35.0337 8.46987L42.9663 22.2096Z" fill="url(#paint0_linear_45_20531)" /> <path d="M24.9744 13.1992C24.2666 13.1992 23.6928 13.7795 23.6928 14.4952V22.4008C23.6928 22.5917 23.5398 22.7464 23.3511 22.7464C23.1623 22.7464 23.0093 22.5917 23.0093 22.4008V15.3592C23.0093 14.6435 22.4356 14.0632 21.7278 14.0632C21.02 14.0632 20.4463 14.6435 20.4463 15.3592V23.308C20.4463 23.4989 20.2933 23.6536 20.1045 23.6536C19.9158 23.6536 19.7628 23.4989 19.7628 23.308V17.8648C19.7628 17.1491 19.189 16.5688 18.4812 16.5688C17.7735 16.5688 17.1997 17.1491 17.1997 17.8648V29.7016H17.2161C17.4341 32.5536 19.7915 34.7992 22.6676 34.7992C26.6554 34.7992 29.0849 34.7983 23.9538 34.7992C28.2518 34.7992 29.4317 32.7982 31.0673 30.2375L31.0683 30.2359C31.1983 30.0323 31.3306 29.8252 31.4675 29.6152L33.7804 25.5719C34.2318 24.7812 33.964 23.7702 33.1821 23.3137C32.4003 22.8573 31.4006 23.1282 30.9492 23.9188L29.901 25.7548C29.7918 25.9462 29.5025 25.8678 29.5025 25.6468V16.0936C29.5025 15.3779 28.9287 14.7976 28.2209 14.7976C27.5132 14.7976 26.9394 15.3779 26.9394 16.0936V22.4008C26.9394 22.5917 26.7864 22.7464 26.5976 22.7464C26.4089 22.7464 26.2559 22.5917 26.2559 22.4008V14.4952C26.2559 13.7795 25.6821 13.1992 24.9744 13.1992Z" fill="white" /> <defs> <linearGradient id="paint0_linear_45_20531" x1="41.8947" y1="24" x2="1.63158" y2="24" gradientUnits="userSpaceOnUse" > <stop stop-color="#FF7171" /> <stop offset="1" stop-color="#E63757" /> </linearGradient> </defs> </svg>
5,789
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/sessionRecovery
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/sessionRecovery/statusCards/lock-icon.svg
<svg width="48" height="48" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" clip-rule="evenodd" d="M11.995 18.7546V13.989C11.995 8.4702 16.4652 4 21.984 4C27.5028 4 31.9737 8.4702 31.9737 13.989V22.6368H28.7194V13.9897C28.7194 10.0158 25.9026 7.1983 21.9287 7.1983C17.9555 7.1983 15.138 10.0158 15.138 13.989V18.7546H11.995V18.7546Z" fill="#706D6B" /> <rect x="8" y="16.25" width="28" height="22.75" rx="4" fill="url(#paint0_linear_46_20541)" /> <path fill-rule="evenodd" clip-rule="evenodd" d="M23.2534 27.307C24.0705 26.8621 24.625 25.9958 24.625 25C24.625 23.5503 23.4497 22.375 22 22.375C20.5503 22.375 19.375 23.5503 19.375 25C19.375 25.9958 19.9295 26.8621 20.7466 27.307L19.6668 31.9579H24.3332L23.2534 27.307Z" fill="#3D3C3A" /> <rect x="28" y="26" width="20" height="20" rx="6" fill="url(#paint1_linear_46_20541)" /> <g filter="url(#filter0_i_46_20541)"> <rect x="30" y="28" width="16" height="16" rx="8" fill="url(#paint2_linear_46_20541)" /> </g> <path d="M38 36L40.5 38.9483" stroke="white" stroke-width="1.2" stroke-linecap="round" /> <path d="M38 31V36" stroke="white" stroke-width="1.2" stroke-linecap="round" /> <defs> <filter id="filter0_i_46_20541" x="30" y="28" width="16" height="16.3333" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB" > <feFlood flood-opacity="0" result="BackgroundImageFix" /> <feBlend mode="normal" in="SourceGraphic" in2="BackgroundImageFix" result="shape" /> <feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha" /> <feOffset dy="0.333333" /> <feGaussianBlur stdDeviation="0.166667" /> <feComposite in2="hardAlpha" operator="arithmetic" k2="-1" k3="1" /> <feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.16 0" /> <feBlend mode="normal" in2="shape" result="effect1_innerShadow_46_20541" /> </filter> <linearGradient id="paint0_linear_46_20541" x1="22.0007" y1="16.5924" x2="22.0007" y2="38.5988" gradientUnits="userSpaceOnUse" > <stop stop-color="#FFE26D" /> <stop offset="1" stop-color="#FFA16D" /> </linearGradient> <linearGradient id="paint1_linear_46_20541" x1="58.4167" y1="14.125" x2="33.2083" y2="51.625" gradientUnits="userSpaceOnUse" > <stop offset="0.217324" stop-color="white" /> <stop offset="0.621556" stop-color="#E6EAEC" /> <stop offset="0.936658" stop-color="#ABC4CC" /> </linearGradient> <linearGradient id="paint2_linear_46_20541" x1="38" y1="28" x2="38" y2="44" gradientUnits="userSpaceOnUse"> <stop stop-color="#8F8F8F" /> <stop offset="1" /> </linearGradient> </defs> </svg>
5,790
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/sessionRecovery
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/sessionRecovery/statusCards/lock-tick-icon.svg
<svg width="48" height="48" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg"> <path fill-rule="evenodd" clip-rule="evenodd" d="M31.9736 13V10.989C31.9736 5.4702 27.5034 1 21.9846 1C16.4658 1 11.9949 5.4702 11.9949 10.989V17.6368H15.2492V10.9897C15.2492 7.0158 18.066 4.1983 22.0399 4.1983C26.0131 4.1983 28.8306 7.0158 28.8306 10.989V13H31.9736Z" fill="#706D6B" /> <rect x="8" y="16.25" width="28" height="22.75" rx="4" fill="url(#paint0_linear_1191_27419)" /> <path fill-rule="evenodd" clip-rule="evenodd" d="M23.2534 27.307C24.0705 26.8621 24.625 25.9958 24.625 25C24.625 23.5503 23.4497 22.375 22 22.375C20.5503 22.375 19.375 23.5503 19.375 25C19.375 25.9958 19.9295 26.8621 20.7466 27.307L19.6668 31.9579H24.3332L23.2534 27.307Z" fill="#3D3C3A" /> <path d="M38 46C43.5229 46 48 41.5228 48 36C48 30.4772 43.5229 26 38 26C32.4772 26 28 30.4772 28 36C28 41.5228 32.4772 46 38 46Z" fill="url(#paint1_linear_1191_27419)" /> <path fill-rule="evenodd" clip-rule="evenodd" d="M42.7069 32.5195C43.0974 32.91 43.0974 33.5431 42.7069 33.9337L37.4342 39.2064C37.0437 39.5969 36.4105 39.5969 36.02 39.2064L33.5199 36.7064C33.1294 36.3159 33.1294 35.6827 33.5199 35.2922C33.9105 34.9016 34.5436 34.9016 34.9342 35.2922L36.7271 37.0851L41.2926 32.5195C41.6832 32.1289 42.3163 32.1289 42.7069 32.5195Z" fill="white" /> <defs> <linearGradient id="paint0_linear_1191_27419" x1="22.0007" y1="16.5924" x2="22.0007" y2="38.5988" gradientUnits="userSpaceOnUse" > <stop stop-color="#FFE26D" /> <stop offset="1" stop-color="#FFA16D" /> </linearGradient> <linearGradient id="paint1_linear_1191_27419" x1="48" y1="26.5" x2="28.5" y2="46" gradientUnits="userSpaceOnUse" > <stop stop-color="#2AF091" /> <stop offset="1" stop-color="#00C5A1" /> </linearGradient> </defs> </svg>
5,791
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/account
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/totp/DisableTOTPModal.tsx
import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { disableTotp } from '@proton/shared/lib/api/settings'; import { ModalProps, Prompt, useModalState } from '../../../components'; import { useEventManager, useNotifications } from '../../../hooks'; import AuthModal from '../../password/AuthModal'; const DisableTOTPModal = ({ onClose, ...rest }: ModalProps) => { const { call } = useEventManager(); const { createNotification } = useNotifications(); const [loading, withLoading] = useLoading(); const [authModalProps, setAuthModalOpen, renderAuthModal] = useModalState(); return ( <> {renderAuthModal && ( <AuthModal config={disableTotp()} {...authModalProps} onCancel={undefined} onSuccess={async () => { await withLoading(call()); onClose?.(); createNotification({ text: c('Info').t`Two-factor authentication disabled` }); }} /> )} <Prompt {...rest} title={c('Title').t`Disable two-factor authentication`} onClose={onClose} buttons={[ <Button loading={loading} color="danger" onClick={() => { setAuthModalOpen(true); }} > {c('Action').t`Disable`} </Button>, <Button disabled={loading} onClick={onClose}> {c('Action').t`Cancel`} </Button>, ]} > {c('Info').t`Are you sure you want to disable two-factor authentication?`} </Prompt> </> ); }; export default DisableTOTPModal;
5,792
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/account
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/totp/EnableTOTPModal.tsx
import { FormEvent, ReactNode, useState } from 'react'; import { c } from 'ttag'; import { Button, Href } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { getApiError } from '@proton/shared/lib/api/helpers/apiErrorHelper'; import { TOTP_WRONG_ERROR, setupTotp } from '@proton/shared/lib/api/settings'; import { unlockPasswordChanges } from '@proton/shared/lib/api/user'; import { APPS, BRAND_NAME } from '@proton/shared/lib/constants'; import downloadFile from '@proton/shared/lib/helpers/downloadFile'; import { requiredValidator } from '@proton/shared/lib/helpers/formValidators'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { getTOTPData } from '@proton/shared/lib/settings/twoFactor'; import noop from '@proton/utils/noop'; import { Form, InlineLinkButton, InputFieldTwo, Loader, ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, ModalProps, QRCode, TotpInput, useFormErrors, } from '../../../components'; import { useApi, useConfig, useEventManager, useNotifications, useUser } from '../../../hooks'; import AuthModal from '../../password/AuthModal'; interface ModalProperties { section: ReactNode; cancelButtonText?: string | null; onCancel?: () => void; submitButtonText?: string | null; onSubmit?: (event: FormEvent<HTMLFormElement>) => void; } interface SetupTOTPResponse { TwoFactorRecoveryCodes: string[]; } const STEPS = { INFO: 1, SCAN_CODE: 2, CONFIRM_CODE: 3, RECOVERY_CODES: 4, }; const EnableTOTPModal = ({ onClose, ...rest }: ModalProps) => { const { APP_NAME } = useConfig(); const [user] = useUser(); const api = useApi(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const [{ sharedSecret, uri = '', period, digits }] = useState(() => { return getTOTPData(user.Email || user.Name); }); const [step, setStep] = useState(STEPS.INFO); const [manualCode, setManualCode] = useState(false); const [recoveryCodes, setRecoveryCodes] = useState<string[]>([]); const [confirmationCode, setConfirmationCode] = useState(''); const [totpError, setTotpError] = useState(''); const [loading, withLoading] = useLoading(); const { validator, onFormSubmit } = useFormErrors(); const handleClose = loading ? noop : onClose; const [authed, setAuthed] = useState(false); if (!authed) { return ( <AuthModal config={unlockPasswordChanges()} {...rest} onCancel={onClose} onSuccess={async () => { setAuthed(true); }} /> ); } const { section, cancelButtonText, onCancel = handleClose, submitButtonText, onSubmit, } = ((): ModalProperties => { if (!sharedSecret) { return { section: <Loader />, }; } if (step === STEPS.INFO) { const twoFactorAuthLink = APP_NAME === APPS.PROTONVPN_SETTINGS ? 'https://protonvpn.com/support/two-factor-authentication' : getKnowledgeBaseUrl('/two-factor-authentication-2fa'); // translator: complete sentence is: If you have never used two-factor authentication before, we strongly recommend you <link>read our two-factor authentication guide first</link>. const guideButton = ( <Href key="0" href={twoFactorAuthLink}>{c('Info') .t`read our two-factor authentication guide first`}</Href> ); const BRAND_NAME_TWO = BRAND_NAME; return { section: ( <> <div className="mb-4"> {c('Info') .t`This wizard will enable Two-Factor Authentication (2FA) on your ${BRAND_NAME} account. Two-factor authentication will make your ${BRAND_NAME_TWO} account more secure so we recommend enabling it.`} </div> <div className="mb-4"> { // translator: complete sentence is: If you have never used two-factor authentication before, we strongly recommend you <link>read our two-factor authentication guide first</link>. c('Info') .jt`If you have never used two-factor authentication before, we strongly recommend you ${guideButton}.` } </div> </> ), onSubmit() { setStep(STEPS.SCAN_CODE); }, }; } const handleSubmitScan = () => { setStep(STEPS.CONFIRM_CODE); }; if (step === STEPS.SCAN_CODE && !manualCode) { const switchButton = ( <InlineLinkButton data-testid="totp:manual-button" key="0" onClick={() => setManualCode(true)}> {c('Info').t`Enter key manually instead`} </InlineLinkButton> ); return { section: ( <> <div className="mb-4"> {c('Info') .jt`Scan this code with your two-factor authentication device to set up your account. ${switchButton}.`} </div> <div className="text-center"> <QRCode value={uri} size={200} /> </div> </> ), onSubmit: handleSubmitScan, }; } if (step === STEPS.SCAN_CODE && manualCode) { const switchButton = ( <InlineLinkButton key="0" onClick={() => setManualCode(false)}> {c('Info').t`Scan QR code instead`} </InlineLinkButton> ); return { section: ( <> <div className="mb-4"> {c('Info') .jt`Manually enter this information into your two-factor authentication device to set up your account. ${switchButton}.`} </div> <div> <div className="flex flex-justify-space-between mb-2"> <div className="w-1/5">{c('Label').t`Key`}</div> <div className="w-4/5 flex-align-self-center text-bold"> <code data-testid="totp:secret-key">{sharedSecret}</code> </div> </div> <div className="flex flex-justify-space-between mb-2"> <div className="w-1/5">{c('Label').t`Interval`}</div> <div className="w-4/5 flex-align-self-center text-bold"> <code>{period}</code> </div> </div> <div className="flex flex-justify-space-between mb-2"> <div className="w-1/5">{c('Label').t`Digits`}</div> <div className="w-4/5 flex-align-self-center text-bold"> <code>{digits}</code> </div> </div> </div> </> ), onSubmit: handleSubmitScan, }; } if (step === STEPS.CONFIRM_CODE) { const handleSubmit = async () => { try { const result = await api<SetupTOTPResponse>(setupTotp(sharedSecret, confirmationCode)); await call(); createNotification({ text: c('Info').t`Two-factor authentication enabled` }); setRecoveryCodes(result.TwoFactorRecoveryCodes); setStep(STEPS.RECOVERY_CODES); } catch (error: any) { const { code, message } = getApiError(error); if (code === TOTP_WRONG_ERROR) { setTotpError(message); } } }; return { section: ( <> <div className="mb-4">{c('Info').t`Enter the code from your authenticator app`}</div> <InputFieldTwo as={TotpInput} autoFocus length={6} autoComplete="one-time-code" id="totp" value={confirmationCode} disableChange={loading} onValue={(value: string) => { setConfirmationCode(value); setTotpError(''); }} error={validator([requiredValidator(confirmationCode), totpError])} /> </> ), cancelButtonText: c('Action').t`Back`, onCancel: () => { setStep(STEPS.SCAN_CODE); }, submitButtonText: c('Action').t`Submit`, onSubmit(event: FormEvent<HTMLFormElement>) { if (!onFormSubmit(event.currentTarget)) { return; } void withLoading(handleSubmit()); }, }; } if (step === STEPS.RECOVERY_CODES) { return { section: ( <> <div className="mb-4"> <span className="text-bold">{c('Info') .t`Important: Please make sure you save the recovery codes. Otherwise you can permanently lose access to your account if you lose your two-factor authentication device.`}</span> <br /> <br /> {c('Info') .t`If you lose your two-factor-enabled device, these codes can be used instead of the 6-digit two-factor authentication code to sign in to your account. Each code can only be used once.`} </div> <div className="flex text-center"> {recoveryCodes.map((code) => { return ( <code data-testid="totp:recovery-code" key={code} className="w-custom p-2" style={{ '--w-custom': '49%' }} > {code} </code> ); })} </div> <div className="text-center"> <Button color="norm" onClick={() => { const blob = new Blob([recoveryCodes.join('\r\n')], { type: 'text/plain;charset=utf-8', }); const filename = 'proton_recovery_codes.txt'; downloadFile(blob, filename); }} > {c('Action').t`Download`} </Button> </div> </> ), submitButtonText: null, onSubmit() { onClose?.(); }, cancelButtonText: c('Action').t`Close`, }; } throw new Error('Unknown step'); })(); return ( <Modal as={Form} onSubmit={onSubmit} onClose={handleClose} size="medium" {...rest}> <ModalHeader title={c('Title').t`Set up two-factor authentication`} /> <ModalContent>{section}</ModalContent> <ModalFooter> {cancelButtonText !== null ? ( <Button onClick={onCancel} disabled={loading}> {cancelButtonText || c('Action').t`Cancel`} </Button> ) : ( // Maintain submit button positioning <div /> )} {submitButtonText !== null && ( <Button loading={loading} type="submit" color="norm"> {submitButtonText || c('Action').t`Next`} </Button> )} </ModalFooter> </Modal> ); }; export default EnableTOTPModal;
5,793
0
petrpan-code/ProtonMail/WebClients/packages/components/containers/account
petrpan-code/ProtonMail/WebClients/packages/components/containers/account/totp/TotpInputs.tsx
import { c } from 'ttag'; import { Info, InputFieldTwo, TotpInput } from '../../../components'; interface Props { type: 'totp' | 'recovery-code'; code: string; error: string; loading?: boolean; bigger?: boolean; setCode: (value: string) => void; } const TotpInputs = ({ code, type, setCode, error, loading, bigger }: Props) => { return ( <> {type === 'totp' && ( <> <div className="mb-6">{c('Info').t`Enter the code from your authenticator app`}</div> <InputFieldTwo id="totp" as={TotpInput} key="totp" length={6} error={error} disableChange={loading} autoFocus autoComplete="one-time-code" value={code} onValue={setCode} /> </> )} {type === 'recovery-code' && ( <> <div className="mb-6 flex flex-align-items-center"> {c('Info').t`Each code can only be used once`}{' '} <Info className="ml-2" title={c('Info') .t`When you set up two-factor authentication, we provide recovery codes which you can use to sign in if you lose access to your authenticator app.`} /> </div> <InputFieldTwo type="text" id="recovery-code" key="recovery-code" autoComplete="off" autoCapitalize="off" autoCorrect="off" spellCheck="false" error={error} disableChange={loading} autoFocus value={code} onValue={setCode} bigger={bigger} /> </> )} </> ); }; export default TotpInputs;
5,794
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/addresses/AddressActions.tsx
import { c } from 'ttag'; import { useLoading } from '@proton/hooks'; import { deleteAddress, disableAddress, enableAddress } from '@proton/shared/lib/api/addresses'; import { ADDRESS_STATUS } from '@proton/shared/lib/constants'; import { Address, CachedOrganizationKey, Member, UserModel } from '@proton/shared/lib/interfaces'; import isTruthy from '@proton/utils/isTruthy'; import { DropdownActions, useModalState } from '../../components'; import EditExternalAddressModal from '../../containers/account/EditExternalAddressModal'; import EditInternalAddressModal from '../../containers/addresses/EditInternalAddressModal'; import { useAddressFlags, useApi, useEventManager, useNotifications } from '../../hooks'; import DeleteAddressModal from './DeleteAddressModal'; import DisableAddressModal from './DisableAddressModal'; import { AddressPermissions } from './helper'; import CreateMissingKeysAddressModal from './missingKeys/CreateMissingKeysAddressModal'; interface Props { address: Address; member?: Member; // undefined if self user: UserModel; organizationKey?: CachedOrganizationKey; onSetDefault?: () => Promise<unknown>; savingIndex?: number; addressIndex?: number; permissions: AddressPermissions; } const useAddressFlagsActionsList = (address: Address, user: UserModel, member: Member | undefined) => { const addressFlags = useAddressFlags(address); const isPaidMail = user.hasPaidMail; // Only allow on the user's own settings address list, not in org admin management panel. // This still allows an admin logged in as sub-user to manage the preferences. const isSelf = member === undefined || !!member.Self; if (!addressFlags || !isPaidMail || !isSelf) { return []; } const { allowDisablingEncryption, encryptionDisabled, expectSignatureDisabled, handleSetAddressFlags } = addressFlags; const actions = []; if (!encryptionDisabled && allowDisablingEncryption) { actions.push({ // translator: this is in a small space, so the string should be short, max 25 characters text: c('Address action').t`Disable E2EE mail`, onClick: () => handleSetAddressFlags(true, expectSignatureDisabled), }); } if (encryptionDisabled) { actions.push({ // translator: this is in a small space, so the string should be short, max 25 characters text: c('Address action').t`Enable E2EE mail`, onClick: () => handleSetAddressFlags(false, expectSignatureDisabled), }); } if (expectSignatureDisabled) { actions.push({ // translator: this is in a small space, so the string should be short, max 25 characters text: c('Address action').t`Disallow unsigned mail`, onClick: () => handleSetAddressFlags(encryptionDisabled, false), }); } return actions; }; const AddressActions = ({ address, member, user, organizationKey, onSetDefault, savingIndex, addressIndex, permissions, }: Props) => { const api = useApi(); const { call } = useEventManager(); const [loading, withLoading] = useLoading(); const { createNotification } = useNotifications(); const addressFlagsActionsList = useAddressFlagsActionsList(address, user, member); const [missingKeysProps, setMissingKeysAddressModalOpen, renderMissingKeysModal] = useModalState(); const [deleteAddressProps, setDeleteAddressModalOpen, renderDeleteAddress] = useModalState(); const [disableAddressProps, setDisableAddressModalOpen, renderDisableAddress] = useModalState(); const [editInternalAddressProps, setEditInternalAddressOpen, renderEditInternalAddressModal] = useModalState(); const [editExternalAddressProps, setEditExternalAddressOpen, renderEditExternalAddressModal] = useModalState(); const handleDelete = async () => { if (address.Status === ADDRESS_STATUS.STATUS_ENABLED) { await api(disableAddress(address.ID)); } await api(deleteAddress(address.ID)); await call(); createNotification({ text: c('Success notification').t`Address deleted` }); }; const handleEnable = async () => { await api(enableAddress(address.ID)); await call(); createNotification({ text: c('Success notification').t`Address enabled` }); }; const handleDisable = async () => { await api(disableAddress(address.ID)); await call(); createNotification({ text: c('Success notification').t`Address disabled` }); }; const list = savingIndex !== undefined ? [savingIndex === addressIndex ? { text: c('Address action').t`Saving` } : null].filter(isTruthy) : [ permissions.canGenerate && { text: c('Address action').t`Generate missing keys`, onClick: () => setMissingKeysAddressModalOpen(true), }, permissions.canEditInternalAddress && { text: c('Address action').t`Edit`, onClick: () => setEditInternalAddressOpen(true), }, permissions.canEditExternalAddress && { text: c('Address action').t`Edit address`, onClick: () => setEditExternalAddressOpen(true), }, permissions.canMakeDefault && onSetDefault && { text: c('Address action').t`Set as default`, onClick: () => onSetDefault(), }, permissions.canEnable && { text: c('Address action').t`Enable`, onClick: () => withLoading(handleEnable()), }, permissions.canDisable && { text: c('Address action').t`Disable`, onClick: () => setDisableAddressModalOpen(true), }, permissions.canDelete && ({ text: c('Address action').t`Delete`, actionType: 'delete', onClick: () => setDeleteAddressModalOpen(true), } as const), ...addressFlagsActionsList, ].filter(isTruthy); return ( <> {renderMissingKeysModal && ( <CreateMissingKeysAddressModal {...missingKeysProps} member={member} addressesToGenerate={[address]} organizationKey={organizationKey} /> )} {renderEditInternalAddressModal && ( <EditInternalAddressModal address={address} {...editInternalAddressProps} /> )} {renderEditExternalAddressModal && ( <EditExternalAddressModal address={address} {...editExternalAddressProps} /> )} {renderDeleteAddress && ( <DeleteAddressModal email={address.Email} onDeleteAddress={handleDelete} {...deleteAddressProps} /> )} {renderDisableAddress && ( <DisableAddressModal email={address.Email} onDisable={handleDisable} {...disableAddressProps} /> )} {list.length ? ( <DropdownActions size="small" list={list} loading={loading || savingIndex !== undefined} /> ) : ( <div // This is a placeholder to avoid height loss when dropdownActions are not rendered style={{ height: '24px' }} /> )} </> ); }; export default AddressActions;
5,795
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/addresses/AddressModal.tsx
import { FormEvent, useState } from 'react'; import { c } from 'ttag'; import { Button, CircleLoader } from '@proton/atoms'; import { useLoading } from '@proton/hooks'; import { createAddress } from '@proton/shared/lib/api/addresses'; import { getAllMemberAddresses } from '@proton/shared/lib/api/members'; import { ADDRESS_TYPE, DEFAULT_ENCRYPTION_CONFIG, ENCRYPTION_CONFIGS, MEMBER_PRIVATE, } from '@proton/shared/lib/constants'; import { confirmPasswordValidator, passwordLengthValidator, requiredValidator, } from '@proton/shared/lib/helpers/formValidators'; import { Address, CachedOrganizationKey, FAMILY_PLAN_INVITE_STATE, Member } from '@proton/shared/lib/interfaces'; import { getShouldSetupMemberKeys, missingKeysMemberProcess, missingKeysSelfProcess, setupMemberKeys, } from '@proton/shared/lib/keys'; import noop from '@proton/utils/noop'; import { DropdownSizeUnit, InputFieldTwo, ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, ModalProps, Option, PasswordInputTwo, SelectTwo, useFormErrors, } from '../../components'; import { useAddresses, useApi, useAuthentication, useEventManager, useGetUserKeys, useNotifications, usePremiumDomains, useUser, } from '../../hooks'; import { useKTVerifier } from '../keyTransparency'; import SelectEncryption from '../keys/addKey/SelectEncryption'; import useAddressDomains from './useAddressDomains'; interface Props extends ModalProps<'form'> { member?: Member; members: Member[]; organizationKey?: CachedOrganizationKey; } const AddressModal = ({ member, members, organizationKey, ...rest }: Props) => { const { call } = useEventManager(); const [user] = useUser(); const [addresses] = useAddresses(); const [premiumDomains] = usePremiumDomains(); const [premiumDomain = ''] = premiumDomains || []; const [password, setPassword] = useState(''); const [confirmPassword, setConfirmPassword] = useState(''); const api = useApi(); const initialMember = member || members[0]; const [encryptionType, setEncryptionType] = useState(DEFAULT_ENCRYPTION_CONFIG); const authentication = useAuthentication(); const [model, setModel] = useState(() => { return { id: initialMember.ID, name: '', address: '', domain: '', }; }); const { createNotification } = useNotifications(); const { validator, onFormSubmit } = useFormErrors(); const [submitting, withLoading] = useLoading(); const hasPremium = addresses.some(({ Type }) => Type === ADDRESS_TYPE.TYPE_PREMIUM); const selectedMember = members.find((otherMember) => otherMember.ID === model.id); const [addressDomains, loadingDomains] = useAddressDomains(selectedMember || initialMember); const domainOptions = addressDomains.map((DomainName) => ({ text: DomainName, value: DomainName })); const selectedDomain = model.domain || domainOptions[0]?.text; const getUserKeys = useGetUserKeys(); const { keyTransparencyVerify, keyTransparencyCommit } = useKTVerifier(api, async () => user); const shouldGenerateKeys = !selectedMember || selectedMember.Self || selectedMember.Private === MEMBER_PRIVATE.READABLE; const shouldSetupMemberKeys = shouldGenerateKeys && getShouldSetupMemberKeys(selectedMember); const handleSubmit = async () => { if (!selectedMember) { throw new Error('Missing member'); } const { name: DisplayName, address: Local } = model; const Domain = selectedDomain; if (!hasPremium && `${user.Name}@${premiumDomain}`.toLowerCase() === `${Local}@${Domain}`.toLowerCase()) { return createNotification({ text: c('Error') .t`${Local} is your username. To create ${Local}@${Domain}, please go to Settings > Messages and composing > Short domain (pm.me)`, type: 'error', }); } const shouldGenerateSelfKeys = selectedMember.Self && selectedMember.Private === MEMBER_PRIVATE.UNREADABLE; const shouldGenerateMemberKeys = !shouldGenerateSelfKeys; if (shouldGenerateKeys && shouldGenerateMemberKeys && !organizationKey?.privateKey) { createNotification({ text: c('Error').t`Organization key is not decrypted`, type: 'error' }); return; } const { Address } = await api<{ Address: Address }>( createAddress({ MemberID: selectedMember.ID, Local, Domain, DisplayName, }) ); const encryptionConfig = ENCRYPTION_CONFIGS[encryptionType]; if (shouldGenerateKeys) { const userKeys = await getUserKeys(); if (shouldGenerateSelfKeys) { await missingKeysSelfProcess({ api, userKeys, addresses, addressesToGenerate: [Address], password: authentication.getPassword(), encryptionConfig, onUpdate: noop, keyTransparencyVerify, }); } else { if (!organizationKey?.privateKey) { throw new Error('Missing org key'); } const memberAddresses = await getAllMemberAddresses(api, selectedMember.ID); if (shouldSetupMemberKeys && password) { await setupMemberKeys({ ownerAddresses: addresses, encryptionConfig, organizationKey: organizationKey.privateKey, member: selectedMember, memberAddresses, password, api, keyTransparencyVerify, }); } else { await missingKeysMemberProcess({ api, encryptionConfig, ownerAddresses: addresses, memberAddressesToGenerate: [Address], member: selectedMember, memberAddresses, onUpdate: noop, organizationKey: organizationKey.privateKey, keyTransparencyVerify, }); } } await keyTransparencyCommit(userKeys); } await call(); rest.onClose?.(); createNotification({ text: c('Success').t`Address added` }); }; const handleClose = submitting ? undefined : rest.onClose; return ( <Modal as="form" {...rest} onSubmit={(event: FormEvent) => { event.preventDefault(); event.stopPropagation(); if (!onFormSubmit()) { return; } withLoading(handleSubmit()); }} onClose={handleClose} > <ModalHeader title={c('Title').t`Add address`} /> <ModalContent> <div className="mb-6"> <div className="text-semibold mb-1" id="label-user-select">{c('Label').t`User`}</div> {member || members?.length === 1 ? ( <div className="text-ellipsis">{member?.Name || members?.[0].Name}</div> ) : ( <SelectTwo aria-describedby="label-user-select" value={model.id} onChange={({ value }) => setModel({ ...model, id: value })} > {members.map((member) => ( <Option value={member.ID} title={member.Name} disabled={ member.State === FAMILY_PLAN_INVITE_STATE.STATUS_DISABLED || member.State === FAMILY_PLAN_INVITE_STATE.STATUS_INVITED } > {member.Name} </Option> ))} </SelectTwo> )} </div> <InputFieldTwo id="address" autoFocus value={model.address} error={validator([requiredValidator(model.address)])} aria-describedby="user-domain-selected" onValue={(address: string) => setModel({ ...model, address })} label={c('Label').t`Address`} placeholder={c('Placeholder').t`Address`} data-testid="settings:identity-section:add-address:address" suffix={ loadingDomains ? ( <CircleLoader /> ) : domainOptions.length === 1 ? ( <span className="text-ellipsis" id="user-domain-selected" title={`@${domainOptions[0].value}`} > @{domainOptions[0].value} </span> ) : ( <SelectTwo unstyled size={{ width: DropdownSizeUnit.Static }} originalPlacement="bottom-end" value={selectedDomain} onChange={({ value }) => setModel({ ...model, domain: value })} data-testid="settings:identity-section:add-address:domain-select" id="user-domain-selected" > {domainOptions.map((option) => ( <Option key={option.value} value={option.value} title={`@${option.text}`}> @{option.text} </Option> ))} </SelectTwo> ) } /> <InputFieldTwo id="name" value={model.name} onValue={(name: string) => setModel({ ...model, name })} label={c('Label').t`Display name`} placeholder={c('Placeholder').t`Choose display name`} data-testid="settings:identity-section:add-address:display-name" /> {shouldSetupMemberKeys && ( <> <div className="mb-4 color-weak"> {c('Info') .t`Before creating this address you need to provide a password and create encryption keys for it.`} </div> <InputFieldTwo required id="password" as={PasswordInputTwo} value={password} error={validator([passwordLengthValidator(password), requiredValidator(password)])} onValue={setPassword} label={c('Label').t`Password`} placeholder={c('Placeholder').t`Password`} autoComplete="new-password" /> <InputFieldTwo id="confirmPassword" as={PasswordInputTwo} label={c('Label').t`Confirm password`} placeholder={c('Placeholder').t`Confirm`} value={confirmPassword} onValue={setConfirmPassword} error={validator([ passwordLengthValidator(confirmPassword), confirmPasswordValidator(confirmPassword, password), ])} autoComplete="new-password" /> </> )} {shouldGenerateKeys && ( <div className="mb-6"> <div className="text-semibold mb-1">{c('Label').t`Key strength`}</div> <SelectEncryption encryptionType={encryptionType} setEncryptionType={setEncryptionType} /> </div> )} </ModalContent> <ModalFooter> <Button onClick={handleClose} disabled={submitting}>{c('Action').t`Cancel`}</Button> <Button color="norm" type="submit" loading={submitting}>{c('Action').t`Save address`}</Button> </ModalFooter> </Modal> ); }; export default AddressModal;
5,796
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/addresses/AddressStatus.tsx
import { c } from 'ttag'; import isTruthy from '@proton/utils/isTruthy'; import { Badge } from '../../components'; import { AddressStatuses } from './helper'; const AddressStatus = ({ isDefault, isActive, isDisabled, isOrphan, isMissingKeys, isExternal, isNotEncrypted, isSignatureNotExpected, }: AddressStatuses) => { const list = [ isDefault && ({ text: c('Address status').t`Default`, type: 'primary', } as const), isExternal && ({ text: c('Address status').t`External`, type: 'info', } as const), isActive && ({ text: c('Address status').t`Active`, type: 'success', } as const), isDisabled && ({ text: c('Address status').t`Disabled`, type: 'light', } as const), isOrphan && ({ text: c('Address status').t`Orphan`, type: 'origin', } as const), isMissingKeys && ({ text: c('Address status').t`Missing keys`, type: 'warning', } as const), isNotEncrypted && ({ // translator: E2EE stands for end-to-end encryption. If possible, keep the abbreviation as the UI will be best with a short translated string. text: c('Address status').t`No E2EE mail`, type: 'error', } as const), isSignatureNotExpected && ({ text: c('Address status').t`Allow unsigned mail`, type: 'error', } as const), ] .filter(isTruthy) .map(({ text, type }) => { return ( <Badge key={text} type={type} className="mr-1 mb-1"> {text} </Badge> ); }); return <>{list}</>; }; export default AddressStatus;
5,797
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/addresses/Addresses.tsx
import { Organization } from '@proton/shared/lib/interfaces'; import { useUser } from '../../hooks'; import AddressesWithMembers from './AddressesWithMembers'; import AddressesWithUser from './AddressesWithUser'; interface AddressesProps { isOnlySelf?: boolean; organization: Organization; memberID?: string; } const Addresses = ({ isOnlySelf, organization, memberID }: AddressesProps) => { const [user] = useUser(); return user.isAdmin && user.hasPaidMail ? ( <AddressesWithMembers isOnlySelf={isOnlySelf} user={user} memberID={memberID} organization={organization} /> ) : ( <AddressesWithUser user={user} /> ); }; export default Addresses;
5,798
0
petrpan-code/ProtonMail/WebClients/packages/components/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/addresses/AddressesSection.tsx
import { Loader } from '../../components'; import { useOrganization } from '../../hooks'; import { SettingsSectionWide } from '../account'; import Addresses from './Addresses'; interface Props { isOnlySelf?: boolean; } const AddressesSection = ({ isOnlySelf }: Props) => { const [organization, loadingOrganization] = useOrganization(); return ( <SettingsSectionWide> {loadingOrganization ? <Loader /> : <Addresses isOnlySelf={isOnlySelf} organization={organization} />} </SettingsSectionWide> ); }; export default AddressesSection;
5,799