@super-calendar/dom 2.17.0 → 2.18.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.
package/src/MonthView.tsx CHANGED
@@ -13,6 +13,7 @@ import {
13
13
  type KeyboardEvent as ReactKeyboardEvent,
14
14
  type ReactElement,
15
15
  type PointerEvent as ReactPointerEvent,
16
+ useCallback,
16
17
  useEffect,
17
18
  useMemo,
18
19
  useRef,
@@ -22,7 +23,9 @@ import {
22
23
  bandRounding,
23
24
  buildMonthGrid,
24
25
  buildMultiWeekGrid,
26
+ nowInTimeZone,
25
27
  type CalendarEvent,
28
+ type CreateGhostArgs,
26
29
  compareDayEvents,
27
30
  dayBadgeKind,
28
31
  type DateRange,
@@ -47,6 +50,7 @@ import {
47
50
  resolveCalendarLabels,
48
51
  } from "@super-calendar/core";
49
52
  import { holdDateDrag } from "./touch";
53
+ import { InertDiv } from "./InertDiv";
50
54
  import { createSlots, dataState, type SlotDefault, type SlotStyleProps } from "./slots";
51
55
  import { type DomCalendarTheme, mergeDomTheme } from "./theme";
52
56
 
@@ -64,6 +68,7 @@ export type MonthViewSlot =
64
68
  | "dayBadge"
65
69
  | "rangeBand"
66
70
  | "events"
71
+ | "createGhost"
67
72
  | "chipButton"
68
73
  | "chip"
69
74
  | "more"
@@ -79,6 +84,10 @@ const CHIP_GAP = 2;
79
84
  const CELL_PAD = 4;
80
85
  // Opacity of an event chip while it is being dragged to another day.
81
86
  const DRAGGED_CHIP_OPACITY = 0.4;
87
+ // How far a press travels before it becomes a drag. Until then the chips stay
88
+ // hit-testable, so a click still reaches the chip it pressed.
89
+ const DRAG_SLOP_PX = 4;
90
+ const TOUCH_DRAG_SLOP_PX = 8;
82
91
 
83
92
  // A day as the shared rows render it. Month days carry `isCurrentMonth`;
84
93
  // multi-week days omit it because every one of them is inside the period.
@@ -110,6 +119,11 @@ type MonthDrag<T> = (
110
119
  ) & {
111
120
  // The rows the drag began in, so a drag never commits into a different window.
112
121
  windowKey: string;
122
+ pointerId: number;
123
+ // Set once the pointer travels past the drag slop (or a touch hold fires).
124
+ // Chips stop taking pointer input only then, so a plain click is not
125
+ // retargeted to the day cell beneath.
126
+ armed: boolean;
113
127
  };
114
128
 
115
129
  /** Props for {@link MonthView}. */
@@ -175,6 +189,13 @@ export interface MonthViewProps<T = unknown>
175
189
  showWeekdays?: boolean;
176
190
  /** date-fns locale for the title and weekday labels. */
177
191
  locale?: Locale;
192
+ /**
193
+ * The instant whose calendar day is highlighted as today. Defaults to the
194
+ * device clock, and is read in `timeZone` when one is set.
195
+ */
196
+ now?: Date;
197
+ /** Highlight today as it is in this IANA time zone (default: the device's). */
198
+ timeZone?: string;
178
199
  /** Theme overrides; falls back to the default light theme. */
179
200
  theme?: Partial<DomCalendarTheme>;
180
201
  /** Fired when a selectable day is clicked. */
@@ -192,6 +213,12 @@ export interface MonthViewProps<T = unknown>
192
213
  * carry `data-creating` for styling.
193
214
  */
194
215
  onCreateEvent?: (start: Date, end: Date) => void;
216
+ /**
217
+ * Custom content for a drag-to-create preview, once per covered week row.
218
+ * Receives the full all-day range with an exclusive end. Requires onCreateEvent.
219
+ * Content is clipped, noninteractive, and hidden from assistive technology.
220
+ */
221
+ renderCreateGhost?: ComponentType<CreateGhostArgs>;
195
222
  /**
196
223
  * Reports the day span of a create sweep **as it happens**, as the ordered
197
224
  * inclusive `[start, end]` days (both at midnight), so a selection highlight can
@@ -571,6 +598,8 @@ export function DateRows<T = unknown>({
571
598
  showTitle = true,
572
599
  showWeekdays = true,
573
600
  locale,
601
+ now,
602
+ timeZone,
574
603
  theme: themeOverrides,
575
604
  minDate,
576
605
  maxDate,
@@ -578,6 +607,7 @@ export function DateRows<T = unknown>({
578
607
  onPressDay,
579
608
  onPressCell,
580
609
  onCreateEvent,
610
+ renderCreateGhost: RenderCreateGhost,
581
611
  onSelectDrag,
582
612
  onDragEvent,
583
613
  onDragStart,
@@ -603,13 +633,16 @@ export function DateRows<T = unknown>({
603
633
  // Calendar layout (date in the corner + event chips) is on whenever `events`
604
634
  // is provided; otherwise the compact picker badge layout is used. Multi-week
605
635
  // rows always use the calendar layout.
606
- const eventsMode = events !== undefined || multiWeek;
636
+ const createContentEnabled = onCreateEvent != null && RenderCreateGhost != null;
637
+ const eventsMode = events !== undefined || multiWeek || createContentEnabled;
607
638
  // The day cells form a roving tab stop (arrow keys + Enter) in the picker
608
639
  // always, and in events mode only when the consumer opts in. Otherwise events
609
640
  // mode tabs through the event chips alone.
610
641
  const dayRoving = !eventsMode || keyboardDayNavigation;
611
642
  // Use the list-built index when provided (MonthList), else build it for this
612
643
  // month. Either way lookups use startOfDay(date).toISOString().
644
+ // The day, not the instant, so the grid is rebuilt once a day.
645
+ const todayKey = startOfDay(nowInTimeZone(now, timeZone)).getTime();
613
646
  const eventsByDay = useMemo(() => {
614
647
  // The list (MonthList) sorts before passing its index in; only sort here when
615
648
  // building our own, so each day reads all-day events first, then by start.
@@ -679,6 +712,7 @@ export function DateRows<T = unknown>({
679
712
  maxDate,
680
713
  isDateDisabled,
681
714
  locale,
715
+ today: new Date(todayKey),
682
716
  };
683
717
  if (numberOfWeeks === undefined) {
684
718
  return {
@@ -706,6 +740,7 @@ export function DateRows<T = unknown>({
706
740
  maxDate,
707
741
  isDateDisabled,
708
742
  locale,
743
+ todayKey,
709
744
  ]);
710
745
 
711
746
  // Lay out each week row's spanning bars once per data change, not per render, so
@@ -833,8 +868,21 @@ export function DateRows<T = unknown>({
833
868
  // all-day span, or press an event chip and drop it on another day. Both are
834
869
  // released on a window pointerup, so letting go anywhere still commits.
835
870
  const [drag, setDrag] = useState<MonthDrag<T> | null>(null);
836
- const dragRef = useRef(drag);
837
- dragRef.current = drag;
871
+ const dragRef = useRef<MonthDrag<T> | null>(null);
872
+ // Release can arrive before React renders the last pointer movement.
873
+ const applyDrag = useCallback((next: MonthDrag<T> | null) => {
874
+ dragRef.current = next;
875
+ setDrag(next);
876
+ }, []);
877
+ const createStart = drag?.kind === "create" ? drag.anchor : null;
878
+ const createEnd = drag?.kind === "create" ? drag.hover : null;
879
+ const createRange = useMemo(
880
+ () =>
881
+ createContentEnabled && createStart !== null && createEnd !== null
882
+ ? monthCreateRange(new Date(createStart), new Date(createEnd))
883
+ : null,
884
+ [createContentEnabled, createStart, createEnd],
885
+ );
838
886
  const movedRef = useRef(false);
839
887
  // Set when a drag commits, so the click the browser fires next is swallowed (it
840
888
  // must not also open the day, or the event the drag landed on). A drag that ends
@@ -842,8 +890,9 @@ export function DateRows<T = unknown>({
842
890
  // common ancestor instead, where no handler consumes the guard — so every press
843
891
  // clears it first, keeping it scoped to the one interaction that set it.
844
892
  const suppressClickRef = useRef(false);
845
- const consumeSuppressedClick = () => {
846
- if (!suppressClickRef.current) return false;
893
+ // Keyboard and assistive-technology clicks have detail 0 and never trail a drag.
894
+ const consumeSuppressedClick = (detail: number) => {
895
+ if (detail === 0 || !suppressClickRef.current) return false;
847
896
  suppressClickRef.current = false;
848
897
  return true;
849
898
  };
@@ -854,30 +903,36 @@ export function DateRows<T = unknown>({
854
903
  !event.disabled &&
855
904
  event.draggable !== false &&
856
905
  (event.startEditable ?? eventStartEditable);
906
+ // Where the current press began and how far it may travel before it drags.
907
+ const pressOrigin = useRef({ x: 0, y: 0, slop: DRAG_SLOP_PX });
857
908
  // A fresh press starts a new interaction, so any guard left over from the
858
909
  // previous one is stale.
859
910
  const beginPress = () => {
860
911
  suppressClickRef.current = false;
861
912
  movedRef.current = false;
862
913
  };
863
- const beginCreate = (day: Date) => {
914
+ const beginCreate = (day: Date, pointerId: number, armed: boolean) => {
864
915
  if (!onCreateEvent && !onSelectDrag) return;
865
916
  const t = startOfDay(day).getTime();
866
- setDrag({ kind: "create", anchor: t, hover: t, windowKey });
917
+ applyDrag({ kind: "create", anchor: t, hover: t, windowKey, pointerId, armed });
867
918
  };
868
- const beginMove = (event: CalendarEvent<T>, day: Date) => {
919
+ const beginMove = (event: CalendarEvent<T>, day: Date, pointerId: number, armed: boolean) => {
869
920
  if (!canMove(event)) return;
870
921
  const t = startOfDay(day).getTime();
871
- setDrag({ kind: "move", event, from: t, to: t, windowKey });
922
+ applyDrag({ kind: "move", event, from: t, to: t, windowKey, pointerId, armed });
872
923
  onDragStart?.(event);
873
924
  };
874
- const extendDrag = (day: Date) => {
925
+ const extendDrag = (day: Date, pointerId: number) => {
875
926
  const current = dragRef.current;
876
- if (!current) return;
927
+ if (!current || current.pointerId !== pointerId) return;
877
928
  const t = startOfDay(day).getTime();
878
929
  if (t === (current.kind === "create" ? current.hover : current.to)) return;
879
930
  movedRef.current = true;
880
- setDrag(current.kind === "create" ? { ...current, hover: t } : { ...current, to: t });
931
+ applyDrag(
932
+ current.kind === "create"
933
+ ? { ...current, hover: t, armed: true }
934
+ : { ...current, to: t, armed: true },
935
+ );
881
936
  // A sweep reports its span live, so a selection can track the drag; a move
882
937
  // has nothing to report until it is dropped.
883
938
  if (current.kind === "create") {
@@ -900,12 +955,17 @@ export function DateRows<T = unknown>({
900
955
  ) => {
901
956
  if (event.button !== 0 || event.isPrimary === false || heldTouch.current) return;
902
957
  beginPress();
903
- const start = () => {
904
- if (moving) touchHandlers.current.beginMove(moving, day);
905
- else touchHandlers.current.beginCreate(day);
958
+ pressOrigin.current = {
959
+ x: event.clientX,
960
+ y: event.clientY,
961
+ slop: event.pointerType === "touch" ? TOUCH_DRAG_SLOP_PX : DRAG_SLOP_PX,
962
+ };
963
+ const start = (armed: boolean) => {
964
+ if (moving) touchHandlers.current.beginMove(moving, day, event.pointerId, armed);
965
+ else touchHandlers.current.beginCreate(day, event.pointerId, armed);
906
966
  };
907
967
  if (!multiWeek || !event.pointerType || event.pointerType === "mouse") {
908
- start();
968
+ start(false);
909
969
  return;
910
970
  }
911
971
  heldOrigin.current = { day, event: moving };
@@ -917,18 +977,18 @@ export function DateRows<T = unknown>({
917
977
  clientX: event.clientX,
918
978
  clientY: event.clientY,
919
979
  },
920
- start,
980
+ // The hold itself is the deliberate gesture, so a held drag starts armed.
981
+ () => start(true),
921
982
  (x, y) => {
922
983
  const element = gridRef.current?.ownerDocument
923
984
  .elementFromPoint(x, y)
924
985
  ?.closest<HTMLElement>("[data-day]");
925
986
  if (!element || !gridRef.current?.contains(element)) return;
926
987
  const day = touchHandlers.current.dayLookup.get(element.dataset.day ?? "");
927
- if (day && !day.isDisabled) touchHandlers.current.extendDrag(day.date);
988
+ if (day && !day.isDisabled) touchHandlers.current.extendDrag(day.date, event.pointerId);
928
989
  },
929
990
  () => {
930
- dragRef.current = null;
931
- setDrag(null);
991
+ applyDrag(null);
932
992
  movedRef.current = false;
933
993
  },
934
994
  () => {
@@ -967,15 +1027,23 @@ export function DateRows<T = unknown>({
967
1027
  }
968
1028
  });
969
1029
  const isDragging = drag !== null;
1030
+ const dragArmed = drag?.armed === true;
970
1031
  // Whether any month drag is wired up at all, so the cells only take over touch
971
1032
  // scrolling and pointer tracking when one of the handlers can actually fire.
972
1033
  const dragWired = onCreateEvent != null || onSelectDrag != null || onDragEvent != null;
973
1034
  useEffect(() => {
974
1035
  if (!isDragging) return;
975
- const finish = () => {
1036
+ const finish = (event: PointerEvent) => {
976
1037
  const current = dragRef.current;
977
- setDrag(null);
978
- if (!current || !movedRef.current) return;
1038
+ if (!current || current.pointerId !== event.pointerId) return;
1039
+ applyDrag(null);
1040
+ if (!movedRef.current) {
1041
+ // An armed move that returns to its day is released over the day cell,
1042
+ // because the chip ignored pointer input mid drag. The click that
1043
+ // follows belongs to the abandoned drag, not to the day.
1044
+ if (current.kind === "move" && current.armed) suppressClickRef.current = true;
1045
+ return;
1046
+ }
979
1047
  // Multi-week rows drop a drag whose window was replaced before release.
980
1048
  if (multiWeek && current.windowKey !== windowKeyRef.current) return;
981
1049
  suppressClickRef.current = true;
@@ -996,9 +1064,38 @@ export function DateRows<T = unknown>({
996
1064
  }
997
1065
  onDragEvent?.(current.event, next.start, next.end);
998
1066
  };
1067
+ const clear = () => {
1068
+ heldTouch.current?.();
1069
+ applyDrag(null);
1070
+ movedRef.current = false;
1071
+ suppressClickRef.current = true;
1072
+ };
1073
+ const cancel = (event: PointerEvent) => {
1074
+ if (dragRef.current?.pointerId === event.pointerId) clear();
1075
+ };
1076
+ const arm = (event: PointerEvent) => {
1077
+ const current = dragRef.current;
1078
+ if (!current || current.armed || current.pointerId !== event.pointerId) return;
1079
+ const origin = pressOrigin.current;
1080
+ if (Math.hypot(event.clientX - origin.x, event.clientY - origin.y) <= origin.slop) return;
1081
+ applyDrag({ ...current, armed: true });
1082
+ };
1083
+ const keyDown = (event: KeyboardEvent) => {
1084
+ if (event.key !== "Escape") return;
1085
+ event.preventDefault();
1086
+ clear();
1087
+ };
1088
+ window.addEventListener("pointermove", arm);
999
1089
  window.addEventListener("pointerup", finish);
1000
- return () => window.removeEventListener("pointerup", finish);
1001
- }, [isDragging, multiWeek, onCreateEvent, onDragEvent, eventOverlap, events]);
1090
+ window.addEventListener("pointercancel", cancel);
1091
+ window.addEventListener("keydown", keyDown);
1092
+ return () => {
1093
+ window.removeEventListener("pointermove", arm);
1094
+ window.removeEventListener("pointerup", finish);
1095
+ window.removeEventListener("pointercancel", cancel);
1096
+ window.removeEventListener("keydown", keyDown);
1097
+ };
1098
+ }, [isDragging, multiWeek, onCreateEvent, onDragEvent, eventOverlap, events, applyDrag]);
1002
1099
  // Replacing the multi-week window cancels a drag and closes the overflow
1003
1100
  // popover, so neither acts on days that are no longer shown.
1004
1101
  const transientWindow = useRef(windowKey);
@@ -1006,9 +1103,9 @@ export function DateRows<T = unknown>({
1006
1103
  if (transientWindow.current === windowKey) return;
1007
1104
  transientWindow.current = windowKey;
1008
1105
  if (!multiWeek) return;
1009
- setDrag(null);
1106
+ applyDrag(null);
1010
1107
  setMoreOpenFor(null);
1011
- }, [multiWeek, windowKey]);
1108
+ }, [multiWeek, windowKey, applyDrag]);
1012
1109
  // Multi-week roving: the neighbouring focusable day, the same weekday in the
1013
1110
  // nearest week that has it enabled, or the first/last focusable day.
1014
1111
  const nextMultiWeekFocus = (key: string): Date | null | undefined => {
@@ -1159,6 +1256,23 @@ export function DateRows<T = unknown>({
1159
1256
  };
1160
1257
  })
1161
1258
  .filter((b) => b.startCol <= b.endCol);
1259
+ const draftColumns = createRange
1260
+ ? week.days.flatMap((day, index) =>
1261
+ (!showAdjacentMonths && isOutsidePeriod(day)) ||
1262
+ day.date < createRange.start ||
1263
+ day.date >= createRange.end
1264
+ ? []
1265
+ : [index],
1266
+ )
1267
+ : [];
1268
+ const draftStart = draftColumns[0];
1269
+ const draftEnd = draftColumns.at(-1);
1270
+ const draftTop =
1271
+ CELL_PAD +
1272
+ DATE_ROW +
1273
+ chipGap +
1274
+ Math.min(visibleLanes, Math.max(0, maxVisibleEventCount - 1)) * (chipHeight + chipGap);
1275
+ const draftHeight = Math.min(chipHeight, Math.max(0, eventRowHeight - draftTop));
1162
1276
  const barChipButton = slot("chipButton", chipButtonDefault);
1163
1277
  const barChip = slot("chip", chipDefault(theme, chipHeight));
1164
1278
  return (
@@ -1277,13 +1391,15 @@ export function DateRows<T = unknown>({
1277
1391
  // A disabled day is out of every selection, drag included, so
1278
1392
  // a sweep never extends onto it and no drop lands there.
1279
1393
  onPointerEnter={
1280
- dragWired && !day.isDisabled ? () => extendDrag(day.date) : undefined
1394
+ dragWired && !day.isDisabled
1395
+ ? (event) => extendDrag(day.date, event.pointerId)
1396
+ : undefined
1281
1397
  }
1282
1398
  onClick={
1283
1399
  day.isDisabled
1284
1400
  ? undefined
1285
- : () => {
1286
- if (consumeSuppressedClick()) return;
1401
+ : (e) => {
1402
+ if (consumeSuppressedClick(e.detail)) return;
1287
1403
  onPressDay?.(day.date);
1288
1404
  onPressCell?.(startOfDay(day.date));
1289
1405
  }
@@ -1316,7 +1432,8 @@ export function DateRows<T = unknown>({
1316
1432
  .filter((b) => b.startCol === dayCol)
1317
1433
  .map((b) => {
1318
1434
  const span = b.endCol - b.startCol + 1;
1319
- const isDragged = drag?.kind === "move" && drag.event === b.seg.event;
1435
+ const isDragged =
1436
+ dragArmed && drag?.kind === "move" && drag.event === b.seg.event;
1320
1437
  return (
1321
1438
  <button
1322
1439
  key={`bar-${b.seg.event.start.toISOString()}:${b.seg.event.title}:${b.seg.lane}`}
@@ -1332,7 +1449,7 @@ export function DateRows<T = unknown>({
1332
1449
  }
1333
1450
  onClick={(e) => {
1334
1451
  e.stopPropagation();
1335
- if (consumeSuppressedClick()) return;
1452
+ if (consumeSuppressedClick(e.detail)) return;
1336
1453
  onPressEvent?.(b.seg.event);
1337
1454
  }}
1338
1455
  {...barChipButton}
@@ -1357,7 +1474,7 @@ export function DateRows<T = unknown>({
1357
1474
  chipGap +
1358
1475
  b.seg.lane * (chipHeight + chipGap),
1359
1476
  height: chipHeight,
1360
- pointerEvents: isDragging ? "none" : "auto",
1477
+ pointerEvents: dragArmed ? "none" : "auto",
1361
1478
  // Fade the bar being carried, so the tinted drop
1362
1479
  // target reads as where it is going.
1363
1480
  opacity: isDragged ? DRAGGED_CHIP_OPACITY : undefined,
@@ -1391,6 +1508,38 @@ export function DateRows<T = unknown>({
1391
1508
  </button>
1392
1509
  );
1393
1510
  })}
1511
+ {RenderCreateGhost &&
1512
+ createRange &&
1513
+ draftStart === dayCol &&
1514
+ draftEnd !== undefined &&
1515
+ draftHeight > 0 ? (
1516
+ <InertDiv
1517
+ {...slot("createGhost", {
1518
+ base: {
1519
+ position: "absolute",
1520
+ left: 2,
1521
+ width: `calc(${(draftEnd - draftStart + 1) * 100}% - 4px)`,
1522
+ top: draftTop,
1523
+ height: draftHeight,
1524
+ boxSizing: "border-box",
1525
+ pointerEvents: "none",
1526
+ overflow: "hidden",
1527
+ zIndex: 3,
1528
+ },
1529
+ themed: {
1530
+ background: theme.rangeBackground,
1531
+ border: `1px solid ${theme.selectedBackground}`,
1532
+ borderRadius: 4,
1533
+ fontSize: 12,
1534
+ color: theme.text,
1535
+ },
1536
+ })}
1537
+ inert
1538
+ aria-hidden="true"
1539
+ >
1540
+ <RenderCreateGhost start={createRange.start} end={createRange.end} />
1541
+ </InertDiv>
1542
+ ) : null}
1394
1543
  <div
1395
1544
  {...slot("events", {
1396
1545
  base: { display: "flex", flexDirection: "column", gap: chipGap },