/
CalendarUtils.js
531 lines (463 loc) · 16.7 KB
/
CalendarUtils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
//@flow
import {getStartOfDay, incrementDate} from "../api/common/utils/DateUtils"
import {pad} from "../api/common/utils/StringUtils"
import type {EventTextTimeOptionEnum, RepeatPeriodEnum, ShareCapabilityEnum, WeekStartEnum} from "../api/common/TutanotaConstants"
import {
defaultCalendarColor,
EventTextTimeOption,
getWeekStart,
GroupType,
ShareCapability,
WeekStart
} from "../api/common/TutanotaConstants"
import {DateTime} from "luxon"
import {clone, neverNull} from "../api/common/utils/Utils"
import {createCalendarRepeatRule} from "../api/entities/tutanota/CalendarRepeatRule"
import {DAYS_SHIFTED_MS, generateEventElementId, isAllDayEvent} from "../api/common/utils/CommonCalendarUtils"
import {lang} from "../misc/LanguageViewModel"
import {formatTime} from "../misc/Formatter"
import {size} from "../gui/size"
import {assertMainOrNode} from "../api/Env"
import {logins} from "../api/main/LoginController"
import {isSameId} from "../api/common/EntityFunctions"
import {getFromMap} from "../api/common/utils/MapUtils"
assertMainOrNode()
export const CALENDAR_EVENT_HEIGHT = size.calendar_line_height + 2
export type CalendarMonthTimeRange = {
start: Date,
end: Date
}
export function eventStartsBefore(currentDate: Date, zone: string, event: CalendarEvent): boolean {
return getEventStart(event, zone).getTime() < currentDate.getTime()
}
export function eventEndsAfterDay(currentDate: Date, zone: string, event: CalendarEvent): boolean {
return getEventEnd(event, zone).getTime() > getStartOfNextDayWithZone(currentDate, zone).getTime()
}
export function generateUid(event: CalendarEvent, timestamp: number): string {
return `${neverNull(event._ownerGroup)}${timestamp}@tutanota.com`
}
/**
* Accepts 2, 2:30, 2:5, 02:05, 02:30, 24:30, 2430, 12:30pm, 12:30 p.m.
*/
export function parseTime(timeString: string): ?{hours: number, minutes: number} {
let suffix // am/pm indicator or undefined
let hours // numeric hours
let minutes // numeric minutes
// See if the time includes a colon separating hh:mm
let mt = timeString.match(/^(\d{1,2}):(\d{1,2})\s*(am|pm|a\.m\.|p\.m\.)?$/i)
if (mt != null) {
suffix = mt[3]
hours = parseInt(mt[1], 10)
minutes = parseInt(mt[2], 10)
} else {
// Interpret 127am as 1:27am or 2311 as 11:11pm, e.g.
mt = timeString.match(/^(\d{1,4})\s*(am|pm|a\.m\.|p\.m\.)?$/i)
if (mt != null) {
suffix = mt[2]
const digits = mt[1]
// Hours only?
if (digits.length <= 2) {
hours = parseInt(digits, 10)
minutes = 0
} else {
hours = parseInt(digits.substr(0, digits.length - 2), 10)
minutes = parseInt(digits.substr(-2, 2), 10)
}
} else {
return null
}
}
if (isNaN(hours) || isNaN(minutes) || minutes > 59) {
return null
}
if (suffix) {
suffix = suffix.toUpperCase()
}
if (suffix === "PM" || suffix == "P.M.") {
if (hours > 12) return null
if (hours !== 12) hours = hours + 12
} else if (suffix === "AM" || suffix == "A.M.") {
if (hours > 12) return null
if (hours === 12) hours = 0
} else if (hours > 23) {
return null
}
return {hours, minutes}
}
export function filterInt(value: string) {
if (/^\d+$/.test(value)) {
return parseInt(value, 10);
} else {
return NaN;
}
}
export function timeString(date: Date, amPm: boolean): string {
return timeStringFromParts(date.getHours(), date.getMinutes(), amPm)
}
export function timeStringFromParts(hours: number, minutes: number, amPm: boolean): string {
let minutesString = pad(minutes, 2)
if (amPm) {
if (hours === 0) {
return `12:${minutesString} am`
} else if (hours === 12) {
return `12:${minutesString} pm`
} else if (hours > 12) {
return `${hours - 12}:${minutesString} pm`
} else {
return `${hours}:${minutesString} am`
}
} else {
let hoursString = pad(hours, 2)
return hoursString + ":" + minutesString
}
}
export function shouldDefaultToAmPmTimeFormat(): boolean {
return lang.code === "en"
}
export function getAllDayDateForTimezone(utcDate: Date, timeZone: string): Date {
return DateTime.fromObject({
year: utcDate.getUTCFullYear(),
month: utcDate.getUTCMonth() + 1,
day: utcDate.getUTCDate(),
zone: timeZone
}).toJSDate()
}
export function getMonth(date: Date, zone: string): CalendarMonthTimeRange {
const startDateTime = DateTime.fromJSDate(date, {zone})
.set({day: 1, hour: 0, minute: 0, second: 0, millisecond: 0})
const start = startDateTime.toJSDate()
const end = startDateTime.plus({month: 1}).toJSDate()
return {start, end}
}
/**
* Provides a date representing the beginning of the given date in local time.
*/
export function getStartOfDayWithZone(date: Date, zone: string): Date {
return DateTime.fromJSDate(date, {zone}).set({hour: 0, minute: 0, second: 0, millisecond: 0}).toJSDate()
}
export function getStartOfNextDayWithZone(date: Date, zone: string): Date {
return DateTime.fromJSDate(date, {zone}).set({hour: 0, minute: 0, second: 0, millisecond: 0}).plus({day: 1}).toJSDate()
}
export function getTimeZone(): string {
return DateTime.local().zoneName
}
export function createRepeatRuleWithValues(frequency: RepeatPeriodEnum, interval: number): CalendarRepeatRule {
const rule = createCalendarRepeatRule()
rule.timeZone = getTimeZone()
rule.frequency = frequency
rule.interval = String(interval)
return rule
}
export function isColorLight(c: string) {
const rgb = parseInt(c, 16); // convert rrggbb to decimal
const r = (rgb >> 16) & 0xff; // extract red
const g = (rgb >> 8) & 0xff; // extract green
const b = (rgb >> 0) & 0xff; // extract blue
// Counting the perceptive luminance
// human eye favors green color...
const a = 1 - (0.299 * r + 0.587 * g + 0.114 * b) / 255;
return (a < 0.5);
}
export function colorForBg(color: string): string {
return isColorLight(color) ? "black" : "white"
}
export type CalendarDay = {
date: Date,
year: number,
month: number,
day: number,
paddingDay: boolean
}
export type CalendarMonth = {
weekdays: Array<string>,
weeks: Array<Array<CalendarDay>>
}
/**
* @param date
* @param firstDayOfWeekFromSundayOffset
* @return {{weeks: Array[], weekdays: Array}}
*/
export function getCalendarMonth(date: Date, firstDayOfWeekFromSundayOffset: number, weekdayNarrowFormat: boolean): CalendarMonth {
const weeks = [[]]
const calculationDate = getStartOfDay(date)
calculationDate.setDate(1)
let currentYear = calculationDate.getFullYear()
let month = calculationDate.getMonth()
// add "padding" days
// getDay returns the day of the week (from 0 to 6) for the specified date (with first one being Sunday)
let firstDay
if (firstDayOfWeekFromSundayOffset > calculationDate.getDay()) {
firstDay = (calculationDate.getDay() + 7) - firstDayOfWeekFromSundayOffset
} else {
firstDay = calculationDate.getDay() - firstDayOfWeekFromSundayOffset
}
let dayCount
incrementDate(calculationDate, -firstDay)
for (dayCount = 0; dayCount < firstDay; dayCount++) {
weeks[0].push({
date: new Date(calculationDate),
day: calculationDate.getDate(),
month: calculationDate.getMonth(),
year: calculationDate.getFullYear(),
paddingDay: true
})
incrementDate(calculationDate, 1)
}
// add actual days
while (calculationDate.getMonth() === month) {
if (weeks[0].length && dayCount % 7 === 0) {
// start new week
weeks.push([])
}
const dayInfo = {
date: new Date(currentYear, month, calculationDate.getDate()),
year: currentYear,
month: month,
day: calculationDate.getDate(),
paddingDay: false
}
weeks[weeks.length - 1].push(dayInfo)
incrementDate(calculationDate, 1)
dayCount++
}
// add remaining "padding" days
while (dayCount < 42) {
if (dayCount % 7 === 0) {
weeks.push([])
}
weeks[weeks.length - 1].push({
day: calculationDate.getDate(),
year: calculationDate.getFullYear(),
month: calculationDate.getMonth(),
date: new Date(calculationDate),
paddingDay: true
})
incrementDate(calculationDate, 1)
dayCount++
}
const weekdays = []
const weekdaysDate = new Date()
incrementDate(weekdaysDate, -weekdaysDate.getDay() + firstDayOfWeekFromSundayOffset)// get first day of week
for (let i = 0; i < 7; i++) {
weekdays.push(weekdayNarrowFormat ? lang.formats.weekdayNarrow.format(weekdaysDate) : lang.formats.weekdayShort.format(weekdaysDate))
incrementDate(weekdaysDate, 1)
}
return {
weekdays,
weeks
}
}
export function layOutEvents(events: Array<CalendarEvent>, zone: string,
renderer: (columns: Array<Array<CalendarEvent>>) => ChildArray, handleAsAllDay: boolean): ChildArray {
events.sort((e1, e2) => {
const e1Start = getEventStart(e1, zone)
const e2Start = getEventStart(e2, zone)
if (e1Start < e2Start) return -1;
if (e1Start > e2Start) return 1;
const e1End = getEventEnd(e1, zone)
const e2End = getEventEnd(e2, zone)
if (e1End < e2End) return -1;
if (e1End > e2End) return 1;
return 0;
})
let lastEventEnding = null
let columns: Array<Array<CalendarEvent>> = []
const children = []
// Cache for calculation events
const calcEvents = new Map()
events.forEach((e) => {
const calcEvent = getFromMap(calcEvents, e, () => getCalculationEvent(e, zone, handleAsAllDay))
// Check if a new event group needs to be started
if (lastEventEnding !== null && calcEvent.startTime.getTime() >= lastEventEnding) {
// The latest event is later than any of the event in the
// current group. There is no overlap. Output the current
// event group and start a new event group.
children.push(...renderer(columns))
columns = []; // This starts new event group.
lastEventEnding = null;
}
// Try to place the event inside the existing columns
let placed = false
for (let i = 0; i < columns.length; i++) {
const col = columns[i]
const lastEvent = col[col.length - 1]
const lastCalcEvent = getFromMap(calcEvents, lastEvent, () => getCalculationEvent(lastEvent, zone, handleAsAllDay))
if (!collidesWith(lastCalcEvent, calcEvent)) {
col.push(e) // push real event here not calc event
placed = true
break
}
}
// It was not possible to place the event. Add a new column
// for the current event group.
if (!placed) {
columns.push([e])
}
// Remember the latest event end time of the current group.
// This is later used to determine if a new groups starts.
if (lastEventEnding === null || calcEvent.endTime.getTime() > lastEventEnding) {
lastEventEnding = calcEvent.endTime.getTime()
}
})
children.push(...renderer(columns))
return children
}
function getCalculationEvent(event: CalendarEvent, zone: string, handleAsAllDay: boolean): CalendarEvent {
if (handleAsAllDay) {
const calcEvent = clone(event)
if (isAllDayEvent(event)) {
calcEvent.startTime = getAllDayDateForTimezone(event.startTime, zone)
calcEvent.endTime = getAllDayDateForTimezone(event.endTime, zone)
} else {
calcEvent.startTime = getStartOfDayWithZone(event.startTime, zone)
calcEvent.endTime = getStartOfNextDayWithZone(event.endTime, zone)
}
return calcEvent
} else {
return event
}
}
function collidesWith(a: CalendarEvent, b: CalendarEvent): boolean {
return a.endTime.getTime() > b.startTime.getTime() && a.startTime.getTime() < b.endTime.getTime()
}
export function getEventText(event: CalendarEvent, showTime: EventTextTimeOptionEnum): string {
switch (showTime) {
case EventTextTimeOption.NO_TIME:
return event.summary
case EventTextTimeOption.START_TIME:
return `${formatTime(event.startTime)} ${event.summary}`
case EventTextTimeOption.END_TIME:
return `- ${formatTime(event.endTime)} ${event.summary}`
case EventTextTimeOption.START_END_TIME:
return `${formatTime(event.startTime)} - ${formatTime(event.endTime)} ${event.summary}`
case EventTextTimeOption.ALL_DAY:
return `${lang.get("allDay_label")} ${event.summary}`
default:
throw new Error("Unknown time option " + showTime)
}
}
export function expandEvent(ev: CalendarEvent, columnIndex: number, columns: Array<Array<CalendarEvent>>): number {
let colSpan = 1;
for (let i = columnIndex + 1; i < columns.length; i++) {
let col = columns[i];
for (let j = 0; j < col.length; j++) {
let ev1 = col[j];
if (collidesWith(ev, ev1)) {
return colSpan;
}
}
colSpan++;
}
return colSpan;
}
/**
* Result is positive or 0 if b > a, result is negative or 0 otherwise
*/
export function getDiffInDays(a: Date, b: Date): number {
// discard the time and time-zone information
return Math.floor(DateTime.fromJSDate(a).diff(DateTime.fromJSDate(b), 'day').days)
}
export function getCalendarName(groupInfo: GroupInfo, allowGroupNameOverride: boolean): string {
const {userSettingsGroupRoot} = logins.getUserController()
const groupSettings = userSettingsGroupRoot.groupSettings.find((gc) => gc.group === groupInfo.group)
return (allowGroupNameOverride && groupSettings && groupSettings.name) || groupInfo.name || lang.get("privateCalendar_label")
}
export function getEventColor(event: CalendarEvent, groupColors: {[Id]: string}): string {
return groupColors[neverNull(event._ownerGroup)] || defaultCalendarColor
}
export function getStartOfWeek(date: Date, firstDayOfWeekFromSundayOffset: number): Date {
let firstDay
if (firstDayOfWeekFromSundayOffset > date.getDay()) {
firstDay = (date.getDay() + 7) - firstDayOfWeekFromSundayOffset
} else {
firstDay = date.getDay() - firstDayOfWeekFromSundayOffset
}
return incrementDate(getStartOfDay(date), -firstDay)
}
export function getCalendarWeek(dayInTheWeek: Date, startOfTheWeek: WeekStartEnum): Array<Date> {
let calculationDate = getStartOfWeek(dayInTheWeek, getStartOfTheWeekOffset(startOfTheWeek))
const days = []
for (let i = 0; i < 7; i++) {
days.push(calculationDate)
calculationDate = incrementDate(new Date(calculationDate), 1)
}
return days
}
export function getStartOfTheWeekOffset(weekStart: WeekStartEnum): number {
switch (weekStart) {
case WeekStart.SUNDAY:
return 0
case WeekStart.MONDAY:
default:
return 1
}
}
export function getStartOfTheWeekOffsetForUser(): number {
return getStartOfTheWeekOffset(getWeekStart(logins.getUserController().userSettingsGroupRoot))
}
export function getWeekNumber(startOfTheWeek: Date): number {
// Currently it doesn't support US-based week numbering system with partial weeks.
return DateTime.fromJSDate(startOfTheWeek).weekNumber
}
export function getEventEnd(event: CalendarEvent, timeZone: string): Date {
if (isAllDayEvent(event)) {
return getAllDayDateForTimezone(event.endTime, timeZone)
} else {
return event.endTime
}
}
export function getEventStart(event: CalendarEvent, timeZone: string): Date {
if (isAllDayEvent(event)) {
return getAllDayDateForTimezone(event.startTime, timeZone)
} else {
return event.startTime
}
}
export function getAllDayDateUTCFromZone(date: Date, timeZone: string): Date {
return DateTime.fromJSDate(date, {zone: timeZone})
.setZone('utc', {keepLocalTime: true})
.toJSDate()
}
export function isLongEvent(event: CalendarEvent, zone: string): boolean {
return getEventEnd(event, zone).getTime() - getEventStart(event, zone).getTime() > DAYS_SHIFTED_MS
}
export function createEventId(event: CalendarEvent, zone: string, groupRoot: CalendarGroupRoot): void {
const listId = event.repeatRule || isLongEvent(event, zone) ? groupRoot.longEvents : groupRoot.shortEvents
event._id = [listId, generateEventElementId(event.startTime.getTime())]
}
export function hasCapabilityOnGroup(user: User, group: Group, requiredCapability: ShareCapabilityEnum): boolean {
if (group.type !== GroupType.Calendar) {
return false
}
if (isSharedGroupOwner(group, user._id)) {
return true;
}
const membership = user.memberships.find((gm: GroupMembership) => isSameId(gm.group, group._id))
if (membership) {
return membership.capability != null && Number(requiredCapability) <= Number(membership.capability)
}
return false
}
export function isSharedGroupOwner(sharedGroup: Group, userId: Id): boolean {
return !!(sharedGroup.user && isSameId(sharedGroup.user, userId))
}
export function getCapabilityText(capability: ?ShareCapabilityEnum): string {
switch (capability) {
case ShareCapability.Invite:
return lang.get("calendarShareCapabilityInvite_label")
case ShareCapability.Write:
return lang.get("calendarShareCapabilityWrite_label")
case ShareCapability.Read:
return lang.get("calendarShareCapabilityRead_label")
default:
return lang.get("comboBoxSelectionNone_msg")
}
}
export function isSameEvent(left: CalendarEvent, right: CalendarEvent): boolean {
// in addition to the id we compare the start time equality to be able to distinguish repeating events. They have the same id but different start time.
return isSameId(left._id, right._id) && left.startTime.getTime() === right.startTime.getTime()
}
export function hasAlarmsForTheUser(event: CalendarEvent): boolean {
const useAlarmList = neverNull(logins.getUserController().user.alarmInfoList).alarms
return event.alarmInfos.some(([listId]) => isSameId(listId, useAlarmList))
}