@super-calendar/core 2.17.0 → 2.19.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.
@@ -146,8 +146,13 @@ export const isWeekend = (date: Date): boolean => {
146
146
  return day === 0 || day === 6;
147
147
  };
148
148
 
149
- /** True when `date` falls on the current calendar day. */
150
- export const getIsToday = (date: Date): boolean => isToday(date);
149
+ /**
150
+ * True when `date` falls on the current calendar day. Pass `today` to compare
151
+ * against that day instead of the device clock, e.g. the result of
152
+ * `nowInTimeZone` for a calendar displayed in another time zone.
153
+ */
154
+ export const getIsToday = (date: Date, today?: Date): boolean =>
155
+ today ? isSameDay(date, today) : isToday(date);
151
156
 
152
157
  /** True when `a` and `b` are the same calendar day (ignoring the time of day). */
153
158
  export const isSameCalendarDay = (a: Date, b: Date): boolean => isSameDay(a, b);
package/src/utils/drag.ts CHANGED
@@ -6,11 +6,19 @@ import { MIN_DURATION_HOURS } from "./minDuration";
6
6
 
7
7
  /**
8
8
  * True when two time ranges overlap. Edges touching (one ends exactly when the
9
- * next begins) do not count as an overlap. Compares absolute instants, so events
10
- * at the same wall-clock time on different days do not overlap.
9
+ * next begins) do not count as an overlap. A zero-length range occupies its own
10
+ * instant: it overlaps a range that contains that instant or starts at it, and
11
+ * another zero-length range at the same instant. Compares absolute instants, so
12
+ * events at the same wall-clock time on different days do not overlap.
11
13
  */
12
14
  export function eventsOverlap(aStart: Date, aEnd: Date, bStart: Date, bEnd: Date): boolean {
13
- return aStart.getTime() < bEnd.getTime() && bStart.getTime() < aEnd.getTime();
15
+ const a0 = aStart.getTime();
16
+ const a1 = aEnd.getTime();
17
+ const b0 = bStart.getTime();
18
+ const b1 = bEnd.getTime();
19
+ if (a0 === a1) return b0 === b1 ? a0 === b0 : b0 <= a0 && a0 < b1;
20
+ if (b0 === b1) return a0 <= b0 && b0 < a1;
21
+ return a0 < b1 && b0 < a1;
14
22
  }
15
23
 
16
24
  /**
@@ -181,8 +189,8 @@ export function resolveDraggedBounds(
181
189
 
182
190
  /**
183
191
  * The all-day range swept out between two day cells of the month grid, ordered
184
- * whichever way the sweep ran: `start` is midnight of the first day and `end` is
185
- * midnight after the last, so a one-day sweep still yields a usable event. Shared
192
+ * whichever way the sweep ran: `start` is the first local day's start and `end` is
193
+ * the next day's start after the last, so a one-day sweep yields a usable event. Shared
186
194
  * by both renderers so a month drag-to-create means the same thing on each.
187
195
  */
