Getting started

Actions

Forms

Layout

Navigation

Overlays

Feedback

Data display

Controllers

Helpers

Recipes

Calendar of events

A month of days, each holding events you can drag to another day, and a filter that narrows them.

Goal

Reach for this shape for a planner, a schedule or a board whose columns are dates. The page imports only from @ecopages/radiant-ui/controllers and @ecopages/radiant-ui/helpers.

Primitives

  • buildCalendarMonth, getWeekStartsOn, getWeekdayLabels, formatMonthYear, formatDisplayDate build the weeks, the week start, the headers and the day names for the locale, so the grid has no date arithmetic of its own.
  • textContains decides which events match the filter, ignoring case and accents.
  • SortableController with one SortableGroup makes every day a container events move between. It handles the pointer drag, the keyboard path (Space lifts, the arrows move within the day, PageDown and PageUp move to the next and previous day) and the announcements. It never moves a node: onChange applies the move to the owner's list of events and renders again.
  • RovingController keeps the days to one tab stop. With orientation: 'none' it handles no keys, so the script maps the arrows to a step of one day or one week and calls focus().

The recipe decides three things itself: how an event is stored (an iso date per event), what the filter does to a day (it leaves non-matching events out), and which keys enter and leave a day (Enter focuses its first event, Escape returns to the day).

A day is named for a screen reader by its aria-label, which carries the date and the number of events it holds, because a gridcell with a label is announced by that name alone. Event titles are placed with textContent (the JSX form does the same by escaping), so a title that contains markup is shown as text and never run.

Example

Drag an event to another day. With the keyboard, move between days with the arrow keys, press Enter to focus the first event of a day, press Space to lift it, use the arrows to reorder it within the day and PageDown or PageUp to move it to the next or previous day, then press Space to drop. Typing in the filter hides the events that do not match.

Pick an authoring pattern below; they all behave the same, and the one you pick is remembered on the other recipes.

The same behavior as a RadiantElement. The markup is authored inside the element and the element finds its parts with @query; there is nothing to mount, clean up or run again.

Focus a day, press Enter, then Space to lift an event

import { RadiantElement, customElement, onEvent, query } from '@ecopages/radiant';
import { SortableGroup, createRovingController, createSortableController } from '@ecopages/radiant-ui/controllers';
import { formatMonthYear, getWeekdayLabels, getWeekStartsOn, textContains } from '@ecopages/radiant-ui/helpers';
import { initialEvents, locale, month, paintDay, steps, weeks } from './calendar-events.data';

@customElement('calendar-events-element')
export class CalendarEventsElement extends RadiantElement {
	@query('input') private filter!: HTMLInputElement;
	@query('[data-title]') private heading!: HTMLElement;
	@query('[data-grid]') private grid!: HTMLElement;
	@query('[data-status]') private status!: HTMLElement;

	private cells: HTMLElement[] = [];

	private readonly events = initialEvents.map((event) => ({ ...event }));

	private readonly group = new SortableGroup();

	private readonly sortables = weeks.flat().map(({ iso }) =>
		createSortableController(this, {
			group: this.group,
			getContainer: () => this.cells.find((cell) => cell.dataset.iso === iso) ?? null,
			getItems: () => [
				...(this.cells
					.find((cell) => cell.dataset.iso === iso)
					?.querySelectorAll<HTMLElement>('[data-event]') ?? []),
			],
			announce: (message) => (this.status.textContent = message),
			onChange: ({ item, to, toContainer }) => {
				const moved = this.events.find((event) => event.id === item.dataset.event)!;
				this.events.splice(this.events.indexOf(moved), 1);
				moved.iso = toContainer.dataset.iso!;
				const next = this.visible(moved.iso)[to];
				this.events.splice(next ? this.events.indexOf(next) : this.events.length, 0, moved);
				this.paint();
				this.grid.querySelector<HTMLElement>(`[data-event="${moved.id}"]`)!.focus();
			},
		}),
	);

	private readonly roving = createRovingController(this, {
		getItems: () => this.cells,
		getTarget: () => this.grid,
		orientation: 'none',
	});

	private visible(iso: string) {
		return this.events.filter((event) => event.iso === iso && textContains(event.title, this.filter.value));
	}

	private paint(): void {
		for (const cell of this.cells) paintDay(cell, this.visible(cell.dataset.iso!));
	}

	/**
	 * Builds the day cells, then attaches the sortables again.
	 *
	 * @remarks
	 * The controllers attach before this runs, when the cells do not exist, so their containers resolve to nothing.
	 * A second `attach()` resolves them again.
	 */
	override onConnected(): void {
		this.heading.textContent = formatMonthYear(month, locale);
		const headers = getWeekdayLabels(locale, getWeekStartsOn(locale)).map(
			(label) => `<b role="columnheader">${label}</b>`,
		);
		this.grid.replaceChildren();
		this.grid.insertAdjacentHTML('beforeend', `<div role="row">${headers.join('')}</div>`);
		this.cells = weeks.flatMap((week) => {
			const row = this.grid.appendChild(document.createElement('div'));
			row.setAttribute('role', 'row');
			return week.map(({ iso, inMonth }) => {
				const cell = row.appendChild(document.createElement('div'));
				cell.setAttribute('role', 'gridcell');
				cell.dataset.iso = iso;
				cell.toggleAttribute('data-outside', !inMonth);
				return cell;
			});
		});
		this.paint();
		for (const sortable of this.sortables) sortable.attach();
		this.roving.sync();
	}

	@onEvent({ selector: 'input', type: 'input' })
	refilter(): void {
		this.paint();
	}

	@onEvent({ selector: '[data-grid]', type: 'keydown' })
	walk(event: KeyboardEvent): void {
		const target = event.target as HTMLElement;
		if (target.hasAttribute('data-event')) {
			if (event.key === 'Escape') target.closest<HTMLElement>('[role="gridcell"]')!.focus();
			return;
		}
		const next = this.cells[this.cells.indexOf(target) + (steps[event.key] ?? 0)];
		if (event.key === 'Enter') target.querySelector<HTMLElement>('[data-event]')?.focus();
		else if (steps[event.key] && next) this.roving.focus(next);
		else return;
		event.preventDefault();
	}
}

createSortableController(this, ...) and createRovingController(this, ...) attach when the element connects and are destroyed when it disconnects, and @onEvent listeners follow the same lifecycle. The element keeps its private methods off the names RadiantElement owns: a method called render would replace the host's own and empty the element. The sortables are created once, one per cell of the grid, which includes the leading and trailing days of the neighbouring months, and share a SortableGroup kept in a field. The day cells are built in onConnected, after the controllers attached, so the sortables are attached once more there to resolve their containers; a second attach() is how a controller finds a target that did not exist yet.

What the Radiant form removes: the mount function and its registration, the cleanup that destroys each sortable and the roving controller, and the re-run after a client-side navigation.