From 5fbadcd0dba6fb7059fd7c829f3a2fc40448a78c Mon Sep 17 00:00:00 2001 From: Linus Rath <139418639+rathlinus@users.noreply.github.com> Date: Wed, 4 Nov 2026 17:44:36 +0100 Subject: [PATCH 1/5] fix: create exactly the time range the drag selection shows in week and day view The existing drag test released the pointer far below its last move and expected the release spot to count; it now moves there first, since the release commits the range last drawn. --- .../use-time-grid-interactions.test.ts | 57 ++++++++++++ hooks/use-time-grid-interactions.ts | 91 +++++++++++++------ 2 files changed, 122 insertions(+), 26 deletions(-) diff --git a/hooks/__tests__/use-time-grid-interactions.test.ts b/hooks/__tests__/use-time-grid-interactions.test.ts index ad9629a86..5c65ef79b 100644 --- a/hooks/__tests__/use-time-grid-interactions.test.ts +++ b/hooks/__tests__/use-time-grid-interactions.test.ts @@ -82,6 +82,8 @@ describe("useTimeGridInteractions slot clicks (#435)", () => { act(() => result.current.handleGridPointerDown(pointer(160), "2026-09-03", day)); act(() => result.current.handleGridPointerMove(pointer(400))); expect(result.current.dragCreate).toEqual({ dayKey: "2026-09-03", startMinutes: 540, endMinutes: 780 }); + act(() => result.current.handleGridPointerMove(pointer(2000))); + expect(result.current.dragCreate).toEqual({ dayKey: "2026-09-03", startMinutes: 540, endMinutes: 1200 }); act(() => result.current.handleGridPointerUp(pointer(2000))); const [start, end] = onCreateRange.mock.calls[0]; @@ -89,6 +91,61 @@ describe("useTimeGridInteractions slot clicks (#435)", () => { expect(end).toEqual(new Date(2026, 8, 3, 20, 0, 0, 0)); }); + // The selection said 11:15 – 16:15 and the event came out shorter: the + // range drawn, its label and the event created must be the same. + describe("drag-to-create creates what the selection shows", () => { + const day = new Date(2026, 10, 2); + let top = 0; + const column = { + getBoundingClientRect: () => ({ top }), + setPointerCapture: vi.fn(), + releasePointerCapture: vi.fn(), + }; + const pointer = (clientY: number) => ({ + pointerType: "mouse", button: 0, pointerId: 1, clientY, + target: { closest: () => null }, currentTarget: column, + }) as unknown as React.PointerEvent; + beforeEach(() => { top = 0; }); + + it("commits the range last drawn, not one measured again on release", () => { + const { result, onCreateRange } = renderInteractions(); + act(() => result.current.handleGridPointerDown(pointer(675), "2026-11-02", day)); + act(() => result.current.handleGridPointerMove(pointer(975))); + expect(result.current.dragCreate).toEqual({ dayKey: "2026-11-02", startMinutes: 675, endMinutes: 975 }); + // The release reports a slightly different spot (a trackpad lifting). + act(() => result.current.handleGridPointerUp(pointer(948))); + + const [start, end] = onCreateRange.mock.calls[0]; + expect(start).toEqual(new Date(2026, 10, 2, 11, 15)); + expect(end).toEqual(new Date(2026, 10, 2, 16, 15)); + }); + + it("follows the grid when it scrolls during the drag, and creates what it then shows", () => { + const { result, onCreateRange } = renderInteractions(); + act(() => result.current.handleGridPointerDown(pointer(675), "2026-11-02", day)); + act(() => result.current.handleGridPointerMove(pointer(975))); + // The wheel scrolls the grid up by an hour under a still pointer. + top = -60; + act(() => { window.dispatchEvent(new Event("scroll")); }); + expect(result.current.dragCreate).toEqual({ dayKey: "2026-11-02", startMinutes: 675, endMinutes: 1035 }); + act(() => result.current.handleGridPointerUp(pointer(975))); + + const [start, end] = onCreateRange.mock.calls[0]; + expect(start).toEqual(new Date(2026, 10, 2, 11, 15)); + expect(end).toEqual(new Date(2026, 10, 2, 17, 15)); + }); + + it("creates nothing when the browser takes the pointer over", () => { + const { result, onCreateRange } = renderInteractions(); + act(() => result.current.handleGridPointerDown(pointer(675), "2026-11-02", day)); + act(() => result.current.handleGridPointerMove(pointer(975))); + act(() => result.current.handleGridPointerCancel()); + expect(result.current.dragCreate).toBeNull(); + act(() => result.current.handleGridPointerUp(pointer(975))); + expect(onCreateRange).not.toHaveBeenCalled(); + }); + }); + it("a 23:00 click ends at midnight of the next day", () => { const { result, onCreateRange } = renderInteractions(); const day = new Date(2026, 8, 3); diff --git a/hooks/use-time-grid-interactions.ts b/hooks/use-time-grid-interactions.ts index 9c48fad53..8e7acca45 100644 --- a/hooks/use-time-grid-interactions.ts +++ b/hooks/use-time-grid-interactions.ts @@ -1,4 +1,4 @@ -import { useState, useCallback, useRef, type PointerEvent, type DragEvent } from "react"; +import { useState, useCallback, useEffect, useRef, type PointerEvent, type DragEvent } from "react"; import { format } from "date-fns"; import { useAuthStore } from "@/stores/auth-store"; import { useCalendarStore } from "@/stores/calendar-store"; @@ -72,6 +72,17 @@ interface UseTimeGridInteractionsOptions { onMoveEvent?: MoveEventHandler; } +/** + * The range a drag from `anchorMinutes` to `currentMinutes` (both snapped) + * selects, or null when it is shorter than a quarter of an hour. The + * drawn selection, its label and the event it creates all come from this. + */ +export function dragCreateRange(anchorMinutes: number, currentMinutes: number): { startMinutes: number; endMinutes: number } | null { + const startMinutes = Math.min(anchorMinutes, currentMinutes); + const endMinutes = Math.max(anchorMinutes, currentMinutes); + return endMinutes - startMinutes >= 15 ? { startMinutes, endMinutes } : null; +} + /** `date` moved by `minutes` on the local clock, not by elapsed time. */ function addWallClockMinutes(date: Date, minutes: number): Date { const shifted = new Date(date); @@ -101,6 +112,9 @@ export function useTimeGridInteractions({ const wasDragging = useRef(false); // --- Drag-to-create --- + // The range on screen is the range created: the release commits the + // selection last drawn rather than measuring the pointer again, and a + // scroll during the drag redraws it under the pointer. const dragRef = useRef<{ dayKey: string; dayDate: Date; @@ -108,10 +122,31 @@ export function useTimeGridInteractions({ pointerId: number; startY: number; captured: boolean; + column: HTMLElement; + lastY: number; + range: { startMinutes: number; endMinutes: number } | null; + stopScrollWatch?: () => void; } | null>(null); const [dragCreate, setDragCreate] = useState(null); + const updateDragRange = useCallback((clientY: number) => { + const drag = dragRef.current; + if (!drag) return; + drag.lastY = clientY; + const range = dragCreateRange(drag.startMinutes, snapToMinutes(clientY, drag.column.getBoundingClientRect().top)); + drag.range = range; + setDragCreate(range ? { dayKey: drag.dayKey, ...range } : null); + }, [snapToMinutes]); + + const endDrag = useCallback(() => { + const drag = dragRef.current; + dragRef.current = null; + drag?.stopScrollWatch?.(); + setDragCreate(null); + return drag; + }, []); + const handleGridPointerDown = useCallback(( e: PointerEvent, dayKey: string, @@ -125,34 +160,34 @@ export function useTimeGridInteractions({ const rect = e.currentTarget.getBoundingClientRect(); const minutes = snapToMinutes(e.clientY, rect.top); + dragRef.current?.stopScrollWatch?.(); dragRef.current = { dayKey, dayDate, startMinutes: minutes, pointerId: e.pointerId, startY: e.clientY, captured: false, + column: e.currentTarget, lastY: e.clientY, range: null, }; }, [snapToMinutes, isMobile]); const handleGridPointerMove = useCallback((e: PointerEvent) => { - if (!dragRef.current) return; + const drag = dragRef.current; + if (!drag) return; - if (!dragRef.current.captured) { - if (Math.abs(e.clientY - dragRef.current.startY) < 5) return; - dragRef.current.captured = true; - e.currentTarget.setPointerCapture(dragRef.current.pointerId); + if (!drag.captured) { + if (Math.abs(e.clientY - drag.startY) < 5) return; + drag.captured = true; + e.currentTarget.setPointerCapture(drag.pointerId); + // The wheel or the browser's autoscroll moves the grid under a + // pointer that stands still: follow it. + const onScroll = () => updateDragRange(drag.lastY); + window.addEventListener("scroll", onScroll, true); + drag.stopScrollWatch = () => window.removeEventListener("scroll", onScroll, true); } - const rect = e.currentTarget.getBoundingClientRect(); - const currentMinutes = snapToMinutes(e.clientY, rect.top); - const start = Math.min(dragRef.current.startMinutes, currentMinutes); - const end = Math.max(dragRef.current.startMinutes, currentMinutes); - - setDragCreate(end > start ? { dayKey: dragRef.current.dayKey, startMinutes: start, endMinutes: end } : null); - }, [snapToMinutes]); + updateDragRange(e.clientY); + }, [updateDragRange]); const handleGridPointerUp = useCallback((e: PointerEvent) => { - const drag = dragRef.current; - dragRef.current = null; - setDragCreate(null); - + const drag = endDrag(); if (!drag || !drag.captured) return; wasDragging.current = true; @@ -160,19 +195,22 @@ export function useTimeGridInteractions({ try { e.currentTarget.releasePointerCapture(drag.pointerId); } catch { /* may already be released */ } - const rect = e.currentTarget.getBoundingClientRect(); - const endMinutes = snapToMinutes(e.clientY, rect.top); - const start = Math.min(drag.startMinutes, endMinutes); - const end = Math.max(drag.startMinutes, endMinutes); - - if (end - start < 15) return; + const range = drag.range; + if (!range) return; const startDate = new Date(drag.dayDate); - startDate.setHours(Math.floor(start / 60), start % 60, 0, 0); + startDate.setHours(Math.floor(range.startMinutes / 60), range.startMinutes % 60, 0, 0); const endDate = new Date(drag.dayDate); - endDate.setHours(Math.floor(end / 60), end % 60, 0, 0); + endDate.setHours(Math.floor(range.endMinutes / 60), range.endMinutes % 60, 0, 0); onCreateRange(startDate, endDate); - }, [snapToMinutes, onCreateRange]); + }, [endDrag, onCreateRange]); + + useEffect(() => () => dragRef.current?.stopScrollWatch?.(), []); + + /** The browser took the pointer over (a touch scroll, a system gesture): nothing is created. */ + const handleGridPointerCancel = useCallback(() => { + endDrag(); + }, [endDrag]); // --- Resize --- const resizeRef = useRef<{ @@ -438,6 +476,7 @@ export function useTimeGridInteractions({ handleGridPointerDown, handleGridPointerMove, handleGridPointerUp, + handleGridPointerCancel, resizeVisual, handleResizePointerDown, handleResizePointerMove, From 849a07345a3df2b6a048bd21bfa6b7305c284083 Mon Sep 17 00:00:00 2001 From: Linus Rath <139418639+rathlinus@users.noreply.github.com> Date: Wed, 4 Nov 2026 17:44:37 +0100 Subject: [PATCH 2/5] fix: draw the drag selection over the events it covers and give the new event its own column --- .../calendar-week-view-drag-create.test.tsx | 141 ++++++++++++++++++ components/calendar/calendar-day-view.tsx | 68 ++++++--- components/calendar/calendar-week-view.tsx | 69 ++++++--- lib/calendar-utils.ts | 37 ++++- 4 files changed, 273 insertions(+), 42 deletions(-) create mode 100644 components/calendar/__tests__/calendar-week-view-drag-create.test.tsx diff --git a/components/calendar/__tests__/calendar-week-view-drag-create.test.tsx b/components/calendar/__tests__/calendar-week-view-drag-create.test.tsx new file mode 100644 index 000000000..8c8aa9331 --- /dev/null +++ b/components/calendar/__tests__/calendar-week-view-drag-create.test.tsx @@ -0,0 +1,141 @@ +import { render, fireEvent, cleanup } from '@testing-library/react'; +import { describe, it, expect, vi, afterEach, beforeAll } from 'vitest'; +import { CalendarWeekView } from '../calendar-week-view'; +import { CalendarDayView } from '../calendar-day-view'; +import type { CalendarEvent, Calendar } from '@/lib/jmap/types'; + +// Usability report 2026-11-04: dragging over an empty stretch of a day drew +// a see-through selection the events showed through, and the new event's +// placeholder lay over the events it overlapped ("Lernblock" hidden behind +// it) instead of taking a column beside them. + +const calendars = [{ id: 'cal-1', name: 'Work', color: '#123456' }] as unknown as Calendar[]; + +function timed(id: string, start: string, duration: string): CalendarEvent { + return { + id, '@type': 'Event', uid: id, title: id, start, duration, timeZone: null, + showWithoutTime: false, calendarIds: { 'cal-1': true }, + } as unknown as CalendarEvent; +} + +const lernblock = timed('Lernblock', '2026-09-09T12:30:00', 'PT1H'); +const draft = { + start: new Date(2026, 8, 9, 11, 45), end: new Date(2026, 8, 9, 15, 45), + title: '(No title)', allDay: false, calendarId: 'cal-1', +}; + +type WeekProps = React.ComponentProps; + +function renderWeek(overrides: Partial = {}) { + const props: WeekProps = { + focus: { date: new Date(2026, 8, 9), nonce: 0 }, + windowKey: 'week:2026-09-07', + rangeStart: new Date(2026, 8, 7), + rangeEnd: new Date(2026, 8, 13), + selectedDate: new Date(2026, 8, 9), + events: [], + calendars, + onSelectDate: vi.fn(), + onSelectEvent: vi.fn(), + onCreateAtTime: vi.fn(), + ...overrides, + }; + return { props, ...render() }; +} + +/** The time column of a day: the grid cell holding its hour slots. */ +function column(key: string): HTMLElement { + const slot = document.querySelector(`[data-slot^="${key}T"]`); + const cell = slot?.closest('[role="gridcell"]'); + if (!cell) throw new Error(`no column for ${key}`); + return cell; +} + +/** The pixel offset of a time in a column whose hours are 60 px tall. */ +function yOf(key: string, minutes: number): number { + const first = Number(document.querySelector(`[data-slot^="${key}T"]`)!.getAttribute('data-slot')!.split('T')[1]); + return minutes - first * 60; +} + +/** The positioned box around the drawn placeholder of the new event. */ +function placeholderBox(): HTMLElement { + const preview = document.querySelector('[data-pending-preview]'); + if (!preview) throw new Error('no placeholder'); + return preview.style.width ? preview : preview.parentElement!; +} + +function eventBox(id: string): HTMLElement { + const box = Array.from(document.querySelectorAll('[data-calendar-event]')) + .find((el) => el.textContent?.includes(id)); + if (!box) throw new Error(`no event ${id}`); + return box; +} + +beforeAll(() => { + // jsdom has no pointer capture. + Element.prototype.setPointerCapture ??= () => {}; + Element.prototype.releasePointerCapture ??= () => {}; +}); + +afterEach(() => cleanup()); + +describe('Week view drag-to-create', () => { + it('draws the selection opaque and above the events it passes over', () => { + renderWeek({ events: [lernblock] }); + const col = column('2026-09-09'); + fireEvent.pointerDown(col, { pointerId: 1, pointerType: 'mouse', button: 0, clientY: yOf('2026-09-09', 675) }); + fireEvent.pointerMove(col, { pointerId: 1, pointerType: 'mouse', clientY: yOf('2026-09-09', 975) }); + + const selection = col.querySelector('[data-drag-selection]'); + expect(selection).not.toBeNull(); + expect(selection!.textContent).toContain('11:15 – 16:15'); + // An opaque fill: the event under it doesn't show through. + expect(selection!.style.backgroundColor).toContain('var(--color-background)'); + expect(selection!.className).toContain('z-30'); + expect(eventBox('Lernblock').className).toContain('z-10'); + }); + + it('creates the range the selection showed', () => { + const { props } = renderWeek({ events: [lernblock] }); + const col = column('2026-09-09'); + fireEvent.pointerDown(col, { pointerId: 1, pointerType: 'mouse', button: 0, clientY: yOf('2026-09-09', 675) }); + fireEvent.pointerMove(col, { pointerId: 1, pointerType: 'mouse', clientY: yOf('2026-09-09', 975) }); + fireEvent.pointerUp(col, { pointerId: 1, pointerType: 'mouse', clientY: yOf('2026-09-09', 940) }); + + expect(props.onCreateAtTime).toHaveBeenCalledWith(new Date(2026, 8, 9, 11, 15), new Date(2026, 8, 9, 16, 15)); + }); +}); + +describe('The new event beside the events it overlaps', () => { + it('shares the width with them in the week view', () => { + renderWeek({ events: [lernblock], pendingPreview: draft }); + expect(placeholderBox().style.width).toBe('50%'); + expect(eventBox('Lernblock').style.width).toBe('50%'); + // Each in its own half. + expect(placeholderBox().style.insetInlineStart).not.toBe(eventBox('Lernblock').style.insetInlineStart); + }); + + it('keeps the whole width where nothing overlaps it', () => { + renderWeek({ events: [timed('Later', '2026-09-09T17:00:00', 'PT1H')], pendingPreview: draft }); + expect(placeholderBox().style.width).toBe('100%'); + }); + + it('shares the width with them in the day view', () => { + render( + , + ); + expect(placeholderBox().style.width).toBe('50%'); + expect(eventBox('Lernblock').style.width).toBe('50%'); + }); +}); diff --git a/components/calendar/calendar-day-view.tsx b/components/calendar/calendar-day-view.tsx index 8368b0429..d5bf5c515 100644 --- a/components/calendar/calendar-day-view.tsx +++ b/components/calendar/calendar-day-view.tsx @@ -10,7 +10,7 @@ import { EventCard, eventFillClass, eventFillStyle } from "./event-card"; import { CalendarTaskChip } from "./task-chip"; import { QuickEventInput } from "./quick-event-input"; import { AllHoursToggle, HiddenEventsIndicator } from "./display-hours-controls"; -import { formatSnapTime, getEventDayBounds, getPrimaryCalendarId, isTimedEventFullDayOnDate, layoutOverlappingEvents } from "@/lib/calendar-utils"; +import { formatSnapTime, getEventDayBounds, getPrimaryCalendarId, isTimedEventFullDayOnDate, layoutOverlappingEvents, pendingTimedMinutes, PENDING_LAYOUT_ID } from "@/lib/calendar-utils"; import { clipToDisplayHours, partitionByDisplayHours } from "@/lib/calendar-display-range"; import { displayNow, isDisplayToday } from "@/lib/timezone"; import { groupTasksByDueDay } from "@/lib/calendar-tasks"; @@ -203,6 +203,25 @@ export function CalendarDayView({ return map; }, [days, eventsByDay, hours]); + // The new event being created takes a column beside the events it + // overlaps, as it will once saved, instead of covering them. Only its + // times count: typing its title doesn't redo the layout. + const pendingStartMs = pendingPreview && !pendingPreview.allDay ? pendingPreview.start.getTime() : null; + const pendingEndMs = pendingPreview && !pendingPreview.allDay ? pendingPreview.end.getTime() : null; + const pendingLayout = useMemo(() => { + if (pendingStartMs === null || pendingEndMs === null) return null; + const preview = { start: new Date(pendingStartMs), end: new Date(pendingEndMs) }; + const day = days.find((d) => isSameDay(d, preview.start)); + const bounds = day ? pendingTimedMinutes(preview, day) : null; + if (!day || !bounds) return null; + const key = format(day, "yyyy-MM-dd"); + const partition = partitionByDisplayHours(eventsByDay.get(key)?.timed ?? [], day, hours); + const all = layoutOverlappingEvents(partition.visible, day, bounds); + const pending = all.find((layout) => layout.event.id === PENDING_LAYOUT_ID); + if (!pending) return null; + return { key, layouts: all.filter((layout) => layout.event.id !== PENDING_LAYOUT_ID), pending }; + }, [pendingStartMs, pendingEndMs, days, eventsByDay, hours]); + const scrollToFocus = useCallback(() => { const root = rootRef.current; if (!root) return; @@ -279,7 +298,7 @@ export function CalendarDayView({ }, []); const { - dragCreate, handleGridPointerDown, handleGridPointerMove, handleGridPointerUp, + dragCreate, handleGridPointerDown, handleGridPointerMove, handleGridPointerUp, handleGridPointerCancel, resizeVisual, handleResizePointerDown, handleResizePointerMove, handleResizePointerUp, quickCreate, handleSlotClick, handleSlotDoubleClick, handleQuickCreateSubmit, handleQuickCreateCancel, dropTarget, handleColumnDragOver, handleColumnDragLeave, handleColumnDrop, @@ -519,7 +538,7 @@ export function CalendarDayView({ const key = format(day, "yyyy-MM-dd"); const today = isDisplayToday(day); const dayLayout = layoutByDay.get(key); - const layouted = dayLayout?.layouts ?? []; + const layouted = (pendingLayout?.key === key ? pendingLayout.layouts : dayLayout?.layouts) ?? []; return (
handleGridPointerDown(e, key, day)} onPointerMove={handleGridPointerMove} onPointerUp={handleGridPointerUp} + onPointerCancel={handleGridPointerCancel} onDragOver={(e) => handleColumnDragOver(e, key)} onDragLeave={handleColumnDragLeave} onDrop={(e) => handleColumnDrop(e, day)} @@ -656,8 +676,11 @@ export function CalendarDayView({ {dragCreate?.dayKey === key && (
)} - {pendingPreview && !pendingPreview.allDay && isSameDay(pendingPreview.start, day) && ( + {pendingPreview && pendingLayout?.key === key && ( (() => { - const startMin = pendingPreview.start.getHours() * 60 + pendingPreview.start.getMinutes(); - const endMin = pendingPreview.end.getHours() * 60 + pendingPreview.end.getMinutes(); - const durationMin = Math.max(15, endMin - startMin); - if (startMin + durationMin <= hours.startMinutes || startMin >= hours.endMinutes) return null; - const clip = clipToDisplayHours(startMin, startMin + durationMin, hours); + const { startMinutes: startMin, endMinutes: endMin, column, totalColumns } = pendingLayout.pending; + if (endMin <= hours.startMinutes || startMin >= hours.endMinutes) return null; + const clip = clipToDisplayHours(startMin, endMin, hours); const cal = calendars.find(c => c.id === pendingPreview.calendarId); const color = paint(cal?.color || "#3b82f6"); - // Drawn like a saved event, so the new event shows where - // it will land while it is being created. + // Drawn like a saved event, in the column it will take, so the new + // event shows where it will land while it is being created. return (
-
- {pendingPreview.title} -
-
- {formatSnapTime(startMin, timeFormat)} – {formatSnapTime(startMin + durationMin, timeFormat)} +
+
+ {pendingPreview.title} +
+
+ {formatSnapTime(startMin, timeFormat)} – {formatSnapTime(endMin, timeFormat)} +
); diff --git a/components/calendar/calendar-week-view.tsx b/components/calendar/calendar-week-view.tsx index 7051e1963..c3467c334 100644 --- a/components/calendar/calendar-week-view.tsx +++ b/components/calendar/calendar-week-view.tsx @@ -12,7 +12,7 @@ import { QuickEventInput } from "./quick-event-input"; import { CalendarTaskChip } from "./task-chip"; import { AllHoursToggle, HiddenEventsIndicator } from "./display-hours-controls"; import { groupTasksByDueDay } from "@/lib/calendar-tasks"; -import { buildTimedFullDayWeekSegments, buildWeekSegmentsRaw, formatSnapTime, getEventDayBounds, getPrimaryCalendarId, isTimedEventFullDayOnDate, layoutOverlappingEvents, packWeekSegments } from "@/lib/calendar-utils"; +import { buildTimedFullDayWeekSegments, buildWeekSegmentsRaw, formatSnapTime, getEventDayBounds, getPrimaryCalendarId, isTimedEventFullDayOnDate, layoutOverlappingEvents, packWeekSegments, pendingTimedMinutes, PENDING_LAYOUT_ID } from "@/lib/calendar-utils"; import { clipToDisplayHours, indexOfDayOnOrAfter, partitionByDisplayHours, remapSegmentsToShownDays, resolveWorkingDays } from "@/lib/calendar-display-range"; import { displayNow, isDisplayToday } from "@/lib/timezone"; import type { CalendarEvent, Calendar, CalendarTask } from "@/lib/jmap/types"; @@ -238,6 +238,25 @@ export function CalendarWeekView({ return map; }, [days, timedEvents, hours]); + // The new event being created takes a column beside the events it + // overlaps, as it will once saved, instead of covering them. Only its + // times count: typing its title doesn't redo the layout. + const pendingStartMs = pendingPreview && !pendingPreview.allDay ? pendingPreview.start.getTime() : null; + const pendingEndMs = pendingPreview && !pendingPreview.allDay ? pendingPreview.end.getTime() : null; + const pendingLayout = useMemo(() => { + if (pendingStartMs === null || pendingEndMs === null) return null; + const preview = { start: new Date(pendingStartMs), end: new Date(pendingEndMs) }; + const day = days.find((d) => isSameDay(d, preview.start)); + const bounds = day ? pendingTimedMinutes(preview, day) : null; + if (!day || !bounds) return null; + const key = format(day, "yyyy-MM-dd"); + const partition = partitionByDisplayHours(timedEvents.get(key) || [], day, hours); + const all = layoutOverlappingEvents(partition.visible, day, bounds); + const pending = all.find((layout) => layout.event.id === PENDING_LAYOUT_ID); + if (!pending) return null; + return { key, layouts: all.filter((layout) => layout.event.id !== PENDING_LAYOUT_ID), pending }; + }, [pendingStartMs, pendingEndMs, days, timedEvents, hours]); + // Built over the consecutive days and then moved onto the drawn columns, // so an event across a hidden weekend still spans Friday to Monday. const allDaySegments = useMemo(() => { @@ -378,7 +397,7 @@ export function CalendarWeekView({ }, []); const { - dragCreate, handleGridPointerDown, handleGridPointerMove, handleGridPointerUp, + dragCreate, handleGridPointerDown, handleGridPointerMove, handleGridPointerUp, handleGridPointerCancel, resizeVisual, handleResizePointerDown, handleResizePointerMove, handleResizePointerUp, quickCreate, handleSlotClick, handleSlotDoubleClick, handleQuickCreateSubmit, handleQuickCreateCancel, dropTarget, handleColumnDragOver, handleColumnDragLeave, handleColumnDrop, @@ -664,7 +683,7 @@ export function CalendarWeekView({ const key = format(day, "yyyy-MM-dd"); const todayCol = isDisplayToday(day); const dayLayout = layoutByDay.get(key); - const layouted = dayLayout?.layouts ?? []; + const layouted = (pendingLayout?.key === key ? pendingLayout.layouts : dayLayout?.layouts) ?? []; return (
handleGridPointerDown(e, key, day)} onPointerMove={handleGridPointerMove} onPointerUp={handleGridPointerUp} + onPointerCancel={handleGridPointerCancel} onDragOver={(e) => handleColumnDragOver(e, key)} onDragLeave={handleColumnDragLeave} onDrop={(e) => handleColumnDrop(e, day)} @@ -801,8 +821,11 @@ export function CalendarWeekView({ {dragCreate?.dayKey === key && (
)} - {pendingPreview && !pendingPreview.allDay && isSameDay(pendingPreview.start, day) && ( + {pendingPreview && pendingLayout?.key === key && ( (() => { - const startMin = pendingPreview.start.getHours() * 60 + pendingPreview.start.getMinutes(); - let endMin = pendingPreview.end.getHours() * 60 + pendingPreview.end.getMinutes(); - if (endMin <= startMin) endMin = 1440; - const durationMin = Math.max(15, endMin - startMin); - if (startMin + durationMin <= hours.startMinutes || startMin >= hours.endMinutes) return null; - const clip = clipToDisplayHours(startMin, startMin + durationMin, hours); + const { startMinutes: startMin, endMinutes: endMin, column, totalColumns } = pendingLayout.pending; + if (endMin <= hours.startMinutes || startMin >= hours.endMinutes) return null; + const clip = clipToDisplayHours(startMin, endMin, hours); const cal = calendars.find(c => c.id === pendingPreview.calendarId); const color = paint(cal?.color || "#3b82f6"); - // Drawn like a saved event, so the new event shows where - // it will land while it is being created. + // Drawn like a saved event, in the column it will take, so the new + // event shows where it will land while it is being created. return (
-
- {pendingPreview.title} -
-
- {formatSnapTime(startMin, timeFormat)} – {formatSnapTime(startMin + durationMin, timeFormat)} +
+
+ {pendingPreview.title} +
+
+ {formatSnapTime(startMin, timeFormat)} – {formatSnapTime(endMin, timeFormat)} +
); diff --git a/lib/calendar-utils.ts b/lib/calendar-utils.ts index faff279c4..e63ff4176 100644 --- a/lib/calendar-utils.ts +++ b/lib/calendar-utils.ts @@ -1,4 +1,4 @@ -import { addDays, differenceInCalendarDays, parseISO, startOfDay, subMilliseconds } from "date-fns"; +import { addDays, differenceInCalendarDays, isSameDay, parseISO, startOfDay, subMilliseconds } from "date-fns"; import { parseDuration } from "@/lib/calendar-event-normalization"; import type { CalendarEvent } from "@/lib/jmap/types"; import { fromWallClock, isValidTimeZone, parseLocalDateTime, toDisplayDate } from "@/lib/timezone"; @@ -229,14 +229,49 @@ export function buildTimedFullDayWeekSegments(events: CalendarEvent[], weekDays: return packWeekSegments(rawSegments); } +/** + * The minutes the unsaved event being created covers on `day` in the week + * and day views, or null when it isn't a timed event starting that day. An + * end at or before the start is midnight. + */ +export function pendingTimedMinutes( + preview: { start: Date; end: Date; allDay?: boolean } | null | undefined, + day: Date, +): { startMinutes: number; endMinutes: number } | null { + if (!preview || preview.allDay || !isSameDay(preview.start, day)) return null; + const startMinutes = preview.start.getHours() * 60 + preview.start.getMinutes(); + let endMinutes = isSameDay(preview.end, day) ? preview.end.getHours() * 60 + preview.end.getMinutes() : 1440; + if (endMinutes <= startMinutes) endMinutes = 1440; + return { startMinutes, endMinutes: Math.max(startMinutes + 15, endMinutes) }; +} + +/** The id the unsaved event being created goes by in a day's layout. */ +export const PENDING_LAYOUT_ID = "__pending-event__"; + +/** + * A day's timed events in columns: each group of overlapping events shares + * the day's width. `pending` is the new event being created (its minutes on + * that day); it takes a column like a saved one, with the id + * PENDING_LAYOUT_ID, so it doesn't cover the events it overlaps. + */ export function layoutOverlappingEvents( events: CalendarEvent[], day: Date, + pending?: { startMinutes: number; endMinutes: number } | null, ): TimedEventLayout[] { const layoutInputs = events.flatMap((event) => { const bounds = getTimedEventBoundsForDay(event, day); return bounds ? [{ event, ...bounds }] : []; }); + if (pending) { + layoutInputs.push({ + event: { id: PENDING_LAYOUT_ID } as CalendarEvent, + startMinutes: pending.startMinutes, + endMinutes: Math.max(pending.startMinutes + 15, pending.endMinutes), + continuesBefore: false, + continuesAfter: false, + }); + } const sorted = layoutInputs.sort((a, b) => { const diff = a.startMinutes - b.startMinutes; From bc2da09be58adaf1a2a66cfab937871656a018df Mon Sep 17 00:00:00 2001 From: Linus Rath <139418639+rathlinus@users.noreply.github.com> Date: Wed, 4 Nov 2026 17:47:25 +0100 Subject: [PATCH 3/5] feat: save a quick event without a title as "(No title)" --- .../calendar/__tests__/calendar-app.test.tsx | 15 +++++++++++++++ components/calendar/calendar-app.tsx | 11 +++++++---- components/calendar/quick-create-popover.tsx | 3 ++- 3 files changed, 24 insertions(+), 5 deletions(-) diff --git a/components/calendar/__tests__/calendar-app.test.tsx b/components/calendar/__tests__/calendar-app.test.tsx index f02537e85..3819a6c36 100644 --- a/components/calendar/__tests__/calendar-app.test.tsx +++ b/components/calendar/__tests__/calendar-app.test.tsx @@ -595,6 +595,21 @@ describe('CalendarApp task feedback', () => { }); }); +describe('CalendarApp quick editor', () => { + // Usability report 2026-11-04: Save stayed off until a title was typed. + // Google Calendar saves "(No title)"; so does the quick editor now. + it('saves an event without a title as "(No title)"', async () => { + renderApp(); + fireEvent.click(slots()[3]); + const quick = await screen.findByRole('dialog', { name: 'quick_create.aria_label' }, { timeout: 2000 }); + const save = within(quick).getByRole('button', { name: 'form.save' }); + expect(save).toBeEnabled(); + fireEvent.click(save); + await waitFor(() => expect(store.createEvent).toHaveBeenCalledTimes(1)); + expect(store.createEvent.mock.calls[0][1]).toMatchObject({ title: 'events.no_title', showWithoutTime: false }); + }); +}); + describe('CalendarApp creating in the month view', () => { it('opens the quick editor for an all-day event on a single click', async () => { setUp([], 'month'); diff --git a/components/calendar/calendar-app.tsx b/components/calendar/calendar-app.tsx index 9bda4c125..1a47f33d7 100644 --- a/components/calendar/calendar-app.tsx +++ b/components/calendar/calendar-app.tsx @@ -1287,12 +1287,15 @@ export function CalendarApp({ linkSegments: routeSegments }: CalendarAppProps = const handleQuickCreateSave = useCallback(async () => { if (!quickDraft) return; - const { start, end, title, calendarId, allDay } = quickDraft; + const { start, end, calendarId, allDay } = quickDraft; + // Saving without a title is allowed, as in Google Calendar: the event + // is called "(No title)" in the user's language. + const title = quickDraft.title.trim() || t("events.no_title"); if (allDay) { setQuickDraft(null); await handleSaveEvent({ uid: generateUUID(), - title: title.trim(), + title, start: format(start, "yyyy-MM-dd'T'00:00:00"), duration: "P1D", timeZone: null, @@ -1313,7 +1316,7 @@ export function CalendarApp({ linkSegments: routeSegments }: CalendarAppProps = // as the full editor's fields, so they are labelled with that zone. await handleSaveEvent({ uid: generateUUID(), - title: title.trim(), + title, start: format(start, "yyyy-MM-dd'T'HH:mm:ss"), duration, timeZone: getEffectiveTimeZone(), @@ -1323,7 +1326,7 @@ export function CalendarApp({ linkSegments: routeSegments }: CalendarAppProps = freeBusyStatus: "busy", privacy: "public", }); - }, [quickDraft, handleSaveEvent]); + }, [quickDraft, handleSaveEvent, t]); // While the quick editor is open its placeholder takes the preview slot. const gridPreview = useMemo(() => { diff --git a/components/calendar/quick-create-popover.tsx b/components/calendar/quick-create-popover.tsx index 913afae41..87f969096 100644 --- a/components/calendar/quick-create-popover.tsx +++ b/components/calendar/quick-create-popover.tsx @@ -148,7 +148,8 @@ export function QuickCreatePopover({ }; }, [onClose]); - const canSave = draft.title.trim().length > 0 && !!draft.calendarId; + // An empty title saves as "(No title)", as in Google Calendar. + const canSave = !!draft.calendarId; const handleSubmit = useCallback((e: React.FormEvent) => { e.preventDefault(); if (canSave) onSave(); From 62f1ffb690f596e6c835fb5be43ac3932b2763e9 Mon Sep 17 00:00:00 2001 From: Linus Rath <139418639+rathlinus@users.noreply.github.com> Date: Wed, 4 Nov 2026 17:48:27 +0100 Subject: [PATCH 4/5] feat: create an event over several days by dragging across them in the month view --- .../calendar/__tests__/calendar-app.test.tsx | 64 ++++ .../calendar-month-view-drag-create.test.tsx | 267 +++++++++++++++++ components/calendar/calendar-app.tsx | 21 +- components/calendar/calendar-month-view.tsx | 110 ++++++- components/calendar/quick-create-popover.tsx | 13 +- hooks/use-month-range-select.ts | 283 ++++++++++++++++++ locales/ar/common.json | 5 + locales/ca/common.json | 5 + locales/cs/common.json | 5 + locales/da/common.json | 5 + locales/de/common.json | 5 + locales/en/common.json | 5 + locales/es/common.json | 5 + locales/et/common.json | 5 + locales/fa/common.json | 5 + locales/fr/common.json | 5 + locales/he/common.json | 5 + locales/hu/common.json | 5 + locales/it/common.json | 5 + locales/ja/common.json | 5 + locales/ko/common.json | 5 + locales/lv/common.json | 5 + locales/mn/common.json | 5 + locales/nb/common.json | 5 + locales/nl/common.json | 5 + locales/pl/common.json | 5 + locales/pt/common.json | 5 + locales/ro/common.json | 5 + locales/ru/common.json | 5 + locales/sk/common.json | 5 + locales/th/common.json | 5 + locales/tr/common.json | 5 + locales/uk/common.json | 5 + locales/vi/common.json | 5 + locales/zh-TW/common.json | 5 + locales/zh/common.json | 5 + 36 files changed, 888 insertions(+), 20 deletions(-) create mode 100644 components/calendar/__tests__/calendar-month-view-drag-create.test.tsx create mode 100644 hooks/use-month-range-select.ts diff --git a/components/calendar/__tests__/calendar-app.test.tsx b/components/calendar/__tests__/calendar-app.test.tsx index 3819a6c36..d9323df6f 100644 --- a/components/calendar/__tests__/calendar-app.test.tsx +++ b/components/calendar/__tests__/calendar-app.test.tsx @@ -626,6 +626,70 @@ describe('CalendarApp creating in the month view', () => { }); }); + // Usability report 2026-11-04: a drag over the month's days did nothing. + it('opens the quick editor for the days a drag picked and saves them as one all-day event', async () => { + setUp([], 'month'); + renderApp(); + // Thursday 15 to Tuesday 20 October, across two week rows. + const thursday = monthCell(/October 15, 2026/)!; + const tuesday = monthCell(/October 20, 2026/)!; + thursday.closest('[data-week]')!.getBoundingClientRect = () => ({ top: 0, bottom: 100, left: 0, right: 700 }) as DOMRect; + tuesday.closest('[data-week]')!.getBoundingClientRect = () => ({ top: 100, bottom: 200, left: 0, right: 700 }) as DOMRect; + thursday.getBoundingClientRect = () => ({ top: 0, bottom: 100, left: 300, right: 400 }) as DOMRect; + tuesday.getBoundingClientRect = () => ({ top: 100, bottom: 200, left: 100, right: 200 }) as DOMRect; + const mouse = { pointerId: 1, pointerType: 'mouse', isPrimary: true, button: 0 }; + fireEvent.pointerDown(thursday, { ...mouse, clientX: 350, clientY: 80 }); + fireEvent.pointerMove(thursday, { ...mouse, clientX: 150, clientY: 180 }); + fireEvent.pointerUp(thursday, { ...mouse, clientX: 150, clientY: 180 }); + + const quick = await screen.findByRole('dialog', { name: 'quick_create.aria_label' }); + expect(within(quick).getByText('events.all_day')).toBeInTheDocument(); + expect(within(quick).getByText(/Oct 15 2026.* – .*Oct 20 2026/)).toBeInTheDocument(); + // No title needed: it saves as "(No title)". + const save = within(quick).getByRole('button', { name: 'form.save' }); + expect(save).toBeEnabled(); + fireEvent.click(save); + await waitFor(() => expect(store.createEvent).toHaveBeenCalledTimes(1)); + expect(store.createEvent.mock.calls[0][1]).toMatchObject({ + title: 'events.no_title', start: '2026-10-15T00:00:00', duration: 'P6D', showWithoutTime: true, calendarIds: { cal: true }, + }); + }); + + it('opens the full editor on the same days from "More options"', async () => { + setUp([], 'month'); + renderApp(); + const thursday = monthCell(/October 15, 2026/)!; + const friday = monthCell(/October 16, 2026/)!; + thursday.closest('[data-week]')!.getBoundingClientRect = () => ({ top: 0, bottom: 100, left: 0, right: 700 }) as DOMRect; + thursday.getBoundingClientRect = () => ({ top: 0, bottom: 100, left: 300, right: 400 }) as DOMRect; + friday.getBoundingClientRect = () => ({ top: 0, bottom: 100, left: 400, right: 500 }) as DOMRect; + const mouse = { pointerId: 1, pointerType: 'mouse', isPrimary: true, button: 0 }; + fireEvent.pointerDown(thursday, { ...mouse, clientX: 350, clientY: 80 }); + fireEvent.pointerMove(thursday, { ...mouse, clientX: 450, clientY: 80 }); + fireEvent.pointerUp(thursday, { ...mouse, clientX: 450, clientY: 80 }); + const quick = await screen.findByRole('dialog', { name: 'quick_create.aria_label' }); + fireEvent.click(within(quick).getByRole('button', { name: 'quick_create.more_options' })); + const dates = await waitFor(() => { + const found = Array.from(document.querySelectorAll('input[type="date"]')).map((input) => input.value); + expect(found.length).toBeGreaterThan(1); + return found; + }); + expect(dates.slice(0, 2)).toEqual(['2026-10-15', '2026-10-16']); + }); + + it('offers no new event in the month view without a calendar that can take one', () => { + setUp([], 'month'); + useCalendarStore.setState({ + calendars: [{ ...calendars[0], myRights: { ...RIGHTS, mayWriteAll: false, mayWriteOwn: false } }], + } as never); + renderApp(); + const day = monthCell(/October 15, 2026/)!; + fireEvent.click(day); + fireEvent.keyDown(day.querySelector('[data-day-button]')!, { key: 'ArrowRight', shiftKey: true }); + expect(screen.queryByRole('dialog', { name: 'quick_create.aria_label' })).toBeNull(); + expect(day.closest('[role="grid"]')!.getAttribute('aria-multiselectable')).toBeNull(); + }); + it('opens the day on a phone tap instead', () => { media.mobile = true; media.desktop = false; diff --git a/components/calendar/__tests__/calendar-month-view-drag-create.test.tsx b/components/calendar/__tests__/calendar-month-view-drag-create.test.tsx new file mode 100644 index 000000000..f87ee1e85 --- /dev/null +++ b/components/calendar/__tests__/calendar-month-view-drag-create.test.tsx @@ -0,0 +1,267 @@ +import { render, fireEvent, cleanup, act, screen } from '@testing-library/react'; +import { describe, it, expect, vi, afterEach, beforeEach, beforeAll } from 'vitest'; +import type { CalendarEvent, Calendar } from '@/lib/jmap/types'; + +// Usability report 2026-11-04: in the month view a drag over the days did +// nothing. It now picks days, as in Google Calendar and Outlook, and opens +// the quick editor for an all-day event over them. + +const announce = vi.hoisted(() => vi.fn()); +vi.mock('@/lib/announce', async (importOriginal) => ({ + ...(await importOriginal()), + announce, +})); + +import { CalendarMonthView } from '../calendar-month-view'; + +const calendars = [{ id: 'cal-1', name: 'Work', color: '#123456' }] as unknown as Calendar[]; +const standup = { + id: 'e1', '@type': 'Event', uid: 'e1', title: 'Standup', start: '2026-11-05T00:00:00', duration: 'P1D', + showWithoutTime: true, calendarIds: { 'cal-1': true }, +} as unknown as CalendarEvent; + +type Props = React.ComponentProps; + +function renderMonth(overrides: Partial = {}) { + const props: Props = { + focus: { date: new Date(2026, 10, 4), nonce: 0 }, + windowKey: 'month:2026-11-04', + // Monday 2 Nov to Sunday 22 Nov 2026: three week rows. + rangeStart: new Date(2026, 10, 2), + rangeEnd: new Date(2026, 10, 22), + selectedDate: new Date(2026, 10, 4), + events: [standup], + calendars, + onSelectDate: vi.fn(), + onSelectEvent: vi.fn(), + onCreateAllDay: vi.fn(), + onCreateRange: vi.fn(), + onOpenDay: vi.fn(), + onContextMenuEmpty: vi.fn(), + ...overrides, + }; + const view = render(); + layOut(props.isMobile ? false : document.documentElement.dir === 'rtl'); + return { props, ...view }; +} + +/** + * jsdom lays nothing out: give the week rows and day cells the boxes a + * 700 px wide grid has (100 px per day and row), mirrored in a + * right-to-left grid. + */ +function layOut(rtl: boolean) { + const box = (left: number, top: number, width: number, height: number) => + () => ({ left, top, right: left + width, bottom: top + height, width, height, x: left, y: top, toJSON() {} }) as DOMRect; + document.querySelectorAll('[data-week]').forEach((row, r) => { + row.getBoundingClientRect = box(0, r * 100, 700, 100); + row.querySelectorAll('[data-month-day]').forEach((cell, c) => { + cell.getBoundingClientRect = box((rtl ? 6 - c : c) * 100, r * 100, 100, 100); + }); + }); +} + +const cell = (key: string) => document.querySelector(`[data-month-day="${key}"]`)!; +/** The middle of a day's box, in the layout above. */ +function pointOf(key: string) { + const rect = cell(key).getBoundingClientRect(); + return { clientX: rect.left + 50, clientY: rect.top + 80 }; +} +const picked = () => Array.from(document.querySelectorAll('[data-month-day][aria-selected="true"]')).map((el) => el.getAttribute('data-month-day')); + +const mouse = { pointerId: 1, pointerType: 'mouse', isPrimary: true, button: 0 }; +function drag(from: string, to: string, via: string[] = [], release = true) { + const grid = cell(from); + fireEvent.pointerDown(grid, { ...mouse, ...pointOf(from) }); + for (const key of [...via, to]) fireEvent.pointerMove(grid, { ...mouse, ...pointOf(key) }); + if (release) fireEvent.pointerUp(grid, { ...mouse, ...pointOf(to) }); +} + +beforeAll(() => { + Element.prototype.setPointerCapture ??= () => {}; + Element.prototype.releasePointerCapture ??= () => {}; +}); +beforeEach(() => announce.mockClear()); +afterEach(() => { + cleanup(); + document.documentElement.dir = ''; + vi.useRealTimers(); +}); + +describe('Month view: dragging over days', () => { + it('picks the days in reading order across week rows and creates over them', () => { + const { props } = renderMonth(); + drag('2026-11-05', '2026-11-10', ['2026-11-06', '2026-11-09'], false); + // Thursday to next Tuesday, wrapping at the end of the row; the + // selected day (Wednesday 4th) keeps its own mark. + expect(picked()).toEqual(['2026-11-04', '2026-11-05', '2026-11-06', '2026-11-07', '2026-11-08', '2026-11-09', '2026-11-10']); + expect(cell('2026-11-07').className).toContain('bg-primary/15'); + fireEvent.pointerUp(cell('2026-11-05'), { ...mouse, ...pointOf('2026-11-10') }); + + expect(props.onCreateRange).toHaveBeenCalledTimes(1); + expect(props.onCreateRange).toHaveBeenCalledWith(new Date(2026, 10, 5), new Date(2026, 10, 10)); + expect(props.onCreateAllDay).not.toHaveBeenCalled(); + }); + + it('works backwards too', () => { + const { props } = renderMonth(); + drag('2026-11-10', '2026-11-05', ['2026-11-09', '2026-11-06']); + expect(props.onCreateRange).toHaveBeenCalledWith(new Date(2026, 10, 5), new Date(2026, 10, 10)); + }); + + it('mirrors in a right-to-left grid: the day to the left is the next one', () => { + document.documentElement.dir = 'rtl'; + const { props } = renderMonth(); + // Thursday 5th sits at x 200-300; Saturday 7th to its left at 0-100. + expect(pointOf('2026-11-07').clientX).toBeLessThan(pointOf('2026-11-05').clientX); + drag('2026-11-05', '2026-11-07'); + expect(props.onCreateRange).toHaveBeenCalledWith(new Date(2026, 10, 5), new Date(2026, 10, 7)); + }); + + it('leaves a click on the empty space of a day to the click: one all-day event there', () => { + const { props } = renderMonth(); + const day = cell('2026-11-12'); + fireEvent.pointerDown(day, { ...mouse, ...pointOf('2026-11-12') }); + fireEvent.pointerUp(day, { ...mouse, ...pointOf('2026-11-12') }); + fireEvent.click(day); + expect(props.onCreateRange).not.toHaveBeenCalled(); + expect(props.onCreateAllDay).toHaveBeenCalledWith(new Date(2026, 10, 12)); + }); + + it("doesn't count the click that ends a drag as a click on the last day", () => { + const { props } = renderMonth(); + drag('2026-11-12', '2026-11-13'); + fireEvent.click(cell('2026-11-13')); + expect(props.onCreateRange).toHaveBeenCalledTimes(1); + expect(props.onCreateAllDay).not.toHaveBeenCalled(); + }); + + it('starts nothing from an event bar, the date number or "+N more"', () => { + // Six events on the 12th: some go under "+N more". + const busy = Array.from({ length: 6 }, (_, i) => ({ ...standup, id: `b${i}`, uid: `b${i}`, title: `Busy ${i}`, start: '2026-11-12T00:00:00' })); + const { props } = renderMonth({ events: [standup, ...busy] }); + const bar = screen.getByRole('button', { name: /Standup/ }); + const dateNumber = cell('2026-11-12').querySelector('[data-day-button]')!; + const more = screen.getByText('events.more'); + for (const target of [bar, dateNumber, more]) { + fireEvent.pointerDown(target, { ...mouse, ...pointOf('2026-11-05') }); + fireEvent.pointerMove(target, { ...mouse, ...pointOf('2026-11-06') }); + fireEvent.pointerUp(target, { ...mouse, ...pointOf('2026-11-06') }); + } + expect(props.onCreateRange).not.toHaveBeenCalled(); + expect(picked()).toEqual(['2026-11-04']); + }); + + it('picks nothing where no calendar can take a new event', () => { + const { props } = renderMonth({ onCreateRange: undefined, onCreateAllDay: undefined }); + drag('2026-11-05', '2026-11-10', ['2026-11-06'], false); + expect(picked()).toEqual(['2026-11-04']); + fireEvent.pointerUp(cell('2026-11-05'), { ...mouse, ...pointOf('2026-11-10') }); + expect(props.onOpenDay).not.toHaveBeenCalled(); + }); + + it('reads the days out while they are picked', async () => { + renderMonth(); + drag('2026-11-05', '2026-11-10', [], false); + expect(announce).toHaveBeenLastCalledWith( + expect.stringMatching(/^selected_range$/), + expect.objectContaining({ key: 'calendar-month-selection' }), + ); + }); + + it('marks the days of the quick editor and spans its placeholder over them', () => { + renderMonth({ + pendingPreview: { start: new Date(2026, 10, 5), end: new Date(2026, 10, 10), title: 'Trip', allDay: true, calendarId: 'cal-1' }, + }); + expect(picked()).toEqual(['2026-11-04', '2026-11-05', '2026-11-06', '2026-11-07', '2026-11-08', '2026-11-09', '2026-11-10']); + const bars = Array.from(document.querySelectorAll('[data-pending-preview]')); + // Thursday to Sunday in the first row, Monday and Tuesday in the next. + expect(bars.map((bar) => bar.closest('[data-month-day]')!.getAttribute('data-month-day'))).toEqual(['2026-11-05', '2026-11-09']); + expect(bars.map((bar) => (bar.parentElement as HTMLElement).style.width)).toEqual(['calc(400% + 2px)', 'calc(200% + 0px)']); + }); +}); + +describe('Month view: picking days by keyboard', () => { + const key = (el: HTMLElement, k: string, shiftKey = false) => fireEvent.keyDown(el, { key: k, shiftKey }); + const dateButton = (day: string) => cell(day).querySelector('[data-day-button]')!; + + it('grows the selection with Shift+arrows and creates over it with Enter', () => { + const { props } = renderMonth(); + key(dateButton('2026-11-04'), 'ArrowRight', true); + key(dateButton('2026-11-05'), 'ArrowDown', true); + expect(picked()).toEqual(expect.arrayContaining(['2026-11-04', '2026-11-05', '2026-11-08', '2026-11-12'])); + expect(announce).toHaveBeenLastCalledWith('selected_range enter_hint', expect.anything()); + key(dateButton('2026-11-12'), 'Enter'); + expect(props.onCreateRange).toHaveBeenCalledWith(new Date(2026, 10, 4), new Date(2026, 10, 12)); + expect(props.onOpenDay).not.toHaveBeenCalled(); + }); + + it('keeps Enter opening the day without a selection, and Escape drops one', () => { + const { props } = renderMonth(); + key(dateButton('2026-11-04'), 'ArrowRight', true); + key(dateButton('2026-11-05'), 'Escape'); + expect(picked()).toEqual(['2026-11-04']); + const enter = fireEvent.keyDown(dateButton('2026-11-05'), { key: 'Enter' }); + expect(enter).toBe(true); + expect(props.onCreateRange).not.toHaveBeenCalled(); + }); + + it('drops the selection on a plain arrow', () => { + const { props } = renderMonth(); + key(dateButton('2026-11-04'), 'ArrowRight', true); + key(dateButton('2026-11-05'), 'ArrowRight'); + key(dateButton('2026-11-06'), 'Enter'); + expect(props.onCreateRange).not.toHaveBeenCalled(); + }); +}); + +describe('Month view: picking days on a touch screen', () => { + const finger = { pointerId: 7, pointerType: 'touch', isPrimary: true, button: 0 }; + + it('starts after a long press, then follows the finger', () => { + vi.useFakeTimers(); + const { props } = renderMonth(); + const start = cell('2026-11-05'); + fireEvent.pointerDown(start, { ...finger, ...pointOf('2026-11-05') }); + act(() => { vi.advanceTimersByTime(500); }); + expect(picked()).toContain('2026-11-05'); + fireEvent.pointerMove(start, { ...finger, ...pointOf('2026-11-12') }); + // The grid doesn't scroll under a finger picking days. + const move = new Event('touchmove', { cancelable: true, bubbles: true }); + start.dispatchEvent(move); + expect(move.defaultPrevented).toBe(true); + fireEvent.pointerUp(start, { ...finger, ...pointOf('2026-11-12') }); + expect(props.onCreateRange).toHaveBeenCalledWith(new Date(2026, 10, 5), new Date(2026, 10, 12)); + // The long press's own menu doesn't open over the new event. + fireEvent.contextMenu(start); + expect(props.onContextMenuEmpty).not.toHaveBeenCalled(); + }); + + it('lets a swipe scroll: nothing is picked', () => { + vi.useFakeTimers(); + const { props } = renderMonth(); + const start = cell('2026-11-05'); + fireEvent.pointerDown(start, { ...finger, ...pointOf('2026-11-05') }); + fireEvent.pointerMove(start, { ...finger, clientX: 150, clientY: 140 }); + act(() => { vi.advanceTimersByTime(500); }); + const move = new Event('touchmove', { cancelable: true, bubbles: true }); + start.dispatchEvent(move); + expect(move.defaultPrevented).toBe(false); + fireEvent.pointerUp(start, { ...finger, ...pointOf('2026-11-12') }); + expect(picked()).toEqual(['2026-11-04']); + expect(props.onCreateRange).not.toHaveBeenCalled(); + }); + + it('keeps the long-press menu of a single day', () => { + vi.useFakeTimers(); + const { props } = renderMonth(); + const start = cell('2026-11-05'); + fireEvent.pointerDown(start, { ...finger, ...pointOf('2026-11-05') }); + act(() => { vi.advanceTimersByTime(500); }); + fireEvent.contextMenu(start); + expect(props.onContextMenuEmpty).not.toHaveBeenCalled(); + fireEvent.pointerUp(start, { ...finger, ...pointOf('2026-11-05') }); + expect(props.onCreateRange).not.toHaveBeenCalled(); + expect(props.onContextMenuEmpty).toHaveBeenCalledWith(expect.anything(), new Date(2026, 10, 5), undefined, true); + }); +}); diff --git a/components/calendar/calendar-app.tsx b/components/calendar/calendar-app.tsx index 1a47f33d7..2b3232029 100644 --- a/components/calendar/calendar-app.tsx +++ b/components/calendar/calendar-app.tsx @@ -7,7 +7,7 @@ import { useTranslations } from "next-intl"; import { Plus, ListTodo, CalendarDays, Upload, Globe, RefreshCw, Search } from "@/components/icons"; import { addMonths, subMonths, addWeeks, subWeeks, addDays, subDays, - format, parseISO, startOfWeek, + differenceInCalendarDays, format, parseISO, startOfWeek, } from "date-fns"; import { useCalendarStore } from "@/stores/calendar-store"; import { isCalendarViewMode, type CalendarViewMode } from "@/stores/calendar-store"; @@ -1267,6 +1267,18 @@ export function CalendarApp({ linkSegments: routeSegments }: CalendarAppProps = handleGridCreate(start, start, true); }, [handleGridCreate]); + // Days picked in the month view: an all-day event from the first to the + // last, in the same quick editor. Not offered without a calendar that can + // take it (read-only and subscribed ones only). + const canCreateEvents = writableCalendars.length > 0; + const handleGridCreateDays = useCallback((first: Date, last: Date) => { + const start = new Date(first); + start.setHours(0, 0, 0, 0); + const end = new Date(last); + end.setHours(0, 0, 0, 0); + handleGridCreate(start, end, true); + }, [handleGridCreate]); + const closeQuickCreate = useCallback(() => setQuickDraft(null), []); // The create button and `n` make what the view shows: a task in Tasks. @@ -1293,11 +1305,13 @@ export function CalendarApp({ linkSegments: routeSegments }: CalendarAppProps = const title = quickDraft.title.trim() || t("events.no_title"); if (allDay) { setQuickDraft(null); + // Every day from the first to the last one picked (a drag in the month view). + const days = Math.max(1, differenceInCalendarDays(end, start) + 1); await handleSaveEvent({ uid: generateUUID(), title, start: format(start, "yyyy-MM-dd'T'00:00:00"), - duration: "P1D", + duration: `P${days}D`, timeZone: null, showWithoutTime: true, calendarIds: { [calendarId]: true }, @@ -1985,7 +1999,8 @@ export function CalendarApp({ linkSegments: routeSegments }: CalendarAppProps = onContextMenuEvent={handleContextMenuEvent} onContextMenuEmpty={handleContextMenuEmpty} onReplyEvent={handleReplyEvent} - onCreateAllDay={handleGridCreateAllDay} + onCreateAllDay={canCreateEvents ? handleGridCreateAllDay : undefined} + onCreateRange={canCreateEvents ? handleGridCreateDays : undefined} firstDayOfWeek={firstDayOfWeek} isMobile={isMobile} pendingPreview={gridPreview} diff --git a/components/calendar/calendar-month-view.tsx b/components/calendar/calendar-month-view.tsx index 6ad3d854a..c5c4ef7a8 100644 --- a/components/calendar/calendar-month-view.tsx +++ b/components/calendar/calendar-month-view.tsx @@ -1,8 +1,8 @@ "use client"; -import { useMemo, useState, useCallback, useRef, useLayoutEffect, type DragEvent } from "react"; +import { useMemo, useState, useCallback, useEffect, useRef, useLayoutEffect, type DragEvent } from "react"; import { useTranslations } from "next-intl"; -import { format, parseISO, eachDayOfInterval, addDays, isSameDay } from "date-fns"; +import { format, parseISO, eachDayOfInterval, addDays, isSameDay, differenceInCalendarDays, startOfDay } from "date-fns"; import { cn } from "@/lib/utils"; import { EventCard } from "./event-card"; import { CalendarTaskChip } from "./task-chip"; @@ -26,6 +26,8 @@ import { useDisplayDateFormatter } from "@/hooks/use-display-date-formatter"; import type { MoveEventHandler } from "@/hooks/use-time-grid-interactions"; import { useCvdColor } from "@/hooks/use-cvd-color"; import { useEventUserEmails } from "@/hooks/use-event-user-emails"; +import { isInMonthRange, useMonthRangeSelect, type MonthRange } from "@/hooks/use-month-range-select"; +import { announce } from "@/lib/announce"; interface CalendarMonthViewProps extends ScrollWindowViewProps { selectedDate: Date; @@ -41,6 +43,12 @@ interface CalendarMonthViewProps extends ScrollWindowViewProps { onReplyEvent?: (anchor: HTMLElement, event: CalendarEvent) => void; /** A click on a day's empty space: a new all-day event there (wide screens). */ onCreateAllDay?: (date: Date) => void; + /** + * Days picked by a drag over empty day space, a long press and drag on + * touch, or Shift+arrows and Enter: a new all-day event over them. Left + * out where no calendar can take a new event. + */ + onCreateRange?: (start: Date, end: Date) => void; /** Open a day in the day view (its date number, or its "N more" link). */ onOpenDay?: (date: Date) => void; firstDayOfWeek?: number; @@ -162,6 +170,7 @@ export function CalendarMonthView({ onContextMenuEmpty, onReplyEvent, onCreateAllDay, + onCreateRange, onOpenDay, isMobile, pendingPreview, @@ -174,6 +183,7 @@ export function CalendarMonthView({ onMoveEvent, }: CalendarMonthViewProps) { const t = useTranslations("calendar"); + const tSelect = useTranslations("calendar_month_select"); const paint = useCvdColor(); const describeError = useCalendarErrorMessage(); // An event of another signed-in login is read with that login's addresses. @@ -271,6 +281,36 @@ export function CalendarMonthView({ const topSentinelRef = useRef(null); const bottomSentinelRef = useRef(null); + // Picking days to create an event over them (drag, long press, Shift+arrows). + const rangeSelect = useMonthRangeSelect({ + scrollRef, + enabled: !!onCreateRange, + onCreateRange: (start, end) => onCreateRange?.(start, end), + onContextMenuDay: onContextMenuEmpty ? (e, day) => onContextMenuEmpty(e, day, undefined, true) : undefined, + }); + // The days stay marked while the quick editor for them is open; Escape + // or a click elsewhere closes it and the mark goes with it. + const draftRange = useMemo(() => { + if (!pendingPreview?.allDay) return null; + const start = startOfDay(pendingPreview.start); + const end = startOfDay(pendingPreview.end); + return end < start ? { start, end: start } : { start, end }; + }, [pendingPreview?.allDay, pendingPreview?.start, pendingPreview?.end]); + const highlight = rangeSelect.selection ?? draftRange; + const picking = rangeSelect.selection; + const announcement = picking + ? [ + isSameDay(picking.start, picking.end) + ? tSelect("selected_day", { day: formatFullDate(picking.start) }) + : tSelect("selected_range", { start: formatFullDate(picking.start), end: formatFullDate(picking.end) }), + picking.keyboard ? tSelect("enter_hint") : "", + ].join(" ").trim() + : ""; + // The days picked, read out as they change (the last of a quick run). + useEffect(() => { + if (announcement) announce(announcement, { key: "calendar-month-selection", debounceMs: 250 }); + }, [announcement]); + // Six rows fill the viewport, as a single month used to; taller rows grow // with their chips. const [viewportHeight, setViewportHeight] = useState(0); @@ -420,8 +460,21 @@ export function CalendarMonthView({ const focusKey = dayKey(focus.date); return keys.has(focusKey) ? focusKey : (weeks[0]?.[0] ? dayKey(weeks[0][0]) : selectedKey); }, [weeks, selectedKey, focus.date]); + const { extendTo, commitKeyboard, clearKeyboard } = rangeSelect; const handleDayKeyDown = useCallback((e: React.KeyboardEvent, day: Date, dayIndex: number) => { - if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) return; + if (e.altKey || e.ctrlKey || e.metaKey) return; + // Enter over days picked with Shift+arrows creates there; without + // them it opens the day, as before. + if (e.key === "Enter" && !e.shiftKey && commitKeyboard()) { + e.preventDefault(); + return; + } + if (e.key === "Escape" && clearKeyboard()) { + e.preventDefault(); + e.stopPropagation(); + return; + } + if (e.shiftKey && !onCreateRange) return; const rtl = getComputedStyle(e.currentTarget).direction === "rtl"; let delta: number; switch (e.key) { @@ -438,9 +491,11 @@ export function CalendarMonthView({ const next = addDays(day, delta); const target = scrollRef.current?.querySelector(`[data-day-button="${dayKey(next)}"]`); if (!target) return; + if (e.shiftKey) extendTo(day, next); + else clearKeyboard(); onSelectDate(next); target.focus(); - }, [onSelectDate]); + }, [onSelectDate, onCreateRange, extendTo, commitKeyboard, clearKeyboard]); const [dropDayKey, setDropDayKey] = useState(null); @@ -484,13 +539,20 @@ export function CalendarMonthView({ }, [t, describeError, userEmailsFor, onMoveEvent]); return ( -
+
list.length), rowCapacity, moreInHeader) : null; const hiddenPerDay = fit?.hidden ?? null; // Rows that grow with their content make room for the new event's preview. - const previewRows = !capRows && pendingPreview && week.some((day) => checkIsSameDay(pendingPreview.start, day)) ? 1 : 0; + const previewRows = !capRows && pendingPreview && week.some((day) => checkIsSameDay(pendingPreview.start, day) || isInMonthRange(day, draftRange)) ? 1 : 0; return (
0 ? week[dayIndex - 1] : addDays(day, -1); const firstOfMonth = !checkIsSameMonth(day, previous); + const picked = isInMonthRange(day, highlight); return (
{ + // The end of a drag over days, not a click on this one. + if (rangeSelect.wasDragging.current) return; onSelectDate(day); // On phones a tap opens the day instead. if (!isMobile) onCreateAllDay?.(day); @@ -550,7 +616,8 @@ export function CalendarMonthView({ !inMonth && "bg-muted/30", "hover:bg-muted/50", selected && isMobile && "bg-primary/10", - dropDayKey === key && "ring-2 ring-inset ring-primary bg-primary/10" + dropDayKey === key && "ring-2 ring-inset ring-primary bg-primary/10", + picked && "bg-primary/15 hover:bg-primary/15" )} >
@@ -649,6 +716,7 @@ export function CalendarMonthView({ isMobile={isMobile} calendarMap={calendarMap} pendingPreview={pendingPreview} + draftRange={draftRange} lastRow={capRows ? rowCapacity - 1 : Infinity} selectedEventId={selectedEventId} currentUserEmails={currentUserEmails} @@ -693,7 +761,7 @@ type WeekSegment = ReturnType[number]; */ function MonthCellEntries({ dayIndex, week, segments, rowLimit, isShown, rowCount, dayEventRows, dayTasks, hidden, overlayTop, rowHeight, chipHeight, - isMobile, calendarMap, pendingPreview, lastRow, selectedEventId, currentUserEmails, canEditEvent, inView, timedStyle, + isMobile, calendarMap, pendingPreview, draftRange, lastRow, selectedEventId, currentUserEmails, canEditEvent, inView, timedStyle, onSelectEvent, onHoverEvent, onHoverLeave, onContextMenuEvent, onReplyEvent, onToggleTaskComplete, onSelectTask, onShowMore, moreLabel, moreInHeader = false, paint, }: { dayIndex: number; @@ -713,6 +781,8 @@ function MonthCellEntries({ isMobile?: boolean; calendarMap: Map; pendingPreview?: PendingEventPreview | null; + /** The days of a new all-day event being created: its bar spans them. */ + draftRange?: MonthRange | null; /** The last row a fixed-height week has room for; the preview must not go past it. */ lastRow: number; selectedEventId?: string | null; @@ -746,13 +816,25 @@ function MonthCellEntries({ // A click, double click or right-click on an entry is the entry's, not a // click on the empty day (which creates an all-day event there). const own = { + // Not empty day space: a drag from here doesn't pick days. + "data-month-entry": true, onClick: (e: React.MouseEvent) => e.stopPropagation(), onDoubleClick: (e: React.MouseEvent) => e.stopPropagation(), onContextMenu: (e: React.MouseEvent) => e.stopPropagation(), }; const daySegments = segments.filter((segment) => segment.startIndex === dayIndex && (isShown ? isShown(segment) : segment.row < rowLimit)); const tasks = dayTasks[dayIndex].filter((_, taskIndex) => dayEventRows[dayIndex] + taskIndex < rowLimit); - const preview = pendingPreview && isSameDay(pendingPreview.start, day) ? pendingPreview : null; + // A new all-day event spans its days, from its first day or the start + // of each week row it continues into; a timed one sits on its day. + const previewSpan = (() => { + if (!pendingPreview) return 0; + if (draftRange) { + if (!isInMonthRange(day, draftRange) || (dayIndex > 0 && !isSameDay(day, draftRange.start))) return 0; + return Math.min(differenceInCalendarDays(draftRange.end, day) + 1, week.length - dayIndex); + } + return isSameDay(pendingPreview.start, day) ? 1 : 0; + })(); + const preview = previewSpan > 0 ? pendingPreview : null; return ( <> @@ -835,10 +917,12 @@ function MonthCellEntries({ )} {preview && (() => { // On a full day it lies over the last row: below it, it landed on the next week's date. - const previewRow = Math.min(lastRow, Math.max(rowCount, dayEventRows[dayIndex] + dayTasks[dayIndex].length)); + let busiest = 0; + for (let d = dayIndex; d < dayIndex + previewSpan; d++) busiest = Math.max(busiest, dayEventRows[d] + dayTasks[d].length); + const previewRow = Math.min(lastRow, Math.max(rowCount, busiest)); const color = paint(calendarMap.get(preview.calendarId)?.color || "#3b82f6"); return ( -
+
= range.start || isSameDay(day, range.start)) && (day <= range.end || isSameDay(day, range.end)); +} + +/** + * The day cell under a point of the month grid: the week row at that + * height, then the cell at that position in it. Measured from the cells + * themselves, so a right-to-left grid needs nothing extra; a point past + * the grid takes the nearest row and cell. Not elementFromPoint: an event + * bar over several days belongs to its first day's cell. + */ +export function monthDayAtPoint(root: HTMLElement, x: number, y: number): Date | null { + const rows = Array.from(root.querySelectorAll("[data-week]")); + if (rows.length === 0) return null; + const nearest = (items: T[], from: (rect: DOMRect) => [number, number], at: number): T => { + let best = items[0]; + let bestDistance = Infinity; + for (const item of items) { + const [low, high] = from(item.getBoundingClientRect()); + const distance = at < low ? low - at : at >= high ? at - high + 1 : 0; + if (distance < bestDistance) { + best = item; + bestDistance = distance; + if (distance === 0) break; + } + } + return best; + }; + const row = nearest(rows, (rect) => [rect.top, rect.bottom], y); + const cells = Array.from(row.querySelectorAll("[data-month-day]")); + if (cells.length === 0) return null; + const cell = nearest(cells, (rect) => [rect.left, rect.right], x); + return parseDayKey(cell.dataset.monthDay ?? ""); +} + +/** What a press on the grid hits that isn't empty day space. */ +const NOT_EMPTY_SPACE = "[data-month-entry], button, a, input, select, textarea, [role='button'], [data-calendar-event]"; + +interface PressState { + pointerId: number; + touch: boolean; + anchor: Date; + current: Date; + x: number; + y: number; + /** Days are being picked (mouse: the pointer left the first day; touch: the long press). */ + active: boolean; + /** The touch's own context menu, held back until it is clear whether days were picked. */ + heldMenu: { event: MouseEvent; day: Date } | null; + timer: ReturnType | null; + stop: () => void; +} + +interface UseMonthRangeSelectOptions { + /** The month grid's scroll container: its rows carry data-week, its cells data-month-day. */ + scrollRef: RefObject; + /** Off when no calendar can take a new event. */ + enabled: boolean; + /** Days were picked: open the quick editor for them. */ + onCreateRange: (start: Date, end: Date) => void; + /** A long press that picked no other day keeps opening the day's menu. */ + onContextMenuDay?: (event: MouseEvent, day: Date) => void; +} + +/** + * Picking days in the month view to create an event over them, as Google + * Calendar and Outlook do: press on a day's empty space and drag to another + * day (across week rows in reading order, either way), or Shift+arrows from + * the focused day and Enter. On touch a long press starts it, so a swipe + * still scrolls. The days go to the same quick editor as a drag in the week + * and day views. + */ +export function useMonthRangeSelect({ scrollRef, enabled, onCreateRange, onContextMenuDay }: UseMonthRangeSelectOptions) { + const [selection, setSelection] = useState(null); + const pressRef = useRef(null); + // The click that ends a drag is not a click on the day it ended on. + const wasDragging = useRef(false); + // A touch drag's own context menu (Windows sends it after the finger lifts). + const muteMenuUntil = useRef(0); + // Shift+arrows: the day the keyboard selection started on. + const keyAnchor = useRef(null); + + const show = useCallback((press: PressState) => { + const range = monthRange(press.anchor, press.current); + setSelection((prev) => (prev && isSameDay(prev.start, range.start) && isSameDay(prev.end, range.end) ? prev : range)); + }, []); + + const end = useCallback(() => { + const press = pressRef.current; + pressRef.current = null; + if (press) { + if (press.timer) clearTimeout(press.timer); + press.stop(); + } + setSelection(null); + return press; + }, []); + + useEffect(() => () => { + const press = pressRef.current; + if (press?.timer) clearTimeout(press.timer); + press?.stop(); + }, []); + + const follow = useCallback((press: PressState) => { + const root = scrollRef.current; + if (!root) return; + const day = monthDayAtPoint(root, press.x, press.y); + if (!day) return; + if (!press.active) { + if (isSameDay(day, press.anchor)) return; + press.active = true; + } + press.current = day; + show(press); + }, [scrollRef, show]); + + const activate = useCallback((press: PressState, root: HTMLElement) => { + press.active = true; + show(press); + // From here a moving finger picks days: the grid must not scroll. + const holdStill = (e: TouchEvent) => { if (e.cancelable) e.preventDefault(); }; + root.addEventListener("touchmove", holdStill, { passive: false }); + const previous = press.stop; + press.stop = () => { + previous(); + root.removeEventListener("touchmove", holdStill); + }; + }, [show]); + + const onPointerDown = useCallback((e: PointerEvent) => { + if (!enabled || !e.isPrimary) return; + const touch = e.pointerType === "touch"; + if (!touch && e.button !== 0) return; + const target = e.target as HTMLElement; + if (target.closest(NOT_EMPTY_SPACE)) return; + const cell = target.closest("[data-month-day]"); + const root = scrollRef.current; + if (!cell || !root) return; + end(); + keyAnchor.current = null; + const anchor = parseDayKey(cell.dataset.monthDay ?? ""); + const press: PressState = { + pointerId: e.pointerId, touch, anchor, current: anchor, x: e.clientX, y: e.clientY, + active: false, heldMenu: null, timer: null, stop: () => {}, + }; + // The wheel moves the grid under a pointer that stands still: follow it. + const onScroll = () => { if (press.active) follow(press); }; + root.addEventListener("scroll", onScroll); + press.stop = () => root.removeEventListener("scroll", onScroll); + if (touch) { + press.timer = setTimeout(() => { + press.timer = null; + if (pressRef.current === press) activate(press, root); + }, LONG_PRESS_MS); + } + pressRef.current = press; + }, [enabled, scrollRef, end, follow, activate]); + + const onPointerMove = useCallback((e: PointerEvent) => { + const press = pressRef.current; + if (!press || e.pointerId !== press.pointerId) return; + if (press.touch && !press.active) { + // A swipe before the long press: the grid scrolls, nothing is picked. + if (Math.hypot(e.clientX - press.x, e.clientY - press.y) > TOUCH_SLOP_PX) end(); + return; + } + press.x = e.clientX; + press.y = e.clientY; + const wasActive = press.active; + follow(press); + if (press.active && !wasActive && !press.touch) { + try { e.currentTarget.setPointerCapture(press.pointerId); } catch { /* the pointer is gone */ } + } + }, [end, follow]); + + const onPointerUp = useCallback((e: PointerEvent) => { + const press = pressRef.current; + if (!press || e.pointerId !== press.pointerId) return; + end(); + if (!press.active) return; + wasDragging.current = true; + requestAnimationFrame(() => { wasDragging.current = false; }); + try { e.currentTarget.releasePointerCapture(press.pointerId); } catch { /* not captured */ } + const range = monthRange(press.anchor, press.current); + if (press.touch && isSameDay(range.start, range.end)) { + // A long press that stayed on its day: the day's menu, as before. + if (press.heldMenu) onContextMenuDay?.(press.heldMenu.event, press.heldMenu.day); + return; + } + if (press.touch) muteMenuUntil.current = Date.now() + 1000; + onCreateRange(range.start, range.end); + }, [end, onCreateRange, onContextMenuDay]); + + const onPointerCancel = useCallback((e: PointerEvent) => { + const press = pressRef.current; + if (!press || e.pointerId !== press.pointerId) return; + end(); + }, [end]); + + /** Captured before the cells' own handler: a touch drag's long press is not a right-click. */ + const onContextMenuCapture = useCallback((e: MouseEvent) => { + const press = pressRef.current; + if (press?.touch) { + // The browser's long press can come before ours: it starts the pick. + if (!press.active && scrollRef.current) { + if (press.timer) clearTimeout(press.timer); + press.timer = null; + activate(press, scrollRef.current); + } + e.preventDefault(); + e.stopPropagation(); + press.heldMenu = { event: e, day: press.anchor }; + return; + } + if (Date.now() < muteMenuUntil.current) { + e.preventDefault(); + e.stopPropagation(); + } + }, [scrollRef, activate]); + + // --- Keyboard --- + + /** Shift+arrow from `from` to `to`: the selection grows or shrinks from where it started. */ + const extendTo = useCallback((from: Date, to: Date) => { + if (!enabled) return; + if (!keyAnchor.current) keyAnchor.current = from; + setSelection({ ...monthRange(keyAnchor.current, to), keyboard: true }); + }, [enabled]); + + /** Enter: create over the keyboard selection. False when there is none. */ + const commitKeyboard = useCallback((): boolean => { + if (!keyAnchor.current || !selection) return false; + const range = selection; + keyAnchor.current = null; + setSelection(null); + onCreateRange(range.start, range.end); + return true; + }, [selection, onCreateRange]); + + /** Escape or a plain arrow: the keyboard selection goes. False when there was none. */ + const clearKeyboard = useCallback((): boolean => { + if (!keyAnchor.current) return false; + keyAnchor.current = null; + setSelection(null); + return true; + }, []); + + return { + selection, + wasDragging, + pointerHandlers: { onPointerDown, onPointerMove, onPointerUp, onPointerCancel, onContextMenuCapture }, + extendTo, + commitKeyboard, + clearKeyboard, + }; +} diff --git a/locales/ar/common.json b/locales/ar/common.json index f5921dc67..60eb1ca90 100644 --- a/locales/ar/common.json +++ b/locales/ar/common.json @@ -5279,6 +5279,11 @@ "cancelled": "ألغى {name} \"{title}\"", "untitled": "حدث بدون عنوان" }, + "calendar_month_select": { + "selected_range": "تم تحديد {start} إلى {end}.", + "selected_day": "تم تحديد {day}.", + "enter_hint": "اضغط Enter لإنشاء حدث." + }, "company_calendars": { "section": "المؤسسة" }, diff --git a/locales/ca/common.json b/locales/ca/common.json index 9fde0d888..e08adc6b2 100644 --- a/locales/ca/common.json +++ b/locales/ca/common.json @@ -5279,6 +5279,11 @@ "cancelled": "{name} ha cancel·lat \"{title}\"", "untitled": "Esdeveniment sense títol" }, + "calendar_month_select": { + "selected_range": "Seleccionat de {start} a {end}.", + "selected_day": "Seleccionat {day}.", + "enter_hint": "Premeu Retorn per crear un esdeveniment." + }, "company_calendars": { "section": "Organització" }, diff --git a/locales/cs/common.json b/locales/cs/common.json index e8199be5a..8ecd4d3da 100644 --- a/locales/cs/common.json +++ b/locales/cs/common.json @@ -5905,6 +5905,11 @@ "cancelled": "{name} zrušil(a) „{title}“", "untitled": "Událost bez názvu" }, + "calendar_month_select": { + "selected_range": "Vybráno {start} až {end}.", + "selected_day": "Vybráno {day}.", + "enter_hint": "Stisknutím klávesy Enter vytvoříte událost." + }, "company_calendars": { "section": "Organizace" }, diff --git a/locales/da/common.json b/locales/da/common.json index 4d8c7681a..7d705da6a 100644 --- a/locales/da/common.json +++ b/locales/da/common.json @@ -5279,6 +5279,11 @@ "cancelled": "{name} har aflyst \"{title}\"", "untitled": "Unavngivet begivenhed" }, + "calendar_month_select": { + "selected_range": "{start} til {end} valgt.", + "selected_day": "{day} valgt.", + "enter_hint": "Tryk på Enter for at oprette en begivenhed." + }, "company_calendars": { "section": "Organisation" }, diff --git a/locales/de/common.json b/locales/de/common.json index 9c39c5a69..f00483783 100644 --- a/locales/de/common.json +++ b/locales/de/common.json @@ -5905,6 +5905,11 @@ "cancelled": "{name} hat „{title}“ abgesagt", "untitled": "Unbenannter Termin" }, + "calendar_month_select": { + "selected_range": "{start} bis {end} ausgewählt.", + "selected_day": "{day} ausgewählt.", + "enter_hint": "Drücken Sie die Eingabetaste, um einen Termin zu erstellen." + }, "company_calendars": { "section": "Organisation" }, diff --git a/locales/en/common.json b/locales/en/common.json index a2e0f400c..396810e4f 100644 --- a/locales/en/common.json +++ b/locales/en/common.json @@ -5279,6 +5279,11 @@ "cancelled": "{name} cancelled \"{title}\"", "untitled": "Untitled event" }, + "calendar_month_select": { + "selected_range": "{start} to {end} selected.", + "selected_day": "{day} selected.", + "enter_hint": "Press Enter to create an event." + }, "company_calendars": { "section": "Organisation" }, diff --git a/locales/es/common.json b/locales/es/common.json index 7b9d02613..c4a8962e7 100644 --- a/locales/es/common.json +++ b/locales/es/common.json @@ -5905,6 +5905,11 @@ "cancelled": "{name} ha cancelado \"{title}\"", "untitled": "Evento sin título" }, + "calendar_month_select": { + "selected_range": "Seleccionado del {start} al {end}.", + "selected_day": "Seleccionado {day}.", + "enter_hint": "Pulsa Intro para crear un evento." + }, "company_calendars": { "section": "Organización" }, diff --git a/locales/et/common.json b/locales/et/common.json index 19ab50447..d95ac4be4 100644 --- a/locales/et/common.json +++ b/locales/et/common.json @@ -5279,6 +5279,11 @@ "cancelled": "{name} tühistas sündmuse \"{title}\"", "untitled": "Nimetu sündmus" }, + "calendar_month_select": { + "selected_range": "Valitud {start} kuni {end}.", + "selected_day": "Valitud {day}.", + "enter_hint": "Sündmuse loomiseks vajutage Enter." + }, "company_calendars": { "section": "Organisatsioon" }, diff --git a/locales/fa/common.json b/locales/fa/common.json index 4e1219635..ee1e1bce5 100644 --- a/locales/fa/common.json +++ b/locales/fa/common.json @@ -5279,6 +5279,11 @@ "cancelled": "{name} «{title}» را لغو کرد", "untitled": "رویداد بدون عنوان" }, + "calendar_month_select": { + "selected_range": "{start} تا {end} انتخاب شد.", + "selected_day": "{day} انتخاب شد.", + "enter_hint": "برای ساختن رویداد، Enter را بزنید." + }, "company_calendars": { "section": "سازمان" }, diff --git a/locales/fr/common.json b/locales/fr/common.json index 83460df07..7a50790b4 100644 --- a/locales/fr/common.json +++ b/locales/fr/common.json @@ -5905,6 +5905,11 @@ "cancelled": "{name} a annulé « {title} »", "untitled": "Événement sans titre" }, + "calendar_month_select": { + "selected_range": "Du {start} au {end} sélectionné.", + "selected_day": "{day} sélectionné.", + "enter_hint": "Appuyez sur Entrée pour créer un événement." + }, "company_calendars": { "section": "Organisation" }, diff --git a/locales/he/common.json b/locales/he/common.json index 6fd019a89..086f3df10 100644 --- a/locales/he/common.json +++ b/locales/he/common.json @@ -5724,6 +5724,11 @@ "cancelled": "{name} ביטל/ה את \"{title}\"", "untitled": "אירוע ללא כותרת" }, + "calendar_month_select": { + "selected_range": "נבחרו {start} עד {end}.", + "selected_day": "נבחר {day}.", + "enter_hint": "הקישו Enter כדי ליצור אירוע." + }, "company_calendars": { "section": "ארגון" }, diff --git a/locales/hu/common.json b/locales/hu/common.json index 1cef7c650..fc7f364a2 100644 --- a/locales/hu/common.json +++ b/locales/hu/common.json @@ -5279,6 +5279,11 @@ "cancelled": "{name} lemondta a(z) „{title}” eseményt", "untitled": "Névtelen esemény" }, + "calendar_month_select": { + "selected_range": "Kijelölve: {start} – {end}.", + "selected_day": "Kijelölve: {day}.", + "enter_hint": "Esemény létrehozásához nyomja meg az Entert." + }, "company_calendars": { "section": "Szervezet" }, diff --git a/locales/it/common.json b/locales/it/common.json index cca81e26e..c9b0c037a 100644 --- a/locales/it/common.json +++ b/locales/it/common.json @@ -5905,6 +5905,11 @@ "cancelled": "{name} ha annullato \"{title}\"", "untitled": "Evento senza titolo" }, + "calendar_month_select": { + "selected_range": "Selezionato dal {start} al {end}.", + "selected_day": "Selezionato {day}.", + "enter_hint": "Premi Invio per creare un evento." + }, "company_calendars": { "section": "Organizzazione" }, diff --git a/locales/ja/common.json b/locales/ja/common.json index 2c7fe67d6..26e8beb33 100644 --- a/locales/ja/common.json +++ b/locales/ja/common.json @@ -5905,6 +5905,11 @@ "cancelled": "{name} さんが「{title}」をキャンセルしました", "untitled": "無題の予定" }, + "calendar_month_select": { + "selected_range": "{start}から{end}を選択しました。", + "selected_day": "{day}を選択しました。", + "enter_hint": "Enter キーで予定を作成します。" + }, "company_calendars": { "section": "組織" }, diff --git a/locales/ko/common.json b/locales/ko/common.json index 4a5501456..50f155550 100644 --- a/locales/ko/common.json +++ b/locales/ko/common.json @@ -5905,6 +5905,11 @@ "cancelled": "{name}님이 \"{title}\"을(를) 취소했습니다", "untitled": "제목 없는 일정" }, + "calendar_month_select": { + "selected_range": "{start}부터 {end}까지 선택됨.", + "selected_day": "{day} 선택됨.", + "enter_hint": "Enter 키를 눌러 일정을 만드세요." + }, "company_calendars": { "section": "조직" }, diff --git a/locales/lv/common.json b/locales/lv/common.json index f12fb9faf..24c64aa80 100644 --- a/locales/lv/common.json +++ b/locales/lv/common.json @@ -5905,6 +5905,11 @@ "cancelled": "{name} atcēla “{title}”", "untitled": "Notikums bez nosaukuma" }, + "calendar_month_select": { + "selected_range": "Atlasīts no {start} līdz {end}.", + "selected_day": "Atlasīts {day}.", + "enter_hint": "Nospiediet Enter, lai izveidotu notikumu." + }, "company_calendars": { "section": "Organizācija" }, diff --git a/locales/mn/common.json b/locales/mn/common.json index ad1ce7427..dad03bc17 100644 --- a/locales/mn/common.json +++ b/locales/mn/common.json @@ -5279,6 +5279,11 @@ "cancelled": "{name} \"{title}\"-г цуцаллаа", "untitled": "Нэргүй арга хэмжээ" }, + "calendar_month_select": { + "selected_range": "{start}-с {end} хүртэл сонгосон.", + "selected_day": "{day} сонгосон.", + "enter_hint": "Үйл явдал үүсгэхийн тулд Enter дарна уу." + }, "company_calendars": { "section": "Байгууллага" }, diff --git a/locales/nb/common.json b/locales/nb/common.json index e0c43c990..c6548bda1 100644 --- a/locales/nb/common.json +++ b/locales/nb/common.json @@ -5279,6 +5279,11 @@ "cancelled": "{name} har avlyst «{title}»", "untitled": "Hendelse uten tittel" }, + "calendar_month_select": { + "selected_range": "{start} til {end} er valgt.", + "selected_day": "{day} er valgt.", + "enter_hint": "Trykk Enter for å opprette en hendelse." + }, "company_calendars": { "section": "Organisasjon" }, diff --git a/locales/nl/common.json b/locales/nl/common.json index 4d04e4400..04644d525 100644 --- a/locales/nl/common.json +++ b/locales/nl/common.json @@ -5905,6 +5905,11 @@ "cancelled": "{name} heeft \"{title}\" geannuleerd", "untitled": "Afspraak zonder titel" }, + "calendar_month_select": { + "selected_range": "{start} tot {end} geselecteerd.", + "selected_day": "{day} geselecteerd.", + "enter_hint": "Druk op Enter om een afspraak te maken." + }, "company_calendars": { "section": "Organisatie" }, diff --git a/locales/pl/common.json b/locales/pl/common.json index 3d23c4671..6ac3eb080 100644 --- a/locales/pl/common.json +++ b/locales/pl/common.json @@ -5905,6 +5905,11 @@ "cancelled": "{name} odwołał(a) „{title}”", "untitled": "Wydarzenie bez tytułu" }, + "calendar_month_select": { + "selected_range": "Wybrano od {start} do {end}.", + "selected_day": "Wybrano {day}.", + "enter_hint": "Naciśnij Enter, aby utworzyć wydarzenie." + }, "company_calendars": { "section": "Organizacja" }, diff --git a/locales/pt/common.json b/locales/pt/common.json index 2b39bb565..4b53b38b6 100644 --- a/locales/pt/common.json +++ b/locales/pt/common.json @@ -5905,6 +5905,11 @@ "cancelled": "{name} cancelou \"{title}\"", "untitled": "Evento sem título" }, + "calendar_month_select": { + "selected_range": "Selecionado de {start} a {end}.", + "selected_day": "Selecionado {day}.", + "enter_hint": "Prima Enter para criar um evento." + }, "company_calendars": { "section": "Organização" }, diff --git a/locales/ro/common.json b/locales/ro/common.json index b8b274456..cfdbc6b34 100644 --- a/locales/ro/common.json +++ b/locales/ro/common.json @@ -5279,6 +5279,11 @@ "cancelled": "{name} a anulat „{title}”", "untitled": "Eveniment fără titlu" }, + "calendar_month_select": { + "selected_range": "Selectat de la {start} la {end}.", + "selected_day": "Selectat {day}.", + "enter_hint": "Apăsați Enter pentru a crea un eveniment." + }, "company_calendars": { "section": "Organizație" }, diff --git a/locales/ru/common.json b/locales/ru/common.json index 1056ad03b..537fe4076 100644 --- a/locales/ru/common.json +++ b/locales/ru/common.json @@ -5905,6 +5905,11 @@ "cancelled": "{name} отменил(а) «{title}»", "untitled": "Событие без названия" }, + "calendar_month_select": { + "selected_range": "Выбрано с {start} по {end}.", + "selected_day": "Выбрано: {day}.", + "enter_hint": "Нажмите Enter, чтобы создать событие." + }, "company_calendars": { "section": "Организация" }, diff --git a/locales/sk/common.json b/locales/sk/common.json index 16209de6f..38836d0d2 100644 --- a/locales/sk/common.json +++ b/locales/sk/common.json @@ -5279,6 +5279,11 @@ "cancelled": "{name} zrušil(a) „{title}“", "untitled": "Udalosť bez názvu" }, + "calendar_month_select": { + "selected_range": "Vybraté {start} až {end}.", + "selected_day": "Vybraté {day}.", + "enter_hint": "Stlačením klávesu Enter vytvoríte udalosť." + }, "company_calendars": { "section": "Organizácia" }, diff --git a/locales/th/common.json b/locales/th/common.json index 659796f68..cfbd32f28 100644 --- a/locales/th/common.json +++ b/locales/th/common.json @@ -2839,6 +2839,11 @@ "cancelled": "{name} ยกเลิกกิจกรรม “{title}”", "untitled": "กิจกรรมที่ไม่มีชื่อ" }, + "calendar_month_select": { + "selected_range": "เลือก {start} ถึง {end} แล้ว", + "selected_day": "เลือก {day} แล้ว", + "enter_hint": "กด Enter เพื่อสร้างกิจกรรม" + }, "company_calendars": { "section": "องค์กร" }, diff --git a/locales/tr/common.json b/locales/tr/common.json index a4e1787c5..1f0ea84b5 100644 --- a/locales/tr/common.json +++ b/locales/tr/common.json @@ -5279,6 +5279,11 @@ "cancelled": "{name} \"{title}\" etkinliğini iptal etti", "untitled": "Başlıksız etkinlik" }, + "calendar_month_select": { + "selected_range": "{start} ile {end} arası seçildi.", + "selected_day": "{day} seçildi.", + "enter_hint": "Etkinlik oluşturmak için Enter tuşuna basın." + }, "company_calendars": { "section": "Kuruluş" }, diff --git a/locales/uk/common.json b/locales/uk/common.json index 129e93f22..db505bd44 100644 --- a/locales/uk/common.json +++ b/locales/uk/common.json @@ -5905,6 +5905,11 @@ "cancelled": "{name} скасував(ла) «{title}»", "untitled": "Подія без назви" }, + "calendar_month_select": { + "selected_range": "Вибрано з {start} по {end}.", + "selected_day": "Вибрано: {day}.", + "enter_hint": "Натисніть Enter, щоб створити подію." + }, "company_calendars": { "section": "Організація" }, diff --git a/locales/vi/common.json b/locales/vi/common.json index 0cd5746c6..bf7d36622 100644 --- a/locales/vi/common.json +++ b/locales/vi/common.json @@ -5291,6 +5291,11 @@ "cancelled": "{name} đã hủy \"{title}\"", "untitled": "Sự kiện không có tiêu đề" }, + "calendar_month_select": { + "selected_range": "Đã chọn từ {start} đến {end}.", + "selected_day": "Đã chọn {day}.", + "enter_hint": "Nhấn Enter để tạo sự kiện." + }, "company_calendars": { "section": "Tổ chức" }, diff --git a/locales/zh-TW/common.json b/locales/zh-TW/common.json index 0f3ae2457..f072d96a2 100644 --- a/locales/zh-TW/common.json +++ b/locales/zh-TW/common.json @@ -5279,6 +5279,11 @@ "cancelled": "{name} 取消了「{title}」", "untitled": "未命名活動" }, + "calendar_month_select": { + "selected_range": "已選取 {start} 至 {end}。", + "selected_day": "已選取 {day}。", + "enter_hint": "按 Enter 鍵建立活動。" + }, "company_calendars": { "section": "組織" }, diff --git a/locales/zh/common.json b/locales/zh/common.json index e22f4805e..2ffbac48c 100644 --- a/locales/zh/common.json +++ b/locales/zh/common.json @@ -5905,6 +5905,11 @@ "cancelled": "{name} 取消了“{title}”", "untitled": "无标题活动" }, + "calendar_month_select": { + "selected_range": "已选择 {start} 至 {end}。", + "selected_day": "已选择 {day}。", + "enter_hint": "按 Enter 键创建活动。" + }, "company_calendars": { "section": "组织" }, From 0fdd0cb5d89c18ded0b99ddf62b4bdcb9696b20d Mon Sep 17 00:00:00 2001 From: Linus Rath <139418639+rathlinus@users.noreply.github.com> Date: Wed, 4 Nov 2026 18:24:31 +0100 Subject: [PATCH 5/5] test: check drag-to-create in the month and week views against Stalwart --- .../tests/27-month-drag-create.spec.ts | 367 ++++++++++++++++++ 1 file changed, 367 insertions(+) create mode 100644 integration/tests/27-month-drag-create.spec.ts diff --git a/integration/tests/27-month-drag-create.spec.ts b/integration/tests/27-month-drag-create.spec.ts new file mode 100644 index 000000000..c9bd255e8 --- /dev/null +++ b/integration/tests/27-month-drag-create.spec.ts @@ -0,0 +1,367 @@ +import { test, expect, type Browser, type Page } from '@playwright/test'; +import { addDays, format, startOfWeek } from 'date-fns'; +import { mkdirSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { contextOptions } from './helpers/ent'; +import { JmapClient } from './helpers/jmap'; +import { neutralizeDevOverlay } from './helpers/app'; + +/** + * Usability report 2026-11-04: creating by dragging over the calendar. + * - Month view: a drag over days (across week rows, either way), Shift+ + * arrows and Enter, a long press and drag on a phone, all open the quick + * editor (the full one on a phone) for an all-day event over the days. + * - Week view: the event created is the range the selection showed, the + * selection is drawn over the events it covers, the new event takes a + * column beside an overlapping one, and Save works without a title. + * Against a VM 106 Stalwart (1.0 and 0.16); every save is checked on the + * server and removed again. + * + * Account: dso-ux-pim, password IT_DSO_PASSWORD. Items are titled + * "MDRAG …" (the untitled one is found by its time) and deleted. + * Screenshots go to IT_SHOTS_DIR, named month-drag--…. + */ + +const PASSWORD = process.env.IT_DSO_PASSWORD ?? ''; +const A = 'dso-ux-pim@example.org'; +const CORE = 'urn:ietf:params:jmap:core'; +const CAL = 'urn:ietf:params:jmap:calendars'; +const RUN = Date.now().toString(36); +const TZ = 'Europe/Berlin'; +const prefix = `MDRAG ${RUN}`; +const SERVER = process.env.IT_ENT_SERVER ?? 'unknown'; +const SHOTS = process.env.IT_SHOTS_DIR ?? path.join(tmpdir(), 'bulwark-month-drag'); + +test.skip(!PASSWORD, 'Set IT_DSO_PASSWORD (vault "Stalwart test – dso-* throwaway accounts")'); + +type Obj = { id: string; title?: string; start?: string; duration?: string; showWithoutTime?: boolean; calendarIds?: Record }; + +async function events(c: JmapClient): Promise { + const r = await c.request([ + ['CalendarEvent/query', { accountId: c.accountId, limit: 2000 }, 'q'], + ['CalendarEvent/get', { + accountId: c.accountId, + '#ids': { resultOf: 'q', name: 'CalendarEvent/query', path: '/ids' }, + properties: ['id', 'title', 'start', 'duration', 'showWithoutTime', 'calendarIds'], + }, 'g'], + ], [CORE, CAL]); + return r.methodResponses[1][1].list as Obj[]; +} + +async function destroy(c: JmapClient, ids: string[]): Promise { + if (ids.length) await c.request([['CalendarEvent/set', { accountId: c.accountId, destroy: ids }, '0']], [CORE, CAL]); +} + +async function defaultCalendar(c: JmapClient): Promise { + const r = await c.request([['Calendar/get', { accountId: c.accountId, properties: ['id', 'isDefault'] }, '0']], [CORE, CAL]); + const list = r.methodResponses[0][1].list as Array<{ id: string; isDefault?: boolean }>; + return (list.find((cal) => cal.isDefault) ?? list[0]).id; +} + +async function create(c: JmapClient, title: string, start: string, duration: string, allDay = false): Promise { + await c.request([['CalendarEvent/set', { + accountId: c.accountId, + create: { n: { '@type': 'Event', title, start, duration, timeZone: allDay ? null : TZ, showWithoutTime: allDay, calendarIds: { [await defaultCalendar(c)]: true } } }, + }, '0']], [CORE, CAL]); +} + +/** Waits for the server to hold an event that `match` accepts. */ +async function serverEvent(c: JmapClient, match: (o: Obj) => boolean): Promise { + let found: Obj | undefined; + await expect.poll(async () => { + found = (await events(c)).find(match); + return !!found; + }, { timeout: 20000 }).toBe(true); + return found!; +} + +async function signIn(browser: Browser, opts: { dark?: boolean; width?: number; phone?: boolean } = {}): Promise { + const base = contextOptions(opts.phone); + const context = await browser.newContext({ + ...base, + timezoneId: TZ, + colorScheme: opts.dark ? 'dark' : 'light', + viewport: opts.phone ? base.viewport : { width: opts.width ?? 1366, height: 860 }, + }); + const page = await context.newPage(); + await neutralizeDevOverlay(page); + await page.goto('/'); + await page.locator('#username').waitFor({ state: 'visible', timeout: 60000 }); + await page.fill('#username', A); + await page.fill('#password', PASSWORD); + await page.click('button[type="submit"]'); + await page.locator('a[href$="/calendar"]').first().waitFor({ timeout: 60000 }); + await page.locator('a[href$="/calendar"]').first().click(); + await page.locator('[data-testid="calendar-item"]').first().waitFor({ timeout: 60000 }).catch(() => {}); + return page; +} + +async function view(page: Page, key: 'm' | 'w'): Promise { + await page.locator('body').click({ position: { x: 1, y: 1 } }).catch(() => {}); + await page.keyboard.press(key); + await page.keyboard.press('t'); + await page.waitForTimeout(800); +} + +async function shot(page: Page, name: string): Promise { + mkdirSync(SHOTS, { recursive: true }); + await page.screenshot({ path: path.join(SHOTS, `month-drag-${SERVER}-${name}.png`) }); +} + +const cell = (page: Page, day: Date) => page.locator(`[data-month-day="${format(day, 'yyyy-MM-dd')}"]`); +const picked = (page: Page) => page.$$eval('[data-month-day][aria-selected="true"]', (els) => els.map((e) => e.getAttribute('data-month-day'))); +const quick = (page: Page) => page.getByRole('dialog').filter({ has: page.getByPlaceholder('Add title') }); + +/** Empty space of a day: just above the bottom edge of its cell. */ +async function emptySpot(page: Page, day: Date): Promise<{ x: number; y: number }> { + const box = (await cell(page, day).boundingBox())!; + return { x: box.x + box.width / 2, y: box.y + box.height - 5 }; +} + +async function dragDays(page: Page, from: Date, to: Date, release = true): Promise { + const a = await emptySpot(page, from); + const b = await emptySpot(page, to); + await page.mouse.move(a.x, a.y); + await page.mouse.down(); + for (let i = 1; i <= 10; i++) await page.mouse.move(a.x + ((b.x - a.x) * i) / 10, a.y + ((b.y - a.y) * i) / 10); + if (release) await page.mouse.up(); +} + +const days = (from: Date, to: Date) => { + const out: string[] = []; + for (let d = from; d <= to; d = addDays(d, 1)) out.push(format(d, 'yyyy-MM-dd')); + return out; +}; + +// Next week's Thursday to the Tuesday after: two week rows. +const nextMonday = addDays(startOfWeek(new Date(), { weekStartsOn: 1 }), 7); +const thursday = addDays(nextMonday, 3); +const tuesday = addDays(nextMonday, 8); +const thisThursday = addDays(nextMonday, -4); + +test.describe('Creating by dragging over the calendar', () => { + test.describe.configure({ mode: 'serial' }); + let c: JmapClient; + const untitled: string[] = []; + + test.beforeAll(async () => { + c = await JmapClient.connect(A, PASSWORD); + }); + + test.afterAll(async () => { + const all = await events(c); + await destroy(c, [...all.filter((o) => o.title?.startsWith(prefix)).map((o) => o.id), ...untitled]); + }); + + test('month: a drag from Thursday to next Tuesday creates one all-day event over the days', async ({ browser }) => { + test.setTimeout(180_000); + const page = await signIn(browser); + await view(page, 'm'); + await dragDays(page, thursday, tuesday, false); + // The days in reading order, wrapping at the end of the row. + expect(await picked(page)).toEqual(expect.arrayContaining(days(thursday, tuesday))); + await shot(page, 'dragging-light-1366'); + await page.mouse.up(); + + const editor = quick(page); + await expect(editor).toBeVisible(); + await expect(editor).toContainText(`${format(thursday, 'EEEE, MMMM d')} – ${format(tuesday, 'EEEE, MMMM d')}`); + await expect(editor).toContainText('All day'); + // The placeholder spans the days while the editor is open. + await expect(page.locator('[data-pending-preview]')).toHaveCount(2); + await shot(page, 'popover-light-1366'); + await editor.getByPlaceholder('Add title').fill(`${prefix} trip`); + await editor.getByRole('button', { name: 'Save' }).click(); + await expect(editor).toBeHidden(); + + const saved = await serverEvent(c, (o) => o.title === `${prefix} trip`); + expect(saved).toMatchObject({ start: `${format(thursday, 'yyyy-MM-dd')}T00:00:00`, duration: 'P6D', showWithoutTime: true }); + expect(Object.keys(saved.calendarIds ?? {})).toEqual([await defaultCalendar(c)]); + await expect(page.locator('[data-month-day] [role="button"], [data-month-day] button').filter({ hasText: `${prefix} trip` }).first()).toBeVisible(); + await shot(page, 'saved-light-1366'); + await destroy(c, [saved.id]); + await page.context().close(); + }); + + test('month: backwards works, and Escape cancels and clears the mark (dark)', async ({ browser }) => { + test.setTimeout(180_000); + const page = await signIn(browser, { dark: true }); + await view(page, 'm'); + await dragDays(page, tuesday, thursday, false); + await shot(page, 'dragging-dark-1366'); + await page.mouse.up(); + const editor = quick(page); + await expect(editor).toContainText(`${format(thursday, 'EEEE, MMMM d')} – ${format(tuesday, 'EEEE, MMMM d')}`); + await shot(page, 'popover-dark-1366'); + await page.keyboard.press('Escape'); + await expect(editor).toBeHidden(); + expect((await picked(page)).filter((d) => days(thursday, tuesday).includes(d!))).toEqual([]); + await page.context().close(); + }); + + test('month: "More options" opens the full editor on the same days; a click still opens one day', async ({ browser }) => { + test.setTimeout(180_000); + const page = await signIn(browser); + await view(page, 'm'); + await dragDays(page, thursday, tuesday); + await quick(page).getByRole('button', { name: 'More options' }).click(); + await expect(page.locator('input[type="date"]').first()).toHaveValue(format(thursday, 'yyyy-MM-dd')); + await expect(page.locator('input[type="date"]').nth(1)).toHaveValue(format(tuesday, 'yyyy-MM-dd')); + await expect(page.getByLabel('All-day event')).toBeChecked(); + await shot(page, 'more-options-light-1366'); + await page.getByRole('button', { name: 'Cancel' }).click(); + + // A single click on empty space: the quick editor for that day, all day. + const spot = await emptySpot(page, thursday); + await page.mouse.click(spot.x, spot.y); + await expect(quick(page)).toContainText(format(thursday, 'EEEE, MMMM d')); + await expect(quick(page)).not.toContainText(' – '); + await expect(quick(page)).toContainText('All day'); + await page.keyboard.press('Escape'); + await page.context().close(); + }); + + test('month: Shift+arrows pick days and Enter opens the quick editor for them', async ({ browser }) => { + test.setTimeout(180_000); + const page = await signIn(browser); + await view(page, 'm'); + await page.locator(`[data-day-button="${format(thursday, 'yyyy-MM-dd')}"]`).focus(); + await page.keyboard.press('Shift+ArrowRight'); + await page.keyboard.press('Shift+ArrowRight'); + expect(await picked(page)).toEqual(expect.arrayContaining(days(thursday, addDays(thursday, 2)))); + await page.keyboard.press('Enter'); + await expect(quick(page)).toContainText(`${format(thursday, 'EEEE, MMMM d')} – ${format(addDays(thursday, 2), 'EEEE, MMMM d')}`); + await shot(page, 'keyboard-light-1366'); + await page.keyboard.press('Escape'); + await page.context().close(); + }); + + test('month: moving an event by drag and opening it still work', async ({ browser }) => { + test.setTimeout(180_000); + // Next week's Sunday, a quiet day, to its Saturday. + const sunday = addDays(nextMonday, 6); + await create(c, `${prefix} move`, `${format(sunday, 'yyyy-MM-dd')}T00:00:00`, 'P1D', true); + const page = await signIn(browser); + await view(page, 'm'); + const bar = page.getByRole('button', { name: new RegExp(`${prefix} move`) }).first(); + await bar.dragTo(cell(page, addDays(sunday, -1)), { targetPosition: { x: 40, y: 90 } }); + const moved = await serverEvent(c, (o) => o.title === `${prefix} move` && o.start === `${format(addDays(sunday, -1), 'yyyy-MM-dd')}T00:00:00`); + expect(moved.duration).toBe('P1D'); + await page.getByRole('button', { name: new RegExp(`${prefix} move`) }).first().click(); + await expect(page.getByRole('dialog').filter({ hasText: `${prefix} move` }).first()).toBeVisible(); + await page.keyboard.press('Escape'); + await page.context().close(); + }); + + for (const dark of [false, true]) { + test(`month at 800 px (${dark ? 'dark' : 'light'}): a drag over days opens an editor on them`, async ({ browser }) => { + test.setTimeout(180_000); + const page = await signIn(browser, { width: 800, dark }); + await view(page, 'm'); + await dragDays(page, thursday, tuesday, false); + expect(await picked(page)).toEqual(expect.arrayContaining(days(thursday, tuesday))); + await shot(page, `dragging-${dark ? 'dark' : 'light'}-800`); + await page.mouse.up(); + // A narrow pane is the phone layout: the full editor; else the quick one. + const full = page.locator('input[type="date"]').first(); + await expect(quick(page).or(full)).toBeVisible(); + if (await full.isVisible()) { + await expect(full).toHaveValue(format(thursday, 'yyyy-MM-dd')); + await expect(page.locator('input[type="date"]').nth(1)).toHaveValue(format(tuesday, 'yyyy-MM-dd')); + } else { + await expect(quick(page)).toContainText(`${format(thursday, 'EEEE, MMMM d')} – ${format(tuesday, 'EEEE, MMMM d')}`); + } + await shot(page, `editor-${dark ? 'dark' : 'light'}-800`); + await page.context().close(); + }); + } + + test('phone: a long press and drag picks days; a swipe still scrolls', async ({ browser }) => { + test.setTimeout(180_000); + const page = await signIn(browser, { phone: true }); + await view(page, 'm'); + const cdp = await page.context().newCDPSession(page); + const touch = (type: string, x?: number, y?: number) => cdp.send('Input.dispatchTouchEvent', { + type, touchPoints: x === undefined ? [] : [{ x, y }], + } as never); + await cell(page, thursday).scrollIntoViewIfNeeded(); + const a = await emptySpot(page, thursday); + const b = await emptySpot(page, tuesday); + await touch('touchStart', a.x, a.y); + await page.waitForTimeout(700); + for (let i = 1; i <= 8; i++) await touch('touchMove', a.x + ((b.x - a.x) * i) / 8, a.y + ((b.y - a.y) * i) / 8); + expect(await picked(page)).toEqual(expect.arrayContaining(days(thursday, tuesday))); + await shot(page, 'phone-long-press'); + await touch('touchEnd'); + // Phones get the full editor, on the same days. + await expect(page.locator('input[type="date"]').first()).toHaveValue(format(thursday, 'yyyy-MM-dd')); + await expect(page.locator('input[type="date"]').nth(1)).toHaveValue(format(tuesday, 'yyyy-MM-dd')); + await page.getByRole('button', { name: 'Cancel' }).click(); + + const scroller = page.locator('[role="grid"] > div').first(); + const before = await scroller.evaluate((el) => el.scrollTop); + const s = await emptySpot(page, thursday); + await touch('touchStart', s.x, s.y); + for (let i = 1; i <= 6; i++) await touch('touchMove', s.x, s.y - i * 40); + await touch('touchEnd'); + await page.waitForTimeout(600); + expect(await scroller.evaluate((el) => el.scrollTop)).not.toBe(before); + expect((await picked(page)).length).toBeLessThanOrEqual(1); + await expect(page.locator('input[type="date"]')).toHaveCount(0); + await page.context().close(); + }); + + test('week: the event created is the range the selection showed, beside the event it overlaps', async ({ browser }) => { + test.setTimeout(180_000); + const day = format(thisThursday, 'yyyy-MM-dd'); + await create(c, `${prefix} Lernblock`, `${day}T12:30:00`, 'PT1H'); + for (const dark of [false, true]) { + const page = await signIn(browser, { dark }); + await view(page, 'w'); + const slot = page.locator(`[data-slot="${day}T11"]`); + await slot.scrollIntoViewIfNeeded(); + const box = (await slot.boundingBox())!; + const y = (minutes: number) => box.y + ((minutes - 660) / 60) * box.height; + const x = box.x + box.width / 2; + await page.mouse.move(x, y(675)); + await page.mouse.down(); + for (let m = 690; m <= 975; m += 15) await page.mouse.move(x, y(m)); + const selection = page.locator('[data-drag-selection]'); + await expect(selection).toContainText('11:15 – 16:15'); + // Drawn over the event it covers: the event doesn't show through. + // (Both sit in the day's column: the higher z-index is on top, and the fill has no transparency.) + const looks = await page.evaluate((title) => { + const sel = document.querySelector('[data-drag-selection]')!; + const ev = Array.from(document.querySelectorAll('[data-calendar-event]')).find((el) => el.textContent?.includes(title))!; + return { selZ: Number(getComputedStyle(sel).zIndex), evZ: Number(getComputedStyle(ev).zIndex), fill: getComputedStyle(sel).backgroundColor, sameColumn: sel.parentElement === ev.parentElement }; + }, `${prefix} Lernblock`); + expect(looks.sameColumn).toBe(true); + expect(looks.selZ).toBeGreaterThan(looks.evZ); + expect(looks.fill).not.toMatch(/rgba\(.*,\s*0(\.\d+)?\)|\/\s*0?\.\d+\)|transparent/); + await shot(page, `week-dragging-${dark ? 'dark' : 'light'}-1366`); + await page.mouse.up(); + const editor = quick(page); + await expect(editor).toContainText('11:15 – 16:15'); + // The new event and the one it overlaps share the day's width. + const placeholder = (await page.locator('[data-pending-preview]').boundingBox())!; + const lernblock = (await page.locator('div[data-calendar-event]').filter({ hasText: `${prefix} Lernblock` }).first().boundingBox())!; + expect(placeholder.x + placeholder.width <= lernblock.x + 1 || lernblock.x + lernblock.width <= placeholder.x + 1).toBe(true); + await shot(page, `week-popover-${dark ? 'dark' : 'light'}-1366`); + if (!dark) { + // Save without a title. + await editor.getByRole('button', { name: 'Save' }).click(); + const saved = await serverEvent(c, (o) => o.start === `${day}T11:15:00` && o.title === '(No title)'); + untitled.push(saved.id); + expect(saved.duration).toBe('PT5H'); + await page.waitForTimeout(1000); + await shot(page, 'week-saved-light-1366'); + // Out of the way of the next drag, which starts at the same spot. + await destroy(c, [saved.id]); + } else { + await page.keyboard.press('Escape'); + } + await page.context().close(); + } + }); +});