@forcecalendar/core 2.4.0 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -98,13 +98,16 @@ export class EventStore {
98
98
 
99
99
  /**
100
100
  * Update an existing event
101
- * @param {string} eventId - The event ID
101
+ *
102
+ * An occurrence id (see {@link Event.occurrenceId}) updates the recurring
103
+ * master the occurrence belongs to, i.e. the whole series.
104
+ * @param {string} eventId - Event id or occurrence id
102
105
  * @param {Partial<import('../types.js').EventData>} updates - Properties to update
103
- * @returns {Event} The updated event
106
+ * @returns {Event} The updated event (the master for an occurrence id)
104
107
  * @throws {Error} If event not found
105
108
  */
106
109
  updateEvent(eventId, updates) {
107
- const existingEvent = this.events.get(eventId);
110
+ const existingEvent = this.events.get(eventId) || this._resolveOccurrenceMaster(eventId);
108
111
  if (!existingEvent) {
109
112
  throw new Error(`Event with id ${eventId} not found`);
110
113
  }
@@ -152,11 +155,14 @@ export class EventStore {
152
155
 
153
156
  /**
154
157
  * Remove an event from the store
155
- * @param {string} eventId - The event ID to remove
158
+ *
159
+ * An occurrence id (see {@link Event.occurrenceId}) removes the recurring
160
+ * master the occurrence belongs to, i.e. the whole series.
161
+ * @param {string} eventId - Event id or occurrence id
156
162
  * @returns {boolean} True if removed, false if not found
157
163
  */
158
164
  removeEvent(eventId) {
159
- const event = this.events.get(eventId);
165
+ const event = this.events.get(eventId) || this._resolveOccurrenceMaster(eventId);
160
166
  if (!event) {
161
167
  return false;
162
168
  }
@@ -193,8 +199,13 @@ export class EventStore {
193
199
 
194
200
  /**
195
201
  * Get an event by ID
196
- * @param {string} eventId - The event ID
197
- * @returns {Event|null} The event or null if not found
202
+ *
203
+ * Occurrence ids produced by {@link EventStore#expandRecurringEvent}
204
+ * (`<masterId>_<startMs>`, see {@link Event.occurrenceId}) resolve to the
205
+ * stored recurring master they were derived from, so an id taken from view
206
+ * data can always be looked up. Occurrences themselves are never stored.
207
+ * @param {string} eventId - Event id or occurrence id
208
+ * @returns {Event|null} The stored event (the master for an occurrence id) or null
198
209
  */
199
210
  getEvent(eventId) {
200
211
  // Check cache first
@@ -209,9 +220,26 @@ export class EventStore {
209
220
  // Cache if found
210
221
  if (event) {
211
222
  this.optimizer.cache(eventId, event, 'event');
223
+ return event;
212
224
  }
213
225
 
214
- return event;
226
+ return this._resolveOccurrenceMaster(eventId);
227
+ }
228
+
229
+ /**
230
+ * Resolve an occurrence id to the stored recurring master it belongs to.
231
+ * Not cached: the master's own cache entry is the one kept in sync.
232
+ * @param {string} eventId - Candidate occurrence id
233
+ * @returns {Event|null} The master event or null
234
+ * @private
235
+ */
236
+ _resolveOccurrenceMaster(eventId) {
237
+ const parsed = Event.parseOccurrenceId(eventId);
238
+ if (!parsed) {
239
+ return null;
240
+ }
241
+ const master = this.events.get(parsed.recurringEventId);
242
+ return master && master.recurring ? master : null;
215
243
  }
216
244
 
217
245
  /**
@@ -343,14 +371,103 @@ export class EventStore {
343
371
 
344
372
  /**
345
373
  * Get events for a specific date
374
+ *
375
+ * Recurring series are expanded for the day, so the result holds their
376
+ * occurrences (see {@link EventStore#expandRecurringEvent}) rather than the
377
+ * master events. When building a grid of days use
378
+ * {@link EventStore#getEventsByDate}, which expands once for the whole range.
346
379
  * @param {Date} date - The date to query
347
380
  * @param {string} [timezone] - Timezone for the query (defaults to store timezone)
348
381
  * @returns {Event[]} Events occurring on the date, sorted by start time
349
382
  */
350
383
  getEventsForDate(date, timezone = null) {
351
384
  timezone = timezone || this.defaultTimezone;
385
+ const dayStart = DateUtils.startOfDay(date);
386
+ const dayEnd = DateUtils.endOfDay(date);
387
+
388
+ const candidates = [];
389
+ for (const id of this._collectDateCandidateIds(date)) {
390
+ const event = this.events.get(id);
391
+ // Recurring masters are represented by their occurrences below
392
+ if (event && !event.recurring) {
393
+ candidates.push(event);
394
+ }
395
+ }
396
+
397
+ for (const id of this.indices.recurring) {
398
+ const event = this.events.get(id);
399
+ if (event) {
400
+ candidates.push(...this.expandRecurringEvent(event, dayStart, dayEnd, timezone));
401
+ }
402
+ }
403
+
404
+ return this._selectEventsForDay(candidates, dayStart, dayEnd, timezone);
405
+ }
406
+
407
+ /**
408
+ * Get the events for every day in a range, keyed by local date (YYYY-MM-DD)
409
+ *
410
+ * Recurring series are expanded once for the whole range rather than once
411
+ * per day, which is what a month or week grid needs. Every day in the range
412
+ * has an entry (an empty array when nothing occurs) and multi-day events
413
+ * appear under each day they span. Each array is sorted like
414
+ * {@link EventStore#getEventsForDate}.
415
+ *
416
+ * @example
417
+ * const byDate = store.getEventsByDate(gridStart, gridEnd);
418
+ * const events = byDate.get(DateUtils.getLocalDateString(cellDate)) || [];
419
+ *
420
+ * @param {Date} start - First day of the range
421
+ * @param {Date} end - Last day of the range
422
+ * @param {string} [timezone] - Timezone deciding which day an event falls on (defaults to store timezone)
423
+ * @returns {Map<string, Event[]>} Local date string -> events on that day
424
+ */
425
+ getEventsByDate(start, end, timezone = null) {
426
+ timezone = timezone || this.defaultTimezone;
427
+ const rangeStart = DateUtils.startOfDay(start);
428
+ const rangeEnd = DateUtils.endOfDay(end);
429
+
430
+ /** @type {Map<string, Event[]>} */
431
+ const byDate = new Map();
432
+ for (const day of DateUtils.getDateRange(rangeStart, rangeEnd)) {
433
+ byDate.set(DateUtils.getLocalDateString(day), []);
434
+ }
435
+
436
+ // Query one day beyond each edge so events that fall on an edge day in
437
+ // the requested timezone are not lost to the UTC-based range filter.
438
+ const events = this.getEventsInRange(
439
+ DateUtils.addDays(rangeStart, -1),
440
+ DateUtils.addDays(rangeEnd, 1),
441
+ true,
442
+ timezone
443
+ );
444
+
445
+ for (const event of events) {
446
+ const eventStart = event.getStartInTimezone(timezone);
447
+ const eventEnd = event.getEndInTimezone(timezone);
448
+ const lastDay = eventEnd < rangeEnd ? eventEnd : rangeEnd;
449
+ let day = DateUtils.startOfDay(eventStart > rangeStart ? eventStart : rangeStart);
450
+ while (day <= lastDay) {
451
+ byDate.get(DateUtils.getLocalDateString(day))?.push(event);
452
+ day = DateUtils.addDays(day, 1);
453
+ }
454
+ }
455
+
456
+ const compare = this._compareByStart(timezone);
457
+ for (const dayEvents of byDate.values()) {
458
+ dayEvents.sort(compare);
459
+ }
460
+
461
+ return byDate;
462
+ }
352
463
 
353
- // Collect candidate event IDs from indices
464
+ /**
465
+ * Collect the ids of stored events that may occur on a date.
466
+ * @param {Date} date - The date to query
467
+ * @returns {Set<string>} Candidate event ids
468
+ * @private
469
+ */
470
+ _collectDateCandidateIds(date) {
354
471
  const candidateIds = new Set();
355
472
 
356
473
  // Check byDate index for nearby dates (handles most events)
@@ -374,35 +491,41 @@ export class EventStore {
374
491
  monthEventIds.forEach(id => candidateIds.add(id));
375
492
  }
376
493
 
377
- // Filter candidates to events that actually overlap with the requested date
378
- const allEvents = [];
379
- const startOfDay = new Date(date);
380
- startOfDay.setHours(0, 0, 0, 0);
381
- const endOfDay = new Date(date);
382
- endOfDay.setHours(23, 59, 59, 999);
494
+ return candidateIds;
495
+ }
383
496
 
384
- for (const id of candidateIds) {
385
- const event = this.events.get(id);
386
- if (event) {
387
- // Check if event actually occurs on the requested date in the given timezone
388
- const eventStartLocal = event.getStartInTimezone(timezone);
389
- const eventEndLocal = event.getEndInTimezone(timezone);
497
+ /**
498
+ * Keep the events that overlap a day in the given timezone, sorted by start.
499
+ * @param {Event[]} events - Candidate events
500
+ * @param {Date} dayStart - Start of the day
501
+ * @param {Date} dayEnd - End of the day
502
+ * @param {string} timezone - Timezone deciding whether an event falls on the day
503
+ * @returns {Event[]} Events on the day, sorted
504
+ * @private
505
+ */
506
+ _selectEventsForDay(events, dayStart, dayEnd, timezone) {
507
+ const onDay = events.filter(event => {
508
+ // Event overlaps with this day if it starts before end of day and ends after start of day
509
+ const eventStartLocal = event.getStartInTimezone(timezone);
510
+ const eventEndLocal = event.getEndInTimezone(timezone);
511
+ return eventStartLocal <= dayEnd && eventEndLocal >= dayStart;
512
+ });
390
513
 
391
- // Event overlaps with this day if it starts before end of day and ends after start of day
392
- if (eventStartLocal <= endOfDay && eventEndLocal >= startOfDay) {
393
- allEvents.push(event);
394
- }
395
- }
396
- }
514
+ return onDay.sort(this._compareByStart(timezone));
515
+ }
397
516
 
398
- return allEvents.sort((a, b) => {
399
- // Sort by start time in the specified timezone
400
- const aStart = a.getStartInTimezone(timezone);
401
- const bStart = b.getStartInTimezone(timezone);
402
- const timeCompare = aStart - bStart;
517
+ /**
518
+ * Comparator ordering events by start time in a timezone, longer events first.
519
+ * @param {string} timezone - Timezone used for the start comparison
520
+ * @returns {(a: Event, b: Event) => number} Comparator
521
+ * @private
522
+ */
523
+ _compareByStart(timezone) {
524
+ return (a, b) => {
525
+ const timeCompare = a.getStartInTimezone(timezone) - b.getStartInTimezone(timezone);
403
526
  if (timeCompare !== 0) return timeCompare;
404
527
  return b.duration - a.duration; // Longer events first
405
- });
528
+ };
406
529
  }
407
530
 
408
531
  /**
@@ -478,11 +601,19 @@ export class EventStore {
478
601
  * @returns {Array<Event[]>} Array of event groups that overlap
479
602
  */
480
603
  getOverlapGroups(date, timedOnly = true) {
481
- let events = this.getEventsForDate(date);
604
+ return this.groupOverlappingEvents(this.getEventsForDate(date), timedOnly);
605
+ }
482
606
 
483
- if (timedOnly) {
484
- events = events.filter(e => !e.allDay);
485
- }
607
+ /**
608
+ * Group a list of events into clusters of overlapping time slots
609
+ * Same result as {@link EventStore#getOverlapGroups} for events already fetched
610
+ * (for example one day of {@link EventStore#getEventsByDate}).
611
+ * @param {Event[]} events - Events to group; the array is not modified
612
+ * @param {boolean} [timedOnly=true] - Only include timed events (not all-day)
613
+ * @returns {Array<Event[]>} Array of event groups that overlap
614
+ */
615
+ groupOverlappingEvents(events, timedOnly = true) {
616
+ events = timedOnly ? events.filter(e => !e.allDay) : [...events];
486
617
 
487
618
  if (events.length === 0) return [];
488
619
 
@@ -644,6 +775,16 @@ export class EventStore {
644
775
 
645
776
  /**
646
777
  * Expand a recurring event into individual occurrences
778
+ *
779
+ * Returns every occurrence that overlaps the range, including ones that
780
+ * start before it but run into it (multi-day series). Each occurrence is an
781
+ * {@link Event} cloned from the master with:
782
+ * - `id` from {@link Event.occurrenceId} (`<masterId>_<startMs>`), stable
783
+ * across ranges and resolvable with {@link EventStore#getEvent},
784
+ * - `isOccurrence: true`, `recurringEventId` and `occurrenceStart`,
785
+ * - `metadata.recurringEventId`, `metadata.occurrenceId` (same as `id`) and
786
+ * `metadata.occurrenceIndex` (position within this expansion).
787
+ * Non-recurring events are returned as-is in a one-element array.
647
788
  * @param {Event} event - The recurring event
648
789
  * @param {Date} rangeStart - Start of the expansion range
649
790
  * @param {Date} rangeEnd - End of the expansion range
@@ -659,27 +800,141 @@ export class EventStore {
659
800
 
660
801
  // Expand in the event's timezone for accurate recurrence calculation
661
802
  const eventTimezone = event.timeZone || timezone;
662
- const occurrences = this.recurrenceEngine.expandEvent(event, rangeStart, rangeEnd, {
803
+
804
+ // The engine selects occurrences by start, so look back one event
805
+ // duration to catch occurrences that began before the range but overlap it
806
+ const duration = Math.max(0, event.end - event.start);
807
+ const expandStart = new Date(rangeStart.getTime() - duration);
808
+ const occurrences = this.recurrenceEngine.expandEvent(event, expandStart, rangeEnd, {
663
809
  timezone: eventTimezone
664
810
  });
665
811
 
666
- return occurrences.map((occurrence, index) => {
667
- // Create a new event instance for each occurrence
668
- const occurrenceEvent = event.clone({
669
- id: `${event.id}_occurrence_${index}`,
670
- start: occurrence.start,
671
- end: occurrence.end,
672
- timeZone: occurrence.timezone || eventTimezone,
673
- metadata: {
674
- ...event.metadata,
675
- recurringEventId: event.id,
676
- occurrenceId: occurrence.id,
677
- occurrenceIndex: index
678
- }
679
- });
812
+ const expanded = [];
813
+ for (const occurrence of occurrences) {
814
+ if (occurrence.end < rangeStart || occurrence.start > rangeEnd) {
815
+ continue;
816
+ }
817
+ expanded.push(this._createOccurrence(event, occurrence, eventTimezone, expanded.length));
818
+ }
680
819
 
681
- return occurrenceEvent;
820
+ return expanded;
821
+ }
822
+
823
+ /**
824
+ * Build the Event instance for one occurrence of a recurring master.
825
+ * @param {Event} event - The recurring master
826
+ * @param {{start: Date, end: Date, timezone?: string}} occurrence - Engine occurrence
827
+ * @param {string} eventTimezone - Timezone the series was expanded in
828
+ * @param {number} index - Position within the current expansion
829
+ * @returns {Event} Occurrence event
830
+ * @private
831
+ */
832
+ _createOccurrence(event, occurrence, eventTimezone, index) {
833
+ const occurrenceStart = new Date(occurrence.start);
834
+ const id = Event.occurrenceId(event.id, occurrenceStart);
835
+
836
+ const occurrenceEvent = event.clone({
837
+ id,
838
+ start: occurrenceStart,
839
+ end: new Date(occurrence.end),
840
+ timeZone: occurrence.timezone || eventTimezone,
841
+ metadata: {
842
+ ...event.metadata,
843
+ recurringEventId: event.id,
844
+ occurrenceId: id,
845
+ occurrenceIndex: index
846
+ }
682
847
  });
848
+
849
+ occurrenceEvent.isOccurrence = true;
850
+ occurrenceEvent.recurringEventId = event.id;
851
+ occurrenceEvent.occurrenceStart = new Date(occurrenceStart);
852
+
853
+ return occurrenceEvent;
854
+ }
855
+
856
+ /**
857
+ * Lazily iterate the occurrences of a stored event in chronological order.
858
+ *
859
+ * Occurrences come one at a time from the store's recurrence engine
860
+ * (RecurrenceEngineV2 by default), so taking the next few occurrences of
861
+ * an open-ended series does not expand the series. `after` and `before`
862
+ * are exclusive unless `inclusive` is set; see
863
+ * RecurrenceEngineV2.iterateOccurrences for the full semantics. The
864
+ * expansion timezone defaults to the event's, then the store's.
865
+ *
866
+ * @example
867
+ * for (const occurrence of store.iterateOccurrences('standup', { after: new Date() })) {
868
+ * if (occurrence.start > deadline) break;
869
+ * remind(occurrence);
870
+ * }
871
+ *
872
+ * @param {string} eventId - The event ID
873
+ * @param {import('../types.js').ExpandedOccurrenceIteratorOptions} [options={}] - Window and expansion options
874
+ * @returns {Generator<import('../types.js').ExpandedOccurrence, void, undefined>} Occurrences in chronological order
875
+ * @throws {Error} If no event with the ID exists
876
+ */
877
+ iterateOccurrences(eventId, options = {}) {
878
+ const query = this._occurrenceQuery(eventId, options);
879
+ return this.recurrenceEngine.iterateOccurrences(query.event, query.options);
880
+ }
881
+
882
+ /**
883
+ * First occurrence of a stored event after an instant, or null when the
884
+ * series has no occurrence after it. `after` is exclusive unless
885
+ * `options.inclusive` is set.
886
+ *
887
+ * @example
888
+ * const upcoming = store.getNextOccurrence('standup', new Date());
889
+ *
890
+ * @param {string} eventId - The event ID
891
+ * @param {Date|number} [after=null] - Instant to search from (defaults to the series start)
892
+ * @param {import('../types.js').ExpandedOccurrenceIteratorOptions} [options={}] - Further options
893
+ * @returns {import('../types.js').ExpandedOccurrence|null} The next occurrence, or null
894
+ * @throws {Error} If no event with the ID exists
895
+ */
896
+ getNextOccurrence(eventId, after = null, options = {}) {
897
+ const query = this._occurrenceQuery(eventId, options);
898
+ return this.recurrenceEngine.nextOccurrence(query.event, after, query.options);
899
+ }
900
+
901
+ /**
902
+ * The first `count` occurrences of a stored event inside a window,
903
+ * generated lazily. `count` is capped at the engine's
904
+ * MAX_OCCURRENCES_HARD_LIMIT.
905
+ *
906
+ * @example
907
+ * const nextFive = store.takeOccurrences('standup', 5, { after: new Date() });
908
+ *
909
+ * @param {string} eventId - The event ID
910
+ * @param {number} count - Maximum number of occurrences to return
911
+ * @param {import('../types.js').ExpandedOccurrenceIteratorOptions} [options={}] - Window and expansion options
912
+ * @returns {import('../types.js').ExpandedOccurrence[]} Up to `count` occurrences in chronological order
913
+ * @throws {Error} If no event with the ID exists
914
+ */
915
+ takeOccurrences(eventId, count, options = {}) {
916
+ const query = this._occurrenceQuery(eventId, options);
917
+ return this.recurrenceEngine.takeOccurrences(query.event, count, query.options);
918
+ }
919
+
920
+ /**
921
+ * Resolve an occurrence query to the stored event and its options, with
922
+ * the timezone defaulted as expandRecurringEvent does
923
+ * @param {string} eventId - The event ID
924
+ * @param {Object} options - Caller options
925
+ * @returns {{ event: Event, options: Object }}
926
+ * @throws {Error} If no event with the ID exists
927
+ * @private
928
+ */
929
+ _occurrenceQuery(eventId, options) {
930
+ const event = this.events.get(eventId);
931
+ if (!event) {
932
+ throw new Error(`Event with id ${eventId} not found`);
933
+ }
934
+ return {
935
+ event,
936
+ options: { ...options, timezone: options.timezone || event.timeZone || this.defaultTimezone }
937
+ };
683
938
  }
684
939
 
685
940
  /**