@super-calendar/dom 2.8.2 → 2.9.1

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.
package/src/YearView.tsx CHANGED
@@ -1,9 +1,15 @@
1
1
  import { format, startOfDay, type Locale } from "date-fns";
2
- import type { CSSProperties, ReactElement } from "react";
3
- import { useMemo } from "react";
2
+ import type { CSSProperties, PointerEvent as ReactPointerEvent, ReactElement } from "react";
3
+ import { useEffect, useMemo, useRef, useState } from "react";
4
4
  import {
5
+ bandRounding,
5
6
  buildMonthWeeks,
6
7
  type CalendarEvent,
8
+ type DateRange,
9
+ type DateSelectionConstraints,
10
+ dayBadgeKind,
11
+ monthCreateRange,
12
+ daySelectionState,
7
13
  getIsToday,
8
14
  filterHiddenDays,
9
15
  getWeekDays,
@@ -11,6 +17,7 @@ import {
11
17
  groupEventsByDay,
12
18
  isBackgroundEvent,
13
19
  isSameCalendarDay,
20
+ rangeBandKind,
14
21
  type WeekStartsOn,
15
22
  weekdayFormatToken,
16
23
  } from "@super-calendar/core";
@@ -19,8 +26,9 @@ import { type DomCalendarTheme, mergeDomTheme } from "./theme";
19
26
 
20
27
  /**
21
28
  * Styleable parts of {@link YearView}. Pass a class or inline style per slot
22
- * via the `classNames` / `styles` props; day cells carry `data-today` and
23
- * `data-events` state attributes for variants.
29
+ * via the `classNames` / `styles` props; day cells carry `data-today`,
30
+ * `data-events`, `data-selected`, `data-range`, `data-disabled` and
31
+ * `data-creating` state attributes for variants.
24
32
  */
25
33
  export type YearViewSlot =
26
34
  | "grid"
@@ -30,10 +38,13 @@ export type YearViewSlot =
30
38
  | "weekday"
31
39
  | "week"
32
40
  | "day"
41
+ | "dayBadge"
42
+ | "rangeBand"
33
43
  | "eventDot";
34
44
 
35
45
  /** Props for {@link YearView}, the twelve mini-month year grid. */
36
- export interface YearViewProps<T = unknown> extends SlotStyleProps<YearViewSlot> {
46
+ export interface YearViewProps<T = unknown>
47
+ extends DateSelectionConstraints, SlotStyleProps<YearViewSlot> {
37
48
  /** Any date inside the year to render. */
38
49
  date: Date;
39
50
  /** Days holding at least one event get a dot. Omit for a plain year. */
@@ -45,6 +56,10 @@ export interface YearViewProps<T = unknown> extends SlotStyleProps<YearViewSlot>
45
56
  locale?: Locale;
46
57
  /** Highlight this date instead of the real "today". */
47
58
  activeDate?: Date;
59
+ /** A selected span: endpoints get a filled badge, the days between get the range band. */
60
+ selectedRange?: DateRange;
61
+ /** Discrete selected days, drawn with a filled badge. */
62
+ selectedDates?: Date[];
48
63
  /**
49
64
  * Smallest width a mini month may take before the grid drops a column
50
65
  * (default 150). The grid fits as many columns as the container allows.
@@ -54,6 +69,22 @@ export interface YearViewProps<T = unknown> extends SlotStyleProps<YearViewSlot>
54
69
  onPressDay?: (date: Date) => void;
55
70
  /** Tap a month's title (e.g. to jump to that month's view). */
56
71
  onPressMonth?: (month: Date) => void;
72
+ /**
73
+ * Enables drag-to-select and reports the swept span live, as the ordered
74
+ * inclusive `[start, end]` days (both at midnight). Pair it with
75
+ * `useDateRange`'s `selectRange` to drive `selectedRange`. Fires on every day the
76
+ * pointer crosses, so the highlight follows the drag; `onCreateEvent` (when also
77
+ * set) fires once on release. Either handler enables the same sweep gesture, and
78
+ * a sweep can run across mini months.
79
+ */
80
+ onSelectDrag?: (start: Date, end: Date) => void;
81
+ /**
82
+ * Enables drag-to-create: press a day and drag across others, then release to
83
+ * fire this with the all-day range (`start` at midnight of the first day, `end`
84
+ * at midnight after the last, exclusive). A plain click without dragging still
85
+ * fires `onPressDay`, not this. Days being sketched carry `data-creating`.
86
+ */
87
+ onCreateEvent?: (start: Date, end: Date) => void;
57
88
  /** Theme overrides; falls back to the default light theme. */
58
89
  theme?: Partial<DomCalendarTheme>;
59
90
  /** Class applied to the root element. */
@@ -74,9 +105,16 @@ export function YearView<T = unknown>({
74
105
  hiddenDays,
75
106
  locale,
76
107
  activeDate,
108
+ selectedRange,
109
+ selectedDates,
110
+ minDate,
111
+ maxDate,
112
+ isDateDisabled,
77
113
  minMonthWidth = 150,
78
114
  onPressDay,
79
115
  onPressMonth,
116
+ onSelectDrag,
117
+ onCreateEvent,
80
118
  theme: themeOverrides,
81
119
  className,
82
120
  style,
@@ -86,6 +124,52 @@ export function YearView<T = unknown>({
86
124
  const theme = useMemo(() => mergeDomTheme(themeOverrides), [themeOverrides]);
87
125
  const slot = createSlots<YearViewSlot>({ classNames, styles });
88
126
 
127
+ // Drag-to-select / drag-to-create: press a day and sweep across others (mini
128
+ // months included), released on a window pointerup so a drop anywhere commits.
129
+ // `onSelectDrag` reports the span live, `onCreateEvent` once on release.
130
+ const sweepEnabled = onSelectDrag != null || onCreateEvent != null;
131
+ const [creating, setCreating] = useState<{ anchor: number; hover: number } | null>(null);
132
+ const creatingRef = useRef(creating);
133
+ creatingRef.current = creating;
134
+ const movedRef = useRef(false);
135
+ // Set when a sweep commits, so the click the browser fires next doesn't also
136
+ // open the day via onPressDay. A sweep that ends over a different cell than it
137
+ // began on gets its trailing click on their common ancestor instead, where no
138
+ // handler consumes the guard, so every fresh press clears it first.
139
+ const suppressClickRef = useRef(false);
140
+ const beginPress = () => {
141
+ suppressClickRef.current = false;
142
+ movedRef.current = false;
143
+ };
144
+ const beginCreate = (day: Date) => {
145
+ const t = startOfDay(day).getTime();
146
+ setCreating({ anchor: t, hover: t });
147
+ };
148
+ const extendCreate = (day: Date) => {
149
+ const current = creatingRef.current;
150
+ if (!current) return;
151
+ const t = startOfDay(day).getTime();
152
+ if (t === current.hover) return;
153
+ movedRef.current = true;
154
+ setCreating((c) => (c ? { ...c, hover: t } : c));
155
+ const [lo, hi] = current.anchor <= t ? [current.anchor, t] : [t, current.anchor];
156
+ onSelectDrag?.(new Date(lo), new Date(hi));
157
+ };
158
+ const isCreating = creating !== null;
159
+ useEffect(() => {
160
+ if (!isCreating) return;
161
+ const finish = () => {
162
+ const c = creatingRef.current;
163
+ setCreating(null);
164
+ if (!c || !movedRef.current) return;
165
+ suppressClickRef.current = true;
166
+ const range = monthCreateRange(new Date(c.anchor), new Date(c.hover));
167
+ onCreateEvent?.(range.start, range.end);
168
+ };
169
+ window.addEventListener("pointerup", finish);
170
+ return () => window.removeEventListener("pointerup", finish);
171
+ }, [isCreating, onCreateEvent]);
172
+
89
173
  const months = useMemo(() => getYearMonths(date), [date]);
90
174
  const weekdayLabels = useMemo(
91
175
  () =>
@@ -201,13 +285,30 @@ export function YearView<T = unknown>({
201
285
  />
202
286
  );
203
287
  }
288
+ const isToday = getIsToday(day);
204
289
  const isHighlighted = activeDate
205
290
  ? isSameCalendarDay(day, activeDate)
206
- : getIsToday(day);
291
+ : isToday;
207
292
  const hasEvents = eventDays.has(startOfDay(day).toISOString());
293
+ // Selection/disabled flags come from core, so the year grid
294
+ // can't disagree with the month grid about a day's state.
295
+ const state = daySelectionState(
296
+ day,
297
+ { selectedDates, selectedRange },
298
+ { minDate, maxDate, isDateDisabled },
299
+ );
300
+ const dayTime = startOfDay(day).getTime();
301
+ const inCreate =
302
+ creating != null &&
303
+ dayTime >= Math.min(creating.anchor, creating.hover) &&
304
+ dayTime <= Math.max(creating.anchor, creating.hover);
208
305
  const label = `${format(day, "EEEE, d LLLL yyyy", { locale })}${
209
- getIsToday(day) ? ", today" : ""
306
+ isToday ? ", today" : ""
307
+ }${state.isSelected ? ", selected" : ""}${
308
+ state.isDisabled ? ", unavailable" : ""
210
309
  }${hasEvents ? ", has events" : ""}`;
310
+ // Today wins over a selection, matching the month grid.
311
+ const badge = dayBadgeKind(state, isHighlighted);
211
312
  const daySlot = slot("day", {
212
313
  base: {
213
314
  position: "relative",
@@ -219,23 +320,56 @@ export function YearView<T = unknown>({
219
320
  border: "none",
220
321
  background: "transparent",
221
322
  font: "inherit",
222
- cursor: onPressDay ? "pointer" : "default",
323
+ cursor: state.isDisabled
324
+ ? "default"
325
+ : onPressDay || sweepEnabled
326
+ ? "pointer"
327
+ : "default",
223
328
  boxSizing: "border-box",
329
+ // The year grid scrolls vertically, so only the sideways
330
+ // axis is handed to the sweep: a vertical swipe still
331
+ // scrolls the months, a sideways drag sketches a range.
332
+ ...(sweepEnabled ? { touchAction: "pan-y" as const } : null),
224
333
  },
225
334
  themed: {
226
335
  fontSize: 11,
227
- borderRadius: "50%",
228
- ...(isHighlighted
229
- ? { background: theme.todayBackground, color: theme.todayText }
230
- : { color: theme.text }),
336
+ color: state.isDisabled ? theme.textDisabled : theme.text,
231
337
  },
232
338
  });
233
339
  const states = dataState({
234
340
  // `data-today` states the fact; the activeDate highlight is
235
341
  // visual only (themed), so the two can differ.
236
- "data-today": getIsToday(day),
342
+ "data-today": isToday,
237
343
  "data-events": hasEvents,
344
+ "data-selected": state.isSelected,
345
+ "data-range": state.isInRange,
346
+ "data-disabled": state.isDisabled,
347
+ "data-creating": inCreate,
238
348
  });
349
+ // The range draws as a band behind the day badges. The mini
350
+ // cells sit flush in the grid, so per-cell segments read as one
351
+ // continuous strip; only the endpoints round their outer edge.
352
+ const bandKind = rangeBandKind(state, true);
353
+ const rounding = bandRounding(rangeBandKind(state, false));
354
+ const band =
355
+ bandKind === "none" ? null : (
356
+ <span
357
+ data-band
358
+ aria-hidden
359
+ {...slot("rangeBand", {
360
+ base: {
361
+ position: "absolute",
362
+ inset: 0,
363
+ zIndex: 0,
364
+ borderTopLeftRadius: rounding.start ? "50%" : 0,
365
+ borderBottomLeftRadius: rounding.start ? "50%" : 0,
366
+ borderTopRightRadius: rounding.end ? "50%" : 0,
367
+ borderBottomRightRadius: rounding.end ? "50%" : 0,
368
+ },
369
+ themed: { background: theme.rangeBackground },
370
+ })}
371
+ />
372
+ );
239
373
  const dot = hasEvents ? (
240
374
  <span
241
375
  aria-hidden
@@ -245,29 +379,95 @@ export function YearView<T = unknown>({
245
379
  bottom: 1,
246
380
  left: "50%",
247
381
  marginLeft: -1.5,
382
+ zIndex: 2,
248
383
  width: 3,
249
384
  height: 3,
250
385
  borderRadius: 2,
251
386
  },
252
387
  themed: {
253
- background: isHighlighted ? theme.todayText : theme.todayBackground,
388
+ background:
389
+ badge === "none" ? theme.todayBackground : theme.todayText,
254
390
  },
255
391
  })}
256
392
  />
257
393
  ) : null;
394
+ const content = (
395
+ <>
396
+ {band}
397
+ <span
398
+ {...slot("dayBadge", {
399
+ base: {
400
+ position: "relative",
401
+ zIndex: 1,
402
+ width: "100%",
403
+ height: "100%",
404
+ borderRadius: "50%",
405
+ display: "flex",
406
+ alignItems: "center",
407
+ justifyContent: "center",
408
+ },
409
+ themed:
410
+ badge === "today"
411
+ ? { background: theme.todayBackground, color: theme.todayText }
412
+ : badge === "selected"
413
+ ? {
414
+ background: theme.selectedBackground,
415
+ color: theme.selectedText,
416
+ }
417
+ : {},
418
+ })}
419
+ >
420
+ {day.getDate()}
421
+ </span>
422
+ {dot}
423
+ </>
424
+ );
425
+ // A disabled day is out of every selection, drag included, so
426
+ // it neither anchors a sweep nor extends one onto itself.
427
+ const sweepHandlers = sweepEnabled
428
+ ? {
429
+ onPointerDown: (e: ReactPointerEvent) => {
430
+ beginPress();
431
+ if (e.button === 0 && !state.isDisabled) beginCreate(day);
432
+ },
433
+ onPointerEnter: state.isDisabled ? undefined : () => extendCreate(day),
434
+ }
435
+ : null;
436
+ // Only a day that does something on click is a button: with
437
+ // just the sweep wired, a button per day would be a tab stop
438
+ // whose click and Enter do nothing.
258
439
  return onPressDay ? (
259
440
  <button
260
441
  key={day.toISOString()}
261
442
  type="button"
262
443
  role="gridcell"
263
- onClick={() => onPressDay(day)}
444
+ disabled={state.isDisabled}
264
445
  aria-label={label}
446
+ onClick={() => {
447
+ if (suppressClickRef.current) {
448
+ suppressClickRef.current = false;
449
+ return;
450
+ }
451
+ onPressDay(day);
452
+ }}
453
+ {...sweepHandlers}
265
454
  {...states}
266
455
  {...daySlot}
267
456
  >
268
- {day.getDate()}
269
- {dot}
457
+ {content}
270
458
  </button>
459
+ ) : sweepEnabled ? (
460
+ <div
461
+ key={day.toISOString()}
462
+ role="gridcell"
463
+ aria-disabled={state.isDisabled || undefined}
464
+ aria-label={label}
465
+ {...sweepHandlers}
466
+ {...states}
467
+ {...daySlot}
468
+ >
469
+ {content}
470
+ </div>
271
471
  ) : (
272
472
  <div
273
473
  key={day.toISOString()}
@@ -276,8 +476,7 @@ export function YearView<T = unknown>({
276
476
  {...states}
277
477
  {...daySlot}
278
478
  >
279
- {day.getDate()}
280
- {dot}
479
+ {content}
281
480
  </div>
282
481
  );
283
482
  })}