Merge branch 'feat/do-month-drag' into feat/desktop-offline

This commit is contained in:
Linus Rath
2026-11-04 18:48:28 +01:00
43 changed files with 1674 additions and 93 deletions
@@ -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');
@@ -611,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<HTMLInputElement>('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;
@@ -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<typeof import('@/lib/announce')>()),
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<typeof CalendarMonthView>;
function renderMonth(overrides: Partial<Props> = {}) {
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(<CalendarMonthView {...props} />);
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<HTMLElement>('[data-week]').forEach((row, r) => {
row.getBoundingClientRect = box(0, r * 100, 700, 100);
row.querySelectorAll<HTMLElement>('[data-month-day]').forEach((cell, c) => {
cell.getBoundingClientRect = box((rtl ? 6 - c : c) * 100, r * 100, 100, 100);
});
});
}
const cell = (key: string) => document.querySelector<HTMLElement>(`[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<HTMLElement>('[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<HTMLElement>('[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<HTMLElement>('[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);
});
});
@@ -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<typeof CalendarWeekView>;
function renderWeek(overrides: Partial<WeekProps> = {}) {
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(<CalendarWeekView {...props} />) };
}
/** The time column of a day: the grid cell holding its hour slots. */
function column(key: string): HTMLElement {
const slot = document.querySelector<HTMLElement>(`[data-slot^="${key}T"]`);
const cell = slot?.closest<HTMLElement>('[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<HTMLElement>('[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<HTMLElement>('[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<HTMLElement>('[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(
<CalendarDayView
focus={{ date: new Date(2026, 8, 9), nonce: 0 }}
windowKey="day:2026-09-09"
rangeStart={new Date(2026, 8, 9)}
rangeEnd={new Date(2026, 8, 9)}
selectedDate={new Date(2026, 8, 9)}
events={[lernblock]}
calendars={calendars}
onSelectEvent={vi.fn()}
onCreateAtTime={vi.fn()}
pendingPreview={draft}
/>,
);
expect(placeholderBox().style.width).toBe('50%');
expect(eventBox('Lernblock').style.width).toBe('50%');
});
});
+25 -7
View File
@@ -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";
@@ -1269,6 +1269,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.
@@ -1289,14 +1301,19 @@ 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);
// 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: title.trim(),
title,
start: format(start, "yyyy-MM-dd'T'00:00:00"),
duration: "P1D",
duration: `P${days}D`,
timeZone: null,
showWithoutTime: true,
calendarIds: { [calendarId]: true },
@@ -1315,7 +1332,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(),
@@ -1325,7 +1342,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<PendingEventPreview | null>(() => {
@@ -1984,7 +2001,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}
+48 -20
View File
@@ -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 (
<div
@@ -529,6 +548,7 @@ export function CalendarDayView({
onPointerDown={(e) => 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 && (
<div
className="absolute left-1 right-1 z-30 rounded-md pointer-events-none bg-primary/15 border-2 border-primary/30 border-dashed"
data-drag-selection
// Opaque and above the events (z-10), which showed through a see-through fill.
className="absolute left-1 right-1 z-30 rounded-md pointer-events-none border-2 border-primary/60 border-dashed"
style={{
backgroundColor: "color-mix(in srgb, var(--color-primary) 15%, var(--color-background))",
top: ((dragCreate.startMinutes - hours.startMinutes) / 60) * hourHeight,
height: ((dragCreate.endMinutes - dragCreate.startMinutes) / 60) * hourHeight,
}}
@@ -683,32 +706,37 @@ export function CalendarDayView({
</div>
)}
{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 (
<div
data-pending-preview
className={cn("absolute left-0.5 right-0.5 z-30 rounded-xs pointer-events-none overflow-hidden px-1.5 py-0.5 text-xs shadow-md", eventFillClass(tintedEvents, false))}
className="absolute z-30 pointer-events-none"
style={{
top: ((clip.startMinutes - hours.startMinutes) / 60) * hourHeight,
height: Math.max(24, ((clip.endMinutes - clip.startMinutes) / 60) * hourHeight),
...eventFillStyle(color, { inactive: false, tinted: tintedEvents }),
insetInlineStart: `${(column / totalColumns) * 100}%`,
width: `${(1 / totalColumns) * 100}%`,
paddingInline: 2,
}}
>
<div className="font-medium truncate">
{pendingPreview.title}
</div>
<div className="text-[0.65625rem] opacity-85 truncate">
<bdi dir="ltr">{formatSnapTime(startMin, timeFormat)} – {formatSnapTime(startMin + durationMin, timeFormat)}</bdi>
<div
data-pending-preview
className={cn("h-full rounded-xs overflow-hidden px-1.5 py-0.5 text-xs shadow-md", eventFillClass(tintedEvents, false))}
style={eventFillStyle(color, { inactive: false, tinted: tintedEvents })}
>
<div className="font-medium truncate">
{pendingPreview.title}
</div>
<div className="text-[0.65625rem] opacity-85 truncate">
<bdi dir="ltr">{formatSnapTime(startMin, timeFormat)} – {formatSnapTime(endMin, timeFormat)}</bdi>
</div>
</div>
</div>
);
+97 -13
View File
@@ -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<HTMLDivElement>(null);
const bottomSentinelRef = useRef<HTMLDivElement>(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<MonthRange | null>(() => {
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<HTMLButtonElement>, 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<HTMLButtonElement>(`[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<string | null>(null);
@@ -484,13 +539,20 @@ export function CalendarMonthView({
}, [t, describeError, userEmailsFor, onMoveEvent]);
return (
<div className="flex flex-col flex-1 overflow-hidden" role="grid" aria-label={`${t("views.month")}, ${formatMonthYear(visibleMonthDate)}`}>
<div
className="flex flex-col flex-1 overflow-hidden"
role="grid"
aria-label={`${t("views.month")}, ${formatMonthYear(visibleMonthDate)}`}
aria-multiselectable={onCreateRange ? true : undefined}
>
<div
ref={scrollRef}
// At 150 % the pane's edge falls inside a device pixel, and the week
// scrolled under the header showed a line of its events there.
className="flex-1 flex flex-col overflow-y-auto [overflow-anchor:none] [clip-path:inset(0.5px_0_0_0)]"
// No text selection or touch callout: a drag over the days picks days.
className="flex-1 flex flex-col overflow-y-auto [overflow-anchor:none] [clip-path:inset(0.5px_0_0_0)] select-none [-webkit-touch-callout:none]"
onScroll={handleScroll}
{...rangeSelect.pointerHandlers}
>
<div
ref={headerRef}
@@ -512,7 +574,7 @@ export function CalendarMonthView({
const fit = capRows ? fitMonthWeek(segments, dayEventRows, dayTasks.map((list) => 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 (
<div key={dayKey(week[0])} data-week={dayKey(week[0])} className="relative flex-shrink-0 border-b border-border" role="row" style={{
minHeight: showChips && !capRows
@@ -530,13 +592,17 @@ export function CalendarMonthView({
const fullDateLabel = formatFullDate(day);
const previous = dayIndex > 0 ? week[dayIndex - 1] : addDays(day, -1);
const firstOfMonth = !checkIsSameMonth(day, previous);
const picked = isInMonthRange(day, highlight);
return (
<div
key={key}
role="gridcell"
aria-selected={selected}
data-month-day={key}
aria-selected={selected || picked}
onClick={() => {
// 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"
)}
>
<div className="flex items-center justify-center gap-1 mb-0.5">
@@ -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<typeof buildWeekSegments>[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<string, Calendar>;
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 (
<div className="absolute z-20 px-0.5 pointer-events-none" style={place(previewRow)}>
<div className="absolute z-20 px-0.5 pointer-events-none" style={place(previewRow, previewSpan)}>
<div
data-pending-preview
className={cn(
+48 -21
View File
@@ -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 (
<div
@@ -674,6 +693,7 @@ export function CalendarWeekView({
onPointerDown={(e) => 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 && (
<div
className="absolute left-1 right-1 z-30 rounded-md pointer-events-none bg-primary/15 border-2 border-primary/30 border-dashed"
data-drag-selection
// Opaque and above the events (z-10), which showed through a see-through fill.
className="absolute left-1 right-1 z-30 rounded-md pointer-events-none border-2 border-primary/60 border-dashed"
style={{
backgroundColor: "color-mix(in srgb, var(--color-primary) 15%, var(--color-background))",
top: ((dragCreate.startMinutes - hours.startMinutes) / 60) * hourHeight,
height: ((dragCreate.endMinutes - dragCreate.startMinutes) / 60) * hourHeight,
}}
@@ -828,33 +851,37 @@ export function CalendarWeekView({
</div>
)}
{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 (
<div
data-pending-preview
className={cn("absolute left-0.5 right-0.5 z-30 rounded-xs pointer-events-none overflow-hidden px-1.5 py-0.5 text-xs shadow-md", eventFillClass(tintedEvents, false))}
className="absolute z-30 pointer-events-none"
style={{
top: ((clip.startMinutes - hours.startMinutes) / 60) * hourHeight,
height: Math.max(20, ((clip.endMinutes - clip.startMinutes) / 60) * hourHeight),
...eventFillStyle(color, { inactive: false, tinted: tintedEvents }),
insetInlineStart: `${(column / totalColumns) * 100}%`,
width: `${(1 / totalColumns) * 100}%`,
paddingInline: 2,
}}
>
<div className="font-medium truncate">
{pendingPreview.title}
</div>
<div className="text-[0.65625rem] opacity-85 truncate">
<bdi dir="ltr">{formatSnapTime(startMin, timeFormat)} – {formatSnapTime(startMin + durationMin, timeFormat)}</bdi>
<div
data-pending-preview
className={cn("h-full rounded-xs overflow-hidden px-1.5 py-0.5 text-xs shadow-md", eventFillClass(tintedEvents, false))}
style={eventFillStyle(color, { inactive: false, tinted: tintedEvents })}
>
<div className="font-medium truncate">
{pendingPreview.title}
</div>
<div className="text-[0.65625rem] opacity-85 truncate">
<bdi dir="ltr">{formatSnapTime(startMin, timeFormat)} – {formatSnapTime(endMin, timeFormat)}</bdi>
</div>
</div>
</div>
);
+11 -5
View File
@@ -3,7 +3,7 @@
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { useTranslations } from "next-intl";
import { format } from "date-fns";
import { format, isSameDay } from "date-fns";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Clock, X } from "@/components/icons";
@@ -58,8 +58,9 @@ export function computePosition(anchor: DOMRect | null, height: number, width =
}
/**
* Compact editor that opens next to an empty slot clicked in the week or
* day view: a title, the time that was picked, the calendar, and a way into
* Compact editor that opens next to an empty slot clicked or dragged over in
* the week or day view, or days picked in the month view: a title, the time
* that was picked, the calendar, and a way into
* the full editor. Enter saves, Escape or a click elsewhere discards.
*/
export function QuickCreatePopover({
@@ -148,14 +149,19 @@ 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();
}, [canSave, onSave]);
const timeFmt = timeFormat === "12h" ? "h:mm a" : "HH:mm";
const dateLabel = intlFormatter.dateTime(draft.start, { weekday: "long", month: "long", day: "numeric" });
const dayFormat = { weekday: "long", month: "long", day: "numeric" } as const;
// Days picked by a drag in the month view: the first and the last.
const dateLabel = draft.allDay && !isSameDay(draft.start, draft.end)
? `${intlFormatter.dateTime(draft.start, dayFormat)} – ${intlFormatter.dateTime(draft.end, dayFormat)}`
: intlFormatter.dateTime(draft.start, dayFormat);
const timeLabel = draft.allDay ? t("events.all_day") : `${format(draft.start, timeFmt)} – ${format(draft.end, timeFmt)}`;
return createPortal(
@@ -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<HTMLDivElement>;
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);
+283
View File
@@ -0,0 +1,283 @@
import { useCallback, useEffect, useRef, useState, type MouseEvent, type PointerEvent, type RefObject } from "react";
import { isSameDay } from "date-fns";
import { parseDayKey } from "@/lib/calendar-scroll-window";
/** Days picked in the month grid, first and last in date order. */
export interface MonthRange {
start: Date;
end: Date;
}
/** Days being picked; `keyboard` when Shift+arrows picked them (Enter creates). */
export interface MonthSelection extends MonthRange {
keyboard?: boolean;
}
/** How long a finger rests on a day before a drag picks days instead of scrolling. */
export const LONG_PRESS_MS = 450;
/** A finger that moves this far before the long press is scrolling. */
const TOUCH_SLOP_PX = 10;
/** The days from `a` to `b` in reading order, whichever way the drag went. */
export function monthRange(a: Date, b: Date): MonthRange {
return a <= b ? { start: a, end: b } : { start: b, end: a };
}
export function isInMonthRange(day: Date, range: MonthRange | null | undefined): boolean {
if (!range) return false;
return (day >= 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<HTMLElement>("[data-week]"));
if (rows.length === 0) return null;
const nearest = <T extends HTMLElement>(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<HTMLElement>("[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<typeof setTimeout> | null;
stop: () => void;
}
interface UseMonthRangeSelectOptions {
/** The month grid's scroll container: its rows carry data-week, its cells data-month-day. */
scrollRef: RefObject<HTMLElement | null>;
/** 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<MonthSelection | null>(null);
const pressRef = useRef<PressState | null>(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<Date | null>(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<HTMLElement>) => {
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<HTMLElement>("[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<HTMLElement>) => {
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<HTMLElement>) => {
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<HTMLElement>) => {
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<HTMLElement>) => {
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,
};
}
+65 -26
View File
@@ -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<DragCreateState | null>(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<HTMLDivElement>,
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<HTMLDivElement>) => {
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<HTMLDivElement>) => {
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,
@@ -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 <run> …" (the untitled one is found by its time) and deleted.
* Screenshots go to IT_SHOTS_DIR, named month-drag-<server>-….
*/
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<string, boolean> };
async function events(c: JmapClient): Promise<Obj[]> {
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<void> {
if (ids.length) await c.request([['CalendarEvent/set', { accountId: c.accountId, destroy: ids }, '0']], [CORE, CAL]);
}
async function defaultCalendar(c: JmapClient): Promise<string> {
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<void> {
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<Obj> {
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<Page> {
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<void> {
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<void> {
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<void> {
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();
}
});
});
+36 -1
View File
@@ -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;
+5
View File
@@ -5279,6 +5279,11 @@
"cancelled": "ألغى {name} \"{title}\"",
"untitled": "حدث بدون عنوان"
},
"calendar_month_select": {
"selected_range": "تم تحديد {start} إلى {end}.",
"selected_day": "تم تحديد {day}.",
"enter_hint": "اضغط Enter لإنشاء حدث."
},
"company_calendars": {
"section": "المؤسسة"
},
+5
View File
@@ -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ó"
},
+5
View File
@@ -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"
},
+5
View File
@@ -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"
},
+5
View File
@@ -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"
},
+5
View File
@@ -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"
},
+5
View File
@@ -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"
},
+5
View File
@@ -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"
},
+5
View File
@@ -5279,6 +5279,11 @@
"cancelled": "{name} «{title}» را لغو کرد",
"untitled": "رویداد بدون عنوان"
},
"calendar_month_select": {
"selected_range": "{start} تا {end} انتخاب شد.",
"selected_day": "{day} انتخاب شد.",
"enter_hint": "برای ساختن رویداد، Enter را بزنید."
},
"company_calendars": {
"section": "سازمان"
},
+5
View File
@@ -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"
},
+5
View File
@@ -5724,6 +5724,11 @@
"cancelled": "{name} ביטל/ה את \"{title}\"",
"untitled": "אירוע ללא כותרת"
},
"calendar_month_select": {
"selected_range": "נבחרו {start} עד {end}.",
"selected_day": "נבחר {day}.",
"enter_hint": "הקישו Enter כדי ליצור אירוע."
},
"company_calendars": {
"section": "ארגון"
},
+5
View File
@@ -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"
},
+5
View File
@@ -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"
},
+5
View File
@@ -5905,6 +5905,11 @@
"cancelled": "{name} さんが「{title}」をキャンセルしました",
"untitled": "無題の予定"
},
"calendar_month_select": {
"selected_range": "{start}から{end}を選択しました。",
"selected_day": "{day}を選択しました。",
"enter_hint": "Enter キーで予定を作成します。"
},
"company_calendars": {
"section": "組織"
},
+5
View File
@@ -5905,6 +5905,11 @@
"cancelled": "{name}님이 \"{title}\"을(를) 취소했습니다",
"untitled": "제목 없는 일정"
},
"calendar_month_select": {
"selected_range": "{start}부터 {end}까지 선택됨.",
"selected_day": "{day} 선택됨.",
"enter_hint": "Enter 키를 눌러 일정을 만드세요."
},
"company_calendars": {
"section": "조직"
},
+5
View File
@@ -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"
},
+5
View File
@@ -5279,6 +5279,11 @@
"cancelled": "{name} \"{title}\"-г цуцаллаа",
"untitled": "Нэргүй арга хэмжээ"
},
"calendar_month_select": {
"selected_range": "{start}-с {end} хүртэл сонгосон.",
"selected_day": "{day} сонгосон.",
"enter_hint": "Үйл явдал үүсгэхийн тулд Enter дарна уу."
},
"company_calendars": {
"section": "Байгууллага"
},
+5
View File
@@ -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"
},
+5
View File
@@ -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"
},
+5
View File
@@ -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"
},
+5
View File
@@ -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"
},
+5
View File
@@ -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"
},
+5
View File
@@ -5905,6 +5905,11 @@
"cancelled": "{name} отменил(а) «{title}»",
"untitled": "Событие без названия"
},
"calendar_month_select": {
"selected_range": "Выбрано с {start} по {end}.",
"selected_day": "Выбрано: {day}.",
"enter_hint": "Нажмите Enter, чтобы создать событие."
},
"company_calendars": {
"section": "Организация"
},
+5
View File
@@ -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"
},
+5
View File
@@ -2839,6 +2839,11 @@
"cancelled": "{name} ยกเลิกกิจกรรม “{title}”",
"untitled": "กิจกรรมที่ไม่มีชื่อ"
},
"calendar_month_select": {
"selected_range": "เลือก {start} ถึง {end} แล้ว",
"selected_day": "เลือก {day} แล้ว",
"enter_hint": "กด Enter เพื่อสร้างกิจกรรม"
},
"company_calendars": {
"section": "องค์กร"
},
+5
View File
@@ -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ş"
},
+5
View File
@@ -5905,6 +5905,11 @@
"cancelled": "{name} скасував(ла) «{title}»",
"untitled": "Подія без назви"
},
"calendar_month_select": {
"selected_range": "Вибрано з {start} по {end}.",
"selected_day": "Вибрано: {day}.",
"enter_hint": "Натисніть Enter, щоб створити подію."
},
"company_calendars": {
"section": "Організація"
},
+5
View File
@@ -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"
},
+5
View File
@@ -5279,6 +5279,11 @@
"cancelled": "{name} 取消了「{title}」",
"untitled": "未命名活動"
},
"calendar_month_select": {
"selected_range": "已選取 {start} 至 {end}。",
"selected_day": "已選取 {day}。",
"enter_hint": "按 Enter 鍵建立活動。"
},
"company_calendars": {
"section": "組織"
},
+5
View File
@@ -5905,6 +5905,11 @@
"cancelled": "{name} 取消了“{title}”",
"untitled": "无标题活动"
},
"calendar_month_select": {
"selected_range": "已选择 {start} 至 {end}。",
"selected_day": "已选择 {day}。",
"enter_hint": "按 Enter 键创建活动。"
},
"company_calendars": {
"section": "组织"
},