Repository navigation
Expand file tree
/
Copy pathModel.js
More file actions
2478 lines (2274 loc) · 94.5 KB
/
Copy pathModel.js
File metadata and controls
2478 lines (2274 loc) · 94.5 KB
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Pure date and format math for the clock widget and its calendar panel.
// Everything here is locale- and Qt-free so it can be unit tested under node
// (test/shell.d/clock-test.sh); the QML owns month/weekday naming through
// Qt.locale().
var MS_PER_DAY = 86400000
// Weekday indices match both JS Date.getDay() and QML's Locale.Sunday…
// Locale.Saturday, so a locale's firstDayOfWeek can be passed straight in.
var WEEKDAY_NAMES = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"]
// ---- Bar label formats. Right-clicking the clock walks these in order and
// writes the result back to shell.json, so the label the bar shows and
// the format the config stores are always the same thing.
//
// The locale-shaped time presets are each followed by their 12-hour twin, so
// the walk from a 24-hour label to the same label in AM/PM is a single right
// click rather than a lap of the ring. The ISO preset is deliberately left
// without one: ISO 8601 writes time on a 24-hour clock, so an AM/PM variant
// would contradict the only thing that format is for.
var CLOCK_FORMATS = [
"dddd HH:mm",
"dddd h:mm AP",
"HH:mm",
"h:mm AP",
"ddd d MMM HH:mm",
"ddd d MMM h:mm AP",
"ddd d HH:mm",
"ddd d h:mm AP",
"d MMMM 'W'ww yyyy",
"yyyy-MM-dd HH:mm"
]
// Vertical bars have room for a few stacked lines and nothing else, so the
// ring stays short. AM/PM costs a fourth line, which is why only the plain
// time carries it here.
var VERTICAL_CLOCK_FORMATS = [
"HH\n—\nmm",
"h\n—\nmm\nAP",
"dd\nMMM\n'W'ww\n''yy",
"HH\nmm"
]
function clockFormats(vertical) {
return vertical ? VERTICAL_CLOCK_FORMATS.slice() : CLOCK_FORMATS.slice()
}
// The presets in a fixed order, plus the configured alternate and current
// format when they are something else. The order must not depend on which
// entry is current: cycling writes the result back to shell.json, and a ring
// that reshuffled itself around the current value would bounce between two
// entries instead of walking.
function clockFormatRing(configured, configuredAlt, presets) {
var ring = []
var candidates = (presets || []).concat([configuredAlt, configured])
for (var i = 0; i < candidates.length; i++) {
var format = String(candidates[i] === undefined || candidates[i] === null ? "" : candidates[i])
if (format === "" || ring.indexOf(format) !== -1) continue
ring.push(format)
}
return ring.length > 0 ? ring : ["HH:mm"]
}
// Next entry after `current`. An unknown current format (a hand-written one
// that is not in the ring) starts the walk at the top.
function nextClockFormat(ring, current) {
if (!ring || ring.length === 0) return ""
var index = ring.indexOf(String(current === undefined || current === null ? "" : current))
return ring[(index + 1) % ring.length]
}
// Two-digit ISO week, substituted into a format's 'ww' token before Qt
// formats it -- Qt has no ISO week specifier of its own.
function isoWeekLiteral(year, month, day) {
return pad2(isoWeek(year, month, day))
}
function pad2(value) {
var n = Number(value)
return (n < 10 ? "0" : "") + n
}
// Stable "yyyy-MM-dd" identity for a day, so a grid cell can be compared
// against today without dragging Date objects through bindings.
function dateKey(year, month, day) {
return year + "-" + pad2(Number(month) + 1) + "-" + pad2(day)
}
function keyForDate(date) {
return dateKey(date.getFullYear(), date.getMonth(), date.getDate())
}
function coerceWeekStart(value) {
if (value === undefined || value === null) return null
if (typeof value === "number")
return isFinite(value) ? ((Math.round(value) % 7) + 7) % 7 : null
var text = String(value).trim().toLowerCase()
if (text === "") return null
for (var i = 0; i < WEEKDAY_NAMES.length; i++)
if (WEEKDAY_NAMES[i] === text || WEEKDAY_NAMES[i].substr(0, 3) === text) return i
var parsed = parseInt(text, 10)
return isFinite(parsed) ? ((parsed % 7) + 7) % 7 : null
}
// Configured week start, falling back to the locale's own first day when
// the setting is missing or nonsense.
function normalizedWeekStart(value, fallback) {
var configured = coerceWeekStart(value)
if (configured !== null) return configured
var fallbackStart = coerceWeekStart(fallback)
return fallbackStart === null ? 1 : fallbackStart
}
function weekStartSettingName(index) {
return WEEKDAY_NAMES[normalizedWeekStart(index, 1)]
}
// The toggle flips between the two conventions people actually switch
// between. A calendar configured to any other start (Saturday, say) is
// shown as-is and lands on Monday the first time it is toggled.
function toggledWeekStart(index) {
return normalizedWeekStart(index, 1) === 1 ? 0 : 1
}
function weekdayOrder(weekStart) {
var start = normalizedWeekStart(weekStart, 1)
var out = []
for (var i = 0; i < 7; i++) out.push((start + i) % 7)
return out
}
// ISO-8601 week number: the week owning the Thursday of that date's
// Monday-based week. Mirrors the clock widget's 'ww' format token.
function isoWeek(year, month, day) {
var date = new Date(Date.UTC(year, month, day))
var weekday = date.getUTCDay() || 7
date.setUTCDate(date.getUTCDate() + 4 - weekday)
var yearStart = new Date(Date.UTC(date.getUTCFullYear(), 0, 1))
return Math.ceil(((date.getTime() - yearStart.getTime()) / MS_PER_DAY + 1) / 7)
}
function dayOfYear(year, month, day) {
return Math.round((Date.UTC(year, month, day) - Date.UTC(year, 0, 1)) / MS_PER_DAY) + 1
}
function daysInYear(year) {
return dayOfYear(year, 11, 31)
}
// Share of the year already behind you: whole days completed over days in
// the year, so January 1 reads 0% and December 31 reads 100%.
function yearProgress(year, month, day) {
var total = daysInYear(year)
if (total <= 0) return 0
return Math.max(0, Math.min(1, (dayOfYear(year, month, day) - 1) / total))
}
function yearProgressPercent(year, month, day) {
return Math.round(yearProgress(year, month, day) * 100)
}
// Memento mori. The default span is a round number rather than anything from
// an actuarial table: the point of the bar is the reminder, not the
// arithmetic, and whoever wants a different number can say so.
var DEFAULT_LIFE_EXPECTANCY = 90
// A whole number in range, or the fallback. Blank, malformed, negative,
// fractional and out-of-range all mean the same thing: the setting is not set.
function parseWholeNumber(value, min, max, fallback) {
var text = String(value === undefined || value === null ? "" : value).trim()
if (!/^\d+$/.test(text)) return fallback
var n = parseInt(text, 10)
return n >= min && n <= max ? n : fallback
}
// A birth year rather than an age, so the bar keeps counting on its own
// instead of going stale the moment it is entered. 0 means "not set".
function parseBirthYear(value, currentYear) {
var now = Math.round(Number(currentYear))
if (!isFinite(now)) return 0
return parseWholeNumber(value, now - 120, now, 0)
}
// Whole years, the way people say their age: born in 1979 makes you 47 for
// all of 2026, whichever side of your birthday today falls.
function ageFromBirthYear(birthYear, currentYear) {
var born = parseBirthYear(birthYear, currentYear)
if (born <= 0) return 0
return Math.round(Number(currentYear)) - born
}
// 0 means "not set" — the life bar simply stays hidden.
function parseAge(value) {
return parseWholeNumber(value, 1, 120, 0)
}
// Unset or nonsense falls back to the default rather than to zero, so the
// bar always has something to measure against.
function parseLifeExpectancy(value) {
return parseWholeNumber(value, 1, 150, DEFAULT_LIFE_EXPECTANCY)
}
function lifeProgress(age, expectancy) {
var years = parseAge(age)
var span = parseLifeExpectancy(expectancy)
if (years <= 0 || span <= 0) return 0
return Math.max(0, Math.min(1, years / span))
}
function lifeProgressPercent(age, expectancy) {
return Math.round(lifeProgress(age, expectancy) * 100)
}
// Always six rows of seven days. A fixed grid keeps the popup exactly the
// same height in every month, so stepping through the year never makes the
// panel jump under the pointer.
function monthGrid(year, month, weekStart, todayKey, eventIndex, taskIndex) {
var start = normalizedWeekStart(weekStart, 1)
var leading = (new Date(year, month, 1).getDay() - start + 7) % 7
var cursor = new Date(year, month, 1 - leading)
var today = String(todayKey || "")
var weeks = []
for (var w = 0; w < 6; w++) {
var days = []
var thursday = null
for (var d = 0; d < 7; d++) {
var cellYear = cursor.getFullYear()
var cellMonth = cursor.getMonth()
var cellDay = cursor.getDate()
var weekday = cursor.getDay()
var key = dateKey(cellYear, cellMonth, cellDay)
if (weekday === 4) thursday = { year: cellYear, month: cellMonth, day: cellDay }
days.push({
key: key,
year: cellYear,
month: cellMonth,
day: cellDay,
weekday: weekday,
inMonth: cellMonth === month && cellYear === year,
weekend: weekday === 0 || weekday === 6,
today: key === today,
hasEvent: eventIndex ? !!eventIndex[key] : false,
colors: eventIndex ? dayColors(eventIndex[key]) : [],
hasTask: taskIndex ? hasOpenTask(taskIndex[key]) : false,
taskColors: taskIndex ? taskColors(taskIndex[key]) : []
})
cursor.setDate(cursor.getDate() + 1)
}
// Number every row by the ISO week owning its Thursday. That is the
// definition itself for Monday-start weeks, and the only answer that
// stays stable for the other starts, where a row straddles two ISO
// weeks but shares all of Monday through Thursday with one of them.
var anchor = thursday || days[0]
weeks.push({
week: isoWeek(anchor.year, anchor.month, anchor.day),
days: days
})
}
return weeks
}
function stepMonth(year, month, delta) {
var target = new Date(year, Number(month) + Number(delta), 1)
return { year: target.getFullYear(), month: target.getMonth() }
}
function indexEventsByDate(events) {
var index = {}
if (!events || !events.length) return index
for (var i = 0; i < events.length; i++) {
var event = events[i]
var key = event && event.dateKey
if (!key) continue
if (!index[key]) index[key] = []
index[key].push(event)
}
return index
}
function eventsForDateKey(index, dateKey) {
if (!index || !dateKey) return []
var list = (index[dateKey] || []).slice()
list.sort(function(a, b) {
if (a.allDay && !b.allDay) return -1
if (!a.allDay && b.allDay) return 1
return String(a.start || a.time || "").localeCompare(String(b.start || b.time || ""))
})
return list
}
function dateFromKey(dateKey, fallback) {
var parts = String(dateKey || "").split("-")
if (parts.length !== 3) return fallback
var year = parseInt(parts[0], 10)
var month = parseInt(parts[1], 10)
var day = parseInt(parts[2], 10)
if (isNaN(year) || isNaN(month) || isNaN(day)) return fallback
return new Date(year, month - 1, day)
}
// ---- Tasks. A VTODO has at most a due date, and most have none at all, so
// a month grid cannot place them the way it places events. Every task is
// sorted into one of three places instead:
//
// "day" — due today or later: it sits on its due date, like an event
// "week" — no due date, or due before today: it belongs to the loose
// pile of work for the current week
// "done" — finished: it is drawn nowhere. Ticking a todo takes it off
// the panel, which is the whole reward for doing it; a struck
// line hanging around is just the list refusing to shrink.
//
// "week" is the HEY calendar's "sometime this week", and the rollover
// that carries an unfinished task into the next week is this function
// and nothing else. Nothing is written back to the server: an overdue
// task is *displayed* in the current week, every week, until it is
// ticked off. That keeps the widget a reader of the calendar rather than
// an editor of it, and there is no state to drift out of sync.
function taskPlacement(task, todayKey) {
if (!task) return "week"
if (task.done) return "done"
var due = String(task.dueKey || "")
if (!due) return "week"
// Plain string compare: YYYY-MM-DD sorts chronologically.
return due < String(todayKey || "") ? "week" : "day"
}
// Whole days between the due date and today, for the "2 days late" note on a
// rolled-forward task. 0 for anything not overdue.
function taskOverdueDays(task, todayKey) {
if (!task || task.done || !task.dueKey) return 0
var due = dateFromKey(task.dueKey)
var today = dateFromKey(todayKey)
if (!due || !today) return 0
var days = Math.round((today.getTime() - due.getTime()) / MS_PER_DAY)
return days > 0 ? days : 0
}
function tasksFromDocument(doc) {
return doc && doc.tasks && doc.tasks.length ? doc.tasks : []
}
// Only the tasks that sit on a day of their own. The undated and the overdue
// are deliberately absent: they are drawn once, in the week bucket, rather
// than twice.
function indexTasksByDate(tasks, todayKey) {
var index = {}
if (!tasks || !tasks.length) return index
for (var i = 0; i < tasks.length; i++) {
var task = tasks[i]
// Only the ones with a day of their own. The undated and the overdue are
// drawn once, in the week bucket; the finished are not drawn at all.
if (taskPlacement(task, todayKey) !== "day") continue
var key = String(task.dueKey || "")
if (!key) continue
if (!index[key]) index[key] = []
index[key].push(task)
}
return index
}
function tasksForDateKey(index, dateKey) {
if (!index || !dateKey) return []
var list = (index[dateKey] || []).slice()
list.sort(function(a, b) {
// By time of day, then by title. Everything here is open work.
var byTime = String(a.time || "").localeCompare(String(b.time || ""))
if (byTime !== 0) return byTime
return String(a.title || "").localeCompare(String(b.title || ""))
})
return list
}
// Which week a date key falls in, named by the key of that week's first day.
// Takes the configured week start, so the answer always matches the row the
// day sits on in the grid rather than an ISO week that may split it.
function weekStartKeyOf(key, weekStart) {
var date = dateFromKey(key, null)
if (!date) return ""
var start = normalizedWeekStart(weekStart, 1)
var back = (date.getDay() - start + 7) % 7
date.setDate(date.getDate() - back)
return keyForDate(date)
}
// The bucket for one week of the grid.
//
// A loose task belongs to the week it was last carried into, which is the
// later of its own week and this one. And that is always this one: a task
// with a week of its own still ahead of it has a due date, which makes it a
// task with a day, drawn on that day. So the bucket has content on the
// current week and on no other — clicking into next week shows what is
// actually planned for it, not this week's leftovers showing up again under
// every row of the month.
function weekTasksFor(tasks, weekKey, todayKey, weekStart) {
var wanted = String(weekKey || "")
if (!wanted || weekStartKeyOf(todayKey, weekStart) !== wanted) return []
return weekTasks(tasks, todayKey)
}
// The week bucket: everything with no day of its own, most overdue first so
// the oldest thing you have been avoiding is the one at the top.
function weekTasks(tasks, todayKey) {
var list = []
for (var i = 0; tasks && i < tasks.length; i++) {
if (taskPlacement(tasks[i], todayKey) === "week") list.push(tasks[i])
}
list.sort(function(a, b) {
var late = taskOverdueDays(b, todayKey) - taskOverdueDays(a, todayKey)
if (late !== 0) return late
var rank = { high: 0, medium: 1, low: 2 }
var byPriority = (rank[a.priority] === undefined ? 3 : rank[a.priority])
- (rank[b.priority] === undefined ? 3 : rank[b.priority])
if (byPriority !== 0) return byPriority
return String(a.title || "").localeCompare(String(b.title || ""))
})
return list
}
// The distinct calendar colours of the open tasks on one day, for the day
// cell's hollow rings. Finished tasks are left out: a ring is a thing still
// owed, and a day whose only task is done should read as clear.
function taskColors(tasks) {
var colors = []
for (var i = 0; tasks && i < tasks.length; i++) {
if (tasks[i] && tasks[i].done) continue
var color = eventColor(tasks[i])
if (color && colors.indexOf(color) === -1) colors.push(color)
}
return colors
}
function hasOpenTask(tasks) {
for (var i = 0; tasks && i < tasks.length; i++) {
if (tasks[i] && !tasks[i].done) return true
}
return false
}
// What the widget hands `quick-add` to tick a task off. The mailbox needs
// the id the listing carried: todo done names it directly, and a uid would
// mean a lookup the CLI does not offer.
function buildCompleteRequest(task, nowMs) {
if (!task || !task.id) return null
return {
kind: "complete",
id: String(task.id || ""),
uid: String(task.id || ""),
calendarId: String(task.calendarId || ""),
calendarName: String(task.calendarName || ""),
done: !task.done,
completedMs: isFinite(nowMs) ? Math.round(nowMs) : Date.now()
}
}
var MINUTE_MS = 60 * 1000
var HOUR_MS = 60 * MINUTE_MS
var DAY_MS = MS_PER_DAY
function eventStartMs(event) {
if (!event || !event.start) return NaN
return Date.parse(event.start)
}
function eventEndMs(event) {
if (!event) return NaN
if (event.end) {
var end = Date.parse(event.end)
if (!isNaN(end)) return end
}
var start = eventStartMs(event)
if (isNaN(start)) return NaN
return start + HOUR_MS
}
// Timed events only. All-day rows stay on the calendar grid and never
// take the bar: they have no join link and no "in 4m" that would mean
// anything.
function isInProgress(event, nowMs) {
if (!event || event.allDay) return false
var start = eventStartMs(event)
var end = eventEndMs(event)
if (isNaN(start) || isNaN(end)) return false
return nowMs >= start && nowMs < end
}
// Current meeting first, otherwise the soonest timed start still ahead.
// MeetingBar keeps the join target on the bar after the hour, so a click
// at 10:01 still opens the 10:00 standup rather than the 11:00 next.
function nextEvent(events, nowMs) {
var current = null
var currentStart = null
var upcoming = null
var upcomingStart = null
for (var i = 0; i < (events || []).length; i++) {
var event = events[i]
if (!event || event.allDay) continue
var startMs = eventStartMs(event)
if (isNaN(startMs)) continue
if (isInProgress(event, nowMs)) {
if (currentStart === null || startMs < currentStart) {
current = event
currentStart = startMs
}
continue
}
if (startMs < nowMs) continue
if (upcomingStart === null || startMs < upcomingStart) {
upcoming = event
upcomingStart = startMs
}
}
return current || upcoming
}
function formatCountdown(deltaMs) {
if (deltaMs === null || isNaN(deltaMs)) return null
if (deltaMs >= DAY_MS || deltaMs < -DAY_MS) return null
if (deltaMs < MINUTE_MS) return "now"
var minutes = Math.floor(deltaMs / MINUTE_MS)
if (minutes < 60) return "in " + minutes + "m"
var hours = Math.floor(minutes / 60)
var rest = minutes % 60
return rest === 0 ? "in " + hours + "h" : "in " + hours + "h " + rest + "m"
}
// "starts in 5 minutes", then "starts now" once the start time is reached.
// Minutes round up so the last partial minute still reads "starts in 1
// minute" rather than jumping to "now" while there is time left.
function formatStartsIn(deltaMs) {
if (deltaMs === null || isNaN(deltaMs)) return ""
if (deltaMs <= 0) return "starts now"
var minutes = Math.ceil(deltaMs / MINUTE_MS)
if (minutes === 1) return "starts in 1 minute"
if (minutes < 60) return "starts in " + minutes + " minutes"
var hours = Math.floor(minutes / 60)
var rest = minutes % 60
if (rest === 0) return hours === 1 ? "starts in 1 hour" : "starts in " + hours + " hours"
return "starts in " + hours + "h " + rest + "m"
}
// Red only in the last minute, including "starts now".
function isImminent(deltaMs) {
if (deltaMs === null || isNaN(deltaMs)) return false
return deltaMs < MINUTE_MS
}
function joinButtonLabel(url) {
var provider = linkProviderLabel(url)
return provider === "Link" ? "Join" : "Join " + provider
}
var MAX_ANNOUNCE_TITLE = 28
function truncateTitle(title, limit) {
var text = String(title === undefined || title === null ? "" : title)
var max = limit || MAX_ANNOUNCE_TITLE
if (text.length <= max) return text
return text.substring(0, max - 1).replace(/\s+$/, "") + "…"
}
function millisUntil(event, nowMs) {
if (!event) return null
var startMs = Date.parse(event.start)
if (isNaN(startMs)) return null
return startMs - nowMs
}
function shouldAnnounce(event, nowMs, leadMinutes, startedLeadMinutes) {
if (!event) return false
var delta = millisUntil(event, nowMs)
if (delta === null) return false
if (delta <= 0) {
if (!isInProgress(event, nowMs)) return false
var startedLead = startedLeadMinutes === undefined || startedLeadMinutes === null
? 5
: Number(startedLeadMinutes)
if (!isFinite(startedLead) || startedLead <= 0) return false
return -delta <= startedLead * MINUTE_MS
}
var lead = Number(leadMinutes)
if (!isFinite(lead) || lead < 0) lead = 0
if (lead > 0 && delta <= lead * MINUTE_MS) return true
// The event's own reminders (--alarm / VALARM) each fire once and briefly:
// shown for blipMinutes and then gone, with no running countdown. The bar
// is the only reminder the desktop has, so it mirrors the phone's single
// buzz rather than sitting on screen for the whole hour before the start.
return inAlarmBlip(event, nowMs, leadMinutes, startedLeadMinutes)
}
var DEFAULT_BLIP_MINUTES = 1
// True while an alarm the event carries is inside its brief on-screen window
// and the normal lead countdown has not taken over yet. The widget reads this
// to drop the countdown phrase and give the label one shake as it appears.
function inAlarmBlip(event, nowMs, leadMinutes, blipMinutes) {
if (!event) return false
var delta = millisUntil(event, nowMs)
if (delta === null || delta <= 0) return false
var lead = Number(leadMinutes)
if (isFinite(lead) && lead > 0 && delta <= lead * MINUTE_MS) return false
var blip = Number(blipMinutes)
if (!isFinite(blip) || blip <= 0) blip = DEFAULT_BLIP_MINUTES
var alarms = event.alarms
for (var i = 0; alarms && i < alarms.length; i++) {
var at = Number(alarms[i]) * MINUTE_MS
if (isFinite(at) && at > 0 && delta <= at && delta > at - blip * MINUTE_MS) return true
}
return false
}
// A join button left unclicked: the meeting is running, it still has a
// Join link, and between graceMs and windowMs has passed since it started
// without one. Past the window the meeting counts as deliberately skipped,
// not forgotten -- and a shell restarted hours into it stays quiet instead
// of punishing the restart. Fires on every tick while true; the widget
// supplies the once-per-occurrence memory so the sound plays a single time.
function shouldNudge(event, nowMs, graceMs, windowMs) {
if (!event) return false
if (!isMeetingUrl(meetingUrlFor(event))) return false
if (!isInProgress(event, nowMs)) return false
var start = eventStartMs(event)
if (isNaN(start)) return false
var grace = Number(graceMs)
if (!isFinite(grace) || grace < 0) grace = MINUTE_MS
var window = Number(windowMs)
if (!isFinite(window) || window < grace) window = 5 * MINUTE_MS
var late = nowMs - start
return late >= grace && late <= window
}
function occurrenceKey(event) {
if (!event) return ""
var id = String(event.id || "")
var start = String(event.start || "")
if (!id && !start) return ""
return id + "|" + start
}
function isDismissed(event, dismissedKey) {
var key = occurrenceKey(event)
return key !== "" && key === String(dismissedKey || "")
}
function eventDisplayTime(event) {
if (!event) return ""
if (event.allDay) return "All day"
if (event.time) return event.time
if (!event.start) return ""
var start = new Date(event.start)
if (isNaN(start.getTime())) return ""
var h = start.getHours()
var m = start.getMinutes()
return (h < 10 ? "0" : "") + h + ":" + (m < 10 ? "0" : "") + m
}
// A link is supplied by whoever sent the invitation, so treating it as
// trusted input would be a mistake. http as well as https — the entry pane
// lets a link be typed by hand, and refusing to open what it just stored
// would be the odder of the two. Every other scheme stays out: this string
// is handed to a browser.
function safeUrl(url) {
var text = String(url || "").trim()
if (!/^https?:\/\//i.test(text)) return ""
if (/[\s"'<>]/.test(text)) return ""
if (text.length > 2000) return ""
return text
}
// The server keeps a colour per calendar and the sync script carries it onto
// every event, so a work event and a personal one on the same day can be told
// apart at a glance instead of both reading as the theme accent. Validated
// rather than trusted: the value comes out of the profile prefs, and QML turns
// anything it cannot parse into black rather than falling back.
function safeColor(value) {
var text = String(value || "").trim()
return /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/.test(text) ? text : ""
}
// The same guard under the name the storing paths call it by.
function safeLinkUrl(url) {
return safeUrl(url)
}
// What to call a meeting link in one word, for the pill that holds it.
function linkProviderLabel(url) {
var text = String(url || "").toLowerCase()
if (!text) return "Link"
if (text.indexOf("zoom.") !== -1) return "Zoom"
if (text.indexOf("meet.google.") !== -1) return "Meet"
if (text.indexOf("teams.") !== -1) return "Teams"
if (text.indexOf("jitsi") !== -1 || text.indexOf("jit.si") !== -1) return "Jitsi"
if (text.indexOf("whereby.") !== -1) return "Whereby"
if (text.indexOf("webex.") !== -1) return "Webex"
return "Link"
}
function eventColor(event) {
return event ? safeColor(event.color) : ""
}
// The distinct calendar colours on one day, in the order their first event
// falls. A day with three events out of one calendar gets one dot; a day
// split across two calendars gets two.
function dayColors(events) {
var colors = []
for (var i = 0; events && i < events.length; i++) {
var color = eventColor(events[i])
if (color && colors.indexOf(color) === -1) colors.push(color)
}
return colors
}
function isCalendarFileUrl(url) {
var text = String(url || "")
return /\/ics(\?|$)/i.test(text) || /\.ics(\?|$)/i.test(text) || /icsToken=/i.test(text)
}
function meetingUrlFor(event) {
var text = event ? safeUrl(event.meetingUrl) : ""
if (!text || isCalendarFileUrl(text)) return ""
return text
}
// A room to join rather than a page to read. Same host rule meetingUrlIn
// applies: a link on an unknown host — the pool's homepage sitting in the
// URL field — is a document, and gets a Link button, never a Join.
function isMeetingUrl(url) {
var text = safeUrl(url)
if (!text || isCalendarFileUrl(text)) return false
var host = text.split("//").pop().split("/")[0]
return MAILBOX_MEETING_HOST.test(host)
}
// ---- Natural-language quick-add. Bilingual by table, not by setting: EN
// and DE keywords are matched simultaneously, so "lunch mit Ana morgen
// 12:30" parses the same way either language wins a token. The start
// day is never parsed from the text — it comes from the day the user
// right-clicked — so the grammar only adds times, ends and flags on top
// of it.
var NL_WEEKDAYS = [
{ index: 0, names: ["sunday", "sonntag", "so."] },
{ index: 1, names: ["monday", "montag", "mo."] },
{ index: 2, names: ["tuesday", "dienstag", "di."] },
{ index: 3, names: ["wednesday", "mittwoch", "mi."] },
{ index: 4, names: ["thursday", "donnerstag", "do."] },
{ index: 5, names: ["friday", "freitag", "fr."] },
{ index: 6, names: ["saturday", "samstag", "sonnabend", "sa."] }
]
var NL_WORDS = {
today: ["today", "heute"],
tomorrow: ["tomorrow", "morgen"],
next: ["next", "nächste", "nächsten", "nächster", "kommende", "kommenden", "kommender"],
till: ["till", "until", "bis"],
for: ["for", "für"],
place: ["at", "bei", "beim"]
}
function nlIs(word, group) {
return NL_WORDS[group].indexOf(String(word || "").toLowerCase()) !== -1
}
function nlWeekdayIndex(word) {
var text = String(word || "").toLowerCase()
for (var i = 0; i < NL_WEEKDAYS.length; i++)
if (NL_WEEKDAYS[i].names.indexOf(text) !== -1) return NL_WEEKDAYS[i].index
return -1
}
// Strict times need an anchor — a colon, an am/pm suffix, a following
// "uhr", or the noon words — so a bare "15" stays part of the title.
function nlParseStrictTime(tokens, i) {
var token = String(tokens[i] || "").toLowerCase().replace(/[,.;]$/, "")
if (token === "noon" || token === "mittag") return { minutes: 12 * 60, used: 1 }
var match = /^(\d{1,2})(?:[:.](\d{2}))?(am|pm)?$/.exec(token)
if (!match) return null
var hours = parseInt(match[1], 10)
var minutes = match[2] ? parseInt(match[2], 10) : 0
var meridiem = match[3] || ""
var anchored = !!match[2] || !!meridiem
var used = 1
if (!anchored && i + 1 < tokens.length && String(tokens[i + 1]).toLowerCase() === "uhr") {
anchored = true
used = 2
} else if (!anchored && !meridiem && token.indexOf("uhr") === token.length - 3 && /\d+uhr/.test(token)) {
// "10uhr" written as one word.
anchored = true
hours = parseInt(/^(\d+)/.exec(token)[1], 10)
}
if (!anchored) return null
if (meridiem === "pm" && hours < 12) hours += 12
if (meridiem === "am" && hours === 12) hours = 0
if (hours > 24 || minutes > 59) return null
return { minutes: hours * 60 + minutes, used: used }
}
function nlTimeLabel(minutesOfDay) {
return pad2(Math.floor(minutesOfDay / 60)) + ":" + pad2(minutesOfDay % 60)
}
// One side of a range: bare hour or hh:mm, minutes optional. Used for
// "12-13", "12 to 13" and friends — deliberately looser than the strict
// time matcher, because the range dash or connector supplies the anchor.
function nlRangeSide(text) {
var match = /^(\d{1,2})(?:[:.](\d{2}))?$/.exec(String(text || "").toLowerCase())
if (!match) return null
var hours = parseInt(match[1], 10)
var minutes = match[2] ? parseInt(match[2], 10) : 0
if (hours > 23 || minutes > 59) return null
return hours * 60 + minutes
}
// Words that join two times into a range: "to", plus the till family,
// which doubles as an end marker when no start time precedes it.
function nlConnector(text) {
var token = String(text || "").toLowerCase().replace(/[,.;]$/, "")
return token === "to" || nlIs(token, "till") ? token : null
}
// Next occurrence of a weekday on or after the base day (same day counts:
// "standup friday" clicked on friday means today).
function nlNextWeekday(base, weekday) {
var d = new Date(base.getFullYear(), base.getMonth(), base.getDate())
d.setDate(d.getDate() + ((weekday - d.getDay() + 7) % 7))
return d
}
// A single day word — "today", "morgen", a weekday name, "15.3." or an ISO
// date — as a Date, or null when the word is not one of those. `next` pushes
// a named weekday or an explicit date a week on; "next today" is not a thing,
// so the relative words ignore it.
function nlDayFrom(word, base, next) {
var lower = String(word || "").toLowerCase().replace(/[,.;]$/, "")
var midnight = new Date(base.getFullYear(), base.getMonth(), base.getDate())
if (nlIs(lower, "today")) return midnight
if (nlIs(lower, "tomorrow")) {
midnight.setDate(midnight.getDate() + 1)
return midnight
}
var weekday = nlWeekdayIndex(lower)
if (weekday !== -1) {
var wd = nlNextWeekday(base, weekday)
if (next) wd.setDate(wd.getDate() + 7)
return wd
}
var explicit = nlExplicitDate(lower, base.getFullYear())
if (!explicit || isNaN(explicit.date.getTime())) return null
var d = explicit.date
// "15.3." said in August means the March that is coming, not the one that
// went. Only yearless dates roll forward; ISO means what it says.
if (explicit.yearless && d.getTime() < midnight.getTime()) d.setFullYear(d.getFullYear() + 1)
if (next) d.setDate(d.getDate() + 7)
return d
}
function nlExplicitDate(text, baseYear) {
var iso = /^(20\d{2})-(\d{1,2})-(\d{1,2})$/.exec(text)
if (iso) return { date: new Date(parseInt(iso[1], 10), parseInt(iso[2], 10) - 1, parseInt(iso[3], 10)), yearless: false }
// German-style day.month, with or without a trailing dot, with optional year:
// "15.3" / "15.3." / "15.3.2026". The trailing-dot strip on tokens leaves "15.3".
var dm = /^(\d{1,2})\.(\d{1,2})\.?(?:(20\d{2}))?\.?$/.exec(text)
if (dm) return {
date: new Date(dm[3] ? parseInt(dm[3], 10) : baseYear, parseInt(dm[2], 10) - 1, parseInt(dm[1], 10)),
yearless: !dm[3]
}
return null
}
function emptyDraft(kind, dayKey) {
return {
kind: kind,
title: "",
dateKey: String(dayKey || ""),
endDateKey: null,
startTime: null,
endTime: null,
endNextDay: false,
durationMinutes: null,
allDay: kind !== "task",
location: null,
description: null,
calendarName: null,
alertMinutes: null,
recurrence: null,
priority: null,
link: null,
// Teams and invites only mean something on a Microsoft 365 calendar, so
// they stay empty until one is picked — buildQuickAddRequest gates them
// on the roster row, and requestToArgs sends only what is there.
teams: false,
// An event that is already a Teams meeting stays one: there is no off
// (a Microsoft 365 rule), so the pane locks the switch instead.
teamsLocked: false,
invitees: [],
originalInvitees: [],
segments: []
}
}
// Everything the natural-language path can express, in one flat object the
// form reads and edits. `knownCalendars` (from the mirror's own list) lets
// bare "in Work" resolve without the slash-flag syntax.
function parseEventPhrase(text, dayKey, nowMs, knownCalendars) {
var raw = String(text === undefined || text === null ? "" : text).trim()
if (!raw) return null
var now = new Date(isFinite(nowMs) ? nowMs : Date.now())
var base = dateFromKey(dayKey, null) || new Date(now.getFullYear(), now.getMonth(), now.getDate())
var draft = emptyDraft("event", keyForDate(base))
var known = []
for (var k = 0; knownCalendars && k < knownCalendars.length; k++)
known.push(String(knownCalendars[k] || "").toLowerCase())
// Every token keeps its offset in `raw` and the role it ends up playing,
// so the entry field can paint the phrase in the colours of the parts it
// understood while it is being typed. `mark` takes positions in `rest`
// (the post-flag token list) and writes the role back to the offsets.
var spans = []
var scan = /\S+/g
var found
while ((found = scan.exec(raw)) !== null)
spans.push({ start: found.index, end: found.index + found[0].length, role: null })
var rest = []
var restIndex = []
function mark(restFrom, restTo, role) {
for (var s = restFrom; s <= restTo && s < restIndex.length; s++)
if (s >= 0) spans[restIndex[s]].role = role
}
// ---- Flags first: /calendar, -aN[mhd], -rN[dwmy], trailing !{1,3}.
var tokens = raw.split(/\s+/)
for (var t = 0; t < tokens.length; t++) {
var token = tokens[t]
var flag
if ((flag = /^\/(.+)$/.exec(token))) {
draft.calendarName = flag[1].replace(/[,.;]$/, "")
spans[t].role = "calendar"
continue
}
if ((flag = /^-a(\d+)([mhd])$/i.exec(token))) {
var factor = flag[2].toLowerCase() === "d" ? 1440 : flag[2].toLowerCase() === "h" ? 60 : 1
draft.alertMinutes = parseInt(flag[1], 10) * factor
spans[t].role = "alert"
continue
}
if ((flag = /^-r(\d+)([dwmy])$/i.exec(token))) {
var unit = flag[2].toLowerCase()
draft.recurrence = {
freq: unit === "d" ? "daily" : unit === "w" ? "weekly" : unit === "m" ? "monthly" : "yearly",
interval: parseInt(flag[1], 10)
}
spans[t].role = "repeat"
continue
}
// A pasted meeting link is a part of its own: it never belongs in the
// title, and the bar's join button reads it back off the created event.
if (/^https?:\/\//i.test(token)) {
var link = safeLinkUrl(token.replace(/[),.;]+$/, ""))
if (link) {
draft.link = link
spans[t].role = "link"
continue
}
}
// Duration flag from the reference quick-add: "-120" is two hours,
// "-90m" and "-2h" say the same thing with the unit spelled out.
if ((flag = /^-(\d+)(m|min|h|std)?$/i.exec(token))) {
var durationUnit = (flag[2] || "m").toLowerCase().charAt(0)
draft.durationMinutes = parseInt(flag[1], 10) * (durationUnit === "h" ? 60 : 1)
spans[t].role = "duration"
continue
}
if (/^!{1,3}$/.test(token)) {
draft.priority = token.length === 1 ? "low" : token.length === 2 ? "medium" : "high"
spans[t].role = "priority"
continue