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,formatDisplayDatebuild the weeks, the week start, the headers and the day names for the locale, so the grid has no date arithmetic of its own.textContainsdecides which events match the filter, ignoring case and accents.SortableControllerwith oneSortableGroupmakes 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:onChangeapplies the move to the owner's list of events and renders again.RovingControllerkeeps the days to one tab stop. Withorientation: 'none'it handles no keys, so the script maps the arrows to a step of one day or one week and callsfocus().
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();
}
}import { buildCalendarMonth, formatDisplayDate } from '@ecopages/radiant-ui/helpers';
export type CalendarEvent = { id: string; iso: string; title: string };
export const locale = 'en-US';
export const month = new Date(2026, 10, 1);
export const weeks = buildCalendarMonth(month.getFullYear(), month.getMonth(), { locale });
const days = new Map(weeks.flat().map((day) => [day.iso, day]));
/**
* The accessible name of a day cell: the full date, then how many events it holds.
*
* @remarks
* A `gridcell` named by `aria-label` is announced by that name alone, not by its content, so the count has to be in it.
*/
export function dayLabel(date: Date, count: number): string {
const events = count === 0 ? '' : `, ${count} ${count === 1 ? 'event' : 'events'}`;
return `${formatDisplayDate(date, locale, 'full')}${events}`;
}
/**
* Fills a day cell with its number and one node per event, and names the cell after both.
*
* @remarks
* The nodes are built with `textContent`, so an event title is text and is never parsed as markup. Assigning titles to
* `innerHTML` would run a title such as `<img onerror=...>` the moment it reached the page.
*/
export function paintDay(cell: HTMLElement, events: CalendarEvent[]): void {
const { date } = days.get(cell.dataset.iso!)!;
const number = document.createElement('span');
number.dataset.day = '';
number.setAttribute('aria-hidden', 'true');
number.textContent = String(date.getDate());
const items = events.map(({ id, title }) => {
const item = document.createElement('div');
item.dataset.event = id;
item.tabIndex = -1;
item.textContent = title;
return item;
});
cell.setAttribute('aria-label', dayLabel(date, events.length));
cell.replaceChildren(number, ...items);
}
/** Days to move the focus by for each arrow key: one day sideways, one week up or down. */
export const steps: Record<string, number> = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -7, ArrowDown: 7 };
/**
* The events a calendar starts with.
*
* @remarks Forms that move events by editing the list in place start from a copy, so the array stays unchanged.
*/
export const initialEvents: readonly CalendarEvent[] = [
{ id: 'review', iso: '2026-11-03', title: 'Design review' },
{ id: 'standup', iso: '2026-11-03', title: 'Standup' },
{ id: 'launch', iso: '2026-11-12', title: 'Launch day' },
{ id: 'retro', iso: '2026-11-19', title: 'Retro' },
];<calendar-events-element>
<input type="search" placeholder="Filter events" aria-label="Filter events" />
<h3 data-title></h3>
<div data-grid role="grid" aria-label="Events by day"></div>
<p data-status aria-live="polite">Focus a day, press Enter, then Space to lift an event</p>
</calendar-events-element>.primitive-example:has(
> calendar-events-element,
> calendar-events-app,
> [data-controller='calendar-events'],
> [data-example='calendar-events']
) {
flex-direction: column;
flex-wrap: nowrap;
align-items: stretch;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where(input) {
padding: var(--space-1) var(--space-3);
border: 1px solid var(--border);
border-radius: var(--radius-control);
background: var(--surface);
color: var(--on-surface);
font: inherit;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-title]) {
margin: 0;
font-size: 1rem;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-grid]) {
display: grid;
grid-template-columns: repeat(7, minmax(4.5rem, 1fr));
gap: var(--space-1);
overflow-x: auto;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([role='row']) {
display: contents;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([role='columnheader']) {
font-weight: normal;
color: var(--on-surface-container-low);
font-size: 0.75rem;
text-align: center;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([role='gridcell']) {
display: flex;
flex-direction: column;
gap: var(--space-1);
min-height: 5rem;
padding: var(--space-1);
border: 1px solid var(--border);
border-radius: var(--radius-control);
background: var(--surface);
color: var(--on-surface);
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-outside]) {
background: transparent;
color: var(--on-surface-container-low);
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-sortable-over]) {
border-color: var(--primary);
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where(span[data-day]) {
font-size: 0.75rem;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-event]) {
padding: var(--space-1);
overflow-wrap: anywhere;
border-radius: var(--radius-control);
background: var(--surface-container);
color: var(--on-surface-container);
cursor: grab;
touch-action: none;
user-select: none;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-event][data-sortable-state='lifted']) {
background: var(--primary);
color: var(--on-primary);
transform: translate(var(--sortable-dx, 0), var(--sortable-dy, 0));
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-sortable-drop='before']) {
box-shadow: 0 -2px 0 var(--primary);
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-sortable-drop='after']) {
box-shadow: 0 2px 0 var(--primary);
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([role='gridcell']:focus-visible, [data-event]:focus-visible) {
outline: 2px solid var(--focus-ring);
outline-offset: 1px;
}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.
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();
}
}import { buildCalendarMonth, formatDisplayDate } from '@ecopages/radiant-ui/helpers';
export type CalendarEvent = { id: string; iso: string; title: string };
export const locale = 'en-US';
export const month = new Date(2026, 10, 1);
export const weeks = buildCalendarMonth(month.getFullYear(), month.getMonth(), { locale });
const days = new Map(weeks.flat().map((day) => [day.iso, day]));
/**
* The accessible name of a day cell: the full date, then how many events it holds.
*
* @remarks
* A `gridcell` named by `aria-label` is announced by that name alone, not by its content, so the count has to be in it.
*/
export function dayLabel(date: Date, count: number): string {
const events = count === 0 ? '' : `, ${count} ${count === 1 ? 'event' : 'events'}`;
return `${formatDisplayDate(date, locale, 'full')}${events}`;
}
/**
* Fills a day cell with its number and one node per event, and names the cell after both.
*
* @remarks
* The nodes are built with `textContent`, so an event title is text and is never parsed as markup. Assigning titles to
* `innerHTML` would run a title such as `<img onerror=...>` the moment it reached the page.
*/
export function paintDay(cell: HTMLElement, events: CalendarEvent[]): void {
const { date } = days.get(cell.dataset.iso!)!;
const number = document.createElement('span');
number.dataset.day = '';
number.setAttribute('aria-hidden', 'true');
number.textContent = String(date.getDate());
const items = events.map(({ id, title }) => {
const item = document.createElement('div');
item.dataset.event = id;
item.tabIndex = -1;
item.textContent = title;
return item;
});
cell.setAttribute('aria-label', dayLabel(date, events.length));
cell.replaceChildren(number, ...items);
}
/** Days to move the focus by for each arrow key: one day sideways, one week up or down. */
export const steps: Record<string, number> = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -7, ArrowDown: 7 };
/**
* The events a calendar starts with.
*
* @remarks Forms that move events by editing the list in place start from a copy, so the array stays unchanged.
*/
export const initialEvents: readonly CalendarEvent[] = [
{ id: 'review', iso: '2026-11-03', title: 'Design review' },
{ id: 'standup', iso: '2026-11-03', title: 'Standup' },
{ id: 'launch', iso: '2026-11-12', title: 'Launch day' },
{ id: 'retro', iso: '2026-11-19', title: 'Retro' },
];<calendar-events-element>
<input type="search" placeholder="Filter events" aria-label="Filter events" />
<h3 data-title></h3>
<div data-grid role="grid" aria-label="Events by day"></div>
<p data-status aria-live="polite">Focus a day, press Enter, then Space to lift an event</p>
</calendar-events-element>.primitive-example:has(
> calendar-events-element,
> calendar-events-app,
> [data-controller='calendar-events'],
> [data-example='calendar-events']
) {
flex-direction: column;
flex-wrap: nowrap;
align-items: stretch;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where(input) {
padding: var(--space-1) var(--space-3);
border: 1px solid var(--border);
border-radius: var(--radius-control);
background: var(--surface);
color: var(--on-surface);
font: inherit;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-title]) {
margin: 0;
font-size: 1rem;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-grid]) {
display: grid;
grid-template-columns: repeat(7, minmax(4.5rem, 1fr));
gap: var(--space-1);
overflow-x: auto;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([role='row']) {
display: contents;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([role='columnheader']) {
font-weight: normal;
color: var(--on-surface-container-low);
font-size: 0.75rem;
text-align: center;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([role='gridcell']) {
display: flex;
flex-direction: column;
gap: var(--space-1);
min-height: 5rem;
padding: var(--space-1);
border: 1px solid var(--border);
border-radius: var(--radius-control);
background: var(--surface);
color: var(--on-surface);
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-outside]) {
background: transparent;
color: var(--on-surface-container-low);
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-sortable-over]) {
border-color: var(--primary);
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where(span[data-day]) {
font-size: 0.75rem;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-event]) {
padding: var(--space-1);
overflow-wrap: anywhere;
border-radius: var(--radius-control);
background: var(--surface-container);
color: var(--on-surface-container);
cursor: grab;
touch-action: none;
user-select: none;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-event][data-sortable-state='lifted']) {
background: var(--primary);
color: var(--on-primary);
transform: translate(var(--sortable-dx, 0), var(--sortable-dy, 0));
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-sortable-drop='before']) {
box-shadow: 0 -2px 0 var(--primary);
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-sortable-drop='after']) {
box-shadow: 0 2px 0 var(--primary);
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([role='gridcell']:focus-visible, [data-event]:focus-visible) {
outline: 2px solid var(--focus-ring);
outline-offset: 1px;
}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.
The same calendar as one self-contained tag. The element owns its markup: the events and the filter are state, and render() draws the filter field, the heading, the weekday headers, the day cells and the events from buildCalendarMonth and the other helpers, so the page holds only the tag.
import { RadiantElement, customElement, onEvent, state } from '@ecopages/radiant';
import { SortableGroup, createRovingController, createSortableController } from '@ecopages/radiant-ui/controllers';
import { formatMonthYear, getWeekdayLabels, getWeekStartsOn, textContains } from '@ecopages/radiant-ui/helpers';
import { dayLabel, initialEvents, locale, month, steps, weeks, type CalendarEvent } from './calendar-events.data';
@customElement('calendar-events-app')
export class CalendarEventsApp extends RadiantElement<{ status: string }> {
@state events: CalendarEvent[] = [...initialEvents];
@state filter = '';
@state status = 'Focus a day, press Enter, then Space to lift an event';
private focusEvent: string | null = null;
private readonly group = new SortableGroup();
private readonly sortables = weeks.flat().map(({ iso }) =>
createSortableController(this, {
group: this.group,
getContainer: () => this.querySelector<HTMLElement>(`[data-iso="${iso}"]`),
getItems: () => [...this.querySelectorAll<HTMLElement>(`[data-iso="${iso}"] [data-event]`)],
announce: (message) => (this.status = message),
onChange: ({ item, to, toContainer }) => {
this.focusEvent = item.dataset.event!;
this.events = this.move(item.dataset.event!, toContainer.dataset.iso!, to);
},
}),
);
private readonly roving = createRovingController(this, {
getItems: () => this.cells,
getTarget: () => this.querySelector<HTMLElement>('[data-grid]'),
orientation: 'none',
});
private get cells(): HTMLElement[] {
return [...this.querySelectorAll<HTMLElement>('[role="gridcell"]')];
}
private visible(events: CalendarEvent[], iso: string): CalendarEvent[] {
return events.filter((event) => event.iso === iso && textContains(event.title, this.filter));
}
private move(id: string, iso: string, to: number): CalendarEvent[] {
const moved = { ...this.events.find((event) => event.id === id)!, iso };
const rest = this.events.filter((event) => event.id !== id);
const next = this.visible(rest, iso)[to];
rest.splice(next ? rest.indexOf(next) : rest.length, 0, moved);
return rest;
}
/**
* Attaches the controllers to the grid the render produced, and focuses the event that was just moved.
*
* @remarks
* The controllers attach when the element connects, before the first render, when no day exists yet; a second
* `attach()` resolves each target again. The keyed days keep their cells across renders, so later calls change
* nothing. An event that changed day is a new node, so it is found by its id.
*/
protected override updated(): void {
for (const sortable of this.sortables) sortable.attach();
this.roving.attach();
this.roving.sync();
if (this.focusEvent) {
this.querySelector<HTMLElement>(`[data-event="${this.focusEvent}"]`)?.focus();
this.focusEvent = null;
}
}
@onEvent({ selector: 'input', type: 'input' })
refilter(event: Event): void {
this.filter = (event.target as HTMLInputElement).value;
}
@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 cells = this.cells;
const next = cells[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();
}
override render() {
return (
<>
<input type="search" placeholder="Filter events" aria-label="Filter events" />
<h3 data-title>{formatMonthYear(month, locale)}</h3>
<div data-grid role="grid" aria-label="Events by day">
<div role="row">
{getWeekdayLabels(locale, getWeekStartsOn(locale)).map((label) => (
<b role="columnheader">{label}</b>
))}
</div>
{weeks.map((week) => (
<div key={week[0].iso} role="row">
{week.map(({ iso, date, inMonth }) => {
const events = this.visible(this.events, iso);
return (
<div
key={iso}
role="gridcell"
aria-label={dayLabel(date, events.length)}
data-iso={iso}
data-outside={inMonth ? undefined : ''}
>
<span data-day aria-hidden="true">
{date.getDate()}
</span>
{events.map(({ id, title }) => (
<div key={id} data-event={id} tabindex="-1">
{title}
</div>
))}
</div>
);
})}
</div>
))}
</div>
<p data-status aria-live="polite">
{this.$.status}
</p>
</>
);
}
}import { buildCalendarMonth, formatDisplayDate } from '@ecopages/radiant-ui/helpers';
export type CalendarEvent = { id: string; iso: string; title: string };
export const locale = 'en-US';
export const month = new Date(2026, 10, 1);
export const weeks = buildCalendarMonth(month.getFullYear(), month.getMonth(), { locale });
const days = new Map(weeks.flat().map((day) => [day.iso, day]));
/**
* The accessible name of a day cell: the full date, then how many events it holds.
*
* @remarks
* A `gridcell` named by `aria-label` is announced by that name alone, not by its content, so the count has to be in it.
*/
export function dayLabel(date: Date, count: number): string {
const events = count === 0 ? '' : `, ${count} ${count === 1 ? 'event' : 'events'}`;
return `${formatDisplayDate(date, locale, 'full')}${events}`;
}
/**
* Fills a day cell with its number and one node per event, and names the cell after both.
*
* @remarks
* The nodes are built with `textContent`, so an event title is text and is never parsed as markup. Assigning titles to
* `innerHTML` would run a title such as `<img onerror=...>` the moment it reached the page.
*/
export function paintDay(cell: HTMLElement, events: CalendarEvent[]): void {
const { date } = days.get(cell.dataset.iso!)!;
const number = document.createElement('span');
number.dataset.day = '';
number.setAttribute('aria-hidden', 'true');
number.textContent = String(date.getDate());
const items = events.map(({ id, title }) => {
const item = document.createElement('div');
item.dataset.event = id;
item.tabIndex = -1;
item.textContent = title;
return item;
});
cell.setAttribute('aria-label', dayLabel(date, events.length));
cell.replaceChildren(number, ...items);
}
/** Days to move the focus by for each arrow key: one day sideways, one week up or down. */
export const steps: Record<string, number> = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -7, ArrowDown: 7 };
/**
* The events a calendar starts with.
*
* @remarks Forms that move events by editing the list in place start from a copy, so the array stays unchanged.
*/
export const initialEvents: readonly CalendarEvent[] = [
{ id: 'review', iso: '2026-11-03', title: 'Design review' },
{ id: 'standup', iso: '2026-11-03', title: 'Standup' },
{ id: 'launch', iso: '2026-11-12', title: 'Launch day' },
{ id: 'retro', iso: '2026-11-19', title: 'Retro' },
];.primitive-example:has(
> calendar-events-element,
> calendar-events-app,
> [data-controller='calendar-events'],
> [data-example='calendar-events']
) {
flex-direction: column;
flex-wrap: nowrap;
align-items: stretch;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where(input) {
padding: var(--space-1) var(--space-3);
border: 1px solid var(--border);
border-radius: var(--radius-control);
background: var(--surface);
color: var(--on-surface);
font: inherit;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-title]) {
margin: 0;
font-size: 1rem;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-grid]) {
display: grid;
grid-template-columns: repeat(7, minmax(4.5rem, 1fr));
gap: var(--space-1);
overflow-x: auto;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([role='row']) {
display: contents;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([role='columnheader']) {
font-weight: normal;
color: var(--on-surface-container-low);
font-size: 0.75rem;
text-align: center;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([role='gridcell']) {
display: flex;
flex-direction: column;
gap: var(--space-1);
min-height: 5rem;
padding: var(--space-1);
border: 1px solid var(--border);
border-radius: var(--radius-control);
background: var(--surface);
color: var(--on-surface);
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-outside]) {
background: transparent;
color: var(--on-surface-container-low);
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-sortable-over]) {
border-color: var(--primary);
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where(span[data-day]) {
font-size: 0.75rem;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-event]) {
padding: var(--space-1);
overflow-wrap: anywhere;
border-radius: var(--radius-control);
background: var(--surface-container);
color: var(--on-surface-container);
cursor: grab;
touch-action: none;
user-select: none;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-event][data-sortable-state='lifted']) {
background: var(--primary);
color: var(--on-primary);
transform: translate(var(--sortable-dx, 0), var(--sortable-dy, 0));
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-sortable-drop='before']) {
box-shadow: 0 -2px 0 var(--primary);
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-sortable-drop='after']) {
box-shadow: 0 2px 0 var(--primary);
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([role='gridcell']:focus-visible, [data-event]:focus-visible) {
outline: 2px solid var(--focus-ring);
outline-offset: 1px;
}Moving an event writes a new events array and the render draws it; the filter is a second @state that render() reads, so typing leaves out the events that do not match without any code to hide them. The controllers attach when the element connects, before the first render, so updated() attaches them once more when the grid exists, then keeps the roving tab stop in step and focuses the event that moved, found by its id because an event that changed day is a new node. The status line is bound with this.$.status, so announcing during a sort patches one text node and does not call render() again.
Compared with the Radiant element above, there is no day-building and painting code to keep in step with the state, but the markup lives inside the element, so restyling the structure means editing the class. It also needs the render path on the server to have content before the script runs: this docs build prerenders the tag empty and the client draws it, so the page shows nothing until the script loads, which a page of authored children does not.
The same behavior as a RadiantController attached to markup that already exists. There is no tag to define: the page carries data-controller="calendar-events" and the controller finds its parts inside that element.
Focus a day, press Enter, then Space to lift an event
import { RadiantController, controller, 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';
@controller('calendar-events')
export class CalendarEventsController extends RadiantController {
@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 after connecting, then attaches the sortables again.
*
* @remarks
* A `RadiantController` has no `onConnected` hook, and its `@query` fields resolve only once `super.connect()`
* ran, so the cells are built after it. The controllers attach inside `super.connect()`, when the cells do not
* exist, so their containers resolve to nothing and a second `attach()` resolves them again.
* `createSortableController` and `createRovingController` take the controller as host unchanged: it has the same
* two registration methods as `RadiantElement`, so they are destroyed when the host element is removed.
*/
override connect(): void {
super.connect();
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();
}
}import { buildCalendarMonth, formatDisplayDate } from '@ecopages/radiant-ui/helpers';
export type CalendarEvent = { id: string; iso: string; title: string };
export const locale = 'en-US';
export const month = new Date(2026, 10, 1);
export const weeks = buildCalendarMonth(month.getFullYear(), month.getMonth(), { locale });
const days = new Map(weeks.flat().map((day) => [day.iso, day]));
/**
* The accessible name of a day cell: the full date, then how many events it holds.
*
* @remarks
* A `gridcell` named by `aria-label` is announced by that name alone, not by its content, so the count has to be in it.
*/
export function dayLabel(date: Date, count: number): string {
const events = count === 0 ? '' : `, ${count} ${count === 1 ? 'event' : 'events'}`;
return `${formatDisplayDate(date, locale, 'full')}${events}`;
}
/**
* Fills a day cell with its number and one node per event, and names the cell after both.
*
* @remarks
* The nodes are built with `textContent`, so an event title is text and is never parsed as markup. Assigning titles to
* `innerHTML` would run a title such as `<img onerror=...>` the moment it reached the page.
*/
export function paintDay(cell: HTMLElement, events: CalendarEvent[]): void {
const { date } = days.get(cell.dataset.iso!)!;
const number = document.createElement('span');
number.dataset.day = '';
number.setAttribute('aria-hidden', 'true');
number.textContent = String(date.getDate());
const items = events.map(({ id, title }) => {
const item = document.createElement('div');
item.dataset.event = id;
item.tabIndex = -1;
item.textContent = title;
return item;
});
cell.setAttribute('aria-label', dayLabel(date, events.length));
cell.replaceChildren(number, ...items);
}
/** Days to move the focus by for each arrow key: one day sideways, one week up or down. */
export const steps: Record<string, number> = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -7, ArrowDown: 7 };
/**
* The events a calendar starts with.
*
* @remarks Forms that move events by editing the list in place start from a copy, so the array stays unchanged.
*/
export const initialEvents: readonly CalendarEvent[] = [
{ id: 'review', iso: '2026-11-03', title: 'Design review' },
{ id: 'standup', iso: '2026-11-03', title: 'Standup' },
{ id: 'launch', iso: '2026-11-12', title: 'Launch day' },
{ id: 'retro', iso: '2026-11-19', title: 'Retro' },
];<div data-controller="calendar-events">
<input type="search" placeholder="Filter events" aria-label="Filter events" />
<h3 data-title></h3>
<div data-grid role="grid" aria-label="Events by day"></div>
<p data-status aria-live="polite">Focus a day, press Enter, then Space to lift an event</p>
</div>.primitive-example:has(
> calendar-events-element,
> calendar-events-app,
> [data-controller='calendar-events'],
> [data-example='calendar-events']
) {
flex-direction: column;
flex-wrap: nowrap;
align-items: stretch;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where(input) {
padding: var(--space-1) var(--space-3);
border: 1px solid var(--border);
border-radius: var(--radius-control);
background: var(--surface);
color: var(--on-surface);
font: inherit;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-title]) {
margin: 0;
font-size: 1rem;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-grid]) {
display: grid;
grid-template-columns: repeat(7, minmax(4.5rem, 1fr));
gap: var(--space-1);
overflow-x: auto;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([role='row']) {
display: contents;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([role='columnheader']) {
font-weight: normal;
color: var(--on-surface-container-low);
font-size: 0.75rem;
text-align: center;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([role='gridcell']) {
display: flex;
flex-direction: column;
gap: var(--space-1);
min-height: 5rem;
padding: var(--space-1);
border: 1px solid var(--border);
border-radius: var(--radius-control);
background: var(--surface);
color: var(--on-surface);
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-outside]) {
background: transparent;
color: var(--on-surface-container-low);
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-sortable-over]) {
border-color: var(--primary);
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where(span[data-day]) {
font-size: 0.75rem;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-event]) {
padding: var(--space-1);
overflow-wrap: anywhere;
border-radius: var(--radius-control);
background: var(--surface-container);
color: var(--on-surface-container);
cursor: grab;
touch-action: none;
user-select: none;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-event][data-sortable-state='lifted']) {
background: var(--primary);
color: var(--on-primary);
transform: translate(var(--sortable-dx, 0), var(--sortable-dy, 0));
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-sortable-drop='before']) {
box-shadow: 0 -2px 0 var(--primary);
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-sortable-drop='after']) {
box-shadow: 0 2px 0 var(--primary);
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([role='gridcell']:focus-visible, [data-event]:focus-visible) {
outline: 2px solid var(--focus-ring);
outline-offset: 1px;
}The class is the element form's logic on a different base: @query, @onEvent and the two create...Controller(this, ...) calls work unchanged, because a RadiantController has the same registration methods as a RadiantElement. It has no onConnected hook, so the days are built in an override of connect() after super.connect(), and the sortables are attached once more there to resolve their containers, as in the element form.
Compared with the Radiant element, there is no custom element tag to define, so the markup can come from a server template or a CMS and only has to carry data-controller. One registry that the docs site starts over the document attaches the controller to each matching element, including ones inserted later, and disconnects it when the element is removed, which destroys the sortables and the roving controller. The cost is that the script only registers a class: nothing runs until a registry is started, and the controller name is global, where a tag name is already scoped to the page.
A mount function wires the controllers to the markup and returns the cleanup that undoes it.
Focus a day, press Enter, then Space to lift an event
import { RovingController, SortableController, SortableGroup } 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';
export function mount(root: HTMLElement): () => void {
const filter = root.querySelector('input')!;
const grid = root.querySelector<HTMLElement>('[data-grid]')!;
const status = root.querySelector('[data-status]')!;
const events = initialEvents.map((event) => ({ ...event }));
root.querySelector('[data-title]')!.textContent = formatMonthYear(month, locale);
const headers = getWeekdayLabels(locale, getWeekStartsOn(locale)).map(
(label) => `<b role="columnheader">${label}</b>`,
);
grid.insertAdjacentHTML('beforeend', `<div role="row">${headers.join('')}</div>`);
const cells: HTMLElement[] = weeks.flatMap((week) => {
const row = 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;
});
});
const visible = (iso: string) =>
events.filter((event) => event.iso === iso && textContains(event.title, filter.value));
function render(): void {
for (const cell of cells) paintDay(cell, visible(cell.dataset.iso!));
}
const group = new SortableGroup();
const sortables = cells.map(
(cell) =>
new SortableController({
group,
getContainer: () => cell,
getItems: () => [...cell.querySelectorAll<HTMLElement>('[data-event]')],
announce: (message) => (status.textContent = message),
onChange: ({ item, to, toContainer }) => {
const moved = events.find((event) => event.id === item.dataset.event)!;
events.splice(events.indexOf(moved), 1);
moved.iso = toContainer.dataset.iso!;
const next = visible(moved.iso)[to];
events.splice(next ? events.indexOf(next) : events.length, 0, moved);
render();
grid.querySelector<HTMLElement>(`[data-event="${moved.id}"]`)!.focus();
},
}),
);
for (const sortable of sortables) sortable.attach();
const roving = new RovingController({ getItems: () => cells, getTarget: () => grid, orientation: 'none' });
grid.addEventListener('keydown', (event) => {
const target = event.target as HTMLElement;
if (target.hasAttribute('data-event')) {
if (event.key === 'Escape') target.closest<HTMLElement>('[role="gridcell"]')!.focus();
return;
}
const next = cells[cells.indexOf(target) + (steps[event.key] ?? 0)];
if (event.key === 'Enter') target.querySelector<HTMLElement>('[data-event]')?.focus();
else if (steps[event.key] && next) roving.focus(next);
else return;
event.preventDefault();
});
filter.addEventListener('input', render);
render();
roving.attach();
roving.sync();
return () => {
for (const sortable of sortables) sortable.destroy();
roving.destroy();
};
}import { buildCalendarMonth, formatDisplayDate } from '@ecopages/radiant-ui/helpers';
export type CalendarEvent = { id: string; iso: string; title: string };
export const locale = 'en-US';
export const month = new Date(2026, 10, 1);
export const weeks = buildCalendarMonth(month.getFullYear(), month.getMonth(), { locale });
const days = new Map(weeks.flat().map((day) => [day.iso, day]));
/**
* The accessible name of a day cell: the full date, then how many events it holds.
*
* @remarks
* A `gridcell` named by `aria-label` is announced by that name alone, not by its content, so the count has to be in it.
*/
export function dayLabel(date: Date, count: number): string {
const events = count === 0 ? '' : `, ${count} ${count === 1 ? 'event' : 'events'}`;
return `${formatDisplayDate(date, locale, 'full')}${events}`;
}
/**
* Fills a day cell with its number and one node per event, and names the cell after both.
*
* @remarks
* The nodes are built with `textContent`, so an event title is text and is never parsed as markup. Assigning titles to
* `innerHTML` would run a title such as `<img onerror=...>` the moment it reached the page.
*/
export function paintDay(cell: HTMLElement, events: CalendarEvent[]): void {
const { date } = days.get(cell.dataset.iso!)!;
const number = document.createElement('span');
number.dataset.day = '';
number.setAttribute('aria-hidden', 'true');
number.textContent = String(date.getDate());
const items = events.map(({ id, title }) => {
const item = document.createElement('div');
item.dataset.event = id;
item.tabIndex = -1;
item.textContent = title;
return item;
});
cell.setAttribute('aria-label', dayLabel(date, events.length));
cell.replaceChildren(number, ...items);
}
/** Days to move the focus by for each arrow key: one day sideways, one week up or down. */
export const steps: Record<string, number> = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -7, ArrowDown: 7 };
/**
* The events a calendar starts with.
*
* @remarks Forms that move events by editing the list in place start from a copy, so the array stays unchanged.
*/
export const initialEvents: readonly CalendarEvent[] = [
{ id: 'review', iso: '2026-11-03', title: 'Design review' },
{ id: 'standup', iso: '2026-11-03', title: 'Standup' },
{ id: 'launch', iso: '2026-11-12', title: 'Launch day' },
{ id: 'retro', iso: '2026-11-19', title: 'Retro' },
];<div data-example="calendar-events">
<input type="search" placeholder="Filter events" aria-label="Filter events" />
<h3 data-title></h3>
<div data-grid role="grid" aria-label="Events by day"></div>
<p data-status aria-live="polite">Focus a day, press Enter, then Space to lift an event</p>
</div>.primitive-example:has(
> calendar-events-element,
> calendar-events-app,
> [data-controller='calendar-events'],
> [data-example='calendar-events']
) {
flex-direction: column;
flex-wrap: nowrap;
align-items: stretch;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where(input) {
padding: var(--space-1) var(--space-3);
border: 1px solid var(--border);
border-radius: var(--radius-control);
background: var(--surface);
color: var(--on-surface);
font: inherit;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-title]) {
margin: 0;
font-size: 1rem;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-grid]) {
display: grid;
grid-template-columns: repeat(7, minmax(4.5rem, 1fr));
gap: var(--space-1);
overflow-x: auto;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([role='row']) {
display: contents;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([role='columnheader']) {
font-weight: normal;
color: var(--on-surface-container-low);
font-size: 0.75rem;
text-align: center;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([role='gridcell']) {
display: flex;
flex-direction: column;
gap: var(--space-1);
min-height: 5rem;
padding: var(--space-1);
border: 1px solid var(--border);
border-radius: var(--radius-control);
background: var(--surface);
color: var(--on-surface);
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-outside]) {
background: transparent;
color: var(--on-surface-container-low);
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-sortable-over]) {
border-color: var(--primary);
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where(span[data-day]) {
font-size: 0.75rem;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-event]) {
padding: var(--space-1);
overflow-wrap: anywhere;
border-radius: var(--radius-control);
background: var(--surface-container);
color: var(--on-surface-container);
cursor: grab;
touch-action: none;
user-select: none;
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-event][data-sortable-state='lifted']) {
background: var(--primary);
color: var(--on-primary);
transform: translate(var(--sortable-dx, 0), var(--sortable-dy, 0));
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-sortable-drop='before']) {
box-shadow: 0 -2px 0 var(--primary);
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([data-sortable-drop='after']) {
box-shadow: 0 2px 0 var(--primary);
}
:is(
[data-example='calendar-events'],
calendar-events-element,
calendar-events-app,
div[data-controller='calendar-events']
)
:where([role='gridcell']:focus-visible, [data-event]:focus-visible) {
outline: 2px solid var(--focus-ring);
outline-offset: 1px;
}mount runs once for each example element on the page, and the function it returns undoes it; see how the examples run.