188
196
  export function monthCreateRange(anchor: Date, hover: Date): { start: Date; end: Date } {
@@ -190,7 +198,7 @@ export function monthCreateRange(anchor: Date, hover: Date): { start: Date; end:
190
198
  const b = startOfDay(hover);
191
199
  const first = a.getTime() <= b.getTime() ? a : b;
192
200
  const last = a.getTime() <= b.getTime() ? b : a;
193
- return { start: first, end: addDays(last, 1) };
201
+ return { start: first, end: startOfDay(addDays(last, 1)) };
194
202
  }
195
203
 
196
204
  /**
@@ -90,6 +90,8 @@ function recurrenceFromJSON(value: unknown, field: string): RecurrenceRule {
90
90
  rule.weekdays = arrayFromJSON(input.weekdays, `${field}.weekdays`).map((day) =>
91
91
  weekdayFromJSON(day, `${field}.weekdays`),
92
92
  );
93
+ if (input.weekStartsOn !== undefined)
94
+ rule.weekStartsOn = weekdayFromJSON(input.weekStartsOn, `${field}.weekStartsOn`);
93
95
  if (input.months !== undefined)
94
96
  rule.months = arrayFromJSON(input.months, `${field}.months`).map((month) =>
95
97
  integerFromJSON(month, `${field}.months`, 1, 12),
package/src/utils/ical.ts CHANGED
@@ -188,6 +188,8 @@ function parseRRule(value: string): RecurrenceRule | undefined {
188
188
  }
189
189
  if (plain.length) rule.weekdays = plain;
190
190
  }
191
+ const wkst = BYDAY.indexOf(parts.get("WKST")?.trim().toUpperCase() as (typeof BYDAY)[number]);
192
+ if (wkst >= 0) rule.weekStartsOn = wkst as WeekStartsOn;
191
193
  const bymonthday = parts.get("BYMONTHDAY");
192
194
  if (bymonthday) {
193
195
  const days = bymonthday
@@ -217,6 +219,9 @@ function formatRRule(rule: RecurrenceRule): string {
217
219
  } else if (rule.weekdays?.length) {
218
220
  parts.push(`BYDAY=${rule.weekdays.map((d) => BYDAY[d]).join(",")}`);
219
221
  }
222
+ if (rule.weekStartsOn != null && BYDAY[rule.weekStartsOn]) {
223
+ parts.push(`WKST=${BYDAY[rule.weekStartsOn]}`);
224
+ }
220
225
  if (rule.monthDays?.length) parts.push(`BYMONTHDAY=${rule.monthDays.join(",")}`);
221
226
  if (rule.months?.length) parts.push(`BYMONTH=${rule.months.join(",")}`);
222
227
  return parts.join(";");
@@ -106,7 +106,14 @@ export function layoutDayEvents<T>(events: CalendarEvent<T>[], day: Date): Posit
106
106
  // paint as bands (see `backgroundBandsForDay`), not boxes.
107
107
  .filter((event) => !isAllDayEvent(event) && !isBackgroundEvent(event))
108
108
  // Overlaps this day if it starts before the day ends and ends after it begins.
109
- .filter((event) => event.start < nextDayStart && event.end > dayStart)
109
+ // A zero-length event occupies its own instant, so one at midnight belongs to
110
+ // the day it starts.
111
+ .filter(
112
+ (event) =>
113
+ event.start < nextDayStart &&
114
+ (event.end > dayStart ||
115
+ (event.end.getTime() === event.start.getTime() && event.start >= dayStart)),
116
+ )
110
117
  .map((event) => {
111
118
  const segStart = maxDate([event.start, dayStart]);
112
119
  const segEnd = minDate([event.end, nextDayStart]);
@@ -123,6 +130,11 @@ export function layoutDayEvents<T>(events: CalendarEvent<T>[], day: Date): Posit
123
130
  let cluster: Segment<T>[] = [];
124
131
  let clusterEnd = Number.NEGATIVE_INFINITY;
125
132
 
133
+ // Columns are packed by each segment's minimum box (see `durationHours`), so
134
+ // two short events whose minimum boxes would overlap sit side by side even
135
+ // when their times don't.
136
+ const drawnEndOf = (seg: Segment<T>) => Math.max(seg.end, seg.start + MIN_DURATION_HOURS);
137
+
126
138
  const flushCluster = () => {
127
139
  const columnEnds: number[] = [];
128
140
  const columnOf = new Map<Segment<T>, number>();
@@ -130,9 +142,9 @@ export function layoutDayEvents<T>(events: CalendarEvent<T>[], day: Date): Posit
130
142
  let column = columnEnds.findIndex((end) => end <= seg.start);
131
143
  if (column === -1) {
132
144
  column = columnEnds.length;
133
- columnEnds.push(seg.end);
145
+ columnEnds.push(drawnEndOf(seg));
134
146
  } else {
135
- columnEnds[column] = seg.end;
147
+ columnEnds[column] = drawnEndOf(seg);
136
148
  }
137
149
  columnOf.set(seg, column);
138
150
  }
@@ -153,7 +165,7 @@ export function layoutDayEvents<T>(events: CalendarEvent<T>[], day: Date): Posit
153
165
  for (const seg of segments) {
154
166
  if (cluster.length > 0 && seg.start >= clusterEnd) flushCluster();
155
167
  cluster.push(seg);
156
- clusterEnd = Math.max(clusterEnd, seg.end);
168
+ clusterEnd = Math.max(clusterEnd, drawnEndOf(seg));
157
169
  }
158
170
  if (cluster.length > 0) flushCluster();
159
171
 
@@ -189,7 +201,9 @@ export function eventDayKeys<T>(event: CalendarEvent<T>): string[] {
189
201
  const last = startOfDay(lastInstant);
190
202
 
191
203
  const keys: string[] = [];
192
- for (let cursor = first; cursor <= last; cursor = addDays(cursor, 1)) {
204
+ // Midnight can normalize to 01:00 on a clock change. Reset each subsequent
205
+ // day so its index still matches startOfDay(date).
206
+ for (let cursor = first; cursor <= last; cursor = startOfDay(addDays(cursor, 1))) {
193
207
  keys.push(cursor.toISOString());
194
208
  }
195
209
  return keys;
@@ -2,6 +2,7 @@ import { format, type Locale, isSameMonth, startOfDay } from "date-fns";
2
2
  import type { CalendarEvent, WeekStartsOn } from "../types";
3
3
  import { type DateRange, type DateSelectionConstraints, daySelectionState } from "./dateRange";
4
4
  import { buildMonthWeeks, getIsToday, isWeekend } from "./dates";
5
+ import { compareDayEvents, eventDayKeys } from "./layout";
5
6
 
6
7
  /**
7
8
  * One event's placement within a single week row of the month grid: the column
@@ -112,6 +113,133 @@ export function layoutMonthWeek<T>(
112
113
  return { segments: placed, laneCount: laneEnds.length };
113
114
  }
114
115
 
116
+ /**
117
+ * The columns of a week row that show one lane more than the row. A row whose
118
+ * lanes overflow shows `visibleLanes` of them and folds each day's rest into a
119
+ * "+N more" label. A day whose only hidden event sits on lane `visibleLanes` draws
120
+ * that event in the label's place instead of "+1 more". Call it only when
121
+ * a bar on lane `visibleLanes` fits in the cell.
122
+ */
123
+ export function monthExtraLaneColumns<T>(
124
+ layout: MonthWeekEvents<T>,
125
+ visibleLanes: number,
126
+ columnCount: number,
127
+ ): boolean[] {
128
+ const hidden = Array.from({ length: columnCount }, () => 0);
129
+ const onFirstHiddenLane = Array.from({ length: columnCount }, () => false);
130
+ for (const segment of layout.segments) {
131
+ if (segment.lane < visibleLanes) continue;
132
+ for (let col = segment.startCol; col <= segment.endCol; col++) {
133
+ hidden[col]++;
134
+ if (segment.lane === visibleLanes) onFirstHiddenLane[col] = true;
135
+ }
136
+ }
137
+ return hidden.map((count, col) => count === 1 && onFirstHiddenLane[col]);
138
+ }
139
+
140
+ /**
141
+ * The bars a week row draws: every segment above `visibleLanes`, plus the parts of
142
+ * a segment on lane `visibleLanes` that cross `extraLane` columns (see
143
+ * {@link monthExtraLaneColumns}), one bar per run of such columns. A bar cut short
144
+ * by a column that hides the event is marked as continuing past that edge.
145
+ */
146
+ export function monthVisibleBars<T>(
147
+ layout: MonthWeekEvents<T>,
148
+ visibleLanes: number,
149
+ extraLane: readonly boolean[],
150
+ ): MonthEventSegment<T>[] {
151
+ const bars: MonthEventSegment<T>[] = [];
152
+ for (const segment of layout.segments) {
153
+ if (segment.lane < visibleLanes) {
154
+ bars.push(segment);
155
+ continue;
156
+ }
157
+ if (segment.lane !== visibleLanes) continue;
158
+ let runStart = -1;
159
+ for (let col = segment.startCol; col <= segment.endCol + 1; col++) {
160
+ const shown = col <= segment.endCol && extraLane[col] === true;
161
+ if (shown && runStart === -1) runStart = col;
162
+ if (!shown && runStart !== -1) {
163
+ bars.push({
164
+ ...segment,
165
+ startCol: runStart,
166
+ endCol: col - 1,
167
+ continuesBefore: segment.continuesBefore || runStart > segment.startCol,
168
+ continuesAfter: segment.continuesAfter || col - 1 < segment.endCol,
169
+ });
170
+ runStart = -1;
171
+ }
172
+ }
173
+ }
174
+ return bars;
175
+ }
176
+
177
+ /**
178
+ * `eventsByDay` with a create draft added to every day it covers, where an event
179
+ * appended to the calendar's events would go: last in each day, or among the
180
+ * day's events in `compareDayEvents` order when `sorted`. Lay a week row out
181
+ * from the result to place the draft where the created event will land.
182
+ */
183
+ export function withDraftEventDays<T>(
184
+ eventsByDay: ReadonlyMap<string, CalendarEvent<T>[]>,
185
+ draft: CalendarEvent<T>,
186
+ sorted = true,
187
+ ): Map<string, CalendarEvent<T>[]> {
188
+ const days = new Map(eventsByDay);
189
+ for (const key of eventDayKeys(draft)) {
190
+ const list = [...(days.get(key) ?? []), draft];
191
+ // Array sort is stable, so the draft stays after the events it ties with.
192
+ if (sorted) list.sort(compareDayEvents);
193
+ days.set(key, list);
194
+ }
195
+ return days;
196
+ }
197
+
198
+ /** How a renderer shows a week row's lanes, for {@link keepMonthDraftVisible}. */
199
+ export interface MonthRowLanes {
200
+ /** Lanes every day of a row with `laneCount` lanes shows. */
201
+ visibleLanes: (laneCount: number) => number;
202
+ /**
203
+ * Whether a day may draw lane `visibleLanes` in place of its "+N more" label
204
+ * (see {@link monthExtraLaneColumns}). Omit when the renderer never does.
205
+ */
206
+ extraLaneFits?: (visibleLanes: number) => boolean;
207
+ }
208
+
209
+ /**
210
+ * A week row's layout with a create draft kept in view. `withDraft` lays the row
211
+ * out with the draft where the created event will land. When the row would hide
212
+ * that lane, the draft moves to lane 0 instead and the row's other bars
213
+ * (`withoutDraft`) move down one lane. A draft on the first hidden lane stays put
214
+ * when every day it covers draws that lane in place of its label. A row the draft
215
+ * misses comes back as `withDraft`.
216
+ */
217
+ export function keepMonthDraftVisible<T>(
218
+ withDraft: MonthWeekEvents<T>,
219
+ withoutDraft: MonthWeekEvents<T>,
220
+ draft: CalendarEvent<T>,
221
+ { visibleLanes, extraLaneFits }: MonthRowLanes,
222
+ ): MonthWeekEvents<T> {
223
+ const segment = withDraft.segments.find((s) => s.event === draft);
224
+ if (!segment) return withDraft;
225
+ const shown = visibleLanes(withDraft.laneCount);
226
+ if (segment.lane < shown) return withDraft;
227
+ if (segment.lane === shown && extraLaneFits?.(shown)) {
228
+ const columns = Math.max(...withDraft.segments.map((s) => s.endCol)) + 1;
229
+ const extraLane = monthExtraLaneColumns(withDraft, shown, columns);
230
+ let drawn = true;
231
+ for (let col = segment.startCol; col <= segment.endCol; col++) drawn &&= extraLane[col];
232
+ if (drawn) return withDraft;
233
+ }
234
+ return {
235
+ segments: [
236
+ { ...segment, lane: 0 },
237
+ ...withoutDraft.segments.map((s) => ({ ...s, lane: s.lane + 1 })),
238
+ ],
239
+ laneCount: withoutDraft.laneCount + 1,
240
+ };
241
+ }
242
+
115
243
  /** A single day in the grid, with all the state a custom cell needs to render. */
116
244
  export interface MonthGridDay {
117
245
  /** The day this cell represents. */
@@ -202,6 +330,11 @@ export interface UseMonthGridOptions extends DateSelectionConstraints {
202
330
  selectedRange?: DateRange;
203
331
  /** A date-fns locale for the weekday labels. */
204
332
  locale?: Locale;
333
+ /**
334
+ * The calendar day flagged `isToday`. Defaults to the device's current day;
335
+ * pass `nowInTimeZone(now, timeZone)` for a grid shown in another time zone.
336
+ */
337
+ today?: Date;
205
338
  }
206
339
 
207
340
  /**
@@ -222,6 +355,7 @@ export function buildMonthGrid(month: Date, options: UseMonthGridOptions = {}):
222
355
  maxDate,
223
356
  isDateDisabled,
224
357
  locale,
358
+ today,
225
359
  } = options;
226
360
 
227
361
  const rows = buildMonthWeeks(month, weekStartsOn, { showSixWeeks, isRTL, hiddenDays });
@@ -233,7 +367,7 @@ export function buildMonthGrid(month: Date, options: UseMonthGridOptions = {}):
233
367
  id: format(date, "yyyy-MM-dd"),
234
368
  label: format(date, "d"),
235
369
  isCurrentMonth: isSameMonth(date, month),
236
- isToday: getIsToday(date),
370
+ isToday: getIsToday(date, today),
237
371
  isWeekend: isWeekend(date),
238
372
  // Shared with MonthView, so the headless grid matches the built-in view.
239
373
  ...daySelectionState(
@@ -76,6 +76,7 @@ export function buildMultiWeekGrid(date: Date, options: MultiWeekGridOptions = {
76
76
  maxDate,
77
77
  isDateDisabled,
78
78
  locale,
79
+ today,
79
80
  } = options;
80
81
 
81
82
  if (!(date instanceof Date) || Number.isNaN(date.getTime())) {
@@ -114,7 +115,7 @@ export function buildMultiWeekGrid(date: Date, options: MultiWeekGridOptions = {
114
115
  date: day,
115
116
  id: format(day, "yyyy-MM-dd"),
116
117
  label: format(day, "d"),
117
- isToday: getIsToday(day),
118
+ isToday: getIsToday(day, today),
118
119
  isWeekend: isWeekend(day),
119
120
  ...daySelectionState(day, selection, constraints),
120
121
  })),