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/applications/calendar/src/app/containers/calendar/eventStore
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/eventStore/cache/recurringCache.ts
import { RecurringCache, RecurringEventsCache } from '../interface'; export const removeEventFromRecurrenceInstances = ( uid: string, recurrenceId: number, recurringEvents: RecurringEventsCache, eventID: string ) => { const oldRecurringEvent = recurringEvents.get(uid); if (!oldRecurringEvent) { return; } const oldRecurrenceInstances = oldRecurringEvent.recurrenceInstances; if (!oldRecurrenceInstances) { return; } const oldEventID = oldRecurrenceInstances[recurrenceId]; if (oldEventID !== eventID) { return; } const newRecurrenceInstances = { ...oldRecurrenceInstances, }; delete newRecurrenceInstances[recurrenceId]; recurringEvents.set(uid, { ...oldRecurringEvent, recurrenceInstances: newRecurrenceInstances, }); }; interface SetEventInRecurrenceInstances { id: string; uid: string; recurrenceId: number; recurringEvents: RecurringEventsCache; oldRecurrenceId?: number; } export const setEventInRecurrenceInstances = ({ id, uid, recurrenceId, recurringEvents, oldRecurrenceId, }: SetEventInRecurrenceInstances) => { // Get the parent recurring event (if any) const oldRecurringEvent = recurringEvents.get(uid) || {}; const oldRecurrenceInstances = oldRecurringEvent.recurrenceInstances || {}; // Update the recurrence id in the recurrence id map const newRecurrenceInstances = { ...oldRecurrenceInstances, }; if (oldRecurrenceId !== undefined) { const oldEventID = newRecurrenceInstances[recurrenceId]; if (oldEventID === id) { delete newRecurrenceInstances[oldRecurrenceId]; } } newRecurrenceInstances[recurrenceId] = id; recurringEvents.set(uid, { ...oldRecurringEvent, recurrenceInstances: newRecurrenceInstances, }); }; export const setEventInRecurringCache = (recurringEvents: RecurringEventsCache, id: string, uid: string) => { const oldRecurringEvent = recurringEvents.get(uid) || {}; recurringEvents.set(uid, { ...oldRecurringEvent, parentEventID: id, cache: {}, }); }; export const removeEventFromRecurringCache = ( recurringEvents: Map<string, RecurringCache>, uid: string, eventID: string ) => { const oldRecurringEvent = recurringEvents.get(uid) || {}; if (oldRecurringEvent.parentEventID !== eventID) { return; } if (!oldRecurringEvent.recurrenceInstances || !Object.keys(oldRecurringEvent.recurrenceInstances).length) { recurringEvents.delete(uid); return; } recurringEvents.set(uid, { ...oldRecurringEvent, parentEventID: undefined, cache: {}, }); };
2,500
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/eventStore
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/eventStore/cache/removeCalendarEventStoreRecord.ts
import {getIsRecurring, getRecurrenceIdDate, getUidValue} from '@proton/shared/lib/calendar/veventHelper'; import { APPS } from '@proton/shared/lib/constants'; import { postMessageFromIframe } from '@proton/shared/lib/drawer/helpers'; import { DRAWER_EVENTS } from '@proton/shared/lib/drawer/interfaces'; import { OpenedMailEvent } from '../../../../hooks/useGetOpenedMailEvents'; import { CalendarEventsCache } from '../interface'; import { removeEventFromRecurrenceInstances, removeEventFromRecurringCache } from './recurringCache'; export const removeCalendarEventStoreRecord = ( EventID: string, { tree, events, recurringEvents }: CalendarEventsCache, getOpenedMailEvents?: () => OpenedMailEvent[] ) => { const oldCalendarEventStoreRecord = events.get(EventID); if (!oldCalendarEventStoreRecord) { return; } const { utcStart, utcEnd, eventComponent } = oldCalendarEventStoreRecord; tree.remove(+utcStart, +utcEnd, EventID); const uid = getUidValue(eventComponent); const recurrenceId = getRecurrenceIdDate(eventComponent); const isRecurring = getIsRecurring(eventComponent); if (recurrenceId) { removeEventFromRecurrenceInstances(uid, +recurrenceId, recurringEvents, EventID); } else if (isRecurring) { removeEventFromRecurringCache(recurringEvents, uid, EventID); } events.delete(EventID); // If the deleted event is open in Mail, tell it to refresh the widget if ((getOpenedMailEvents?.() || []).find(({ UID }) => UID === uid)) { postMessageFromIframe( { type: DRAWER_EVENTS.REFRESH_WIDGET, payload: { UID: uid, ModifyTime: Number.POSITIVE_INFINITY }, }, APPS.PROTONMAIL ); } }; export default removeCalendarEventStoreRecord;
2,501
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/eventStore
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/eventStore/cache/upsertCalendarApiEvent.ts
import { APPS } from '@proton/shared/lib/constants'; import { postMessageFromIframe } from '@proton/shared/lib/drawer/helpers'; import { DRAWER_EVENTS } from '@proton/shared/lib/drawer/interfaces'; import { CalendarEvent } from '@proton/shared/lib/interfaces/calendar'; import { OpenedMailEvent } from '../../../../hooks/useGetOpenedMailEvents'; import { CalendarEventsCache } from '../interface'; import getComponentFromCalendarEventUnencryptedPart from './getComponentFromCalendarEventUnencryptedPart'; import removeCalendarEventStoreRecord from './removeCalendarEventStoreRecord'; import { getCalendarEventStoreRecord, upsertCalendarEventStoreRecord } from './upsertCalendarEventStoreRecord'; const upsertCalendarApiEvent = ( Event: CalendarEvent, calendarEventsCache: CalendarEventsCache, getOpenedMailEvents?: () => OpenedMailEvent[] ) => { const { ID: eventID, UID, ModifyTime } = Event; try { const eventComponent = getComponentFromCalendarEventUnencryptedPart(Event); const newCalendarEventStoreRecord = getCalendarEventStoreRecord(eventComponent, Event); const didUpsert = upsertCalendarEventStoreRecord(eventID, newCalendarEventStoreRecord, calendarEventsCache); // If the upserted event is open in Mail, tell it to refresh the widget const isOpenInMail = !!(getOpenedMailEvents?.() || []).find(({ UID: uid }) => UID === uid); if (didUpsert && isOpenInMail) { postMessageFromIframe( { type: DRAWER_EVENTS.REFRESH_WIDGET, payload: { UID, ModifyTime }, }, APPS.PROTONMAIL ); } return didUpsert; } catch (error: any) { removeCalendarEventStoreRecord(eventID, calendarEventsCache); return false; } }; export default upsertCalendarApiEvent;
2,502
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/eventStore
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/eventStore/cache/upsertCalendarApiEventWithoutBlobs.ts
import { pick } from '@proton/shared/lib/helpers/object'; import { CalendarEventWithoutBlob } from '@proton/shared/lib/interfaces/calendar'; import { CalendarEventsCache } from '../interface'; import getComponentFromCalendarEventWithoutBlob from './getComponentFromCalendarEventWithoutBlob'; import removeCalendarEventStoreRecord from './removeCalendarEventStoreRecord'; import { getCalendarEventStoreRecord, upsertCalendarEventStoreRecord } from './upsertCalendarEventStoreRecord'; const FIELDS_TO_KEEP = [ 'ID', 'Author', 'SharedEventID', 'CalendarID', 'CreateTime', 'ModifyTime', 'Permissions', 'IsOrganizer', 'IsProtonProtonInvite', ] as const; const upsertCalendarApiEventWithoutBlob = ( Event: CalendarEventWithoutBlob, calendarEventsCache: CalendarEventsCache ) => { const eventID = Event.ID; try { const eventComponent = getComponentFromCalendarEventWithoutBlob(Event); const eventData = pick(Event, FIELDS_TO_KEEP); const newCalendarEventStoreRecord = getCalendarEventStoreRecord(eventComponent, eventData); return upsertCalendarEventStoreRecord(eventID, newCalendarEventStoreRecord, calendarEventsCache); } catch { removeCalendarEventStoreRecord(eventID, calendarEventsCache); return false; } }; export default upsertCalendarApiEventWithoutBlob;
2,503
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/eventStore
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/eventStore/cache/upsertCalendarEventInTree.ts
import { IntervalTree } from '../interface'; interface UpsertCalendarEventInTreeArguments { oldStart?: number; oldEnd?: number; start: number; end: number; isOldRecurring: boolean; id: string; tree: IntervalTree; } const upsertCalendarEventInTree = ({ oldStart, oldEnd, isOldRecurring, start, end, id, tree, }: UpsertCalendarEventInTreeArguments) => { if (oldStart === undefined || oldEnd === undefined || isOldRecurring) { tree.insert(+start, +end, id); return; } if (start !== oldStart || end !== oldEnd) { // Interval changed tree.remove(oldStart, oldEnd, id); tree.insert(start, end, id); } }; export default upsertCalendarEventInTree;
2,504
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/eventStore
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/eventStore/cache/upsertCalendarEventStoreRecord.spec.ts
import { getUnixTime } from 'date-fns'; import { ATTENDEE_STATUS_API } from '@proton/shared/lib/calendar/constants'; import { CalendarEvent, CalendarEventBlobData, CalendarEventSharedData } from '@proton/shared/lib/interfaces/calendar'; import { getHasUpdatedAttendees, getHasUpdatedEventData } from './upsertCalendarEventStoreRecord'; // dummy test data const dummyModifyTime = getUnixTime(Date.UTC(2023, 9, 24)); const dummyAttendee = { ID: 'attendee-1', Token: 'token-1', Status: ATTENDEE_STATUS_API.NEEDS_ACTION, UpdateTime: dummyModifyTime, }; const dummySharedData: CalendarEventSharedData = { ID: 'id', SharedEventID: 'shared-event-id', CalendarID: 'calendar-id', CreateTime: 0, ModifyTime: dummyModifyTime, Permissions: 0, IsOrganizer: 0, IsProtonProtonInvite: 0, Author: 'author', }; const dummyBlobData: CalendarEventBlobData = { CalendarKeyPacket: null, CalendarEvents: [], SharedKeyPacket: 'shared-key-packet', AddressKeyPacket: null, AddressID: 'address-id', SharedEvents: [], Notifications: null, AttendeesEvents: [], Attendees: [dummyAttendee], }; const dummyEventData: CalendarEvent = { ...dummySharedData, ...dummyBlobData, StartTime: getUnixTime(Date.UTC(2023, 9, 31)), StartTimezone: 'Europe/Warsaw', EndTime: getUnixTime(Date.UTC(2023, 10, 1)), EndTimezone: 'Europe/Warsaw', FullDay: 1, RRule: null, UID: 'uid', RecurrenceID: null, Exdates: [], }; describe('getHasUpdatedAttendees', function () { it('does not update attendees when the new event does not have blob data', () => { const newEventData = { ...dummySharedData }; // no old event data expect(getHasUpdatedAttendees(newEventData)).toEqual({ hasUpdatedAttendees: false }); // old event data has only shared data expect( getHasUpdatedAttendees(newEventData, { ...dummySharedData, ModifyTime: dummyModifyTime - 1, }) ).toEqual({ hasUpdatedAttendees: false }); expect( getHasUpdatedAttendees(newEventData, { ...dummySharedData, ModifyTime: dummyModifyTime + 1, }) ).toEqual({ hasUpdatedAttendees: false }); // old event data is full expect( getHasUpdatedAttendees(newEventData, { ...dummyEventData, }) ).toEqual({ hasUpdatedAttendees: false }); }); it('does not update attendees when attendees nor attendee times have not changed', () => { const newEventData = { ...dummyEventData, Attendees: [ { ...dummyAttendee, // status changed Status: ATTENDEE_STATUS_API.ACCEPTED, }, ], }; const oldEventData = { ...dummyEventData, }; expect(getHasUpdatedAttendees(newEventData, oldEventData)).toEqual({ hasUpdatedAttendees: false, attendees: oldEventData.Attendees, }); }); it('updates attendees (but only the ones with new update times) when there are new attendees', () => { const oldEventData = { ...dummyEventData, }; const newEventData = { ...oldEventData, Attendees: [ { ...dummyAttendee, // status changed Status: ATTENDEE_STATUS_API.ACCEPTED, }, { ID: 'attendee-2', Token: 'token-2', Status: ATTENDEE_STATUS_API.TENTATIVE, UpdateTime: dummyModifyTime + 1, }, ], }; expect(getHasUpdatedAttendees(newEventData, oldEventData)).toEqual({ hasUpdatedAttendees: true, attendees: [dummyAttendee, newEventData.Attendees[1]], }); }); it('updates attendees (but only the ones with new update times) when some attendees got removed', () => { const oldEventData = { ...dummyEventData, Attendees: [ dummyAttendee, { ID: 'attendee-2', Token: 'token-2', Status: ATTENDEE_STATUS_API.TENTATIVE, UpdateTime: dummyModifyTime, }, ], }; const newEventData = { ...oldEventData, Attendees: [ { ...dummyAttendee, // status changed Status: ATTENDEE_STATUS_API.ACCEPTED, }, ], }; expect(getHasUpdatedAttendees(newEventData, oldEventData)).toEqual({ hasUpdatedAttendees: true, attendees: [dummyAttendee], }); }); it('updates the attendees with new update times', () => { const oldEventData = { ...dummyEventData, Attendees: [ dummyAttendee, { ID: 'attendee-2', Token: 'token-2', Status: ATTENDEE_STATUS_API.TENTATIVE, UpdateTime: dummyModifyTime, }, ], }; const newEventData = { ...oldEventData, Attendees: [ { ...dummyAttendee, // status changed Status: ATTENDEE_STATUS_API.ACCEPTED, }, { ID: 'attendee-2', Token: 'token-2', Status: ATTENDEE_STATUS_API.TENTATIVE, UpdateTime: dummyModifyTime + 1, }, ], }; expect(getHasUpdatedAttendees(newEventData, oldEventData)).toEqual({ hasUpdatedAttendees: true, attendees: [dummyAttendee, newEventData.Attendees[1]], }); }); }); describe('getHasUpdatedEventData', () => { it('does not return updated shared data if ModifyTime has not changed (both old and new event contain just shared data)', () => { const oldEventData = { ...dummySharedData }; const newEventData = { ...dummySharedData, // isOrganizer changed IsOrganizer: 1 as const, }; expect(getHasUpdatedEventData(newEventData, oldEventData)).toEqual({ hasUpdatedEventData: false, eventData: oldEventData, }); }); it('returns updated shared data if ModifyTime has changed (both old and new event contain just shared data)', () => { const oldEventData = { ...dummySharedData }; const newEventData = { ...dummySharedData, // isOrganizer changed IsOrganizer: 1 as const, ModifyTime: dummyModifyTime + 1, }; expect(getHasUpdatedEventData(newEventData, oldEventData)).toEqual({ hasUpdatedEventData: true, eventData: newEventData, }); }); it('returns new event (complete) data when the old event only has shared data, even if ModifyTime has not changed', () => { const oldEventData = { ...dummySharedData }; const newEventData = { ...dummyEventData }; expect(getHasUpdatedEventData(newEventData, oldEventData)).toEqual({ hasUpdatedEventData: true, eventData: newEventData, }); }); it('always returns new event data if ModifyTime has increased', () => { // no old event data expect(getHasUpdatedEventData(dummySharedData)).toEqual({ hasUpdatedEventData: true, eventData: dummySharedData, }); expect(getHasUpdatedEventData(dummyEventData)).toEqual({ hasUpdatedEventData: true, eventData: dummyEventData, }); // old shared data const oldEventSharedData = { ...dummySharedData, ModifyTime: dummyModifyTime - 1 }; expect(getHasUpdatedEventData(dummySharedData, oldEventSharedData)).toEqual({ hasUpdatedEventData: true, eventData: dummySharedData, }); expect(getHasUpdatedEventData(dummyEventData, oldEventSharedData)).toEqual({ hasUpdatedEventData: true, eventData: dummyEventData, }); // old full data const oldEventData = { ...dummyEventData, ModifyTime: dummyModifyTime - 1 }; expect(getHasUpdatedEventData(dummySharedData, oldEventData)).toEqual({ hasUpdatedEventData: true, eventData: dummySharedData, }); expect(getHasUpdatedEventData(dummyEventData, oldEventData)).toEqual({ hasUpdatedEventData: true, eventData: dummyEventData, }); }); it('returns old event data if ModifyTime is not changed (both old and new data are full)', () => { const oldEventData = { ...dummyEventData }; const newEventData = { ...dummyEventData, // isOrganizer changed IsOrganizer: 1 as const, }; expect(getHasUpdatedEventData(newEventData, oldEventData)).toEqual({ hasUpdatedEventData: false, eventData: oldEventData, }); }); it('returns old event data but new attendees if attendees have been modified', () => { const oldEventData = { ...dummyEventData }; const newEventData = { ...dummyEventData, // isOrganizer changed IsOrganizer: 1 as const, Attendees: [ { ...dummyAttendee, // status changed Status: ATTENDEE_STATUS_API.ACCEPTED, }, { ID: 'attendee-2', Token: 'token-2', Status: ATTENDEE_STATUS_API.TENTATIVE, UpdateTime: dummyModifyTime + 1, }, ], }; expect(getHasUpdatedEventData(newEventData, oldEventData)).toEqual({ hasUpdatedEventData: true, eventData: { ...oldEventData, Attendees: [ dummyAttendee, { ID: 'attendee-2', Token: 'token-2', Status: ATTENDEE_STATUS_API.TENTATIVE, UpdateTime: dummyModifyTime + 1, }, ], }, }); }); it('returns new event data but old attendees if attendees have not been modified', () => { const oldEventData = { ...dummyEventData }; const newEventData = { ...dummyEventData, // isOrganizer changed IsOrganizer: 1 as const, ModifyTime: dummyModifyTime + 1, Attendees: [ { ...dummyAttendee, // status changed Status: ATTENDEE_STATUS_API.ACCEPTED, }, ], }; expect(getHasUpdatedEventData(newEventData, oldEventData)).toEqual({ hasUpdatedEventData: true, eventData: { ...newEventData, Attendees: oldEventData.Attendees, }, }); }); it("returns old event data and old attendees when ModifyTime and UpdateTime's are not changed", () => { const oldEventData = { ...dummyEventData }; const newEventData = { ...dummyEventData, // isOrganizer changed IsOrganizer: 1 as const, Attendees: [ { ...dummyAttendee, // status changed Status: ATTENDEE_STATUS_API.ACCEPTED, }, ], }; expect(getHasUpdatedEventData(newEventData, oldEventData)).toEqual({ hasUpdatedEventData: false, eventData: oldEventData, }); }); });
2,505
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/eventStore
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/eventStore/cache/upsertCalendarEventStoreRecord.ts
import { getIsRecurring, getRecurrenceIdDate, getUidValue } from '@proton/shared/lib/calendar/veventHelper'; import { RequireSome, SimpleMap } from '@proton/shared/lib/interfaces'; import { Attendee, CalendarEvent, CalendarEventSharedData } from '@proton/shared/lib/interfaces/calendar'; import { getViewEventDateProperties } from '../../eventHelper'; import { CalendarEventStoreRecord, CalendarEventsCache, SharedVcalVeventComponent } from '../interface'; import { getIsCalendarEvent } from './helper'; import { setEventInRecurrenceInstances, setEventInRecurringCache } from './recurringCache'; import upsertCalendarEventInTree from './upsertCalendarEventInTree'; export const getHasUpdatedAttendees = ( newEventData: CalendarEvent | CalendarEventSharedData, oldEventData?: CalendarEvent | CalendarEventSharedData ) => { if (!oldEventData || !getIsCalendarEvent(oldEventData)) { if (!getIsCalendarEvent(newEventData)) { return { hasUpdatedAttendees: false, }; } return { attendees: newEventData.Attendees, hasUpdatedAttendees: !!newEventData.Attendees.length, }; } if (!getIsCalendarEvent(newEventData)) { return { hasUpdatedAttendees: false, }; } let hasUpdatedAttendees = oldEventData.Attendees.length !== newEventData.Attendees.length; const attendeeMap = oldEventData.Attendees.reduce<SimpleMap<Attendee>>((acc, attendee) => { acc[attendee.Token] = attendee; return acc; }, {}); const attendees = newEventData.Attendees.map((attendee) => { const oldAttendee = attendeeMap[attendee.Token]; const oldUpdateTime = oldAttendee?.UpdateTime || 0; if (!oldUpdateTime) { hasUpdatedAttendees = true; return attendee; } const newUpdateTime = attendee.UpdateTime || 0; if (oldUpdateTime >= newUpdateTime) { // we should return old attendee data return oldAttendee; } hasUpdatedAttendees = true; return attendee; }); return { attendees, hasUpdatedAttendees }; }; /** * Different event parts are updated asynchronously in the BE^**. Ideally we would have a ModifyTime per event part. * Since we don't atm, we rely on the global ModifyTime plus attendee update times. * * ** E.g.: a Proton organizer makes a modification to shared event data (shared with the attendee) * but the attendee makes a change to e.g. notifications before receiving the notification of the organizer change */ export const getHasUpdatedEventData = ( newEventData: CalendarEvent | CalendarEventSharedData, oldEventData?: CalendarEvent | CalendarEventSharedData ) => { const isOldEventDataFull = oldEventData && getIsCalendarEvent(oldEventData); const isNewEventFull = getIsCalendarEvent(newEventData); const oldModifyTime = oldEventData?.ModifyTime || 0; const newModifyTime = newEventData.ModifyTime; const isNewEventLastEditTime = newModifyTime > oldModifyTime ? true : !isOldEventDataFull && isNewEventFull; const isNewEvent = !oldEventData; const hasUpdatedEventDataGlobal = isNewEvent || isNewEventLastEditTime; const { hasUpdatedAttendees, attendees } = getHasUpdatedAttendees(newEventData, oldEventData); const eventData: CalendarEvent | CalendarEventSharedData | undefined = hasUpdatedEventDataGlobal ? newEventData : oldEventData; if (attendees && eventData && 'Attendees' in eventData) { eventData.Attendees = attendees; } return { hasUpdatedEventData: hasUpdatedEventDataGlobal || hasUpdatedAttendees, eventData, }; }; export const getCalendarEventStoreRecord = ( eventComponent: SharedVcalVeventComponent, eventData: CalendarEvent | CalendarEventSharedData ): RequireSome<CalendarEventStoreRecord, 'eventData'> => { const { utcStart, utcEnd, isAllDay, isAllPartDay } = getViewEventDateProperties(eventComponent); return { utcStart, utcEnd, isAllDay, isAllPartDay, eventComponent, eventData, }; }; const DEFAULT = {}; const upsertCalendarEventStoreRecordHelper = ( calendarEventID: string, calendarEventStoreRecord: CalendarEventStoreRecord, { tree, events, recurringEvents }: CalendarEventsCache ) => { const oldCalendarEventStoreRecord = events.get(calendarEventID); const { utcStart: newUtcStart, utcEnd: newUtcEnd, eventComponent: newVeventComponent } = calendarEventStoreRecord; const { utcStart: oldUtcStart, utcEnd: oldUtcEnd, eventComponent: oldEventComponent, }: Partial<CalendarEventStoreRecord> = oldCalendarEventStoreRecord || DEFAULT; const isRecurring = getIsRecurring(newVeventComponent); const recurrenceId = getRecurrenceIdDate(newVeventComponent); const uid = getUidValue(newVeventComponent); const isOldRecurring = oldEventComponent ? getIsRecurring(oldEventComponent) : false; const oldRecurrenceId = oldEventComponent ? getRecurrenceIdDate(oldEventComponent) : undefined; const oldUid = oldEventComponent ? getUidValue(newVeventComponent) : undefined; if (oldCalendarEventStoreRecord && oldUid !== uid) { throw new Error('Event with incorrect UID'); } if (oldCalendarEventStoreRecord && recurrenceId && !oldRecurrenceId) { // This should never happen throw new Error('Old event without recurrence id'); } if (recurrenceId) { setEventInRecurrenceInstances({ id: calendarEventID, uid, recurringEvents, recurrenceId: +recurrenceId, oldRecurrenceId: oldRecurrenceId ? +oldRecurrenceId : undefined, }); upsertCalendarEventInTree({ id: calendarEventID, oldStart: oldUtcStart ? +oldUtcStart : undefined, oldEnd: oldUtcEnd ? +oldUtcEnd : undefined, isOldRecurring, start: +newUtcStart, end: +newUtcEnd, tree, }); } else if (isRecurring) { if (oldCalendarEventStoreRecord && !isOldRecurring && oldUtcStart && oldUtcEnd) { tree.remove(+oldUtcStart, +oldUtcEnd, calendarEventID); } setEventInRecurringCache(recurringEvents, calendarEventID, uid); } else { if (isOldRecurring) { recurringEvents.delete(uid); } upsertCalendarEventInTree({ id: calendarEventID, oldStart: oldUtcStart ? +oldUtcStart : undefined, oldEnd: oldUtcEnd ? +oldUtcEnd : undefined, isOldRecurring, start: +newUtcStart, end: +newUtcEnd, tree, }); } events.set(calendarEventID, calendarEventStoreRecord); }; export const upsertCalendarEventStoreRecord = ( eventID: string, calendarEventStoreRecord: RequireSome<CalendarEventStoreRecord, 'eventData'>, calendarEventsCache: CalendarEventsCache ) => { const oldEventRecord = calendarEventsCache.events.get(eventID); const oldEventData = oldEventRecord?.eventData; const newEventData = calendarEventStoreRecord.eventData; const { hasUpdatedEventData, eventData } = getHasUpdatedEventData(newEventData, oldEventData); if (!hasUpdatedEventData) { return false; } const newCalendarEventStoreRecord: CalendarEventStoreRecord = { ...calendarEventStoreRecord, eventData, }; upsertCalendarEventStoreRecordHelper(eventID, newCalendarEventStoreRecord, calendarEventsCache); return true; };
2,506
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/eventStore
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/eventStore/cache/upsertResponsesArray.ts
import { API_CODES } from '@proton/shared/lib/constants'; import { SyncMultipleApiResponse, SyncMultipleApiResponses, UpdateEventPartApiResponse, } from '@proton/shared/lib/interfaces/calendar'; import { OpenedMailEvent } from '../../../../hooks/useGetOpenedMailEvents'; import { UpdatePartstatOperation, UpdatePersonalPartOperation } from '../../../../interfaces/Invite'; import { SyncEventActionOperations, getIsDeleteSyncOperation } from '../../getSyncMultipleEventsPayload'; import { CalendarsEventsCache } from '../interface'; import removeCalendarEventStoreRecord from './removeCalendarEventStoreRecord'; import upsertCalendarApiEvent from './upsertCalendarApiEvent'; const getResponse = (responses: SyncMultipleApiResponses[], index: number) => { return responses.find((x) => x.Index === index); }; export const upsertSyncMultiActionsResponses = ( multiActions: SyncEventActionOperations[], multiResponses: SyncMultipleApiResponse[], calendarsEventsCache: CalendarsEventsCache, getOpenedMailEvents: () => OpenedMailEvent[] ) => { for (let i = 0; i < multiResponses.length; ++i) { const actions = multiActions[i]; const responses = multiResponses[i]; const responsesArray = responses?.Responses; const calendarEventsCache = calendarsEventsCache.calendars[actions.calendarID]; if (!Array.isArray(responsesArray) || !calendarEventsCache) { continue; } for (let j = 0; j < actions.operations.length; ++j) { const operation = actions.operations[j]; const matchingResponse = getResponse(responsesArray, j); if (getIsDeleteSyncOperation(operation)) { if (!matchingResponse || matchingResponse.Response.Code === API_CODES.SINGLE_SUCCESS) { removeCalendarEventStoreRecord( operation.data.calendarEvent.ID, calendarEventsCache, getOpenedMailEvents ); } continue; } if (matchingResponse) { const matchingEvent = matchingResponse.Response.Event; if (matchingEvent && matchingResponse.Response.Code === API_CODES.SINGLE_SUCCESS) { upsertCalendarApiEvent(matchingEvent, calendarEventsCache, getOpenedMailEvents); } } } } }; export const upsertUpdateEventPartResponses = ( operations: (UpdatePartstatOperation | UpdatePersonalPartOperation)[], responses: UpdateEventPartApiResponse[], calendarsEventsCache: CalendarsEventsCache, getOpenedMailEvents: () => OpenedMailEvent[] ) => { for (let i = 0; i < responses.length; ++i) { const operation = operations[i]; const { Code, Event } = responses[i]; const calendarEventsCache = calendarsEventsCache.calendars[operation.data.calendarID]; if (!calendarEventsCache) { continue; } if (Code === API_CODES.SINGLE_SUCCESS) { upsertCalendarApiEvent(Event, calendarEventsCache, getOpenedMailEvents); } } };
2,507
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/recurrence/createFutureRecurrence.spec.js
import { MAX_CHARS_API } from '@proton/shared/lib/calendar/constants'; import { getFutureRecurrenceUID } from './createFutureRecurrence'; describe('create future recurrence', () => { it('should append a recurrence offset for short uids without previous offset', () => { expect( getFutureRecurrenceUID( '6pG/5UGJGWB9O88ykIOCYx75cjUb@proton.me', new Date(Date.UTC(2000, 1, 1, 1, 1, 1)), false ) ).toBe('6pG/5UGJGWB9O88ykIOCYx75cjUb_R20000101T010101@proton.me'); expect(getFutureRecurrenceUID('9O88ykIOCYx75cjUb', new Date(Date.UTC(1990, 8, 13, 13, 0, 15)), false)).toBe( '9O88ykIOCYx75cjUb_R19900813T130015' ); expect(getFutureRecurrenceUID('9O@8@8yk@google.com', new Date(Date.UTC(2000, 1, 1, 0, 0, 0)), true)).toBe( '9O@8@8yk_R20000101@google.com' ); }); it('should append a recurrence offset for long uids without previous offset', () => { const chars180 = 'tenchars01tenchars02tenchars03tenchars04tenchars05tenchars06tenchars07tenchars08tenchars09tenchars10tenchars11tenchars12tenchars13tenchars14tenchars15tenchars16tenchars17tenchars18'; const domain = '@proton.me'; const expectedOffsetPartday = '_R20000101T010101'; const expectedOffsetAllday = '_R20000101'; expect(getFutureRecurrenceUID(`${chars180}${domain}`, new Date(Date.UTC(2000, 1, 1, 1, 1, 1)), false)).toBe( `${chars180.slice( chars180.length + expectedOffsetPartday.length + domain.length - MAX_CHARS_API.UID )}${expectedOffsetPartday}${domain}` ); expect(getFutureRecurrenceUID(`${chars180}${domain}`, new Date(Date.UTC(2000, 1, 1, 1, 1, 1)), true)).toBe( `${chars180.slice( chars180.length + expectedOffsetAllday.length + domain.length - MAX_CHARS_API.UID )}${expectedOffsetAllday}${domain}` ); }); it('should replace recurrence offset(s) for short uids with previous offsets', () => { // part-day -> part-day; single offset expect( getFutureRecurrenceUID( '6pG/5UGJGWB9O88ykIOCYx75cjUb_R22220202T020202@proton.me', new Date(Date.UTC(2000, 1, 1, 1, 1, 1)), false ) ).toBe('6pG/5UGJGWB9O88ykIOCYx75cjUb_R20000101T010101@proton.me'); // part-day -> all-day; single offset expect( getFutureRecurrenceUID( '6pG/5UGJGWB9O88ykIOCYx75cjUb_R22220202T020202@proton.me', new Date(Date.UTC(2000, 1, 1, 1, 1, 1)), true ) ).toBe('6pG/5UGJGWB9O88ykIOCYx75cjUb_R20000101@proton.me'); // all-day -> all-day; single offset expect( getFutureRecurrenceUID( '6pG/5UGJGWB9O88ykIOCYx75cjUb_R22220202@proton.me', new Date(Date.UTC(2000, 1, 1, 1, 1, 1)), true ) ).toBe('6pG/5UGJGWB9O88ykIOCYx75cjUb_R20000101@proton.me'); // all-day -> part-day; single offset expect( getFutureRecurrenceUID( '6pG/5UGJGWB9O88ykIOCYx75cjUb_R22220202@proton.me', new Date(Date.UTC(2000, 1, 1, 1, 1, 1)), false ) ).toBe('6pG/5UGJGWB9O88ykIOCYx75cjUb_R20000101T010101@proton.me'); // multiple part-day offsets expect( getFutureRecurrenceUID( '9O88ykIOCYx75cjUb_R22220202T020202_R33330303T030303', new Date(Date.UTC(1990, 8, 13, 13, 0, 15)), false ) ).toBe('9O88ykIOCYx75cjUb_R19900813T130015'); // multiple all-day offsets expect( getFutureRecurrenceUID( '9O88ykIOCYx75cjUb_R22220202_R33330303', new Date(Date.UTC(1990, 8, 13, 13, 0, 15)), true ) ).toBe('9O88ykIOCYx75cjUb_R19900813'); // multiple mixed offsets expect( getFutureRecurrenceUID( '9O@8@8yk_R22220202T020202_R33330303@google.com', new Date(Date.UTC(2000, 1, 1, 0, 0, 0)), false ) ).toBe('9O@8@8yk_R20000101T000000@google.com'); expect( getFutureRecurrenceUID( '9O@8@8yk_R22220202T020202_R33330303_R44440404T040404@google.com', new Date(Date.UTC(2000, 1, 1, 0, 0, 0)), true ) ).toBe('9O@8@8yk_R20000101@google.com'); expect( getFutureRecurrenceUID( '9O@8@8yk_R11110101_R22220202T020202_R33330303_R44440404T040404@google.com', new Date(Date.UTC(2000, 1, 1, 0, 0, 0)), false ) ).toBe('9O@8@8yk_R20000101T000000@google.com'); // multiple badly mixed offsets expect( getFutureRecurrenceUID( '9O_R44440404T040404@8@8yk_R22220202_R33330303T030303@google.com', new Date(Date.UTC(2000, 1, 1, 0, 0, 0)) ) ).toBe('9O_R44440404T040404@8@8yk_R20000101T000000@google.com'); }); it('should replace recurrence offset(s) for long uids with previous offset', () => { const chars180 = 'tenchars01tenchars02tenchars03tenchars04tenchars05tenchars06tenchars07tenchars08tenchars09tenchars10tenchars11tenchars12tenchars13tenchars14tenchars15tenchars16tenchars17tenchars18'; const domain = '@proton.me'; const expectedOffsetPartday = '_R20000101T010101'; const expectedOffsetAllday = '_R20000101'; expect( getFutureRecurrenceUID( `${chars180}_R22220202T020202_R33330303T030303${domain}`, new Date(Date.UTC(2000, 1, 1, 1, 1, 1)), false ) ).toBe( `${chars180.slice( chars180.length + expectedOffsetPartday.length + domain.length - MAX_CHARS_API.UID )}${expectedOffsetPartday}${domain}` ); expect( getFutureRecurrenceUID( `${chars180}_R22220202T020202_R33330303T030303${domain}`, new Date(Date.UTC(2000, 1, 1, 1, 1, 1)), true ) ).toBe( `${chars180.slice( chars180.length + expectedOffsetAllday.length + domain.length - MAX_CHARS_API.UID )}${expectedOffsetAllday}${domain}` ); // real-life examples expect( getFutureRecurrenceUID( 'pEZO1MmPI87KEexIjCGcHQVz4yP8_R20210828T000000_R20210829T000000_R20210830T000000_R20210901T000000_R20210902T000000_R20210903T000000_R20210905T000000_R20210906T000000_R20210907T000000@proton.me', new Date(Date.UTC(2000, 1, 1, 1, 1, 1)), false ) ).toBe('pEZO1MmPI87KEexIjCGcHQVz4yP8_R20000101T010101@proton.me'); expect( getFutureRecurrenceUID( '07e673fo4slrlb4tvaadrh0bjv_R20200720_R20200621T000000_R20200622T000000_R20200623T000000_R20200624T000000_R20200625T000000@google.com', new Date(Date.UTC(2000, 1, 1, 1, 1, 1)), true ) ).toBe('07e673fo4slrlb4tvaadrh0bjv_R20000101@google.com'); }); });
2,508
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/recurrence/createFutureRecurrence.ts
import { getSupportedUID } from '@proton/shared/lib/calendar/helper'; import {getIsAllDay} from '@proton/shared/lib/calendar/veventHelper'; import { omit } from '@proton/shared/lib/helpers/object'; import { VcalVeventComponent } from '@proton/shared/lib/interfaces/calendar/VcalModel'; import { CalendarEventRecurring } from '../../../interfaces/CalendarEvents'; import { getSafeRruleCount, getSafeRruleUntil } from './helper'; const getRecurrenceOffsetID = (date: Date, isAllDay: boolean) => { const dateString = [date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()] .map((n) => `${n}`.padStart(2, '0')) .join(''); const timeString = [date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds()] .map((n) => `${n}`.padStart(2, '0')) .join(''); return isAllDay ? `R${dateString}` : `R${dateString}T${timeString}`; }; const getComponentWithUpdatedRrule = ( component: VcalVeventComponent, originalComponent: VcalVeventComponent, recurrence: CalendarEventRecurring ): VcalVeventComponent => { const { rrule: originalRrule } = originalComponent; const { rrule: newRrule } = component; if (!originalRrule) { throw new Error('Original RRULE undefined'); } if (!newRrule) { return omit(component, ['rrule']); } // Count was not changed, so set a new count based on this occurrence if (newRrule.value.count && originalRrule.value.count === newRrule.value.count) { const newCount = newRrule.value.count - (recurrence.occurrenceNumber - 1); const safeRrule = getSafeRruleCount(newRrule, newCount); if (!safeRrule) { return omit(component, ['rrule']); } return { ...component, rrule: safeRrule }; } if (newRrule.value.until) { return { ...component, rrule: getSafeRruleUntil(newRrule, component), }; } return { ...component, rrule: newRrule, }; }; export const getFutureRecurrenceUID = (oldUID: string, localStart: Date, isAllDay: boolean) => { const offset = getRecurrenceOffsetID(localStart, isAllDay); const endIndex = oldUID.lastIndexOf('@'); const pre = endIndex === -1 ? oldUID : oldUID.slice(0, endIndex); const post = endIndex === -1 ? '' : oldUID.slice(endIndex); // we remove any possible previous recurrence offsets (we match our own type of offset) const cleanPre = pre.replace(/(?:_R\d{8}(?:T\d{6})?)+$/, ''); return getSupportedUID(`${cleanPre}_${offset}${post}`); }; const createFutureRecurrence = ( component: VcalVeventComponent, originalComponent: VcalVeventComponent, recurrence: CalendarEventRecurring ) => { const veventWithNewUID = { ...component, uid: { value: getFutureRecurrenceUID( originalComponent.uid.value, recurrence.localStart, getIsAllDay(originalComponent) ), }, }; const veventStripped = omit(veventWithNewUID, ['recurrence-id', 'exdate']); return getComponentWithUpdatedRrule(veventStripped, originalComponent, recurrence); }; export default createFutureRecurrence;
2,509
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/recurrence/createSingleRecurrence.ts
import { toExdate } from '@proton/shared/lib/calendar/exdate'; import { getPropertyTzid } from '@proton/shared/lib/calendar/vcalHelper'; import {getIsAllDay} from '@proton/shared/lib/calendar/veventHelper'; import { fromUTCDate } from '@proton/shared/lib/date/timezone'; import { omit } from '@proton/shared/lib/helpers/object'; import { VcalVeventComponent } from '@proton/shared/lib/interfaces/calendar/VcalModel'; const createSingleRecurrence = ( component: VcalVeventComponent, originalComponent: VcalVeventComponent, localStartToExclude: Date ): VcalVeventComponent => { const singleExdate = toExdate( fromUTCDate(localStartToExclude), getIsAllDay(originalComponent), getPropertyTzid(originalComponent.dtstart) ); const veventWithRecurrenceId = { ...component, 'recurrence-id': singleExdate, }; // Strip any RRULE when creating a single occurrence return omit(veventWithRecurrenceId, ['rrule', 'exdate']); }; export default createSingleRecurrence;
2,510
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/recurrence/deleteFutureRecurrence.ts
import { getUntilProperty } from '@proton/shared/lib/calendar/vcalConverter'; import { getIsPropertyAllDay, getPropertyTzid } from '@proton/shared/lib/calendar/vcalHelper'; import { addDays } from '@proton/shared/lib/date-fns-utc'; import { fromUTCDate } from '@proton/shared/lib/date/timezone'; import { omit } from '@proton/shared/lib/helpers/object'; import { VcalVeventComponent } from '@proton/shared/lib/interfaces/calendar/VcalModel'; import { getSafeRruleCount } from './helper'; const deleteFutureRecurrence = ( component: VcalVeventComponent, localStartToExclude: Date, occurrenceNumber: number ): VcalVeventComponent => { const { dtstart, rrule } = component; if (!rrule) { throw new Error('Trying to delete future recurrence of a non-recurring event'); } if (rrule.value.count) { const newCount = occurrenceNumber - 1; const safeRrule = getSafeRruleCount(rrule, newCount); if (!safeRrule) { return omit(component, ['rrule']); } return { ...component, rrule: safeRrule }; } // Subtract one day from the local start, and get until property which in the end yields the previous day at 23:59:59 const until = getUntilProperty( fromUTCDate(addDays(localStartToExclude, -1)), getIsPropertyAllDay(dtstart), getPropertyTzid(dtstart) ); return { ...component, rrule: { ...rrule, value: { ...rrule.value, until, }, }, }; }; export default deleteFutureRecurrence;
2,511
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/recurrence/deleteSingleRecurrence.ts
import { toExdate } from '@proton/shared/lib/calendar/exdate'; import { getIsPropertyAllDay, getPropertyTzid } from '@proton/shared/lib/calendar/vcalHelper'; import { fromUTCDate, toUTCDate } from '@proton/shared/lib/date/timezone'; import { VcalVeventComponent } from '@proton/shared/lib/interfaces/calendar/VcalModel'; import uniqueBy from '@proton/utils/uniqueBy'; const deleteSingleRecurrence = (component: VcalVeventComponent, localStartToExclude: Date) => { const { dtstart, exdate: oldExdate = [] } = component; const singleExdate = toExdate( fromUTCDate(localStartToExclude), getIsPropertyAllDay(dtstart), getPropertyTzid(dtstart) ); const newExdates = uniqueBy([...oldExdate, singleExdate], (property) => { return +toUTCDate(property.value); }).sort((a, b) => { return +toUTCDate(a.value) - +toUTCDate(b.value); }); return { ...component, exdate: newExdates, } as VcalVeventComponent; }; export default deleteSingleRecurrence;
2,512
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/recurrence/getDateTimeMerged.spec.js
import { getDateProperty, getDateTimeProperty } from '@proton/shared/lib/calendar/vcalConverter'; import { fromUTCDate } from '@proton/shared/lib/date/timezone'; import { getStartDateTimeMerged } from './getDateTimeMerged'; const d = (year = 2000, month = 1, date = 1, hours = 0, minutes = 0) => new Date(Date.UTC(year, month - 1, date, hours, minutes)); describe('merge date time', () => { it('should keep original start date', () => { const a = getDateProperty(fromUTCDate(d(2000, 1, 1))); const c = getDateTimeProperty(fromUTCDate(d(2000, 1, 3, 14, 30)), 'Europe/Zurich'); const r = getDateTimeProperty(fromUTCDate(d(2000, 1, 1, 14, 30)), 'Europe/Zurich'); expect(getStartDateTimeMerged(c, a)).toEqual(r); }); it('should keep original start date even if day was moved', () => { const a = getDateProperty(fromUTCDate(d(2000, 1, 1))); const c = getDateProperty(fromUTCDate(d(2000, 1, 4))); expect(getStartDateTimeMerged(c, a)).toEqual(getDateProperty(fromUTCDate(d(2000, 1, 1)))); }); it('should keep original start date-time', () => { const a = getDateTimeProperty(fromUTCDate(d(2000, 1, 1, 14, 30)), 'Europe/Zurich'); const c = getDateTimeProperty(fromUTCDate(d(2000, 1, 2, 12, 30)), 'Europe/Zurich'); const r = getDateTimeProperty(fromUTCDate(d(2000, 1, 1, 12, 30)), 'Europe/Zurich'); expect(getStartDateTimeMerged(c, a)).toEqual(r); }); it('should keep original start date-time', () => { const a = getDateTimeProperty(fromUTCDate(d(2000, 1, 1, 14, 30)), 'Europe/Madrid'); const c = getDateTimeProperty(fromUTCDate(d(2000, 1, 2, 12, 0)), 'UTC'); const r = getDateTimeProperty(fromUTCDate(d(2000, 1, 1, 12, 0)), 'UTC'); expect(getStartDateTimeMerged(c, a)).toEqual(r); }); });
2,513
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/recurrence/getDateTimeMerged.ts
import { getDateOrDateTimeProperty, getDateProperty, getDateTimeProperty, } from '@proton/shared/lib/calendar/vcalConverter'; import { getIsPropertyAllDay } from '@proton/shared/lib/calendar/vcalHelper'; import { toUTCDate } from '@proton/shared/lib/date/timezone'; import { VcalDateOrDateTimeProperty } from '@proton/shared/lib/interfaces/calendar/VcalModel'; export const getStartDateTimeMerged = ( newProperty: VcalDateOrDateTimeProperty, originalProperty: VcalDateOrDateTimeProperty ): VcalDateOrDateTimeProperty => { if (getIsPropertyAllDay(newProperty)) { return getDateProperty(originalProperty.value); } return getDateTimeProperty( { year: originalProperty.value.year, month: originalProperty.value.month, day: originalProperty.value.day, hours: newProperty.value.hours, minutes: newProperty.value.minutes, seconds: 0, }, newProperty.parameters?.tzid || 'UTC' ); }; export const getEndDateTimeMerged = ( newStartProperty: VcalDateOrDateTimeProperty, newEndProperty: VcalDateOrDateTimeProperty, originalStartProperty: VcalDateOrDateTimeProperty ): VcalDateOrDateTimeProperty => { const diff = +toUTCDate(newEndProperty.value) - +toUTCDate(newStartProperty.value); const newEnd = +toUTCDate(originalStartProperty.value) + diff; return getDateOrDateTimeProperty(newEndProperty, new Date(newEnd)); };
2,514
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/recurrence/helper.ts
import { getUntilProperty, propertyToUTCDate } from '@proton/shared/lib/calendar/vcalConverter'; import { getPropertyTzid } from '@proton/shared/lib/calendar/vcalHelper'; import {getIsAllDay} from '@proton/shared/lib/calendar/veventHelper'; import { toUTCDate } from '@proton/shared/lib/date/timezone'; import { VcalRruleProperty, VcalVeventComponent } from '@proton/shared/lib/interfaces/calendar/VcalModel'; export const getSafeRruleCount = (rrule: VcalRruleProperty, newCount: number) => { if (newCount < 1) { return; } return { ...rrule, value: { ...rrule.value, count: newCount, }, }; }; export const getSafeRruleUntil = (rrule: VcalRruleProperty, component: VcalVeventComponent) => { const { dtstart } = component; if (!rrule.value.until) { throw new Error('Until required'); } const originalUntilDateTime = toUTCDate(rrule.value.until); const newStartTime = propertyToUTCDate(dtstart); // If the event was moved after the until date, fixup the until if (newStartTime > originalUntilDateTime) { const until = getUntilProperty(dtstart.value, getIsAllDay(component), getPropertyTzid(dtstart)); return { ...rrule, value: { ...rrule.value, until, }, }; } return rrule; };
2,515
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/recurrence/updateAllRecurrence.spec.js
import { parse, serialize } from '@proton/shared/lib/calendar/vcal'; import { getDateOrDateTimeProperty } from '@proton/shared/lib/calendar/vcalConverter'; import { UpdateAllPossibilities } from '../eventActions/getRecurringUpdateAllPossibilities'; import updateAllRecurrence from './updateAllRecurrence'; const getRecurrence = (start, end) => { return { localStart: start, localEnd: end, }; }; const c = (component, start, end) => { return { ...component, dtstart: getDateOrDateTimeProperty(component.dtstart, start), ...(end && { dtend: getDateOrDateTimeProperty(component.dtend, end) }), }; }; const d = (year = 2000, month = 1, date = 1, hours = 0, minutes = 0) => new Date(Date.UTC(year, month - 1, date, hours, minutes)); const expectCompare = (component, str) => { expect(serialize(component).replace(/\r/g, '')).toBe(str); }; const ALL_DAY_COMPONENT = parse(`BEGIN:VEVENT UID:abc DTSTART;VALUE=DATE:20190812 DTEND;VALUE=DATE:20190813 SUMMARY:text RRULE:FREQ=DAILY END:VEVENT`); const PART_DAY_COMPONENT = parse(`BEGIN:VEVENT UID:abc DTSTART;TZID=Europe/Zurich:20190719T120000 DTEND:20190719T160000Z SUMMARY:text RRULE:FREQ=DAILY END:VEVENT`); describe('update all recurrence', () => { it('should keep original start date (all day)', () => { const newComponent = c(ALL_DAY_COMPONENT, d(2019, 8, 16), d(2019, 8, 17)); const recurrence = getRecurrence(d(2019, 8, 16), d(2019, 8, 16)); const updatedComponent = updateAllRecurrence({ component: newComponent, originalComponent: ALL_DAY_COMPONENT, recurrence, isSingleEdit: false, isInvitation: false, mode: UpdateAllPossibilities.KEEP_ORIGINAL_START_DATE_BUT_USE_TIME, }); expectCompare( updatedComponent, `BEGIN:VEVENT UID:abc DTSTART;VALUE=DATE:20190812 DTEND;VALUE=DATE:20190813 SUMMARY:text RRULE:FREQ=DAILY END:VEVENT` ); }); it('should use the new start date (all day)', () => { const newComponent = c(ALL_DAY_COMPONENT, d(2019, 8, 17), d(2019, 8, 18)); const recurrence = getRecurrence(d(2019, 8, 16), d(2019, 8, 16)); const updatedComponent = updateAllRecurrence({ component: newComponent, originalComponent: ALL_DAY_COMPONENT, recurrence, mode: UpdateAllPossibilities.USE_NEW_START_DATE, isSingleEdit: false, isInvitation: false, }); expectCompare( updatedComponent, `BEGIN:VEVENT UID:abc DTSTART;VALUE=DATE:20190817 DTEND;VALUE=DATE:20190818 SUMMARY:text RRULE:FREQ=DAILY END:VEVENT` ); }); it('should keep the old date (part day)', () => { const oldStart = d(2019, 7, 20, 12); const newStart = d(2019, 7, 20, 14); const oldEnd = d(2019, 7, 20, 18); const newComponent = c(PART_DAY_COMPONENT, newStart, oldEnd); const localEnd = d(2019, 7, 20, 16); const recurrence = getRecurrence(oldStart, localEnd); const updatedComponent = updateAllRecurrence({ component: newComponent, originalComponent: PART_DAY_COMPONENT, recurrence, isSingleEdit: false, isInvitation: false, mode: UpdateAllPossibilities.KEEP_ORIGINAL_START_DATE_BUT_USE_TIME, }); expectCompare( updatedComponent, `BEGIN:VEVENT UID:abc DTSTART;TZID=Europe/Zurich:20190719T140000 DTEND:20190719T180000Z SUMMARY:text RRULE:FREQ=DAILY END:VEVENT` ); }); it('should take the new date (all day -> part day)', () => { const newComponent = c(PART_DAY_COMPONENT, d(2019, 8, 16, 14), d(2019, 8, 16, 18)); const recurrence = getRecurrence(d(2019, 8, 16), d(2019, 8, 16)); const updatedComponent = updateAllRecurrence({ component: newComponent, originalComponent: ALL_DAY_COMPONENT, recurrence, isSingleEdit: false, isInvitation: false, mode: UpdateAllPossibilities.KEEP_ORIGINAL_START_DATE_BUT_USE_TIME, }); expectCompare( updatedComponent, `BEGIN:VEVENT UID:abc DTSTART;TZID=Europe/Zurich:20190812T140000 DTEND:20190812T180000Z SUMMARY:text RRULE:FREQ=DAILY END:VEVENT` ); }); });
2,516
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/recurrence/updateAllRecurrence.ts
import { getDtendProperty } from '@proton/shared/lib/calendar/vcalConverter'; import { omit } from '@proton/shared/lib/helpers/object'; import { VcalVeventComponent } from '@proton/shared/lib/interfaces/calendar/VcalModel'; import { UpdateAllPossibilities } from '../eventActions/getRecurringUpdateAllPossibilities'; import { getEndDateTimeMerged, getStartDateTimeMerged } from './getDateTimeMerged'; import { getSafeRruleUntil } from './helper'; const getComponentWithUpdatedRrule = (component: VcalVeventComponent) => { const { rrule } = component; if (!rrule) { return omit(component, ['rrule']); } // Otherwise it's using the original rrule and we'll set a safer until value just in case the event got moved if (rrule.value.until) { return { ...component, rrule: getSafeRruleUntil(rrule, component), }; } return { ...component, rrule, }; }; interface Arguments { component: VcalVeventComponent; originalComponent: VcalVeventComponent; mode: UpdateAllPossibilities; isSingleEdit: boolean; isAttendee: boolean; } const updateAllRecurrence = ({ component, originalComponent, mode, isAttendee }: Arguments): VcalVeventComponent => { // Have to set the old UID (this won't be necessary until we merge chains) const veventWithOldUID = { ...omit(component, ['recurrence-id']), uid: { value: originalComponent.uid.value }, } as VcalVeventComponent; if (mode === UpdateAllPossibilities.KEEP_SINGLE_EDITS || isAttendee) { return { ...veventWithOldUID, // If single edits are to be kept, the start time can not change, shouldn't get here if not but just to be sure dtstart: originalComponent.dtstart, dtend: getEndDateTimeMerged(component.dtstart, getDtendProperty(component), veventWithOldUID.dtstart), // Copy over the exdates, if any ...(originalComponent.exdate && { exdate: originalComponent.exdate }), }; } if (mode === UpdateAllPossibilities.KEEP_ORIGINAL_START_DATE_BUT_USE_TIME) { const mergedDtstart = getStartDateTimeMerged(component.dtstart, originalComponent.dtstart); return { // Time changed so remove the exdate ...omit(veventWithOldUID, ['exdate']), dtstart: mergedDtstart, dtend: getEndDateTimeMerged(component.dtstart, getDtendProperty(component), mergedDtstart), }; } // Date has changed here return getComponentWithUpdatedRrule(omit(veventWithOldUID, ['exdate'])); }; export default updateAllRecurrence;
2,517
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/recurrence/updateSingleRecurrence.ts
import { omit } from '@proton/shared/lib/helpers/object'; import { VcalVeventComponent } from '@proton/shared/lib/interfaces/calendar/VcalModel'; const updateSingleRecurrence = (component: VcalVeventComponent): VcalVeventComponent => { return omit(component, ['rrule', 'exdate']); }; export default updateSingleRecurrence;
2,518
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/search/CalendarSearch.tsx
import { useEffect, useRef, useState } from 'react'; import { generateUID, usePopperAnchor } from '@proton/components'; import { useEncryptedSearchLibrary } from '../../EncryptedSearchLibraryProvider'; import CalendarSearchActivation from './CalendarSearchActivation'; import CalendarSearchInput from './CalendarSearchInput'; import { useCalendarSearch } from './CalendarSearchProvider'; import SearchOverlay from './SearchOverlay'; import './SearchOverlay.scss'; interface Props { containerRef: HTMLDivElement | null; onSearch: () => void; onBackFromSearch: () => void; } const CalendarSearch = ({ containerRef, onSearch, onBackFromSearch }: Props) => { const searchRef = useRef<HTMLDivElement>(null); const [uid] = useState(generateUID('advanced-search-overlay')); const { anchorRef, isOpen, open, close } = usePopperAnchor<HTMLDivElement>(); const { cacheIndexedDB } = useEncryptedSearchLibrary(); const { searchParams, isEnabled, isActive: isSearchActive, loading, setIsSearching, setSearchInput, searchInput, } = useCalendarSearch(); const isSearchEnabled = isEnabled !== false; const handleCloseSearch = (e: MouseEvent | TouchEvent) => { // Close the overlay close(); const clickedOutsideSearch = searchRef.current && !searchRef.current.contains(e.target as Node); // Show regular calendar header when user is not searching for event results and clicking outside search if (!searchParams.keyword && clickedOutsideSearch) { setIsSearching(false); } }; const handleCloseOverlay = () => { close(); setIsSearching(false); }; useEffect(() => { void cacheIndexedDB(); }, []); useEffect(() => { if (!isOpen && !isSearchEnabled) { open(); } if (isOpen && isSearchEnabled) { close(); } }, [isOpen, isSearchEnabled]); useEffect(() => { if (!containerRef) { return; } containerRef.addEventListener('mousedown', handleCloseSearch, { passive: true }); containerRef.addEventListener('touchstart', handleCloseSearch, { passive: true }); return () => { containerRef.removeEventListener('mousedown', handleCloseSearch); containerRef.removeEventListener('touchstart', handleCloseSearch); }; }, [containerRef, handleCloseSearch]); return ( <> <CalendarSearchInput value={searchInput} setValue={setSearchInput} ref={anchorRef} onSearch={onSearch} onBack={onBackFromSearch} loading={loading} isSearchActive={isSearchActive} searchRef={searchRef} /> <SearchOverlay id={uid} isOpen={isOpen} anchorRef={anchorRef} onClose={handleCloseOverlay} disableFocusTrap> {!isSearchEnabled && <CalendarSearchActivation onClose={handleCloseOverlay} />} </SearchOverlay> </> ); }; export default CalendarSearch;
2,519
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/search/CalendarSearchActivation.tsx
import { useEffect } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { useEncryptedSearchLibrary } from '../../EncryptedSearchLibraryProvider'; import CalendarSearchProgress from './CalendarSearchProgress'; interface Props { onClose: () => void; } const CalendarSearchActivation = ({ onClose }: Props) => { const { isLibraryInitialized, enableEncryptedSearch, pauseMetadataIndexing, esIndexingProgressState, esStatus } = useEncryptedSearchLibrary(); const { esEnabled, isMetadataIndexingPaused, isConfigFromESDBLoaded } = esStatus; useEffect(() => { if (!isLibraryInitialized || !isConfigFromESDBLoaded || esEnabled) { return; } if (!isMetadataIndexingPaused) { void enableEncryptedSearch(); } }, [isLibraryInitialized, isMetadataIndexingPaused, isConfigFromESDBLoaded, esEnabled]); return ( <div className="px-6 py-4"> <h4 className="text-bold text-xl flex flex-justify-space-between flex-align-items-center flex-nowrap mb-4"> {c('Title').t`We're setting up Calendar search`} </h4> <div className="mb-4"> {c('Description').t`This can take a few minutes. Meanwhile, you can continue using Calendar as usual.`} </div> <CalendarSearchProgress esIndexingProgressState={esIndexingProgressState} isPaused={isMetadataIndexingPaused} /> <div className="flex flex-row-reverse flex-justify-space-between "> <Button shape="solid" color="norm" onClick={onClose}> {c('Action').t`Got it`} </Button> {esStatus.isMetadataIndexingPaused ? ( <Button shape="outline" color="weak" onClick={() => { void enableEncryptedSearch(); }} > {c('Action').t`Resume indexing`} </Button> ) : ( <Button shape="outline" color="weak" onClick={pauseMetadataIndexing}> {c('Action').t`Pause indexing`} </Button> )} </div> </div> ); }; export default CalendarSearchActivation;
2,520
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/search/CalendarSearchForm.tsx
import { Dispatch, SetStateAction } from 'react'; import { isAfter, isBefore } from 'date-fns'; import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { DateInput, Label, PrimaryButton } from '@proton/components/components'; import clsx from '@proton/utils/clsx'; import { useCalendarSearch } from './CalendarSearchProvider'; import { SearchModel } from './interface'; /** * TODO: Support searching in specific time range to turn this to false */ const HIDE_SEARCH_FORM = true; interface Props { model: SearchModel; isNarrow: boolean; showMore: boolean; canReset: boolean; updateModel: Dispatch<SetStateAction<SearchModel>>; toggleShowMore: () => void; } const CalendarSearchForm = ({ model, isNarrow, showMore, canReset, updateModel, toggleShowMore }: Props) => { const { loading } = useCalendarSearch(); return ( <> <div className="pt-4 px-5 pb-0"> {showMore && ( <> <div className="mt-4"> <Button className="mb-2 w-full md:w-auto" onClick={toggleShowMore} data-testid="advanced-search:show-less" title={c('Action').t`Show fewer search options`} > {c('Action').t`Fewer search options`} </Button> </div> <div className="mb-2 flex flex-justify-space-between on-mobile-flex-column"> <div className={clsx(['flex-item-fluid', isNarrow ? 'pr-0' : 'pr-4'])}> <Label className="advanced-search-label text-semibold" htmlFor="begin-date">{c('Label') .t`From`}</Label> <DateInput placeholder={c('Placeholder').t`Start date`} id="begin-date" data-testid="advanced-search:start-date" value={model.startDate} onChange={async (startDate) => { if (!model.endDate || !startDate || isBefore(startDate, model.endDate)) { updateModel({ ...model, startDate }); } }} /> </div> <div className="flex-item-fluid"> <Label className="advanced-search-label text-semibold" htmlFor="end-date">{c('Label') .t`To`}</Label> <DateInput placeholder={c('Placeholder').t`End date`} id="end-date" data-testid="advanced-search:end-date" value={model.endDate} onChange={(endDate) => (!model.startDate || !endDate || isAfter(endDate, model.startDate)) && updateModel({ ...model, endDate }) } /> </div> </div> </> )} </div> <div className="my-4 mx-5 flex flex-align-items-center flex-justify-space-between"> {!showMore && !HIDE_SEARCH_FORM && ( <Button data-testid="advanced-search:show-more" className="mb-2 w-full md:w-auto" onClick={toggleShowMore} title={c('Action').t`Show more search options`} > {c('Action').t`More search options`} </Button> )} <div className="ml-auto w-full md:w-auto"> {canReset ? ( <Button data-testid="advanced-search:reset" className="mb-2 w-full md:w-auto mr-4" type="reset" title={c('Action').t`Reset search form`} >{c('Action').t`Reset`}</Button> ) : null} <PrimaryButton data-testid="advanced-search:submit" type="submit" disabled={!model.keyword.trim()} className="mb-2 w-full md:w-auto" loading={loading} >{c('Action').t`Search`}</PrimaryButton> </div> </div> </> ); }; export default CalendarSearchForm;
2,521
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/search/CalendarSearchInput.spec.tsx
import { ComponentProps } from 'react'; import { render, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import SpotlightProvider from '@proton/components/components/spotlight/Provider'; import { mockUseSpotlightOnFeature } from '@proton/testing/index'; import CalendarSearchInput from './CalendarSearchInput'; const baseProps: ComponentProps<typeof CalendarSearchInput> = { value: '', setValue: jest.fn(), loading: false, onBack: jest.fn(), onSearch: jest.fn(), isSearchActive: true, }; const renderComponent = (props: ComponentProps<typeof CalendarSearchInput>) => { render( <SpotlightProvider> <CalendarSearchInput {...props} /> </SpotlightProvider> ); }; describe('CalendarSearchInput', () => { describe('when input is focused', () => { const onSpotlightClose = jest.fn(); beforeEach(() => { mockUseSpotlightOnFeature({ show: true, onClose: onSpotlightClose }); }); afterEach(() => { onSpotlightClose.mockClear(); }); it('should be focused on click', async () => { renderComponent({ ...baseProps }); const input = screen.getByRole('textbox'); await userEvent.click(input); await waitFor(() => { expect(input).toHaveFocus(); }); }); }); describe('when Search button is hit', () => { it('should open', async () => { const onSearch = jest.fn(); renderComponent({ ...baseProps, value: 'test', onSearch }); const button = screen.getByRole('button', { name: 'Search' }); await userEvent.click(button); await waitFor(() => { expect(onSearch).toHaveBeenCalledTimes(1); }); expect(onSearch).toHaveBeenCalledWith(); }); }); describe('when clear button is hit', () => { it('act clear search and open', async () => { const testValue = 'test value here'; renderComponent({ ...baseProps, value: testValue }); expect(screen.getByDisplayValue(testValue)); const button = screen.getByText('Clear'); await userEvent.click(button); await waitFor(() => { expect(screen.queryByText(testValue)).not.toBeInTheDocument(); }); }); }); });
2,522
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/search/CalendarSearchInput.tsx
import { FormEvent, KeyboardEvent, MouseEvent, Ref, RefObject, forwardRef, useEffect, useRef } from 'react'; import { c } from 'ttag'; import { Button, Input } from '@proton/atoms'; import { Icon } from '@proton/components/components/icon'; import { ToolbarButton } from '@proton/components/components/toolbar'; import { useCalendarSearch } from './CalendarSearchProvider'; interface Props { value: string; setValue: (value: string) => void; loading: boolean; onSearch: () => void; onBack: () => void; isSearchActive: boolean; searchRef?: RefObject<HTMLDivElement>; } const CalendarSearchInput = ( { value: inputValue, setValue, loading, onSearch, onBack, isSearchActive, searchRef }: Props, ref: Ref<HTMLDivElement> ) => { const { search, searchParams } = useCalendarSearch(); const inputRef = useRef<HTMLInputElement>(null); const placeholder = isSearchActive ? c('Placeholder').t`Search events` : c('Placeholder').t`Indexing...`; const trimmedKeyword = inputValue.trim(); const previousKeyword = searchParams.keyword; const cannotSearch = !trimmedKeyword || trimmedKeyword === previousKeyword || !isSearchActive || loading; const handleChange = (event: FormEvent<HTMLInputElement>) => { setValue(event.currentTarget.value); }; const handleClear = () => { setValue(''); inputRef.current?.focus(); }; const handleSearch = () => { if (cannotSearch) { return; } search({ keyword: inputValue.trim(), }); onSearch(); }; const handleOnKeyDown = (event: KeyboardEvent<HTMLInputElement>) => { if (event.key === 'Enter') { handleSearch(); event.preventDefault(); } if (event.key === 'Escape') { onBack(); event.preventDefault(); } }; const handleBack = (event: MouseEvent<HTMLButtonElement>) => { event.stopPropagation(); onBack(); }; useEffect(() => { // focus right after indexation if (isSearchActive) { inputRef.current?.focus(); } }, [isSearchActive]); return ( <> <ToolbarButton icon={<Icon name="arrow-left" alt={c('Action').t`Back`} />} className="mr-2" onClick={handleBack} /> <div className="flex flex-nowrap gap-2" ref={searchRef}> <div className="searchbox flex max-w-custom" role="search" style={{ '--max-w-custom': '22.5rem' }} ref={ref} > <div className="w-full m-auto"> <Input ref={inputRef} inputClassName="cursor-text" value={inputValue} placeholder={placeholder} onChange={handleChange} onKeyDown={handleOnKeyDown} onSubmit={handleSearch} data-testid="search-keyword" autoFocus disabled={!isSearchActive} prefix={ loading ? ( <Icon name="arrow-rotate-right" className="location-refresh-rotate" /> ) : ( <Icon name="magnifier" alt={c('Action').t`Search`} /> ) } suffix={ inputValue.length ? ( <Button type="button" shape="ghost" color="weak" size="small" className="rounded-sm" disabled={loading} title={c('Action').t`Clear search`} onClick={handleClear} data-testid="clear-button" > {c('Action').t`Clear`} </Button> ) : null } /> </div> </div> <Button type="submit" shape="solid" color="norm" onClick={handleSearch} disabled={cannotSearch} className="hidden md:inline-flex" >{c('Action').t`Search`}</Button> </div> </> ); }; export default forwardRef(CalendarSearchInput);
2,523
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/search/CalendarSearchProgress.tsx
import { c, msgid } from 'ttag'; import { Progress } from '@proton/components/components'; import { ESIndexingState } from '@proton/encrypted-search/lib'; import clsx from '@proton/utils/clsx'; const getProgressStatusText = ({ isEstimating, isPaused, current, total, }: { isEstimating: boolean; isPaused: boolean; current: number; total: number; }) => { if (isPaused) { return c('Info').t`Indexing paused`; } else if (isEstimating) { return c('Info').t`Estimating time remaining...`; } else { // translator: current is a number representing how many events have been indexed already, total is the total number of events in all user calendars return c('Info').t`Indexing events: ${current}/${total}`; } }; interface Props { esIndexingProgressState: ESIndexingState; isPaused?: boolean; } const CalendarSearchProgress = ({ esIndexingProgressState, isPaused = false }: Props) => { const { estimatedMinutes, totalIndexingItems, esProgress, currentProgressValue } = esIndexingProgressState; const isEstimating = estimatedMinutes === 0 && (totalIndexingItems === 0 || esProgress !== totalIndexingItems); const etaMessage = estimatedMinutes <= 1 ? c('Info').t`Estimated time remaining: Less than a minute` : // translator: the variable is a positive integer (written in digits) always strictly bigger than 1 c('Info').ngettext( msgid`Estimated time remaining: ${estimatedMinutes} minute`, `Estimated time remaining: ${estimatedMinutes} minutes`, estimatedMinutes ); const statusMessage = getProgressStatusText({ isEstimating, isPaused, current: esProgress, total: totalIndexingItems, }); return ( <div className="my-6 flex flex-column"> <span className="color-weak relative advanced-search-progress-status" aria-live="polite" aria-atomic="true"> {statusMessage} </span> <div className="flex flex-justify-space-between"> <Progress value={currentProgressValue} aria-describedby="timeRemaining" className={clsx(['my-2 flex-item-fluid', isPaused ? 'progress-bar--disabled' : undefined])} /> </div> <span id="timeRemaining" aria-live="polite" aria-atomic="true" className={clsx([ 'color-weak relative advanced-search-time-remaining', isEstimating ? 'visibility-hidden' : undefined, ])} > {etaMessage} </span> </div> ); }; export default CalendarSearchProgress;
2,524
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/search/CalendarSearchProvider.tsx
import {SimpleMap} from '@proton/shared/lib/interfaces'; import { MutableRefObject, ReactNode, createContext, useCallback, useContext, useEffect, useRef, useState, } from 'react'; import { useHistory } from 'react-router-dom'; import { ESItem } from '@proton/encrypted-search/lib'; import { useLoading } from '@proton/hooks'; import { VIEWS } from '@proton/shared/lib/calendar/constants'; import noop from '@proton/utils/noop'; import { extractSearchParameters, generatePathnameWithSearchParams } from '../../../helpers/encryptedSearch/esUtils'; import { ESCalendarContent, ESCalendarMetadata, ESCalendarSearchParams } from '../../../interfaces/encryptedSearch'; import { useEncryptedSearchLibrary } from '../../EncryptedSearchLibraryProvider'; import { fromUrlParams } from '../getUrlHelper'; import { VisualSearchItem } from './interface'; interface UseCalendarSearch { searchParams: ESCalendarSearchParams; items: ESItem<ESCalendarMetadata, ESCalendarContent>[]; recurrenceIDsMap: SimpleMap<number[]>; search: (params: ESCalendarSearchParams) => void; triggerSearch: () => void; hasSearchedCounter: number; openedSearchItem: VisualSearchItem | undefined; setOpenedSearchItem: (item: VisualSearchItem | undefined) => void; /** * the state `isSearching` determines if the UI displays: * * a search bar (if true) * * a magnifier button (if false) */ isSearching: boolean; setIsSearching: (isSearching: boolean) => void; lastNonSearchViewRef: MutableRefObject<VIEWS | undefined>; isEnabled?: boolean; isIndexing: boolean; isActive: boolean; disabled: boolean; loading: boolean; searchInput: string; setSearchInput: (search: string) => void; } const CalendarSearchContext = createContext<UseCalendarSearch>({ searchParams: {}, items: [], recurrenceIDsMap: {}, search: noop, triggerSearch: noop, openedSearchItem: undefined, setOpenedSearchItem: noop, isSearching: false, setIsSearching: noop, lastNonSearchViewRef: { current: undefined }, hasSearchedCounter: 0, isEnabled: undefined, isIndexing: false, isActive: false, disabled: true, loading: false, searchInput: '', setSearchInput: noop, }); export const useCalendarSearch = () => useContext(CalendarSearchContext); interface Props { children?: ReactNode; } const CalendarSearchProvider = ({ children }: Props) => { const history = useHistory(); const { isLibraryInitialized, encryptedSearch, recurrenceIDsMap, esStatus } = useEncryptedSearchLibrary(); const searchParams = extractSearchParameters(history.location); const keyword = searchParams?.keyword || ''; const lastNonSearchViewRef = useRef<VIEWS>(); const [hasSearchedCounter, setHasSearchedCounter] = useState(0); const [renderCounter, setRenderCounter] = useState(0); const isInitialSearching = fromUrlParams(history.location.pathname).view === VIEWS.SEARCH; const [isSearching, setIsSearching] = useState(isInitialSearching); const [loading, withLoading, setLoading] = useLoading(true); const [openedSearchItem, setOpenedSearchItem] = useState<VisualSearchItem>(); const [searchInput, setSearchInput] = useState(keyword); const { dbExists, isEnablingEncryptedSearch, esEnabled, isRefreshing, isMetadataIndexingPaused } = esStatus; const isIndexing = isEnablingEncryptedSearch || isRefreshing || isMetadataIndexingPaused; const isActive = dbExists && !isIndexing; const triggerSearch = useCallback(() => { return setRenderCounter((c) => c + 1); }, []); const search = ({ keyword, begin, end }: ESCalendarSearchParams) => { history.push( generatePathnameWithSearchParams(history.location, { keyword, begin: begin ? begin.toString() : undefined, end: end ? end.toString() : undefined, }) ); }; const [items, setItems] = useState<ESItem<ESCalendarMetadata, ESCalendarContent>[]>([]); useEffect(() => { if (!isLibraryInitialized) { return; } if (!keyword) { setLoading(false); return; } void withLoading( encryptedSearch((result) => { /** * We have to copy to a new reference because ES library mutates the initial one, and it prevents a normal rerendering */ setItems([...result]); }).then(() => { setHasSearchedCounter((c) => c + 1); }) ); }, [renderCounter, isLibraryInitialized, keyword]); const value = { searchParams, items, recurrenceIDsMap, search, triggerSearch, hasSearchedCounter, openedSearchItem, setOpenedSearchItem, isSearching, setIsSearching, lastNonSearchViewRef, isEnabled: isLibraryInitialized ? esEnabled : undefined, isIndexing, isActive, disabled: !isLibraryInitialized || !isActive, loading, searchInput, setSearchInput, }; return <CalendarSearchContext.Provider value={value}>{children}</CalendarSearchContext.Provider>; }; export default CalendarSearchProvider;
2,525
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/search/CalendarSearchView.tsx
import React, { MouseEvent, MutableRefObject, useCallback, useEffect, useMemo, useState } from 'react'; import { getYear, isSameYear, startOfDay } from 'date-fns'; import { c } from 'ttag'; import { Button } from '@proton/atoms/Button'; import { Icon } from '@proton/components/components'; import { SkeletonLoader } from '@proton/components/components/skeletonLoader'; import { IllustrationPlaceholder } from '@proton/components/containers'; import { CALENDAR_DISPLAY } from '@proton/shared/lib/calendar/constants'; import { SimpleMap } from '@proton/shared/lib/interfaces'; import { VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import noResultsImg from '@proton/styles/assets/img/illustrations/empty-search.svg'; import noop from '@proton/utils/noop'; import unique from '@proton/utils/unique'; import { OpenedMailEvent } from '../../../hooks/useGetOpenedMailEvents'; import getCalendarEventsCache from '../eventStore/cache/getCalendarEventsCache'; import upsertCalendarApiEventWithoutBlob from '../eventStore/cache/upsertCalendarApiEventWithoutBlobs'; import { CalendarsEventsCache, EventReadResult } from '../eventStore/interface'; import useCalendarsEventsReader from '../eventStore/useCalendarsEventsReader'; import { CalendarViewEvent, InteractiveState } from '../interface'; import { useCalendarSearch } from './CalendarSearchProvider'; import CalendarSearchViewDayEvents from './CalendarSearchViewDayEvents'; import CalendarSearchViewYearSeparator from './CalendarSearchViewYearSeparator'; import { VisualSearchItem } from './interface'; import { expandAndOrderItems, fillEmptyToday, getCalendarViewEventWithMetadata, getVisualSearchItems, groupItemsByDay, } from './searchHelpers'; import { useCalendarSearchPagination } from './useCalendarSearchPagination'; import './SearchView.scss'; const formatListWithAnd = (items: string[]) => { if (items.length <= 1) { return <i className="text-nowrap">{items[0]}</i>; } const firstItems = items.slice(0, items.length - 1).reduce((acc: React.JSX.Element[], cur: string) => { return acc.length ? [...acc, <span>{', '}</span>, <i className="text-nowrap">{cur}</i>] : [...acc, <i className="text-nowrap">{cur}</i>]; }, []); const lastItem = <i className="text-nowrap">{items[items.length - 1]}</i>; // translator: This is the list of the calendar with visibility turned off, used to warn the user when he gets no result on search but has some in hidden calendars return c('Info').jt`${firstItems} and ${lastItem}`; }; interface Props { calendars: VisualCalendar[]; calendarsEventsCacheRef: MutableRefObject<CalendarsEventsCache>; tzid: string; date: Date; now: Date; setTargetEventRef: (targetEvent: HTMLElement) => void; setInteractiveData: (state: InteractiveState) => void; getOpenedMailEvents: () => OpenedMailEvent[]; } const CalendarSearchView = ({ calendars, calendarsEventsCacheRef, tzid, date, now, setTargetEventRef, setInteractiveData, getOpenedMailEvents, }: Props) => { const [closestToDateRef, setClosestToDateRef] = useState<HTMLDivElement | null>(null); const { items, recurrenceIDsMap, loading } = useCalendarSearch(); const [calendarViewEvents, setCalendarViewEvents] = useState<CalendarViewEvent[]>([]); const calendarsMap = useMemo( () => calendars.reduce<SimpleMap<VisualCalendar>>((acc, calendar) => { acc[calendar.ID] = calendar; return acc; }, {}), [calendars] ); const [visibleItems, hiddenItems] = useMemo( () => items.reduce( ([visibleItems, hiddenItems]: [typeof items, typeof items], item) => { const calendarDisplay = calendarsMap[item.CalendarID]?.Display; if (calendarDisplay === CALENDAR_DISPLAY.VISIBLE) { visibleItems.push(item); } else if (calendarDisplay === CALENDAR_DISPLAY.HIDDEN) { hiddenItems.push(item); } return [visibleItems, hiddenItems]; }, [[], []] ), [items, calendarsMap] ); const shouldDisplayCalendarDisplayWarning = !visibleItems.length && !!hiddenItems.length; const hiddenWithItemsCalendarNames = useMemo( () => unique(hiddenItems.map((item) => calendarsMap[item.CalendarID]!.Name)), [hiddenItems, calendarsMap] ); const hiddenWithItemsCalendarList = formatListWithAnd(hiddenWithItemsCalendarNames); const visualItems = useMemo(() => { return getVisualSearchItems({ items: expandAndOrderItems(visibleItems, calendarsEventsCacheRef.current, recurrenceIDsMap, date), calendarsMap, tzid, date, }); }, [visibleItems, date]); useEffect(() => { closestToDateRef?.scrollIntoView(true); }, [closestToDateRef]); const loadPopoverContent = ( calendarID: string, eventID: string, { calendarViewEvent, eventReadResult, }: { calendarViewEvent: CalendarViewEvent; eventReadResult: EventReadResult } ) => { setInteractiveData({ searchData: { ...calendarViewEvent, data: { ...calendarViewEvent.data, eventReadResult, eventRecurrence: calendarViewEvent.data.eventRecurrence ? { ...calendarViewEvent.data.eventRecurrence, } : undefined, }, }, }); }; useCalendarsEventsReader({ calendarEvents: calendarViewEvents, calendarsEventsCacheRef, rerender: noop, getOpenedMailEvents, onEventRead: loadPopoverContent, forceDecryption: true, metadataOnly: false, }); const { setOpenedSearchItem } = useCalendarSearch(); // visualItems are sorted by StartTime, so we can paginate them directly without sorting them again const { items: paginatedItems, isNextEnabled, isPreviousEnabled, next, previous, } = useCalendarSearchPagination(visualItems, date); const handleClickSearchItem = useCallback( (e: MouseEvent<HTMLButtonElement>, item: VisualSearchItem) => { const calendarsEventsCache = calendarsEventsCacheRef.current; if (!calendarsEventsCache) { return; } const { calendars } = calendarsEventsCache; let calendarEventsCache = calendars[item.CalendarID]; if (!calendarEventsCache) { calendarEventsCache = getCalendarEventsCache(); calendarsEventsCache.calendars[item.CalendarID] = calendarEventsCache; } /** * Upsert event metadata in cache in case it's not there * * This is a bit of a hack to avoid modifying too much our current structure for reading events. * That structure is quite rigid: * 1/ First we insert the API calendar event (with or without blob data) in the cache. This is done by * useCalendarsEventFetcher or by the event loop. * 2/ Then we decrypt the cached events with useCalendarsEventReader * This hack plays the role of step 1 for events that appear in the list of results but were not fetched previously. */ upsertCalendarApiEventWithoutBlob(item, calendarEventsCache); const calendarViewEvent = getCalendarViewEventWithMetadata(item); setTargetEventRef(e.currentTarget); setOpenedSearchItem(item); // setting search data opens the popover, its content is loaded by useCalendarsEventsReader setInteractiveData({ searchData: calendarViewEvent, }); // trigger event reader setCalendarViewEvents([calendarViewEvent]); }, [setTargetEventRef, setOpenedSearchItem, setCalendarViewEvents] ); const maybeWithEmptyToday = useMemo(() => { const eventsGroupedByDay = groupItemsByDay(paginatedItems); return fillEmptyToday(eventsGroupedByDay, now); }, [paginatedItems]); if (loading) { return ( <div className="h-full w-full"> {/* Custom py to have the same height as normal state's header */} <div className="py-custom px-5 border-bottom border-weak" style={{ '--py-custom': '0.912rem' }}> <div className="h6"> <SkeletonLoader width="5em" index={0} /> </div> </div> <div className="p-12"> <div className="max-w-custom" style={{ '--max-w-custom': '22em' }}> <SkeletonLoader width="100%" index={1} /> <SkeletonLoader width="80%" index={2} className="mb-8" /> <SkeletonLoader width="100%" index={3} /> <SkeletonLoader width="90%" index={4} className="mb-8" /> <SkeletonLoader width="100%" index={5} /> <SkeletonLoader width="70%" index={6} /> </div> </div> </div> ); } const hasResults = Boolean(visualItems.length); return ( <div className="relative flex-no-min-children flex-column flex-nowrap flex-justify-start flex-align-items-start w-full h-full reset4print"> <div className="toolbar toolbar--heavy flex flex-nowrap flex-item-noshrink flex-align-items-center gap-2 no-print flex-justify-space-between py-1 pr-2 pl-4 w-full"> <h2 className="h6 text-semibold"> {hasResults ? c('esCalendar').t`Results` : c('esCalendar').t`No result`} </h2> {hasResults && ( <div> <Button color="weak" shape="ghost" size="small" className="mx-2" disabled={!isPreviousEnabled} onClick={previous} > {c('Action').t`Previous`} </Button> <Button color="weak" shape="ghost" size="small" className="mx-2" disabled={!isNextEnabled} onClick={next} > {c('Action').t`Next`} </Button> </div> )} </div> {hasResults ? ( <div className="w-full flex-item-fluid overflow-auto reset4print"> {maybeWithEmptyToday.reduce((acc: React.JSX.Element[], dailyEvents, index) => { const isEmptyDay = !dailyEvents.length; const utcStartDate = isEmptyDay ? startOfDay(new Date()) : dailyEvents[0]?.fakeUTCStartDate; const previousDailyEvents = maybeWithEmptyToday[index - 1]; const previousUtcStartDate = previousDailyEvents?.[0]?.fakeUTCStartDate ?? new Date(); const shouldDisplayYearSeparatorBeforeCurrentDay = !previousDailyEvents || !isSameYear(previousUtcStartDate, utcStartDate); const year = getYear(utcStartDate); return [ ...acc, ...(shouldDisplayYearSeparatorBeforeCurrentDay ? [<CalendarSearchViewYearSeparator key={`year_${year}`} year={year} />] : []), <CalendarSearchViewDayEvents key={utcStartDate.toString()} closestToDateRef={setClosestToDateRef} dailyEvents={dailyEvents} onClickSearchItem={handleClickSearchItem} />, ]; }, [])} </div> ) : ( <div className="flex flex-column w-full h-full"> {shouldDisplayCalendarDisplayWarning && ( <div className="bg-weak rounded m-2 px-4 py-2 flex"> <div className="flex-item-noshrink"> <Icon name="magnifier" className="mr-2" /> </div> <div className="flex-item-fluid pl-1"> { // translator: This is a warning displayed to the user when he gets no result on current search but has some in hidden calendars c('Info') .jt`Can't find the events you're looking for? Some events in hidden calendars match your query. To see those results, turn on visibility for ${hiddenWithItemsCalendarList}.` } </div> </div> )} <div className="flex flex-column flex-justify-center flex-align-items-center flex-item-grow w-full"> <IllustrationPlaceholder title={c('Info message').t`No results found`} url={noResultsImg} /> <div className="text-center"> {c('Info calendar search') .t`You can either update your search query or close search to go back to calendar views`} </div> </div> </div> )} </div> ); }; export default CalendarSearchView;
2,526
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/search/CalendarSearchViewDayEvents.spec.tsx
import { render, screen, waitFor, within } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { mockUseAddresses } from '@proton/testing/index'; import CalendarSearchViewDayEvents from './CalendarSearchViewDayEvents'; import { VisualSearchItem } from './interface'; const dailyEvents = [ { ID: 'z1atJaCep8olkfcWKkWxUz_t0wbXL6JXeVRZhSHD2JFjqz3xxKXVcNo4I-KdQCdxqAV_aAxuR4fASmIgTXfPzw==', CalendarID: 'ZJflPbyEpNUINXU4ES56y31KgmMO20zOzY6OB7gRCN_yLRY4YI-21AXCBBmUo-Sm2UFfHAx2GtTmQftN5bDNWA==', isAllDay: false, plusDaysToEnd: 0, Summary: 'Tataratatata', fakeUTCStartDate: new Date('2021-09-01T14:00:00.000Z'), fakeUTCEndDate: new Date('2021-09-01T14:30:00.000Z'), Organizer: { value: 'mailto:jovan@proton.me' }, visualCalendar: { Color: '#415DF0', }, }, { ID: 'sDg73oEngnm_5U7Wkl1V2ClOnND0xgY4GbicaN-0ZgrgDJfaKuvY1XdTORbb9Yy77DC7WzvH3sv6oT2lS1h80g==', CalendarID: 'ZJflPbyEpNUINXU4ES56y31KgmMO20zOzY6OB7gRCN_yLRY4YI-21AXCBBmUo-Sm2UFfHAx2GtTmQftN5bDNWA==', isAllDay: false, fakeUTCStartDate: new Date('2021-09-01T15:00:00.000Z'), fakeUTCEndDate: new Date('2021-09-01T15:30:00.000Z'), Summary: 'Testerere', plusDaysToEnd: 0, Organizer: { value: 'mailto:jovan@proton.me' }, visualCalendar: { Color: '#415DF0', }, }, ] as unknown as VisualSearchItem[]; describe('CalendarSearchViewDayEvents', () => { beforeEach(() => { mockUseAddresses(); }); const dummyRef = () => {}; it('should correctly displayed day events', () => { render( <CalendarSearchViewDayEvents dailyEvents={dailyEvents} onClickSearchItem={jest.fn()} closestToDateRef={dummyRef} /> ); expect(screen.getByText('1')); expect(screen.getByText('Wed, Sep 2021')); const events = screen.getAllByRole('button'); expect(events).toHaveLength(2); const [first, second] = events; // first event expect(within(first).getByText('2:00 PM - 2:30 PM')); expect(within(first).getByText('Tataratatata')); // first event expect(within(second).getByText('3:00 PM - 3:30 PM')); expect(within(second).getByText('Testerere')); }); describe('when the is no event', () => { const today = new Date('2023-07-17T13:30:00.000Z'); beforeEach(() => { jest.useFakeTimers(); jest.setSystemTime(today); }); afterEach(() => { jest.useRealTimers(); }); it('should correctly render empty today line', () => { render( <CalendarSearchViewDayEvents dailyEvents={[]} onClickSearchItem={jest.fn()} closestToDateRef={dummyRef} /> ); expect(screen.getByText('17')); expect(screen.getByText('Mon, Jul 2023')); }); it('should set `aria-current` attribute', () => { render( <CalendarSearchViewDayEvents dailyEvents={[]} onClickSearchItem={jest.fn()} closestToDateRef={dummyRef} /> ); expect(screen.getByTestId('month-day-block')).toHaveAttribute('aria-current', 'date'); }); }); describe('when user click on an event', () => { it('should call `onClickSearchItem`', async () => { const onClickSearchItem = jest.fn(); render( <CalendarSearchViewDayEvents dailyEvents={dailyEvents} onClickSearchItem={onClickSearchItem} closestToDateRef={dummyRef} /> ); const events = screen.getAllByRole('button'); const [first] = events; await userEvent.click(first); await waitFor(() => { expect(onClickSearchItem).toHaveBeenCalledTimes(1); }); // first callback argument is a react event expect(onClickSearchItem.mock.calls[0][1]).toStrictEqual(dailyEvents[0]); }); }); describe('when an event is cancelled', () => { it('should render event without striked text', () => { const cancelledEvent = { Status: 'CANCELLED', ID: 'sDg73oEngnm_5U7Wkl1V2ClOnND0xgY4GbicaN-0ZgrgDJfaKuvY1XdTORbb9Yy77DC7WzvH3sv6oT2lS1h80g==', CalendarID: 'ZJflPbyEpNUINXU4ES56y31KgmMO20zOzY6OB7gRCN_yLRY4YI-21AXCBBmUo-Sm2UFfHAx2GtTmQftN5bDNWA==', isAllDay: false, fakeUTCStartDate: new Date('2021-09-01T15:00:00.000Z'), fakeUTCEndDate: new Date('2021-09-01T15:30:00.000Z'), Summary: 'Testerere', plusDaysToEnd: 0, Organizer: { value: 'mailto:mike@proton.me' }, visualCalendar: { Color: '#415DF0', }, } as unknown as VisualSearchItem; render( <CalendarSearchViewDayEvents dailyEvents={[cancelledEvent]} onClickSearchItem={jest.fn()} closestToDateRef={dummyRef} /> ); const event = screen.getByRole('button'); expect(event).toBeInTheDocument(); expect(event).toHaveClass('text-strike'); }); }); describe('when an invite is unanswered', () => { it('should render event correct border', () => { const inviteEvent = { ID: 'z1atJaCep8olkfcWKkWxUz_t0wbXL6JXeVRZhSHD2JFjqz3xxKXVcNo4I-KdQCdxqAV_aAxuR4fASmIgTXfPzw==', CalendarID: 'ZJflPbyEpNUINXU4ES56y31KgmMO20zOzY6OB7gRCN_yLRY4YI-21AXCBBmUo-Sm2UFfHAx2GtTmQftN5bDNWA==', isAllDay: false, plusDaysToEnd: 0, Summary: 'Tataratatata', fakeUTCStartDate: new Date('2021-09-01T14:00:00.000Z'), fakeUTCEndDate: new Date('2021-09-01T14:30:00.000Z'), Organizer: { value: 'mailto:mike@proton.me' }, Attendees: [ { value: 'mailto:jovan@proton.me', parameters: { cn: 'jovan@proton.me', role: 'REQ-PARTICIPANT', rsvp: 'TRUE', partstat: 'NEEDS-ACTION', }, }, ], visualCalendar: { Color: '#415DF0', }, } as unknown as VisualSearchItem; render( <CalendarSearchViewDayEvents dailyEvents={[inviteEvent]} onClickSearchItem={jest.fn()} closestToDateRef={dummyRef} /> ); const event = screen.getByRole('button'); expect(event).toBeInTheDocument(); expect(event.firstChild).toHaveClass('isUnanswered'); }); }); });
2,527
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/search/CalendarSearchViewDayEvents.tsx
import React, { MouseEvent } from 'react'; import { isSameDay } from 'date-fns'; import { useAddresses } from '@proton/components/hooks'; import { getDisplayTitle } from '@proton/shared/lib/calendar/helper'; import { format as formatUTC } from '@proton/shared/lib/date-fns-utc'; import { dateLocale } from '@proton/shared/lib/i18n'; import clsx from '@proton/utils/clsx'; import { useCalendarSearch } from './CalendarSearchProvider'; import { getEventTraits } from './CalendarSearchViewDayEvents.utils'; import { VisualSearchItem } from './interface'; import { getEventsDayDateString, getTimeString } from './searchHelpers'; import './SearchView.scss'; interface Props { dailyEvents?: VisualSearchItem[]; onClickSearchItem?: (e: MouseEvent<HTMLButtonElement>, item: VisualSearchItem) => void; closestToDateRef: (element: HTMLDivElement | null) => void; } const CalendarSearchViewDayEvents = ({ dailyEvents = [], onClickSearchItem, closestToDateRef }: Props) => { const [addresses] = useAddresses(); const now = new Date(); const startDate = dailyEvents.length ? dailyEvents[0].fakeUTCStartDate : new Date(); const formattedDate = getEventsDayDateString(startDate); const day = formatUTC(startDate, 'd', { locale: dateLocale }); const isToday = isSameDay(now, startDate); // const isPast = isBefore(startDate, now); // might be used again const { openedSearchItem } = useCalendarSearch(); return ( <div className="flex flex-nowrap border-bottom border-weak search-result-line w-full px-4 py-2 on-tablet-flex-column" style={{ scrollPaddingTop: '5em' }} > <div data-testid="month-day-block" className="flex-no-min-children flex-item-noshrink flex-align-items-baseline search-month-day" aria-current={isToday ? `date` : undefined} > <div className="text-lg text-semibold text-center min-w-custom lg:min-w-custom mr-2" style={{ '--min-w-custom': '2rem', '--lg-min-w-custom': '5rem', }} > <span className="search-day-number rounded-sm p-1 inline-block">{day}</span> </div> <div className="color-weak min-w-custom" style={{ '--min-w-custom': '9em' }}> {formattedDate} </div> </div> {Boolean(dailyEvents.length) && ( <div className="flex-item-grow search-day flex flex-nowrap flex-column pl-7 lg:pl-0 mt-2 lg:mt-0"> {dailyEvents.map((event) => { const { UID, ID, CalendarID, visualCalendar, fakeUTCStartDate, fakeUTCEndDate, isAllDay, occurrenceNumber, plusDaysToEnd, Summary, isClosestToDate, } = event; const isOpen = ID === openedSearchItem?.ID && UID === openedSearchItem?.UID && CalendarID === openedSearchItem?.CalendarID && occurrenceNumber === openedSearchItem?.occurrenceNumber; const { isCancelled, isUnanswered } = getEventTraits(event, addresses); const timeString = getTimeString({ startDate: fakeUTCStartDate, endDate: fakeUTCEndDate, isAllDay, plusDaysToEnd, }); return ( <button type="button" key={`${CalendarID}-${ID}-${fakeUTCStartDate}`} className={clsx( 'flex flex-nowrap search-event-cell flex-align-items-center text-left relative interactive-pseudo w-full color-norm rounded-sm pl-1', isCancelled && 'text-strike', isOpen && 'bg-weak' )} onClick={(e) => onClickSearchItem?.(e, event)} > <span className={clsx( 'search-calendar-border flex-item-noshrink my-1', isUnanswered && 'isUnanswered' )} style={{ '--calendar-color': visualCalendar.Color }} /> <span className="flex-no-min-children flex-nowrap flex-item-fluid search-event-time-details on-tablet-flex-column" ref={isClosestToDate ? closestToDateRef : null} > <span className="min-w-custom pl-2 lg:pl-0 pr-2 search-event-time" style={{ '--min-w-custom': '14em' }} > {timeString} </span> <span className={clsx( 'text-ellipsis flex-item-fluid pl-2 lg:pl-0 search-event-summary text-bold' )} > {getDisplayTitle(Summary)} </span> </span> </button> ); })} </div> )} </div> ); }; export default CalendarSearchViewDayEvents;
2,528
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/search/CalendarSearchViewDayEvents.utils.tsx
import { ICAL_ATTENDEE_STATUS, ICAL_EVENT_STATUS } from '@proton/shared/lib/calendar/constants'; import { getSelfAddressData } from '@proton/shared/lib/calendar/deserialize'; import { getVeventStatus } from '@proton/shared/lib/calendar/vcalHelper'; import { Address } from '@proton/shared/lib/interfaces'; import { VisualSearchItem } from './interface'; export const getEventTraits = (event: VisualSearchItem, addresses: Address[]) => { const { Status, Attendees, Organizer } = event; const eventStatus = getVeventStatus({ status: { value: Status } }); const isCancelled = eventStatus === ICAL_EVENT_STATUS.CANCELLED; const { selfAttendeeIndex } = getSelfAddressData({ organizer: Organizer, attendees: Attendees, addresses, }); const selfAttendee = selfAttendeeIndex !== undefined && Attendees?.[selfAttendeeIndex]; if (eventStatus === ICAL_EVENT_STATUS.CONFIRMED && !!selfAttendee) { const partstat = selfAttendee.parameters?.partstat; return { isUnanswered: partstat === ICAL_ATTENDEE_STATUS.NEEDS_ACTION, isCancelled: partstat === ICAL_ATTENDEE_STATUS.DECLINED, }; } return { isCancelled }; };
2,529
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/search/CalendarSearchViewYearSeparator.spec.tsx
import { render, screen } from '@testing-library/react'; import CalendarSearchViewYearSeparator from './CalendarSearchViewYearSeparator'; describe('CalendarSearchViewYearSeparator', () => { it('should render line with correct year', () => { render(<CalendarSearchViewYearSeparator year={2023} />); expect(screen.getByRole('heading', { name: /2023/, level: 3 })); }); });
2,530
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/search/CalendarSearchViewYearSeparator.tsx
import React from 'react'; interface Props { year: number; } const CalendarSearchViewYearSeparator = ({ year }: Props) => { return ( <div className="border-bottom border-weak px-4 py-3"> <h3 className="text-rg text-no-bold">{year}</h3> </div> ); }; export default CalendarSearchViewYearSeparator;
2,531
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/search/SearchOverlay.scss
@use 'sass:math'; @import '~@proton/styles/scss/lib'; $searchoverlay-breakpoint: em(1000, 16); .overlay { --min-width: 0; --max-width: 100vw; --max-height: 100vh; position: fixed; z-index: $layer-modals; transform-origin: top center; color: var(--text-norm); animation: anime-dropdown-in 0.15s easing(ease-out-cubic) both; @keyframes anime-dropdown-in { from { opacity: 0; } to { opacity: 1; } } &.is-dropdown-out { animation-name: anime-dropdown-out; @keyframes anime-dropdown-out { from { opacity: 1; } to { opacity: 0; } } } @include media('<=#{$searchoverlay-breakpoint}') { inset: 0; display: flex; padding-block: 15%; padding-inline: 25%; overflow: hidden; flex-flow: column nowrap; justify-content: center; align-items: center; background-color: var(--backdrop-norm); } @include media('<=#{em(520, 16)}') { padding: 5%; } @include media('>#{$searchoverlay-breakpoint}') { inset-block-start: calc(var(--top) * 1px - 1px + var(--space-2)); /* stylelint-disable */ inset-inline-start: calc(var(--left) * 1px - 1px); /* stylelint-enable */ border-radius: calc(var(--border-radius) * 1px); box-shadow: var(--shadow-lifted); border: 1px solid var(--border-norm); background: var(--background-norm); } /* Backdrop button, meant to override 'autoClose' option on mobile */ &-backdrop { @include media('<=#{$searchoverlay-breakpoint}') { position: absolute; inset: 0; z-index: 0; display: block; inline-size: 100%; block-size: 100%; margin: 0; padding: 0; border: none; outline: none; background: none; } @include media('>#{$searchoverlay-breakpoint}') { display: none; } } /* Scrollable insides of the dropdown */ &-content { block-size: calc( var(--height) * 1px ); // The min size can't be greater than the remaining space when the dropdown is positioned min-inline-size: min(var(--min-width, 1.5em), var(--max-width-bounds)); min-block-size: min(var(--min-height, 1em), var(--max-height-bounds)); overflow: auto; border-radius: var(--border-radius-md); background-color: var(--background-norm); background-image: radial-gradient(farthest-side at 50% 0, var(--backdrop-norm), transparent), radial-gradient(farthest-side at 50% 100%, var(--backdrop-norm), transparent); background-position: 50% 0, 0 100%; background-size: calc(100% - #{rem(20)}) rem(3); background-repeat: no-repeat; @include media('<=#{$searchoverlay-breakpoint}') { position: relative; z-index: 1; inline-size: 100%; box-shadow: var(--shadow-lifted); transition: transform 0.1s ease-out; } @include media('>#{$searchoverlay-breakpoint}') { inline-size: calc(var(--width) * 1px); max-inline-size: var(--max-width, unset); max-block-size: var(--max-height, unset); min-inline-size: rem(340); } &::before, &::after { content: ''; position: relative; z-index: 1; display: block; block-size: rem(3); flex: 0 0 rem(3); background: var(--background-norm); } } }
2,532
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/search/SearchOverlay.tsx
import { AnimationEvent, CSSProperties, HTMLAttributes, MouseEvent as ReactMouseEvent, ReactNode, RefObject, useLayoutEffect, useRef, } from 'react'; import { c } from 'ttag'; import { HotkeyTuple, getCustomSizingClasses, useDropdownArrowNavigation, useFocusTrap, useHotkeys, useIsClosing, } from '@proton/components'; import { Portal } from '@proton/components/components/portal'; import clsx from '@proton/utils/clsx'; import noop from '@proton/utils/noop'; import { ADVANCED_SEARCH_OVERLAY_OPEN_EVENT } from '../../../components/calendar/interactions/constants'; interface ContentProps extends HTMLAttributes<HTMLDivElement> { ref?: RefObject<HTMLDivElement>; } interface Props extends HTMLAttributes<HTMLDivElement> { anchorRef: RefObject<HTMLElement>; children: ReactNode; className?: string; style?: CSSProperties; onClose?: (event?: ReactMouseEvent<HTMLDivElement> | Event) => void; onClosed?: () => void; onContextMenu?: (event: ReactMouseEvent<HTMLDivElement, MouseEvent>) => void; disableFocusTrap?: boolean; isOpen?: boolean; sameAnchorWidth?: boolean; offset?: number; autoClose?: boolean; contentProps?: ContentProps; disableDefaultArrowNavigation?: boolean; updatePositionOnDOMChange?: boolean; } const SearchOverlay = ({ anchorRef, children, className, style, onClose = noop, onClosed, onContextMenu = noop, isOpen = false, disableFocusTrap = false, sameAnchorWidth = false, contentProps, disableDefaultArrowNavigation = false, ...rest }: Props) => { const boundingRect = anchorRef.current?.getBoundingClientRect(); const rootRef = useRef<HTMLDivElement>(null); const contentRef = useRef<HTMLDivElement>(null); const anchorRectRef = useRef<DOMRect | undefined>(); const focusTrapProps = useFocusTrap({ rootRef, active: isOpen && !disableFocusTrap, enableInitialFocus: false }); const { shortcutHandlers: arrowNavigationShortcutHandlers } = useDropdownArrowNavigation({ rootRef, }); const defaultShortcutHandlers: HotkeyTuple = [ 'Escape', (e) => { e.stopPropagation(); onClose?.(); }, ]; const hotkeyTuples = disableDefaultArrowNavigation ? [defaultShortcutHandlers] : [...arrowNavigationShortcutHandlers, defaultShortcutHandlers]; useHotkeys(rootRef, hotkeyTuples, { dependencies: [isOpen, !disableDefaultArrowNavigation], }); useLayoutEffect(() => { if (!isOpen) { return; } document.dispatchEvent(new CustomEvent(ADVANCED_SEARCH_OVERLAY_OPEN_EVENT)); if (sameAnchorWidth) { anchorRectRef.current = anchorRef.current?.getBoundingClientRect(); } }, [isOpen]); const [isClosing, isClosed, setIsClosed] = useIsClosing(isOpen); const popperClassName = clsx(['overlay', isClosing && `is-dropdown-out`, className, 'no-outline']); if (isClosed && !isOpen) { return null; } const varPosition = { '--top': boundingRect?.bottom, '--left': boundingRect?.left, }; const varSize = { '--width': boundingRect?.width, }; const handleAnimationEnd = ({ animationName }: AnimationEvent) => { if (animationName.includes('anime-dropdown-out') && isClosing) { setIsClosed(); onClosed?.(); } }; const rootStyle = { ...style, ...varPosition, ...varSize, }; const contentStyle = { '--height-custom': 'auto' }; return ( <Portal> <div ref={rootRef} style={rootStyle} role="dialog" className={popperClassName} onAnimationEnd={handleAnimationEnd} onContextMenu={onContextMenu} data-testid="overlay-button" {...rest} {...focusTrapProps} > {/* Backdrop button, meant to override 'autoClose' option on mobile */} <div role="button" tabIndex={0} data-ignore-close="true" className="overlay-backdrop" title={c('Action').t`Close`} onClick={() => onClose()} > <span className="sr-only">{c('Action').t`Close`}</span> </div> <div ref={contentRef} style={contentStyle} {...contentProps} className={clsx(['overlay-content', getCustomSizingClasses(contentStyle), contentProps?.className])} > {children} </div> </div> </Portal> ); }; export default SearchOverlay;
2,533
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/search/SearchView.scss
@use 'sass:map'; @import '~@proton/styles/scss/lib'; // hardcoded media queries, need to be checked .search { &-result-line { border-block-end: 1px solid var(--border-weak); @include media('<=#{em(1000, 16)}') { border: 0; } } &-day-number { font-variant-numeric: tabular-nums; border: 1px solid transparent; min-inline-size: 2rem; [aria-current='date'] & { border-color: var(--primary); color: var(--primary); background-color: var(--interaction-default); } } &-month-day { margin-block-start: rem(1); } &-calendar-border { inline-size: rem(4); border-radius: rem(4); background-color: var(--calendar-color, transparent); margin-inline-end: rem(8); min-block-size: rem(28); &.isUnanswered { background-color: transparent; background-image: repeating-linear-gradient( -45deg, transparent, transparent rem(2), var(--calendar-color, transparent) rem(2), var(--calendar-color, transparent) rem(4) ); } @include media('<=#{em(1000, 16)}') { min-block-size: rem(44); } @include media('<=#{em(870, 16)}') { min-block-size: rem(34); } } &-event-time-details { @include media('<=#{em(870, 16)}') { line-height: 1.3; } } &-event-time, &-event-summary { @include media('<=#{em(870, 16)}') { font-size: rem(13); } } }
2,534
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/search/constants.ts
export const DEFAULT_MAX_ITEMS_PER_PAGE = 100; export const YEARS_TO_EXPAND_AHEAD = { YEARLY: 20, OTHER: 3, };
2,535
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/search/interface.ts
import { VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import { ESCalendarMetadata } from '../../../interfaces/encryptedSearch'; export type VisualSearchItem = ESCalendarMetadata & { visualCalendar: VisualCalendar; isAllDay: boolean; plusDaysToEnd: number; fakeUTCStartDate: Date; fakeUTCEndDate: Date; occurrenceNumber?: number; localStart?: Date; localEnd?: Date; isSingleOccurrence?: boolean; isClosestToDate?: boolean; }; export interface SearchModel { keyword: string; startDate?: Date; endDate?: Date; }
2,536
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/search/searchHelpers.spec.ts
import { getUnixTime } from 'date-fns'; import { ESItem } from '@proton/encrypted-search/lib'; import { MAXIMUM_DATE_UTC } from '@proton/shared/lib/calendar/constants'; import { SECOND } from '@proton/shared/lib/constants'; import { differenceInCalendarYears } from '@proton/shared/lib/date-fns-utc'; import { ESCalendarContent, ESCalendarMetadata } from '../../../interfaces/encryptedSearch'; import { YEARS_TO_EXPAND_AHEAD } from './constants'; import { expandSearchItem } from './searchHelpers'; describe('expandSearchItem()', () => { describe('expands until given date + expected number of years', () => { it('for daily events', () => { const item = { FullDay: 0, StartTime: getUnixTime(Date.UTC(2001, 1, 22, 9)), StartTimezone: 'America/New_York', EndTime: getUnixTime(Date.UTC(2001, 1, 22, 9, 30)), EndTimezone: 'America/New_York', RRule: 'FREQ=DAILY', RecurrenceID: null, Exdates: [] as number[], } as ESItem<ESCalendarMetadata, ESCalendarContent>; const date = new Date(Date.UTC(2023, 8, 7, 10)); const occurrences = expandSearchItem({ item, date }) as ESItem<ESCalendarMetadata, ESCalendarContent>[]; const lastOccurrenceUtcStart = new Date(occurrences[occurrences.length - 1].StartTime * SECOND); expect(differenceInCalendarYears(lastOccurrenceUtcStart, date)).toBe(YEARS_TO_EXPAND_AHEAD.OTHER); }); it('for weekly events with non-trivial recurring rule', () => { const item = { FullDay: 1, StartTime: getUnixTime(Date.UTC(2011, 5, 5)), StartTimezone: 'UTC', EndTime: getUnixTime(Date.UTC(2011, 5, 6)), EndTimezone: 'UTC', RRule: 'FREQ=WEEKLY;INTERVAL=2;BYDAY=MO,WE', RecurrenceID: null, Exdates: [] as number[], } as ESItem<ESCalendarMetadata, ESCalendarContent>; const date = new Date(Date.UTC(2023, 8, 7, 10)); const occurrences = expandSearchItem({ item, date }) as ESItem<ESCalendarMetadata, ESCalendarContent>[]; const lastOccurrenceUtcStart = new Date(occurrences[occurrences.length - 1].StartTime * SECOND); expect(differenceInCalendarYears(lastOccurrenceUtcStart, date)).toBe(YEARS_TO_EXPAND_AHEAD.OTHER); }); it('for monthly events with non-trivial recurring rule', () => { const item = { FullDay: 1, StartTime: getUnixTime(Date.UTC(2017, 9, 9)), StartTimezone: 'UTC', EndTime: getUnixTime(Date.UTC(2017, 9, 10)), EndTimezone: 'UTC', RRule: 'FREQ=MONTHLY;BYDAY=2SU', RecurrenceID: null, Exdates: [] as number[], } as ESItem<ESCalendarMetadata, ESCalendarContent>; const date = new Date(Date.UTC(2023, 8, 7, 10)); const occurrences = expandSearchItem({ item, date }) as ESItem<ESCalendarMetadata, ESCalendarContent>[]; const lastOccurrenceUtcStart = new Date(occurrences[occurrences.length - 1].StartTime * SECOND); expect(differenceInCalendarYears(lastOccurrenceUtcStart, date)).toBe(YEARS_TO_EXPAND_AHEAD.OTHER); }); it('for yearly events', () => { const item = { FullDay: 0, StartTime: getUnixTime(Date.UTC(1978, 4, 12, 23)), StartTimezone: 'Asia/Shanghai', EndTime: getUnixTime(Date.UTC(1978, 4, 13, 3, 30)), EndTimezone: 'Asia/Shanghai', RRule: 'FREQ=YEARLY', RecurrenceID: null, Exdates: [] as number[], } as ESItem<ESCalendarMetadata, ESCalendarContent>; const date = new Date(Date.UTC(2013, 8, 7, 10)); const occurrences = expandSearchItem({ item, date }) as ESItem<ESCalendarMetadata, ESCalendarContent>[]; const lastOccurrenceUtcStart = new Date(occurrences[occurrences.length - 1].StartTime * SECOND); expect(differenceInCalendarYears(lastOccurrenceUtcStart, date)).toBe(YEARS_TO_EXPAND_AHEAD.YEARLY); }); }); describe('caps the expansion at the maximum date', () => { it('for yearly events', () => { const item = { FullDay: 0, StartTime: getUnixTime(Date.UTC(1978, 4, 12, 23)), StartTimezone: 'Asia/Shanghai', EndTime: getUnixTime(Date.UTC(1978, 4, 13, 3, 30)), EndTimezone: 'Asia/Shanghai', RRule: 'FREQ=YEARLY', RecurrenceID: null, Exdates: [] as number[], } as ESItem<ESCalendarMetadata, ESCalendarContent>; const date = new Date(Date.UTC(2023, 8, 7, 10)); const occurrences = expandSearchItem({ item, date }) as ESItem<ESCalendarMetadata, ESCalendarContent>[]; const lastOccurrenceUtcStart = new Date(occurrences[occurrences.length - 1].StartTime * SECOND); expect(differenceInCalendarYears(lastOccurrenceUtcStart, date)).toBe( MAXIMUM_DATE_UTC.getUTCFullYear() - date.getUTCFullYear() ); }); }); describe('does not expand beyond number of occurrences', () => { it('for a weekly event', () => { const item = { FullDay: 0, StartTime: getUnixTime(Date.UTC(2022, 2, 2, 15)), StartTimezone: 'America/Sao_Paulo', EndTime: getUnixTime(Date.UTC(2022, 2, 2, 18)), EndTimezone: 'America/Sao_Paulo', RRule: 'FREQ=WEEKLY;INTERVAL=2;COUNT=10', RecurrenceID: null, Exdates: [] as number[], } as ESItem<ESCalendarMetadata, ESCalendarContent>; const date = new Date(Date.UTC(2023, 8, 7, 10)); const occurrences = expandSearchItem({ item, date }) as ESItem<ESCalendarMetadata, ESCalendarContent>[]; const lastOccurrenceUtcStart = new Date(occurrences[occurrences.length - 1].StartTime * SECOND); expect(occurrences.length).toBe(10); expect(lastOccurrenceUtcStart.getUTCFullYear()).toBe(2022); }); }); });
2,537
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/search/searchHelpers.ts
import { getUnixTime, isAfter, isBefore } from 'date-fns'; import { c, msgid } from 'ttag'; import { ESItem } from '@proton/encrypted-search/lib'; import { MAXIMUM_DATE_UTC } from '@proton/shared/lib/calendar/constants'; import { OccurrenceIterationCache, getOccurrencesBetween } from '@proton/shared/lib/calendar/recurrence/recurring'; import { propertyToUTCDate } from '@proton/shared/lib/calendar/vcalConverter'; import { DAY, SECOND } from '@proton/shared/lib/constants'; import { addDays as addUTCDays, addYears as addUTCYears, endOfDay as endOfUTCDay, format as formatUTC, isSameDay as isSameUTCDay, startOfDay as startOfUTCDay, } from '@proton/shared/lib/date-fns-utc'; import { formatIntlUTCDate } from '@proton/shared/lib/date-utc/formatIntlUTCDate'; import { convertTimestampToTimezone, toUTCDate } from '@proton/shared/lib/date/timezone'; import { pick } from '@proton/shared/lib/helpers/object'; import { dateLocale } from '@proton/shared/lib/i18n'; import { MaybeArray, SimpleMap } from '@proton/shared/lib/interfaces'; import { VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import groupWith from '@proton/utils/groupWith'; import isTruthy from '@proton/utils/isTruthy'; import { getEventKey } from '../../../helpers/encryptedSearch/esUtils'; import { generateEventUniqueId } from '../../../helpers/event'; import { ESCalendarContent, ESCalendarMetadata } from '../../../interfaces/encryptedSearch'; import { getCurrentEvent } from '../eventActions/recurringHelper'; import getComponentFromCalendarEventWithoutBlob from '../eventStore/cache/getComponentFromCalendarEventWithoutBlob'; import { CalendarsEventsCache } from '../eventStore/interface'; import { CalendarViewEvent } from '../interface'; import { YEARS_TO_EXPAND_AHEAD } from './constants'; import { VisualSearchItem } from './interface'; /** * Given a UNIX timestamp, convert it into a fake UTC date for a given time zone. * I.e. result.getUTC[DateTimeAttribute] should give the date-time attribute of the timestamp localized to that time zone */ const getFakeUTCDateFromTimestamp = (timestamp: number, isAllDay: boolean, tzid: string) => { return isAllDay ? new Date(timestamp * SECOND) : toUTCDate(convertTimestampToTimezone(timestamp, tzid)); }; const getVisualSearchItem = ({ item, calendarsMap, tzid, isClosestToDate, }: { item: ESItem<ESCalendarMetadata, ESCalendarContent>; calendarsMap: SimpleMap<VisualCalendar>; tzid: string; isClosestToDate: boolean; }): VisualSearchItem | undefined => { const { CalendarID, StartTime, EndTime, FullDay } = item; const calendar = calendarsMap[CalendarID]; if (!calendar) { return; } const isAllDay = !!FullDay; const fakeUTCStartDate = getFakeUTCDateFromTimestamp(StartTime, isAllDay, tzid); const fakeUTCEndDate = getFakeUTCDateFromTimestamp(EndTime, isAllDay, tzid); const plusDaysToEnd = Math.floor((+endOfUTCDay(fakeUTCEndDate) - +endOfUTCDay(fakeUTCStartDate)) / DAY); return { ...item, isAllDay, plusDaysToEnd, isClosestToDate, visualCalendar: calendar, fakeUTCStartDate, fakeUTCEndDate, }; }; const getClosestToDateIndex = (date: Date, items: ESItem<ESCalendarMetadata, ESCalendarContent>[]) => { const dateTimestamp = getUnixTime(date); /** * Closest event before date */ const lowClosestToDateIndex = items.findLastIndex( ({ StartTime, EndTime }) => StartTime <= dateTimestamp || EndTime <= dateTimestamp ); /** * Closest event after date */ const highClosestToDateIndex = items.findIndex( ({ StartTime, EndTime }) => StartTime >= dateTimestamp || EndTime >= dateTimestamp ); const lowStartTime = items[lowClosestToDateIndex]?.StartTime; const highStartTime = items[highClosestToDateIndex]?.StartTime; if (!highStartTime) { return lowClosestToDateIndex; } if (!lowStartTime) { return highClosestToDateIndex; } return dateTimestamp - lowStartTime <= dateTimestamp - highStartTime ? lowClosestToDateIndex : highClosestToDateIndex; }; export const getVisualSearchItems = ({ items, calendarsMap, tzid, date, }: { items: ESItem<ESCalendarMetadata, ESCalendarContent>[]; calendarsMap: SimpleMap<VisualCalendar>; tzid: string; date: Date; }) => { const closestToDateIndex = getClosestToDateIndex(date, items); return items .map((item, index) => getVisualSearchItem({ item, calendarsMap, tzid, isClosestToDate: closestToDateIndex === index }) ) .filter(isTruthy); }; export const expandSearchItem = ({ item, date, cache = {}, recurrenceIDs, }: { item: ESItem<ESCalendarMetadata, ESCalendarContent>; date: Date; cache?: Partial<OccurrenceIterationCache>; recurrenceIDs?: number[]; }): MaybeArray<ESItem<ESCalendarMetadata, ESCalendarContent> | undefined> => { try { if (!item.RRule) { return item; } const component = getComponentFromCalendarEventWithoutBlob(item); // we expand three years ahead of passed date, unless it's a yearly event, in which case we expand 20 years ahead const yearsToExpand = item.RRule.includes('FREQ=YEARLY') ? YEARS_TO_EXPAND_AHEAD.YEARLY : YEARS_TO_EXPAND_AHEAD.OTHER; const untilDate = addUTCYears(date, yearsToExpand); // don't expand beyond the maximum date supported in the calendar const cappedUntilTime = Math.min(+untilDate, +MAXIMUM_DATE_UTC); const occurrences = getOccurrencesBetween(component, item.StartTime * SECOND, +cappedUntilTime, cache); const isSingleOccurrence = occurrences.length === 1; return occurrences.map((recurrence) => { const { dtstart, dtend } = getCurrentEvent(component, recurrence); const { localStart, localEnd, occurrenceNumber } = recurrence; const startTime = getUnixTime(propertyToUTCDate(dtstart)); if (recurrenceIDs?.includes(startTime)) { return; } return { ...item, StartTime: getUnixTime(propertyToUTCDate(dtstart)), EndTime: getUnixTime(propertyToUTCDate(dtend)), occurrenceNumber, localStart, localEnd, isSingleOccurrence, }; }); } catch (e: any) { // ignore events that fail to be expanded console.warn(e); } }; export const expandAndOrderItems = ( items: ESItem<ESCalendarMetadata, ESCalendarContent>[], calendarsEventsCache: CalendarsEventsCache, recurrenceIDsMap: SimpleMap<number[]>, date: Date ) => { const expanded = items .map((item) => { const { CalendarID, UID } = item; const recurringEvents = calendarsEventsCache.calendars[CalendarID]?.recurringEvents; const { cache } = recurringEvents?.get(UID) || {}; const recurrenceIDs = recurrenceIDsMap[getEventKey(CalendarID, UID)]; return expandSearchItem({ item, date, cache, recurrenceIDs }); }) .flat() .filter(isTruthy); return expanded.sort(({ StartTime: startA }, { StartTime: startB }) => { return startA - startB; }); }; export const groupItemsByDay = (items: VisualSearchItem[]) => { return groupWith<VisualSearchItem>((a, b) => isSameUTCDay(a.fakeUTCStartDate, b.fakeUTCStartDate), items); }; export const getCalendarViewEventWithMetadata = (item: VisualSearchItem): CalendarViewEvent => { const { CalendarID, ID, visualCalendar, fakeUTCStartDate, fakeUTCEndDate, isAllDay, occurrenceNumber, localStart, localEnd, isSingleOccurrence, } = item; const result: CalendarViewEvent = { uniqueId: generateEventUniqueId(CalendarID, ID), start: fakeUTCStartDate, end: isAllDay ? addUTCDays(fakeUTCEndDate, -1) : fakeUTCEndDate, isAllDay, isAllPartDay: false, data: { calendarData: visualCalendar, eventData: pick(item, [ 'ID', 'SharedEventID', 'CalendarID', 'CreateTime', 'ModifyTime', 'Permissions', 'IsOrganizer', 'IsProtonProtonInvite', 'Author', ]), }, }; if ( occurrenceNumber !== undefined && localStart !== undefined && localEnd !== undefined && isSingleOccurrence !== undefined ) { result.data.eventRecurrence = { occurrenceNumber, localStart, localEnd, isSingleOccurrence, }; } return result; }; export const getTimeString = ({ startDate, endDate, isAllDay, plusDaysToEnd, }: { startDate: Date; endDate: Date; isAllDay: boolean; plusDaysToEnd: number; }) => { if (isAllDay) { if (plusDaysToEnd <= 1) { return c('Event info in search view; event duration').t`All day`; } // translator: the variable plusDaysToEnd is a numeric value for the duration of the event in days return c('Event info in search view; event duration').ngettext( msgid`All day, lasts ${plusDaysToEnd} day`, `All day, lasts ${plusDaysToEnd} days`, plusDaysToEnd ); } const formattedStartTime = formatUTC(startDate, 'p', { locale: dateLocale }); const formattedEndTime = formatUTC(endDate, 'p', { locale: dateLocale }); return plusDaysToEnd === 0 ? `${formattedStartTime} - ${formattedEndTime}` : `${formattedStartTime} - ${formattedEndTime} (+${plusDaysToEnd})`; }; export const getEventsDayDateString = (date: Date) => { const formattedMonthYear = formatIntlUTCDate(date, { month: 'short', year: 'numeric', }); const shortWeekDay = formatUTC(date, 'ccc'); return `${shortWeekDay}, ${formattedMonthYear}`; }; /** * Used to know in which position append empty today, returns either 0 or 1: * * - 0: empty today should not be displayed (because there are events today) * - 1: empty today should be placed after current day (either because today is between current & next day or there is no next day) */ const getEmptyTodayPosition = ({ currentStartDate, nextStartDate, now, }: { currentStartDate: Date; now: Date; nextStartDate?: Date; }): number => { return +Boolean( isAfter(startOfUTCDay(now), startOfUTCDay(currentStartDate)) && nextStartDate && isBefore(startOfUTCDay(now), startOfUTCDay(nextStartDate)) ); }; /** * If `today` has no event, we'll add an empty group */ export const fillEmptyToday = (eventsGroupedByDay: VisualSearchItem[][], now: Date) => { return eventsGroupedByDay.reduce((acc: VisualSearchItem[][], currentDayEvents, index) => { const [{ fakeUTCStartDate }] = eventsGroupedByDay[index]; const nextDailyEvents = eventsGroupedByDay[index + 1]; const emptyTodayPosition = getEmptyTodayPosition({ currentStartDate: fakeUTCStartDate, nextStartDate: nextDailyEvents?.[0]?.fakeUTCStartDate, now, }); const withMaybeEmptyToday = [currentDayEvents]; if (emptyTodayPosition === -1) { withMaybeEmptyToday.unshift([]); } else if (emptyTodayPosition === 1) { withMaybeEmptyToday.push([]); } return [...acc, ...withMaybeEmptyToday]; }, []); };
2,538
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/search/useCalendarSearchPagination.spec.ts
import { useHistory } from 'react-router-dom'; import { act, renderHook } from '@testing-library/react-hooks'; import { mockUseHistory } from '@proton/testing/index'; import { DEFAULT_MAX_ITEMS_PER_PAGE } from './constants'; import { VisualSearchItem } from './interface'; import { useCalendarSearchPagination } from './useCalendarSearchPagination'; const generateTestVisualItem = (index: number, isClosestToDate = false) => { return { UID: index.toString(), isClosestToDate } as VisualSearchItem; }; describe('useCalendarSearchPagination', () => { let mockHistoryPush: jest.MockedFn<ReturnType<typeof useHistory>['push']>; const array = new Array(2 * DEFAULT_MAX_ITEMS_PER_PAGE + 2) .fill(null) .map((_, index) => generateTestVisualItem(index)); const arrayWithClosestToDate = new Array(2 * DEFAULT_MAX_ITEMS_PER_PAGE + 2) .fill(null) .map((_, index) => generateTestVisualItem(index, index === DEFAULT_MAX_ITEMS_PER_PAGE + 2)); const dummyDate = new Date(); beforeEach(() => { mockHistoryPush = jest.fn(); mockUseHistory({ push: mockHistoryPush }); }); describe('when no maxItemsPerPage is provided', () => { it('should return 100 first items', () => { const { result } = renderHook(() => useCalendarSearchPagination(array, dummyDate)); expect(result.current.items).toStrictEqual( Array(DEFAULT_MAX_ITEMS_PER_PAGE) .fill(null) .map((_, index) => generateTestVisualItem(index)) ); // there is more than 100 remaining items => enable next expect(result.current.isNextEnabled).toBe(true); }); it('should handle `next` pagination', () => { const { result } = renderHook(() => useCalendarSearchPagination(array, dummyDate)); act(() => result.current.next()); expect(result.current.currentPage).toBe(1); expect(result.current.items).toStrictEqual( Array(DEFAULT_MAX_ITEMS_PER_PAGE) .fill(null) .map((_, index) => generateTestVisualItem(DEFAULT_MAX_ITEMS_PER_PAGE + index)) ); // new page has been written to query string expect(mockHistoryPush).toHaveBeenCalledTimes(1); expect(mockHistoryPush).toHaveBeenCalledWith('/search#page=1'); // there is more than 100 remaining items => enable next expect(result.current.isNextEnabled).toBe(true); mockHistoryPush.mockClear(); act(() => result.current.next()); expect(result.current.currentPage).toBe(2); expect(result.current.items).toStrictEqual( Array(2) .fill(null) .map((_, index) => generateTestVisualItem(2 * DEFAULT_MAX_ITEMS_PER_PAGE + index)) ); // new page has been written to query string expect(mockHistoryPush).toHaveBeenCalledTimes(1); expect(mockHistoryPush).toHaveBeenCalledWith('/search#page=2'); // there isn't more than 100 remaining items => disable next expect(result.current.isNextEnabled).toBe(false); }); it('should handle `previous` pagination', () => { const { result } = renderHook(() => useCalendarSearchPagination(array, dummyDate)); // current page is first one => disable previous expect(result.current.isPreviousEnabled).toBe(false); // go to last page act(() => result.current.next()); act(() => result.current.next()); mockHistoryPush.mockClear(); expect(result.current.currentPage).toBe(2); expect(result.current.items).toStrictEqual( Array(2) .fill(null) .map((_, index) => generateTestVisualItem(2 * DEFAULT_MAX_ITEMS_PER_PAGE + index)) ); // current page is not first one => enable previous expect(result.current.isPreviousEnabled).toBe(true); act(() => result.current.previous()); expect(result.current.currentPage).toBe(1); expect(result.current.items).toStrictEqual( Array(DEFAULT_MAX_ITEMS_PER_PAGE) .fill(null) .map((_, index) => generateTestVisualItem(DEFAULT_MAX_ITEMS_PER_PAGE + index)) ); // new page has been written to query string expect(mockHistoryPush).toHaveBeenCalledTimes(1); expect(mockHistoryPush).toHaveBeenCalledWith('/search#page=1'); // current page is still not first one => enable previous expect(result.current.isPreviousEnabled).toBe(true); mockHistoryPush.mockClear(); act(() => result.current.previous()); // current page is back to first one => disable previous expect(result.current.isPreviousEnabled).toBe(false); expect(result.current.currentPage).toBe(0); // new page has been written to query string expect(mockHistoryPush).toHaveBeenCalledTimes(1); expect(mockHistoryPush).toHaveBeenCalledWith('/search'); }); }); describe('when maxItemsPerPage is provided', () => { it('should return `maxItemsPerPage` first items', () => { const { result } = renderHook(() => useCalendarSearchPagination(array, dummyDate, 40)); expect(result.current.items).toStrictEqual( Array(40) .fill(null) .map((_, index) => generateTestVisualItem(index)) ); // there is more than 100 remaining items => enable next expect(result.current.isNextEnabled).toBe(true); }); it('should increment pagination by `maxItemsPerPage`', () => { const { result } = renderHook(() => useCalendarSearchPagination(array, dummyDate, 40)); act(() => result.current.next()); expect(result.current.items).toStrictEqual( Array(40) .fill(null) .map((_, index) => generateTestVisualItem(40 + index)) ); }); it('should decrement pagination by `maxItemsPerPage`', () => { const { result } = renderHook(() => useCalendarSearchPagination(array, dummyDate, 40)); act(() => result.current.next()); act(() => result.current.previous()); expect(result.current.items).toStrictEqual( Array(40) .fill(null) .map((_, index) => generateTestVisualItem(index)) ); }); }); describe('when an item is marked as closest to date', () => { it('should return the page with the item closest to date', () => { const { result } = renderHook(() => useCalendarSearchPagination(arrayWithClosestToDate, dummyDate)); expect(result.current.items).toStrictEqual( Array(DEFAULT_MAX_ITEMS_PER_PAGE) .fill(null) .map((_, index) => generateTestVisualItem(DEFAULT_MAX_ITEMS_PER_PAGE + index, index === 2)) ); // there is more than 100 remaining items => enable next expect(result.current.isNextEnabled).toBe(true); }); }); });
2,539
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/calendar/search/useCalendarSearchPagination.ts
import { useEffect, useMemo, useRef, useState } from 'react'; import { useHistory } from 'react-router-dom'; import { extractSearchParameters, generatePathnameWithSearchParams, parseSearchParams, } from '../../../helpers/encryptedSearch/esUtils'; import { DEFAULT_MAX_ITEMS_PER_PAGE } from './constants'; import { VisualSearchItem } from './interface'; const getInitialPage = (items: VisualSearchItem[], maxItemsPerPage = DEFAULT_MAX_ITEMS_PER_PAGE) => { const index = items.findIndex(({ isClosestToDate }) => isClosestToDate); return index === -1 ? 0 : Math.floor(index / maxItemsPerPage); }; export const useCalendarSearchPagination = ( items: VisualSearchItem[], date: Date, maxItemsPerPage = DEFAULT_MAX_ITEMS_PER_PAGE ) => { const history = useHistory(); const isFirstRenderRef = useRef(true); const [currentPage, setCurrentPage] = useState(getInitialPage(items, maxItemsPerPage)); const maxPage = Math.floor(items.length / maxItemsPerPage); const isPreviousEnabled = currentPage > 0; const isNextEnabled = currentPage < maxPage; const setPage = (page: number) => { setCurrentPage(page); const searchParams = extractSearchParameters(history.location); history.push( generatePathnameWithSearchParams(history.location, { keyword: searchParams.keyword, begin: searchParams.begin ? String(searchParams.begin) : undefined, end: searchParams.end ? String(searchParams.end) : undefined, ...(!!page && { page: page.toString() }), }) ); }; useEffect(() => { const { esSearchParams } = parseSearchParams(history.location); if (esSearchParams?.page) { setCurrentPage(esSearchParams?.page); } }, [history.location]); useEffect(() => { /** * This useEffect is in charge of setting the page that contains the closest item to the selected date in case * the selected date gets changed. */ if (isFirstRenderRef.current) { // no need to do anything isFirstRenderRef.current = false; return; } const { keyword, begin, end, page } = extractSearchParameters(history.location); if (page !== undefined) { // If a page was visible, we will remove it because the user is now navigating by selected date (and not by page) history.push( generatePathnameWithSearchParams(history.location, { keyword, begin: begin ? String(begin) : undefined, end: end ? String(end) : undefined, }) ); } setCurrentPage(getInitialPage(items, maxItemsPerPage)); }, [items, date]); const paginatedItems = useMemo( () => items.slice(currentPage * maxItemsPerPage, (currentPage + 1) * maxItemsPerPage), [items, currentPage, maxItemsPerPage] ); return { currentPage, first: () => setPage(0), previous: () => setPage(isPreviousEnabled ? currentPage - 1 : currentPage), next: () => setPage(isNextEnabled ? currentPage + 1 : currentPage), items: paginatedItems, isPreviousEnabled, isNextEnabled, }; };
2,540
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/settings/AskUpdateTimezoneModal.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Button } from '@proton/atoms'; import { Checkbox, Prompt, useApi, useCalendarUserSettings, useEventManager, useNotifications, } from '@proton/components'; import { useLoading } from '@proton/hooks'; import { updateCalendarUserSettings } from '@proton/shared/lib/api/calendars'; interface Props { localTzid: string; onClose?: () => void; isOpen: boolean; } const AskUpdateTimezoneModal = ({ localTzid, onClose, isOpen }: Props) => { const api = useApi(); const { call } = useEventManager(); const { createNotification } = useNotifications(); const [calendarUserSettings] = useCalendarUserSettings(); const [updating, withUpdating] = useLoading(); const [cancelling, withCancelling] = useLoading(); const [autoDetectPrimaryTimezone, setAutoDetectPrimaryTimezone] = useState<boolean>( !!calendarUserSettings.AutoDetectPrimaryTimezone ); const handleUpdateTimezone = async () => { await api( updateCalendarUserSettings({ PrimaryTimezone: localTzid, AutoDetectPrimaryTimezone: +autoDetectPrimaryTimezone, }) ); await call(); onClose?.(); createNotification({ text: c('Success').t`Preference saved` }); }; const handleCancel = async () => { if (autoDetectPrimaryTimezone !== !!calendarUserSettings.AutoDetectPrimaryTimezone) { await api( updateCalendarUserSettings({ AutoDetectPrimaryTimezone: +autoDetectPrimaryTimezone, }) ); await call(); createNotification({ text: c('Success').t`Preference saved` }); } onClose?.(); }; const timezone = <b key={0}>{localTzid}</b>; return ( <Prompt open={isOpen} onClose={onClose} title={c('Modal title').t`Time zone changed`} buttons={[ <Button loading={updating} onClick={() => { void withUpdating(handleUpdateTimezone()); }} color="norm" > {c('Action').t`Update`} </Button>, <Button loading={cancelling} onClick={() => { void withCancelling(handleCancel()); }} > {c('Action').t`Keep current time zone`} </Button>, ]} actions={ <Checkbox id="autodetect-primary-timezone" autoFocus checked={!autoDetectPrimaryTimezone} disabled={updating} onChange={() => setAutoDetectPrimaryTimezone(!autoDetectPrimaryTimezone)} > {c("Don't ask to update timezone checkbox label").t`Don't ask again`} </Checkbox> } > <p> {c('Info') .jt`Your system time zone seems to have changed to ${timezone}. Do you want to update your time zone preference?`} </p> </Prompt> ); }; export default AskUpdateTimezoneModal;
2,541
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/setup/CalendarOnboardingContainer.tsx
import CalendarOnboardingModal from '../../components/onboarding/CalendarOnboardingModal'; import DummyCalendarContainerView from '../calendar/DummyCalendarContainerView'; interface Props { onDone: () => void; } const CalendarOnboardingContainer = ({ onDone }: Props) => { return ( <> <DummyCalendarContainerView /> <CalendarOnboardingModal open onDone={onDone} /> </> ); }; export default CalendarOnboardingContainer;
2,542
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/setup/CalendarReactivateSection.tsx
import { c } from 'ttag'; import { Alert } from '@proton/components'; import { VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import CalendarTableRows from './CalendarTableRows'; interface Props { calendarsToReactivate: VisualCalendar[]; } const CalendarReactivateSection = ({ calendarsToReactivate = [] }: Props) => { return ( <> <Alert className="mb-4" type="info">{c('Info') .t`You have reactivated your keys and events linked to the following calendars can now be decrypted.`}</Alert> <CalendarTableRows calendars={calendarsToReactivate} /> </> ); }; export default CalendarReactivateSection;
2,543
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/setup/CalendarResetSection.tsx
import { useState } from 'react'; import { c } from 'ttag'; import { Href } from '@proton/atoms'; import { Collapsible, CollapsibleContent, CollapsibleHeader, CollapsibleHeaderIconButton, Icon } from '@proton/components'; import CalendarSelectIcon from '@proton/components/components/calendarSelect/CalendarSelectIcon'; import { getKnowledgeBaseUrl } from '@proton/shared/lib/helpers/url'; import { VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import encryptedEventSvg from '@proton/styles/assets/img/illustrations/encrypted-event.svg'; const getFirstParagraphText = (resetAll: boolean) => { if (resetAll) { return c('Info; reset calendar keys modal; part 1') .t`Your calendars will not show details of previously created events.`; } return c('Info; reset calendar keys modal; part 1') .t`Some of your calendars will not show details of previously created events.`; }; interface Props { calendarsToReset: VisualCalendar[]; resetAll: boolean; } const CalendarResetSection = ({ calendarsToReset = [], resetAll }: Props) => { const altText = c('Title').t`Encrypted event`; const [show, setShow] = useState(false); const clickShow = () => setShow((show) => !show); const calendarsList = ( <div> {calendarsToReset.map(({ ID, Name, Color }) => ( <div key={ID} className="flex flex-nowrap w-full flex-align-items-center mb-2"> <span className="flex flex-item-noshrink"> <CalendarSelectIcon color={Color} className="mr-2" /> </span> <span className="text-ellipsis" title={Name}> {Name} </span> </div> ))} </div> ); return ( <> <p>{getFirstParagraphText(resetAll)}</p> {!resetAll && ( <div> <Collapsible> <CollapsibleHeader suffix={ <CollapsibleHeaderIconButton onClick={clickShow}> <Icon name="chevron-down" /> </CollapsibleHeaderIconButton> } disableFullWidth onClick={clickShow} > {show ? c('Action').t`Hide affected calendars` : c('Action').t`Show affected calendars`} </CollapsibleHeader> <CollapsibleContent>{calendarsList}</CollapsibleContent> </Collapsible> </div> )} <div className="flex w-full"> <img src={encryptedEventSvg} alt={altText} className="m-auto" /> </div> <p> {c('Info; reset calendar keys modal; part 2') .t`This is because your password was recently reset without using a recovery method.`} </p> <p> {c('Info; reset calendar keys modal; part 3') .t`You can recover your encrypted data with a recovery file, recovery phrase, or your old password.`} </p> <p className="mb-2"> <Href href={getKnowledgeBaseUrl('/set-account-recovery-methods')}> {c('Link; reset calendar keys modal').t`What's a recovery method?`} </Href> </p> </> ); }; export default CalendarResetSection;
2,544
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/setup/CalendarSetupContainer.tsx
import { useEffect, useState } from 'react'; import { LoaderPage, StandardLoadErrorPage, useApi, useCache, useEventManager, useGetAddressKeys, useGetAddresses, } from '@proton/components'; import { useGetHolidaysDirectory } from '@proton/components/containers/calendar/hooks/useHolidaysDirectory'; import { getSilentApi } from '@proton/shared/lib/api/helpers/customConfig'; import setupCalendarHelper from '@proton/shared/lib/calendar/crypto/keys/setupCalendarHelper'; import { setupCalendarKeys } from '@proton/shared/lib/calendar/crypto/keys/setupCalendarKeys'; import setupHolidaysCalendarHelper from '@proton/shared/lib/calendar/crypto/keys/setupHolidaysCalendarHelper'; import { getSuggestedHolidaysCalendar } from '@proton/shared/lib/calendar/holidaysCalendar/holidaysCalendar'; import { getRandomAccentColor } from '@proton/shared/lib/colors'; import { getTimezone } from '@proton/shared/lib/date/timezone'; import { traceError } from '@proton/shared/lib/helpers/sentry'; import { languageCode } from '@proton/shared/lib/i18n'; import { getBrowserLanguageTags } from '@proton/shared/lib/i18n/helper'; import { VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import { CalendarUserSettingsModel, CalendarsModel } from '@proton/shared/lib/models'; import { loadModels } from '@proton/shared/lib/models/helper'; import noop from '@proton/utils/noop'; interface Props { hasCalendarToGenerate?: boolean; hasHolidaysCalendarToGenerate?: boolean; calendars?: VisualCalendar[]; onDone: () => void; } const CalendarSetupContainer = ({ hasCalendarToGenerate, hasHolidaysCalendarToGenerate, calendars, onDone }: Props) => { const { call } = useEventManager(); const cache = useCache(); const getAddresses = useGetAddresses(); const getAddressKeys = useGetAddressKeys(); const normalApi = useApi(); const silentApi = getSilentApi(normalApi); const getHolidaysDirectory = useGetHolidaysDirectory(silentApi); const [error, setError] = useState(); useEffect(() => { const run = async () => { const addresses = await getAddresses(); if (calendars) { await setupCalendarKeys({ api: silentApi, calendars, getAddressKeys, }); } else { const promises = []; if (hasCalendarToGenerate) { // we create a personal calendar promises.push( setupCalendarHelper({ api: silentApi, addresses, getAddressKeys, }) ); } if (hasHolidaysCalendarToGenerate) { // we create a public holidays calendar. If we fail, we do it silently try { const directory = await getHolidaysDirectory(); const visibleDirectory = directory.filter(({ Hidden }) => !Hidden); const languageTags = getBrowserLanguageTags(); const holidaysCalendar = getSuggestedHolidaysCalendar( visibleDirectory, getTimezone(), languageCode, languageTags ); if (!holidaysCalendar) { throw new Error('Skip creating holidays calendar'); } promises.push( setupHolidaysCalendarHelper({ holidaysCalendar, color: getRandomAccentColor(), notifications: [], addresses, getAddressKeys, api: silentApi, }).catch(noop) ); } catch (e) { noop(); } } await Promise.all(promises); } await call(); await loadModels([CalendarsModel, CalendarUserSettingsModel], { api: silentApi, cache, useCache: false }); }; run() .then(() => { onDone(); }) .catch((e) => { setError(e); traceError(e); }); }, []); if (error) { return <StandardLoadErrorPage />; } return <LoaderPage />; }; export default CalendarSetupContainer;
2,545
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/setup/CalendarTableRows.tsx
import { c } from 'ttag'; import { Table, TableBody, TableHeader, TableRow } from '@proton/components'; import { VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import CalendarIcon from '../../components/CalendarIcon'; const CalendarTableRow = ({ Name, Color }: VisualCalendar) => { return ( <TableRow cells={[ <div key={0} className="flex flex-align-items-center flex-nowrap"> <CalendarIcon color={Color} className="flex-item-noshrink mr-4" /> <span className="text-ellipsis" title={Name}> {Name} </span> </div>, ]} /> ); }; interface Props { calendars: VisualCalendar[]; } const CalendarTableRows = ({ calendars = [] }: Props) => { return ( <Table> <TableHeader cells={[c('Header').t`Name`]} /> <TableBody> {calendars.map((calendar) => { return <CalendarTableRow key={calendar.ID} {...calendar} />; })} </TableBody> </Table> ); }; export default CalendarTableRows;
2,546
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/setup/UnlockCalendarsContainer.tsx
import { getPersonalCalendars } from '@proton/shared/lib/calendar/calendar'; import { VIEWS } from '@proton/shared/lib/calendar/constants'; import { VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import DummyCalendarContainerView from '../calendar/DummyCalendarContainerView'; import UnlockCalendarsModal from './UnlockCalendarsModal'; interface Props { calendars: VisualCalendar[]; calendarsToUnlock: VisualCalendar[]; onDone: () => void; drawerView?: VIEWS; hasReactivatedCalendarsRef: React.MutableRefObject<boolean>; } const UnlockCalendarsContainer = ({ calendars, calendarsToUnlock, onDone, drawerView, hasReactivatedCalendarsRef, }: Props) => { // Don't take into account subscribed calendars to decide whether to show a partial list of the calendars that need reset. // Although we do need to reset the calendar keys for those, they will be immediately re-synced so the users should not see them "locked" const numberOfPersonalCalendars = getPersonalCalendars(calendars).length; const numberOfPersonalCalendarsToUnlock = getPersonalCalendars(calendarsToUnlock).length; const hasOnlySubscribedCalendarsToUnlock = numberOfPersonalCalendarsToUnlock === 0; const unlockAll = hasOnlySubscribedCalendarsToUnlock || numberOfPersonalCalendars === numberOfPersonalCalendarsToUnlock; return ( <> <UnlockCalendarsModal calendars={calendarsToUnlock} unlockAll={unlockAll} hasReactivatedCalendarsRef={hasReactivatedCalendarsRef} onDone={onDone} /> <DummyCalendarContainerView drawerView={drawerView} /> </> ); }; export default UnlockCalendarsContainer;
2,547
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/containers/setup/UnlockCalendarsModal.tsx
import { useEffect } from 'react'; import { c } from 'ttag'; import { Button, ButtonLike } from '@proton/atoms/Button'; import { GenericError, ModalTwo as Modal, ModalTwoContent as ModalContent, ModalTwoFooter as ModalFooter, ModalTwoHeader as ModalHeader, PrimaryButton, Prompt, SettingsLink, useApi, useCache, useConfig, useDrawer, useGetAddressKeys, useGetAddresses, useModalState, } from '@proton/components'; import { useLoading } from '@proton/hooks'; import { getPersonalCalendars } from '@proton/shared/lib/calendar/calendar'; import { CALENDAR_FLAGS } from '@proton/shared/lib/calendar/constants'; import { process } from '@proton/shared/lib/calendar/crypto/keys/resetHelper'; import { getCalendarsSettingsPath } from '@proton/shared/lib/calendar/settingsRoutes'; import { APPS, APPS_CONFIGURATION } from '@proton/shared/lib/constants'; import { closeDrawerFromChildApp } from '@proton/shared/lib/drawer/helpers'; import { hasBit } from '@proton/shared/lib/helpers/bitset'; import { VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import CalendarReactivateSection from './CalendarReactivateSection'; import CalendarResetSection from './CalendarResetSection'; interface FilteredCalendars { calendarsToReset: VisualCalendar[]; calendarsToReactivate: VisualCalendar[]; calendarsToClean: VisualCalendar[]; } interface Props { calendars: VisualCalendar[]; unlockAll: boolean; onDone: () => void; hasReactivatedCalendarsRef: React.MutableRefObject<boolean>; } const UnlockCalendarsModal = ({ calendars, unlockAll, hasReactivatedCalendarsRef, onDone }: Props) => { const api = useApi(); const cache = useCache(); const getAddresses = useGetAddresses(); const getAddressKeys = useGetAddressKeys(); const { parentApp } = useDrawer(); const { APP_NAME: currentApp } = useConfig(); const { calendarsToReset, calendarsToReactivate, calendarsToClean } = calendars.reduce<FilteredCalendars>( (acc, calendar) => { const { Flags } = calendar; if (hasBit(Flags, CALENDAR_FLAGS.RESET_NEEDED)) { acc.calendarsToReset.push(calendar); } else if (hasBit(Flags, CALENDAR_FLAGS.UPDATE_PASSPHRASE)) { acc.calendarsToReactivate.push(calendar); } else if (hasBit(Flags, CALENDAR_FLAGS.LOST_ACCESS)) { acc.calendarsToClean.push(calendar); } return acc; }, { calendarsToReset: [], calendarsToReactivate: [], calendarsToClean: [], } ); const hasCalendarsToReset = calendarsToReset.length > 0; const hasCalendarsToReactivate = calendarsToReactivate.length > 0; const hasCalendarsToClean = calendarsToClean.length > 0; const [errorModal, setErrorModalOpen, renderErrorModal] = useModalState(); const [resetModal, setResetModalOpen, renderResetModal] = useModalState(); const [reshareModal, setReshareModalOpen, renderReshareModal] = useModalState(); const [reactivateModal, setReactivateModalOpen, renderReactivateModal] = useModalState(); const [isLoading, withLoading] = useLoading(false); const handleProcess = () => { return withLoading( process({ api, cache, getAddressKeys, getAddresses, calendarsToReset, calendarsToReactivate, calendarsToClean, }) ); }; useEffect(() => { if (hasCalendarsToReactivate) { setReactivateModalOpen(true); } else if (hasCalendarsToReset) { setResetModalOpen(true); } else if (hasCalendarsToClean) { // When user has only calendars to clean (e.g: holidays/shared), we want to do the process in the background void handleProcess().then(() => { onDone(); }); } }, []); const handleError = () => window.location.reload(); const handleReset = () => { handleProcess() .then((hasSharedCalendars = false) => { if (hasSharedCalendars) { setResetModalOpen(false); setReshareModalOpen(true); } else { onDone(); } }) .catch((error) => { console.error(error); setResetModalOpen(false); setErrorModalOpen(true); }); }; const handleReactivate = () => { handleProcess() .then(() => { hasReactivatedCalendarsRef.current = true; if (hasCalendarsToReset) { setReactivateModalOpen(false); setResetModalOpen(true); return; } onDone(); }) .catch((error) => { console.error(error); setReactivateModalOpen(false); setErrorModalOpen(true); }); }; const closeDrawer = () => { if (parentApp) { closeDrawerFromChildApp(parentApp, currentApp, true); } }; const calendarAppBareName = APPS_CONFIGURATION[APPS.PROTONCALENDAR].bareName.toLowerCase(); return ( <> {renderErrorModal && ( <Modal {...errorModal}> <ModalHeader title={c('Title').t`Error`} hasClose={false} /> <ModalContent> <GenericError /> </ModalContent> <ModalFooter> <PrimaryButton type="submit" onClick={handleError}>{c('Action').t`Close`}</PrimaryButton> </ModalFooter> </Modal> )} {renderResetModal && ( <Modal {...resetModal} size="large"> <ModalHeader title={ unlockAll ? c('Title').t`We've locked your calendars to protect your data` : c('Title').t`We've locked some calendars to protect your data` } hasClose={false} /> <ModalContent> <CalendarResetSection calendarsToReset={getPersonalCalendars(calendarsToReset)} resetAll={unlockAll} /> </ModalContent> <ModalFooter> <ButtonLike as={SettingsLink} path={'/recovery'} onClick={closeDrawer}> {c('Action').t`Recover data`} </ButtonLike> <PrimaryButton type="submit" loading={isLoading} onClick={handleReset}> {c('Action').t`Continue to ${calendarAppBareName}`} </PrimaryButton> </ModalFooter> </Modal> )} {renderReshareModal && ( <Prompt {...reshareModal} title={c('Title').t`Reshare your calendars`} buttons={[ <ButtonLike as={SettingsLink} type="submit" color="norm" path={getCalendarsSettingsPath()} onClick={closeDrawer} > {c('Action').t`Open settings`} </ButtonLike>, <Button onClick={onDone}>{c('Action').t`Close`}</Button>, ]} > <p> {c('Info; reshare calendar modal; part 1') .t`Calendar sharing was disabled following your recent password reset.`} </p> <p>{c('Info; reshare calendar modal; part 2').t`You can reshare your calendars in settings.`}</p> </Prompt> )} {renderReactivateModal && ( <Modal {...reactivateModal}> <ModalHeader title={c('Title').t`Reactivate calendar keys`} hasClose={false} /> <ModalContent> <CalendarReactivateSection calendarsToReactivate={calendarsToReactivate} /> </ModalContent> <ModalFooter> <Button onClick={onDone}>{c('Action').t`Cancel`}</Button> <PrimaryButton type="submit" loading={isLoading} onClick={handleReactivate}> {c('Action').t`Got it`} </PrimaryButton> </ModalFooter> </Modal> )} </> ); }; export default UnlockCalendarsModal;
2,548
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/content/PrivateApp.tsx
import { FeatureCode, LoaderPage, StandardPrivateApp, useApi, useAppTitle, useDrawer, useDrawerParent, } from '@proton/components'; import { useGetHolidaysDirectory } from '@proton/components/containers/calendar/hooks/useHolidaysDirectory'; import { getSilentApi } from '@proton/shared/lib/api/helpers/customConfig'; import { loadAllowedTimeZones } from '@proton/shared/lib/date/timezone'; import { DRAWER_VISIBILITY } from '@proton/shared/lib/interfaces'; import { TtagLocaleMap } from '@proton/shared/lib/interfaces/Locale'; import { AddressesModel, CalendarUserSettingsModel, CalendarsModel, ContactEmailsModel, ContactsModel, LabelsModel, MailSettingsModel, UserInvitationModel, UserModel, UserSettingsModel, } from '@proton/shared/lib/models'; import noop from '@proton/utils/noop'; const EVENT_MODELS = [ UserModel, UserSettingsModel, MailSettingsModel, AddressesModel, ContactEmailsModel, ContactsModel, LabelsModel, UserInvitationModel, ]; const PRELOAD_MODELS = [UserModel, UserSettingsModel, AddressesModel, CalendarsModel, CalendarUserSettingsModel]; const getAppContainer = () => import(/* webpackChunkName: "MainContainer" */ '../containers/calendar/MainContainer'); interface Props { onLogout: () => void; locales: TtagLocaleMap; } const PrivateApp = ({ onLogout, locales }: Props) => { const api = useApi(); const silentApi = getSilentApi(api); const getHolidaysDirectory = useGetHolidaysDirectory(silentApi); const { setShowDrawerSidebar } = useDrawer(); useAppTitle(''); useDrawerParent(); return ( <StandardPrivateApp onLogout={onLogout} locales={locales} onInit={() => { // Intentionally ignoring to return promises to avoid blocking app start loadAllowedTimeZones(silentApi).catch(noop); getHolidaysDirectory().catch(noop); }} preloadModels={PRELOAD_MODELS} preloadFeatures={[FeatureCode.CalendarFetchMetadataOnly, FeatureCode.AutoAddHolidaysCalendars]} eventModels={EVENT_MODELS} loader={<LoaderPage />} hasPrivateMemberKeyGeneration hasReadableMemberKeyActivation hasMemberKeyMigration app={getAppContainer} onUserSettings={({ HideSidePanel }) => setShowDrawerSidebar(HideSidePanel === DRAWER_VISIBILITY.SHOW)} /> ); }; export default PrivateApp;
2,549
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/helpers/attendees.test.ts
import { SimpleMap } from '@proton/shared/lib/interfaces'; import { ContactEmail } from '@proton/shared/lib/interfaces/contacts'; import { DisplayNameEmail } from '../containers/calendar/interface'; import { getOrganizerDisplayData } from './attendees'; const generateDummyContactEmail = ({ email, name, contactEmailID, contactID, }: { email: string; name: string; contactEmailID: string; contactID: string; }) => { const result: ContactEmail = { ID: contactEmailID, Email: email, Name: name, Type: [], Defaults: 0, Order: 0, ContactID: contactID, LabelIDs: [], LastUsedTime: 0, }; return result; }; describe('getOrganizerDisplayData()', () => { const testEmail = 'te_st.E-mail@proton.me'; const organizer = { email: testEmail, cn: 'The organizer' }; const isOrganizer = false; const contacts = [ { name: 'Unexpected match', email: testEmail, contactEmailID: '2', contactID: 'unexpected' }, { name: 'Canonicalized match', email: 'testemail@proton.me', contactEmailID: '3', contactID: 'internal', }, { name: 'A gmail match', email: 'te_ste-mail@proton,me', contactEmailID: '4', contactID: 'gmail' }, { name: 'A lonely contact', email: 'lonely@proton.me', contactEmailID: '5', contactID: 'other' }, { name: 'Expected match', email: 'te_st.e-mail@proton.me', contactEmailID: '1', contactID: 'expected' }, ]; // keys in contactsEmailMap are emails canonicalized with the generic scheme const contactsEmailMap = contacts.reduce<SimpleMap<ContactEmail>>((acc, contact) => { acc[contact.email] = generateDummyContactEmail(contact); return acc; }, {}); // keys in displayNameEmailMap are emails canonicalized by guess. In particular all Proton ones are canonicalized internally const displayNameEmailMap: SimpleMap<DisplayNameEmail> = { 'testemail@proton.me': { displayName: "It's me", displayEmail: 'test.email@proton.me' }, 'lonely@proton.me': { displayName: 'Lone star', displayEmail: 'Lonely@proton.me' }, }; test('Distinguishes dots, hyphens and underscores, but not capitalization, to return correct contactId', () => { const { contactID } = getOrganizerDisplayData(organizer, isOrganizer, contactsEmailMap, displayNameEmailMap); expect(contactID).toEqual('expected'); }); test('Neither distinguishes dots, hyphens, underscores or capitalization, to return correct display name', () => { const { title, name } = getOrganizerDisplayData(organizer, isOrganizer, contactsEmailMap, displayNameEmailMap); expect(name).toEqual("It's me"); expect(title).toEqual("It's me <te_st.E-mail@proton.me>"); }); describe('when user is organiser', () => { const isOrganizer = true; test('Neither distinguish dots, hyphens, underscores nor capitalization, to return correct display name', () => { expect(getOrganizerDisplayData(organizer, isOrganizer, contactsEmailMap, displayNameEmailMap)).toEqual({ name: 'You', title: testEmail, contactID: 'expected', }); }); }); });
2,550
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/helpers/attendees.ts
import { c } from 'ttag'; import { apiNotificationsToModel } from '@proton/shared/lib/calendar/alarms/notificationsToModel'; import { ICAL_ATTENDEE_STATUS } from '@proton/shared/lib/calendar/constants'; import { canonicalizeEmail, canonicalizeEmailByGuess } from '@proton/shared/lib/helpers/email'; import { CalendarSettings, EventModel } from '@proton/shared/lib/interfaces/calendar'; import { ContactEmail } from '@proton/shared/lib/interfaces/contacts'; import { RequireOnly, SimpleMap } from '@proton/shared/lib/interfaces/utils'; import { DisplayNameEmail } from '../containers/calendar/interface'; const { NEEDS_ACTION, DECLINED, ACCEPTED, TENTATIVE } = ICAL_ATTENDEE_STATUS; export const modifyEventModelPartstat = ( model: RequireOnly<EventModel, 'isAllDay'>, partstat: ICAL_ATTENDEE_STATUS, calendarSettings: CalendarSettings ): Partial<EventModel> => { const { attendees = [], isAllDay, selfAttendeeIndex } = model; const selfAttendee = selfAttendeeIndex !== undefined ? attendees[selfAttendeeIndex] : undefined; let addDefaultNotifications = false; const modelWithPartstat = { ...model }; const notificationsKey = isAllDay ? 'fullDayNotifications' : 'partDayNotifications'; if (modelWithPartstat.attendees && selfAttendee && selfAttendeeIndex !== undefined) { addDefaultNotifications = [NEEDS_ACTION, DECLINED].includes(selfAttendee.partstat) && [ACCEPTED, TENTATIVE].includes(partstat) && model[notificationsKey]?.length === 0; modelWithPartstat.attendees[selfAttendeeIndex].partstat = partstat; } if (partstat === DECLINED) { return { ...modelWithPartstat, hasDefaultNotifications: false, partDayNotifications: [], fullDayNotifications: [], }; } if (!addDefaultNotifications) { return modelWithPartstat; } const notifications = apiNotificationsToModel({ notifications: null, isAllDay, calendarSettings }); return { ...modelWithPartstat, hasDefaultNotifications: true, [notificationsKey]: notifications, }; }; export const getOrganizerDisplayData = ( organizer = { email: '', cn: '' }, isSelfOrganizer: boolean, contactEmailsMap: SimpleMap<ContactEmail>, displayNameEmailMap: SimpleMap<DisplayNameEmail> ) => { const { email, cn } = organizer; if (!email) { // it should not happen return { name: '', title: '' }; } const { displayName } = displayNameEmailMap[canonicalizeEmailByGuess(email)] || {}; const { ContactID: contactID } = contactEmailsMap[canonicalizeEmail(email)] || {}; if (isSelfOrganizer) { return { name: c('Event info. Organizer name').t`You`, title: `${email}`, contactID, }; } const name = displayName || cn || email; const title = name === email ? email : `${name} <${email}>`; return { name, title, contactID }; };
2,551
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/helpers/color.ts
import { CSSProperties } from 'react'; import tinycolor from 'tinycolor2'; import { genAccentShades } from '@proton/colors'; import { COLORS } from '@proton/shared/lib/calendar/constants'; export const getEventStyle = (backgroundColor = '', style: CSSProperties = {}) => { const [base, alt] = genAccentShades(tinycolor(backgroundColor)).map((c) => c.toHexString()); const alpha = tinycolor(backgroundColor)?.setAlpha(0.3); return { ...style, '--color-main': base, '--color-alt': alt, '--color-alpha': alpha, '--foreground': COLORS.WHITE, }; };
2,552
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/helpers/date.ts
import { convertUTCDateTimeToZone, convertZonedDateTimeToUTC, fromUTCDate, toUTCDate, } from '@proton/shared/lib/date/timezone'; /** * Given a date, if we are to display a single time zone offset for the whole day, * we pick the UTC offset at noon. DST changes usually happens at 2:00, * so the offset at noon is more representative of the offset of the day. */ export const getNoonDateForTimeZoneOffset = ({ date, dateTzid, targetTzid, }: { date: Date; dateTzid: string; targetTzid: string; }) => { // Extract year, month and day in the date time zone const dateTimeInDateTzid = convertUTCDateTimeToZone(fromUTCDate(date), dateTzid); // Pick noon of that date const noonDateTimeInDateTzid = { ...dateTimeInDateTzid, hours: 12, minutes: 0, seconds: 0, }; // Return date corresponding to the noon above in the target time zone return toUTCDate(convertZonedDateTimeToUTC(noonDateTimeInDateTzid, targetTzid)); };
2,553
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/helpers/event.test.ts
import { MAX_ATTENDEES } from '@proton/shared/lib/calendar/constants'; import { ADDRESS_SEND } from '@proton/shared/lib/constants'; import { addressBuilder } from '@proton/testing/lib/builders'; import { getCanChangeCalendarOfEvent, getCanDeleteEvent, getCanDuplicateEvent, getCanEditEvent, getCanEditSharedEventData, getCanReplyToEvent, getCannotSaveEvent, getIsAvailableCalendar, } from './event'; describe('getCannotSaveEvent()', () => { test('Member cannot create invites in a shared calendar', () => { const isOwnedCalendar = false; const isOrganizer = true; const numberOfAttendees = MAX_ATTENDEES - 1; const canEditSharedEventData = true; expect(getCannotSaveEvent({ isOwnedCalendar, isOrganizer, numberOfAttendees, canEditSharedEventData })).toEqual( true ); }); test('Owner can create invites in a personal calendar', () => { const isOwnedCalendar = true; const isOrganizer = true; const numberOfAttendees = MAX_ATTENDEES - 1; const canEditSharedEventData = true; expect(getCannotSaveEvent({ isOwnedCalendar, isOrganizer, numberOfAttendees, canEditSharedEventData })).toEqual( false ); }); test('Owner cannot create invites with too many participants', () => { const isOwnedCalendar = true; const isOrganizer = true; const numberOfAttendees = MAX_ATTENDEES + 1; const canEditSharedEventData = true; expect( getCannotSaveEvent({ isOwnedCalendar, isOrganizer, numberOfAttendees, canEditSharedEventData, maxAttendees: MAX_ATTENDEES, }) ).toEqual(true); }); test('Attendee can add notifications to invite in a personal calendar', () => { const isOwnedCalendar = true; const isOrganizer = false; const numberOfAttendees = MAX_ATTENDEES - 1; const canEditSharedEventData = false; expect(getCannotSaveEvent({ isOwnedCalendar, isOrganizer, numberOfAttendees, canEditSharedEventData })).toEqual( false ); }); test('Attendee can add notifications to invite in a shared calendar', () => { const isOwnedCalendar = false; const isOrganizer = false; const numberOfAttendees = MAX_ATTENDEES - 1; const canEditSharedEventData = false; expect(getCannotSaveEvent({ isOwnedCalendar, isOrganizer, numberOfAttendees, canEditSharedEventData })).toEqual( false ); }); test('Member can add notifications to an invite she organized in a shared calendar', () => { const isOwnedCalendar = false; const isOrganizer = true; const numberOfAttendees = 10; const canEditSharedEventData = false; expect(getCannotSaveEvent({ isOwnedCalendar, isOrganizer, numberOfAttendees, canEditSharedEventData })).toEqual( false ); }); }); describe('getCanEditEvent()', () => { test('User can edit events only if the calendar is of known type and is not disabled', () => { const combinations = []; for (let i = 0; i < 2 ** 2; i++) { const isUnknownCalendar = !!(1 & i); const isCalendarDisabled = !!(2 & i); combinations.push({ isUnknownCalendar, isCalendarDisabled }); } combinations.forEach(({ isUnknownCalendar, isCalendarDisabled }) => { expect( getCanEditEvent({ isUnknownCalendar, isCalendarDisabled, }) ).toEqual(!isCalendarDisabled && !isUnknownCalendar); }); }); }); describe('getCanDeleteEvent()', () => { test('User cannot delete events in subscribed or other read-only calendars', () => { const combinations = []; for (let i = 0; i < 2 ** 2; i++) { const isOwnedCalendar = !!(1 & i); const isInvitation = !!(2 & i); combinations.push({ isOwnedCalendar, isInvitation }); } combinations.forEach(({ isOwnedCalendar, isInvitation }) => { expect( getCanDeleteEvent({ isOwnedCalendar, isCalendarWritable: false, isInvitation, }) ).toEqual(false); }); }); test('Attendee can delete invites in her own calendar', () => { const isOwnedCalendar = true; const isCalendarWritable = true; const isInvitation = true; expect(getCanDeleteEvent({ isOwnedCalendar, isCalendarWritable, isInvitation })).toEqual(true); }); test('Member cannot delete invites in a shared calendar with edit rights', () => { const isOwnedCalendar = false; const isCalendarWritable = true; const isInvitation = true; expect(getCanDeleteEvent({ isOwnedCalendar, isCalendarWritable, isInvitation })).toEqual(false); }); test('Member cannot delete invites in a shared calendar with view-only rights', () => { const isOwnedCalendar = false; const isCalendarWritable = false; const isInvitation = true; expect(getCanDeleteEvent({ isOwnedCalendar, isCalendarWritable, isInvitation })).toEqual(false); }); }); describe('getCanEditSharedEventData()', () => { const activeAddress = addressBuilder(); const cannotSendAddress = { ...activeAddress, Send: ADDRESS_SEND.SEND_NO, }; test('Owner can edit shared event data of events which are not invitations', () => { expect( getCanEditSharedEventData({ isOwnedCalendar: true, isCalendarWritable: true, isOrganizer: false, isAttendee: false, isInvitation: false, selfAddress: undefined, }) ).toEqual(true); }); test('Owner can edit shared event data of events she organizes if the address is active', () => { expect( getCanEditSharedEventData({ isOwnedCalendar: true, isCalendarWritable: true, isOrganizer: true, isAttendee: false, isInvitation: false, selfAddress: activeAddress, }) ).toEqual(true); }); test('Owner cannot edit shared event data of events she organizes if the address cannot send', () => { expect( getCanEditSharedEventData({ isOwnedCalendar: true, isCalendarWritable: true, isOrganizer: true, isAttendee: false, isInvitation: true, selfAddress: cannotSendAddress, }) ).toEqual(false); }); test('User cannot edit shared event data in subscribed calendars or other read-only calendars', () => { const combinations = []; for (let i = 0; i < 2 ** 3; i++) { const isOrganizer = !!(1 & i); const isAttendee = !!(2 & i); const isInvitation = isOrganizer || isAttendee || !!(4 & i); const selfAddress = isOrganizer || isAttendee ? activeAddress : undefined; combinations.push({ isOrganizer, isAttendee, isInvitation, selfAddress }); } combinations.forEach(({ isOrganizer, isAttendee, isInvitation, selfAddress }) => { expect( getCanEditSharedEventData({ isOwnedCalendar: true, isCalendarWritable: false, isOrganizer, isAttendee, isInvitation, selfAddress, }) ).toEqual(false); }); }); test('Member cannot edit shared event data in shared calendars with view-only rights', () => { const combinations = []; for (let i = 0; i < 2 ** 3; i++) { const isOrganizer = !!(1 & i); const isAttendee = !!(2 & i); const isInvitation = isOrganizer || isAttendee || !!(4 & i); const selfAddress = isOrganizer || isAttendee ? activeAddress : undefined; combinations.push({ isOrganizer, isAttendee, isInvitation, selfAddress }); } combinations.forEach(({ isOrganizer, isAttendee, isInvitation, selfAddress }) => { expect( getCanEditSharedEventData({ isOwnedCalendar: false, isCalendarWritable: false, isOrganizer, isAttendee, isInvitation, selfAddress, }) ).toEqual(false); }); }); test('Member with edit rights cannot edit shared event data of invitations', () => { const combinations = []; for (let i = 0; i < 2 ** 2; i++) { const isOrganizer = !!(1 & i); const isAttendee = !!(2 & i); const selfAddress = isOrganizer || isAttendee ? activeAddress : undefined; combinations.push({ isOrganizer, isAttendee, selfAddress }); } combinations.forEach(({ isOrganizer, isAttendee, selfAddress }) => { expect( getCanEditSharedEventData({ isOwnedCalendar: false, isCalendarWritable: true, isOrganizer, isAttendee, isInvitation: true, selfAddress, }) ).toEqual(false); }); }); test('Member with view-only rights cannot edit invitations', () => { const combinations = []; for (let i = 0; i < 2 ** 2; i++) { const isOrganizer = !!(1 & i); const isAttendee = !!(2 & i); const selfAddress = isOrganizer || isAttendee ? activeAddress : undefined; combinations.push({ isOrganizer, isAttendee, selfAddress }); } combinations.forEach(({ isOrganizer, isAttendee, selfAddress }) => { expect( getCanEditSharedEventData({ isOwnedCalendar: false, isCalendarWritable: false, isOrganizer, isAttendee, isInvitation: true, selfAddress, }) ).toEqual(false); }); }); test('User cannot edit invitations in owned calendars if she is not organizing or attending', () => { expect( getCanEditSharedEventData({ isOwnedCalendar: true, isCalendarWritable: true, isOrganizer: false, isAttendee: false, isInvitation: true, selfAddress: undefined, }) ).toEqual(false); }); }); describe('getCanChangeCalendar()', () => { test('User can change calendar of events that are not invitations', () => { const combinations = []; for (let i = 0; i < 2 ** 2; i++) { const isOwnedCalendar = !!(1 & i); const isSingleEdit = !!(2 & i); combinations.push({ isOwnedCalendar, isSingleEdit }); } combinations.forEach(({ isOwnedCalendar, isSingleEdit }) => { expect( getCanChangeCalendarOfEvent({ isCreateEvent: false, isOwnedCalendar, isCalendarWritable: true, isSingleEdit, isInvitation: false, isAttendee: false, isOrganizer: false, }) ).toEqual(true); }); }); test('User creating event can change calendar', () => { const combinations = []; for (let i = 0; i < 2 ** 2; i++) { const isOwnedCalendar = !!(1 & i); const isOrganizer = !!(2 & i); const isInvitation = isOrganizer; combinations.push({ isOwnedCalendar, isOrganizer, isInvitation }); } combinations.forEach(({ isOwnedCalendar, isInvitation, isOrganizer }) => { expect( getCanChangeCalendarOfEvent({ isCreateEvent: true, isOwnedCalendar, isCalendarWritable: true, isSingleEdit: false, isInvitation, isAttendee: false, isOrganizer, }) ).toEqual(true); }); }); test('User cannot change calendar of event in non-writable calendar', () => { const combinations = []; for (let i = 0; i < 2 ** 5; i++) { const isOwnedCalendar = !!(1 & i); const isSingleEdit = !!(2 & i); const isOrganizer = !!(4 & i); const isAttendee = isOrganizer ? false : !!(8 & i); const isInvitation = isOrganizer || isAttendee ? true : !!(16 & i); combinations.push({ isOwnedCalendar, isSingleEdit, isInvitation, isOrganizer, isAttendee }); } combinations.forEach(({ isOwnedCalendar, isSingleEdit, isInvitation, isOrganizer, isAttendee }) => { expect( getCanChangeCalendarOfEvent({ isCreateEvent: false, isOwnedCalendar, isCalendarWritable: false, isSingleEdit, isInvitation, isAttendee, isOrganizer, }) ).toEqual(false); }); }); test('Member cannot change calendar of non-organized invitation in shared calendar', () => { const combinations = []; for (let i = 0; i < 2 ** 2; i++) { const isSingleEdit = !!(1 & i); const isAttendee = !!(2 & i); combinations.push({ isSingleEdit, isAttendee }); } combinations.forEach(({ isSingleEdit, isAttendee }) => { expect( getCanChangeCalendarOfEvent({ isCreateEvent: false, isOwnedCalendar: false, isCalendarWritable: true, isSingleEdit, isInvitation: true, isAttendee, isOrganizer: false, }) ).toEqual(false); }); }); test('Organizer cannot change calendar existing invitation', () => { const combinations = []; for (let i = 0; i < 2 ** 3; i++) { const isOwnedCalendar = !!(1 & i); const isCalendarWritable = !!(2 & i); const isSingleEdit = !!(4 & i); combinations.push({ isOwnedCalendar, isCalendarWritable, isSingleEdit }); } combinations.forEach(({ isOwnedCalendar, isCalendarWritable, isSingleEdit }) => { expect( getCanChangeCalendarOfEvent({ isCreateEvent: false, isOwnedCalendar, isCalendarWritable, isSingleEdit, isInvitation: true, isAttendee: false, isOrganizer: true, }) ).toEqual(false); }); }); test('Attendee can change calendar in owned calendars if the event is not a single edit', () => { expect( getCanChangeCalendarOfEvent({ isCreateEvent: false, isOwnedCalendar: true, isCalendarWritable: true, isSingleEdit: false, isInvitation: true, isAttendee: true, isOrganizer: false, }) ).toEqual(true); expect( getCanChangeCalendarOfEvent({ isCreateEvent: false, isOwnedCalendar: true, isCalendarWritable: true, isSingleEdit: true, isInvitation: true, isAttendee: true, isOrganizer: false, }) ).toEqual(false); }); }); describe('getIsAvailableCalendar()', () => { test('User cannot change calendar of events to subscribed or other read-only calendars', () => { const combinations = []; for (let i = 0; i < 2 ** 2; i++) { const isOwnedCalendar = !!(1 & i); const isInvitation = !!(2 & i); combinations.push({ isOwnedCalendar, isInvitation }); } combinations.forEach(({ isOwnedCalendar, isInvitation }) => { expect( getIsAvailableCalendar({ isOwnedCalendar, isCalendarWritable: false, isInvitation, }) ).toEqual(false); }); }); test('Invitations can only be changed to owned calendars', () => { const combinations = []; for (let i = 0; i < 2 ** 2; i++) { const isOwnedCalendar = !!(1 & i); const isCalendarWritable = isOwnedCalendar || !!(2 & i); combinations.push({ isOwnedCalendar, isCalendarWritable }); } combinations.forEach(({ isOwnedCalendar, isCalendarWritable }) => { expect( getIsAvailableCalendar({ isOwnedCalendar, isCalendarWritable, isInvitation: true, }) ).toEqual(isOwnedCalendar); }); }); test('Events that are not invitations can be changed to writable calendars', () => { const combinations = []; for (let i = 0; i < 2 ** 1; i++) { const isOwnedCalendar = !!(1 & i); const isCalendarWritable = isOwnedCalendar || !!(2 & i); combinations.push({ isOwnedCalendar, isCalendarWritable }); } combinations.forEach(({ isOwnedCalendar, isCalendarWritable }) => { expect( getIsAvailableCalendar({ isOwnedCalendar, isCalendarWritable, isInvitation: true, }) ).toEqual(isCalendarWritable); }); }); }); describe('getCanDuplicateEvent()', () => { test('User cannot duplicate events in unknown calendars', () => { const combinations = []; for (let i = 0; i < 2 ** 4; i++) { const isSubscribedCalendar = !!(1 & i); const isOwnedCalendar = !!(2 & i); const isOrganizer = !!(4 & i); const isInvitation = !!(8 & i); combinations.push({ isSubscribedCalendar, isOwnedCalendar, isOrganizer, isInvitation }); } combinations.forEach(({ isSubscribedCalendar, isOwnedCalendar, isOrganizer, isInvitation }) => { expect( getCanDuplicateEvent({ isUnknownCalendar: true, isSubscribedCalendar, isOwnedCalendar, isInvitation, isOrganizer, }) ).toEqual(false); }); }); test('User cannot duplicate events in subscribed calendars', () => { const combinations = []; for (let i = 0; i < 2 ** 2; i++) { const isOrganizer = !!(1 & i); const isInvitation = isOrganizer || !!(2 & i); combinations.push({ isOrganizer, isInvitation }); } combinations.forEach(({ isOrganizer, isInvitation }) => { expect( getCanDuplicateEvent({ isUnknownCalendar: false, isSubscribedCalendar: true, isOwnedCalendar: true, isInvitation, isOrganizer, }) ).toEqual(false); }); }); test('Owner can duplicate events that are not invitations', () => { expect( getCanDuplicateEvent({ isUnknownCalendar: false, isSubscribedCalendar: false, isOwnedCalendar: true, isInvitation: false, isOrganizer: false, }) ).toEqual(true); }); test('Owner can duplicate invitations that she is organizing', () => { expect( getCanDuplicateEvent({ isUnknownCalendar: false, isSubscribedCalendar: false, isOwnedCalendar: true, isInvitation: true, isOrganizer: true, }) ).toEqual(true); }); test('Owner cannot duplicate invitations if she is not the organizer', () => { expect( getCanDuplicateEvent({ isUnknownCalendar: false, isSubscribedCalendar: false, isOwnedCalendar: true, isInvitation: true, isOrganizer: false, }) ).toEqual(false); }); test('Member can duplicate events that are not invitations', () => { expect( getCanDuplicateEvent({ isUnknownCalendar: false, isSubscribedCalendar: false, isOwnedCalendar: false, isInvitation: false, isOrganizer: false, }) ).toEqual(true); }); test('Member cannot duplicate invitations', () => { const combinations = []; for (let i = 0; i < 2 ** 1; i++) { const isOrganizer = !!(1 & i); combinations.push({ isOrganizer }); } combinations.forEach(({ isOrganizer }) => { expect( getCanDuplicateEvent({ isUnknownCalendar: false, isSubscribedCalendar: false, isOwnedCalendar: false, isInvitation: true, isOrganizer, }) ).toEqual(false); }); }); }); describe('getCanReplyToEvent()', () => { test('User can reply to events he is invited in one of his own personal calendars if and only if the event is not cancelled', () => { const combinations = []; for (let i = 0; i < 2 ** 1; i++) { const isCancelled = !!(1 & i); combinations.push({ isCancelled }); } combinations.forEach(({ isCancelled }) => { expect( getCanReplyToEvent({ isOwnedCalendar: true, isCalendarWritable: true, isAttendee: true, isCancelled, }) ).toEqual(!isCancelled); }); }); test('User cannot reply to events he is not attending', () => { const combinations = []; for (let i = 0; i < 2 ** 3; i++) { const isOwnedCalendar = !!(1 & i); const isCalendarWritable = isOwnedCalendar || !!(2 & i); const isCancelled = !!(4 & i); combinations.push({ isOwnedCalendar, isCalendarWritable, isCancelled }); } combinations.forEach(({ isOwnedCalendar, isCalendarWritable, isCancelled }) => { expect( getCanReplyToEvent({ isOwnedCalendar, isCalendarWritable, isAttendee: false, isCancelled, }) ).toEqual(false); }); }); test('User cannot reply to invitations on subscribed calendars', () => { const combinations = []; for (let i = 0; i < 2 ** 1; i++) { const isCancelled = !!(1 & i); combinations.push({ isCancelled }); } combinations.forEach(({ isCancelled }) => { expect( getCanReplyToEvent({ isOwnedCalendar: true, isCalendarWritable: false, isAttendee: true, isCancelled, }) ).toEqual(false); }); }); test('User cannot reply to invitations on shared calendars, with or without edit rights', () => { const combinations = []; for (let i = 0; i < 2 ** 2; i++) { const isCalendarWritable = !!(1 & i); const isCancelled = !!(2 & i); combinations.push({ isCalendarWritable, isCancelled }); } combinations.forEach(({ isCalendarWritable, isCancelled }) => { expect( getCanReplyToEvent({ isOwnedCalendar: false, isCalendarWritable, isAttendee: true, isCancelled, }) ).toEqual(false); }); }); });
2,554
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/helpers/event.ts
import { ICAL_ATTENDEE_STATUS, ICAL_EVENT_STATUS } from '@proton/shared/lib/calendar/constants'; import { getIsAddressActive } from '@proton/shared/lib/helpers/address'; import { Address } from '@proton/shared/lib/interfaces'; import { EventModelReadView } from '@proton/shared/lib/interfaces/calendar'; import { getParticipantsError } from '../components/eventModal/helpers'; export const generateEventUniqueId = (calendarID: string, eventID: string) => `${calendarID}.${eventID}`; export const getCalendarIDFromUniqueId = (itemID: string) => itemID.split('.')[0]; export const getEventIDFromUniqueId = (itemID: string) => itemID.split('.')[1]; export const getEventStatusTraits = (model: EventModelReadView) => { const { status: eventStatus, selfAttendeeIndex } = model; if (model.isAttendee && eventStatus === ICAL_EVENT_STATUS.CONFIRMED) { const selfAttendee = selfAttendeeIndex !== undefined ? model.attendees[selfAttendeeIndex] : undefined; if (selfAttendee) { const { partstat } = selfAttendee; return { isUnanswered: partstat === ICAL_ATTENDEE_STATUS.NEEDS_ACTION, isTentative: partstat === ICAL_ATTENDEE_STATUS.TENTATIVE, isCancelled: partstat === ICAL_ATTENDEE_STATUS.DECLINED, }; } } return { isTentative: eventStatus === ICAL_EVENT_STATUS.TENTATIVE, isCancelled: eventStatus === ICAL_EVENT_STATUS.CANCELLED, }; }; export const getCanEditEvent = ({ isUnknownCalendar, isCalendarDisabled, }: { isUnknownCalendar: boolean; isCalendarDisabled: boolean; }) => { if (isUnknownCalendar) { return false; } if (isCalendarDisabled) { return false; } return true; }; export const getCanDeleteEvent = ({ isOwnedCalendar, isCalendarWritable, isInvitation, }: { isOwnedCalendar: boolean; isCalendarWritable: boolean; isInvitation: boolean; }) => { if (!isCalendarWritable) { return false; } if (!isOwnedCalendar) { return !isInvitation; } return true; }; export const getCanDuplicateEvent = ({ isUnknownCalendar, isSubscribedCalendar, isOwnedCalendar, isOrganizer, isInvitation, }: { isUnknownCalendar: boolean; isSubscribedCalendar: boolean; isOwnedCalendar: boolean; isOrganizer: boolean; isInvitation: boolean; }) => { if (isUnknownCalendar) { return false; } if (isSubscribedCalendar) { return false; } if (isOwnedCalendar) { return isInvitation ? isOrganizer : true; } return !isInvitation; }; export const getCanChangeCalendarOfEvent = ({ isCreateEvent, isOwnedCalendar, isCalendarWritable, isSingleEdit, isInvitation, isAttendee, isOrganizer, }: { isCreateEvent: boolean; isOwnedCalendar: boolean; isCalendarWritable: boolean; isSingleEdit: boolean; isInvitation: boolean; isAttendee: boolean; isOrganizer: boolean; }) => { if (isCreateEvent) { return true; } if (!isCalendarWritable) { return false; } if (isInvitation) { if (!isOwnedCalendar) { return false; } if (isAttendee) { return !isSingleEdit; } if (isOrganizer) { return false; } // we should never fall here, but just in case return false; } return true; }; export const getCannotSaveEvent = ({ isOwnedCalendar, isOrganizer, numberOfAttendees, canEditSharedEventData = true, maxAttendees, }: { isOwnedCalendar: boolean; isOrganizer: boolean; numberOfAttendees: number; canEditSharedEventData?: boolean; maxAttendees?: number; }) => { if (!canEditSharedEventData) { // user is editing only notifications return false; } if (isOrganizer) { return !!getParticipantsError({ isOwnedCalendar, numberOfAttendees, maxAttendees }); } return false; }; export const getCanEditSharedEventData = ({ isOwnedCalendar, isCalendarWritable, isOrganizer, isAttendee, isInvitation, selfAddress, }: { isOwnedCalendar: boolean; isCalendarWritable: boolean; isOrganizer: boolean; isAttendee: boolean; isInvitation: boolean; selfAddress?: Address; }) => { if (!isCalendarWritable) { return false; } if (isInvitation) { if (isOwnedCalendar) { if (isAttendee) { return false; } if (isOrganizer) { return selfAddress ? getIsAddressActive(selfAddress) : false; } return false; } return false; } return true; }; export const getCanReplyToEvent = ({ isOwnedCalendar, isCalendarWritable, isAttendee, isCancelled, }: { isOwnedCalendar: boolean; isCalendarWritable: boolean; isAttendee: boolean; isCancelled: boolean; }) => { return isOwnedCalendar && isCalendarWritable && isAttendee && !isCancelled; }; export const getIsAvailableCalendar = ({ isOwnedCalendar, isCalendarWritable, isInvitation, }: { isOwnedCalendar: boolean; isCalendarWritable: boolean; isInvitation: boolean; }) => { if (!isCalendarWritable) { return false; } if (isInvitation) { return isOwnedCalendar; } return true; };
2,555
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/helpers/i18n.ts
import { c } from 'ttag'; import { VIEWS } from '@proton/shared/lib/calendar/constants'; const { DAY, WEEK, MONTH, YEAR, AGENDA, CUSTOM, MAIL, DRIVE, SEARCH } = VIEWS; export const getNavigationArrowsText = (view: VIEWS) => { const dayText = { previous: c('Action').t`Previous day`, next: c('Action').t`Next day`, }; const weekText = { previous: c('Action').t`Previous week`, next: c('Action').t`Next week`, }; const monthText = { previous: c('Action').t`Previous month`, next: c('Action').t`Next month`, }; const yearText = { previous: c('Action').t`Previous year`, next: c('Action').t`Next year`, }; const previous = { [DAY]: dayText.previous, [WEEK]: weekText.previous, [MONTH]: monthText.previous, [AGENDA]: monthText.previous, [CUSTOM]: monthText.previous, [YEAR]: yearText.previous, [MAIL]: weekText.previous, [DRIVE]: weekText.previous, [SEARCH]: weekText.previous, }; const next = { [DAY]: dayText.next, [WEEK]: weekText.next, [MONTH]: monthText.next, [AGENDA]: monthText.next, [CUSTOM]: monthText.next, [YEAR]: yearText.next, [MAIL]: weekText.next, [DRIVE]: weekText.next, [SEARCH]: weekText.next, }; return { next: next[view], previous: previous[view], }; };
2,556
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/helpers/invite.ts
import { getAttendeeEmail } from '@proton/shared/lib/calendar/attendees'; import { VcalVeventComponent } from '@proton/shared/lib/interfaces/calendar'; import { INVITE_ACTION_TYPES, InviteActions } from '../interfaces/Invite'; const { SEND_INVITATION, SEND_UPDATE, CHANGE_PARTSTAT, DECLINE_INVITATION, CANCEL_INVITATION } = INVITE_ACTION_TYPES; export const extractInviteEmails = ({ inviteActions, vevent, cancelVevent, }: { inviteActions: InviteActions; vevent?: VcalVeventComponent; cancelVevent?: VcalVeventComponent; }) => { const { type, addedAttendees, removedAttendees } = inviteActions; const hasAddedAttendees = !!addedAttendees?.length; const hasRemovedAttendees = !!removedAttendees?.length; const invitedEmails = vevent?.attendee?.map((attendee) => getAttendeeEmail(attendee)); const addedEmails = addedAttendees?.map((attendee) => getAttendeeEmail(attendee)); const removedEmails = removedAttendees?.map((attendee) => getAttendeeEmail(attendee)); const cancelledEmails = cancelVevent?.attendee?.map((attendee) => getAttendeeEmail(attendee)); const organizerEmail = vevent?.organizer ? getAttendeeEmail(vevent.organizer) : undefined; const emails: string[] = []; if (type === SEND_INVITATION) { if (!hasAddedAttendees && !hasRemovedAttendees && invitedEmails?.length) { emails.push(...invitedEmails); } else { if (addedEmails?.length) { emails.push(...addedEmails); } if (removedEmails?.length) { emails.push(...removedEmails); } } } else if (type === SEND_UPDATE) { if (invitedEmails?.length) { emails.push(...invitedEmails); } if (removedEmails?.length) { emails.push(...removedEmails); } } else if (type === CANCEL_INVITATION) { if (cancelledEmails?.length) { emails.push(...cancelledEmails); } } else if ([CHANGE_PARTSTAT, DECLINE_INVITATION].includes(type)) { if (organizerEmail) { emails.push(organizerEmail); } } return emails; };
2,557
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/helpers/time.ts
export const millisecondsToSeconds = (ms: number) => ~~(ms / 1000); export const secondsToMilliseconds = (s: number) => s * 1000;
2,558
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/helpers/timezoneSuggestion.ts
import { getSHA256String } from '@proton/shared/lib/helpers/crypto'; const DAY_IN_MILLISECONDS = 86400000; const LOCALSTORAGE_TZ_KEY = 'tzSuggestion'; export const getTimezoneSuggestionKey = async (userID: string) => { return getSHA256String(`${LOCALSTORAGE_TZ_KEY}${userID}`); }; export const getLastTimezoneSuggestion = (key: string) => { const defaultDate = new Date(2000, 0, 1); try { const lastSuggestion = parseInt(`${window.localStorage.getItem(key)}`, 10); const date = new Date(lastSuggestion); if (Number.isNaN(+date)) { return defaultDate; } return date; } catch (e: any) { return defaultDate; } }; export const saveLastTimezoneSuggestion = (key: string) => { try { const timestamp = +new Date(); window.localStorage.setItem(key, `${timestamp}`); // eslint-disable-next-line no-empty } catch (e: any) {} }; export const canAskTimezoneSuggestion = (key: string) => { return Date.now() - +getLastTimezoneSuggestion(key) >= DAY_IN_MILLISECONDS; };
2,559
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/helpers/views.ts
import { VIEWS } from '@proton/shared/lib/calendar/constants'; import { SUPPORTED_VIEWS_IN_DRAWER } from '../containers/calendar/constants'; import { VIEW_URL_PARAMS_VIEWS_CONVERSION } from '../containers/calendar/getUrlHelper'; export const getIsCalendarAppInDrawer = (view?: VIEWS) => { return view ? SUPPORTED_VIEWS_IN_DRAWER.includes(view) : false; }; export const getViewString = (view?: VIEWS) => { if (!view) { return ''; } return VIEW_URL_PARAMS_VIEWS_CONVERSION[view] || ''; };
2,560
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/helpers/encryptedSearch/calendarESCallbacks.tsx
import { History } from 'history'; import { CachedItem, ESCallbacks, ESItemInfo, ESStatusBooleans, ES_MAX_CONCURRENT, ES_MAX_ITEMS_PER_BATCH, EventsObject, RecordProgress, checkVersionedESDB, esSentryReport, metadataIndexingProgress, normalizeKeyword, storeItemsMetadata, testKeywords, } from '@proton/encrypted-search'; import { getEventsCount, queryLatestModelEventID } from '@proton/shared/lib/api/calendars'; import { getLatestID } from '@proton/shared/lib/api/events'; import runInQueue from '@proton/shared/lib/helpers/runInQueue'; import { Api } from '@proton/shared/lib/interfaces'; import { GetCalendarEventRaw } from '@proton/shared/lib/interfaces/hooks/GetCalendarEventRaw'; import chunk from '@proton/utils/chunk'; import { ESCalendarContent, ESCalendarMetadata, ESCalendarSearchParams, MetadataRecoveryPoint, } from '../../interfaces/encryptedSearch'; import { generateEventUniqueId } from '../event'; import { CALENDAR_CORE_LOOP, MAX_EVENT_BATCH, MIN_EVENT_BATCH } from './constants'; import { extractAttendees, extractOrganizer, getESEvent, getESEventsFromCalendarInBatch, parseSearchParams, searchUndecryptedElements, transformAttendees, transformOrganizer, } from './esUtils'; interface Props { api: Api; calendarIDs: string[]; history: History; userID: string; getCalendarEventRaw: GetCalendarEventRaw; } interface ItemMetadataQueryResult { resultMetadata?: ESCalendarMetadata[]; setRecoveryPoint?: (setIDB?: boolean) => Promise<void>; } const popOneCalendar = ( calendarIDs: string[] ): Pick<MetadataRecoveryPoint, 'remainingCalendarIDs' | 'currentCalendarId'> => { const [first, ...rest] = calendarIDs; return { remainingCalendarIDs: rest, currentCalendarId: first, }; }; export const getESCallbacks = ({ api, calendarIDs, history, userID, getCalendarEventRaw, }: Props): ESCallbacks<ESCalendarMetadata, ESCalendarSearchParams, ESCalendarContent> => { // We need to keep the recovery point for metadata indexing in memory // for cases where IDB couldn't be instantiated but we still want to // index content let metadataRecoveryPoint: MetadataRecoveryPoint | undefined; const queryItemsMetadata = async ( signal: AbortSignal, isBackgroundIndexing?: boolean ): Promise<ItemMetadataQueryResult> => { let recoveryPoint: MetadataRecoveryPoint = metadataRecoveryPoint ?? popOneCalendar(calendarIDs); // Note that indexing, and therefore an instance of this function, // can exist even without an IDB, because we can index in memory only. // Therefore, we have to check if an IDB exists before querying it const esdbExists = await checkVersionedESDB(userID); if (esdbExists) { const localRecoveryPoint: MetadataRecoveryPoint = await metadataIndexingProgress.readRecoveryPoint(userID); if (localRecoveryPoint) { recoveryPoint = localRecoveryPoint; } } const { currentCalendarId } = recoveryPoint; if (!currentCalendarId) { return { resultMetadata: [] }; } /** * On calendar with a lot of events, having a pseudo-random batch size on each iteration makes the indexing look a bit more dynamic */ const batchSize = Math.floor(Math.random() * (MAX_EVENT_BATCH - MIN_EVENT_BATCH + 1)) + MIN_EVENT_BATCH; const { events: esMetadataEvents, cursor: newCursor } = await getESEventsFromCalendarInBatch({ calendarID: currentCalendarId, limit: batchSize, eventCursor: recoveryPoint.eventCursor, api, getCalendarEventRaw, }); const newRecoveryPoint: MetadataRecoveryPoint = newCursor ? { ...recoveryPoint, eventCursor: newCursor, } : popOneCalendar(recoveryPoint.remainingCalendarIDs); const setNewRecoveryPoint = esdbExists ? async (setIDB: boolean = true) => { metadataRecoveryPoint = newRecoveryPoint; if (setIDB) { await metadataIndexingProgress.setRecoveryPoint(userID, newRecoveryPoint); } } : undefined; // some calendars might have no event so if there is others, we want to forward query to them if (!esMetadataEvents.length && newRecoveryPoint.currentCalendarId) { await setNewRecoveryPoint?.(); return queryItemsMetadata(signal, isBackgroundIndexing); } return { resultMetadata: esMetadataEvents, setRecoveryPoint: setNewRecoveryPoint, }; }; const getPreviousEventID = async () => { const eventObject: { [key: string]: string } = {}; // Calendars previous events await Promise.all( calendarIDs.map(async (ID) => { const { CalendarModelEventID } = await api<{ CalendarModelEventID: string }>( queryLatestModelEventID(ID) ); eventObject[ID] = CalendarModelEventID; }) ); // Core previous event const { EventID } = await api<{ EventID: string }>(getLatestID()); eventObject[CALENDAR_CORE_LOOP] = EventID; return eventObject; }; const getItemInfo = (item: ESCalendarMetadata): ESItemInfo => ({ ID: generateEventUniqueId(item.CalendarID, item.ID), timepoint: [item.CreateTime, item.Order], }); const getSearchParams = () => { const { isSearch, esSearchParams } = parseSearchParams(history.location); return { isSearch, esSearchParams, }; }; const getKeywords = (esSearchParams: ESCalendarSearchParams) => esSearchParams.keyword ? normalizeKeyword(esSearchParams.keyword) : []; const searchKeywords = ( keywords: string[], itemToSearch: CachedItem<ESCalendarMetadata, ESCalendarContent>, hasApostrophe: boolean ) => { const { metadata } = itemToSearch; const stringsToSearch: string[] = [ metadata?.Description || '', metadata?.Location || '', metadata?.Summary || '', ...transformOrganizer(extractOrganizer(metadata?.Organizer)), ...transformAttendees(extractAttendees(metadata?.Attendees)), ]; return testKeywords(keywords, stringsToSearch, hasApostrophe); }; const getTotalItems = async () => { const counts = await Promise.all(calendarIDs.map((ID) => api<{ Total: number }>(getEventsCount(ID)))); return counts.reduce((p, c) => p + c.Total, 0); }; const getEventFromIDB = async (previousEventsObject?: EventsObject) => ({ newEvents: [], shouldRefresh: false, eventsToStore: previousEventsObject ?? {}, }); const applyFilters = (esSearchParams: ESCalendarSearchParams, metadata: ESCalendarMetadata) => { const { calendarID, begin, end } = esSearchParams; if (!metadata.IsDecryptable) { return false; } const { CalendarID, StartTime, EndTime, RRule } = metadata; // If it's the wrong calendar, we exclude it if (calendarID && calendarID !== CalendarID) { return false; } // If it's recurrent, we don't immediately check the timings since that will // be done upon displaying the search results if (typeof RRule === 'string') { return true; } // Check it's within time window selected by the user if ((begin && EndTime < begin) || (end && StartTime > end)) { return false; } return true; }; const correctDecryptionErrors = async ( userID: string, indexKey: CryptoKey, abortIndexingRef: React.MutableRefObject<AbortController>, esStatus: ESStatusBooleans, recordProgress: RecordProgress ) => { if (esStatus.isEnablingEncryptedSearch || !esStatus.esEnabled) { return 0; } let correctedEventsCount = 0; let events = await searchUndecryptedElements(userID, indexKey, abortIndexingRef); void recordProgress([0, events.length], 'metadata'); const chunks = chunk(events, ES_MAX_ITEMS_PER_BATCH); for (const chunk of chunks) { const metadatas = await runInQueue( chunk.map(({ ID, CalendarID }) => () => { return getESEvent(ID, CalendarID, api, getCalendarEventRaw); }), ES_MAX_CONCURRENT ); const decryptedMetadatas = metadatas.filter((item) => item.IsDecryptable); // if we reach this part of code, es is considered supported const esSupported = true; const success = await storeItemsMetadata<ESCalendarMetadata>( userID, decryptedMetadatas, esSupported, indexKey, getItemInfo ).catch((error: any) => { if (!(error?.message === 'Operation aborted') && !(error?.name === 'AbortError')) { esSentryReport('storeItemsBatches: storeItems', { error }); } return false; }); if (!success) { break; } correctedEventsCount += decryptedMetadatas.length; void recordProgress(correctedEventsCount, 'metadata'); } return correctedEventsCount; }; return { queryItemsMetadata, getPreviousEventID, getItemInfo, getSearchParams, getKeywords, searchKeywords, getTotalItems, getEventFromIDB, applyFilters, correctDecryptionErrors, }; };
2,561
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/helpers/encryptedSearch/constants.ts
export const CALENDAR_CORE_LOOP = 'core'; export const MIN_EVENT_BATCH = 20; export const MAX_EVENT_BATCH = 100;
2,562
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/helpers/encryptedSearch/esUtils.ts
import { Location } from 'history'; import { CryptoProxy } from '@proton/crypto'; import { CachedItem, ESEvent, ESItemEvent, ES_MAX_CONCURRENT, ES_MAX_ITEMS_PER_BATCH, ES_SYNC_ACTIONS, EncryptedItemWithInfo, EventsObject, apiHelper, decryptFromDB, normalizeKeyword, readAllLastEvents, readMetadataBatch, readMetadataItem, readSortedIDs, } from '@proton/encrypted-search'; import { getEvent, queryEventsIDs, queryLatestModelEventID } from '@proton/shared/lib/api/calendars'; import { EVENT_ACTIONS } from '@proton/shared/lib/constants'; import runInQueue from '@proton/shared/lib/helpers/runInQueue'; import { getSearchParams as getSearchParamsFromURL, stringifySearchParams } from '@proton/shared/lib/helpers/url'; import { isNumber } from '@proton/shared/lib/helpers/validators'; import { Api, SimpleMap } from '@proton/shared/lib/interfaces'; import { CalendarEvent, CalendarEventWithoutBlob, CalendarEventsIDsQuery, VcalAttendeeProperty, VcalOrganizerProperty, } from '@proton/shared/lib/interfaces/calendar'; import { CalendarEventManager, CalendarEventsEventManager } from '@proton/shared/lib/interfaces/calendar/EventManager'; import { GetCalendarEventRaw } from '@proton/shared/lib/interfaces/hooks/GetCalendarEventRaw'; import unique from '@proton/utils/unique'; import { propertiesToAttendeeModel } from '../../components/eventModal/eventForm/propertiesToAttendeeModel'; import { propertiesToOrganizerModel } from '../../components/eventModal/eventForm/propertiesToOrganizerModel'; import { CalendarSearchQuery } from '../../containers/calendar/interface'; import { ESAttendeeModel, ESCalendarContent, ESCalendarMetadata, ESCalendarSearchParams, ESOrganizerModel, } from '../../interfaces/encryptedSearch'; import { generateEventUniqueId, getCalendarIDFromUniqueId, getEventIDFromUniqueId } from '../event'; import { CALENDAR_CORE_LOOP } from './constants'; export const getEventKey = (calendarID: string, uid: string) => `${calendarID}-${uid}`; export const generateOrder = async (ID: string) => { const numericalID = ID.split('').map((char) => char.charCodeAt(0)); const digest = await CryptoProxy.computeHash({ algorithm: 'unsafeMD5', data: Uint8Array.from(numericalID) }); const orderArray = new Uint32Array(digest.buffer); return orderArray[0]; }; const checkIsSearch = (searchParams: ESCalendarSearchParams) => !!searchParams.calendarID || !!searchParams.begin || !!searchParams.end || !!searchParams.keyword; const stringToInt = (string: string | undefined): number | undefined => { if (string === undefined) { return undefined; } return isNumber(string) ? parseInt(string, 10) : undefined; }; export const generatePathnameWithSearchParams = (location: Location, searchQuery: CalendarSearchQuery) => { const parts = location.pathname.split('/'); parts[1] = 'search'; const pathname = parts.join('/'); const hash = stringifySearchParams(searchQuery as { [key: string]: string }, '#'); return pathname + hash; }; export const extractSearchParameters = (location: Location): ESCalendarSearchParams => { const { calendarID, keyword, begin, end, page } = getSearchParamsFromURL(location.hash); return { calendarID, page: stringToInt(page), keyword: keyword ?? undefined, begin: stringToInt(begin), end: stringToInt(end), }; }; export const parseSearchParams = (location: Location) => { const searchParameters = extractSearchParameters(location); const isSearch = checkIsSearch(searchParameters); return { isSearch, esSearchParams: { ...searchParameters, ...(isSearch && searchParameters?.keyword ? { normalizedKeywords: normalizeKeyword(searchParameters.keyword) } : undefined), }, }; }; export const transformOrganizer = (organizer: ESOrganizerModel) => [ organizer.email.toLocaleLowerCase(), organizer.cn.toLocaleLowerCase(), ]; export const transformAttendees = (attendees: ESAttendeeModel[]) => [ ...attendees.map((attendee) => attendee.email.toLocaleLowerCase()), ...attendees.map((attendee) => attendee.cn.toLocaleLowerCase()), ]; export const getAllEventsIDs = async (calendarID: string, api: Api, Limit: number = 100) => { const result: string[] = []; let previousLength = -1; const params: CalendarEventsIDsQuery = { Limit, AfterID: undefined, }; while (result.length > previousLength) { previousLength = result.length; const { IDs } = await api<{ IDs: string[] }>(queryEventsIDs(calendarID, params)); result.push(...IDs); params.AfterID = IDs[IDs.length - 1]; } return result; }; export const extractOrganizer = (organizerProperty?: VcalOrganizerProperty): ESOrganizerModel => { const { email = '', cn = '' } = propertiesToOrganizerModel(organizerProperty) || {}; return { email, cn }; }; export const extractAttendees = (attendeeProperty: VcalAttendeeProperty[]): ESAttendeeModel[] => { const attendees = propertiesToAttendeeModel(attendeeProperty); return attendees.map(({ email, cn, role, partstat }) => ({ email, cn, role, partstat })); }; export const getESEvent = async ( eventID: string, calendarID: string, api: Api, getCalendarEventRaw: GetCalendarEventRaw, signal?: AbortSignal ): Promise<ESCalendarMetadata> => { const response = await apiHelper<{ Event: CalendarEvent }>( api, signal, getEvent(calendarID, eventID), 'queryEventMetadata' ); if (!response?.Event) { throw new Error('Could not fetch event metadata'); } const { Event } = response; let hasError = false; const { veventComponent } = await getCalendarEventRaw(Event).catch((error) => { console.error('cannot decrypt event: ', error); hasError = true; return { veventComponent: { status: undefined, summary: undefined, location: undefined, description: undefined, organizer: undefined, attendee: [], }, }; }); return { Status: veventComponent.status?.value || '', Summary: veventComponent.summary?.value || '', Location: veventComponent.location?.value || '', Description: veventComponent.description?.value || '', Attendees: veventComponent.attendee ?? [], Organizer: veventComponent.organizer, Order: await generateOrder(generateEventUniqueId(calendarID, eventID)), ID: Event.ID, SharedEventID: Event.SharedEventID, CalendarID: Event.CalendarID, CreateTime: Event.CreateTime, ModifyTime: Event.ModifyTime, Permissions: Event.Permissions, IsOrganizer: Event.IsOrganizer, IsProtonProtonInvite: Event.IsProtonProtonInvite, Author: Event.Author, StartTime: Event.StartTime, StartTimezone: Event.StartTimezone, EndTime: Event.EndTime, EndTimezone: Event.EndTimezone, FullDay: Event.FullDay, RRule: Event.RRule, UID: Event.UID, RecurrenceID: Event.RecurrenceID, Exdates: Event.Exdates, IsDecryptable: !hasError, }; }; export const getAllESEventsFromCalendar = async ( calendarID: string, api: Api, getCalendarEventRaw: GetCalendarEventRaw ) => { const eventIDs = await getAllEventsIDs(calendarID, api, 1000); return runInQueue( eventIDs.map((eventID) => () => getESEvent(eventID, calendarID, api, getCalendarEventRaw)), ES_MAX_CONCURRENT ); }; /** * Fetches a batch of events from a calendar * * @returns if calendar has still more events after cursor + limit, then it will be return last fetched event as new cursor */ export const getESEventsFromCalendarInBatch = async ({ calendarID, limit, eventCursor, api, getCalendarEventRaw, }: { calendarID: string; limit: number; eventCursor?: string; api: Api; getCalendarEventRaw: GetCalendarEventRaw; }) => { const params: CalendarEventsIDsQuery = { Limit: limit, AfterID: eventCursor, }; const { IDs: eventIDs } = await api<{ IDs: string[] }>(queryEventsIDs(calendarID, params)); const cursor = eventIDs.length === limit ? eventIDs[eventIDs.length - 1] : undefined; const events = await runInQueue( eventIDs.map( // eslint-disable-next-line @typescript-eslint/no-loop-func (eventID) => () => getESEvent(eventID, calendarID, api, getCalendarEventRaw) ), ES_MAX_CONCURRENT ); return { events, cursor, }; }; const pushToRecurrenceIDsMap = (map: SimpleMap<number[]>, calendarID: string, UID: string, recurrenceID: number) => { const key = getEventKey(calendarID, UID); const entry = map[key]; map[key] = entry ? [...entry, recurrenceID] : [recurrenceID]; }; const getItemMetadataFromEventID = async (eventID: string, userID: string, itemIDs: string[], indexKey: CryptoKey) => { const itemID = itemIDs.find((itemID) => getEventIDFromUniqueId(itemID) === eventID); if (!itemID) { return; } return readMetadataItem<ESCalendarMetadata>(userID, itemID, indexKey); }; const handleCreateRecurrenceIDInMap = (map: SimpleMap<number[]>, event: CalendarEventWithoutBlob) => { const { CalendarID, UID, RecurrenceID } = event; if (!RecurrenceID) { return; } pushToRecurrenceIDsMap(map, CalendarID, UID, RecurrenceID); }; const handleDeleteRecurrenceIDInMap = async ( map: SimpleMap<number[]>, eventID: string, userID: string, itemIDs: string[], indexKey: CryptoKey ) => { const metadata = await getItemMetadataFromEventID(eventID, userID, itemIDs, indexKey); if (!metadata?.RecurrenceID) { return; } pushToRecurrenceIDsMap(map, metadata.CalendarID, metadata.UID, metadata.RecurrenceID); }; /** * Builds a global map of recurrence ids */ export const buildRecurrenceIDsMap = (cache: Map<string, CachedItem<ESCalendarMetadata, ESCalendarContent>>) => { const result: SimpleMap<number[]> = {}; const iterator = cache.values(); let iteration = iterator.next(); while (!iteration.done) { const { metadata: { CalendarID, UID, RecurrenceID }, } = iteration.value; iteration = iterator.next(); if (!RecurrenceID) { continue; } pushToRecurrenceIDsMap(result, CalendarID, UID, RecurrenceID); } return result; }; export const updateRecurrenceIDsMap = async ( userID: string, indexKey: CryptoKey, events: CalendarEventsEventManager[], updateMap: (setter: (map: SimpleMap<number[]>) => SimpleMap<number[]>) => void ) => { const additions: SimpleMap<number[]> = {}; const deletions: SimpleMap<number[]> = {}; const itemIDs: string[] = []; if (events.some(({ Action }) => [EVENT_ACTIONS.DELETE, EVENT_ACTIONS.UPDATE].includes(Action))) { itemIDs.push(...((await readSortedIDs(userID, false)) || [])); } await Promise.all( events.map(async (event) => { if (event.Action === EVENT_ACTIONS.DELETE) { handleDeleteRecurrenceIDInMap(deletions, event.ID, userID, itemIDs, indexKey); } else if (event.Action === EVENT_ACTIONS.CREATE) { handleCreateRecurrenceIDInMap(additions, event.Event); } else if (event.Action === EVENT_ACTIONS.UPDATE) { handleCreateRecurrenceIDInMap(additions, event.Event); handleDeleteRecurrenceIDInMap(deletions, event.ID, userID, itemIDs, indexKey); } }) ); updateMap((map: SimpleMap<number[]>) => { const result: SimpleMap<number[]> = { ...map }; Object.entries(additions).forEach(([UID, recurrenceIDs]) => { const value = unique([...(result[UID] || []), ...(recurrenceIDs || [])]); result[UID] = value.length ? value : undefined; }); Object.entries(deletions).forEach(([UID, recurrenceIDs]) => { result[UID] = result[UID]?.filter((recurrenceID) => !recurrenceIDs?.includes(recurrenceID)); }); return result; }); }; /** * Returns all the elements stored in the IDB and flagged as not decryptable */ export const searchUndecryptedElements = async ( userID: string, indexKey: CryptoKey, abortSearchingRef?: React.MutableRefObject<AbortController> ): Promise<ESCalendarMetadata[]> => { const results: ESCalendarMetadata[] = []; let remainingIDs = await readSortedIDs(userID, false); if (!remainingIDs?.length) { return results; } while (remainingIDs.length) { const IDs = remainingIDs.slice(0, ES_MAX_ITEMS_PER_BATCH); remainingIDs = remainingIDs?.slice(ES_MAX_ITEMS_PER_BATCH); const metadatas = await readMetadataBatch(userID, IDs); if (!metadatas || abortSearchingRef?.current.signal.aborted) { return results; } const plaintextMetadatas: ESCalendarMetadata[] = await Promise.all( metadatas .filter((item): item is EncryptedItemWithInfo => !!item) .map(async (encryptedMetadata) => { const plaintextMetadata = await decryptFromDB<ESCalendarMetadata>( encryptedMetadata.aesGcmCiphertext, indexKey ); return plaintextMetadata; }) ); const undecryptedMetadatas = plaintextMetadatas.filter((item) => !item.IsDecryptable); results.push(...undecryptedMetadatas); } return results; }; export const processCoreEvents = async ({ userID, Calendars, Refresh, EventID, api, getCalendarEventRaw, }: { userID: string; Calendars: CalendarEventManager[]; Refresh: number; EventID: string; api: Api; getCalendarEventRaw: GetCalendarEventRaw; }): Promise<ESEvent<ESCalendarMetadata> | undefined> => { if (!Calendars.length && !Refresh) { return; } // Get all existing event loops const oldEventsObject = await readAllLastEvents(userID); if (!oldEventsObject) { return; } const eventLoopsToDelete = []; const newEventsObject: EventsObject = {}; const Items: ESItemEvent<ESCalendarMetadata>[] = []; for (const { ID, Action } of Calendars) { if (Action === EVENT_ACTIONS.CREATE) { // Get events from API and add them, plus add calendarID to event object const { CalendarModelEventID } = await api<{ CalendarModelEventID: string }>(queryLatestModelEventID(ID)); newEventsObject[ID] = CalendarModelEventID; const maybeEventsFromCalendar = (await getAllESEventsFromCalendar(ID, api, getCalendarEventRaw)) .filter((item): item is ESCalendarMetadata => !!item) .map((item) => ({ ID: generateEventUniqueId(item.CalendarID, item.ID), Action: ES_SYNC_ACTIONS.CREATE, ItemMetadata: item, })); Items.push(...maybeEventsFromCalendar); } else if (Action === EVENT_ACTIONS.DELETE) { // Get from IDB all items such that itemID={calendarID}.* and delete them, plus+ remove calendarID from event object eventLoopsToDelete.push(ID); const itemIDs = (await readSortedIDs(userID, false)) || []; Items.push( ...itemIDs .filter((itemID) => getCalendarIDFromUniqueId(itemID) === ID) .map((itemID) => ({ ID: itemID, Action: ES_SYNC_ACTIONS.DELETE, ItemMetadata: undefined })) ); } } for (const componentID in oldEventsObject) { if (!eventLoopsToDelete.includes(componentID)) { const lastEventID = oldEventsObject[componentID]; newEventsObject[componentID] = lastEventID; } } newEventsObject[CALENDAR_CORE_LOOP] = EventID; return { Refresh, Items, eventsToStore: newEventsObject, }; }; export const processCalendarEvents = async ( CalendarEvents: CalendarEventsEventManager[], Refresh: number, userID: string, CalendarModelEventID: string, api: Api, getCalendarEventRaw: GetCalendarEventRaw ): Promise<ESEvent<ESCalendarMetadata> | undefined> => { if (!CalendarEvents.length && !Refresh) { return; } // Get all existing event loops const oldEventsObject = await readAllLastEvents(userID); if (!oldEventsObject) { return; } const Items: ESItemEvent<ESCalendarMetadata>[] = []; const newEventsObject: EventsObject = {}; const itemIDs = (await readSortedIDs(userID, false)) || []; for (const CalendarEvent of CalendarEvents) { const { ID, Action } = CalendarEvent; let calendarID: string | undefined; if (Action === EVENT_ACTIONS.DELETE) { // If it's a delete event, we should have the item already in IDB, therefore // we can deduce the calendar ID from it const itemID = itemIDs.find((itemID) => getEventIDFromUniqueId(itemID) === ID); if (itemID) { calendarID = getCalendarIDFromUniqueId(itemID); Items.push({ ID: itemID, Action: ES_SYNC_ACTIONS.DELETE, ItemMetadata: undefined }); } } else { // In case of update or create events, instead, we have the calendar ID in the event const { CalendarID } = CalendarEvent.Event; calendarID = CalendarID; const esAction = EVENT_ACTIONS.UPDATE ? ES_SYNC_ACTIONS.UPDATE_METADATA : ES_SYNC_ACTIONS.CREATE; const esItem = await getESEvent(ID, CalendarID, api, getCalendarEventRaw); if (esItem) { Items.push({ ID: generateEventUniqueId(CalendarID, ID), Action: esAction, ItemMetadata: esItem }); } } if (calendarID) { newEventsObject[calendarID] = CalendarModelEventID; } } for (const componentID in oldEventsObject) { const last: string | undefined = newEventsObject[componentID]; if (typeof last === 'undefined') { const lastEventID = oldEventsObject[componentID]; newEventsObject[componentID] = lastEventID; } } return { Refresh, Items, eventsToStore: newEventsObject, }; };
2,563
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/helpers/test/NotificationsTestProvider.tsx
import React, { useRef, useState } from 'react'; import NotificationsContainer from '@proton/components/containers/notifications/Container'; import { Notification } from '@proton/components/containers/notifications/interfaces'; import createNotificationManager from '@proton/components/containers/notifications/manager'; import NotificationsContext from '@proton/components/containers/notifications/notificationsContext'; import noop from '@proton/utils/noop'; interface Props { children: React.ReactNode; } const NotificationsTestProvider = ({ children }: Props) => { const [notifications, setNotifications] = useState<Notification[]>([]); const managerRef = useRef<ReturnType<typeof createNotificationManager>>(); if (!managerRef.current) { managerRef.current = createNotificationManager(setNotifications as any, noop); } const manager = managerRef.current; const { hideNotification, removeNotification, removeDuplicate } = manager; return ( <NotificationsContext.Provider value={manager}> {children} <NotificationsContainer notifications={notifications} removeNotification={removeNotification} removeDuplicate={removeDuplicate} hideNotification={hideNotification} /> </NotificationsContext.Provider> ); }; export default NotificationsTestProvider;
2,564
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/helpers
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/helpers/test/render.tsx
import { ReactElement, ReactNode } from 'react'; import * as React from 'react'; import { Router } from 'react-router'; import { render as originalRender } from '@testing-library/react'; import { renderHook as originalRenderHook } from '@testing-library/react-hooks'; import { createMemoryHistory } from 'history'; import { CacheProvider, ExperimentsProvider, ModalsChildren, ModalsProvider } from '@proton/components'; import ConfigProvider from '@proton/components/containers/config/Provider'; import { APPS } from '@proton/shared/lib/constants'; import createCache from '@proton/shared/lib/helpers/cache'; import { ProtonConfig } from '@proton/shared/lib/interfaces'; import NotificationsTestProvider from './NotificationsTestProvider'; jest.mock('@proton/shared/lib/helpers/setupCryptoWorker', () => ({ __esModule: true, loadCryptoWorker: jest.fn(), })); const history = createMemoryHistory({ initialEntries: ['/'] }); const config = { APP_NAME: APPS.PROTONCALENDAR, APP_VERSION: 'test-app-version', DATE_VERSION: 'test-date-version', } as ProtonConfig; const TestProvider = ({ children }: { children: ReactNode }) => ( <ConfigProvider config={config}> <NotificationsTestProvider> <ModalsProvider> <CacheProvider cache={createCache()}> <ExperimentsProvider> <ModalsChildren /> <Router history={history}>{children}</Router> </ExperimentsProvider> </CacheProvider> </ModalsProvider> </NotificationsTestProvider> </ConfigProvider> ); export const render = (ui: ReactElement) => originalRender(ui, { wrapper: TestProvider, }); export const renderHook = <TProps, TResult>(callback: (props: TProps) => TResult) => originalRenderHook<TProps, TResult>(callback, { wrapper: TestProvider as any });
2,565
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/hooks/observeRect.ts
export interface Rect { width: number; height: number; top: number; right: number; bottom: number; left: number; } type Callback = (rect: Rect) => void; const props = ['width', 'height', 'top', 'right', 'bottom', 'left']; const rectChanged = (a: any = {}, b: any = {}) => props.some((prop) => a[prop] !== b[prop]); const observedNodes = new Map(); let rafId = 0; const run = () => { observedNodes.forEach((state) => { if (state.hasRectChanged) { state.callbacks.forEach((cb: Callback) => cb(state.rect)); state.hasRectChanged = false; } }); setTimeout(() => { observedNodes.forEach((state, node) => { const newRect = node.getBoundingClientRect(); if (rectChanged(newRect, state.rect)) { state.hasRectChanged = true; state.rect = newRect; } }); }, 0); rafId = requestAnimationFrame(run); }; export default (node: HTMLElement, cb: Callback) => { const wasEmpty = observedNodes.size === 0; if (observedNodes.has(node)) { const { callbacks, rect, hasRectChanged } = observedNodes.get(node); callbacks.push(cb); if (rect && !hasRectChanged) { cb(rect); } } else { observedNodes.set(node, { rect: undefined, hasRectChanged: false, callbacks: [cb], }); } if (wasEmpty) { run(); } return () => { const state = observedNodes.get(node); if (!state) { return; } const index = state.callbacks.indexOf(cb); if (index >= 0) { state.callbacks.splice(index, 1); } if (!state.callbacks.length) { observedNodes.delete(node); } if (!observedNodes.size) { cancelAnimationFrame(rafId); } }; };
2,566
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/hooks/useCalendarFavicon.ts
import { useDynamicFavicon } from '@proton/components/hooks'; import useDynamicMonthDay from '@proton/components/hooks/useDynamicMonthDay'; import favicons from '../../assets/favicons'; const useCalendarFavicon = () => { const monthDay = useDynamicMonthDay(); useDynamicFavicon(favicons[monthDay]); }; export default useCalendarFavicon;
2,567
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/hooks/useGetOpenedMailEvents.tsx
import { useCallback, useEffect, useRef } from 'react'; import { VIEWS } from '@proton/shared/lib/calendar/constants'; import { APPS } from '@proton/shared/lib/constants'; import { getIsDrawerPostMessage, postMessageFromIframe } from '@proton/shared/lib/drawer/helpers'; import { DRAWER_EVENTS } from '@proton/shared/lib/drawer/interfaces'; const getIsMatch = (existingEvent: OpenedMailEvent, newEvent: OpenedMailEvent) => { const { messageID: existingMessageID, UID: existingUID } = existingEvent; const { messageID: newMessageID, UID: newUID } = newEvent; return newMessageID === existingMessageID && newUID === existingUID; }; export interface OpenedMailEvent { messageID: string; UID: string; } export const useGetOpenedMailEvents = (drawerView?: VIEWS): (() => OpenedMailEvent[]) => { const isMailView = drawerView === VIEWS.MAIL; const ref = useRef<OpenedMailEvent[]>([]); useEffect(() => { if (isMailView) { // Ask Mail if calendar events are opened already postMessageFromIframe({ type: DRAWER_EVENTS.REQUEST_OPEN_EVENTS }, APPS.PROTONMAIL); } }, [isMailView]); useEffect(() => { const handleMessageEvents = (event: MessageEvent) => { if (!getIsDrawerPostMessage(event)) { return; } if (event.data.type === DRAWER_EVENTS.SET_WIDGET_EVENT) { const newOpenedMailEvent = event.data.payload; if (!ref.current.some((event) => getIsMatch(event, newOpenedMailEvent))) { ref.current.push({ ...newOpenedMailEvent }); } } if (event.data.type === DRAWER_EVENTS.UNSET_WIDGET_EVENT) { const newOpenedMailEvent = event.data.payload; const index = ref.current.findIndex((event) => getIsMatch(event, newOpenedMailEvent)); if (index !== -1) { ref.current.splice(index, 1); } } }; window.addEventListener('message', handleMessageEvents); return () => { window.removeEventListener('message', handleMessageEvents); }; }, []); return useCallback(() => { return ref.current; }, []); };
2,568
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/hooks/useOpenCalendarEvents.tsx
import { Dispatch, SetStateAction, useCallback } from 'react'; import { getDateOrDateTimeProperty, propertyToUTCDate } from '@proton/shared/lib/calendar/vcalConverter'; import { startOfDay } from '@proton/shared/lib/date-fns-utc'; import { convertUTCDateTimeToZone, fromUTCDate, fromUTCDateToLocalFakeUTCDate, toUTCDate, } from '@proton/shared/lib/date/timezone'; import { CalendarEventSharedData, VcalVeventComponent } from '@proton/shared/lib/interfaces/calendar'; import { getViewEventDateProperties } from '../containers/calendar/eventHelper'; import { EventTargetAction } from '../containers/calendar/interface'; import { generateEventUniqueId } from '../helpers/event'; interface Props { onChangeDate: (newDate: Date) => void; tzid: string; setEventTargetAction: Dispatch<SetStateAction<EventTargetAction | undefined>>; preventPopover?: boolean; } export const useOpenCalendarEvents = ({ onChangeDate, tzid, setEventTargetAction, preventPopover }: Props) => { const navigateToEvent = useCallback( (utcDate: Date, isAllDay: boolean) => { const fakeUTCDate = fromUTCDateToLocalFakeUTCDate(utcDate, isAllDay, tzid); onChangeDate(startOfDay(fakeUTCDate)); }, [tzid, setEventTargetAction] ); const goToEvent = useCallback( (eventData: CalendarEventSharedData, eventComponent: VcalVeventComponent) => { const { utcStart, isAllDay, isAllPartDay } = getViewEventDateProperties(eventComponent); const startInTzid = toUTCDate(convertUTCDateTimeToZone(fromUTCDate(utcStart), tzid)); navigateToEvent(utcStart, isAllDay); setEventTargetAction({ uniqueId: `${generateEventUniqueId(eventData.CalendarID, eventData.ID)}`, isAllDay, isAllPartDay, startInTzid, preventPopover, }); }, [setEventTargetAction, onChangeDate, tzid, navigateToEvent] ); const goToOccurrence = useCallback( ( eventData: CalendarEventSharedData, eventComponent: VcalVeventComponent, occurrence: { localStart: Date; occurrenceNumber: number } ) => { const { isAllDay, isAllPartDay } = getViewEventDateProperties(eventComponent); const withOccurrenceDtstart = getDateOrDateTimeProperty(eventComponent.dtstart, occurrence.localStart); const utcDate = propertyToUTCDate(withOccurrenceDtstart); const startInTzid = toUTCDate(convertUTCDateTimeToZone(fromUTCDate(utcDate), tzid)); navigateToEvent(utcDate, isAllDay); setEventTargetAction({ uniqueId: `${generateEventUniqueId(eventData.CalendarID, eventData.ID)}-${occurrence.occurrenceNumber}`, isAllDay, isAllPartDay, startInTzid, preventPopover, }); }, [setEventTargetAction, onChangeDate, navigateToEvent] ); return { goToEvent, goToOccurrence }; }; export default useOpenCalendarEvents;
2,569
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/hooks/useOpenEvent.ts
import {getRecurrenceIdDate} from '@proton/shared/lib/calendar/veventHelper'; import { useCallback } from 'react'; import { getUnixTime } from 'date-fns'; import { useApi, useCache } from '@proton/components'; import { getEvent, updateMember } from '@proton/shared/lib/api/calendars'; import { MAXIMUM_DATE, MINIMUM_DATE } from '@proton/shared/lib/calendar/constants'; import { getMemberAndAddress } from '@proton/shared/lib/calendar/members'; import getRecurrenceIdValueFromTimestamp from '@proton/shared/lib/calendar/recurrence/getRecurrenceIdValueFromTimestamp'; import { getOccurrences } from '@proton/shared/lib/calendar/recurrence/recurring'; import { getIsPropertyAllDay, getPropertyTzid } from '@proton/shared/lib/calendar/vcalHelper'; import { addMilliseconds, isSameDay } from '@proton/shared/lib/date-fns-utc'; import { toUTCDate } from '@proton/shared/lib/date/timezone'; import { Address } from '@proton/shared/lib/interfaces'; import { CalendarEvent, VcalVeventComponent, VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import { CalendarsModel } from '@proton/shared/lib/models'; import { loadModels } from '@proton/shared/lib/models/helper'; import parseMainEventData from '../containers/calendar/event/parseMainEventData'; import getAllEventsByUID from '../containers/calendar/getAllEventsByUID'; interface HandlerProps { calendars: VisualCalendar[]; addresses: Address[]; calendarID: string | null; eventID: string | null; recurrenceId: string | null; onGoToEvent: (eventData: CalendarEvent, eventComponent: VcalVeventComponent) => void; onGoToOccurrence: ( eventData: CalendarEvent, eventComponent: VcalVeventComponent, occurrence: { localStart: Date; occurrenceNumber: number } ) => void; onEventNotFoundError: () => void; onOtherError?: () => void; } export const useOpenEvent = () => { const api = useApi(); const cache = useCache(); return useCallback( async ({ calendars, addresses, calendarID, eventID, recurrenceId, onGoToEvent, onGoToOccurrence, onEventNotFoundError, onOtherError, }: HandlerProps) => { if (!calendarID || !eventID) { return onEventNotFoundError(); } const calendar = calendars.find(({ ID }) => ID === calendarID); if (!calendar) { return onEventNotFoundError(); } if (!calendar.Display) { const [{ ID: memberID }] = getMemberAndAddress(addresses, calendar.Members); await api({ ...updateMember(calendarID, memberID, { Display: 1 }), silence: true, }).catch(() => {}); await loadModels([CalendarsModel], { api, cache, useCache: false }); } try { const result = await api<{ Event: CalendarEvent }>({ ...getEvent(calendarID, eventID), silence: true, }); const parsedEvent = parseMainEventData(result.Event); if (!parsedEvent) { throw new Error('Missing parsed event'); } if (!parsedEvent.rrule) { return onGoToEvent(result.Event, parsedEvent); } if (!recurrenceId) { const occurrences = getOccurrences({ component: parsedEvent, maxCount: 1 }); if (!occurrences.length) { return onEventNotFoundError(); } const [firstOccurrence] = occurrences; return onGoToOccurrence(result.Event, parsedEvent, firstOccurrence); } const parsedRecurrenceID = parseInt(recurrenceId || '', 10); if ( !Number.isInteger(parsedRecurrenceID) || parsedRecurrenceID < getUnixTime(MINIMUM_DATE) || parsedRecurrenceID > getUnixTime(MAXIMUM_DATE) ) { return onEventNotFoundError(); } const eventsByUID = await getAllEventsByUID(api, calendarID, parsedEvent.uid.value); const { dtstart } = parsedEvent; const localRecurrenceID = toUTCDate( getRecurrenceIdValueFromTimestamp( parsedRecurrenceID, getIsPropertyAllDay(dtstart), getPropertyTzid(dtstart) || 'UTC' ).value ); const isTargetOccurrenceEdited = eventsByUID.some((recurrence) => { const parsedEvent = parseMainEventData(recurrence); if (!parsedEvent) { return false; } const recurrenceID = getRecurrenceIdDate(parsedEvent); if (!recurrenceID) { return false; } // Here a date-time comparison could be used instead, but since the recurrence id parameter can be easily tweaked to change // e.g. the seconds and since a recurring granularity less than daily is not allowed, just compare the day return isSameDay(localRecurrenceID, recurrenceID); }); const maxStart = addMilliseconds(localRecurrenceID, 1); const untilTargetOccurrences = getOccurrences({ component: parsedEvent, maxCount: 10000000, maxStart, }); if (!untilTargetOccurrences.length || isTargetOccurrenceEdited) { // Target occurrence could not be found, fall back to the first generated occurrence const initialOccurrences = getOccurrences({ component: parsedEvent, maxCount: 1 }); if (!initialOccurrences.length) { return onEventNotFoundError(); } const [firstOccurrence] = initialOccurrences; return onGoToOccurrence(result.Event, parsedEvent, firstOccurrence); } const [firstOccurrence] = untilTargetOccurrences; const targetOccurrence = untilTargetOccurrences[untilTargetOccurrences.length - 1]; // Target recurrence could not be expanded to if (!isSameDay(localRecurrenceID, targetOccurrence.localStart)) { return onGoToOccurrence(result.Event, parsedEvent, firstOccurrence); } return onGoToOccurrence(result.Event, parsedEvent, targetOccurrence); } catch (e: any) { if (e.status >= 400 && e.status <= 499) { return onEventNotFoundError(); } return onOtherError?.(); } }, [api, cache] ); };
2,570
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/hooks/useOpenEventsFromMail.tsx
import { Dispatch, SetStateAction, useCallback, useEffect } from 'react'; import { c } from 'ttag'; import { useCalendarModelEventManager, useNotifications } from '@proton/components'; import { getIsDrawerPostMessage } from '@proton/shared/lib/drawer/helpers'; import { DRAWER_EVENTS } from '@proton/shared/lib/drawer/interfaces'; import { Address } from '@proton/shared/lib/interfaces'; import { VisualCalendar } from '@proton/shared/lib/interfaces/calendar'; import { EventTargetAction } from '../containers/calendar/interface'; import useOpenCalendarEvents from './useOpenCalendarEvents'; import { useOpenEvent } from './useOpenEvent'; interface Props { calendars: VisualCalendar[]; addresses: Address[]; onChangeDate: (newDate: Date) => void; tzid: string; setEventTargetAction: Dispatch<SetStateAction<EventTargetAction | undefined>>; } export const useOpenEventsFromMail = ({ calendars, addresses, onChangeDate, tzid, setEventTargetAction }: Props) => { const { call } = useCalendarModelEventManager(); const { createNotification } = useNotifications(); const openEvent = useOpenEvent(); const { goToEvent, goToOccurrence } = useOpenCalendarEvents({ onChangeDate, tzid, setEventTargetAction, preventPopover: true, }); const handleLinkError = () => { createNotification({ type: 'error', // translator: event here is for calendar event text: c('Error').t`Event not found`, }); }; const handleEvents = useCallback( (event: MessageEvent) => { if (!getIsDrawerPostMessage(event)) { return; } switch (event.data.type) { case DRAWER_EVENTS.CALENDAR_OPEN_EVENT: { const { calendarID, eventID, recurrenceID } = event.data.payload; void openEvent({ calendars, addresses, calendarID, eventID, recurrenceId: recurrenceID ? recurrenceID.toString() : null, onGoToEvent: goToEvent, onGoToOccurrence: goToOccurrence, onEventNotFoundError: handleLinkError, }); } break; case DRAWER_EVENTS.CALL_CALENDAR_EVENT_MANAGER: { void call([event.data.payload.calendarID]); } break; case DRAWER_EVENTS.SHOW: { // When showing again the cached calendar app, we need to call the event manager for all calendars to get all updates const allCalendarIDs = calendars.map(({ ID }) => ID); void call(allCalendarIDs); } break; default: break; } }, [calendars, addresses, goToEvent, goToOccurrence] ); useEffect(() => { window.addEventListener('message', handleEvents); return () => { window.removeEventListener('message', handleEvents); }; }, [handleEvents]); };
2,571
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/hooks/useRect.ts
import { useLayoutEffect, useState } from 'react'; import observeRect, { Rect } from './observeRect'; export function useRect(nodeRef: HTMLElement | null, observe = true, once = false, dependency?: any) { const [rect, setRect] = useState<Rect | undefined>(undefined); useLayoutEffect(() => { if (!nodeRef || !observe) { setRect(undefined); return; } if (once) { let onceState = false; const stop = observeRect(nodeRef, (rect: Rect) => { if (!onceState) { onceState = true; stop(); setRect(rect); } }); return stop; } return observeRect(nodeRef, (rect) => { setRect(rect); }); }, [nodeRef, observe, once, dependency]); return rect; }
2,572
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/interfaces/CalendarEvents.ts
export interface CalendarEventRecurring { occurrenceNumber: number; localStart: Date; localEnd: Date; isSingleOccurrence: boolean; }
2,573
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/interfaces/EventData.ts
import { CalendarEvent } from '@proton/shared/lib/interfaces/calendar'; import { VcalVeventComponent } from '@proton/shared/lib/interfaces/calendar/VcalModel'; export interface EventTargetData { calendarID: string; memberID: string; addressID: string; } export interface EventNewData extends EventTargetData { veventComponent: VcalVeventComponent; } export interface EventOldData extends EventTargetData { eventData: CalendarEvent; uid: string; mainVeventComponent: VcalVeventComponent; veventComponent?: VcalVeventComponent; }
2,574
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/interfaces/EventInternalProperties.ts
export interface EventInternalProperties { Permissions: number; IsOrganizer: 1 | 0; IsProtonProtonInvite: 1 | 0; }
2,575
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/interfaces/Invite.ts
import { ICAL_ATTENDEE_STATUS, RECURRING_TYPES } from '@proton/shared/lib/calendar/constants'; import { Address } from '@proton/shared/lib/interfaces'; import { CalendarEvent, VcalAttendeeProperty, VcalVeventComponent } from '@proton/shared/lib/interfaces/calendar'; import { SimpleMap } from '@proton/shared/lib/interfaces/utils'; import { AugmentedSendPreferences } from '../containers/calendar/interface'; export enum INVITE_ACTION_TYPES { NONE, CHANGE_PARTSTAT, DECLINE_INVITATION, DECLINE_DISABLED, SEND_INVITATION, // organizer creates new invitation, or just adds/removes attendees SEND_UPDATE, // organizer updates event details and/or attendees CANCEL_INVITATION, // organizer deletes invitation CANCEL_DISABLED, // organizer deletes invitation but can't notify attendees } export interface InviteActions { type: INVITE_ACTION_TYPES; sharedEventID?: string; sharedSessionKey?: string; isProtonProtonInvite?: boolean; partstat?: ICAL_ATTENDEE_STATUS; sendCancellationNotice?: boolean; resetSingleEditsPartstat?: boolean; deleteSingleEdits?: boolean; selfAddress?: Address; selfAttendeeIndex?: number; addedAttendees?: VcalAttendeeProperty[]; removedAttendees?: VcalAttendeeProperty[]; hasRemovedAllAttendees?: boolean; } export interface RecurringActionData { type: RECURRING_TYPES; inviteActions: InviteActions; } export interface SendIcsActionData { inviteActions: InviteActions; vevent?: VcalVeventComponent; cancelVevent?: VcalVeventComponent; noCheckSendPrefs?: boolean; } export interface ReencryptInviteActionData { calendarEvent: CalendarEvent; calendarID: string; } export interface CleanSendIcsActionData extends SendIcsActionData { sendPreferencesMap: SimpleMap<AugmentedSendPreferences>; } export interface UpdatePartstatOperation { data: { calendarID: string; eventID: string; attendeeID: string; partstat: ICAL_ATTENDEE_STATUS; updateTime: number; }; silence: boolean; } export interface UpdatePersonalPartOperation { data: { calendarID: string; eventID: string; addressID?: string; eventComponent?: VcalVeventComponent; hasDefaultNotifications?: boolean; }; }
2,576
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/interfaces/encryptedSearch.ts
import { EncryptedSearchFunctions } from '@proton/encrypted-search'; import { AttendeeModel, CalendarEventMetadata, CalendarEventSharedData, OrganizerModel, VcalAttendeeProperty, VcalOrganizerProperty, } from '@proton/shared/lib/interfaces/calendar'; export interface ESOrganizerModel extends Pick<OrganizerModel, 'email' | 'cn'> {} export interface ESAttendeeModel extends Pick<AttendeeModel, 'email' | 'cn' | 'role' | 'partstat'> {} export interface ESCalendarMetadata extends CalendarEventSharedData, CalendarEventMetadata { Status: string; Order: number; Summary: string; Location: string; Description: string; Attendees: VcalAttendeeProperty[]; Organizer?: VcalOrganizerProperty; IsDecryptable: boolean; } export interface ESCalendarContent {} export interface ESCalendarSearchParams { keyword?: string; calendarID?: string; begin?: number; end?: number; page?: number; } /** * @var remainingCalendarIDs the calendars for which indexation has not been done yet * @var currentCalendarId the calendar for which indexation is currently ongoing. Can be undefined when there no calendar left to be indexed * @var eventCursor the cursor fetched during last query. Can be undefined when starting to index event from a new calendar */ export type MetadataRecoveryPoint = { remainingCalendarIDs: string[]; currentCalendarId?: string; eventCursor?: string; }; export type EncryptedSearchFunctionsCalendar = EncryptedSearchFunctions< ESCalendarMetadata, ESCalendarSearchParams, ESCalendarContent >;
2,577
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/styles/_aside.scss
@import '~@proton/styles/scss/lib'; .calendar-aside { inline-size: $calendar-aside-width; font-size: rem(10); } .calendar-primary-timezone-cell, .calendar-secondary-timezone-cell { border-inline: 1px solid var(--border-norm); background-color: var(--background-weak); &--header { border-block-start: 1px solid var(--border-norm); border-inline-end: 1px solid var(--border-norm); border-start-end-radius: var(--border-radius-md); border-start-start-radius: var(--border-radius-md); } } .calendar-primary-timezone-cell { border-color: transparent; background-color: transparent; &--header { border-color: transparent; } }
2,578
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/styles/_config.scss
@import '~@proton/styles/scss/lib'; $calendar-aside-width: rem(60) !default; $calendar-hour-height: rem(48) !default; $calendar-grid-border: 1px solid var(--border-weak); $calendar-gridcell-margin: rem(10) !default; $calendar-gridcell-gutter: rem(3) !default;
2,579
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/styles/_daygrid.scss
.calendar-daygrid { min-block-size: rem(410); @include media('print') { min-block-size: rem(700); } &-weeknumber { border-block-end: $calendar-grid-border; border-inline-end: $calendar-grid-border; background-color: var(--background-weak); &-width { inline-size: rem(25); } } &-row, &-days { border-block-end: $calendar-grid-border; } &-day { @include media('screen') { &[aria-current='true'] { font-weight: var(--font-weight-bold); color: var(--primary); } } } &-columns { position: absolute; inset: 0; } &-column:not(:last-child) { border-inline-end: $calendar-grid-border; } }
2,580
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/styles/_debug.scss
// fix for Safari mobile shitty way to handle vh unit .is-day-view, .is-week-view, .is-month-view { .calendar-time-grid::after { content: ''; display: flex; inline-size: 100%; block-size: 5em; } } @include media('<=small') { .is-day-view, .is-week-view, .is-month-view { .calendar-time-grid::after { padding-block-end: env(safe-area-inset-bottom); // thanks Apple for the fixed toolbar at the bottom } } } // hide the thing on desktop devices supporting media query 4 spec @media (pointer: fine) { .is-day-view, .is-week-view, .is-month-view { .calendar-time-grid::after { content: none; } } }
2,581
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/styles/_dropzone.scss
@import '~@proton/styles/scss/lib'; .main-dropzone { &-image { margin-block-end: rem(40); } &-heading { margin-block-end: rem(8); } }
2,582
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/styles/_eventcell.scss
/* Appearance factorization */ .calendar-dayeventcell, .calendar-eventcell { --opacity: 1; } .calendar-dayeventcell-inner, .calendar-eventcell { border: solid rgb(0 0 0 / 0.2); border-block-start-width: 1px; border-block-end-width: 1px; border-inline-start-width: 5px; border-inline-end-width: 1px; padding-block: em(2); padding-inline: em(3); border-radius: var(--border-radius-sm); background-color: var(--background-strong); color: var(--text-norm); line-height: em(18); cursor: pointer; opacity: var(--opacity); transition: all 0.1s ease-out, opacity 0.5s ease-out, background-color 0.15s ease-in-out; animation: loadingEvent 1s easing(ease-in-quint) infinite alternate; & > * { transition: opacity 0.1s ease-out; } &.isHidden { z-index: 4; opacity: 0; visibility: hidden; pointer-events: none; } &.isLoaded { border-color: var(--color-alt); background-color: var(--color-main); color: var(--foreground); animation: none; } &.isDeclined, &.isCancelled { border-color: var(--color-alt); background-color: var(--background-norm); color: inherit; text-decoration: line-through; } &.isUnanswered { border-color: var(--color-alpha); border-inline-start-color: var(--color-alt); background-color: var(--background-norm); background-image: linear-gradient( 105deg, transparent 38%, var(--color-alpha) 42%, var(--color-alpha) 48%, transparent 52%, transparent 88%, var(--color-alpha) 92%, var(--color-alpha) 100% ); background-size: 5.18px 19.32px; color: currentcolor; } &.isPast { border-color: rgb(0 0 0 / 0.1); border-inline-start-color: var(--color-alt); background: var(--background-strong); color: inherit; &:not(.isSelected) > * { opacity: 0.5; } } &.isSelected { z-index: 6; border-color: rgb(0 0 0 / 0.4); box-shadow: var(--shadow-norm); &.isPast, &.isDeclined, &.isCancelled, &.isUnanswered { border-inline-start-color: var(--color-alt); } } } @keyframes loadingEvent { from { opacity: var(--opacity); } to { opacity: calc(var(--opacity) - 0.4); } } /* Full day event */ .calendar-dayeventcell { padding-inline-end: $calendar-gridcell-margin; padding-block-start: $calendar-gridcell-gutter; white-space: nowrap; &-inner { position: relative; min-block-size: 100%; padding-block: 0; padding-inline: 0.5em; &.isNotAllDay { border: none; &.isPast, &:not(.isUnanswered) { background: none; color: inherit; } &:hover, &:focus { background-color: var(--interaction-default-hover); } &:active { background-color: var(--interaction-default-active); } } } &.isOutsideStart &-inner { padding-inline-start: 0; } &.isOutsideEnd, &.isOutsideEnd &-inner { padding-inline-end: 0; } &-circle { color: var(--background-strong); } &-inner.isLoaded &-circle { color: var(--color-main); } &-lock-icon { transform: translateY(-0.125em); // Magic number to visually align it -_-v } &-time { margin-inline-end: 0.25em; } &-title { font-weight: var(--font-weight-semibold); } } /* Part day event */ .calendar-eventcell { position: absolute; z-index: 5; &-title { /* stylelint-disable-next-line */ display: -webkit-box; /* stylelint-disable-next-line */ -webkit-box-orient: vertical; overflow: hidden; -webkit-line-clamp: max(calc(var(--line-number) - 1), 1); font-weight: var(--font-weight-semibold); word-break: break-word; } // in this case, we remove 2 lines ellipsis for a simple ellipsis // because it's creating bad truncation of content in some cases &--title-small-fit &-title { display: block; /* stylelint-disable-next-line */ -webkit-box-orient: unset; /* stylelint-disable-next-line */ -webkit-line-clamp: unset; text-overflow: ellipsis; white-space: nowrap; } @include media('<=small') { &-title, &-timestring { font-size: rem(12); } } /* * Adaptations for small sizes, meaning below 30 minutes events */ $line-height: calc(var(--line-height) * 1px - 2px); // 2px for borders &:is(#{&}--sm, #{&}--xs, #{&}--2xs) { padding-block: 0; line-height: $line-height; } &:is(#{&}--sm, #{&}--xs, #{&}--2xs) &-lock-icon { inline-size: min(#{$line-height}, #{rem(16)}); block-size: min(#{$line-height}, #{rem(16)}); } &--sm &-title { font-size: em(13); } &--xs &-title { font-size: em(12); } &--2xs &-title { font-size: em(10); } }
2,583
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/styles/_eventpopover.scss
@import '~@proton/styles/scss/lib'; .eventpopover { position: absolute; z-index: $layer-floating-frames; transform-origin: 50%; padding: rem(24); overflow: auto; background: var(--background-norm); color: var(--text-norm); animation: eventpopoverIn ease 0.15s; animation-fill-mode: both; @include media('<=small') { inset: 0; inline-size: 100%; block-size: 100%; } @include media('>small') { inline-size: rem(500); max-inline-size: rem(392); max-block-size: 100%; border-radius: var(--border-radius-md); box-shadow: var(--shadow-lifted); } @include media('<=small') { padding-inline: rem(16); } @include media('print') { inline-size: rem(392); block-size: fit-content; border: 1px solid var(--border-norm); } &, &:focus-visible, &:focus:focus-visible { outline: none; } // transition: all .25s ease; should be applied only when opened and end of animation <-- this is solved by react-transition-group &-header { &--draggable { padding-block: rem(24) 0; padding-inline: rem(24); margin-block: rem(-24) 0; margin-inline: rem(-24); cursor: grab; &:active { cursor: grabbing; } } } &-actions { > * + * { margin-inline-start: rem(8); } &-separator { background-color: var(--border-norm); inline-size: rem(1); block-size: rem(28); } } &-title { font-size: rem(24); } .participant { min-block-size: rem(32); &-text { line-height: rem(20); } &-extra-text { line-height: rem(16); } &:first-child, &.is-organizer, + .participant { margin-block-start: em(12); // from design } &.needsAction { border-color: var(--border-norm); } &-display { border-radius: var(--border-radius-md); } } .partstatIcon { position: absolute; inset-inline-end: 0; inset-block-end: 0; transform: translate3d(50%, 50%, 0); } .tabs { min-block-size: 12em; } // special fixes for recurring frequency ------------------ .noInEventPopover { display: none; } .onpopover-flex-column { flex-direction: column; & > * { inline-size: 100%; flex-basis: auto; } } // -------------------------------------------------------- } @keyframes eventpopoverIn { from { opacity: 0; } to { opacity: 1; } }
2,584
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/styles/_grid.scss
.calendar-grid { &-heading { color: var(--text-norm); font-weight: var(--font-weight-semibold); @include media('>small') { flex-wrap: nowrap; } @include media('>small', '<large') { padding-inline: 0; } &-day { @include media('<=small') { inline-size: 100%; } @include media('>small') { margin-inline-end: rem(2); } } &-number { border-radius: var(--border-radius-sm); border: 1px solid transparent; line-height: 1; inline-size: 1.75em; block-size: 1.75em; transition: 0.15s easing(ease-out-quint); @include media('>small') { block-size: rem(28); inline-size: rem(28); } } &:hover &-number, &:focus &-number { background-color: var(--interaction-default-hover); } &:active &-number { background-color: var(--interaction-default-active); } @include media('screen') { &[aria-current='date'] { .calendar-grid-heading-day { @include media('>small') { margin-inline-end: rem(6); } } .calendar-grid-heading-number { border-color: var(--primary); color: var(--primary); background-color: var(--interaction-default); } &:hover, &:focus { .calendar-grid-heading-number { color: var(--interaction-norm-hover); border-color: var(--interaction-norm-hover); background-color: var(--interaction-default-hover); } } &:active { .calendar-grid-heading-number { color: var(--interaction-norm-active); border-color: var(--interaction-norm-active); background-color: var(--interaction-default-active); } } } } @include media('<=small') { &[aria-pressed='true'] &-number { @include media('screen') { background-color: var(--primary); color: var(--primary-contrast); } } } } &-gridcells { border-block-end: $calendar-grid-border; } &-dayLine, &-hourLine, &-gridcell { &::after { content: ''; position: absolute; pointer-events: none; } } &-dayLine { &::after { block-size: 100%; margin-inline-start: -1px; border-inline-start: $calendar-grid-border; } } &-hourLine { block-size: $calendar-hour-height; &::after { inline-size: 100%; margin-block-start: -1px; border-block-end: $calendar-grid-border; } } &-gridcell { margin-inline-end: $calendar-gridcell-margin; &::after { border-inline-start: $calendar-grid-border; block-size: 100%; margin-inline-start: -1px; } } &-nowHourLine { z-index: 8; // Need to be higher than .calendar-eventcell.isSelected's z-index inset-inline-start: 0; inset-inline-end: -$calendar-gridcell-margin; border-block-end: 2px solid var(--primary); box-shadow: var(--shadow-norm); pointer-events: none; &::before { content: ''; position: absolute; inset-block-start: rem(-3); inset-inline-start: rem(-4); inline-size: rem(7); block-size: rem(7); border-radius: 50%; background-color: var(--primary); } } &-timeBlock { block-size: $calendar-hour-height; } &-timeText { inset-block-start: rem(-10); font-size: rem(10); } } .calendar-time-grid { @include media('print') { flex-basis: auto; } }
2,585
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/styles/_loader-container.scss
.calendar-loader-container { @extend .notifications-container; position: absolute; z-index: $layer-upper; inset-block-start: em(160); inset-block-end: unset; inset-inline-start: 50%; @include media('>small') { inset-block-start: em(140); } .notification { --top-custom: 0; } }
2,586
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/styles/_monthgrid.scss
.calendar-monthgrid { &-day { color: var(--text-norm); &-number { display: inline-flex; inline-size: 1.75em; block-size: 1.75em; border-radius: var(--border-radius-md); border: 1px solid transparent; transition: 0.15s easing(ease-out-quint); } &:hover &-number, &:focus &-number { background-color: var(--interaction-default-hover); } &:active &-number { background-color: var(--interaction-default-active); } @include media('screen') { &[aria-current='date'] { .calendar-monthgrid-day-number { color: var(--primary); border-color: var(--primary); font-weight: var(--font-weight-bold); } &:hover, &:focus { .calendar-monthgrid-day-number { color: var(--interaction-norm-hover); border-color: var(--interaction-norm-hover); background-color: var(--interaction-default-hover); } } &:active { .calendar-monthgrid-day-number { color: var(--interaction-norm-active); border-color: var(--interaction-norm-active); background-color: var(--interaction-default-active); } } } @include media('<=small') { &[aria-pressed='true'] &-number { background-color: var(--primary); color: var(--primary-contrast); font-weight: var(--font-weight-bold); } } } } }
2,587
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app
petrpan-code/ProtonMail/WebClients/applications/calendar/src/app/styles/_specifics.scss
@import '~@proton/styles/scss/lib'; .calendar-fullday-row { border-block-end: $calendar-grid-border; padding-block-end: $calendar-gridcell-gutter; .calendar-aside { margin-block-end: -$calendar-gridcell-gutter; } } .calendar-row-heading { z-index: 1; > div { padding-inline-end: rem(11); } } .calendar-first-row-heading { @include media('<=medium') { font-size: rem(12); } } .address-item { background: var(--background-weak); border-radius: 5px; button { display: block; } } @include media('<=small') { // we show abbreviated version only on week/month view .is-week-view, .is-month-view { .calendar-grid-heading-day-fullname { border: 0; clip: rect(0 0 0 0); block-size: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; inline-size: 1px; } } // thus hide the abbrievated version on day view .is-day-view { .calendar-grid-heading-day-shortname { display: none; } } }
2,588
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/assets
petrpan-code/ProtonMail/WebClients/applications/calendar/src/assets/favicons/favicon-calendar-dynamic-1.svg
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 16 16"> <path fill="#fff" d="M6 5h10v7.5a2.5 2.5 0 0 1-2.5 2.5H6V5Z" /> <path fill="url(#a)" fill-rule="evenodd" d="M0 3a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V3Z" clip-rule="evenodd" /> <path fill="url(#b)" fill-rule="evenodd" d="M0 3a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V3Z" clip-rule="evenodd" /> <path fill="url(#c)" fill-rule="evenodd" d="M0 3h11.5A1.5 1.5 0 0 1 13 4.5V15h1a2 2 0 0 0 2-2V3a2 2 0 0 0-2-2H2a2 2 0 0 0-2 2Z" clip-rule="evenodd" /> <path fill="#fff" d="M5.127 6.87v1.17l1.215-.855V12h1.143V5.862h-.909L5.127 6.87Z" /> <defs> <linearGradient id="a" x1="8" x2="9.218" y1="-4.593" y2="11.766" gradientUnits="userSpaceOnUse"> <stop offset=".989" stop-color="#6D4AFF" /> </linearGradient> <linearGradient id="c" x1="19" x2="-.508" y1="23.75" y2="-10.353" gradientUnits="userSpaceOnUse"> <stop stop-color="#C8E8FF" /> <stop offset=".411" stop-color="#BDAEFF" /> <stop offset=".775" stop-color="#6D4AFF" /> </linearGradient> <radialGradient id="b" cx="0" cy="0" r="1" gradientTransform="rotate(109.399 7.624 .785) scale(24.0163 30.6627)" gradientUnits="userSpaceOnUse" > <stop offset=".556" stop-color="#54B7FF" stop-opacity="0" /> <stop offset=".994" stop-color="#54B7FF" /> </radialGradient> </defs> </svg>
2,589
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/assets
petrpan-code/ProtonMail/WebClients/applications/calendar/src/assets/favicons/favicon-calendar-dynamic-10.svg
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 16 16"> <path fill="#fff" d="M6 5h10v7.5a2.5 2.5 0 0 1-2.5 2.5H6V5Z" /> <path fill="url(#a)" fill-rule="evenodd" d="M0 3a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V3Z" clip-rule="evenodd" /> <path fill="url(#b)" fill-rule="evenodd" d="M0 3a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V3Z" clip-rule="evenodd" /> <path fill="url(#c)" fill-rule="evenodd" d="M0 3h11.5A1.5 1.5 0 0 1 13 4.5V15h1a2 2 0 0 0 2-2V3a2 2 0 0 0-2-2H2a2 2 0 0 0-2 2Z" clip-rule="evenodd" /> <path fill="#fff" d="M2.45 6.87v1.17l1.216-.855V12h1.143V5.862h-.91L2.452 6.87Zm5.726 5.229c1.458 0 2.295-1.296 2.295-3.168s-.837-3.159-2.295-3.159c-1.467 0-2.304 1.287-2.304 3.159 0 1.872.837 3.168 2.304 3.168Zm0-1.071c-.81 0-1.161-.864-1.161-2.097s.35-2.088 1.16-2.088c.802 0 1.153.855 1.153 2.088s-.351 2.097-1.152 2.097Z" /> <defs> <linearGradient id="a" x1="8" x2="9.218" y1="-4.593" y2="11.766" gradientUnits="userSpaceOnUse"> <stop offset=".989" stop-color="#6D4AFF" /> </linearGradient> <linearGradient id="c" x1="19" x2="-.508" y1="23.75" y2="-10.353" gradientUnits="userSpaceOnUse"> <stop stop-color="#C8E8FF" /> <stop offset=".411" stop-color="#BDAEFF" /> <stop offset=".775" stop-color="#6D4AFF" /> </linearGradient> <radialGradient id="b" cx="0" cy="0" r="1" gradientTransform="rotate(109.399 7.624 .785) scale(24.0163 30.6627)" gradientUnits="userSpaceOnUse" > <stop offset=".556" stop-color="#54B7FF" stop-opacity="0" /> <stop offset=".994" stop-color="#54B7FF" /> </radialGradient> </defs> </svg>
2,590
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/assets
petrpan-code/ProtonMail/WebClients/applications/calendar/src/assets/favicons/favicon-calendar-dynamic-11.svg
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 16 16"> <path fill="#fff" d="M6 5h10v7.5a2.5 2.5 0 0 1-2.5 2.5H6V5Z" /> <path fill="url(#a)" fill-rule="evenodd" d="M0 3a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V3Z" clip-rule="evenodd" /> <path fill="url(#b)" fill-rule="evenodd" d="M0 3a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V3Z" clip-rule="evenodd" /> <path fill="url(#c)" fill-rule="evenodd" d="M0 3h11.5A1.5 1.5 0 0 1 13 4.5V15h1a2 2 0 0 0 2-2V3a2 2 0 0 0-2-2H2a2 2 0 0 0-2 2Z" clip-rule="evenodd" /> <path fill="#fff" d="M3.457 6.87v1.17l1.215-.855V12h1.143V5.862h-.909L3.457 6.87Zm3.34 0v1.17l1.215-.855V12h1.143V5.862h-.909L6.797 6.87Z" /> <defs> <linearGradient id="a" x1="8" x2="9.218" y1="-4.593" y2="11.766" gradientUnits="userSpaceOnUse"> <stop offset=".989" stop-color="#6D4AFF" /> </linearGradient> <linearGradient id="c" x1="19" x2="-.508" y1="23.75" y2="-10.353" gradientUnits="userSpaceOnUse"> <stop stop-color="#C8E8FF" /> <stop offset=".411" stop-color="#BDAEFF" /> <stop offset=".775" stop-color="#6D4AFF" /> </linearGradient> <radialGradient id="b" cx="0" cy="0" r="1" gradientTransform="rotate(109.399 7.624 .785) scale(24.0163 30.6627)" gradientUnits="userSpaceOnUse" > <stop offset=".556" stop-color="#54B7FF" stop-opacity="0" /> <stop offset=".994" stop-color="#54B7FF" /> </radialGradient> </defs> </svg>
2,591
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/assets
petrpan-code/ProtonMail/WebClients/applications/calendar/src/assets/favicons/favicon-calendar-dynamic-12.svg
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 16 16"> <path fill="#fff" d="M6 5h10v7.5a2.5 2.5 0 0 1-2.5 2.5H6V5Z" /> <path fill="url(#a)" fill-rule="evenodd" d="M0 3a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V3Z" clip-rule="evenodd" /> <path fill="url(#b)" fill-rule="evenodd" d="M0 3a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V3Z" clip-rule="evenodd" /> <path fill="url(#c)" fill-rule="evenodd" d="M0 3h11.5A1.5 1.5 0 0 1 13 4.5V15h1a2 2 0 0 0 2-2V3a2 2 0 0 0-2-2H2a2 2 0 0 0-2 2Z" clip-rule="evenodd" /> <path fill="#fff" d="M2.644 6.87v1.17l1.215-.855V12h1.143V5.862h-.909L2.644 6.87ZM10.277 12v-1.071H7.766v-.009l.693-.495c1.071-.756 1.863-1.647 1.863-2.565 0-1.449-1.008-2.088-2.178-2.088-1.503 0-2.286 1.062-2.304 2.268h1.161c.018-.666.369-1.242 1.143-1.242.594 0 1.026.405 1.026 1.062 0 .738-.558 1.26-1.962 2.295l-1.197.882V12h4.266Z" /> <defs> <linearGradient id="a" x1="8" x2="9.218" y1="-4.593" y2="11.766" gradientUnits="userSpaceOnUse"> <stop offset=".989" stop-color="#6D4AFF" /> </linearGradient> <linearGradient id="c" x1="19" x2="-.508" y1="23.75" y2="-10.353" gradientUnits="userSpaceOnUse"> <stop stop-color="#C8E8FF" /> <stop offset=".411" stop-color="#BDAEFF" /> <stop offset=".775" stop-color="#6D4AFF" /> </linearGradient> <radialGradient id="b" cx="0" cy="0" r="1" gradientTransform="rotate(109.399 7.624 .785) scale(24.0163 30.6627)" gradientUnits="userSpaceOnUse" > <stop offset=".556" stop-color="#54B7FF" stop-opacity="0" /> <stop offset=".994" stop-color="#54B7FF" /> </radialGradient> </defs> </svg>
2,592
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/assets
petrpan-code/ProtonMail/WebClients/applications/calendar/src/assets/favicons/favicon-calendar-dynamic-13.svg
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 16 16"> <path fill="#fff" d="M6 5h10v7.5a2.5 2.5 0 0 1-2.5 2.5H6V5Z" /> <path fill="url(#a)" fill-rule="evenodd" d="M0 3a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V3Z" clip-rule="evenodd" /> <path fill="url(#b)" fill-rule="evenodd" d="M0 3a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V3Z" clip-rule="evenodd" /> <path fill="url(#c)" fill-rule="evenodd" d="M0 3h11.5A1.5 1.5 0 0 1 13 4.5V15h1a2 2 0 0 0 2-2V3a2 2 0 0 0-2-2H2a2 2 0 0 0-2 2Z" clip-rule="evenodd" /> <path fill="#fff" d="M2.534 6.87v1.17l1.215-.855V12h1.143V5.862h-.909L2.534 6.87Zm5.69 5.229c1.223 0 2.168-.702 2.168-1.746 0-.945-.666-1.404-1.179-1.521v-.018c.387-.117.972-.576.972-1.395 0-.99-.819-1.647-1.989-1.647-1.494 0-2.07 1.089-2.115 1.836h1.18c.053-.441.35-.819.926-.819.495 0 .873.297.873.783 0 .495-.378.783-1.125.783h-.423v1.017h.513c.756 0 1.233.288 1.233.837 0 .522-.423.873-1.035.873-.603 0-.999-.369-1.098-.855H5.901c.081 1.08.972 1.872 2.322 1.872Z" /> <defs> <linearGradient id="a" x1="8" x2="9.218" y1="-4.593" y2="11.766" gradientUnits="userSpaceOnUse"> <stop offset=".989" stop-color="#6D4AFF" /> </linearGradient> <linearGradient id="c" x1="19" x2="-.508" y1="23.75" y2="-10.353" gradientUnits="userSpaceOnUse"> <stop stop-color="#C8E8FF" /> <stop offset=".411" stop-color="#BDAEFF" /> <stop offset=".775" stop-color="#6D4AFF" /> </linearGradient> <radialGradient id="b" cx="0" cy="0" r="1" gradientTransform="rotate(109.399 7.624 .785) scale(24.0163 30.6627)" gradientUnits="userSpaceOnUse" > <stop offset=".556" stop-color="#54B7FF" stop-opacity="0" /> <stop offset=".994" stop-color="#54B7FF" /> </radialGradient> </defs> </svg>
2,593
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/assets
petrpan-code/ProtonMail/WebClients/applications/calendar/src/assets/favicons/favicon-calendar-dynamic-14.svg
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 16 16"> <path fill="#fff" d="M6 5h10v7.5a2.5 2.5 0 0 1-2.5 2.5H6V5Z" /> <path fill="url(#a)" fill-rule="evenodd" d="M0 3a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V3Z" clip-rule="evenodd" /> <path fill="url(#b)" fill-rule="evenodd" d="M0 3a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V3Z" clip-rule="evenodd" /> <path fill="url(#c)" fill-rule="evenodd" d="M0 3h11.5A1.5 1.5 0 0 1 13 4.5V15h1a2 2 0 0 0 2-2V3a2 2 0 0 0-2-2H2a2 2 0 0 0-2 2Z" clip-rule="evenodd" /> <path fill="#fff" d="M2.38 6.87v1.17l1.216-.855V12h1.143V5.862h-.91L2.38 6.87Zm7.372 2.916V5.862h-1.43L5.593 9.921v.891H8.61V12h1.143v-1.188h.9V9.786h-.9Zm-2.988-.009c.1-.09.19-.207.342-.432l1.35-2.016c.063-.09.1-.153.135-.243h.018v2.7H6.764v-.009Z" /> <defs> <linearGradient id="a" x1="8" x2="9.218" y1="-4.593" y2="11.766" gradientUnits="userSpaceOnUse"> <stop offset=".989" stop-color="#6D4AFF" /> </linearGradient> <linearGradient id="c" x1="19" x2="-.508" y1="23.75" y2="-10.353" gradientUnits="userSpaceOnUse"> <stop stop-color="#C8E8FF" /> <stop offset=".411" stop-color="#BDAEFF" /> <stop offset=".775" stop-color="#6D4AFF" /> </linearGradient> <radialGradient id="b" cx="0" cy="0" r="1" gradientTransform="rotate(109.399 7.624 .785) scale(24.0163 30.6627)" gradientUnits="userSpaceOnUse" > <stop offset=".556" stop-color="#54B7FF" stop-opacity="0" /> <stop offset=".994" stop-color="#54B7FF" /> </radialGradient> </defs> </svg>
2,594
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/assets
petrpan-code/ProtonMail/WebClients/applications/calendar/src/assets/favicons/favicon-calendar-dynamic-15.svg
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 16 16"> <path fill="#fff" d="M6 5h10v7.5a2.5 2.5 0 0 1-2.5 2.5H6V5Z" /> <path fill="url(#a)" fill-rule="evenodd" d="M0 3a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V3Z" clip-rule="evenodd" /> <path fill="url(#b)" fill-rule="evenodd" d="M0 3a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V3Z" clip-rule="evenodd" /> <path fill="url(#c)" fill-rule="evenodd" d="M0 3h11.5A1.5 1.5 0 0 1 13 4.5V15h1a2 2 0 0 0 2-2V3a2 2 0 0 0-2-2H2a2 2 0 0 0-2 2Z" clip-rule="evenodd" /> <path fill="#fff" d="M2.512 6.87v1.17l1.215-.855V12H4.87V5.862h-.909L2.512 6.87Zm6.184 1.071c-.756 0-1.107.225-1.278.351H7.4l.225-1.377h2.547V5.862H6.716l-.567 3.51h1.233c.252-.297.558-.477.972-.477.54 0 1.026.369 1.026 1.089 0 .702-.504 1.116-1.089 1.116s-.99-.351-1.089-.828H5.996c.135 1.134 1 1.827 2.304 1.827 1.107 0 2.223-.657 2.223-2.205 0-1.314-.98-1.953-1.827-1.953Z" /> <defs> <linearGradient id="a" x1="8" x2="9.218" y1="-4.593" y2="11.766" gradientUnits="userSpaceOnUse"> <stop offset=".989" stop-color="#6D4AFF" /> </linearGradient> <linearGradient id="c" x1="19" x2="-.508" y1="23.75" y2="-10.353" gradientUnits="userSpaceOnUse"> <stop stop-color="#C8E8FF" /> <stop offset=".411" stop-color="#BDAEFF" /> <stop offset=".775" stop-color="#6D4AFF" /> </linearGradient> <radialGradient id="b" cx="0" cy="0" r="1" gradientTransform="rotate(109.399 7.624 .785) scale(24.0163 30.6627)" gradientUnits="userSpaceOnUse" > <stop offset=".556" stop-color="#54B7FF" stop-opacity="0" /> <stop offset=".994" stop-color="#54B7FF" /> </radialGradient> </defs> </svg>
2,595
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/assets
petrpan-code/ProtonMail/WebClients/applications/calendar/src/assets/favicons/favicon-calendar-dynamic-16.svg
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 16 16"> <path fill="#fff" d="M6 5h10v7.5a2.5 2.5 0 0 1-2.5 2.5H6V5Z" /> <path fill="url(#a)" fill-rule="evenodd" d="M0 3a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V3Z" clip-rule="evenodd" /> <path fill="url(#b)" fill-rule="evenodd" d="M0 3a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V3Z" clip-rule="evenodd" /> <path fill="url(#c)" fill-rule="evenodd" d="M0 3h11.5A1.5 1.5 0 0 1 13 4.5V15h1a2 2 0 0 0 2-2V3a2 2 0 0 0-2-2H2a2 2 0 0 0-2 2Z" clip-rule="evenodd" /> <path fill="#fff" d="M2.684 6.87v1.17l1.215-.855V12h1.143V5.862h-.91L2.685 6.87Zm5.572 5.229c1.224 0 2.115-.882 2.115-2.07 0-1.206-.91-1.926-1.827-1.926-.261 0-.46.063-.585.144l-.018-.018 1.62-2.367H8.229L6.753 8.274c-.495.801-.621 1.269-.621 1.791 0 1.152.89 2.034 2.124 2.034Zm0-1.017c-.585 0-1.008-.423-1.008-1.017 0-.594.423-1.026 1.008-1.026s.999.432.999 1.026c0 .594-.414 1.017-1 1.017Z" /> <defs> <linearGradient id="a" x1="8" x2="9.218" y1="-4.593" y2="11.766" gradientUnits="userSpaceOnUse"> <stop offset=".989" stop-color="#6D4AFF" /> </linearGradient> <linearGradient id="c" x1="19" x2="-.508" y1="23.75" y2="-10.353" gradientUnits="userSpaceOnUse"> <stop stop-color="#C8E8FF" /> <stop offset=".411" stop-color="#BDAEFF" /> <stop offset=".775" stop-color="#6D4AFF" /> </linearGradient> <radialGradient id="b" cx="0" cy="0" r="1" gradientTransform="rotate(109.399 7.624 .785) scale(24.0163 30.6627)" gradientUnits="userSpaceOnUse" > <stop offset=".556" stop-color="#54B7FF" stop-opacity="0" /> <stop offset=".994" stop-color="#54B7FF" /> </radialGradient> </defs> </svg>
2,596
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/assets
petrpan-code/ProtonMail/WebClients/applications/calendar/src/assets/favicons/favicon-calendar-dynamic-17.svg
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 16 16"> <path fill="#fff" d="M6 5h10v7.5a2.5 2.5 0 0 1-2.5 2.5H6V5Z" /> <path fill="url(#a)" fill-rule="evenodd" d="M0 3a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V3Z" clip-rule="evenodd" /> <path fill="url(#b)" fill-rule="evenodd" d="M0 3a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V3Z" clip-rule="evenodd" /> <path fill="url(#c)" fill-rule="evenodd" d="M0 3h11.5A1.5 1.5 0 0 1 13 4.5V15h1a2 2 0 0 0 2-2V3a2 2 0 0 0-2-2H2a2 2 0 0 0-2 2Z" clip-rule="evenodd" /> <path fill="#fff" d="M2.917 6.87v1.17l1.215-.855V12h1.143V5.862h-.91L2.918 6.87ZM7.714 12l2.511-5.166v-.972H6.112v1.071h2.871l.01.009a2.55 2.55 0 0 0-.154.27L6.5 12h1.215Z" /> <defs> <linearGradient id="a" x1="8" x2="9.218" y1="-4.593" y2="11.766" gradientUnits="userSpaceOnUse"> <stop offset=".989" stop-color="#6D4AFF" /> </linearGradient> <linearGradient id="c" x1="19" x2="-.508" y1="23.75" y2="-10.353" gradientUnits="userSpaceOnUse"> <stop stop-color="#C8E8FF" /> <stop offset=".411" stop-color="#BDAEFF" /> <stop offset=".775" stop-color="#6D4AFF" /> </linearGradient> <radialGradient id="b" cx="0" cy="0" r="1" gradientTransform="rotate(109.399 7.624 .785) scale(24.0163 30.6627)" gradientUnits="userSpaceOnUse" > <stop offset=".556" stop-color="#54B7FF" stop-opacity="0" /> <stop offset=".994" stop-color="#54B7FF" /> </radialGradient> </defs> </svg>
2,597
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/assets
petrpan-code/ProtonMail/WebClients/applications/calendar/src/assets/favicons/favicon-calendar-dynamic-18.svg
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 16 16"> <path fill="#fff" d="M6 5h10v7.5a2.5 2.5 0 0 1-2.5 2.5H6V5Z" /> <path fill="url(#a)" fill-rule="evenodd" d="M0 3a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V3Z" clip-rule="evenodd" /> <path fill="url(#b)" fill-rule="evenodd" d="M0 3a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V3Z" clip-rule="evenodd" /> <path fill="url(#c)" fill-rule="evenodd" d="M0 3h11.5A1.5 1.5 0 0 1 13 4.5V15h1a2 2 0 0 0 2-2V3a2 2 0 0 0-2-2H2a2 2 0 0 0-2 2Z" clip-rule="evenodd" /> <path fill="#fff" d="M2.547 6.87v1.17l1.215-.855V12h1.143V5.862h-.909L2.547 6.87Zm5.626 5.229c1.206 0 2.205-.756 2.205-1.836 0-.864-.657-1.422-1.188-1.566v-.018c.378-.144.891-.594.891-1.278 0-.891-.72-1.629-1.908-1.629-1.197 0-1.908.738-1.908 1.629 0 .684.513 1.134.891 1.278v.018c-.53.144-1.197.702-1.197 1.566 0 1.08 1 1.836 2.214 1.836Zm0-3.87c-.459 0-.792-.333-.792-.756 0-.405.315-.756.792-.756.468 0 .792.351.792.756 0 .423-.342.756-.792.756Zm0 2.88c-.558 0-1.062-.351-1.062-.936 0-.54.45-.954 1.062-.954.612 0 1.053.414 1.053.954 0 .585-.495.936-1.053.936Z" /> <defs> <linearGradient id="a" x1="8" x2="9.218" y1="-4.593" y2="11.766" gradientUnits="userSpaceOnUse"> <stop offset=".989" stop-color="#6D4AFF" /> </linearGradient> <linearGradient id="c" x1="19" x2="-.508" y1="23.75" y2="-10.353" gradientUnits="userSpaceOnUse"> <stop stop-color="#C8E8FF" /> <stop offset=".411" stop-color="#BDAEFF" /> <stop offset=".775" stop-color="#6D4AFF" /> </linearGradient> <radialGradient id="b" cx="0" cy="0" r="1" gradientTransform="rotate(109.399 7.624 .785) scale(24.0163 30.6627)" gradientUnits="userSpaceOnUse" > <stop offset=".556" stop-color="#54B7FF" stop-opacity="0" /> <stop offset=".994" stop-color="#54B7FF" /> </radialGradient> </defs> </svg>
2,598
0
petrpan-code/ProtonMail/WebClients/applications/calendar/src/assets
petrpan-code/ProtonMail/WebClients/applications/calendar/src/assets/favicons/favicon-calendar-dynamic-19.svg
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="none" viewBox="0 0 16 16"> <path fill="#fff" d="M6 5h10v7.5a2.5 2.5 0 0 1-2.5 2.5H6V5Z" /> <path fill="url(#a)" fill-rule="evenodd" d="M0 3a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V3Z" clip-rule="evenodd" /> <path fill="url(#b)" fill-rule="evenodd" d="M0 3a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V3Z" clip-rule="evenodd" /> <path fill="url(#c)" fill-rule="evenodd" d="M0 3h11.5A1.5 1.5 0 0 1 13 4.5V15h1a2 2 0 0 0 2-2V3a2 2 0 0 0-2-2H2a2 2 0 0 0-2 2Z" clip-rule="evenodd" /> <path fill="#fff" d="M2.74 6.87v1.17l1.216-.855V12h1.143V5.862h-.91L2.742 6.87ZM8.16 12l1.467-2.304c.513-.801.684-1.314.684-1.89 0-1.188-.891-2.034-2.124-2.034-1.224 0-2.115.873-2.115 2.061 0 1.206.909 1.926 1.827 1.926.252 0 .45-.063.567-.144l.018.018L6.819 12h1.34Zm.027-3.177c-.585 0-1-.423-1-1.026 0-.594.415-1.017 1-1.017s1.008.423 1.008 1.017c0 .603-.423 1.026-1.008 1.026Z" /> <defs> <linearGradient id="a" x1="8" x2="9.218" y1="-4.593" y2="11.766" gradientUnits="userSpaceOnUse"> <stop offset=".989" stop-color="#6D4AFF" /> </linearGradient> <linearGradient id="c" x1="19" x2="-.508" y1="23.75" y2="-10.353" gradientUnits="userSpaceOnUse"> <stop stop-color="#C8E8FF" /> <stop offset=".411" stop-color="#BDAEFF" /> <stop offset=".775" stop-color="#6D4AFF" /> </linearGradient> <radialGradient id="b" cx="0" cy="0" r="1" gradientTransform="rotate(109.399 7.624 .785) scale(24.0163 30.6627)" gradientUnits="userSpaceOnUse" > <stop offset=".556" stop-color="#54B7FF" stop-opacity="0" /> <stop offset=".994" stop-color="#54B7FF" /> </radialGradient> </defs> </svg>
2,599