@jsb188/calendar 1.1.2

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.
@@ -0,0 +1,341 @@
1
+ import {
2
+ CALENDAR_DEFAULT_NEW_EVENT_MINUTES,
3
+ CALENDAR_DRAG_THRESHOLD_PX,
4
+ CALENDAR_MIN_EVENT_MINUTES,
5
+ CALENDAR_SNAP_MINUTES,
6
+ } from '../constants/calendar.ts';
7
+ import type { CalendarDayObj } from '../types/calendar.d.ts';
8
+ import {
9
+ getDayLengthMinutes,
10
+ getInstantFromDayMinutes,
11
+ snapMinutes,
12
+ } from './calendar-range.ts';
13
+
14
+ /**
15
+ * The calendar's pointer gesture engine.
16
+ *
17
+ * Shaped after the Sheet's grid-selection-move: the gesture is a closure with
18
+ * window-level listeners, filtered by pointerId, torn down exactly once
19
+ * whether it was released or cancelled. Nothing here touches React — the
20
+ * in-flight gesture is a closure and a ref, never state, because a pointermove
21
+ * handler that set state would re-render every event in the week at pointer
22
+ * frequency.
23
+ *
24
+ * The time math is separated out into pure functions above the gesture so it
25
+ * can be tested without a DOM.
26
+ */
27
+
28
+ export interface CalendarGestureRange {
29
+ startAt: Date;
30
+ endAt: Date;
31
+ dayIndex: number;
32
+ }
33
+
34
+ /**
35
+ * Convert a pointer's position over the grid into a day index and a snapped
36
+ * minute offset within that day.
37
+ */
38
+
39
+ export function getCalendarPointerSlot(p: {
40
+ // Pointer position relative to the scrolling grid's content box
41
+ offsetX: number;
42
+ offsetY: number;
43
+ contentWidth: number;
44
+ hourHeight: number;
45
+ days: CalendarDayObj[];
46
+ }): { dayIndex: number; minute: number } {
47
+ const { offsetX, offsetY, contentWidth, hourHeight, days } = p;
48
+
49
+ const columnWidth = contentWidth / Math.max(1, days.length);
50
+ const dayIndex = Math.max(
51
+ 0,
52
+ Math.min(days.length - 1, Math.floor(offsetX / Math.max(1, columnWidth))),
53
+ );
54
+ const dayLengthMinutes = getDayLengthMinutes(days[dayIndex]);
55
+
56
+ return {
57
+ dayIndex,
58
+ minute: snapMinutes(
59
+ (offsetY / hourHeight) * 60,
60
+ CALENDAR_SNAP_MINUTES,
61
+ dayLengthMinutes,
62
+ ),
63
+ };
64
+ }
65
+
66
+ /**
67
+ * Build the time range a CREATE gesture describes.
68
+ *
69
+ * A press that never moved is a click, and a click means "an event of the
70
+ * default length starting here" — not a zero-length event, which is what a
71
+ * naive drag implementation produces because no hand is perfectly still.
72
+ */
73
+
74
+ export function getCalendarCreateRange(p: {
75
+ days: CalendarDayObj[];
76
+ anchorDayIndex: number;
77
+ anchorMinute: number;
78
+ currentDayIndex: number;
79
+ currentMinute: number;
80
+ moved: boolean;
81
+ }): CalendarGestureRange {
82
+ const { days, anchorDayIndex, anchorMinute, currentMinute, moved } = p;
83
+
84
+ // Creation stays in the column it began in: dragging sideways while drawing
85
+ // a block is almost always a wobble, not a request for a multi-day event
86
+ const day = days[anchorDayIndex];
87
+ const dayLengthMinutes = getDayLengthMinutes(day);
88
+
89
+ if (!moved) {
90
+ const startMinute = Math.min(
91
+ anchorMinute,
92
+ dayLengthMinutes - CALENDAR_DEFAULT_NEW_EVENT_MINUTES,
93
+ );
94
+
95
+ return {
96
+ dayIndex: anchorDayIndex,
97
+ startAt: getInstantFromDayMinutes(day.startAt, Math.max(0, startMinute)),
98
+ endAt: getInstantFromDayMinutes(
99
+ day.startAt,
100
+ Math.min(
101
+ dayLengthMinutes,
102
+ Math.max(0, startMinute) + CALENDAR_DEFAULT_NEW_EVENT_MINUTES,
103
+ ),
104
+ ),
105
+ };
106
+ }
107
+
108
+ // Dragging upward is a legitimate way to draw a block, so the anchor is
109
+ // whichever end is earlier rather than whichever came first
110
+ const startMinute = Math.min(anchorMinute, currentMinute);
111
+ const endMinute = Math.max(anchorMinute, currentMinute);
112
+
113
+ return {
114
+ dayIndex: anchorDayIndex,
115
+ startAt: getInstantFromDayMinutes(day.startAt, startMinute),
116
+ endAt: getInstantFromDayMinutes(
117
+ day.startAt,
118
+ Math.min(
119
+ dayLengthMinutes,
120
+ Math.max(endMinute, startMinute + CALENDAR_MIN_EVENT_MINUTES),
121
+ ),
122
+ ),
123
+ };
124
+ }
125
+
126
+ /**
127
+ * Build the time range a MOVE gesture describes.
128
+ *
129
+ * The event keeps its duration and is offset by how far the pointer travelled
130
+ * from where it grabbed the block — not snapped to the pointer itself, which
131
+ * would make the block jump under the finger on the first pixel of movement.
132
+ */
133
+
134
+ export function getCalendarMoveRange(p: {
135
+ days: CalendarDayObj[];
136
+ startAt: Date;
137
+ endAt: Date;
138
+ // Minutes between the grab point and the event's start
139
+ grabOffsetMinutes: number;
140
+ currentDayIndex: number;
141
+ currentMinute: number;
142
+ }): CalendarGestureRange {
143
+ const {
144
+ days,
145
+ startAt,
146
+ endAt,
147
+ grabOffsetMinutes,
148
+ currentDayIndex,
149
+ currentMinute,
150
+ } = p;
151
+
152
+ const day = days[currentDayIndex];
153
+ const dayLengthMinutes = getDayLengthMinutes(day);
154
+ const durationMs = endAt.getTime() - startAt.getTime();
155
+ const durationMinutes = durationMs / 60_000;
156
+
157
+ // Clamped so a drag near the bottom of the column cannot push the event
158
+ // past midnight and silently turn it into an overnight shift
159
+ const rawStart = currentMinute - grabOffsetMinutes;
160
+ const startMinute = snapMinutes(
161
+ Math.max(0, Math.min(rawStart, dayLengthMinutes - durationMinutes)),
162
+ CALENDAR_SNAP_MINUTES,
163
+ dayLengthMinutes,
164
+ );
165
+ const nextStart = getInstantFromDayMinutes(day.startAt, startMinute);
166
+
167
+ return {
168
+ dayIndex: currentDayIndex,
169
+ startAt: nextStart,
170
+ // Duration is preserved in ABSOLUTE time, so moving a shift onto a DST
171
+ // day keeps it the same number of hours long rather than the same
172
+ // wall-clock span
173
+ endAt: new Date(nextStart.getTime() + durationMs),
174
+ };
175
+ }
176
+
177
+ /**
178
+ * Build the time range a RESIZE gesture describes.
179
+ *
180
+ * The edge being dragged moves; the other stays put. A resize that would
181
+ * invert or collapse the event is clamped to the minimum length instead,
182
+ * because an event whose end precedes its start is not something the user
183
+ * meant to ask for.
184
+ */
185
+
186
+ export function getCalendarResizeRange(p: {
187
+ days: CalendarDayObj[];
188
+ dayIndex: number;
189
+ startAt: Date;
190
+ endAt: Date;
191
+ edge: 'START' | 'END';
192
+ currentMinute: number;
193
+ }): CalendarGestureRange {
194
+ const { days, dayIndex, startAt, endAt, edge, currentMinute } = p;
195
+
196
+ const day = days[dayIndex];
197
+ const dayLengthMinutes = getDayLengthMinutes(day);
198
+ const dayStartMs = day.startAt.getTime();
199
+
200
+ if (edge === 'START') {
201
+ const endMinute = (endAt.getTime() - dayStartMs) / 60_000;
202
+ const startMinute = Math.min(
203
+ currentMinute,
204
+ endMinute - CALENDAR_MIN_EVENT_MINUTES,
205
+ );
206
+
207
+ return {
208
+ dayIndex,
209
+ startAt: getInstantFromDayMinutes(day.startAt, Math.max(0, startMinute)),
210
+ endAt,
211
+ };
212
+ }
213
+
214
+ const startMinute = (startAt.getTime() - dayStartMs) / 60_000;
215
+ const endMinute = Math.max(
216
+ currentMinute,
217
+ startMinute + CALENDAR_MIN_EVENT_MINUTES,
218
+ );
219
+
220
+ return {
221
+ dayIndex,
222
+ startAt,
223
+ endAt: getInstantFromDayMinutes(
224
+ day.startAt,
225
+ Math.min(dayLengthMinutes, endMinute),
226
+ ),
227
+ };
228
+ }
229
+
230
+ export interface CalendarGestureParams {
231
+ // Deliberately no "kind": what a gesture DOES is entirely decided by the
232
+ // resolveRange the caller supplies, so a kind field here was an input
233
+ // nothing read — and the grid was passing 'RESIZE_END' for both resize
234
+ // edges, a wrong value that only went unnoticed because it was ignored.
235
+ pointerId: number;
236
+ // Client coordinates where the gesture began, for the movement threshold
237
+ originClientX: number;
238
+ originClientY: number;
239
+ // Called on every movement past the threshold, and once on release
240
+ onPreview: (range: CalendarGestureRange | null) => void;
241
+ // Called on release only when the gesture was not cancelled
242
+ onCommit: (range: CalendarGestureRange, moved: boolean) => void;
243
+ // Resolve the range for the pointer's current client position
244
+ resolveRange: (
245
+ clientX: number,
246
+ clientY: number,
247
+ moved: boolean,
248
+ ) => CalendarGestureRange | null;
249
+ onFinish?: () => void;
250
+ }
251
+
252
+ /**
253
+ * Start one calendar pointer gesture.
254
+ *
255
+ * Returns a cleanup function that is safe to call more than once; the gesture
256
+ * also calls it itself on release or cancel. Listeners live on the window so a
257
+ * drag that leaves the grid — which every drag does at the edges — keeps
258
+ * tracking rather than freezing at the boundary.
259
+ */
260
+
261
+ export function startCalendarGesture(
262
+ params: CalendarGestureParams,
263
+ ): () => void {
264
+ let finished = false;
265
+ let moved = false;
266
+
267
+ /*
268
+ * Remove every global side effect exactly once, whether the gesture was
269
+ * released or cancelled.
270
+ */
271
+
272
+ function cleanup() {
273
+ if (finished) {
274
+ return;
275
+ }
276
+
277
+ finished = true;
278
+ params.onPreview(null);
279
+ globalThis.removeEventListener('pointermove', onPointerMove);
280
+ globalThis.removeEventListener('pointerup', onPointerUp);
281
+ globalThis.removeEventListener('pointercancel', onPointerCancel);
282
+ params.onFinish?.();
283
+ }
284
+
285
+ function onPointerMove(event: PointerEvent) {
286
+ if (event.pointerId !== params.pointerId) {
287
+ return;
288
+ }
289
+
290
+ if (!moved) {
291
+ const travelled = Math.hypot(
292
+ event.clientX - params.originClientX,
293
+ event.clientY - params.originClientY,
294
+ );
295
+
296
+ if (travelled < CALENDAR_DRAG_THRESHOLD_PX) {
297
+ return;
298
+ }
299
+
300
+ moved = true;
301
+ }
302
+
303
+ params.onPreview(params.resolveRange(event.clientX, event.clientY, true));
304
+ }
305
+
306
+ function finish(event: PointerEvent, commit: boolean) {
307
+ if (event.pointerId !== params.pointerId) {
308
+ return;
309
+ }
310
+
311
+ if (commit) {
312
+ const range = params.resolveRange(event.clientX, event.clientY, moved);
313
+
314
+ if (range) {
315
+ // Committed BEFORE cleanup, so the commit handler can still read
316
+ // whatever the gesture was showing
317
+ params.onCommit(range, moved);
318
+ }
319
+ }
320
+
321
+ cleanup();
322
+ }
323
+
324
+ function onPointerUp(event: PointerEvent) {
325
+ finish(event, true);
326
+ }
327
+
328
+ /*
329
+ * Discard one browser-cancelled pointer stream.
330
+ */
331
+
332
+ function onPointerCancel(event: PointerEvent) {
333
+ finish(event, false);
334
+ }
335
+
336
+ globalThis.addEventListener('pointermove', onPointerMove);
337
+ globalThis.addEventListener('pointerup', onPointerUp);
338
+ globalThis.addEventListener('pointercancel', onPointerCancel);
339
+
340
+ return cleanup;
341
+ }
@@ -0,0 +1,39 @@
1
+ import { useEffect, useState } from 'react';
2
+ import { CALENDAR_NOW_TICK_MS } from '../constants/calendar.ts';
3
+
4
+ /**
5
+ * A clock the calendar can trust.
6
+ *
7
+ * Every other surface in the app can read the time once at mount and be right
8
+ * for as long as it is open. A calendar cannot: it draws a "now" line, it
9
+ * highlights today's column, and it decides which day an undated URL means. A
10
+ * calendar left open on a wall display or on somebody's second monitor — which
11
+ * is exactly how calendars are used — would otherwise keep yesterday
12
+ * highlighted and keep the now line frozen where it was when the page loaded.
13
+ *
14
+ * The returned Date only changes identity when the minute does, so a consumer
15
+ * can use it as a hook dependency without re-running on every tick.
16
+ */
17
+
18
+ export function useCalendarNow(): Date {
19
+ const [now, setNow] = useState(() => new Date());
20
+
21
+ useEffect(() => {
22
+ const interval = setInterval(() => {
23
+ setNow((current) => {
24
+ const next = new Date();
25
+
26
+ // Returning the SAME reference within a minute is what keeps this
27
+ // from invalidating the layout memos sixty times an hour
28
+ return Math.floor(next.getTime() / 60_000) ===
29
+ Math.floor(current.getTime() / 60_000)
30
+ ? current
31
+ : next;
32
+ });
33
+ }, CALENDAR_NOW_TICK_MS);
34
+
35
+ return () => clearInterval(interval);
36
+ }, []);
37
+
38
+ return now;
39
+ }