@super-calendar/native 2.8.2 → 2.9.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.
@@ -1,7 +1,8 @@
1
1
  import { format, startOfDay, type Locale } from "date-fns";
2
- import { memo, type ReactElement, useMemo, useState } from "react";
2
+ import { memo, type ReactElement, useCallback, useEffect, useMemo, useRef, useState } from "react";
3
3
  import {
4
4
  type LayoutChangeEvent,
5
+ Platform,
5
6
  Pressable,
6
7
  ScrollView,
7
8
  StyleSheet,
@@ -9,24 +10,38 @@ import {
9
10
  type TextStyle,
10
11
  View,
11
12
  } from "react-native";
13
+ import { Gesture, GestureDetector, type PanGesture } from "react-native-gesture-handler";
12
14
  import { useCalendarTheme } from "../theme";
13
15
  import type { CalendarEvent, WeekStartsOn } from "../types";
14
16
  import { createSlots, type SlotStyleProps } from "../utils/slots";
15
17
  import {
18
+ bandRounding,
16
19
  buildMonthWeeks,
20
+ type DateRange,
21
+ dayBadgeKind,
22
+ monthCreateRange,
23
+ daySelectionState,
17
24
  getIsToday,
18
25
  filterHiddenDays,
19
26
  getWeekDays,
20
27
  getYearMonths,
21
28
  groupEventsByDay,
22
29
  isBackgroundEvent,
30
+ isDateSelectable,
23
31
  isSameCalendarDay,
32
+ rangeBandKind,
24
33
  weekdayFormatToken,
25
34
  } from "@super-calendar/core";
26
35
 
36
+ const isWeb = Platform.OS === "web";
37
+ // Hold before a year-grid drag takes over, so a tap still opens the day.
38
+ const DRAG_HOLD_MS = 400;
39
+
27
40
  /**
28
41
  * The styleable parts of {@link YearView}. `dayText` and `eventDot` are the
29
- * text/marker inside a day cell (React Native text colour doesn't inherit).
42
+ * text/marker inside a day cell (React Native text colour doesn't inherit);
43
+ * `dayBadge` is the round highlight behind the number and `rangeBand` the
44
+ * selection strip behind it.
30
45
  */
31
46
  export type YearViewSlot =
32
47
  | "grid"
@@ -36,7 +51,9 @@ export type YearViewSlot =
36
51
  | "weekday"
37
52
  | "week"
38
53
  | "day"
54
+ | "dayBadge"
39
55
  | "dayText"
56
+ | "rangeBand"
40
57
  | "eventDot";
41
58
 
42
59
  /** Props for {@link YearView}, the twelve mini-month year grid. */
@@ -51,6 +68,16 @@ export type YearViewProps<T = unknown> = SlotStyleProps<YearViewSlot> & {
51
68
  locale?: Locale;
52
69
  /** Highlight this date instead of the real "today". */
53
70
  activeDate?: Date;
71
+ /** A selected span: endpoints get a filled badge, the days between get the range band. */
72
+ selectedRange?: DateRange;
73
+ /** Discrete selected days, drawn with a filled badge. */
74
+ selectedDates?: Date[];
75
+ /** Earliest selectable day (inclusive); earlier days render disabled. */
76
+ minDate?: Date;
77
+ /** Latest selectable day (inclusive); later days render disabled. */
78
+ maxDate?: Date;
79
+ /** Return true to render a specific day disabled (dimmed, taps ignored). */
80
+ isDateDisabled?: (date: Date) => boolean;
54
81
  /**
55
82
  * Smallest width a mini month may take before the grid drops a column
56
83
  * (default 150). The grid fits 2–4 columns from the measured width.
@@ -60,6 +87,22 @@ export type YearViewProps<T = unknown> = SlotStyleProps<YearViewSlot> & {
60
87
  onPressDay?: (date: Date) => void;
61
88
  /** Tap a month's title (e.g. to jump to that month's view). */
62
89
  onPressMonth?: (month: Date) => void;
90
+ /**
91
+ * Enables drag-to-select and reports the swept span live, as the ordered
92
+ * inclusive `[start, end]` days (both at midnight). Pair it with
93
+ * `useDateRange`'s `selectRange` to drive `selectedRange`. Fires on every day the
94
+ * drag crosses, so the highlight follows it; `onCreateEvent` (when also set)
95
+ * fires once on release. Either handler enables the same sweep: hold a day and
96
+ * drag on a device, press and drag on the web. On a device a sweep stays inside
97
+ * the mini month it started in; on the web it can run across months.
98
+ */
99
+ onSelectDrag?: (start: Date, end: Date) => void;
100
+ /**
101
+ * Enables drag-to-create: sweep across days and release to fire this with the
102
+ * all-day range (`start` at midnight of the first day, `end` at midnight after
103
+ * the last, exclusive). A plain tap still fires `onPressDay`, not this.
104
+ */
105
+ onCreateEvent?: (start: Date, end: Date) => void;
63
106
  };
64
107
 
65
108
  // Seed before the first layout pass so the grid renders immediately (and in
@@ -73,9 +116,16 @@ function YearViewInner<T>({
73
116
  hiddenDays,
74
117
  locale,
75
118
  activeDate,
119
+ selectedRange,
120
+ selectedDates,
121
+ minDate,
122
+ maxDate,
123
+ isDateDisabled,
76
124
  minMonthWidth = 150,
77
125
  onPressDay,
78
126
  onPressMonth,
127
+ onSelectDrag,
128
+ onCreateEvent,
79
129
  classNames,
80
130
  styles: styleOverrides,
81
131
  }: YearViewProps<T>): ReactElement {
@@ -90,6 +140,12 @@ function YearViewInner<T>({
90
140
  };
91
141
 
92
142
  const months = useMemo(() => getYearMonths(date), [date]);
143
+ // Each mini month's week rows, built once per year rather than per render, so
144
+ // the drag hit-test (and the pan it is built into) keeps a stable identity.
145
+ const monthWeeks = useMemo(
146
+ () => months.map((month) => buildMonthWeeks(month, weekStartsOn, { hiddenDays })),
147
+ [months, weekStartsOn, hiddenDays],
148
+ );
93
149
  // Weekday initials for one shared header per mini month.
94
150
  const weekdayLabels = useMemo(
95
151
  () =>
@@ -109,11 +165,89 @@ function YearViewInner<T>({
109
165
  [events],
110
166
  );
111
167
 
168
+ // ---- drag-to-select / create ---------------------------------------------
169
+ // One sweep gesture, reported live through `onSelectDrag` and committed to
170
+ // `onCreateEvent`. Native runs a pan over each mini month's grid (so a hold and
171
+ // drag sweeps its days); the web drives it from the cells' own pointer events,
172
+ // which lets a sweep run across mini months.
173
+ const sweepEnabled = onSelectDrag != null || onCreateEvent != null;
174
+ const [sweep, setSweep] = useState<{ anchor: number; hover: number } | null>(null);
175
+ const sweepRef = useRef(sweep);
176
+ sweepRef.current = sweep;
177
+ const movedRef = useRef(false);
178
+ // Web only: a committed sweep has to swallow the click the browser fires next,
179
+ // so it doesn't also open the day it landed on. A pan never leaves a press
180
+ // behind, so the flag would otherwise outlive its interaction and eat the next
181
+ // unrelated tap; every fresh sweep clears it. Mirrors MonthView.
182
+ const suppressPressRef = useRef(false);
183
+
184
+ const isSelectable = useCallback(
185
+ (day: Date) => isDateSelectable(day, { minDate, maxDate, isDateDisabled }),
186
+ [minDate, maxDate, isDateDisabled],
187
+ );
188
+ const beginSweep = useCallback((day: Date) => {
189
+ const time = startOfDay(day).getTime();
190
+ suppressPressRef.current = false;
191
+ movedRef.current = false;
192
+ setSweep({ anchor: time, hover: time });
193
+ }, []);
194
+ const extendSweep = useCallback(
195
+ (day: Date) => {
196
+ const current = sweepRef.current;
197
+ if (!current || !isSelectable(day)) return;
198
+ const time = startOfDay(day).getTime();
199
+ if (time === current.hover) return;
200
+ movedRef.current = true;
201
+ setSweep((c) => (c ? { ...c, hover: time } : c));
202
+ const [lo, hi] = current.anchor <= time ? [current.anchor, time] : [time, current.anchor];
203
+ onSelectDrag?.(new Date(lo), new Date(hi));
204
+ },
205
+ [isSelectable, onSelectDrag],
206
+ );
207
+ const finishSweep = useCallback(() => {
208
+ const current = sweepRef.current;
209
+ setSweep(null);
210
+ if (!current || !movedRef.current) return;
211
+ if (isWeb) suppressPressRef.current = true;
212
+ const range = monthCreateRange(new Date(current.anchor), new Date(current.hover));
213
+ onCreateEvent?.(range.start, range.end);
214
+ }, [onCreateEvent]);
215
+
216
+ // Web: a released pointer ends the sweep wherever it lands.
217
+ useEffect(() => {
218
+ if (!isWeb || !sweepEnabled) return;
219
+ const target = globalThis as unknown as {
220
+ addEventListener?: (type: string, cb: () => void) => void;
221
+ removeEventListener?: (type: string, cb: () => void) => void;
222
+ };
223
+ target.addEventListener?.("pointerup", finishSweep);
224
+ return () => target.removeEventListener?.("pointerup", finishSweep);
225
+ }, [sweepEnabled, finishSweep]);
226
+
227
+ // Swallow the click trailing a committed web sweep, so it doesn't open a day too.
228
+ const pressDay = useCallback(
229
+ (day: Date) => {
230
+ if (suppressPressRef.current) {
231
+ suppressPressRef.current = false;
232
+ return;
233
+ }
234
+ onPressDay?.(day);
235
+ },
236
+ [onPressDay],
237
+ );
238
+
112
239
  return (
113
- <ScrollView onLayout={handleLayout} showsVerticalScrollIndicator>
240
+ <ScrollView
241
+ onLayout={handleLayout}
242
+ showsVerticalScrollIndicator
243
+ // Native only: once the hold has armed a sweep, stop the list scrolling
244
+ // under the finger. On the web a press arms it immediately, so freezing
245
+ // there would cost every touch scroll; the browser arbitrates instead.
246
+ scrollEnabled={isWeb || sweep == null}
247
+ >
114
248
  <View {...slot("grid", { base: styles.grid })}>
115
- {months.map((month) => {
116
- const weeks = buildMonthWeeks(month, weekStartsOn, { hiddenDays });
249
+ {months.map((month, monthIndex) => {
250
+ const weeks = monthWeeks[monthIndex];
117
251
  const title = format(month, "MMMM", { locale });
118
252
  const monthLabel = format(month, "MMMM yyyy", { locale });
119
253
  const titleText = (
@@ -166,82 +300,153 @@ function YearViewInner<T>({
166
300
  </Text>
167
301
  ))}
168
302
  </View>
169
- {weeks.map((week) => (
170
- <View key={week[0].toISOString()} {...slot("week", { base: styles.week })}>
171
- {week.map((day) => {
172
- // Adjacent-month days keep the grid shape but stay blank,
173
- // like the mini months of other year views.
174
- if (day.getMonth() !== month.getMonth()) {
175
- return <View key={day.toISOString()} style={styles.day} />;
176
- }
177
- const isHighlighted = activeDate
178
- ? isSameCalendarDay(day, activeDate)
179
- : getIsToday(day);
180
- const hasEvents = eventDays.has(startOfDay(day).toISOString());
181
- const label = `${format(day, "EEEE, d LLLL yyyy", { locale })}${
182
- getIsToday(day) ? ", today" : ""
183
- }${hasEvents ? ", has events" : ""}`;
184
- const daySlot = slot("day", {
185
- base: styles.day,
186
- themed: isHighlighted
187
- ? {
188
- backgroundColor: theme.colors.todayBackground,
189
- borderRadius: theme.todayBadgeRadius,
190
- }
191
- : undefined,
192
- });
193
- const content = (
194
- <>
195
- <Text
196
- {...slot<TextStyle>("dayText", {
197
- themed: [
198
- styles.dayText,
199
- {
200
- color: isHighlighted ? theme.colors.todayText : theme.colors.text,
201
- },
202
- ],
203
- })}
204
- allowFontScaling={false}
205
- >
206
- {day.getDate()}
207
- </Text>
208
- {hasEvents ? (
303
+ <MiniMonthGrid
304
+ testID={`year-month-grid-${month.getMonth()}`}
305
+ month={month}
306
+ weeks={weeks}
307
+ sweepEnabled={sweepEnabled && !isWeb}
308
+ isSelectable={isSelectable}
309
+ onBeginSweep={beginSweep}
310
+ onExtendSweep={extendSweep}
311
+ onFinishSweep={finishSweep}
312
+ >
313
+ {weeks.map((week) => (
314
+ <View key={week[0].toISOString()} {...slot("week", { base: styles.week })}>
315
+ {week.map((day) => {
316
+ // Adjacent-month days keep the grid shape but stay blank,
317
+ // like the mini months of other year views.
318
+ if (day.getMonth() !== month.getMonth()) {
319
+ return <View key={day.toISOString()} style={styles.day} />;
320
+ }
321
+ const isToday = getIsToday(day);
322
+ const isHighlighted = activeDate
323
+ ? isSameCalendarDay(day, activeDate)
324
+ : isToday;
325
+ const hasEvents = eventDays.has(startOfDay(day).toISOString());
326
+ // Selection/disabled flags come from core, so the year grid
327
+ // can't disagree with the month grid about a day's state.
328
+ const state = daySelectionState(
329
+ day,
330
+ { selectedDates, selectedRange },
331
+ { minDate, maxDate, isDateDisabled },
332
+ );
333
+ const dayTime = startOfDay(day).getTime();
334
+ const inSweep =
335
+ sweep != null &&
336
+ dayTime >= Math.min(sweep.anchor, sweep.hover) &&
337
+ dayTime <= Math.max(sweep.anchor, sweep.hover);
338
+ const label = `${format(day, "EEEE, d LLLL yyyy", { locale })}${
339
+ isToday ? ", today" : ""
340
+ }${state.isSelected ? ", selected" : ""}${
341
+ state.isDisabled ? ", unavailable" : ""
342
+ }${hasEvents ? ", has events" : ""}`;
343
+ // Today wins over a selection, matching the month grid.
344
+ const badge = dayBadgeKind(state, isHighlighted);
345
+ const daySlot = slot("day", { base: styles.day });
346
+ // The range draws as a band behind the badges. The mini cells
347
+ // sit flush in the row, so per-cell segments read as one strip;
348
+ // only the endpoints round their outer edge.
349
+ const showBand = rangeBandKind(state, true) !== "none";
350
+ const rounding = bandRounding(rangeBandKind(state, false));
351
+ const content = (
352
+ <>
353
+ {showBand || inSweep ? (
354
+ <View
355
+ {...slot("rangeBand", {
356
+ base: [
357
+ styles.rangeBand,
358
+ rounding.start && styles.rangeBandStart,
359
+ rounding.end && styles.rangeBandEnd,
360
+ ],
361
+ themed: { backgroundColor: theme.colors.rangeBackground },
362
+ })}
363
+ />
364
+ ) : null}
209
365
  <View
210
- {...slot("eventDot", {
211
- base: styles.eventDot,
212
- themed: {
213
- backgroundColor: isHighlighted
214
- ? theme.colors.todayText
215
- : theme.colors.todayBackground,
216
- },
366
+ {...slot("dayBadge", {
367
+ base: styles.dayBadge,
368
+ themed:
369
+ badge === "none"
370
+ ? undefined
371
+ : {
372
+ backgroundColor:
373
+ badge === "today"
374
+ ? theme.colors.todayBackground
375
+ : theme.colors.selectedBackground,
376
+ borderRadius: theme.todayBadgeRadius,
377
+ },
217
378
  })}
218
- />
219
- ) : null}
220
- </>
221
- );
222
- return onPressDay ? (
223
- <Pressable
224
- key={day.toISOString()}
225
- onPress={() => onPressDay(day)}
226
- accessibilityRole="button"
227
- accessibilityLabel={label}
228
- {...daySlot}
229
- >
230
- {content}
231
- </Pressable>
232
- ) : (
233
- <View
234
- key={day.toISOString()}
235
- accessible
236
- accessibilityLabel={label}
237
- {...daySlot}
238
- >
239
- {content}
240
- </View>
241
- );
242
- })}
243
- </View>
244
- ))}
379
+ >
380
+ <Text
381
+ {...slot<TextStyle>("dayText", {
382
+ themed: [
383
+ styles.dayText,
384
+ {
385
+ color: state.isDisabled
386
+ ? theme.colors.textDisabled
387
+ : badge === "today"
388
+ ? theme.colors.todayText
389
+ : badge === "selected"
390
+ ? theme.colors.selectedText
391
+ : theme.colors.text,
392
+ },
393
+ ],
394
+ })}
395
+ allowFontScaling={false}
396
+ >
397
+ {day.getDate()}
398
+ </Text>
399
+ </View>
400
+ {hasEvents ? (
401
+ <View
402
+ {...slot("eventDot", {
403
+ base: styles.eventDot,
404
+ themed: {
405
+ backgroundColor:
406
+ badge === "none"
407
+ ? theme.colors.todayBackground
408
+ : theme.colors.todayText,
409
+ },
410
+ })}
411
+ />
412
+ ) : null}
413
+ </>
414
+ );
415
+ return onPressDay || sweepEnabled ? (
416
+ <Pressable
417
+ key={day.toISOString()}
418
+ onPress={() => pressDay(day)}
419
+ disabled={state.isDisabled}
420
+ accessibilityRole="button"
421
+ accessibilityLabel={label}
422
+ // Web only: the cells drive the sweep themselves, since a
423
+ // pan can't reach past the pressables there.
424
+ {...(isWeb && sweepEnabled
425
+ ? {
426
+ onPointerDown: () => {
427
+ if (isSelectable(day)) beginSweep(day);
428
+ },
429
+ onPointerEnter: () => extendSweep(day),
430
+ }
431
+ : null)}
432
+ {...daySlot}
433
+ >
434
+ {content}
435
+ </Pressable>
436
+ ) : (
437
+ <View
438
+ key={day.toISOString()}
439
+ accessible
440
+ accessibilityLabel={label}
441
+ {...daySlot}
442
+ >
443
+ {content}
444
+ </View>
445
+ );
446
+ })}
447
+ </View>
448
+ ))}
449
+ </MiniMonthGrid>
245
450
  </View>
246
451
  );
247
452
  })}
@@ -250,11 +455,84 @@ function YearViewInner<T>({
250
455
  );
251
456
  }
252
457
 
458
+ // One mini month's week rows, wrapped in a pan when drag-to-select is on. The
459
+ // gesture is bound per month (rather than to the whole year) because that keeps
460
+ // the hit-test to a single measured box, so a sweep runs across the days of the
461
+ // month it started in.
462
+ function MiniMonthGrid({
463
+ testID,
464
+ month,
465
+ weeks,
466
+ sweepEnabled,
467
+ isSelectable,
468
+ onBeginSweep,
469
+ onExtendSweep,
470
+ onFinishSweep,
471
+ children,
472
+ }: {
473
+ testID: string;
474
+ month: Date;
475
+ weeks: Date[][];
476
+ sweepEnabled: boolean;
477
+ isSelectable: (day: Date) => boolean;
478
+ onBeginSweep: (day: Date) => void;
479
+ onExtendSweep: (day: Date) => void;
480
+ onFinishSweep: () => void;
481
+ children: React.ReactNode;
482
+ }) {
483
+ const sizeRef = useRef({ width: 0, height: 0 });
484
+ const onLayout = useCallback((event: LayoutChangeEvent) => {
485
+ const { width, height } = event.nativeEvent.layout;
486
+ sizeRef.current = { width, height };
487
+ }, []);
488
+ // The gesture reads its inputs from here rather than closing over them, so a
489
+ // consumer's inline handler (or the re-render each swept day causes) can't
490
+ // rebuild the pan and cancel the drag that is running through it.
491
+ const latest = useRef({ month, weeks, isSelectable, onBeginSweep, onExtendSweep, onFinishSweep });
492
+ latest.current = { month, weeks, isSelectable, onBeginSweep, onExtendSweep, onFinishSweep };
493
+ // The day under a grid-relative point, or null for a point on a blanked
494
+ // adjacent-month cell or an unselectable day: neither can anchor a sweep or
495
+ // be swept onto. Mirrors MonthView's `hitTest`.
496
+ const dayAt = useCallback((x: number, y: number): Date | null => {
497
+ const { width, height } = sizeRef.current;
498
+ const { month: current, weeks: rows, isSelectable: selectable } = latest.current;
499
+ if (width <= 0 || height <= 0 || rows.length === 0) return null;
500
+ const row = Math.min(rows.length - 1, Math.max(0, Math.floor(y / (height / rows.length))));
501
+ const cols = rows[row].length;
502
+ const col = Math.min(cols - 1, Math.max(0, Math.floor(x / (width / cols))));
503
+ const day = rows[row][col];
504
+ if (!day) return null;
505
+ if (day.getMonth() !== current.getMonth()) return null;
506
+ return selectable(day) ? day : null;
507
+ }, []);
508
+ const gesture = useMemo<PanGesture | undefined>(() => {
509
+ if (!sweepEnabled) return undefined;
510
+ return Gesture.Pan()
511
+ .activateAfterLongPress(DRAG_HOLD_MS)
512
+ .runOnJS(true)
513
+ .onStart((event) => {
514
+ const day = dayAt(event.x, event.y);
515
+ if (day) latest.current.onBeginSweep(day);
516
+ })
517
+ .onUpdate((event) => {
518
+ const day = dayAt(event.x, event.y);
519
+ if (day) latest.current.onExtendSweep(day);
520
+ })
521
+ .onFinalize(() => latest.current.onFinishSweep());
522
+ }, [sweepEnabled, dayAt]);
523
+ const grid = (
524
+ <View testID={testID} onLayout={onLayout}>
525
+ {children}
526
+ </View>
527
+ );
528
+ return gesture ? <GestureDetector gesture={gesture}>{grid}</GestureDetector> : grid;
529
+ }
530
+
253
531
  /**
254
532
  * A year at a glance: the twelve months as compact mini grids, with today
255
533
  * highlighted and a dot under days that hold events. Tap a day or a month
256
- * title to drill into a denser view. It's the view `Calendar` renders for
257
- * `mode="year"`.
534
+ * title to drill into a denser view, or hold and drag to sweep out a date
535
+ * range. It's the view `Calendar` renders for `mode="year"`.
258
536
  *
259
537
  * @example
260
538
  * ```tsx
@@ -282,6 +560,15 @@ const styles = StyleSheet.create({
282
560
  weekdayText: { fontSize: 9, fontWeight: "600" },
283
561
  week: { flexDirection: "row" },
284
562
  day: { flex: 1, aspectRatio: 1, alignItems: "center", justifyContent: "center" },
563
+ dayBadge: {
564
+ width: "100%",
565
+ height: "100%",
566
+ alignItems: "center",
567
+ justifyContent: "center",
568
+ },
285
569
  dayText: { fontSize: 11 },
570
+ rangeBand: { position: "absolute", top: 0, bottom: 0, left: 0, right: 0 },
571
+ rangeBandStart: { borderTopLeftRadius: 999, borderBottomLeftRadius: 999 },
572
+ rangeBandEnd: { borderTopRightRadius: 999, borderBottomRightRadius: 999 },
286
573
  eventDot: { position: "absolute", bottom: 1, width: 3, height: 3, borderRadius: 2 },
287
574
  });
package/src/types.ts CHANGED
@@ -26,6 +26,25 @@ export type {
26
26
  WeekStartsOn,
27
27
  } from "@super-calendar/core";
28
28
 
29
+ /**
30
+ * Called when an event is dragged (moved or resized) to new start/end times.
31
+ * Return `false` to reject the drop — the event snaps back to where it started
32
+ * (e.g. to forbid overlaps or out-of-bounds slots). Any other return accepts it.
33
+ */
34
+ export type EventDragHandler<T> = (
35
+ event: CalendarEvent<T>,
36
+ start: Date,
37
+ end: Date,
38
+ ) => void | boolean;
39
+
40
+ /**
41
+ * Called when a move or resize gesture begins, before any change is committed:
42
+ * on grab for a move (after the long-press), and when the resize drag starts.
43
+ * Handy for haptic feedback (e.g. `expo-haptics`). Requires drag to be enabled
44
+ * via `onDragEvent`.
45
+ */
46
+ export type EventDragStartHandler<T> = (event: CalendarEvent<T>) => void;
47
+
29
48
  // The React Native render contract lives here, not in core: it references
30
49
  // Reanimated (`SharedValue`) and React Native (`ViewStyle`) types, which must
31
50
  // not leak into the platform-free core.