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/containers
petrpan-code/ProtonMail/WebClients/packages/components/containers/zendesk/LiveChatZendesk.tsx
import React, { MutableRefObject, useEffect, useImperativeHandle, useRef, useState } from 'react'; import { addHours } from 'date-fns'; import { c } from 'ttag'; import * as sessionStorageWrapper from '@proton/shared/lib/helpers/sessionStorage'; import * as localStorageWrapper from '@proton/shared/lib/helpers/storage'; import { getApiSubdomainUrl } from '@proton/shared/lib/helpers/url'; import { UserModel } from '@proton/shared/lib/interfaces'; import { useNotifications } from '../../hooks'; // The sizes for these are hardcoded since the widget calculates it based on the viewport, and since it's in // an iframe it needs to have something reasonable. // The main chat widget. const OPENED_SIZE = { height: `${572 / 16}rem`, width: `${374 / 16}rem`, }; // The small button to toggle the chat. const CLOSED_SIZE = { height: `${70 / 16}rem`, width: `${140 / 16}rem`, }; const SINGLE_CHAT_KEY = 'zk_state'; const SINGLE_CHAT_TIMEOUT = 10000; const getIframeUrl = (zendeskKey: string) => { const url = getApiSubdomainUrl('/core/v4/resources/zendesk'); url.searchParams.set('Key', zendeskKey); return url; }; export const getIsSelfChat = () => { return sessionStorageWrapper.getItem(SINGLE_CHAT_KEY); }; const removeSelfActiveMarker = () => { return sessionStorageWrapper.removeItem(SINGLE_CHAT_KEY); }; const getIsActiveInAnotherWindow = () => { return !getIsSelfChat() && +(localStorageWrapper.getItem(SINGLE_CHAT_KEY) || 0) > Date.now(); }; const setActiveMarker = () => { localStorageWrapper.setItem(SINGLE_CHAT_KEY, `${+Date.now() + SINGLE_CHAT_TIMEOUT}`); sessionStorageWrapper.setItem(SINGLE_CHAT_KEY, '1'); }; const clearPaidMarkers = () => { if (!localStorageWrapper.hasStorage()) { return; } for (let i = 0; i < localStorage.length; i++) { const key = localStorage.key(i); if (key?.startsWith('LiveChat')) { if (+(localStorage.getItem(key) || 0) < Date.now()) { localStorage.removeItem(key); } } } }; const setPaidMarker = (userID: string) => { return localStorageWrapper.setItem(`LiveChat-${userID}`, addHours(new Date(), 24).getTime().toString()); }; const getPaidMarker = (userID: string) => { return +(localStorageWrapper.getItem(`LiveChat-${userID}`) || 0); }; export const useCanEnableChat = (user: UserModel) => { const hasCachedChat = getPaidMarker(user.ID) > Date.now(); const canEnableChat = user.hasPaidVpn || hasCachedChat; useEffect(() => { clearPaidMarkers(); if (!user.hasPaidVpn) { return; } const setMarker = () => { // Clear old items clearPaidMarkers(); // Enable the user to access chat 24 hours after in case she unsubscribes setPaidMarker(user.ID); }; setMarker(); const handle = window.setInterval(setMarker, 60000); return () => window.clearInterval(handle); }, [user.hasPaidVpn]); return canEnableChat; }; export interface ZendeskRef { run: (data: object) => void; toggle: () => void; } interface Props { zendeskKey: string; zendeskRef?: MutableRefObject<ZendeskRef | undefined>; name?: string; email?: string; onLoaded: () => void; onUnavailable: () => void; locale: string; tags: string[]; } const LiveChatZendesk = ({ zendeskKey, zendeskRef, name, email, onLoaded, onUnavailable, locale, tags }: Props) => { const [style, setStyle] = useState({ position: 'absolute', bottom: 0, right: 0, maxHeight: '100%', maxWidth: '100%', zIndex: '999999', ...CLOSED_SIZE, }); const [state, setState] = useState({ loaded: false, connected: false }); const stateRef = useRef({ loaded: false, connected: false }); const iframeRef = useRef<HTMLIFrameElement>(null); const pendingLoadingRef = useRef<{ toggle?: boolean; locale?: string }>({}); const iframeUrl = getIframeUrl(zendeskKey); const src = iframeUrl.toString(); const targetOrigin = iframeUrl.origin; const handleRun = (args: any) => { const contentWindow = iframeRef.current?.contentWindow; if (!contentWindow || !stateRef.current.loaded) { return; } contentWindow.postMessage({ args }, targetOrigin); }; const handleToggle = () => { // Using the ref instead of state to not have to wait for re-render if (!stateRef.current.connected) { onUnavailable(); return; } pendingLoadingRef.current.toggle = true; handleRun(['webWidget', 'toggle']); }; useImperativeHandle(zendeskRef, () => ({ run: handleRun, toggle: handleToggle, })); useEffect(() => { if (!state.loaded) { return; } handleRun([ 'webWidget', 'prefill', { name: { value: name, readOnly: false }, email: { value: email, readOnly: Boolean(email) }, }, ]); }, [state.loaded, name, email]); useEffect(() => { if (!state.loaded) { return; } handleRun(['webWidget', 'setLocale', locale]); }, [state.loaded, locale]); useEffect(() => { if (!state.loaded || !tags.length) { return; } handleRun(['webWidget', 'chat:addTags', tags]); return () => { handleRun(['webWidget', 'chat:removeTags', tags]); }; }, [state.loaded, tags]); useEffect(() => { if (!state.loaded || !pendingLoadingRef.current) { return; } const oldPending = pendingLoadingRef.current; pendingLoadingRef.current = {}; if (oldPending.toggle) { handleToggle(); } }, [state.loaded]); useEffect(() => { let globalId = 1; const handlers: { [key: string]: [(value: any) => void, (reason?: any) => void, number] } = {}; const sendMessage = (contentWindow: Window, args: any) => { contentWindow.postMessage({ args }, targetOrigin); }; const sendMessageWithReply = <T,>(contentWindow: Window, args: any): Promise<T> => { const id = globalId++; contentWindow.postMessage({ id, args }, targetOrigin); return new Promise((resolve, reject) => { const intervalId = window.setTimeout(() => { delete handlers[id]; }, 30000); handlers[id] = [resolve, reject, intervalId]; }); }; const handleMessage = (event: MessageEvent) => { const contentWindow = iframeRef.current?.contentWindow; const { origin, data, source } = event; if (!contentWindow || origin !== targetOrigin || !data || source !== contentWindow) { return; } const departmentName = 'Support'; if (data.type === 'on') { if (data.payload?.event === 'open') { setStyle((oldStyle) => ({ ...oldStyle, ...OPENED_SIZE })); } if (data.payload?.event === 'close') { setStyle((oldStyle) => ({ ...oldStyle, ...CLOSED_SIZE })); } if (data.payload?.event === 'chat:connected') { sendMessage(contentWindow, [ 'webWidget', 'updateSettings', { webWidget: { chat: { departments: { enabled: [departmentName], select: departmentName, }, }, }, }, ]); sendMessageWithReply<any>(contentWindow, ['webWidget:get', 'chat:department', departmentName]) .then((result) => { const connected = result?.status === 'online'; stateRef.current = { loaded: true, connected }; setState({ loaded: true, connected }); onLoaded(); }) .catch(() => { stateRef.current = { loaded: true, connected: false }; setState({ loaded: true, connected: false }); onLoaded(); }); } if (data.payload?.event === 'chat:departmentStatus') { const { chatDepartment } = data.payload; if (!chatDepartment) { return; } const connected = chatDepartment?.status === 'online'; stateRef.current = { loaded: true, connected }; setState({ loaded: true, connected }); } } if (data.type === 'response') { if (data.payload.id !== undefined) { const handler = handlers[data.payload.id]; if (handler) { delete handlers[data.payload.id]; handler[0](data.payload.result); } } } if (data.type === 'loaded') { sendMessage(contentWindow, [ 'webWidget', 'updateSettings', { webWidget: { color: { launcher: '#6d4aff', button: '#6d4aff', header: '#261b57', }, }, }, ]); } }; window.addEventListener('message', handleMessage, false); return () => { window.removeEventListener('message', handleMessage, false); for (const handlerKey of Object.keys(handlers)) { const handler = handlers[handlerKey]; handler[1](new Error('Unmount')); window.clearTimeout(handler[2]); delete handlers[handlerKey]; } }; }, []); return ( <div className={!state.connected ? 'hidden' : ''}> <iframe title="Zendesk" src={src} style={style} ref={iframeRef} sandbox="allow-scripts allow-same-origin allow-popups allow-forms" /> </div> ); }; const LiveChatZendeskSingleton = ({ zendeskRef, ...rest }: Props) => { const { createNotification } = useNotifications(); const [isActive, setIsActive] = useState(() => !getIsActiveInAnotherWindow()); const actualZendeskRef = useRef<ZendeskRef>(); useEffect(() => { const interval = window.setInterval(() => { if (getIsActiveInAnotherWindow()) { return; } setIsActive(true); setActiveMarker(); }, SINGLE_CHAT_TIMEOUT / 2); return () => { clearInterval(interval); removeSelfActiveMarker(); }; }, []); useImperativeHandle(zendeskRef, () => ({ run: (...args) => actualZendeskRef.current?.run(...args), toggle: (...args) => { if (getIsActiveInAnotherWindow()) { createNotification({ text: c('Info') .t`You can only have one chat instance open at a time. Please close previous conversations before starting a new one.`, type: 'error', }); return; } actualZendeskRef.current?.toggle(...args); }, })); useEffect(() => { if (!isActive) { rest.onLoaded(); } }, []); if (!isActive) { return null; } return <LiveChatZendesk zendeskRef={actualZendeskRef} {...rest} />; }; export default LiveChatZendeskSingleton;
7,000
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/helpers/appVersion.ts
export const getAppVersion = (versionString: string) => { return versionString.replace(/-beta.(\d+)/, ' - Beta $1'); };
7,001
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/helpers/component.ts
import isTruthy from '@proton/utils/isTruthy'; let current = 0; export const generateUID = (prefix?: string) => `${prefix || 'id'}-${current++}`; export const fakeEvent = <T>(value: T) => ({ target: { value } }); export const concatStringProp = (strings: (string | boolean | null | undefined)[] = []) => { return strings.filter(isTruthy).join(' ').trim(); };
7,002
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/helpers/countries.ts
const TOP_COUNTRIES = [ { label: 'United States', value: 'US' }, { label: 'United Kingdom', value: 'GB' }, { label: 'Switzerland', value: 'CH' }, { label: 'France', value: 'FR' }, { label: 'Germany', value: 'DE' }, { label: 'Canada', value: 'CA' }, ]; export const DEFAULT_SEPARATOR = { label: '------------------', value: '', disabled: true, key: 'separator' }; const COUNTRIES = [ { value: 'AF', label: 'Afghanistan' }, { value: 'AL', label: 'Albania' }, { value: 'DZ', label: 'Algeria' }, { value: 'AD', label: 'Andorra' }, { value: 'AO', label: 'Angola' }, { value: 'AI', label: 'Anguilla' }, { value: 'AG', label: 'Antigua and Barbuda' }, { value: 'AR', label: 'Argentina' }, { value: 'AM', label: 'Armenia' }, { value: 'AW', label: 'Aruba' }, { value: 'AU', label: 'Australia' }, { value: 'AT', label: 'Austria' }, { value: 'AZ', label: 'Azerbaijan' }, { value: 'BS', label: 'Bahamas' }, { value: 'BH', label: 'Bahrain' }, { value: 'BD', label: 'Bangladesh' }, { value: 'BB', label: 'Barbados' }, { value: 'BY', label: 'Belarus' }, { value: 'BE', label: 'Belgium' }, { value: 'BZ', label: 'Belize' }, { value: 'BJ', label: 'Benin' }, { value: 'BM', label: 'Bermuda' }, { value: 'BT', label: 'Bhutan' }, { value: 'BO', label: 'Bolivia' }, { value: 'BA', label: 'Bosnia Herzegovina' }, { value: 'BW', label: 'Botswana' }, { value: 'BV', label: 'Bouvet Island' }, { value: 'BR', label: 'Brazil' }, { value: 'IO', label: 'British Indian Ocean Territory' }, { value: 'VG', label: 'British Virgin Islands' }, { value: 'BN', label: 'Brunei Darussalam' }, { value: 'BG', label: 'Bulgaria' }, { value: 'BF', label: 'Burkina Faso' }, { value: 'BI', label: 'Burundi' }, { value: 'KH', label: 'Cambodia' }, { value: 'CM', label: 'Cameroon' }, { value: 'CA', label: 'Canada' }, { value: 'CV', label: 'Cape Verde' }, { value: 'KY', label: 'Cayman Islands' }, { value: 'CF', label: 'Central African Republic' }, { value: 'TD', label: 'Chad' }, { value: 'CL', label: 'Chile' }, { value: 'CN', label: 'China' }, { value: 'CX', label: 'Christmas Island' }, { value: 'CC', label: 'Cocos (Keeling) Islands' }, { value: 'CO', label: 'Colombia' }, { value: 'KM', label: 'Comoros' }, { value: 'CG', label: 'Congo' }, { value: 'CD', label: 'Congo (The Democratic Republic of the)' }, { value: 'CK', label: 'Cook Islands' }, { value: 'CR', label: 'Costa Rica' }, { value: 'CI', label: 'Cote d Ivoire (Ivory Coast)' }, { value: 'HR', label: 'Croatia' }, { value: 'CU', label: 'Cuba' }, { value: 'CW', label: 'Curaçao' }, { value: 'CY', label: 'Cyprus' }, { value: 'CZ', label: 'Czech Republic' }, { value: 'DK', label: 'Denmark' }, { value: 'DJ', label: 'Djibouti' }, { value: 'DM', label: 'Dominica' }, { value: 'DO', label: 'Dominican Republic' }, { value: 'TL', label: 'East Timor' }, { value: 'EC', label: 'Ecuador' }, { value: 'EG', label: 'Egypt' }, { value: 'SV', label: 'El Salvador' }, { value: 'GQ', label: 'Equatorial Guinea' }, { value: 'ER', label: 'Eritrea' }, { value: 'EE', label: 'Estonia' }, { value: 'ET', label: 'Ethiopia' }, { value: 'FK', label: 'Falkland Islands (Malvinas)' }, { value: 'FO', label: 'Faroe Islands' }, { value: 'FJ', label: 'Fiji' }, { value: 'FI', label: 'Finland' }, { value: 'FR', label: 'France' }, { value: 'GF', label: 'French Guiana' }, { value: 'PF', label: 'French Polynesia' }, { value: 'TF', label: 'French Southern Territories' }, { value: 'GA', label: 'Gabon' }, { value: 'GM', label: 'Gambia' }, { value: 'GE', label: 'Georgia' }, { value: 'DE', label: 'Germany' }, { value: 'GH', label: 'Ghana' }, { value: 'GI', label: 'Gibraltar' }, { value: 'GR', label: 'Greece' }, { value: 'GL', label: 'Greenland' }, { value: 'GD', label: 'Grenada' }, { value: 'GP', label: 'Guadeloupe' }, { value: 'GT', label: 'Guatemala' }, { value: 'GN', label: 'Guinea' }, { value: 'GW', label: 'Guinea-Bissau' }, { value: 'GY', label: 'Guyana' }, { value: 'HT', label: 'Haiti' }, { value: 'HM', label: 'Heard Island and McDonald Islands' }, { value: 'VA', label: 'Holy See (Vatican City State)' }, { value: 'HN', label: 'Honduras' }, { value: 'HK', label: 'Hong Kong' }, { value: 'HU', label: 'Hungary' }, { value: 'IS', label: 'Iceland' }, { value: 'IN', label: 'India' }, { value: 'ID', label: 'Indonesia' }, { value: 'IQ', label: 'Iraq' }, { value: 'IE', label: 'Ireland' }, { value: 'IR', label: 'Islamic Republic of Iran' }, { value: 'IL', label: 'Israel' }, { value: 'IT', label: 'Italy' }, { value: 'JM', label: 'Jamaica' }, { value: 'JP', label: 'Japan' }, { value: 'JO', label: 'Jordan' }, { value: 'KZ', label: 'Kazakhstan' }, { value: 'KE', label: 'Kenya' }, { value: 'KI', label: 'Kiribati' }, { value: 'KP', label: 'Korea (Democratic People s Republic of)' }, { value: 'KR', label: 'Korea (Republic of)' }, { value: 'KW', label: 'Kuwait' }, { value: 'KG', label: 'Kyrgzstan' }, { value: 'LA', label: 'Lao People s Democratic Republic' }, { value: 'LV', label: 'Latvia' }, { value: 'LB', label: 'Lebanon' }, { value: 'LS', label: 'Lesotho' }, { value: 'LR', label: 'Liberia' }, { value: 'LY', label: 'Libyan Arab Jamahiriya' }, { value: 'LI', label: 'Liechtenstein' }, { value: 'LT', label: 'Lithuania' }, { value: 'LU', label: 'Luxembourg' }, { value: 'MO', label: 'Macao' }, { value: 'MK', label: 'Macedonia' }, { value: 'MG', label: 'Madagascar' }, { value: 'MW', label: 'Malawi' }, { value: 'MY', label: 'Malaysia' }, { value: 'MV', label: 'Maldives' }, { value: 'ML', label: 'Mali' }, { value: 'MT', label: 'Malta' }, { value: 'MH', label: 'Marshall Islands' }, { value: 'MQ', label: 'Martinique' }, { value: 'MR', label: 'Mauritania' }, { value: 'MU', label: 'Mauritius' }, { value: 'YT', label: 'Mayotte' }, { value: 'MX', label: 'Mexico' }, { value: 'MD', label: 'Moldova' }, { value: 'MC', label: 'Monaco' }, { value: 'MN', label: 'Mongolia' }, { value: 'ME', label: 'Montenegro' }, { value: 'MS', label: 'Montserrat' }, { value: 'MA', label: 'Morocco' }, { value: 'MZ', label: 'Mozambique' }, { value: 'MM', label: 'Myanmar' }, { value: 'NA', label: 'Namibia' }, { value: 'NR', label: 'Nauru' }, { value: 'NP', label: 'Nepal' }, { value: 'NL', label: 'Netherlands' }, { value: 'AN', label: 'Netherlands Antilles' }, { value: 'NC', label: 'New Caledonia' }, { value: 'NZ', label: 'New Zealand' }, { value: 'NI', label: 'Nicaragua' }, { value: 'NE', label: 'Niger' }, { value: 'NG', label: 'Nigeria' }, { value: 'NU', label: 'Niue' }, { value: 'NF', label: 'Norfolk Island' }, { value: 'NO', label: 'Norway' }, { value: 'OM', label: 'Oman' }, { value: 'PK', label: 'Pakistan' }, { value: 'PW', label: 'Palau' }, { value: 'PA', label: 'Panama' }, { value: 'PG', label: 'Papua New Guinea' }, { value: 'PY', label: 'Paraguay' }, { value: 'PE', label: 'Peru' }, { value: 'PH', label: 'Philippines' }, { value: 'PN', label: 'Pitcairn' }, { value: 'PL', label: 'Poland' }, { value: 'PT', label: 'Portugal' }, { value: 'PR', label: 'Puerto Rico' }, { value: 'QA', label: 'Qatar' }, { value: 'RE', label: 'Reunion' }, { value: 'RO', label: 'Romania' }, { value: 'RU', label: 'Russian Federation' }, { value: 'RW', label: 'Rwanda' }, { value: 'SH', label: 'Saint Helena' }, { value: 'KN', label: 'Saint Kitts and Nevis' }, { value: 'LC', label: 'Saint Lucia' }, { value: 'PM', label: 'Saint Pierre and Miquelon' }, { value: 'VC', label: 'Saint Vincent and the Grenadines' }, { value: 'WS', label: 'Samoa' }, { value: 'SM', label: 'San Marino' }, { value: 'ST', label: 'Sao Tome and Principe' }, { value: 'SA', label: 'Saudi Arabia' }, { value: 'SN', label: 'Senegal' }, { value: 'RS', label: 'Serbia' }, { value: 'SC', label: 'Seychelles' }, { value: 'SL', label: 'Sierra Leone' }, { value: 'SG', label: 'Singapore' }, { value: 'SK', label: 'Slovakia' }, { value: 'SI', label: 'Slovenia' }, { value: 'SB', label: 'Solomon Islands' }, { value: 'SO', label: 'Somalia' }, { value: 'ZA', label: 'South Africa' }, { value: 'GS', label: 'South Georgia and the South Sandwich Islands' }, { value: 'ES', label: 'Spain' }, { value: 'LK', label: 'Sri Lanka' }, { value: 'SD', label: 'Sudan' }, { value: 'SR', label: 'Suriname' }, { value: 'SJ', label: 'Svalbard and Jan Mayen' }, { value: 'SZ', label: 'Swaziland' }, { value: 'SE', label: 'Sweden' }, { value: 'CH', label: 'Switzerland' }, { value: 'SY', label: 'Syrian Arab Republic' }, { value: 'TW', label: 'Taiwan' }, { value: 'TJ', label: 'Tajikstan' }, { value: 'TZ', label: 'Tanzania United Republic' }, { value: 'TH', label: 'Thailand' }, { value: 'TG', label: 'Togo' }, { value: 'TK', label: 'Tokelau' }, { value: 'TO', label: 'Tonga' }, { value: 'TT', label: 'Trinidad and Tobago' }, { value: 'TN', label: 'Tunisia' }, { value: 'TR', label: 'Turkey' }, { value: 'TM', label: 'Turkmenistan' }, { value: 'TC', label: 'Turks and Caicos Islands' }, { value: 'TV', label: 'Tuvalu' }, { value: 'UG', label: 'Uganda' }, { value: 'UA', label: 'Ukraine' }, { value: 'AE', label: 'United Arab Emirates' }, { value: 'GB', label: 'United Kingdom' }, { value: 'US', label: 'United States' }, { value: 'UY', label: 'Uruguay' }, { value: 'UZ', label: 'Uzbekistan' }, { value: 'VU', label: 'Vanuatu' }, { value: 'VE', label: 'Venezuela' }, { value: 'VN', label: 'Vietnam' }, { value: 'WF', label: 'Wallis and Futuna' }, { value: 'EH', label: 'Western Sahara' }, { value: 'YE', label: 'Yemen' }, { value: 'ZM', label: 'Zambia' }, { value: 'ZW', label: 'Zimbabwe' }, ]; const countriesByAbbr = COUNTRIES.reduce<{ [key: string]: string }>( (list, country) => ({ ...list, [country.value]: country.label }), {} ); const getCountryByAbbr = (abbr: string) => countriesByAbbr[abbr]; export const getLocalizedCountryByAbbr = ( abbr: string, languageOrLanguages: string | readonly string[] ): string | undefined => { const [language, languages] = languageOrLanguages instanceof Array ? [languageOrLanguages[0], languageOrLanguages] : [languageOrLanguages, [languageOrLanguages]]; if (!language || /^en([_-].*)?$/.test(language)) { return getCountryByAbbr(abbr); } const normalizedLanguages = languages.map((l) => l.replace(/_/g, '-')); try { const shortName = new Intl.DisplayNames(normalizedLanguages, { type: 'region', style: 'short' }).of(abbr); switch (language.split(/[_-]/)[0]) { case 'jp': case 'zh': return shortName || getCountryByAbbr(abbr); } const longName = new Intl.DisplayNames(normalizedLanguages, { type: 'region' }).of(abbr); if (shortName && longName && shortName.length < 6 && longName.length < 14) { return longName || getCountryByAbbr(abbr); } return shortName || getCountryByAbbr(abbr); } catch (e) { return getCountryByAbbr(abbr); } }; export const correctAbbr = (abbr: string) => (abbr === 'UK' ? 'GB' : abbr); interface CountryItem { value: string; key: string; label: string; disabled: boolean; } export const getFullList = (): CountryItem[] => TOP_COUNTRIES.map((country) => ({ ...country, key: `${country.value}-top`, disabled: false, })).concat( [DEFAULT_SEPARATOR], COUNTRIES.map((country) => ({ ...country, disabled: false, key: country.value })) ); export const getList = () => COUNTRIES; export const getFirstTop = () => TOP_COUNTRIES[0];
7,003
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/helpers/createScrollIntoView.tsx
const DEFAULT_DURATION = 600; const easeOutQuad = (t: number) => (t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1); const createScrollIntoView = (target: Element, container: Element, indefinite?: boolean, offset = 0) => { let rafId: number; let start: number; const duration = DEFAULT_DURATION; const run = (timestamp: number) => { if (!start) { start = timestamp; } const time = timestamp - start; const percent = easeOutQuad(Math.min(time / duration, 1)); const rectTarget = target.getBoundingClientRect(); const rectContainer = container.getBoundingClientRect(); const diff = rectTarget.top - rectContainer.top - offset; const scrollY = container.scrollTop + diff * percent; container.scrollTop = Math.round(scrollY); if (time < duration || indefinite) { rafId = requestAnimationFrame(run); } }; rafId = requestAnimationFrame(run); return () => { cancelAnimationFrame(rafId); }; }; export default createScrollIntoView;
7,004
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/helpers/earlyAccessDesynchronization.ts
import { APPS, APP_NAMES } from '@proton/shared/lib/constants'; import { doesNotSupportEarlyAccessVersion } from '@proton/shared/lib/helpers/browser'; import { getItem, removeItem, setItem } from '@proton/shared/lib/helpers/sessionStorage'; import { Environment } from '@proton/shared/lib/interfaces'; import { UserSettings } from '@proton/shared/lib/interfaces'; import { Feature } from '../containers/features/FeaturesContext'; import { getTargetEnvironment, getVersionCookieIsValid, updateVersionCookie, versionCookieAtLoad, } from '../hooks/useEarlyAccess'; const MAX_NUMBER_OF_EARLY_ACCESS_DESYNCHRONIZATION_RETRIES = 2; // Set to -1 in browser to disable auto refresh const EARLY_ACCESS_DESYNCHRONIZATION_RETRIES_STORAGE_KEY = 'EARLY_ACCESS_DESYNCHRONIZATION_RETRIES_STORAGE_KEY'; const getCurrentRetries = () => { const currentRetries = Number(getItem(EARLY_ACCESS_DESYNCHRONIZATION_RETRIES_STORAGE_KEY)); if (Number.isNaN(currentRetries)) { return undefined; } return currentRetries; }; export const setCurrentRetries = (currentRetries: number) => { setItem(EARLY_ACCESS_DESYNCHRONIZATION_RETRIES_STORAGE_KEY, `${currentRetries}`); }; const removeCurrentRetries = () => { removeItem(EARLY_ACCESS_DESYNCHRONIZATION_RETRIES_STORAGE_KEY); }; export const handleEarlyAccessDesynchronization = ({ userSettings, earlyAccessScope, appName, }: { userSettings: UserSettings; earlyAccessScope: Feature<Environment> | undefined; appName: APP_NAMES; }) => { if (doesNotSupportEarlyAccessVersion()) { return; } const currentRetries = getCurrentRetries() || 0; if (currentRetries >= MAX_NUMBER_OF_EARLY_ACCESS_DESYNCHRONIZATION_RETRIES || currentRetries < 0) { return; } // TEMP: Exempt 'relaunch' from desynchronisation reload while it's under wraps if ((versionCookieAtLoad as any) === 'relaunch') { return; } const normalizedVersionCookieAtLoad = getVersionCookieIsValid(versionCookieAtLoad, earlyAccessScope) ? versionCookieAtLoad : undefined; const targetEnvironment = getTargetEnvironment(earlyAccessScope, Boolean(userSettings.EarlyAccess)); const environmentIsDesynchronized = normalizedVersionCookieAtLoad !== targetEnvironment; const isVpnSettings = appName === APPS.PROTONVPN_SETTINGS; const shouldUpdateToEarlyAccessVersion = !isVpnSettings && environmentIsDesynchronized; if (shouldUpdateToEarlyAccessVersion) { return () => { setCurrentRetries(currentRetries + 1); updateVersionCookie(targetEnvironment, earlyAccessScope); window.location.reload(); }; } removeCurrentRetries(); };
7,005
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/helpers/getBoldFormattedText.tsx
// Replace "**" by strong tags const getBoldFormattedText = (text: string) => { const splitText = text.split('**'); // If the length is odd, it means that we can apply the change on the text if (splitText.length > 2 && splitText.length % 2 !== 0) { const formattedText = splitText.map((s, index) => { // All odd indexes corresponds to a part to surround with a tag if (index % 2 !== 0) { return <strong key={`formattedText-${s}`}>{s}</strong>; } return <span key={`formattedText-${s}`}>{s}</span>; }); return <>{formattedText}</>; } return text; }; export default getBoldFormattedText;
7,006
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/helpers/getCustomSizingClasses.ts
import clsx from '@proton/utils/clsx'; export const getCustomSizingClasses = (style?: any): string => { if (!style) { return ''; } return clsx([ style['--h-custom'] !== undefined && 'h-custom', style['--w-custom'] !== undefined && 'w-custom', style['--top-custom'] !== undefined && 'top-custom', style['--right-custom'] !== undefined && 'right-custom', style['--left-custom'] !== undefined && 'left-custom', style['--bottom-custom'] !== undefined && 'bottom-custom', ]); };
7,007
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/helpers/getObjectKeys.ts
export const getObjectKeys = <T>(obj: T | undefined): (keyof T)[] => { return Object.keys(obj || {}) as (keyof T)[]; };
7,008
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/helpers/index.ts
export * from './component'; export * from './appVersion'; export * from './getCustomSizingClasses'; export * from './getObjectKeys';
7,009
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/helpers/report.ts
import { APPS_CONFIGURATION, APP_NAMES } from '@proton/shared/lib/constants'; import { getBrowser, getDevice, getOS } from '@proton/shared/lib/helpers/browser'; export const getClientName = (appName: APP_NAMES) => { return `Web ${APPS_CONFIGURATION[appName].bareName}`; }; const getIsTouchDevice = () => navigator.maxTouchPoints > 1; // Override the reported OS name. On iOS in the Safari Settings there is a setting called "Request Desktop Website". // When this is enabled the user agent meta-data is altered by Safari mimicking a Desktop device so that it will // trick servers into sending the desktop version by setting the user agent's OS to MacOS. const getArtificialOSName = (osName: string) => { if (!getIsTouchDevice()) { return; } if (osName === 'Mac OS') { return 'iOS'; } if (osName === 'Linux') { return 'Android'; } }; const getEnhancedOSInfo = () => { const os = getOS(); const artificialOSName = getArtificialOSName(os.name); if (artificialOSName) { return { name: artificialOSName, version: '', artificial: true, }; } return { ...os, artificial: false, }; }; export const getReportInfo = () => { const browser = getBrowser(); const device = getDevice(); const os = getEnhancedOSInfo(); return { OS: os.name, OSVersion: os.version || '', OSArtificial: os.artificial, Browser: browser.name, BrowserVersion: browser.version, Resolution: `${window.innerHeight} x ${window.innerWidth}`, DeviceName: device.vendor, DeviceModel: device.model, }; };
7,010
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/helpers/url.test.helpers.ts
const initialWindowLocation: Location = window.location; export const mockWindowLocation = (origin = 'https://mail.proton.pink', hostname = 'mail.proton.pink') => { // @ts-ignore delete window.location; window.location = { ...initialWindowLocation, origin, hostname }; }; export const resetWindowLocation = () => { window.location = initialWindowLocation; };
7,011
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/helpers/url.test.ts
import { getHostname, isExternal, isMailTo, isSubDomain, isURLProtonInternal, punycodeUrl, } from '@proton/components/helpers/url'; import { mockWindowLocation, resetWindowLocation } from '@proton/components/helpers/url.test.helpers'; const windowHostname = 'mail.proton.me'; describe('isSubDomain', function () { it('should detect that same hostname is a subDomain', () => { const hostname = 'mail.proton.me'; expect(isSubDomain(hostname, hostname)).toBeTruthy(); }); it('should detect that domain is a subDomain', () => { const hostname = 'mail.proton.me'; const domain = 'proton.me'; expect(isSubDomain(hostname, domain)).toBeTruthy(); }); it('should detect that domain is not a subDomain', () => { const hostname = 'mail.proton.me'; const domain = 'whatever.com'; expect(isSubDomain(hostname, domain)).toBeFalsy(); }); }); describe('getHostname', function () { it('should give the correct hostname', () => { const hostname = 'mail.proton.me'; const url = `https://${hostname}/u/0/inbox`; expect(getHostname(url)).toEqual(hostname); }); }); describe('isMailTo', function () { it('should detect that the url is a mailto link', () => { const url = 'mailto:mail@proton.me'; expect(isMailTo(url)).toBeTruthy(); }); it('should detect that the url is not a mailto link', () => { const url = 'https://proton.me'; expect(isMailTo(url)).toBeFalsy(); }); }); describe('isExternal', function () { beforeEach(() => { mockWindowLocation(undefined, windowHostname); }); afterEach(() => { resetWindowLocation(); }); it('should detect that the url is not external', () => { const url1 = 'https://mail.proton.me'; expect(window.location.hostname).toEqual(windowHostname); expect(isExternal(url1)).toBeFalsy(); }); it('should detect that the url is external', () => { const url = 'https://url.whatever.com'; expect(window.location.hostname).toEqual(windowHostname); expect(isExternal(url)).toBeTruthy(); }); it('should detect that the mailto link is not external', () => { const url = 'mailto:mail@proton.me'; expect(window.location.hostname).toEqual(windowHostname); expect(isExternal(url)).toBeFalsy(); }); }); describe('isProtonInternal', function () { beforeEach(() => { mockWindowLocation(undefined, windowHostname); }); afterEach(() => { resetWindowLocation(); }); it('should detect that the url is proton internal', () => { const url1 = 'https://mail.proton.me'; const url2 = 'https://calendar.proton.me'; expect(isURLProtonInternal(url1)).toBeTruthy(); expect(isURLProtonInternal(url2)).toBeTruthy(); }); it('should detect that the url is not proton internal', () => { const url = 'https://url.whatever.com'; expect(isURLProtonInternal(url)).toBeFalsy(); }); }); describe('punycodeUrl', () => { it('should encode the url with punycode', () => { // reference: https://www.xudongz.com/blog/2017/idn-phishing/ const url = 'https://www.аррӏе.com'; const encodedUrl = punycodeUrl(url); expect(encodedUrl).toEqual('https://www.xn--80ak6aa92e.com'); }); it('should encode url with punycode and keep pathname, query parameters and fragment', () => { const url = 'https://www.äöü.com/ümläüts?ä=ö&ü=ä#ümläüts'; const encodedUrl = punycodeUrl(url); expect(encodedUrl).toEqual( 'https://www.xn--4ca0bs.com/%C3%BCml%C3%A4%C3%BCts?%C3%A4=%C3%B6&%C3%BC=%C3%A4#%C3%BCml%C3%A4%C3%BCts' ); }); it('should not encode url already punycode', () => { const url = 'https://www.xn--4ca0bs.com'; const encodedUrl = punycodeUrl(url); expect(encodedUrl).toEqual(url); }); it('should not encode url with no punycode', () => { const url = 'https://www.protonmail.com'; const encodedUrl = punycodeUrl(url); expect(encodedUrl).toEqual(url); }); it('should keep the trailing slash', () => { const url = 'https://www.äöü.com/EDEQWE/'; const encodedUrl = punycodeUrl(url); expect(encodedUrl).toEqual('https://www.xn--4ca0bs.com/EDEQWE/'); }); it('should keep the port', () => { const url = 'https://www.äöü.com:8080'; const encodedUrl = punycodeUrl(url); expect(encodedUrl).toEqual('https://www.xn--4ca0bs.com:8080'); }); it('should keep the trailing slash if hash or search after', () => { const sUrl = 'https://www.dude.com/r/?dude=buddy'; const encodedSUrl = punycodeUrl(sUrl); expect(encodedSUrl).toEqual('https://www.dude.com/r/?dude=buddy'); const hUrl = 'https://www.dude.com/r/#dude'; const encodedHUrl = punycodeUrl(hUrl); expect(encodedHUrl).toEqual('https://www.dude.com/r/#dude'); }); });
7,012
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/helpers/url.ts
import punycode from 'punycode.js'; import { getSecondLevelDomain } from '@proton/shared/lib/helpers/url'; import window from '@proton/shared/lib/window'; import isTruthy from '@proton/utils/isTruthy'; export const isSubDomain = (hostname: string, domain: string) => { if (hostname === domain) { return true; } return hostname.endsWith(`.${domain}`); }; export const getHostname = (url: string) => { // The easy way to parse an URL, is to create <a> element. // @see: https://gist.github.com/jlong/2428561 const parser = document.createElement('a'); parser.href = url; return parser.hostname; }; export const isMailTo = (url: string): boolean => { return url.toLowerCase().startsWith('mailto:'); }; export const isExternal = (url: string) => { try { return window.location.hostname !== getHostname(url) && !isMailTo(url); } catch (e: any) { /* * IE11/Edge are the worst, they crash when they try to parse * ex: http://xn--rotonmail-4sg.com * so if it does we know it's an external link (⌐■_■) */ return true; } }; export const isURLProtonInternal = (url: string) => { const currentDomain = getSecondLevelDomain(window.location.hostname); const targetOriginHostname = getHostname(url); // Still need to check the current domain otherwise it would not work on proton.local, localhost, etc... return ['protonmail.com', currentDomain] .filter(isTruthy) .some((domain) => isSubDomain(targetOriginHostname, domain)); }; /** * Force URL to display punycode * Punycode is a special encoding used to convert Unicode characters to ASCII, which is a smaller, restricted character set. Punycode is used to encode internationalized domain names (IDN). * Explanation about the potential attack: https://www.xudongz.com/blog/2017/idn-phishing/ */ export const punycodeUrl = (url: string) => { const hasTrailingSlash = url.endsWith('/'); const { protocol, hostname, pathname, search, hash, port } = new URL(url); const punycodeHostname = punycode.toASCII(hostname); // Even if modern browsers support IDN, we still need to convert it to punycode for old browsers const cleanPathname = search || hash ? pathname : pathname.replace(/\/$/, ''); // Remove trailing slash if no search or hash after return `${protocol}//${punycodeHostname}${port ? `:${port}` : ''}${cleanPathname}${search}${hash}${ hasTrailingSlash ? '/' : '' }`; };
7,013
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/index.ts
export { default as useActiveBreakpoint } from './useActiveBreakpoint'; export { default as useElementBreakpoints } from './useElementBreakpoints'; export { default as useActiveWindow } from './useActiveWindow'; export { default as useAddresses, useGetAddresses } from './useAddresses'; export { useAddressesKeys, useGetAddressesKeys } from './useAddressesKeys'; export { default as useAddressFlags } from './useAddressFlags'; export { default as useApi } from './useApi'; export { default as useApiResult } from './useApiResult'; export { default as useApiWithoutResult } from './useApiWithoutResult'; export { default as useAppTitle } from './useAppTitle'; export { default as useAuthentication } from './useAuthentication'; export { default as useAutocompleteAriaProps } from './useAutocompleteAriaProps'; export { default as useBeforeUnload } from './useBeforeUnload'; export { default as useCache } from './useCache'; export { default as useCachedModelResult } from './useCachedModelResult'; export { default as useCalendars, useGetCalendars } from './useCalendars'; export { default as useSubscribedCalendars } from './useSubscribedCalendars'; export { default as useCalendarShareInvitations } from './useCalendarShareInvitations'; export { default as useCalendarShareInvitationActions } from './useCalendarShareInvitationActions'; export * from './useCalendarUserSettings'; export { default as useCanReactivateKeys } from './useCanReactivateKeys'; export { useLabels, useFolders, useSystemFolders, useContactGroups } from './useCategories'; export { default as useClickOutside } from './useClickOutside'; export { default as useConfig } from './useConfig'; export { default as useContactEmails } from './useContactEmails'; export { default as useContactEmailsSortedByName } from './useContactEmailsSortedByName'; export { default as useContacts } from './useContacts'; export * from './useConversationCounts'; export { default as useCookieState } from './useCookieState'; export { default as useCyberMondayPeriod } from './useCyberMondayPeriod'; export { default as useDocumentTitle } from './useDocumentTitle'; export { default as useDomains } from './useDomains'; export { default as useDomainsAddresses } from './useDomainsAddresses'; export { useDeviceRecovery, useIsDeviceRecoveryAvailable, useIsDeviceRecoveryEnabled } from './useDeviceRecovery'; export { default as useDragMove } from './useDragMove'; export { default as useDragOver } from './useDragOver'; export { default as useDropdownArrowNavigation } from './useDropdownArrowNavigation'; export { default as useEarlyAccess } from './useEarlyAccess'; export { default as useElementRect } from './useElementRect'; export { default as useErrorHandler } from './useErrorHandler'; export { default as useEventManager } from './useEventManager'; export { default as useLoadFeature } from './useLoadFeature'; export { default as useFeature } from './useFeature'; export { default as useFeatures } from './useFeatures'; export { default as useProgressiveRollout } from './useProgressiveRollout'; export { default as useExperiment } from './useExperiment'; export { default as useFilters } from './useFilters'; export { default as useFolderColor } from './useFolderColor'; export { default as useForceRefresh } from './useForceRefresh'; export { default as useGetAddressKeys } from './useGetAddressKeys'; export { default as useGetCalendarBootstrap, useCalendarBootstrap, useReadCalendarBootstrap, } from './useGetCalendarBootstrap'; export { default as useGetCalendarInfo } from './useGetCalendarInfo'; export { default as useGetCalendarEventRaw } from './useGetCalendarEventRaw'; export { useGetDecryptedPassphraseAndCalendarKeys, useGetCalendarKeys, } from './useGetDecryptedPassphraseAndCalendarKeys'; export { default as useGetEncryptionPreferences } from './useGetEncryptionPreferences'; export { default as useGetVerificationPreferences } from './useGetVerificationPreferences'; export { default as useGetOrganizationKeyRaw } from './useGetOrganizationKeyRaw'; export { default as useGetPublicKeysForInbox } from './useGetPublicKeysForInbox'; export { default as useHasOutdatedRecoveryFile } from './useHasOutdatedRecoveryFile'; export { default as useHandler, useEventListener, useSubscribeEventManager, useInterval } from './useHandler'; export { default as useHasSuspendedCounter } from './useHasSuspendedCounter'; export * from './useHotkeys'; export * from './useImporters'; export { default as useIsClosing } from './useIsClosing'; export { default as useKeyPress } from './useKeyPress'; export { default as useLoad } from './useLoad'; export { default as useLocalState } from './useLocalState'; export * from './useMailSettings'; export { default as useMainArea, MainAreaContext } from './useMainArea'; export { useMemberAddresses } from './useMemberAddresses'; export { default as useMembers } from './useMembers'; export * from './useMessageCounts'; export { default as useModals } from './useModals'; export { default as useMozillaCheck } from './useMozillaCheck'; export { default as useIsDataRecoveryAvailable } from './useIsDataRecoveryAvailable'; export { default as useIsMnemonicAvailable } from './useIsMnemonicAvailable'; export { default as useIsRecoveryFileAvailable } from './useIsRecoveryFileAvailable'; export { default as useMyCountry } from './useMyCountry'; export { default as useMyLocation } from './useMyLocation'; export { default as useNextSubscription } from './useNextSubscription'; export { default as useNotifications } from './useNotifications'; export { default as useOnline } from './useOnline'; export * from './useOrganization'; export { default as useOrganizationKey } from './useOrganizationKey'; export { default as useIsPaidUserCookie } from './useIsPaidUserCookie'; export { default as useIsProtonUserCookie } from './useIsProtonUserCookie'; export { default as usePaymentMethods } from './usePaymentMethods'; export { default as usePlans } from './usePlans'; export { default as usePremiumDomains } from './usePremiumDomains'; export { default as usePreventLeave, PreventLeaveProvider } from './usePreventLeave'; export { default as usePrimaryRecoverySecret } from './usePrimaryRecoverySecret'; export { default as usePromiseResult } from './usePromiseResult'; export { default as useRecoverySecrets } from './useRecoverySecrets'; export { default as useRecoveryStatus } from './useRecoveryStatus'; export { default as useRevisionRetentionDays } from './useRevisionRetentionDays'; export { default as useSearch } from './useSearch'; export { default as useRecoveryNotification } from './useRecoveryNotification'; export { default as useSortedList, useSortedListAsync, useMultiSortedList } from './useSortedList'; export { default as useSpotlightOnFeature } from './useSpotlightOnFeature'; export { default as useStep } from './useStep'; export { default as useSubscription, useTypedSubscription } from './useSubscription'; export { default as useLastSubscriptionEnd } from './useLastSubscriptionEnd'; export { default as useSvgGraphicsBbox } from './useSvgGraphicsBbox'; export { default as useApiEnvironmentConfig } from './useApiEnvironmentConfig'; export { default as useRelocalizeText } from './useRelocalizeText'; export * from './useSessionRecovery'; export { default as useToggle } from './useToggle'; export { default as useTraceUpdate } from './useTraceUpdate'; export { default as useUser, useGetUser } from './useUser'; export { useUserKeys, useGetUserKeys } from './useUserKeys'; export { default as useUserScopes } from './useUserScopes'; export { default as useUserSettings } from './useUserSettings'; export { default as useUserVPN } from './useUserVPN'; export { default as useVPNLogicals } from './useVPNLogicals'; export { default as useVPNServersCount } from './useVPNServersCount'; export { default as useWelcomeFlags } from './useWelcomeFlags'; export * from './useWelcomeFlags'; export { default as useWindowSize } from './useWindowSize'; export { default as useSearchParamsEffect } from './useSearchParamsEffect'; export * from './drawer'; export { default as useDynamicFavicon } from './useDynamicFavicon'; export * from './useDriveWindowsGASpotlight'; export { useDragToScroll } from './useDragToScroll'; export { default as useIsInboxElectronApp } from './useIsInboxElectronApp';
7,014
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useActiveBreakpoint.ts
import { useEffect, useMemo, useState } from 'react'; import debounce from '@proton/utils/debounce'; const getBreakpoint = () => { const bodyEl = document.querySelector('body'); if (!bodyEl) { return ''; } return window.getComputedStyle(bodyEl, ':before').getPropertyValue('content').replace(/['"]+/g, ''); }; /** Contains React state setter of each instantiated hooks */ const callbackStack: Set<Function> = new Set(); const onResize = () => { const result = getBreakpoint(); for (let callback of callbackStack.values()) { callback(result); } }; const onResizeDebounced = debounce(onResize, 250); const useActiveBreakpoint = () => { const [breakpoint, setBreakpoint] = useState(() => getBreakpoint()); useEffect(() => { if (callbackStack.size === 0) { window.addEventListener('load', onResize); window.addEventListener('resize', onResizeDebounced); } callbackStack.add(setBreakpoint); return () => { callbackStack.delete(setBreakpoint); if (callbackStack.size === 0) { window.removeEventListener('load', onResize); window.removeEventListener('resize', onResizeDebounced); } }; }, []); return useMemo(() => { const isLargeDesktop = breakpoint === 'large-desktop'; const isMediumDesktop = breakpoint === 'medium-desktop'; const isSmallDesktop = breakpoint === 'small-desktop'; const isTablet = breakpoint === 'tablet'; const isMobile = breakpoint === 'mobile'; const isTinyMobile = breakpoint === 'tinymobile'; return { breakpoint, isLargeDesktop, isMediumDesktop, isSmallDesktop, isDesktop: isLargeDesktop || isMediumDesktop || isSmallDesktop, isTablet, isMobile, isTinyMobile, isNarrow: isMobile || isTinyMobile, }; }, [breakpoint]); }; export default useActiveBreakpoint;
7,015
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useActiveWindow.ts
import { useEffect, useState } from 'react'; const useActiveWindow = () => { const [windowIsActive, setWindowIsActive] = useState(true); const onFocus = () => setWindowIsActive(true); const onBlur = () => setWindowIsActive(false); useEffect(() => { window.addEventListener('focus', onFocus); window.addEventListener('blur', onBlur); return () => { window.removeEventListener('focus', onFocus); window.removeEventListener('blur', onBlur); }; }, []); return windowIsActive; }; export default useActiveWindow;
7,016
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useAddressFlags.ts
import { c } from 'ttag'; import { FeatureCode } from '@proton/components/containers/features'; import { useKTVerifier } from '@proton/components/containers/keyTransparency'; import { getNewKeyFlags } from '@proton/components/containers/keys/shared/flags'; import { FlagAction } from '@proton/components/containers/keys/shared/interface'; import { useAddressesKeys, useApi, useEventManager, useFeature, useNotifications, useUser, } from '@proton/components/hooks'; import { updateAddressFlags } from '@proton/shared/lib/api/members'; import { ADDRESS_FLAGS } from '@proton/shared/lib/constants'; import { hasBit } from '@proton/shared/lib/helpers/bitset'; import { Address } from '@proton/shared/lib/interfaces'; import { getActiveKeys, getNormalizedActiveKeys } from '@proton/shared/lib/keys/getActiveKeys'; import { getSignedKeyListWithDeferredPublish } from '@proton/shared/lib/keys/signedKeyList'; type UseAddressFlags = (address?: Address) => { allowDisablingEncryption: boolean; encryptionDisabled: boolean; expectSignatureDisabled: boolean; handleSetAddressFlags: (encryptionDisabled: boolean, expectSignatureDisabled: boolean) => Promise<void>; } | null; const useAddressFlags: UseAddressFlags = (address) => { const api = useApi(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const [User] = useUser(); const [addressesKeys] = useAddressesKeys(); const { keyTransparencyVerify } = useKTVerifier(api, async () => User); const mailDisableE2EEFeature = useFeature<boolean>(FeatureCode.MailDisableE2EE); const isDisableEncryptionEnabled = mailDisableE2EEFeature.feature?.Value === true; if (!address || address.Flags === undefined) { return null; } const handleSetAddressFlags = async ( encryptionDisabled: boolean, expectSignatureDisabled: boolean ): Promise<void> => { const { ID: addressID, SignedKeyList: currentSignedKeyList, Keys: currentKeys } = address; const addressWithKeys = addressesKeys?.find(({ address: { ID } }) => ID === addressID); if (addressWithKeys === undefined) { throw new Error('addressWithKeys is undefined!'); } const { keys } = addressWithKeys; const activeKeys = await getActiveKeys(address, currentSignedKeyList, currentKeys, keys); const newActiveKeys = getNormalizedActiveKeys( address, activeKeys.map((activeKey) => ({ ...activeKey, flags: getNewKeyFlags( getNewKeyFlags( activeKey.flags, encryptionDisabled ? FlagAction.DISABLE_ENCRYPTION : FlagAction.ENABLE_ENCRYPTION ), expectSignatureDisabled ? FlagAction.DISABLE_EXPECT_SIGNED : FlagAction.ENABLE_EXPECT_SIGNED ), })) ); const [newSignedKeyList, onSKLPublishSuccess] = await getSignedKeyListWithDeferredPublish( newActiveKeys, address, keyTransparencyVerify ); await api(updateAddressFlags(address.ID, !encryptionDisabled, !expectSignatureDisabled, newSignedKeyList)); await onSKLPublishSuccess(); await call(); createNotification({ text: c('Success notification').t`Preference updated` }); }; const allowDisablingEncryption = !address.ProtonMX && isDisableEncryptionEnabled; const encryptionDisabled = hasBit(address.Flags, ADDRESS_FLAGS.FLAG_DISABLE_E2EE); const expectSignatureDisabled = hasBit(address.Flags, ADDRESS_FLAGS.FLAG_DISABLE_EXPECTED_SIGNED); return { allowDisablingEncryption, encryptionDisabled, expectSignatureDisabled, handleSetAddressFlags, }; }; export default useAddressFlags;
7,017
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useAddresses.ts
import { useCallback } from 'react'; import { Address } from '@proton/shared/lib/interfaces'; import { GetAddresses } from '@proton/shared/lib/interfaces/hooks/GetAddresses'; import { AddressesModel } from '@proton/shared/lib/models/addressesModel'; import useApi from './useApi'; import useCache from './useCache'; import useCachedModelResult, { getPromiseValue } from './useCachedModelResult'; export const useGetAddresses = (): GetAddresses => { const api = useApi(); const cache = useCache(); const miss = useCallback(() => AddressesModel.get(api), [api]); return useCallback(() => { return getPromiseValue(cache, AddressesModel.key, miss); }, [cache, miss]); }; export const useAddresses = (): [Address[], boolean, any] => { const cache = useCache(); const miss = useGetAddresses(); return useCachedModelResult(cache, AddressesModel.key, miss); }; export default useAddresses;
7,018
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useAddressesKeys.ts
import { useCallback } from 'react'; import { Address, DecryptedKey } from '@proton/shared/lib/interfaces'; import { Unwrap } from '@proton/shared/lib/interfaces/utils'; import { useGetAddresses } from './useAddresses'; import useCache from './useCache'; import useCachedModelResult from './useCachedModelResult'; import { useGetAddressKeys } from './useGetAddressKeys'; export const KEY = 'ADDRESSES_KEYS'; export const useGetAddressesKeys = (): (() => Promise<{ address: Address; keys: DecryptedKey[] }[]>) => { const getAddresses = useGetAddresses(); const getAddressKeys = useGetAddressKeys(); return useCallback(async () => { const addresses = await getAddresses(); return Promise.all( addresses.map(async (address) => { return { address, keys: await getAddressKeys(address.ID), }; }) ); }, [getAddresses, getAddressKeys]); }; export const useAddressesKeys = (): [Unwrap<ReturnType<typeof useGetAddressesKeys>>, boolean, any] => { const cache = useCache(); const miss = useGetAddressesKeys(); return useCachedModelResult(cache, KEY, miss); };
7,019
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useApi.ts
import { useContext } from 'react'; import { Api } from '@proton/shared/lib/interfaces'; import ContextApi from '../containers/api/apiContext'; const useApi = (): Api => { return useContext(ContextApi); }; export default useApi;
7,020
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useApiEnvironmentConfig.ts
import { ApiEnvironmentConfig } from '@proton/shared/lib/interfaces'; import { ApiEnvironmentConfigModel } from '@proton/shared/lib/models/apiEnvironmentConfigModel'; import createUseModelHook from './helpers/createModelHook'; export default createUseModelHook<ApiEnvironmentConfig>(ApiEnvironmentConfigModel);
7,021
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useApiResult.ts
import { useCallback, useEffect } from 'react'; import useApi from './useApi'; import useAsync from './useAsync'; export type QueryFunction = (...args: any[]) => { method: string; url: string }; interface Result<R, U extends any[]> { result: R | undefined; error: Error; loading: boolean; request: (...args: U) => Promise<R>; } const useApiResult = <R, F extends QueryFunction = QueryFunction>( fn: QueryFunction, dependencies?: any[] ): Result<R, Parameters<F>> => { const request = useApi(); const { loading, result, error, run } = useAsync(true); // Either user specified dependencies or empty array to always cancel requests on unmount. const hookDependencies = dependencies || []; // Callback updates const requestAndSetResults = useCallback( (...args: Parameters<F>) => { const promise = request<R>(fn(...args)); run(promise); return promise; }, [request, run, fn] ); useEffect(() => { // If user has specified any dependencies, auto request if (dependencies) { requestAndSetResults(...([] as unknown as Parameters<F>)).catch(() => { // catch the error to stop the "uncaught exception error" }); } }, [...hookDependencies]); if (error) { // Throw in render to allow the error boundary to catch it throw error; } return { result, error, loading, request: requestAndSetResults, }; }; export default useApiResult;
7,022
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useApiServerTime.ts
import { useContext } from 'react'; import ContextApi from '../containers/api/apiServerTimeContext'; const useApiServerTime = () => { return useContext(ContextApi); }; export default useApiServerTime;
7,023
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useApiStatus.ts
import { useContext } from 'react'; import ContextApi from '../containers/api/apiStatusContext'; const useApiStatus = () => { return useContext(ContextApi); }; export default useApiStatus;
7,024
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useApiWithoutResult.ts
import { useCallback } from 'react'; import useApi from './useApi'; import { QueryFunction } from './useApiResult'; import useAsync from './useAsync'; interface Result<R, U extends any[]> { loading: boolean; request: (...args: U) => Promise<R>; } const useApiWithoutResult = <R, F extends QueryFunction = QueryFunction>(fn: F): Result<R, Parameters<F>> => { const request = useApi(); const { loading, run } = useAsync(false); const requestAndSetLoading = useCallback( (...args) => { const promise = request<R>(fn(...args)); run(promise); return promise; }, [request, run, fn] ); return { loading, request: requestAndSetLoading, }; }; export default useApiWithoutResult;
7,025
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useAppTitle.ts
import { useMemo } from 'react'; import { getAppName } from '@proton/shared/lib/apps/helper'; import useConfig from './useConfig'; import useDocumentTitle from './useDocumentTitle'; const useAppTitle = (title?: string, maybeAppName?: string) => { const { APP_NAME } = useConfig(); const memoedTitle = useMemo(() => { const appName = maybeAppName || getAppName(APP_NAME); return [title, appName].filter(Boolean).join(' - '); }, [title]); useDocumentTitle(memoedTitle); }; export default useAppTitle;
7,026
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useAsync.js
import { useCallback, useReducer, useRef } from 'react'; import useIsMounted from '@proton/hooks/useIsMounted'; const DEFAULT_STATE = { loading: false, }; const reducer = (state, action) => { switch (action.type) { case 'loading': return { ...state, loading: true, }; case 'success': return { error: undefined, loading: false, result: action.payload, }; default: case 'error': return { result: undefined, loading: false, error: action.payload, }; } }; const useAsync = (setResults = true) => { const [{ loading, result, error }, dispatch] = useReducer(reducer, DEFAULT_STATE); const isMounted = useIsMounted(); const promiseRef = useRef(); const run = useCallback(async (promise) => { const isCurrentPromise = () => promiseRef.current === promise; promiseRef.current = promise; dispatch({ type: 'loading' }); try { const data = await promise; if (isMounted() && isCurrentPromise()) { dispatch({ type: 'success', payload: setResults ? data : undefined }); } return data; } catch (e) { if (isMounted() && isCurrentPromise() && e.name !== 'AbortError') { dispatch({ type: 'error', payload: setResults ? e : undefined }); } throw e; } }, []); return { result, error, loading, run, }; }; export default useAsync;
7,027
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useAuthentication.ts
import { useContext } from 'react'; import { PrivateAuthenticationStore } from '../containers/app/interface'; import AuthenticationContext from '../containers/authentication/authenticationContext'; const useAuthentication = () => { // Force private authentication store because the public app is a special case return useContext(AuthenticationContext) as PrivateAuthenticationStore; }; export default useAuthentication;
7,028
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useAutoGrow.ts
import { useCallback, useState } from 'react'; const getTextAreaRows = ({ el, minRows, maxRows }: { el: HTMLTextAreaElement; minRows: number; maxRows: number }) => { const textAreaLineHeight = +getComputedStyle(el).lineHeight.replace('px', ''); const previousRows = el.rows; // Reset rows so we can calculate calculate currentRows correctly el.rows = minRows; const currentRows = Math.min(maxRows, Math.max(minRows, ~~(el.scrollHeight / textAreaLineHeight))); // Set rows attribute directly because React won't update it as it stayed the same if (currentRows === previousRows) { el.rows = currentRows; } return currentRows; }; const useAutoGrow = ({ maxRows = 5, minRows = 1, autoGrow = false }) => { const [rows, setRows] = useState(minRows); const updateTextArea = useCallback( (el) => { setRows(getTextAreaRows({ el, minRows, maxRows })); }, [minRows, maxRows] ); if (!autoGrow) { return { rows: maxRows, }; } return { rows, updateTextArea }; }; export default useAutoGrow;
7,029
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useAutocompleteAriaProps.tsx
import { c, msgid } from 'ttag'; const useAutocompleteAriaProps = ({ baseId, selectedSuggest }: { baseId: string; selectedSuggest?: number }) => { const helpTextId = `${baseId}-help-text`; const helpText = ( <span id={helpTextId} className="sr-only"> {c('Help') .t`Use Up and Down keys to access and browse suggestions after input. Press Enter to confirm your choice, or Escape to close the suggestions box.`} </span> ); const getNumberHelpText = (numberOfSuggests: number) => numberOfSuggests > 0 ? ( <div className="sr-only" aria-atomic="true" aria-live="assertive"> {c('Help').ngettext( msgid`Found ${numberOfSuggests} suggestion, use keyboard to navigate.`, `Found ${numberOfSuggests} suggestions, use keyboard to navigate.`, numberOfSuggests )} </div> ) : ( '' ); const suggestionsId = `${baseId}-suggestions`; const getOptionId = (idx: number) => `${baseId}-option-${idx}`; return { labelAriaProps: { for: baseId, }, inputAriaProps: { id: baseId, role: 'combobox', 'aria-autocomplete': 'list' as const, 'aria-owns': suggestionsId, 'aria-activedescendant': selectedSuggest !== undefined ? getOptionId(selectedSuggest) : undefined, 'aria-describedby': helpTextId, autoCorrect: 'off', autoCapitalize: 'off', spellCheck: false, autoComplete: 'off', }, suggestionsAriaProps: { role: 'listbox', id: suggestionsId, }, getAriaPropsForOption: (idx: number) => ({ id: getOptionId(idx), role: 'option', }), helpText, getNumberHelpText, }; }; export default useAutocompleteAriaProps;
7,030
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useBeforeUnload.ts
import { useEffect } from 'react'; import busy from '@proton/shared/lib/busy'; const useBeforeUnload = (message?: string | boolean) => { useEffect(() => { if (!message) { return; } const handleUnload = (event: BeforeUnloadEvent) => { const computedMessage = message === true ? '' : message; if (event) { event.preventDefault(); event.returnValue = computedMessage; } return computedMessage; }; const unregister = busy.register(); window.addEventListener('beforeunload', handleUnload); return () => { unregister(); window.removeEventListener('beforeunload', handleUnload); }; }, [message]); }; export default useBeforeUnload;
7,031
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useCache.ts
import { useContext } from 'react'; import { Cache } from '@proton/shared/lib/helpers/cache'; import Context from '../containers/cache/cacheContext'; const useCache = <K = string, V = any>() => { const cache = useContext(Context); if (!cache) { throw new Error('Trying to use uninitialized CacheContext'); } return cache as Cache<K, V>; }; export default useCache;
7,032
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useCachedModelResult.js
import { useEffect, useMemo, useRef, useState } from 'react'; import { STATUS } from '@proton/shared/lib/models/cache'; const ERROR_IDX = 2; export const getState = ({ value, status } = { status: STATUS.PENDING }, oldState = []) => { return [ // The old state value is returned in case the model has been deleted from the cache status === STATUS.PENDING || status === STATUS.RESOLVED ? value || oldState[0] : undefined, status === STATUS.PENDING, status === STATUS.REJECTED ? value : undefined, ]; }; const getRecordPending = (promise) => { return { status: STATUS.PENDING, value: undefined, promise, timestamp: Date.now(), }; }; const getRecordThen = (promise) => { return promise .then((value) => { return { status: STATUS.RESOLVED, value, timestamp: Date.now(), }; }) .catch((error) => { return { status: STATUS.REJECTED, value: error, timestamp: Date.now(), }; }); }; /** * The strategy to re-fetch is: * 1) When no record exists for that key. * 2) If the old record has failed to fetch. * This should only happen when: * 1) When the component is initially mounted. * 2) A mounted component that receives an update from the cache that the key has been removed. * 3) A mounted component receives an update that the key has changed. * @param {Object} cache * @param {Object} key * @param {Promise} promise * @return {Object} */ const update = (cache, key, promise) => { const record = getRecordPending(promise); cache.set(key, record); getRecordThen(promise).then((newRecord) => cache.get(key) === record && cache.set(key, newRecord)); return record; }; export const getIsRecordInvalid = (record, lifetime = Number.MAX_SAFE_INTEGER) => { return ( !record || record.status === STATUS.REJECTED || (record.status === STATUS.RESOLVED && Date.now() - record.timestamp > lifetime) ); }; export const getPromiseValue = (cache, key, miss, lifetime) => { const oldRecord = cache.get(key); if (getIsRecordInvalid(oldRecord, lifetime)) { const record = update(cache, key, miss(key)); return record.promise; } return oldRecord.promise || Promise.resolve(oldRecord.value); }; /** * Caches a model globally in the cache. Can be updated from the event manager. * @param {Map} cache * @param {String | undefined} key * @param {Function} miss - Returning a promise * @return {[value, loading, error]} */ const useCachedModelResult = (cache, key, miss) => { const [forceRefresh, setForceRefresh] = useState(); const latestValue = useRef(); const result = useMemo(() => { const oldRecord = cache.get(key); // If no record, or it's the first time loading this hook and the promise was previously rejected, retry the fetch strategy. if (!oldRecord || (!latestValue.current && oldRecord.status === STATUS.REJECTED)) { return getState(update(cache, key, miss(key)), latestValue.current); } return getState(oldRecord, latestValue.current); }, [cache, key, miss, forceRefresh]); useEffect(() => { // https://reactjs.org/docs/hooks-faq.html#how-to-read-an-often-changing-value-from-usecallback latestValue.current = result; }); useEffect(() => { const checkForChange = () => { const oldRecord = cache.get(key); if (!oldRecord) { return setForceRefresh({}); } const newValue = getState(oldRecord, latestValue.current); if (newValue.some((value, i) => value !== latestValue.current[i])) { setForceRefresh({}); } }; const cacheListener = (changedKey) => { if (changedKey !== key) { return; } checkForChange(); }; checkForChange(); return cache.subscribe(cacheListener); }, [cache, key, miss]); // Throw in render to allow the error boundary to catch it if (result[ERROR_IDX]) { throw result[ERROR_IDX]; } return result; }; export default useCachedModelResult;
7,033
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useCalendarShareInvitationActions.ts
import { useCallback } from 'react'; import { c } from 'ttag'; import { useAddresses, useEventManager, useGetAddressKeys, useGetEncryptionPreferences, useNotifications, } from '@proton/components/hooks'; import useApi from '@proton/components/hooks/useApi'; import { getSilentApi } from '@proton/shared/lib/api/helpers/customConfig'; import { acceptCalendarShareInvitation, rejectCalendarShareInvitation, } from '@proton/shared/lib/calendar/sharing/shareProton/shareProton'; import { canonicalizeInternalEmail } from '@proton/shared/lib/helpers/email'; import { CalendarMemberInvitation } from '@proton/shared/lib/interfaces/calendar'; const useCalendarShareInvitationActions = () => { const [addresses] = useAddresses(); const api = useApi(); const { call } = useEventManager(); const getAddressKeys = useGetAddressKeys(); const getEncryptionPreferences = useGetEncryptionPreferences(); const { createNotification } = useNotifications(); const accept = useCallback( async ({ invitation, skipSignatureVerification, onFinish, onError, }: { invitation: CalendarMemberInvitation; skipSignatureVerification?: boolean; onFinish?: () => void; onError: (e: Error) => void; }) => { const { CalendarID: calendarID, Email: invitedEmail, Passphrase: armoredPassphrase, Calendar: { SenderEmail: senderEmail, Name: calendarName }, Signature: armoredSignature, } = invitation; const canonicalizedInvitedEmail = canonicalizeInternalEmail(invitedEmail); const addressID = addresses.find( ({ Email }) => canonicalizeInternalEmail(Email) === canonicalizedInvitedEmail )?.ID; if (!addressID) { const text = 'Own address not found'; createNotification({ type: 'error', text }); throw new Error(text); } try { const accepted = await acceptCalendarShareInvitation({ addressID, calendarID, armoredPassphrase, armoredSignature, senderEmail, getAddressKeys, getEncryptionPreferences, skipSignatureVerification, api: getSilentApi(api), }); createNotification({ type: 'success', text: c('Notification in shared calendar modal').t`Joined ${calendarName} (${senderEmail})`, }); await call(); onFinish?.(); return accepted; } catch (e: any) { if (!(e instanceof Error)) { onError(new Error('Unknown error')); } onError(e); } }, [api, getAddressKeys] ); const reject = useCallback( async ({ invitation, onFinish, onError, }: { invitation: CalendarMemberInvitation; onFinish?: () => void; onError: (e: Error) => void; }) => { const { CalendarID: calendarID, Email: invitedEmail } = invitation; const canonicalizedInvitedEmail = canonicalizeInternalEmail(invitedEmail); const addressID = addresses.find( ({ Email }) => canonicalizeInternalEmail(Email) === canonicalizedInvitedEmail )?.ID; if (!addressID) { const text = 'Own address not found'; createNotification({ type: 'error', text }); throw new Error(text); } if (!addressID) { const text = 'Own address not found'; createNotification({ type: 'error', text }); throw new Error(text); } try { await rejectCalendarShareInvitation({ addressID, calendarID, api: getSilentApi(api), }); createNotification({ type: 'success', text: c('Notification in shared calendar modal').t`Calendar invitation declined`, }); await call(); onFinish?.(); } catch (e: any) { if (!(e instanceof Error)) { onError(new Error('Unknown error')); } onError(e); } }, [api] ); return { accept, reject }; }; export default useCalendarShareInvitationActions;
7,034
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useCalendarShareInvitations.ts
import { useEffect, useState } from 'react'; import { useApi } from '@proton/components/hooks'; import { useLoading } from '@proton/hooks'; import { getAllInvitations } from '@proton/shared/lib/api/calendars'; import { CalendarMemberInvitation } from '@proton/shared/lib/interfaces/calendar'; import noop from '@proton/utils/noop'; const useCalendarShareInvitations = () => { const api = useApi(); const [invitations, setInvitations] = useState<CalendarMemberInvitation[]>([]); const [loading, withLoading] = useLoading(true); useEffect(() => { const run = async () => { try { const { Invitations } = await api<{ Invitations: CalendarMemberInvitation[] }>(getAllInvitations()); setInvitations(Invitations); } catch { // we simply let the API growl noop(); } }; void withLoading(run()); }, []); return { invitations, loading }; }; export default useCalendarShareInvitations;
7,035
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useCalendarUserSettings.ts
import { useCallback } from 'react'; import { CalendarUserSettings as tsCalendarUserSettings } from '@proton/shared/lib/interfaces/calendar'; import { CalendarUserSettingsModel } from '@proton/shared/lib/models/calendarSettingsModel'; import useApi from './useApi'; import useCache from './useCache'; import useCachedModelResult, { getPromiseValue } from './useCachedModelResult'; export const useGetCalendarUserSettings = (): (() => Promise<tsCalendarUserSettings>) => { const api = useApi(); const cache = useCache(); return useCallback(() => { return getPromiseValue(cache, CalendarUserSettingsModel.key, () => CalendarUserSettingsModel.get(api)); }, [cache, api]); }; export const useCalendarUserSettings = (): [tsCalendarUserSettings, boolean, any] => { const cache = useCache(); const miss = useGetCalendarUserSettings(); return useCachedModelResult(cache, CalendarUserSettingsModel.key, miss); };
7,036
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useCalendars.ts
import { useCallback } from 'react'; import { CalendarWithOwnMembers } from '@proton/shared/lib/interfaces/calendar'; import { CalendarsModel } from '@proton/shared/lib/models/calendarsModel'; import useApi from './useApi'; import useCache from './useCache'; import useCachedModelResult, { getPromiseValue } from './useCachedModelResult'; export const useGetCalendars = (): (() => Promise<CalendarWithOwnMembers[] | undefined>) => { const api = useApi(); const cache = useCache(); const miss = useCallback(() => CalendarsModel.get(api), [api]); return useCallback(() => { return getPromiseValue(cache, CalendarsModel.key, miss); }, [cache, miss]); }; export const useCalendars = (): [CalendarWithOwnMembers[] | undefined, boolean, any] => { const cache = useCache(); const miss = useGetCalendars(); return useCachedModelResult(cache, CalendarsModel.key, miss); }; export default useCalendars;
7,037
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useCanReactivateKeys.ts
import { getAllKeysReactivationRequests, getKeysToReactivateCount, } from '../containers/keys/reactivateKeys/getAllKeysToReactive'; import { useAddressesKeys } from './useAddressesKeys'; import useUser from './useUser'; import { useUserKeys } from './useUserKeys'; const useCanReactivateKeys = () => { const [User] = useUser(); const [addressesKeys, loadingAddressesKeys] = useAddressesKeys(); const [userKeys, loadingUserKeys] = useUserKeys(); if (loadingAddressesKeys || loadingUserKeys) { return false; } const allKeysToReactivate = getAllKeysReactivationRequests(addressesKeys, User, userKeys); const numberOfKeysToReactivate = getKeysToReactivateCount(allKeysToReactivate); const { isSubUser } = User; const hasDecryptedUserKeys = userKeys?.length > 0; const canReactivateKeys = !isSubUser && numberOfKeysToReactivate > 0 && hasDecryptedUserKeys; return canReactivateKeys; }; export default useCanReactivateKeys;
7,038
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useCategories.ts
import { useCallback, useMemo } from 'react'; import { LABEL_TYPE } from '@proton/shared/lib/constants'; import { Folder } from '@proton/shared/lib/interfaces/Folder'; import { Label } from '@proton/shared/lib/interfaces/Label'; import { ContactGroup } from '@proton/shared/lib/interfaces/contacts'; import { LabelsModel } from '@proton/shared/lib/models/labelsModel'; import createUseModelHook from './helpers/createModelHook'; import useApi from './useApi'; import useCache from './useCache'; import { getPromiseValue } from './useCachedModelResult'; type Category = Folder & Label & ContactGroup; const useCategories = createUseModelHook<Category[] | undefined>(LabelsModel); const filterCategories = (categories: Category[] | undefined, type: number): Category[] | undefined => { if (!Array.isArray(categories)) { return; } return categories.filter(({ Type }: { Type: number }) => Type === type); }; export const useLabels = (): [Label[] | undefined, boolean] => { const [categories, loading] = useCategories(); const labels = useMemo(() => filterCategories(categories, LABEL_TYPE.MESSAGE_LABEL), [categories]); return [labels, loading]; }; export const useFolders = (): [Folder[] | undefined, boolean] => { const [categories, loading] = useCategories(); const folders = useMemo(() => filterCategories(categories, LABEL_TYPE.MESSAGE_FOLDER), [categories]); return [folders, loading]; }; export const useSystemFolders = (): [Label[] | undefined, boolean] => { const [categories, loading] = useCategories(); const systemFolders = useMemo(() => filterCategories(categories, LABEL_TYPE.SYSTEM_FOLDER), [categories]); return [systemFolders, loading]; }; export const useContactGroups = (): [ContactGroup[] | undefined, boolean] => { const [categories, loading] = useCategories(); const contactGroups = useMemo(() => filterCategories(categories, LABEL_TYPE.CONTACT_GROUP), [categories]); return [contactGroups, loading]; }; const filterContactGroups = (labels: Label[]) => labels.filter(({ Type }) => Type === LABEL_TYPE.CONTACT_GROUP); export const useGetContactGroups = (): (() => Promise<ContactGroup[] | undefined>) => { const api = useApi(); const cache = useCache(); const miss = useCallback(() => LabelsModel.get(api), [api]); return useCallback(() => { return getPromiseValue(cache, LabelsModel.key, miss).then(filterContactGroups); }, [cache, miss]); };
7,039
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useClickOutside.ts
import { RefObject, useEffect } from 'react'; const useClickOutside = (ref: RefObject<HTMLDivElement>, fn: () => void) => { const listener = (e: MouseEvent | TouchEvent) => { if (ref.current && e.target && !ref.current.contains(e.target as Node)) { fn(); } }; useEffect(() => { document.addEventListener('click', listener, { passive: true }); document.addEventListener('touchstart', listener, { passive: true }); return () => { document.removeEventListener('click', listener); document.removeEventListener('touchstart', listener); }; }); }; export default useClickOutside;
7,040
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useConfig.ts
import { useContext } from 'react'; import ConfigContext from '../containers/config/configContext'; const useConfig = () => { return useContext(ConfigContext); }; export default useConfig;
7,041
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useContactEmails.ts
import { useCallback } from 'react'; import { ContactEmail } from '@proton/shared/lib/interfaces/contacts'; import { GetContactEmails } from '@proton/shared/lib/interfaces/hooks/GetContactEmails'; import { ContactEmailsModel } from '@proton/shared/lib/models/contactEmailsModel'; import useApi from './useApi'; import useCache from './useCache'; import useCachedModelResult, { getPromiseValue } from './useCachedModelResult'; export const useGetContactEmails = (): GetContactEmails => { const api = useApi(); const cache = useCache(); const miss = useCallback(() => ContactEmailsModel.get(api), [api]); return useCallback(() => { return getPromiseValue(cache, ContactEmailsModel.key, miss); }, [cache, miss]); }; export const useContactEmails = (): [result: ContactEmail[] | undefined, loading: boolean, error: any] => { const cache = useCache(); const miss = useGetContactEmails(); return useCachedModelResult(cache, ContactEmailsModel.key, miss); }; export default useContactEmails;
7,042
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useContactEmailsSortedByName.ts
import { useMemo } from 'react'; import { ContactEmail } from '@proton/shared/lib/interfaces/contacts/Contact'; import useContactEmails from './useContactEmails'; const compareContactEmailByName = (a: ContactEmail, b: ContactEmail) => { return a.Name.localeCompare(b.Name); }; const useContactEmailsSortedByName = () => { const [contactEmails, loading] = useContactEmails(); return useMemo(() => { return [[...(contactEmails || [])].sort(compareContactEmailByName), loading] as const; }, [contactEmails]); }; export default useContactEmailsSortedByName;
7,043
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useContactFocus.tsx
import { MutableRefObject, useEffect, useRef, useState } from 'react'; import { useHandler } from './index'; export interface ContactFocusContext { elementIDs: string[]; listRef: MutableRefObject<HTMLElement | null>; } export const useContactFocus = ({ elementIDs, listRef }: ContactFocusContext) => { const [focusIndex, setFocusIndex] = useState<number>(); const getFocusedId = () => (focusIndex !== undefined ? elementIDs[focusIndex] : undefined); const focusedIDRef = useRef(getFocusedId()); const handleFocus = useHandler((index) => { setFocusIndex(index); }); const focusOnElementByIndex = (index: number) => { const element = listRef.current?.querySelector( `[data-shortcut-target="contact-container"][data-element-id="${elementIDs[index]}"]` ) as HTMLElement; element?.focus(); }; useEffect(() => { if (focusIndex !== undefined) { focusOnElementByIndex(focusIndex); } focusedIDRef.current = getFocusedId(); }, [focusIndex]); return { focusIndex, getFocusedId, setFocusIndex, handleFocus, }; };
7,044
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useContactHotkeys.tsx
import { useRef } from 'react'; import { HotkeyTuple, useHotkeys } from './index'; export interface ContactHotkeysContext { elementIDs: string[]; focusIndex?: number; } export interface ContactHotkeysHandlers { getFocusedId: () => string | undefined; setFocusIndex: (index?: number) => void; handleElement: (ID: string) => void; } export const useContactHotkeys = ( { elementIDs, focusIndex }: ContactHotkeysContext, { getFocusedId, setFocusIndex, handleElement }: ContactHotkeysHandlers ) => { const elementRef = useRef<HTMLDivElement>(null); const shortcutHandlers: HotkeyTuple[] = [ [ 'ArrowUp', (e) => { e.preventDefault(); const previousIndex = focusIndex !== undefined ? Math.max(0, focusIndex - 1) : elementIDs.length - 1; setFocusIndex(previousIndex); }, ], [ 'ArrowDown', (e) => { e.preventDefault(); const nextIndex = focusIndex !== undefined ? Math.min(elementIDs.length - 1, focusIndex + 1) : 0; setFocusIndex(nextIndex); }, ], [ 'Enter', (e) => { const id = getFocusedId(); const { activeElement } = document; if (id && activeElement?.tagName.toLocaleLowerCase() !== 'button') { e.stopPropagation(); handleElement(id); } }, ], ]; useHotkeys(elementRef, shortcutHandlers); return elementRef; };
7,045
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useContacts.ts
import { useCallback } from 'react'; import { Contact } from '@proton/shared/lib/interfaces/contacts'; import { GetContacts } from '@proton/shared/lib/interfaces/hooks/GetContacts'; import { ContactsModel } from '@proton/shared/lib/models/contactsModel'; import useApi from './useApi'; import useCache from './useCache'; import useCachedModelResult, { getPromiseValue } from './useCachedModelResult'; export const useGetContacts = (): GetContacts => { const api = useApi(); const cache = useCache(); const miss = useCallback(() => ContactsModel.get(api), [api]); return useCallback(() => { return getPromiseValue(cache, ContactsModel.key, miss); }, [cache, miss]); }; export const useContacts = (): [result: Contact[] | undefined, loading: boolean, error: any] => { const cache = useCache(); const miss = useGetContacts(); return useCachedModelResult(cache, ContactsModel.key, miss); }; export default useContacts;
7,046
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useConversationCounts.ts
import { useCallback } from 'react'; import { LabelCount } from '@proton/shared/lib/interfaces/Label'; import { ConversationCountsModel } from '@proton/shared/lib/models/conversationCountsModel'; import useApi from './useApi'; import useCache from './useCache'; import useCachedModelResult, { getPromiseValue } from './useCachedModelResult'; export const useGetConversationCounts = (): (() => Promise<LabelCount[]>) => { const api = useApi(); const cache = useCache(); const miss = useCallback(() => ConversationCountsModel.get(api), [api]); return useCallback(() => { return getPromiseValue(cache, ConversationCountsModel.key, miss); }, [cache, miss]); }; export const useConversationCounts = (): [LabelCount[], boolean, any] => { const cache = useCache(); const miss = useGetConversationCounts(); return useCachedModelResult(cache, ConversationCountsModel.key, miss); };
7,047
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useCookieState.ts
import { useCallback, useState } from 'react'; import { SetCookieArguments, getCookie, setCookie } from '@proton/shared/lib/helpers/cookies'; import { getSecondLevelDomain } from '@proton/shared/lib/helpers/url'; interface Props extends Omit<SetCookieArguments, 'cookieValue'> { cookieValue?: string; } // By default a cookie state is available on all subdomains const useCookieState = ({ cookieName, expirationDate, path = '/', cookieDomain = `.${getSecondLevelDomain(window.location.hostname)}`, }: Props): [string | undefined, (value: string | undefined) => void] => { const [value, setValue] = useState(() => getCookie(cookieName)); const setCookieValue = useCallback( (value: string | undefined) => { setValue(value); setCookie({ cookieName, cookieValue: value, expirationDate, path, cookieDomain, }); }, [setValue] ); return [value, setCookieValue]; }; export default useCookieState;
7,048
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useCyberMondayPeriod.ts
import { useEffect, useState } from 'react'; import { isCyberMonday } from '@proton/shared/lib/helpers/blackfriday'; const EVERY_MINUTE = 60 * 1000; const useCyberMondayPeriod = () => { const [cyberMonday, setCyberMonday] = useState(isCyberMonday()); useEffect(() => { const intervalID = setInterval(() => { setCyberMonday(isCyberMonday()); }, EVERY_MINUTE); return () => { clearInterval(intervalID); }; }, []); return cyberMonday; }; export default useCyberMondayPeriod;
7,049
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useDeviceRecovery.ts
import { useEffect } from 'react'; import { getHasRecoveryMessage, getKeysFromDeviceRecovery, removeDeviceRecovery, storeDeviceRecovery, } from '@proton/shared/lib/recoveryFile/deviceRecovery'; import arraysContainSameElements from '@proton/utils/arraysContainSameElements'; import { FeatureCode } from '../../components/containers/features'; import useApi from './useApi'; import useAuthentication from './useAuthentication'; import useFeature from './useFeature'; import useIsRecoveryFileAvailable from './useIsRecoveryFileAvailable'; import useUser from './useUser'; import { useUserKeys } from './useUserKeys'; import useUserSettings from './useUserSettings'; export const useIsDeviceRecoveryEnabled = () => { const [userSettings] = useUserSettings(); const authentication = useAuthentication(); return userSettings.DeviceRecovery && authentication.getTrusted(); }; export const useIsDeviceRecoveryAvailable = () => { const trustedDeviceRecoveryFeature = useFeature<boolean>(FeatureCode.TrustedDeviceRecovery); const [recoveryFileAvailable, loading] = useIsRecoveryFileAvailable(); return [ recoveryFileAvailable && trustedDeviceRecoveryFeature.feature?.Value, loading || trustedDeviceRecoveryFeature.loading, ]; }; export const useDeviceRecovery = () => { const [userKeys] = useUserKeys(); const [user] = useUser(); const api = useApi(); const [isDeviceRecoveryAvailable] = useIsDeviceRecoveryAvailable(); const isDeviceRecoveryEnabled = useIsDeviceRecoveryEnabled(); const hasRecoveryMessage = getHasRecoveryMessage(user.ID); const privateKeyFingerPrints = userKeys?.map((key) => key.privateKey.getFingerprint()) || []; useEffect(() => { let aborted = false; const run = async () => { const shouldRemoveDeviceRecovery = hasRecoveryMessage && !isDeviceRecoveryEnabled; if (shouldRemoveDeviceRecovery) { removeDeviceRecovery(user.ID); return; } const shouldStoreDeviceRecovery = isDeviceRecoveryAvailable && (isDeviceRecoveryEnabled || hasRecoveryMessage); if (!privateKeyFingerPrints.length || !shouldStoreDeviceRecovery) { return; } const storedKeys = (await getKeysFromDeviceRecovery(user)) || []; if (aborted) { return; } const storedKeyFingerprints = storedKeys.map((key) => key.getFingerprint()); const userKeysHaveUpdated = !arraysContainSameElements(storedKeyFingerprints, privateKeyFingerPrints); if (!userKeysHaveUpdated || aborted) { return; } await storeDeviceRecovery({ api, user, userKeys }); }; void run(); return () => { aborted = true; }; }, [ isDeviceRecoveryAvailable, isDeviceRecoveryEnabled, hasRecoveryMessage, privateKeyFingerPrints.join(''), user.ID, ]); };
7,050
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useDisplayContactsWidget.ts
import { useActiveBreakpoint, useConfig } from '@proton/components/hooks/index'; import { getDisplayContactsInDrawer } from '@proton/shared/lib/drawer/helpers'; const useDisplayContactsWidget = () => { const { isNarrow } = useActiveBreakpoint(); const { APP_NAME } = useConfig(); const displayContactsInDrawer = getDisplayContactsInDrawer(APP_NAME); // We want to display contacts in the header if window is too small to display Drawer return !displayContactsInDrawer || isNarrow; }; export default useDisplayContactsWidget;
7,051
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useDocumentTitle.ts
import { useMemo } from 'react'; const useDocumentTitle = (title?: string) => { // This is explicitly happening in render and not in a useEffect to allow children to override parent titles useMemo(() => { if (title === undefined) { return; } document.title = title; }, [title]); }; export default useDocumentTitle;
7,052
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useDomains.ts
import { Domain, UserModel as tsUserModel } from '@proton/shared/lib/interfaces'; import { UserModel } from '@proton/shared/lib/models'; import { DomainsModel } from '@proton/shared/lib/models/domainsModel'; import useApi from './useApi'; import useCache from './useCache'; import useCachedModelResult from './useCachedModelResult'; const useDomains = (): [Domain[], boolean, Error] => { const cache = useCache(); const api = useApi(); const miss = () => { const user = cache.get(UserModel.key).value as tsUserModel; if (!user.hasPaidMail) { return Promise.resolve([]); } return DomainsModel.get(api); }; return useCachedModelResult(cache, DomainsModel.key, miss); }; export default useDomains;
7,053
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useDomainsAddresses.js
import { queryDomainAddresses } from '@proton/shared/lib/api/domains'; import queryPages from '@proton/shared/lib/api/helpers/queryPages'; import { cachedPromise } from './helpers/cachedPromise'; import useApi from './useApi'; import useCache from './useCache'; import usePromiseResult from './usePromiseResult'; export const getAllDomainAddresses = (api, domainID) => { return queryPages((page, pageSize) => { return api( queryDomainAddresses(domainID, { Page: page, PageSize: pageSize, }) ); }).then((pages) => { return pages.flatMap(({ Addresses = [] }) => Addresses); }); }; const useDomainsAddresses = (domains) => { const cache = useCache(); const api = useApi(); return usePromiseResult(async () => { if (!Array.isArray(domains)) { return; } const domainAddresses = await Promise.all( domains.map((domain) => { return cachedPromise( cache, `${domain.ID}`, () => { return getAllDomainAddresses(api, domain.ID); }, domain ); }) ); return domains.reduce((acc, { ID }, i) => { return { ...acc, [ID]: domainAddresses[i], }; }, {}); }, [domains]); }; export default useDomainsAddresses;
7,054
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useDragMove.ts
import { DragEvent, ReactNode, useEffect, useMemo, useRef } from 'react'; import { createPortal } from 'react-dom'; interface DragMoveContentProps<T> { data?: T; dragging?: boolean; children: ReactNode; } interface UseDragMoveParams { dragging: boolean; setDragging: (value: boolean) => void; format?: string; formatter?: (value: any) => string; } function useDragMove({ dragging, setDragging, format = 'text/plain', formatter = (str) => str }: UseDragMoveParams) { const container = useRef<HTMLDivElement>(); const transferData = useRef<any>(); const handleDragStart = (event: DragEvent<HTMLTableRowElement>) => { if (!container.current) { container.current = document.createElement('div'); container.current.className = 'absolute'; } document.body.appendChild(container.current); event.dataTransfer.setDragImage(container.current, 0, 0); event.dataTransfer.setData(format, formatter(transferData.current)); setDragging(true); }; const handleDragEnd = () => { if (container.current) { document.body.removeChild(container.current); } setDragging(false); }; const DragMoveContent = useMemo( () => function Component<T>({ children, data, dragging }: DragMoveContentProps<T>) { transferData.current = data; useEffect(() => { return () => { transferData.current = undefined; }; }, []); if (dragging && container.current) { return createPortal(children, container.current); } return null; }, [] ); return { dragging, handleDragEnd, handleDragStart, DragMoveContent }; } export default useDragMove;
7,055
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useDragOver.ts
import { DragEvent, DragEventHandler, useState } from 'react'; interface Options { onDragOver?: (event: DragEvent) => void; onDragEnter?: (event: DragEvent) => void; onDragLeave?: (event: DragEvent) => void; onDrop?: (event: DragEvent) => void; } type DragOverReturn = [ dragsOver: boolean, dragHandlers: { onDragEnter: DragEventHandler; onDragLeave: DragEventHandler; onDragOver: DragEventHandler; onDrop: DragEventHandler; } ]; /** * Hooks to manage a dragOver flag * Takes an optional filter function to accept only specific drag content * Returns the flag and the handlers to pass to the element you want to drag on */ const useDragOver = ( dragFilter: (event: DragEvent) => boolean = () => true, dropEffect: 'none' | 'copy' | 'link' | 'move' = 'move', { onDragOver, onDragEnter, onDragLeave, onDrop }: Options = {} ): DragOverReturn => { const [dragOver, setDragOver] = useState(0); const handleDragEnter = (event: DragEvent) => { if (dragFilter(event)) { event.preventDefault(); if (dragOver === 0) { onDragEnter?.(event); } setDragOver(dragOver + 1); } }; const handleDragLeave = (event: DragEvent) => { if (dragFilter(event)) { event.preventDefault(); if (dragOver === 1) { onDragLeave?.(event); } setDragOver(dragOver - 1); } }; const handleDragOver = (event: DragEvent) => { if (dragFilter(event)) { if (event.dataTransfer.effectAllowed === 'all') { event.dataTransfer.dropEffect = dropEffect; } event.preventDefault(); onDragOver?.(event); } }; const handleDrop = (event: DragEvent) => { event.preventDefault(); setDragOver(0); onDrop?.(event); }; return [ dragOver > 0, { onDragEnter: handleDragEnter, onDragLeave: handleDragLeave, onDragOver: handleDragOver, onDrop: handleDrop }, ]; }; export default useDragOver;
7,056
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useDragToScroll.ts
import { MouseEvent as ReactMouseEvent, RefObject, useEffect, useState } from 'react'; /** * This hook will allow any element to be scrolled by dragging it * @param ref * @param defaultCursor */ export function useDragToScroll(ref: RefObject<HTMLElement>, { defaultCursor } = { defaultCursor: 'default' }) { let initialPosition = { scrollTop: 0, scrollLeft: 0, mouseX: 0, mouseY: 0 }; // We check if element is scrollable or not. So we only show the grab if it can be grab const [isScrollable, setIsScrollable] = useState(false); const scrollHeight = ref?.current?.scrollHeight; const clientHeight = ref?.current?.clientHeight; useEffect(() => { if (scrollHeight && clientHeight) { setIsScrollable(scrollHeight > clientHeight); } }, [scrollHeight, clientHeight]); useEffect(() => { if (!ref.current) { return; } ref.current.style.cursor = isScrollable ? 'grab' : defaultCursor; }, [isScrollable]); const handleMouseMove = (event: MouseEvent) => { if (!ref.current) { return; } ref.current.scrollTop = initialPosition.scrollTop - (event.clientY - initialPosition.mouseY); ref.current.scrollLeft = initialPosition.scrollLeft - (event.clientX - initialPosition.mouseX); }; const handleMouseUp = () => { if (ref.current) { ref.current.style.cursor = isScrollable ? 'grab' : defaultCursor; } document.removeEventListener('mousemove', handleMouseMove); document.removeEventListener('mouseup', handleMouseUp); }; const onMouseDown = (event: ReactMouseEvent) => { if (!ref.current || !isScrollable) { return; } // Prevent image default drop event event.preventDefault(); initialPosition = { scrollLeft: ref.current.scrollLeft, scrollTop: ref.current.scrollTop, mouseX: event.clientX, mouseY: event.clientY, }; ref.current.style.cursor = 'grabbing'; ref.current.style.userSelect = 'none'; document.addEventListener('mousemove', handleMouseMove); document.addEventListener('mouseup', handleMouseUp); }; useEffect(() => { document.removeEventListener('mousemove', handleMouseMove); document.removeEventListener('mouseup', handleMouseUp); }, []); return { onMouseDown }; }
7,057
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useDrawerContactFocus.ts
import { RefObject, useEffect, useRef } from 'react'; import { CONTACT_TAB } from '@proton/components/components/drawer/views/DrawerContactView'; import { SelectedDrawerOption } from '@proton/components/components/drawer/views/DrawerView'; const useDrawerParent = (searchInputRef: RefObject<HTMLInputElement>, tab: SelectedDrawerOption) => { const animationEnded = useRef(false); const onFocusSearchInput = () => { searchInputRef?.current?.focus(); animationEnded.current = true; }; // When we switch tab (contact, contact group, setting), we also want to focus the search input useEffect(() => { if (animationEnded.current && tab.value === CONTACT_TAB.CONTACT) { onFocusSearchInput(); } }, [tab]); return { onFocusSearchInput }; }; export default useDrawerParent;
7,058
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useDriveWindowsGASpotlight.tsx
import { MouseEventHandler, useState } from 'react'; import { c } from 'ttag'; import { SpotlightProps } from '@proton/components/components'; import { DRIVE_APP_NAME } from '@proton/shared/lib/constants'; import devicesSpotlightIcon from '@proton/styles/assets/img/drive/computers-spotlight.png'; type DriveWindowsGASpotlightConfig = { placement?: SpotlightProps['originalPlacement']; }; export const useDriveWindowsGASpotlight = ( config: DriveWindowsGASpotlightConfig = {} ): [SpotlightProps, (show: boolean) => void] => { const [show, setShow] = useState<boolean>(true); const stopPropagationOnClose: MouseEventHandler = (e) => { e.preventDefault(); e.stopPropagation(); }; const content = ( <div className="flex flex-nowrap flex-align-items-center my-2"> <div className="flex-item-noshrink mr-4"> <img src={devicesSpotlightIcon} className="w-custom" style={{ '--w-custom': '4em' }} alt="" /> </div> <div> <p className="mt-0 mb-2 text-bold" data-testid="drive:my-devices:spotlight-title"> {c('Link').t`${DRIVE_APP_NAME} Windows app`} </p> <p className="m-0">{c('Link') .t`Seamlessly sync files and folders between your computer and ${DRIVE_APP_NAME}.`}</p> </div> </div> ); return [ { show, content, originalPlacement: config.placement || 'right', size: 'large', onClose: stopPropagationOnClose, }, setShow, ]; };
7,059
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useDropdownArrowNavigation.ts
import { MutableRefObject } from 'react'; import { tabbable } from 'tabbable'; import { HotkeyTuple } from './useHotkeys'; interface Context { rootRef: MutableRefObject<HTMLDivElement | null>; } const useDropdownArrowNavigation = ({ rootRef }: Context) => { const getDropdownMenuItems = () => { if (!rootRef.current) { return []; } return tabbable(rootRef.current, { includeContainer: false }).filter( (elm) => !elm.dataset.preventArrowNavigation ); }; const getFocusIndex = () => getDropdownMenuItems().findIndex((elm) => elm === document.activeElement); const findElementAndFocus = (startingIndex: number) => { const dropdownMenuItems = getDropdownMenuItems(); if (!dropdownMenuItems.length) { return; } const lastIndex = dropdownMenuItems.length - 1; let index = startingIndex; /* loop from last to first item */ if (index > lastIndex) { index = 0; } /* reverse loop from first to last item */ if (index < 0) { index = lastIndex; } const elem = dropdownMenuItems[index] as any; elem.focus(); }; const focusOnFirst = () => { const index = 0; findElementAndFocus(index); }; const focusOnLast = () => { const dropdownMenuItems = getDropdownMenuItems(); const index = dropdownMenuItems.length - 1; findElementAndFocus(index); }; const focusOnPrevious = () => { const focusIndex = getFocusIndex(); findElementAndFocus(focusIndex - 1); }; const focusOnNext = () => { const focusIndex = getFocusIndex(); findElementAndFocus(focusIndex + 1); }; const shortcutHandlers: HotkeyTuple[] = [ [ 'ArrowUp', (e) => { e.preventDefault(); focusOnPrevious(); }, ], [ ['Meta', 'ArrowUp'], (e) => { e.preventDefault(); focusOnFirst(); }, ], [ 'ArrowDown', (e) => { e.preventDefault(); focusOnNext(); }, ], [ ['Meta', 'ArrowDown'], (e) => { e.preventDefault(); focusOnLast(); }, ], ]; return { shortcutHandlers, }; }; export default useDropdownArrowNavigation;
7,060
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useDynamicFavicon.ts
import { useEffect, useRef } from 'react'; import { HTTP_STATUS_CODE } from '@proton/shared/lib/constants'; import useApiStatus from './useApiStatus'; const useDynamicFavicon = (faviconSrc: string) => { const faviconRef = useRef<string>(''); const { offline, apiUnreachable } = useApiStatus(); // We can't rely solely on the Boolean offline because browsers may not catch all offline instances properly. // We will get some false positives with the condition below, but that's ok const isPossiblyOffline = offline || !!apiUnreachable; useEffect( () => { const run = async () => { if (faviconSrc === faviconRef.current) { // no need to update the favicon return; } // Add random param to force refresh const randomParameter = Math.random().toString(36).substring(2); const href = `${faviconSrc}?v=${randomParameter}`; try { /** * Proactively fetch favicon to test if /assets are reachable. * * If that goes well, the request is cached and not launched again below when actually changing the favicon in the HTML * * If that doesn't work, we want to handle the error here since we can't attach an error handled to the link tag that controls the favicon */ const { status } = await fetch(href); if (status !== HTTP_STATUS_CODE.OK) { throw new Error('New favicon was not fetched properly'); } } catch (e) { // if we cannot fetch the favicon, do not attempt to change it return; } // Ensure all favicons are removed, otherwise chrome has trouble updating to the dynamic icon const links = document.querySelectorAll('link[rel="icon"]:not([data-dynamic-favicon])'); links.forEach((link) => { link.remove(); }); const favicon = document.querySelector('link[rel="icon"][type="image/svg+xml"][data-dynamic-favicon]'); if (favicon) { favicon.setAttribute('href', href); } else { const link = document.createElement('link'); link.setAttribute('rel', 'icon'); link.setAttribute('type', 'image/svg+xml'); link.setAttribute('data-dynamic-favicon', ''); link.setAttribute('href', href); document.head.appendChild(link); } faviconRef.current = faviconSrc; }; run(); }, // isPossiblyOffline is a dependency so that we re-try to update the favicon when going offline and back online [faviconSrc, isPossiblyOffline] ); }; export default useDynamicFavicon;
7,061
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useDynamicMonthDay.ts
import { useEffect, useState } from 'react'; import { MINUTE } from '@proton/shared/lib/constants'; interface Props { onChangeMonthDay?: () => void; } const useDynamicMonthDay = ({ onChangeMonthDay }: Props = {}) => { const [monthDay, setMonthDay] = useState(new Date().getDate()); useEffect(() => { onChangeMonthDay?.(); const interval = setInterval(() => { const monthDayNow = new Date().getDate(); if (monthDayNow !== monthDay) { setMonthDay(monthDayNow); } }, MINUTE); return () => { clearInterval(interval); }; }, [monthDay]); return monthDay; }; export default useDynamicMonthDay;
7,062
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useEarlyAccess.ts
import { useLoading } from '@proton/hooks'; import { updateEarlyAccess } from '@proton/shared/lib/api/settings'; import { doesNotSupportEarlyAccessVersion } from '@proton/shared/lib/helpers/browser'; import { deleteCookie, getCookie, setCookie } from '@proton/shared/lib/helpers/cookies'; import { Environment } from '@proton/shared/lib/interfaces'; import { Feature, FeatureCode } from '../containers/features'; import useApi from './useApi'; import useFeature from './useFeature'; import useUserSettings from './useUserSettings'; export const getVersionCookieIsValid = ( versionCookie: Environment | undefined, earlyAccessScope: Feature<Environment> | undefined ) => versionCookie === undefined || earlyAccessScope?.Options?.includes(versionCookie); export const getTargetEnvironment = ( earlyAccessScope: Feature<Environment> | undefined, earlyAccessUserSetting: boolean ): Environment | undefined => { if (!earlyAccessScope || !earlyAccessUserSetting) { return; } return earlyAccessScope.Value; }; export const versionCookieAtLoad = getCookie('Tag') as Environment | undefined; export const updateVersionCookieHelper = ( cookieName: string, environment: Environment | undefined, earlyAccessScopeFeature: Feature<Environment> | undefined ) => { if (environment) { setCookie({ cookieName, cookieValue: environment, expirationDate: 'max', path: '/', }); } /* * if there is a not-allowed cookie already set in the browser, * leave it be, version will not be treated as set by it */ if (!getVersionCookieIsValid(getCookie(cookieName) as Environment | undefined, earlyAccessScopeFeature)) { return; } if (!environment) { deleteCookie(cookieName); } }; export const updateVersionCookie = ( environment: Environment | undefined, earlyAccessScopeFeature: Feature<Environment> | undefined ) => { if (doesNotSupportEarlyAccessVersion()) { return; } updateVersionCookieHelper('Tag', environment, earlyAccessScopeFeature); // If the `Tag` cookie will get deleted, a possibly existing `Version` cookie will get priority over it. // Also delete that cookie (It's not used anymore). deleteCookie('Version'); }; export const deleteVersionCookies = () => { deleteCookie('Version'); deleteCookie('Tag'); }; const useEarlyAccess = () => { const api = useApi(); const earlyAccessScope = useFeature(FeatureCode.EarlyAccessScope); const { feature: { Value: maybeEarlyAccess, DefaultValue } = {} } = earlyAccessScope; const [loadingUpdate, withLoadingUpdate] = useLoading(); const [userSettings, userSettingsLoading] = useUserSettings(); const earlyAccessScopeValue = maybeEarlyAccess || DefaultValue; const hasLoaded = !(userSettingsLoading || earlyAccessScope.loading); /* * Shouldn't be able to call update without the request for the EarlyAccessScope * feature to have completed since the environment is set based on it should * earlyAccessEnabled be true */ const canUpdate = earlyAccessScope.feature && 'Value' in earlyAccessScope.feature; const update = async (earlyAccessEnabled: boolean) => { /* * Can't update the cookie without the request for the EarlyAccessScope * feature to have completed since the environment is set based on it should * earlyAccessEnabled be true */ if (canUpdate) { updateVersionCookie(earlyAccessEnabled ? earlyAccessScopeValue : undefined, earlyAccessScope.feature); } await withLoadingUpdate(api(updateEarlyAccess({ EarlyAccess: Number(earlyAccessEnabled) }))); }; const normalizedVersionCookieAtLoad = getVersionCookieIsValid(versionCookieAtLoad, earlyAccessScope.feature) ? versionCookieAtLoad : undefined; const targetEnvironment = getTargetEnvironment(earlyAccessScope.feature, Boolean(userSettings.EarlyAccess)); const currentEnvironmentMatchesTargetEnvironment = normalizedVersionCookieAtLoad === targetEnvironment; const environmentIsDesynchronized = hasLoaded && !currentEnvironmentMatchesTargetEnvironment; const loading = earlyAccessScope.loading || loadingUpdate; return { value: Boolean(userSettings.EarlyAccess), scope: earlyAccessScopeValue, canUpdate, update, loading, loadingUpdate, environmentIsDesynchronized, targetEnvironment, currentEnvironment: versionCookieAtLoad, }; }; export default useEarlyAccess;
7,063
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useElementBreakpoints.ts
import { RefObject, useEffect, useMemo, useState } from 'react'; const useElementBreakpoints = (ref: RefObject<HTMLElement>, breakpoints: { [key: string]: number }) => { const [breakpoint, setBreakpoint] = useState<string>(); const orderedBreakpoints = useMemo(() => { const entries = Object.entries(breakpoints); return entries.sort((a, b) => b[1] - a[1]); }, [breakpoints]); useEffect(() => { if (!ref.current) { return; } const observer = new ResizeObserver((entries) => { requestAnimationFrame(() => { const width = entries[0].contentRect.width; const breakpoint = orderedBreakpoints.find((breakpoint) => { return breakpoint[1] < width; })?.[0]; setBreakpoint(breakpoint); }); }); observer.observe(ref.current); return () => observer.disconnect(); }, [breakpoints]); return breakpoint; }; export default useElementBreakpoints;
7,064
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useElementRect.ts
import { RefObject, useLayoutEffect, useState } from 'react'; import noop from '@proton/utils/noop'; import throttle from '@proton/utils/throttle'; // Can't loop over DOMRect keys with getOwnPropertyNames. const keys = ['bottom', 'height', 'left', 'right', 'top', 'width', 'x', 'y']; const isEquivalent = (aRect?: DOMRect, bRect?: DOMRect) => { if (!aRect && bRect) { return false; } if (aRect && !bRect) { return false; } for (const key of keys) { if (aRect?.[key as keyof DOMRect] !== bRect?.[key as keyof DOMRect]) { return false; } } return true; }; function getElementRect(target: HTMLElement): DOMRect; function getElementRect(target?: HTMLElement | null) { if (!target) { return; } return target.getBoundingClientRect(); } type RateLimiter = <A extends any[]>(func: (...args: A) => void) => ((...args: A) => void) & { cancel: () => void }; /** * It might be helpful if you have `ResizeObserver loop limit exceeded` error. * The error can also manifest itself as `ResizeObserver loop completed with undelivered notifications.` * * Simply toss it as the second argument: * * ```typescript * * const elementRect = useElementRect(ref, requestAnimationFrameRateLimiter); * * ``` */ export const requestAnimationFrameRateLimiter: RateLimiter = <A extends any[]>(func: (...args: A) => void) => { const cb = (...args: A) => requestAnimationFrame(() => func(...args)); cb.cancel = noop; return cb; }; export const equivalentReducer = (oldRect?: DOMRect, newRect?: DOMRect) => { return isEquivalent(oldRect, newRect) ? oldRect : newRect; }; export const createObserver = ( target: HTMLElement, onResize: (rect: DOMRect) => void, maybeRateLimiter?: RateLimiter | null ) => { if (maybeRateLimiter === undefined) { maybeRateLimiter = (cb) => throttle(cb, 16, { leading: true, trailing: true }); } let cache = {} as DOMRect; const handleResizeCallback = (rect: DOMRect) => { if (isEquivalent(cache, rect)) { return; } cache = rect; onResize(rect); }; handleResizeCallback.cancel = noop; const handleResize = maybeRateLimiter ? maybeRateLimiter(handleResizeCallback) : handleResizeCallback; const handleResizeObserver = () => { handleResize(getElementRect(target)); }; const resizeObserver = new ResizeObserver(handleResizeObserver); resizeObserver.observe(target, { box: 'border-box' }); handleResizeObserver(); return () => { handleResize?.cancel?.(); resizeObserver.disconnect(); }; }; const useElementRect = <E extends HTMLElement>(ref: RefObject<E> | null, maybeRateLimiter?: RateLimiter | null) => { const [elementRect, setElementRect] = useState<DOMRect | null>(null); useLayoutEffect(() => { const target = ref?.current; if (!target) { return; } return createObserver( target, (rect: DOMRect) => { setElementRect(rect); }, maybeRateLimiter ); }, [ref, ref?.current]); return elementRect; }; export default useElementRect;
7,065
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useErrorHandler.ts
import { useCallback } from 'react'; import { c } from 'ttag'; import { getApiErrorMessage, getIsUnreachableError } from '@proton/shared/lib/api/helpers/apiErrorHelper'; import { traceError } from '@proton/shared/lib/helpers/sentry'; import useNotifications from './useNotifications'; const ignoreErrors = ['InactiveSession', 'AppVersionBadError', 'OfflineError', 'AbortError']; const useErrorHandler = () => { const { createNotification } = useNotifications(); return useCallback((error: any, { notify = true, trace = true }: { notify?: boolean; trace?: boolean } = {}) => { if (!error) { return; } const apiErrorMessage = getApiErrorMessage(error); const errorMessage = error.message || c('Error').t`Unknown error`; // Bad app version and unreachable errors are handled in a top banner const shouldNotify = notify && !error.cancel && !ignoreErrors.includes(error.name) && !getIsUnreachableError(error); if (shouldNotify) { createNotification({ type: 'error', text: apiErrorMessage || errorMessage }); } const shouldTrace = trace && error.trace !== false && !apiErrorMessage; if (shouldTrace) { traceError(error); } }, []); }; export default useErrorHandler;
7,066
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useEventManager.ts
import { useContext } from 'react'; import Context from '../containers/eventManager/context'; function useEventManager() { const eventManager = useContext(Context); if (!eventManager) { throw new Error('Trying to use uninitialized EventManagerContext'); } return eventManager; } export default useEventManager;
7,067
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useExperiment.ts
import { useContext, useEffect } from 'react'; import ExperimentsContext, { ExperimentCode } from '../containers/experiments/ExperimentsContext'; import { DEFAULT_EXPERIMENT_VALUE } from '../containers/experiments/ExperimentsProvider'; const useExperiment = (code: ExperimentCode, trigger = true) => { const { experiments, loading, initialize } = useContext(ExperimentsContext); useEffect(() => { if (trigger) { void initialize(); } }, [trigger]); return { value: experiments[code] || DEFAULT_EXPERIMENT_VALUE, loading: !!loading, }; }; export default useExperiment;
7,068
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useFeature.ts
import { FeatureCode, FeatureContextValue } from '../containers'; import useFeatures from './useFeatures'; const useFeature = <FeatureValue = any>(code: FeatureCode, prefetch = true) => { // Forcing type, not sure how to type a generic array const { featuresFlags } = useFeatures([code], prefetch); return featuresFlags[0] as FeatureContextValue<FeatureValue>; }; export default useFeature;
7,069
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useFeatures.ts
import { useContext, useEffect, useMemo } from 'react'; import noop from '@proton/utils/noop'; import { FeatureCode, FeatureContextValue, FeaturesContext } from '../containers/features'; const useFeatures = <Flags extends FeatureCode>(codes: Flags[], prefetch = true) => { const { features, loading, get, put, enqueue } = useContext(FeaturesContext); useMemo(() => { // Features are queued up during render to gather possible feature codes from // children and merge them together with feature codes from parents enqueue(codes); }, codes); useEffect(() => { if (prefetch) { get(codes).catch(noop); } }, codes); const featuresFlags = codes.map((code): FeatureContextValue => { return { get: () => get([code]).then(([result]) => result), update: (value) => put(code, value), feature: features[code], loading: loading[code] === undefined || !!loading[code], code, }; }); type CodeType = (typeof codes)[number]; const getFeature = <T extends CodeType>(code: T) => { const feature = featuresFlags.find((feature) => feature.code === code); if (!feature) { throw new Error('Feature not present in codes'); } return feature; }; return { featuresFlags, getFeature }; }; export default useFeatures;
7,070
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useFilters.js
import { FiltersModel } from '@proton/shared/lib/models/filtersModel'; import createUseModelHook from './helpers/createModelHook'; export default createUseModelHook(FiltersModel);
7,071
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useFolderColor.test.ts
import { Folder } from '@proton/shared/lib/interfaces/Folder'; import { FOLDER_COLOR, INHERIT_PARENT_FOLDER_COLOR } from '@proton/shared/lib/mail/mailSettings'; import useFolderColor from './useFolderColor'; import { useMailSettings } from './useMailSettings'; const mockFolderSetting = FOLDER_COLOR.ENABLED; const mockinheritSetting = INHERIT_PARENT_FOLDER_COLOR.ENABLED; jest.mock('./useMailSettings', () => ({ useMailSettings: jest.fn(() => [ { EnableFolderColor: mockFolderSetting, InheritParentFolderColor: mockinheritSetting }, false, ]), })); jest.mock('./useCategories', () => ({ useFolders: () => [ [ { ID: 'A', Color: 'red' }, { ID: 'B', Color: 'blue', ParentID: 'A' }, { ID: 'C', Color: 'green', ParentID: 'B' }, ], false, ], })); describe('useFolderColor hook', () => { it('should not return color if EnableFolderColor is disabled', () => { (useMailSettings as jest.Mock).mockReturnValueOnce([ { EnableFolderColor: FOLDER_COLOR.DISABLED, InheritParentFolderColor: INHERIT_PARENT_FOLDER_COLOR.ENABLED }, false, ]); const folder = { ID: 'C', Color: 'green' } as Folder; const color = useFolderColor(folder); expect(color).toBe(undefined); }); it('should return current color if InheritParentFolderColor is disabled', () => { (useMailSettings as jest.Mock).mockReturnValueOnce([ { EnableFolderColor: FOLDER_COLOR.ENABLED, InheritParentFolderColor: INHERIT_PARENT_FOLDER_COLOR.DISABLED }, false, ]); const folder = { ID: 'C', Color: 'green', ParentID: 'B' } as Folder; const color = useFolderColor(folder); expect(color).toBe('green'); }); it('should return current folder color since it is a root', () => { const folder = { ID: 'C', Color: 'green' } as Folder; const color = useFolderColor(folder); expect(color).toBe('green'); }); it('should search for root folder color', () => { const folder = { ID: 'C', Color: 'green', ParentID: 'B' } as Folder; const color = useFolderColor(folder); expect(color).toBe('red'); }); });
7,072
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useFolderColor.ts
import { toMap } from '@proton/shared/lib/helpers/object'; import { Folder } from '@proton/shared/lib/interfaces/Folder'; import { useFolders } from './useCategories'; import { useMailSettings } from './useMailSettings'; const useFolderColor = (folder: Folder) => { const [folders] = useFolders(); const [mailSettings] = useMailSettings(); if (!mailSettings?.EnableFolderColor) { return undefined; } if (!mailSettings?.InheritParentFolderColor) { return folder.Color; } const folderMap = toMap(folders); const getParentFolderColor = ({ ParentID, Color }: Folder): string | undefined => { // ParentID is undefined for root folder if (!ParentID) { return Color; } const folder = folderMap[ParentID]; if (folder) { return getParentFolderColor(folder); } return undefined; }; return getParentFolderColor(folder); }; export default useFolderColor;
7,073
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useForceRefresh.ts
import { useContext } from 'react'; import Context from '../containers/forceRefresh/context'; const useForceRefresh = () => { return useContext(Context); }; export default useForceRefresh;
7,074
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useGetAddressKeys.ts
import { useCallback } from 'react'; import { DecryptedAddressKey } from '@proton/shared/lib/interfaces'; import { GetAddressKeys } from '@proton/shared/lib/interfaces/hooks/GetAddressKeys'; import { getDecryptedAddressKeysHelper } from '@proton/shared/lib/keys'; import { useGetAddresses } from './useAddresses'; import useAuthentication from './useAuthentication'; import useCache from './useCache'; import { getPromiseValue } from './useCachedModelResult'; import { useGetUser } from './useUser'; import { useGetUserKeys } from './useUserKeys'; export const CACHE_KEY = 'ADDRESS_KEYS'; export const useGetAddressKeysRaw = (): ((id: string) => Promise<DecryptedAddressKey[]>) => { const authentication = useAuthentication(); const getUser = useGetUser(); const getAddresses = useGetAddresses(); const getUserKeys = useGetUserKeys(); return useCallback( async (addressID) => { const [user, userKeys, addresses] = await Promise.all([getUser(), getUserKeys(), getAddresses()]); const address = addresses.find(({ ID: AddressID }) => AddressID === addressID); if (!address) { return []; } return getDecryptedAddressKeysHelper(address.Keys, user, userKeys, authentication.getPassword()); }, [getUser, getAddresses, getUserKeys] ); }; export const useGetAddressKeys = (): GetAddressKeys => { const cache = useCache(); const miss = useGetAddressKeysRaw(); return useCallback( (key) => { if (!cache.has(CACHE_KEY)) { cache.set(CACHE_KEY, new Map()); } const subCache = cache.get(CACHE_KEY); return getPromiseValue(subCache, key, miss); }, [cache, miss] ); }; export default useGetAddressKeys;
7,075
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useGetCalendarBootstrap.ts
import { useCallback } from 'react'; import { getFullCalendar } from '@proton/shared/lib/api/calendars'; import createCache from '@proton/shared/lib/helpers/cache'; import { STATUS } from '@proton/shared/lib/models/cache'; import useApi from './useApi'; import useCache from './useCache'; import useCachedModelResult, { getPromiseValue } from './useCachedModelResult'; export const KEY = 'CALENDAR_BOOTSTRAP'; export const useGetCalendarBootstrap = () => { const api = useApi(); const cache = useCache(); const miss = useCallback( (calendarID: string) => { if (!calendarID) { return Promise.resolve(); } return api(getFullCalendar(calendarID)); }, [api] ); return useCallback( (calendarID: string) => { if (!cache.has(KEY)) { cache.set(KEY, createCache()); } return getPromiseValue(cache.get(KEY), calendarID, miss); }, [cache, miss] ); }; export const useReadCalendarBootstrap = () => { const cache = useCache(); return useCallback( (calendarID: string) => { if (!cache.has(KEY)) { cache.set(KEY, createCache()); } const oldRecord = cache.get(KEY).get(calendarID); if (!oldRecord || oldRecord.status !== STATUS.RESOLVED) { return; } return oldRecord.value; }, [cache] ); }; export const useCalendarBootstrap = (calendarID?: string) => { const cache = useCache(); const getCalendarBootstrap = useGetCalendarBootstrap(); if (!cache.has(KEY)) { cache.set(KEY, createCache()); } return useCachedModelResult(cache.get(KEY), calendarID, getCalendarBootstrap); }; export default useGetCalendarBootstrap;
7,076
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useGetCalendarEventRaw.ts
import { useCallback } from 'react'; import { getIsAutoAddedInvite } from '@proton/shared/lib/calendar/apiModels'; import { getAuthorPublicKeysMap, withNormalizedAuthors } from '@proton/shared/lib/calendar/author'; import { getCalendarEventDecryptionKeys } from '@proton/shared/lib/calendar/crypto/keys/helpers'; import { readCalendarEvent, readSessionKeys } from '@proton/shared/lib/calendar/deserialize'; import { SimpleMap } from '@proton/shared/lib/interfaces'; import { CalendarEvent } from '@proton/shared/lib/interfaces/calendar'; import { ContactEmail } from '@proton/shared/lib/interfaces/contacts'; import { GetCalendarEventRaw } from '@proton/shared/lib/interfaces/hooks/GetCalendarEventRaw'; import { useGetAddresses } from './useAddresses'; import { useGetAddressKeys } from './useGetAddressKeys'; import { useGetCalendarBootstrap } from './useGetCalendarBootstrap'; import { useGetCalendarKeys } from './useGetDecryptedPassphraseAndCalendarKeys'; import useGetVerificationPreferences from './useGetVerificationPreferences'; const useGetCalendarEventRaw = (contactEmailsMap: SimpleMap<ContactEmail>): GetCalendarEventRaw => { const getCalendarKeys = useGetCalendarKeys(); const getCalendarBootstrap = useGetCalendarBootstrap(); const getAddresses = useGetAddresses(); const getAddressKeys = useGetAddressKeys(); const getVerificationPreferences = useGetVerificationPreferences(); return useCallback( async (Event: CalendarEvent) => { const { CalendarID, ID, SharedEvents, CalendarEvents, AttendeesEvents, Attendees, Notifications, FullDay } = Event; const encryptingAddressID = getIsAutoAddedInvite(Event) ? Event.AddressID : undefined; const addresses = await getAddresses(); const [privateKeys, publicKeysMap, { CalendarSettings: calendarSettings }] = await Promise.all([ getCalendarEventDecryptionKeys({ calendarEvent: Event, getAddressKeys, getCalendarKeys }), getAuthorPublicKeysMap({ event: Event, addresses, getAddressKeys, getVerificationPreferences, contactEmailsMap, }), getCalendarBootstrap(CalendarID), ]); const [sharedSessionKey, calendarSessionKey] = await readSessionKeys({ calendarEvent: Event, privateKeys, }); return readCalendarEvent({ event: { SharedEvents: withNormalizedAuthors(SharedEvents), CalendarEvents: withNormalizedAuthors(CalendarEvents), AttendeesEvents: withNormalizedAuthors(AttendeesEvents), Attendees, Notifications, FullDay, CalendarID, ID, }, publicKeysMap, sharedSessionKey, calendarSessionKey, calendarSettings, addresses, encryptingAddressID, }); }, [getAddresses, getAddressKeys, getCalendarKeys, contactEmailsMap] ); }; export default useGetCalendarEventRaw;
7,077
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useGetCalendarInfo.ts
import { useCallback } from 'react'; import { getMemberAndAddress } from '@proton/shared/lib/calendar/members'; import { GetCalendarInfo } from '@proton/shared/lib/interfaces/hooks/GetCalendarInfo'; import { useGetAddresses } from './useAddresses'; import { useGetAddressKeys } from './useGetAddressKeys'; import { useGetCalendarBootstrap } from './useGetCalendarBootstrap'; import { useGetDecryptedPassphraseAndCalendarKeys } from './useGetDecryptedPassphraseAndCalendarKeys'; export const useGetCalendarInfo = (): GetCalendarInfo => { const getCalendarBootstrap = useGetCalendarBootstrap(); const getAddresses = useGetAddresses(); const getDecryptedPassphraseAndCalendarKeys = useGetDecryptedPassphraseAndCalendarKeys(); const getAddressKeys = useGetAddressKeys(); return useCallback( async (calendarID: string) => { const [{ Members, CalendarSettings: calendarSettings }, Addresses] = await Promise.all([ getCalendarBootstrap(calendarID), getAddresses(), ]); const [{ ID: memberID }, { ID: addressID }] = getMemberAndAddress(Addresses, Members); const [{ decryptedCalendarKeys, decryptedPassphrase, passphraseID }, addressKeys] = await Promise.all([ getDecryptedPassphraseAndCalendarKeys(calendarID), getAddressKeys(addressID), ]); return { memberID, addressID, addressKeys, calendarKeys: decryptedCalendarKeys, calendarSettings, passphrase: decryptedPassphrase, passphraseID, }; }, [getCalendarBootstrap, getAddresses, getDecryptedPassphraseAndCalendarKeys, getAddressKeys] ); }; export default useGetCalendarInfo;
7,078
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useGetCalendarPublicLinks.ts
import { useCallback } from 'react'; import { getPublicLinks } from '@proton/shared/lib/api/calendars'; import createCache from '@proton/shared/lib/helpers/cache'; import { CalendarUrlsResponse } from '@proton/shared/lib/interfaces/calendar'; import useApi from './useApi'; import useCache from './useCache'; import { getPromiseValue } from './useCachedModelResult'; export const KEY = 'CALENDAR_PUBLIC_LINKS'; export const useGetCalendarPublicLinks = () => { const api = useApi(); const cache = useCache(); const miss = useCallback( (calendarID: string) => { if (!calendarID) { return Promise.resolve(); } return api<CalendarUrlsResponse>(getPublicLinks(calendarID)); }, [api] ); return useCallback( (calendarID: string) => { if (!cache.has(KEY)) { cache.set(KEY, createCache()); } return getPromiseValue(cache.get(KEY), calendarID, miss); }, [cache, miss] ); };
7,079
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useGetCanonicalEmailsMap.ts
import { useCallback } from 'react'; import { getCanonicalAddresses } from '@proton/shared/lib/api/addresses'; import { API_CODES, GET_CANONICAL_EMAILS_API_LIMIT } from '@proton/shared/lib/constants'; import { GetCanonicalAddressesApiResponse } from '@proton/shared/lib/interfaces/calendar'; import { GetCanonicalEmailsMap } from '@proton/shared/lib/interfaces/hooks/GetCanonicalEmailsMap'; import { SimpleMap } from '@proton/shared/lib/interfaces/utils'; import chunk from '@proton/utils/chunk'; import useApi from './useApi'; import useCache from './useCache'; import { getIsRecordInvalid, getPromiseValue } from './useCachedModelResult'; const CACHE_KEY = 'CANONICAL_EMAILS'; export const useGetCanonicalEmailsMap = () => { const api = useApi(); const cache = useCache(); const getCanonicalEmailsMap = useCallback( async (emails: string[]): Promise<SimpleMap<string>> => { if (!emails.length) { return Promise.resolve({}); } const encodedEmails = emails.map((email) => encodeURIComponent(email)); const batchedEmails = chunk(encodedEmails, GET_CANONICAL_EMAILS_API_LIMIT); const maps = await Promise.all( batchedEmails.map(async (batch) => { const { Responses, Code } = await api<GetCanonicalAddressesApiResponse>( getCanonicalAddresses(batch) ); if (Code !== API_CODES.GLOBAL_SUCCESS) { throw new Error('Canonicalize operation failed'); } return Responses.reduce<SimpleMap<string>>((acc, { Email, Response: { CanonicalEmail } }) => { acc[Email] = CanonicalEmail; return acc; }, {}); }) ); return maps.reduce<SimpleMap<string>>((acc, curr) => ({ ...acc, ...curr }), {}); }, [api, cache] ); return useCallback<GetCanonicalEmailsMap>( (emails: string[]) => { if (!cache.has(CACHE_KEY)) { cache.set(CACHE_KEY, new Map()); } const subCache = cache.get(CACHE_KEY); const missing = emails.filter((email) => { return getIsRecordInvalid(subCache.get(email)); }); const promise = getCanonicalEmailsMap(missing); const miss = async (tzid: string) => { const map = await promise; return map[tzid]; }; return Promise.all( emails.map(async (email) => { const result = await getPromiseValue(subCache, email, miss); return { email, result: result as string, }; }) ).then((result) => { return result.reduce<SimpleMap<string>>((acc, { email, result }) => { acc[email] = result; return acc; }, {}); }); }, [cache, getCanonicalEmailsMap] ); };
7,080
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useGetDecryptedPassphraseAndCalendarKeys.ts
import { useCallback } from 'react'; import { decryptPassphrase, decryptPassphraseSessionKey, getDecryptedCalendarKeys, } from '@proton/shared/lib/calendar/crypto/keys/calendarKeys'; import { getAddressesMembersMap } from '@proton/shared/lib/calendar/crypto/keys/helpers'; import { Address } from '@proton/shared/lib/interfaces'; import { MemberPassphrase } from '@proton/shared/lib/interfaces/calendar'; import { GetAddressKeys } from '@proton/shared/lib/interfaces/hooks/GetAddressKeys'; import { GetDecryptedPassphraseAndCalendarKeys } from '@proton/shared/lib/interfaces/hooks/GetDecryptedPassphraseAndCalendarKeys'; import { splitKeys } from '@proton/shared/lib/keys'; import noop from '@proton/utils/noop'; import { useGetAddresses } from './useAddresses'; import useCache from './useCache'; import { getPromiseValue } from './useCachedModelResult'; import { useGetAddressKeys } from './useGetAddressKeys'; import { useGetCalendarBootstrap } from './useGetCalendarBootstrap'; export const CACHE_KEY = 'CALENDAR_KEYS'; const getCalendarKeyPassphrase = async ( getAddressKeys: GetAddressKeys, MemberPassphrases: MemberPassphrase[] = [], addressesMembersMap: { [key: string]: Address } = {} ) => { // Try to decrypt each passphrase with the address keys belonging to that member until it succeeds. for (const { Passphrase, Signature, MemberID } of MemberPassphrases) { const Address = addressesMembersMap[MemberID]; if (!Address) { continue; } const addressKeys = await getAddressKeys(Address.ID); const [decryptedPassphrase, decryptedPassphraseSessionKey] = await Promise.all([ decryptPassphrase({ armoredPassphrase: Passphrase, armoredSignature: Signature, ...splitKeys(addressKeys), }).catch(noop), decryptPassphraseSessionKey({ armoredPassphrase: Passphrase, ...splitKeys(addressKeys) }), ]); if (!decryptedPassphrase || !decryptedPassphraseSessionKey) { throw new Error('Error decrypting calendar passphrase'); } return { decryptedPassphrase, decryptedPassphraseSessionKey }; } return {}; }; const useGetDecryptedPassphraseAndCalendarKeysRaw = () => { const getAddresses = useGetAddresses(); const getAddressKeys = useGetAddressKeys(); const getCalendarBootstrap = useGetCalendarBootstrap(); return useCallback( async (calendarID) => { const [{ Keys = [], Passphrase = {}, Members = [] }, Addresses = []] = await Promise.all([ getCalendarBootstrap(calendarID), getAddresses(), ]); const { ID: PassphraseID, MemberPassphrases } = Passphrase; const addressesMembersMap = getAddressesMembersMap(Members, Addresses); const { decryptedPassphrase, decryptedPassphraseSessionKey } = await getCalendarKeyPassphrase( getAddressKeys, MemberPassphrases, addressesMembersMap ); if (!decryptedPassphrase || !decryptedPassphraseSessionKey) { throw new Error('No passphrase'); } return { decryptedCalendarKeys: await getDecryptedCalendarKeys(Keys, { [PassphraseID]: decryptedPassphrase }), decryptedPassphrase, decryptedPassphraseSessionKey, passphraseID: PassphraseID, }; }, [getAddresses, getAddressKeys, getCalendarBootstrap] ); }; export const useGetDecryptedPassphraseAndCalendarKeys = (): GetDecryptedPassphraseAndCalendarKeys => { const cache = useCache(); const miss = useGetDecryptedPassphraseAndCalendarKeysRaw(); return useCallback( (calendarID: string) => { if (!cache.has(CACHE_KEY)) { cache.set(CACHE_KEY, new Map()); } const subCache = cache.get(CACHE_KEY); return getPromiseValue(subCache, calendarID, miss); }, [cache, miss] ); }; export const useGetCalendarKeys = () => { const getDecryptedPassphraseAndCalendarKeys = useGetDecryptedPassphraseAndCalendarKeys(); return useCallback( async (calendarID: string) => { const { decryptedCalendarKeys } = await getDecryptedPassphraseAndCalendarKeys(calendarID); return decryptedCalendarKeys; }, [getDecryptedPassphraseAndCalendarKeys] ); };
7,081
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useGetEncryptionPreferences.ts
import { useCallback } from 'react'; import getPublicKeysVcardHelper from '@proton/shared/lib/api/helpers/getPublicKeysVcardHelper'; import { MINUTE, RECIPIENT_TYPES } from '@proton/shared/lib/constants'; import { getSelfSendAddresses } from '@proton/shared/lib/helpers/address'; import { canonicalizeEmail, canonicalizeInternalEmail } from '@proton/shared/lib/helpers/email'; import { KT_VERIFICATION_STATUS } from '@proton/shared/lib/interfaces'; import { GetEncryptionPreferences } from '@proton/shared/lib/interfaces/hooks/GetEncryptionPreferences'; import { getKeyHasFlagsToEncrypt } from '@proton/shared/lib/keys'; import { getActiveKeys } from '@proton/shared/lib/keys/getActiveKeys'; import { splitKeys } from '@proton/shared/lib/keys/keys'; import { getContactPublicKeyModel, getKeyEncryptionCapableStatus } from '@proton/shared/lib/keys/publicKeys'; import extractEncryptionPreferences from '@proton/shared/lib/mail/encryptionPreferences'; import { useGetAddresses } from './useAddresses'; import useApi from './useApi'; import useCache from './useCache'; import { getPromiseValue } from './useCachedModelResult'; import { useGetAddressKeys } from './useGetAddressKeys'; import useGetPublicKeysForInbox from './useGetPublicKeysForInbox'; import { useGetMailSettings } from './useMailSettings'; import { useGetUserKeys } from './useUserKeys'; export const CACHE_KEY = 'ENCRYPTION_PREFERENCES'; const DEFAULT_LIFETIME = 5 * MINUTE; /** * Given an email address and the user mail settings, return the encryption preferences for sending to that email. * The logic for how those preferences are determined is laid out in the * Confluence document 'Encryption preferences for outgoing email'. * NB: the current logic does not handle internal address keys belonging to external accounts, since these keys are not used by Inbox. */ const useGetEncryptionPreferences = () => { const api = useApi(); const cache = useCache(); const getAddresses = useGetAddresses(); const getUserKeys = useGetUserKeys(); const getAddressKeys = useGetAddressKeys(); const getPublicKeysForInbox = useGetPublicKeysForInbox(); const getMailSettings = useGetMailSettings(); const getEncryptionPreferences = useCallback<GetEncryptionPreferences>( async ({ email, lifetime, contactEmailsMap, intendedForEmail = true }) => { const [addresses, mailSettings] = await Promise.all([getAddresses(), getMailSettings()]); const canonicalEmail = canonicalizeInternalEmail(email); const selfAddress = getSelfSendAddresses(addresses).find( ({ Email }) => canonicalizeInternalEmail(Email) === canonicalEmail ); let selfSend; let apiKeysConfig; let pinnedKeysConfig; if (selfAddress) { // we do not trust the public keys in ownAddress (they will be deprecated in the API response soon anyway) const selfAddressKeys = await getAddressKeys(selfAddress.ID); const primaryAddressKey = ( await getActiveKeys(selfAddress, selfAddress.SignedKeyList, selfAddress.Keys, selfAddressKeys) )[0]; const selfPublicKey = primaryAddressKey?.publicKey; const canEncrypt = selfPublicKey ? await getKeyEncryptionCapableStatus(selfPublicKey) : undefined; const canSend = canEncrypt && getKeyHasFlagsToEncrypt(primaryAddressKey.flags); selfSend = { address: selfAddress, publicKey: selfPublicKey, canSend }; // For own addresses, we use the decrypted keys in selfSend and do not fetch any data from the API apiKeysConfig = { publicKeys: [], RecipientType: RECIPIENT_TYPES.TYPE_INTERNAL, ktVerificationResult: { status: KT_VERIFICATION_STATUS.VERIFIED_KEYS }, }; pinnedKeysConfig = { pinnedKeys: [], isContact: false }; } else { const { publicKeys } = splitKeys(await getUserKeys()); apiKeysConfig = await getPublicKeysForInbox({ email, internalKeysOnly: intendedForEmail === false, includeInternalKeysWithE2EEDisabledForMail: intendedForEmail === false, lifetime, noCache: !lifetime, }); const isInternal = apiKeysConfig.RecipientType === RECIPIENT_TYPES.TYPE_INTERNAL; pinnedKeysConfig = await getPublicKeysVcardHelper(api, email, publicKeys, isInternal, contactEmailsMap); } const publicKeyModel = await getContactPublicKeyModel({ emailAddress: email, apiKeysConfig, pinnedKeysConfig, }); return extractEncryptionPreferences(publicKeyModel, mailSettings, selfSend); }, [api, getAddressKeys, getAddresses, getPublicKeysForInbox, getMailSettings] ); return useCallback<GetEncryptionPreferences>( ({ email, lifetime = DEFAULT_LIFETIME, contactEmailsMap, intendedForEmail }) => { if (!cache.has(CACHE_KEY)) { cache.set(CACHE_KEY, new Map()); } const subCache = cache.get(CACHE_KEY); // By normalizing email here, we consider that it could not exist different encryption preferences // For 2 addresses identical but for the cases. // If a provider does different one day, this would have to evolve. const canonicalEmail = canonicalizeEmail(email); const miss = () => getEncryptionPreferences({ email: canonicalEmail, intendedForEmail, lifetime, contactEmailsMap, }); return getPromiseValue(subCache, canonicalEmail, miss, lifetime); }, [cache, getEncryptionPreferences] ); }; export default useGetEncryptionPreferences;
7,082
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useGetOrganizationKeyRaw.ts
import { useCallback } from 'react'; import { getOrganizationKeys } from '@proton/shared/lib/api/organization'; import { OrganizationKey } from '@proton/shared/lib/interfaces'; import { getCachedOrganizationKey } from '@proton/shared/lib/keys'; import useApi from './useApi'; import useAuthentication from './useAuthentication'; export const useGetOrganizationKeyRaw = () => { const authentication = useAuthentication(); const api = useApi(); return useCallback(async () => { const Key = await api<OrganizationKey>(getOrganizationKeys()); return getCachedOrganizationKey({ keyPassword: authentication.getPassword(), Key }); }, []); }; export default useGetOrganizationKeyRaw;
7,083
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useGetPublicKeysForInbox.ts
import { useCallback } from 'react'; import getPublicKeysEmailHelper from '@proton/shared/lib/api/helpers/getPublicKeysEmailHelper'; import { MINUTE } from '@proton/shared/lib/constants'; import { GetPublicKeysForInbox } from '@proton/shared/lib/interfaces/hooks/GetPublicKeysForInbox'; import { useKeyTransparencyContext } from '../containers/keyTransparency'; import useApi from './useApi'; import useCache from './useCache'; import { getPromiseValue } from './useCachedModelResult'; export const CACHE_KEY = 'PUBLIC_KEYS'; const DEFAULT_LIFETIME = 30 * MINUTE; /** * Get public keys valid in the context of Inbox apps. * In particular, internal address keys from external accounts are not returned. */ export const useGetPublicKeysForInbox = () => { const cache = useCache(); const api = useApi(); const { verifyOutboundPublicKeys, ktActivation } = useKeyTransparencyContext(); return useCallback<GetPublicKeysForInbox>( ({ email, lifetime = DEFAULT_LIFETIME, noCache = false, internalKeysOnly, includeInternalKeysWithE2EEDisabledForMail, }) => { if (!cache.has(CACHE_KEY)) { cache.set(CACHE_KEY, new Map()); } const subCache = cache.get(CACHE_KEY); const miss = () => getPublicKeysEmailHelper({ email, internalKeysOnly, includeInternalKeysWithE2EEDisabledForMail, api, ktActivation, verifyOutboundPublicKeys, silence: true, noCache, }); const cacheEntryID = `${email},${ktActivation},${internalKeysOnly},${includeInternalKeysWithE2EEDisabledForMail}`; return getPromiseValue(subCache, cacheEntryID, miss, lifetime); }, [api, cache, ktActivation] ); }; export default useGetPublicKeysForInbox;
7,084
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useGetUserKeysRaw.ts
import { useCallback } from 'react'; import { getDecryptedUserKeys, getDecryptedUserKeysHelper } from '@proton/shared/lib/keys'; import useAuthentication from './useAuthentication'; import { useGetUser } from './useUser'; export const useGetUserKeysRaw = (): (() => ReturnType<typeof getDecryptedUserKeys>) => { const authentication = useAuthentication(); const getUser = useGetUser(); return useCallback(async () => { const user = await getUser(); const keyPassword = authentication.getPassword(); return getDecryptedUserKeysHelper(user, keyPassword); }, [getUser]); };
7,085
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useGetVerificationPreferences.ts
import { useCallback } from 'react'; import { PublicKeyReference } from '@proton/crypto'; import getPublicKeysVcardHelper from '@proton/shared/lib/api/helpers/getPublicKeysVcardHelper'; import { KEY_FLAG, MINUTE, RECIPIENT_TYPES } from '@proton/shared/lib/constants'; import { hasBit } from '@proton/shared/lib/helpers/bitset'; import { canonicalizeEmail, canonicalizeInternalEmail } from '@proton/shared/lib/helpers/email'; import { ApiKeysConfig, KT_VERIFICATION_STATUS } from '@proton/shared/lib/interfaces'; import { GetVerificationPreferences } from '@proton/shared/lib/interfaces/hooks/GetVerificationPreferences'; import { splitKeys } from '@proton/shared/lib/keys'; import { getActiveKeys } from '@proton/shared/lib/keys/getActiveKeys'; import { getVerifyingKeys } from '@proton/shared/lib/keys/publicKeys'; import { useGetAddresses } from './useAddresses'; import useApi from './useApi'; import useCache from './useCache'; import { getPromiseValue } from './useCachedModelResult'; import { useGetAddressKeys } from './useGetAddressKeys'; import useGetPublicKeysForInbox from './useGetPublicKeysForInbox'; import { useGetMailSettings } from './useMailSettings'; import { useGetUserKeys } from './useUserKeys'; export const CACHE_KEY = 'VERIFICATION_PREFERENCES'; const DEFAULT_LIFETIME = 5 * MINUTE; /** * Given an email address and the user mail settings, return the verification preferences for verifying messages * from that email address. */ const useGetVerificationPreferences = () => { const api = useApi(); const cache = useCache(); const getAddresses = useGetAddresses(); const getUserKeys = useGetUserKeys(); const getAddressKeys = useGetAddressKeys(); const getPublicKeysForInbox = useGetPublicKeysForInbox(); const getMailSettings = useGetMailSettings(); const getVerificationPreferences = useCallback<GetVerificationPreferences>( async ({ email, lifetime, contactEmailsMap }) => { const addresses = await getAddresses(); const canonicalEmail = canonicalizeInternalEmail(email); const selfAddress = addresses.find(({ Email }) => canonicalizeInternalEmail(Email) === canonicalEmail); if (selfAddress) { const selfAddressKeys = await getAddressKeys(selfAddress.ID); const activeAddressKeys = await getActiveKeys( selfAddress, selfAddress.SignedKeyList, selfAddress.Keys, selfAddressKeys ); const activePublicKeys = activeAddressKeys.map(({ publicKey }) => publicKey); const compromisedFingerprints = new Set( activeAddressKeys .filter(({ flags }) => !hasBit(flags, KEY_FLAG.FLAG_NOT_COMPROMISED)) .map(({ fingerprint }) => fingerprint) ); const verifyingKeys = getVerifyingKeys(activePublicKeys, compromisedFingerprints); return { isOwnAddress: true, verifyingKeys, apiKeys: activePublicKeys, pinnedKeys: [], compromisedFingerprints, ktVerificationResult: { status: KT_VERIFICATION_STATUS.VERIFIED_KEYS }, }; } const { RecipientType, publicKeys: apiKeys, ktVerificationResult, Errors, }: ApiKeysConfig = await getPublicKeysForInbox({ email, lifetime, // messages from internal senders with e2ee disabled are still signed, thus we need to fetch the corresponding verification keys includeInternalKeysWithE2EEDisabledForMail: true, // untrusted WKD keys are not used for verification, and requesting WKD keys leaks to the sender's domain owner that the message has been read. internalKeysOnly: true, }); const isInternal = RecipientType === RECIPIENT_TYPES.TYPE_INTERNAL; const { publicKeys } = splitKeys(await getUserKeys()); const { pinnedKeys, isContactSignatureVerified: pinnedKeysVerified } = await getPublicKeysVcardHelper( api, email, publicKeys, isInternal, contactEmailsMap ); const compromisedKeysFingerprints = new Set( apiKeys .filter(({ flags }) => !hasBit(flags, KEY_FLAG.FLAG_NOT_COMPROMISED)) .map(({ publicKey }) => publicKey!.getFingerprint()) ); const pinnedKeysFingerprints = new Set(pinnedKeys.map((key) => key.getFingerprint())); const apiPublicKeys = apiKeys.filter(({ publicKey }) => !!publicKey).map(({ publicKey }) => publicKey!); let verifyingKeys: PublicKeyReference[] = []; if (pinnedKeys.length) { verifyingKeys = getVerifyingKeys(pinnedKeys, compromisedKeysFingerprints); } else if (isInternal && ktVerificationResult?.status === KT_VERIFICATION_STATUS.VERIFIED_KEYS) { verifyingKeys = getVerifyingKeys(apiPublicKeys, compromisedKeysFingerprints); } return { isOwnAddress: false, verifyingKeys, pinnedKeys, apiKeys: apiPublicKeys, ktVerificationResult, pinnedKeysFingerprints, compromisedKeysFingerprints, pinnedKeysVerified, apiKeysErrors: Errors, }; }, [api, getAddressKeys, getAddresses, getPublicKeysForInbox, getMailSettings] ); return useCallback<GetVerificationPreferences>( ({ email, lifetime = DEFAULT_LIFETIME, contactEmailsMap }) => { if (!cache.has(CACHE_KEY)) { cache.set(CACHE_KEY, new Map()); } const subCache = cache.get(CACHE_KEY); // By normalizing email here, we consider that it could not exists different encryption preferences // For 2 addresses identical but for the cases. // If a provider does different one day, this would have to evolve. const canonicalEmail = canonicalizeEmail(email); const miss = () => getVerificationPreferences({ email: canonicalEmail, lifetime, contactEmailsMap }); return getPromiseValue(subCache, canonicalEmail, miss, lifetime); }, [cache, getVerificationPreferences] ); }; export default useGetVerificationPreferences;
7,086
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useGetVtimezonesMap.ts
import { useCallback } from 'react'; import { getVtimezones } from '@proton/shared/lib/api/calendars'; import { parse } from '@proton/shared/lib/calendar/vcal'; import { GET_VTIMEZONES_API_LIMIT } from '@proton/shared/lib/constants'; import { VcalVtimezoneComponent } from '@proton/shared/lib/interfaces/calendar'; import { GetVTimezonesMap, VTimezoneObject } from '@proton/shared/lib/interfaces/hooks/GetVTimezonesMap'; import { SimpleMap } from '@proton/shared/lib/interfaces/utils'; import chunk from '@proton/utils/chunk'; import unique from '@proton/utils/unique'; import useApi from './useApi'; import useCache from './useCache'; import { getIsRecordInvalid, getPromiseValue } from './useCachedModelResult'; const CACHE_KEY = 'VTIMEZONES'; export const useGetVtimezonesMap = () => { const api = useApi(); const cache = useCache(); const getVTimezonesMap = useCallback( async (tzids: string[]): Promise<SimpleMap<VTimezoneObject>> => { const uniqueTzids = unique(tzids.filter((tzid) => tzid.toLowerCase() !== 'utc')); const encodedTzids = uniqueTzids.map((tzid) => encodeURIComponent(tzid)); if (!uniqueTzids.length) { return Promise.resolve({}); } const batchedTimezones = chunk(encodedTzids, GET_VTIMEZONES_API_LIMIT); return ( await Promise.all( batchedTimezones.map(async (batch) => { const { Timezones = {} } = await api<{ Timezones: SimpleMap<string> }>(getVtimezones(batch)); return tzids.reduce<SimpleMap<VTimezoneObject>>((acc, tzid) => { const vtimezoneString = Timezones[tzid]; if (vtimezoneString) { acc[tzid] = { vtimezoneString, vtimezone: parse(vtimezoneString) as VcalVtimezoneComponent, }; } return acc; }, {}); }) ) ).reduce<SimpleMap<VTimezoneObject>>((acc, curr) => ({ ...acc, ...curr }), {}); }, [api, cache] ); return useCallback<GetVTimezonesMap>( (tzids: string[]) => { if (!cache.has(CACHE_KEY)) { cache.set(CACHE_KEY, new Map()); } const subCache = cache.get(CACHE_KEY); const missing = tzids.filter((tzid) => { return getIsRecordInvalid(subCache.get(tzid)); }); const promise = getVTimezonesMap(missing); const miss = async (tzid: string) => { const map = await promise; return map[tzid]; }; return Promise.all( tzids.map(async (tzid) => { const result = await getPromiseValue(subCache, tzid, miss); return { tzid, result: result as VTimezoneObject, }; }) ).then((result) => { return result.reduce<SimpleMap<VTimezoneObject>>((acc, { tzid, result }) => { acc[tzid] = result; return acc; }, {}); }); }, [cache, getVTimezonesMap] ); };
7,087
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useHandler.ts
import { DependencyList, RefObject, useEffect, useMemo, useRef } from 'react'; import debounce from '@proton/utils/debounce'; import throttle from '@proton/utils/throttle'; import useEventManager from './useEventManager'; export type Handler = (...args: any[]) => void; export interface Cancellable { cancel?: () => void; } /** * Create a stable reference of handler * But will always run the updated version of the handler in argument */ export const useHandler = <T extends Handler>( handler: T, options: { debounce?: number; throttle?: number } = {} ): T & Cancellable => { const handlerRef = useRef(handler); useEffect(() => { handlerRef.current = handler; }, [handler]); const actualHandler = useMemo(() => { const handler = (...args: any[]) => handlerRef.current(...args); if (options.debounce && options.debounce > 0) { return debounce(handler, options.debounce); } if (options.throttle && options.throttle > 0) { return throttle(handler, options.throttle); } return handler; }, []) as T & Cancellable; return actualHandler; }; /** * Listen to the eventName of the ref element * Use useHandler to ensure an updated version of the handler */ export const useEventListener = ( ref: RefObject<Document | Element | null | undefined>, eventName: string, handler: Handler, dependencies: DependencyList ) => { const actualHandler = useHandler(handler); useEffect(() => { const el = ref.current; if (!el) { return; } el.addEventListener(eventName, actualHandler); return () => { el.removeEventListener(eventName, actualHandler); }; }, dependencies); }; /** * Listen to the event manager * Use useHandler to ensure an updated version of the handler */ export const useSubscribeEventManager = (handler: Handler) => { const { subscribe } = useEventManager(); const actualHandler = useHandler(handler); useEffect(() => subscribe(actualHandler), []); }; /** * Run a handler at a defined interval * Returns a function to abort the interval before the component is unmount * Using an interval 0 will prevent the interval to be used */ export const useInterval = (interval: number, handler: Handler) => { const actualHandler: Handler & Cancellable = useHandler(handler); useEffect(() => { if (interval > 0) { const intervalID = window.setInterval(actualHandler, interval); actualHandler(); actualHandler.cancel = () => clearInterval(intervalID); return actualHandler.cancel; } }, []); return () => actualHandler.cancel?.(); }; export default useHandler;
7,088
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useHasOutdatedRecoveryFile.ts
import usePrimaryRecoverySecret from './usePrimaryRecoverySecret'; import useRecoverySecrets from './useRecoverySecrets'; const useHasOutdatedRecoveryFile = () => { const primaryRecoverySecret = usePrimaryRecoverySecret(); const recoverySecrets = useRecoverySecrets(); return recoverySecrets?.length > 0 && !primaryRecoverySecret; }; export default useHasOutdatedRecoveryFile;
7,089
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useHasSuspendedCounter.ts
import { useEffect, useState } from 'react'; interface Props { refreshInterval: number; tolerance: number; } const useHasSuspendedCounter = ({ refreshInterval, tolerance }: Props) => { const [counter, setCounter] = useState(0); useEffect(() => { let previousTime = Date.now(); let unmounted = false; const intervalHandle = window.setInterval(() => { const currentTime = Date.now(); const computedInterval = currentTime - previousTime; const isOutOfSync = Math.abs(computedInterval - refreshInterval) > tolerance; if (isOutOfSync && !unmounted) { setCounter((counter) => counter + 1); } previousTime = currentTime; }, refreshInterval); return () => { unmounted = true; clearInterval(intervalHandle); }; }, [refreshInterval, tolerance]); return counter; }; export default useHasSuspendedCounter;
7,090
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useHotkeys.ts
import { DependencyList, RefObject, useRef } from 'react'; import { isMac } from '@proton/shared/lib/helpers/browser'; import isDeepEqual from '@proton/shared/lib/helpers/isDeepEqual'; import { KeyboardKey, KeyboardKeyType } from '@proton/shared/lib/interfaces'; import isTruthy from '@proton/utils/isTruthy'; import { useEventListener } from './useHandler'; /* * A Hotkey being an array means we have a "modifier" combination * of keys (e.g. "Cmd + K" would translate to ['Meta', 'K']) * */ type Hotkey = KeyboardKeyType | KeyboardKeyType[]; /* * A Sequence is a suite of Hotkeys * (e.g. press "G" then "I" to navigate to the Inbox folder) * */ type Sequence = Hotkey[]; type HotKeyCallback = (e: KeyboardEvent) => void; /* * The longest allowed sequence matches the "Konami code" length * if ever someone wants to do implement it somewhere ¯\_(ツ)_/¯ * */ // @todo try to find a way to have an infinity of hotkeys if wanted export type HotkeyTuple = | [Hotkey, HotKeyCallback] | [Hotkey, Hotkey, HotKeyCallback] | [Hotkey, Hotkey, Hotkey, HotKeyCallback] | [Hotkey, Hotkey, Hotkey, Hotkey, HotKeyCallback] | [Hotkey, Hotkey, Hotkey, Hotkey, Hotkey, HotKeyCallback] | [Hotkey, Hotkey, Hotkey, Hotkey, Hotkey, Hotkey, HotKeyCallback] | [Hotkey, Hotkey, Hotkey, Hotkey, Hotkey, Hotkey, Hotkey, HotKeyCallback] | [Hotkey, Hotkey, Hotkey, Hotkey, Hotkey, Hotkey, Hotkey, Hotkey, HotKeyCallback] | [Hotkey, Hotkey, Hotkey, Hotkey, Hotkey, Hotkey, Hotkey, Hotkey, Hotkey, HotKeyCallback] | [Hotkey, Hotkey, Hotkey, Hotkey, Hotkey, Hotkey, Hotkey, Hotkey, Hotkey, Hotkey, HotKeyCallback] | [Hotkey, Hotkey, Hotkey, Hotkey, Hotkey, Hotkey, Hotkey, Hotkey, Hotkey, Hotkey, Hotkey, HotKeyCallback]; type KeyEventType = 'keyup' | 'keydown' | 'keypress'; type HotKeysOptions = { keyEventType?: KeyEventType; sequenceResetTime?: number; dependencies?: DependencyList; }; const MODIFIER_KEYS = { META: KeyboardKey.Meta.toLowerCase(), SHIFT: KeyboardKey.Shift.toLowerCase(), CONTROL: KeyboardKey.Control.toLowerCase(), ALT: KeyboardKey.Alt.toLowerCase(), }; const isMacOS = isMac(); const normalizeHotkeySequence = (a: string | string[]) => Array.isArray(a) ? a.sort().map((k) => k.toLowerCase()) : [a.toLowerCase()]; /* * Here we normalize Meta / Ctrl for Mac / PC & Linux users * E.g. ['Meta', 'A'] will translate `Cmd + A` for Mac users and `Ctrl + A` for PC/Linux users * */ const normalizeMetaControl = (initalTuple: HotkeyTuple) => { const sequence = initalTuple.slice(0, -1) as Sequence; const callback = initalTuple[initalTuple.length - 1]; const keys = sequence.reduce<Sequence>((acc, hotkey) => { if (Array.isArray(hotkey)) { acc.push(hotkey.map((k) => (!isMacOS && k === KeyboardKey.Meta ? KeyboardKey.Control : k))); } else { acc.push(!isMacOS && hotkey === KeyboardKey.Meta ? KeyboardKey.Control : hotkey); } return acc; }, []); return [...keys, callback]; }; export const useHotkeys = ( ref: RefObject<HTMLElement | Document | undefined>, hotkeyTupleArray: HotkeyTuple[], options?: HotKeysOptions ) => { const { keyEventType = 'keydown', sequenceResetTime = 1000, dependencies = [] } = options || {}; const msSinceLastEvent = useRef(0); const sequence = useRef<Sequence>([]); const handleKeyDown = (e: KeyboardEvent) => { if (!e.key) { return; } const key = e.key.toLowerCase() as KeyboardKey; if (Date.now() - msSinceLastEvent.current > sequenceResetTime) { sequence.current = []; } msSinceLastEvent.current = Date.now(); if ([MODIFIER_KEYS.ALT, MODIFIER_KEYS.SHIFT, MODIFIER_KEYS.CONTROL, MODIFIER_KEYS.META].includes(key)) { return; } const isAlphaNumericalOrSpace = key.match(/[a-zA-Z1-9 ]/gi); const modifiedKey = [ key, e.metaKey && MODIFIER_KEYS.META, e.ctrlKey && MODIFIER_KEYS.CONTROL, // Some non-alphanumerical keys need Shift or Alt modifiers // to be typed, thus cannot be used (e.g. "?" or "/") isAlphaNumericalOrSpace && e.shiftKey && MODIFIER_KEYS.SHIFT, isAlphaNumericalOrSpace && e.altKey && MODIFIER_KEYS.ALT, ].filter(isTruthy) as Hotkey; sequence.current.push(modifiedKey); const normalizedHotkeyTupleArray = hotkeyTupleArray.map(normalizeMetaControl); for (let i = 0; i < normalizedHotkeyTupleArray.length; i++) { const hotKeyTuple = normalizedHotkeyTupleArray[i]; const hotkeySequence = (hotKeyTuple.slice(0, -1) as Sequence).map(normalizeHotkeySequence); /* * take the number of items from the sequence as the number of items in * the hotkey sequence, starting from the end, so that even if the sequences * are not identical, a match is still found should the tails be identical * */ const tailSequence = sequence.current.slice(-hotkeySequence.length).map(normalizeHotkeySequence); if (isDeepEqual(hotkeySequence, tailSequence)) { const callback = hotKeyTuple[hotKeyTuple.length - 1] as HotKeyCallback; callback(e); break; } } }; useEventListener(ref, keyEventType, handleKeyDown, dependencies); };
7,091
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useImporters.ts
import { ImportReportAggregated, Importer } from '@proton/activation/src/interface'; import { ImportReportsModel, ImportersModel } from '@proton/shared/lib/models/importersModel'; import createUseModelHook from './helpers/createModelHook'; export const useImporters = createUseModelHook<Importer[]>(ImportersModel); export const useImportReports = createUseModelHook<ImportReportAggregated[]>(ImportReportsModel);
7,092
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useIncomingAddressForwarding.ts
import { IncomingAddressForwarding } from '@proton/shared/lib/interfaces'; import { IncomingAddressForwardingModel } from '@proton/shared/lib/models/incomingAddressForwardingModel'; import useApi from './useApi'; import useCache from './useCache'; import useCachedModelResult from './useCachedModelResult'; const useIncomingAddressForwarding = (): [IncomingAddressForwarding[], boolean, Error] => { const cache = useCache(); const api = useApi(); const miss = () => IncomingAddressForwardingModel.get(api); return useCachedModelResult(cache, IncomingAddressForwardingModel.key, miss); }; export default useIncomingAddressForwarding;
7,093
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useIsClosing.ts
import { useLayoutEffect, useState } from 'react'; import usePrevious from '@proton/hooks/usePrevious'; const useIsClosing = (isOpen = false): [boolean, boolean, () => void] => { const [[isClosed, isClosing], setResult] = useState(() => [false, !isOpen]); const isOpenPrevious = usePrevious(isOpen); useLayoutEffect(() => { if (isOpen) { setResult([false, false]); } else if (!isOpen && isOpenPrevious) { setResult([true, false]); } }, [isOpen, isOpenPrevious]); const setIsClosed = () => setResult([false, true]); return [isClosed, isClosing, setIsClosed]; }; export default useIsClosing;
7,094
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useIsDataRecoveryAvailable.ts
import useIsMnemonicAvailable from './useIsMnemonicAvailable'; import useIsRecoveryFileAvailable from './useIsRecoveryFileAvailable'; const useIsDataRecoveryAvailable = () => { const [isRecoveryFileAvailable, loadingIsRecoveryFileAvailable] = useIsRecoveryFileAvailable(); const [isMnemonicAvailable, loadingIsMnemonicAvailable] = useIsMnemonicAvailable(); const isDataRecoveryAvailable = isRecoveryFileAvailable || isMnemonicAvailable; return [isDataRecoveryAvailable, loadingIsRecoveryFileAvailable || loadingIsMnemonicAvailable]; }; export default useIsDataRecoveryAvailable;
7,095
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useIsElectronApp.ts
import { useFlag } from '@protontech/proxy-client-react'; import { isElectronApp, isElectronOnMac as testIsElectronOnMac } from '@proton/shared/lib/helpers/desktop'; const useIsElectronApp = (flag: string) => { const isElectron = isElectronApp(); const electronFlag = useFlag(flag); const isElectronDisabled = isElectron && electronFlag; const isElectronOnMac = testIsElectronOnMac(); return { isElectron, isElectronDisabled, isElectronOnMac }; }; export default useIsElectronApp;
7,096
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useIsInboxElectronApp.ts
import useIsElectronApp from './useIsElectronApp'; const useIsInboxElectronApp = () => { const { isElectron, isElectronDisabled, isElectronOnMac } = useIsElectronApp('DisableElectronMail'); return { isElectron, isElectronDisabled, isElectronOnMac }; }; export default useIsInboxElectronApp;
7,097
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useIsMnemonicAvailable.ts
import { getIsMnemonicAvailable } from '../containers/mnemonic/helper'; import useAddresses from './useAddresses'; import useConfig from './useConfig'; import useUser from './useUser'; const useIsMnemonicAvailable = () => { const { APP_NAME } = useConfig(); const [user, loadingUser] = useUser(); const [addresses = [], loadingAddresses] = useAddresses(); const isMnemonicAvailable = getIsMnemonicAvailable({ addresses, user, app: APP_NAME }); return [isMnemonicAvailable, loadingAddresses || loadingUser] as const; }; export default useIsMnemonicAvailable;
7,098
0
petrpan-code/ProtonMail/WebClients/packages/components
petrpan-code/ProtonMail/WebClients/packages/components/hooks/useIsPaidUserCookie.ts
import { useEffect } from 'react'; import { getCookie, setCookie } from '@proton/shared/lib/helpers/cookies'; import { getSecondLevelDomain } from '@proton/shared/lib/helpers/url'; import { useUser } from './useUser'; const COOKIE_NAME = 'no-offer'; const today = new Date(); const lastDayOfTheYear = new Date(today.getFullYear(), 11, 31, 23, 59, 59); const cookieDomain = `.${getSecondLevelDomain(window.location.hostname)}`; /** * Set a cookie for non eligible user to BF offer * Used by proton.me website to hide BF banner */ const useIsPaidUserCookie = () => { const [user, loadingUser] = useUser(); const loading = loadingUser; useEffect(() => { if (loading) { return; } const cookie = getCookie(COOKIE_NAME); const isPaid = user.isPaid; const shouldSet = isPaid; if (shouldSet && cookie !== '1') { setCookie({ cookieName: COOKIE_NAME, cookieValue: '1', cookieDomain, expirationDate: lastDayOfTheYear.toUTCString(), path: '/', }); } else if (!shouldSet && cookie === '1') { setCookie({ cookieName: COOKIE_NAME, cookieValue: undefined, cookieDomain, expirationDate: new Date(0).toUTCString(), path: '/', }); } }, [user, loading]); }; export default useIsPaidUserCookie;
7,099