Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(lab): the Schedule month view takes renderPopover (#7113)

Cindy Zhangb5e5e6832552
diff --git a/apps/storybook/stories/Schedule.stories.tsx b/apps/storybook/stories/Schedule.stories.tsx
index 914f421540..c440a50cb8 100644
--- a/apps/storybook/stories/Schedule.stories.tsx
+++ b/apps/storybook/stories/Schedule.stories.tsx
@@ -789,6 +789,59 @@ export const MonthOverflow: Story = {
},
};
+// The month-overflow fixture with renderPopover (component:Schedule FR19–
+// FR20): chips with content open the month's one popover, the company
+// holiday has none and stays static text, and a busy day's list hands an
+// event to the same popover.
+export const MonthEventPopover: Story = {
+ render: () => {
+ const [date, setDate] = useState<Instant>(FIXTURE_DATE);
+ const monthEvents = useSyncExternalStore(
+ subscribeToMonthOverflowEvents,
+ getMonthOverflowEvents,
+ getMonthOverflowEvents,
+ );
+ const view = useMemo(
+ () =>
+ createScheduleMonthlyView({
+ renderPopover: event =>
+ event.id === 'holiday' ? null : (
+ <div
+ data-event-details={event.id}
+ style={{display: 'flex', flexDirection: 'column', gap: 4}}>
+ <Text type="label" weight="bold">
+ {event.title}
+ </Text>
+ <Text type="supporting" color="secondary">
+ {event.category ?? 'No category'} · {event.id}
+ </Text>
+ </div>
+ ),
+ }),
+ [],
+ );
+ useEffect(() => {
+ (
+ window as unknown as {
+ scheduleMonthOverflowStory?: {removeEvent: (id: string) => void};
+ }
+ ).scheduleMonthOverflowStory = {removeEvent: removeMonthOverflowEvent};
+ }, []);
+
+ return (
+ <Schedule
+ view={view}
+ events={monthEvents}
+ categories={categories}
+ date={date}
+ focusDate={FIXTURE_DATE}
+ onChangeDate={setDate}
+ timezoneID={FIXTURE_TIMEZONE}
+ />
+ );
+ },
+};
+
export const ViewSelectorPlugin: Story = {
render: () => {
const views = useMemo(
diff --git a/packages/lab/src/Schedule/MonthlyView.tsx b/packages/lab/src/Schedule/MonthlyView.tsx
index c4666539ab..16ce470f3b 100644
--- a/packages/lab/src/Schedule/MonthlyView.tsx
+++ b/packages/lab/src/Schedule/MonthlyView.tsx
@@ -6,12 +6,14 @@
* @file MonthlyView.tsx
* @input Schedule context and monthly view options
* @output Month grid schedule view factory: chips on at most three levels per
- * week row, and a "+N more" button on a busy day that opens the view's one
- * popover listing that day's events
+ * week row, each in the cell where it starts; a "+N more" button on a busy
+ * day that opens the view's one popover listing that day's events; and,
+ * with renderPopover, chips and list rows that open an event's content in
+ * that same popover
* @position Concrete schedule view; exported as createScheduleMonthlyView
*/
-import {useRef} from 'react';
+import {useRef, type ReactNode} from 'react';
import * as stylex from '@stylexjs/stylex';
import {layerAnimations} from '@astryxdesign/core/Layer';
import {spacingVars} from '@astryxdesign/core/theme/tokens.stylex';
@@ -29,20 +31,27 @@ import {
type PlainDate,
} from '@astryxdesign/core/utils';
import {Heading, Text} from '@astryxdesign/core/Text';
-import {enumerateDates, getScheduleRangeFromDates} from './dateMath';
+import {
+ enumerateDates,
+ getScheduleRangeFromDates,
+ isDayEvent,
+} from './dateMath';
import {useScheduleContext} from './context';
import {
getEventDateSpan,
layoutMonthEvents,
MONTH_VISIBLE_LEVELS,
+ type MonthChipPlacement,
} from './monthLayout';
import {
formatDayNumber,
formatEventAccessibilityLabel,
+ formatEventTimeRange,
formatFullDate,
formatMonthTitle,
formatWeekday,
formatWeekRange,
+ getEventCategory,
isEventInPast,
ListEventRow,
MonthEventPill,
@@ -54,19 +63,68 @@ import {
import {useCurrentTime} from './useCurrentTime';
import {useScheduleViewPopover} from './useScheduleViewPopover';
import {scheduleRangeToZonedDateTimeRange} from './zonedDateTime';
+import type {Locale} from '@astryxdesign/core/i18n';
import type {
CalendarEvent,
+ ScheduleCategory,
ScheduleView,
ScheduleViewComponentProps,
} from './types';
export interface ScheduleMonthlyViewOptions {
weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6;
+ /**
+ * Content of the view-owned event popover. A chip whose content is not
+ * null or undefined is a button that opens it; absent, the month is
+ * read-only (component:Schedule FR19–FR20).
+ */
+ renderPopover?: (event: CalendarEvent) => ReactNode;
+}
+
+// The view's one popover shows a busy day's list, a chip's event, or an event
+// handed over from a day's list. Event ids may contain any character, so the
+// id is always the key's last part.
+type MonthPopoverKey =
+ | {kind: 'day'; dayISO: string}
+ | {kind: 'chip'; segment: string; eventID: string}
+ | {kind: 'row'; dayISO: string; eventID: string};
+
+function dayKey(dayISO: string): string {
+ return `day/${dayISO}`;
+}
+
+/** One painted chip: a span cut around a busy day paints as two chips. */
+function chipKey(chip: MonthChipPlacement): string {
+ return `chip/${chip.week}:${chip.columnStart}/${chip.event.id}`;
+}
+
+function rowKey(dayISO: string, eventID: string): string {
+ return `row/${dayISO}/${eventID}`;
}
-function ScheduleMonthlyView(
- _props: ScheduleViewComponentProps<ScheduleMonthlyViewOptions>,
-) {
+function parseKey(key: string | null): MonthPopoverKey | null {
+ if (key == null) {
+ return null;
+ }
+ const kind = key.slice(0, key.indexOf('/'));
+ const rest = key.slice(kind.length + 1);
+ if (kind === 'day') {
+ return {kind, dayISO: rest};
+ }
+ const second = rest.indexOf('/');
+ const head = rest.slice(0, second);
+ const eventID = rest.slice(second + 1);
+ if (kind === 'chip') {
+ return {kind, segment: head, eventID};
+ }
+ return kind === 'row' ? {kind, dayISO: head, eventID} : null;
+}
+
+function ScheduleMonthlyView({
+ options,
+}: ScheduleViewComponentProps<ScheduleMonthlyViewOptions>) {
+ const {renderPopover} = options;
+ const hasPopover = renderPopover != null;
const {
events,
categories,
@@ -88,28 +146,112 @@ function ScheduleMonthlyView(
layout.overflow.map(day => [day.dayIndex, day.count]),
);
const eventsByDay = getMonthEventsByDay(events, days, timezoneID);
- // Day popover (component:Schedule FR17, AR7): one popover for the grid,
- // opened from a busy day's "+N more" and named by that day's full date.
- const dayByKey = new Map<string, PlainDate>(
+ // Every chip that covers each day, in level order: a chip renders in the
+ // cell where it starts, and with renderPopover each later day it covers
+ // names it as static text (component:Schedule FR19, AR8).
+ const chipsByDay = new Map<number, MonthChipPlacement[]>();
+ for (const chip of layout.chips) {
+ for (let column = chip.columnStart; column <= chip.columnEnd; column += 1) {
+ const index = chip.week * 7 + column;
+ const cellChips = chipsByDay.get(index) ?? [];
+ cellChips.push(chip);
+ chipsByDay.set(index, cellChips);
+ }
+ }
+ chipsByDay.forEach(cellChips => cellChips.sort((a, b) => a.level - b.level));
+ const eventByID = new Map(events.map(event => [event.id, event]));
+ // The view's one popover (component:Schedule FR17, FR20, AR7): a busy
+ // day's list named by its full date, or one event's content named by its
+ // title.
+ const dayByISO = new Map<string, PlainDate>(
days.map(day => [plainDateToISO(day), day]),
);
const monthTitle = formatMonthTitle(rangeDate, timezoneID, locale);
const tableRef = useRef<HTMLDivElement>(null);
- const dayPopover = useScheduleViewPopover(
+ // Where each chip painted so far starts, so focus can land on that cell if
+ // the chip goes away while its popover is open.
+ const chipStartDayRef = useRef(new Map<string, string>());
+ const chipStartDay = chipStartDayRef.current;
+ const focusCell = (dayISO: string | undefined) => {
+ if (dayISO != null) {
+ tableRef.current
+ ?.querySelector<HTMLElement>(`[data-schedule-day="${dayISO}"]`)
+ ?.focus();
+ }
+ };
+ const monthPopover = useScheduleViewPopover(
key => {
- const day = key == null ? undefined : dayByKey.get(key);
- return day == null ? monthTitle : formatFullDate(day, timezoneID, locale);
+ const parsed = parseKey(key);
+ if (parsed == null) {
+ return monthTitle;
+ }
+ if (parsed.kind === 'day') {
+ const day = dayByISO.get(parsed.dayISO);
+ return day == null
+ ? monthTitle
+ : formatFullDate(day, timezoneID, locale);
+ }
+ return eventByID.get(parsed.eventID)?.title ?? monthTitle;
},
- // A day that stops being busy takes its "+N more" with it; focus lands
- // on that day's cell instead of the page.
+ // What opened the popover is gone: focus lands on the day it belonged
+ // to, or on the day's "+N more" when an event leaves a day that is
+ // still busy.
key => {
- tableRef.current
- ?.querySelector<HTMLElement>(`[data-schedule-day="${key}"]`)
- ?.focus();
+ const parsed = parseKey(key);
+ if (parsed == null) {
+ return;
+ }
+ if (parsed.kind === 'chip') {
+ focusCell(chipStartDayRef.current.get(key));
+ return;
+ }
+ const more =
+ parsed.kind === 'row'
+ ? tableRef.current?.querySelector<HTMLElement>(
+ `[data-schedule-popover-trigger="${dayKey(parsed.dayISO)}"]`,
+ )
+ : null;
+ if (more != null) {
+ more.focus();
+ return;
+ }
+ focusCell(parsed.dayISO);
},
);
+ const openParsed = parseKey(monthPopover.openKey);
const openDay =
- dayPopover.openKey == null ? null : dayByKey.get(dayPopover.openKey);
+ openParsed?.kind === 'day' ? dayByISO.get(openParsed.dayISO) : undefined;
+ const openEvent =
+ openParsed != null && openParsed.kind !== 'day'
+ ? eventByID.get(openParsed.eventID)
+ : undefined;
+ // The popover's content scrolls inside its surface, never the layer
+ // (SchedulePopoverBody): a day's list, or one event's content.
+ let openContent: ReactNode = null;
+ if (openDay != null) {
+ const openDayISO = plainDateToISO(openDay);
+ openContent = (
+ <SchedulePopoverBody
+ label={`${formatFullDate(openDay, timezoneID, locale)} events`}>
+ <MonthDayEvents
+ day={openDay}
+ events={eventsByDay.get(openDayISO) ?? EMPTY_EVENTS}
+ renderPopover={renderPopover}
+ onOpenEvent={event =>
+ monthPopover.switchTo(rowKey(openDayISO, event.id))
+ }
+ />
+ </SchedulePopoverBody>
+ );
+ } else if (openEvent != null) {
+ const content = renderPopover?.(openEvent) ?? null;
+ openContent =
+ content == null ? null : (
+ <SchedulePopoverBody label={`${openEvent.title} details`}>
+ {content}
+ </SchedulePopoverBody>
+ );
+ }
return (
<ScheduleFrame
@@ -128,7 +270,7 @@ function ScheduleMonthlyView(
role="table"
aria-label={monthTitle}
tabIndex={0}
- {...dayPopover.containerProps}
+ {...monthPopover.containerProps}
{...stylex.props(styles.monthGrid)}>
<div role="row" {...stylex.props(styles.weekHeader)}>
<div
@@ -214,7 +356,46 @@ function ScheduleMonthlyView(
{formatDayNumber(day, timezoneID, locale)}
</Text>
</div>
- {dayEvents.length > 0 && (
+ {(chipsByDay.get(index) ?? EMPTY_CHIPS).map(chip => {
+ const key = chipKey(chip);
+ if (chip.columnStart !== dayIndex) {
+ const startDay =
+ days[chip.week * 7 + chip.columnStart];
+ return hasPopover && startDay != null ? (
+ <span
+ key={key}
+ {...stylex.props(styles.visuallyHidden)}>
+ {formatMonthEventName(
+ chip.event,
+ `since ${formatFullDate(startDay, timezoneID, locale)}`,
+ timezoneID,
+ categories,
+ locale,
+ )}
+ </span>
+ ) : null;
+ }
+ chipStartDay.set(key, dayISO);
+ return (
+ <MonthChip
+ key={key}
+ chip={chip}
+ isLastColumn={dayIndex === 6}
+ popoverKey={key}
+ popover={monthPopover}
+ renderPopover={renderPopover}
+ isPast={isEventInPast(
+ chip.event,
+ currentTime,
+ timezoneID,
+ )}
+ />
+ );
+ })}
+ {/* With renderPopover the chips are the cell's
+ accessible events, so the hidden list would repeat
+ them (component:Schedule FR19). */}
+ {!hasPopover && dayEvents.length > 0 && (
<ul {...stylex.props(styles.visuallyHidden)}>
{dayEvents.map(event => (
<li key={event.id}>
@@ -235,7 +416,22 @@ function ScheduleMonthlyView(
aria-label={`${hiddenCount} more ${
hiddenCount === 1 ? 'event' : 'events'
}, ${formatFullDate(day, timezoneID, locale)}`}
- {...dayPopover.getTriggerProps(dayISO)}
+ {...monthPopover.getTriggerProps(
+ dayKey(dayISO),
+ // An event handed over from this day's list
+ // keeps "+N more" as its trigger while the
+ // event is still on this day.
+ openKey => {
+ const parsed = parseKey(openKey);
+ return (
+ parsed?.kind === 'row' &&
+ parsed.dayISO === dayISO &&
+ dayEvents.some(
+ event => event.id === parsed.eventID,
+ )
+ );
+ },
+ )}
{...stylex.props(
styles.eventButtonReset,
styles.monthMoreButton,
@@ -255,79 +451,182 @@ function ScheduleMonthlyView(
</div>
))}
</div>
- <div aria-hidden {...stylex.props(styles.monthEventOverlay)}>
- {layout.chips.map(segment => (
- <div
- key={`${segment.event.id}:${segment.week}:${segment.columnStart}`}
- {...stylex.props(
- styles.monthEventSpan(
- segment.week,
- segment.columnStart,
- segment.columnEnd,
- segment.level,
- ),
- )}>
- <MonthEventPill
- event={segment.event}
- timezoneID={timezoneID}
- isPast={isEventInPast(segment.event, currentTime, timezoneID)}
- />
- </div>
- ))}
- </div>
</div>
</div>
- {dayPopover.popover.render(
- openDay == null ? null : (
- <SchedulePopoverBody
- label={`${formatFullDate(openDay, timezoneID, locale)} events`}>
- <MonthDayEvents
- day={openDay}
- events={eventsByDay.get(plainDateToISO(openDay)) ?? EMPTY_EVENTS}
- />
- </SchedulePopoverBody>
- ),
- {
- placement: 'below',
- alignment: 'start',
- offset: spacingVars['--spacing-1'],
- xstyle: layerAnimations.below,
- },
- )}
+ {monthPopover.popover.render(openContent, {
+ placement: 'below',
+ alignment: 'start',
+ offset: spacingVars['--spacing-1'],
+ xstyle: layerAnimations.below,
+ })}
</ScheduleFrame>
);
}
-/** The day popover's content: every event of one day, in start order. */
+/**
+ * One chip, in the cell where it starts. Read-only it is painted
+ * decoration; with renderPopover it is the button that opens its event, or
+ * static text when the event has no content (component:Schedule FR19, AR8).
+ */
+function MonthChip({
+ chip,
+ isLastColumn,
+ popoverKey,
+ popover,
+ renderPopover,
+ isPast,
+}: {
+ chip: MonthChipPlacement;
+ isLastColumn: boolean;
+ popoverKey: string;
+ popover: ReturnType<typeof useScheduleViewPopover>;
+ renderPopover: ScheduleMonthlyViewOptions['renderPopover'];
+ isPast: boolean;
+}) {
+ const {categories, timezoneID, locale} = useScheduleContext();
+ const placement = [
+ styles.monthChip(chip.columnEnd - chip.columnStart + 1, chip.level),
+ isLastColumn && styles.monthChipInLastColumn,
+ ];
+ const pill = (
+ <MonthEventPill
+ event={chip.event}
+ timezoneID={timezoneID}
+ isPast={isPast}
+ />
+ );
+ if (renderPopover == null) {
+ return (
+ <div aria-hidden data-schedule-month-chip="" {...stylex.props(placement)}>
+ {pill}
+ </div>
+ );
+ }
+ const name = formatMonthEventName(
+ chip.event,
+ formatEventDays(chip.event, timezoneID, locale),
+ timezoneID,
+ categories,
+ locale,
+ );
+ if (renderPopover(chip.event) == null) {
+ return (
+ <div data-schedule-month-chip="" {...stylex.props(placement)}>
+ <span {...stylex.props(styles.visuallyHidden)}>{name}</span>
+ <span aria-hidden>{pill}</span>
+ </div>
+ );
+ }
+ return (
+ <button
+ type="button"
+ aria-label={name}
+ data-schedule-month-chip=""
+ {...popover.getTriggerProps(popoverKey)}
+ {...stylex.props(
+ styles.eventButtonReset,
+ placement,
+ styles.monthChipFocus,
+ focusOutlineStyles.focusVisible,
+ )}>
+ {pill}
+ </button>
+ );
+}
+
+/**
+ * A busy day's list: every event of the day, in start order. With
+ * renderPopover, a row whose event has content is a button that hands the
+ * event to the view's popover (component:Schedule FR20).
+ */
function MonthDayEvents({
day,
events,
+ renderPopover,
+ onOpenEvent,
}: {
day: PlainDate;
events: ReadonlyArray<CalendarEvent>;
+ renderPopover: ScheduleMonthlyViewOptions['renderPopover'];
+ onOpenEvent: (event: CalendarEvent) => void;
}) {
- const {timezoneID, locale} = useScheduleContext();
+ const {categories, timezoneID, locale} = useScheduleContext();
const currentTime = useCurrentTime();
+ const fullDate = formatFullDate(day, timezoneID, locale);
return (
<div {...stylex.props(styles.monthDayEvents)}>
<Text type="supporting" weight="bold" color="secondary">
- {formatFullDate(day, timezoneID, locale)}
+ {fullDate}
</Text>
<ul {...stylex.props(styles.monthDayEventList)}>
- {events.map(event => (
- <li key={event.id}>
+ {events.map(event => {
+ const row = (
<ListEventRow
event={event}
timezoneID={timezoneID}
isPast={isEventInPast(event, currentTime, timezoneID)}
/>
- </li>
- ))}
+ );
+ return (
+ <li key={event.id}>
+ {renderPopover?.(event) == null ? (
+ row
+ ) : (
+ <button
+ type="button"
+ aria-label={formatMonthEventName(
+ event,
+ fullDate,
+ timezoneID,
+ categories,
+ locale,
+ )}
+ onClick={() => onOpenEvent(event)}
+ {...stylex.props(
+ styles.eventButtonReset,
+ styles.monthDayEventButton,
+ focusOutlineStyles.focusVisible,
+ )}>
+ {row}
+ </button>
+ )}
+ </li>
+ );
+ })}
</ul>
</div>
);
}
+/**
+ * A month event button's name: the title, the time range or "all day", the
+ * category, and the day (component:Schedule AR8).
+ */
+function formatMonthEventName(
+ event: CalendarEvent,
+ dayLabel: string,
+ timezoneID: string,
+ categories: ReadonlyArray<ScheduleCategory>,
+ locale: Locale,
+): string {
+ const time = isDayEvent(event)
+ ? 'all day'
+ : formatEventTimeRange(event, timezoneID, locale);
+ return `${event.title}, ${time}, ${getEventCategory(event, categories).label}, ${dayLabel}`;
+}
+
+/** The event's day, or its date range when it covers several days. */
+function formatEventDays(
+ event: CalendarEvent,
+ timezoneID: string,
+ locale: Locale,
+): string {
+ const [first, last] = getEventDateSpan(event, timezoneID);
+ return plainDateIsEqual(first, last)
+ ? formatFullDate(first, timezoneID, locale)
+ : formatWeekRange(first, last, timezoneID, locale);
+}
+
function getWeeks(days: ReadonlyArray<PlainDate>): PlainDate[][] {
const weeks: PlainDate[][] = [];
for (let index = 0; index < days.length; index += 7) {
@@ -337,6 +636,7 @@ function getWeeks(days: ReadonlyArray<PlainDate>): PlainDate[][] {
}
const EMPTY_EVENTS: ReadonlyArray<CalendarEvent> = [];
+const EMPTY_CHIPS: ReadonlyArray<MonthChipPlacement> = [];
function getMonthEventsByDay(
events: ReadonlyArray<CalendarEvent>,
@@ -377,10 +677,11 @@ function getMonthEventsByDay(
export function createScheduleMonthlyView({
weekStartsOn = 0,
+ renderPopover,
}: ScheduleMonthlyViewOptions = {}): ScheduleView<ScheduleMonthlyViewOptions> {
return {
component: ScheduleMonthlyView,
- options: {weekStartsOn},
+ options: {weekStartsOn, renderPopover},
getDateRange: date => {
const range = getMonthDateRange({
date: date.toPlainDate(),
diff --git a/packages/lab/src/Schedule/Schedule.doc.mjs b/packages/lab/src/Schedule/Schedule.doc.mjs
index 1c162b6edf..cb87c7be6b 100644
--- a/packages/lab/src/Schedule/Schedule.doc.mjs
+++ b/packages/lab/src/Schedule/Schedule.doc.mjs
@@ -10,7 +10,7 @@ export const docs = {
usage: {
description:
- "Schedule is a calendar surface that renders events as a month grid, a day or week time grid, or a list grouped by day: the layout comes from a view object you pass in. It handles timezone-aware date math, paging between ranges, and async event loading, and exposes header slots that plugins fill with navigation controls. Use it to display an existing schedule; build the week or day view with renderPopover to let people open an event's details in a popover the view manages. It has no event selection, creation, or editing affordances.",
+ "Schedule is a calendar surface that renders events as a month grid, a day or week time grid, or a list grouped by day: the layout comes from a view object you pass in. It handles timezone-aware date math, paging between ranges, and async event loading, and exposes header slots that plugins fill with navigation controls. Use it to display an existing schedule; build the week, day, or month view with renderPopover to let people open an event's details in a popover the view manages. It has no event selection, creation, or editing affordances.",
bestPractices: [
{
guidance: true,
@@ -88,7 +88,7 @@ export const docs = {
name: 'Event',
required: false,
description:
- 'One pill (grid views) or row with a color dot (list view) per event, tinted by its category and dimmed once it is in the past. In the day and week grids, events that happen at the same time share the column side by side, and when the view is built with renderPopover each event with content is a button that opens the view\'s popover. In the month grid a week row shows at most three levels of chips; a busy day shows two and a "+N more" button that opens a popover listing every event of that day. A month chip leads with the title; the start time of a timed event follows it only when both fit.',
+ 'One pill (grid views) or row with a color dot (list view) per event, tinted by its category and dimmed once it is in the past. In the day and week grids, events that happen at the same time share the column side by side, and when the view is built with renderPopover each event with content is a button that opens the view\'s popover. In the month grid a week row shows at most three levels of chips; a busy day shows two and a "+N more" button that opens a popover listing every event of that day. A month chip leads with the title; the start time of a timed event follows it only when both fit. When the month view is built with renderPopover, each chip with content is a button that opens the same popover as its day\'s "+N more", and each later day a chip covers names its event for screen readers.',
},
{
name: 'Current time line',
@@ -104,7 +104,7 @@ export const docs = {
name: 'view',
type: 'ScheduleView<Options>',
description:
- "The view object that owns the layout and the date range each page covers. Build one with createScheduleMonthlyView, createScheduleWeeklyView, createScheduleDayView, or createScheduleListView; each factory takes its own options (weekStartsOn, minHour/maxHour/hourHeight, days). The week and day factories also take renderPopover(event): return the content for an event and the view renders that event as a button that opens a popover it manages — one popover for the grid, named by the event title, with the system's standard surface, padding, Escape and light dismiss, and focus return; return null to leave an event read-only. The month and list views have no interaction option.",
+ "The view object that owns the layout and the date range each page covers. Build one with createScheduleMonthlyView, createScheduleWeeklyView, createScheduleDayView, or createScheduleListView; each factory takes its own options (weekStartsOn, minHour/maxHour/hourHeight, days). The week, day, and month factories also take renderPopover(event): return the content for an event and the view renders that event as a button that opens a popover it manages — one popover for the view, named by the event title, with the system's standard surface, padding, Escape and light dismiss, and focus return; return null to leave an event read-only. In the month view that popover also shows a busy day's list, and a row in the list opens its event in place. The list view has no interaction option.",
required: true,
},
{
diff --git a/packages/lab/src/Schedule/Schedule.test.tsx b/packages/lab/src/Schedule/Schedule.test.tsx
index aab4cb09af..0593316785 100644
--- a/packages/lab/src/Schedule/Schedule.test.tsx
+++ b/packages/lab/src/Schedule/Schedule.test.tsx
@@ -1,7 +1,13 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
import {describe, it, expect, vi} from 'vitest';
-import {fireEvent, render, screen, waitFor} from '@testing-library/react';
+import {
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+ within,
+} from '@testing-library/react';
import {useMemo, useState} from 'react';
import {InternationalizationProvider} from '@astryxdesign/core/i18n';
import {createEventFromISO} from './CalendarEvent';
@@ -1200,3 +1206,218 @@ describe('Schedule month overflow', () => {
expect(screen.queryByRole('dialog')).toBeNull();
});
});
+
+describe('Schedule month event popover', () => {
+ // component:Schedule FR19–FR20 and AR8, on May 2026 in UTC. Wednesday May 13
+ // is busy: the conference span and Alpha review are painted, and "+3 more"
+ // counts Offsite, Bravo sync, and Charlie demo. The holiday has no content.
+ const categories: ScheduleCategory[] = [
+ {label: 'Company', color: 'blue'},
+ {label: 'Launch', color: 'green'},
+ ];
+ const timed = (id: string, title: string, day: number, hour: number) =>
+ createEventFromISO({
+ id,
+ title,
+ category: 'Company',
+ start: `2026-05-${day}T${String(hour).padStart(2, '0')}:00:00.000Z`,
+ end: `2026-05-${day}T${String(hour + 1).padStart(2, '0')}:00:00.000Z`,
+ });
+ const events: CalendarEvent[] = [
+ createEventFromISO({
+ id: 'conference',
+ title: 'Conference',
+ category: 'Launch',
+ start: '2026-05-10',
+ end: '2026-05-13',
+ }),
+ createEventFromISO({
+ id: 'hack-week',
+ title: 'Hack week',
+ category: 'Launch',
+ start: '2026-05-10',
+ end: '2026-05-12',
+ }),
+ createEventFromISO({
+ id: 'offsite',
+ title: 'Offsite',
+ category: 'Company',
+ start: '2026-05-11',
+ end: '2026-05-13',
+ }),
+ timed('alpha', 'Alpha review', 13, 9),
+ timed('bravo', 'Bravo sync', 13, 11),
+ timed('charlie', 'Charlie demo', 13, 14),
+ createEventFromISO({
+ id: 'holiday',
+ title: 'Holiday',
+ category: 'Company',
+ start: '2026-05-25',
+ end: '2026-05-25',
+ }),
+ ];
+ const renderPopover = (event: CalendarEvent) =>
+ event.id === 'holiday' ? null : <p>{event.title} details</p>;
+
+ function MonthAt({
+ source = events,
+ withPopover = true,
+ }: {
+ source?: ReadonlyArray<CalendarEvent>;
+ withPopover?: boolean;
+ }) {
+ const [date, setDate] = useState<Instant>(Date.UTC(2026, 4, 13));
+ const view = useMemo(
+ () =>
+ createScheduleMonthlyView(withPopover ? {renderPopover} : undefined),
+ [withPopover],
+ );
+ return (
+ <Schedule
+ view={view}
+ events={source}
+ categories={categories}
+ date={date}
+ focusDate={Date.UTC(2026, 4, 13)}
+ onChangeDate={setDate}
+ timezoneID="UTC"
+ />
+ );
+ }
+
+ function openDialog(): HTMLElement {
+ const dialogs = Array.from(
+ document.querySelectorAll<HTMLElement>('[role="dialog"]'),
+ ).filter(dialog => dialog.textContent !== '');
+ expect(dialogs).toHaveLength(1);
+ return dialogs[0];
+ }
+
+ const cell = (name: string) => screen.getByRole('cell', {name});
+
+ it('keeps chips painted decoration without the option', () => {
+ render(<MonthAt withPopover={false} />);
+ expect(screen.queryByRole('button', {name: /^Conference,/})).toBeNull();
+ expect(screen.getAllByRole('button', {name: /more events?,/})).toHaveLength(
+ 1,
+ );
+ });
+
+ it('renders each chip with content as a named button in the cell where it starts, and the null chip as text', () => {
+ render(<MonthAt />);
+ const conference = screen.getByRole('button', {name: /^Conference,/});
+ expect(conference.getAttribute('aria-label')).toMatch(
+ /^Conference, all day, Launch, May 10\s*–\s*13, 2026$/u,
+ );
+ expect(conference).toHaveAttribute('aria-haspopup', 'dialog');
+ expect(conference).toHaveAttribute('aria-expanded', 'false');
+ expect(conference.closest('[role="cell"]')).toBe(
+ cell('Sunday, May 10, 2026'),
+ );
+ const alpha = screen.getByRole('button', {name: /^Alpha review,/});
+ expect(alpha).toHaveAttribute(
+ 'aria-label',
+ 'Alpha review, 9:00 AM - 10:00 AM, Company, Wednesday, May 13, 2026',
+ );
+ expect(alpha.closest('[role="cell"]')).toBe(
+ cell('Wednesday, May 13, 2026'),
+ );
+ // Events behind "+3 more" have no chip button.
+ expect(screen.queryByRole('button', {name: /^Bravo sync,/})).toBeNull();
+ // The holiday has no content: static text with its name, never a button.
+ expect(screen.queryByRole('button', {name: /^Holiday,/})).toBeNull();
+ expect(
+ within(cell('Monday, May 25, 2026')).getByText(
+ 'Holiday, all day, Company, Monday, May 25, 2026',
+ ),
+ ).toBeInTheDocument();
+ // The buttons are the cells' events: no hidden list repeats them.
+ expect(cell('Wednesday, May 13, 2026').querySelectorAll('li')).toHaveLength(
+ 0,
+ );
+ });
+
+ it('names a chip as static text on each later day it covers, so no covered day reads as free', () => {
+ render(<MonthAt />);
+ const monday = cell('Monday, May 11, 2026');
+ const mention = within(monday).getByText(
+ /^Conference, all day, Launch, since Sunday, May 10, 2026$/u,
+ );
+ expect(mention.closest('button')).toBeNull();
+ expect(mention).not.toHaveAttribute('tabindex');
+ expect(
+ within(monday).queryByRole('button', {name: /^Conference,/}),
+ ).toBeNull();
+ // Tuesday is covered by three spans, two from Sunday and one from Monday.
+ const tuesday = cell('Tuesday, May 12, 2026');
+ expect(tuesday).toHaveTextContent(
+ 'Hack week, all day, Launch, since Sunday, May 10, 2026',
+ );
+ expect(tuesday).toHaveTextContent(
+ 'Offsite, all day, Company, since Monday, May 11, 2026',
+ );
+ // On busy Wednesday the cut Offsite is counted, not mentioned.
+ const wednesday = cell('Wednesday, May 13, 2026');
+ expect(wednesday).toHaveTextContent(/Conference, all day, Launch, since/);
+ expect(wednesday).not.toHaveTextContent(/Offsite, all day, Company, since/);
+ });
+
+ it('opens one popover named by the event with its content, switches events, and closes on Escape', () => {
+ render(<MonthAt />);
+ const conference = screen.getByRole('button', {name: /^Conference,/});
+ const alpha = screen.getByRole('button', {name: /^Alpha review,/});
+ fireEvent.click(conference);
+ expect(conference).toHaveAttribute('aria-expanded', 'true');
+ expect(openDialog()).toHaveAttribute('aria-label', 'Conference');
+ expect(openDialog()).toHaveTextContent('Conference details');
+
+ fireEvent.pointerDown(alpha);
+ fireEvent.click(alpha);
+ expect(conference).toHaveAttribute('aria-expanded', 'false');
+ expect(alpha).toHaveAttribute('aria-expanded', 'true');
+ expect(openDialog()).toHaveAttribute('aria-label', 'Alpha review');
+
+ fireEvent.keyDown(openDialog(), {key: 'Escape'});
+ expect(alpha).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('hands an event from a busy day\u2019s list to the same popover, with "+N more" as its trigger', () => {
+ render(<MonthAt />);
+ const more = screen.getByRole('button', {name: /^3 more events,/});
+ fireEvent.click(more);
+ const list = openDialog();
+ expect(list).toHaveAttribute('aria-label', 'Wednesday, May 13, 2026');
+ // jsdom does not show native popovers, so their content is queried with
+ // hidden elements included.
+ const bravo = within(list).getByRole('button', {
+ name: /^Bravo sync,/,
+ hidden: true,
+ });
+ expect(bravo).toHaveAttribute(
+ 'aria-label',
+ 'Bravo sync, 11:00 AM - 12:00 PM, Company, Wednesday, May 13, 2026',
+ );
+ fireEvent.click(bravo);
+ const event = openDialog();
+ expect(event).toHaveAttribute('aria-label', 'Bravo sync');
+ expect(event).toHaveTextContent('Bravo sync details');
+ expect(more).toHaveAttribute('aria-expanded', 'true');
+
+ fireEvent.keyDown(event, {key: 'Escape'});
+ expect(more).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('closes when the open chip\u2019s event leaves and moves focus to the cell where it started', () => {
+ const {rerender} = render(<MonthAt />);
+ const conference = screen.getByRole('button', {name: /^Conference,/});
+ fireEvent.click(conference);
+ expect(conference).toHaveAttribute('aria-expanded', 'true');
+ openDialog().focus();
+ rerender(
+ <MonthAt source={events.filter(event => event.id !== 'conference')} />,
+ );
+ expect(document.querySelectorAll('[role="dialog"]').length).toBeLessThan(2);
+ expect(screen.queryByRole('button', {name: /^Conference,/})).toBeNull();
+ expect(document.activeElement).toBe(cell('Sunday, May 10, 2026'));
+ });
+});
diff --git a/packages/lab/src/Schedule/__tests__/ScheduleMonthChip.a11y.chromium.spec.ts b/packages/lab/src/Schedule/__tests__/ScheduleMonthChip.a11y.chromium.spec.ts
index aae7b51143..9a0ebf8341 100644
--- a/packages/lab/src/Schedule/__tests__/ScheduleMonthChip.a11y.chromium.spec.ts
+++ b/packages/lab/src/Schedule/__tests__/ScheduleMonthChip.a11y.chromium.spec.ts
@@ -49,9 +49,9 @@ interface ChipReading {
}
/**
- * Reads each chip by its text: the chip is the painted child of the month's
- * hidden event overlay that holds the title, the title and time are text
- * runs inside it, and the visible line is the chip's own content box.
+ * Reads each chip by its text: the chip is the marked chip (or a build's
+ * hidden overlay child) that holds the title, the title and time are text
+ * runs inside it, and the visible line is the box the title sits in.
*/
function readChips(
page: Page,
@@ -61,6 +61,12 @@ function readChips(
const table = document.querySelector<HTMLElement>(
'.astryx-schedule [role="table"], .astryx-schedule [role="grid"]',
);
+ // Chips carry a marker; a build without it paints them as the children of
+ // one hidden overlay.
+ const marked = [
+ ...(table?.querySelectorAll<HTMLElement>('[data-schedule-month-chip]') ??
+ []),
+ ];
const overlay = [
...(table?.querySelectorAll<HTMLElement>('[aria-hidden="true"]') ?? []),
].find(
@@ -68,6 +74,8 @@ function readChips(
getComputedStyle(element).position === 'absolute' &&
element.children.length > 0,
);
+ const chips: Element[] =
+ marked.length > 0 ? marked : [...(overlay?.children ?? [])];
const isRtl = getComputedStyle(table ?? document.body).direction === 'rtl';
const textNodes = (root: Node): Text[] => {
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
@@ -87,7 +95,7 @@ function readChips(
return range.getBoundingClientRect();
};
return wanted.map(title => {
- const chip = [...(overlay?.children ?? [])].find(element =>
+ const chip = chips.find(element =>
textNodes(element).some(node => node.textContent === title),
);
if (chip == null) {
diff --git a/packages/lab/src/Schedule/__tests__/ScheduleMonthEventPopover.a11y.chromium.spec.ts b/packages/lab/src/Schedule/__tests__/ScheduleMonthEventPopover.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..3ec4b27a4a
--- /dev/null
+++ b/packages/lab/src/Schedule/__tests__/ScheduleMonthEventPopover.a11y.chromium.spec.ts
@@ -0,0 +1,279 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ScheduleMonthEventPopover.a11y.chromium.spec.ts
+ * @input The built Lab/Schedule month-event-popover story in real Chromium
+ * @output Receipted evidence that, with renderPopover, month chips are named
+ * buttons in the cells where they start and inside their week rows; a chip
+ * without content is static text; one view-owned popover opens on click and
+ * Enter, switches between chips in one gesture, takes an event handed over
+ * from a busy day's list, returns focus to the chip or the "+N more", and
+ * closes when its chip leaves, with focus on the chip's start cell
+ * @position Browser binding for `component:Schedule` FR19–FR20 and AR8. jsdom
+ * cannot show a native popover, return focus through it, or lay out chips.
+ */
+
+import {expect, test, type Page} from '@playwright/test';
+import {
+ finishEvidence,
+ openStory,
+ record,
+ startEvidence,
+ WIDE,
+ type Evidence,
+} from './timeGridProbe';
+
+const STORY = 'lab-schedule--month-event-popover';
+const WEDNESDAY = 'Wednesday, May 13, 2026';
+const FRIDAY = 'Friday, May 15, 2026';
+
+let evidence: Evidence;
+test.beforeAll(async () => {
+ evidence = await startEvidence();
+});
+test.afterAll(async () => {
+ await finishEvidence(evidence, 'month-event-popover');
+});
+
+function chip(page: Page, title: string) {
+ return page.getByRole('button', {name: new RegExp(`^${title},`)});
+}
+
+/** The one open dialog: its name, its content's marker, and whether it holds focus. */
+function readDialog(page: Page) {
+ return page.evaluate(() => {
+ const open = [
+ ...document.querySelectorAll<HTMLElement>('[role="dialog"]'),
+ ].filter(dialog => dialog.checkVisibility());
+ const dialog = open[0];
+ return {
+ openCount: open.length,
+ label: dialog?.getAttribute('aria-label') ?? null,
+ details:
+ dialog
+ ?.querySelector('[data-event-details]')
+ ?.getAttribute('data-event-details') ?? null,
+ focusInside:
+ dialog != null && dialog.contains(document.activeElement ?? null),
+ };
+ });
+}
+
+/** Where focus is: its role, name, and the ring it paints. */
+function readFocus(page: Page) {
+ return page.evaluate(() => {
+ const active = document.activeElement as HTMLElement | null;
+ const style = active == null ? null : getComputedStyle(active);
+ return {
+ tag: active?.tagName ?? null,
+ role: active?.getAttribute('role') ?? null,
+ label: active?.getAttribute('aria-label') ?? null,
+ tabIndex: active?.tabIndex ?? null,
+ outlineStyle: style?.outlineStyle ?? null,
+ zIndex: style?.zIndex ?? null,
+ };
+ });
+}
+
+/** Each chip's start cell, whether it is a button, and whether it stays in its row. */
+function readChips(page: Page) {
+ return page.evaluate(() => {
+ const table = document.querySelector('.astryx-schedule [role="table"]');
+ const chips = [
+ ...(table?.querySelectorAll<HTMLElement>('[data-schedule-month-chip]') ??
+ []),
+ ];
+ return chips.map(element => {
+ const cell = element.closest('[role="cell"]');
+ const rect = element.getBoundingClientRect();
+ const cellRect = cell?.getBoundingClientRect();
+ return {
+ name:
+ element.getAttribute('aria-label') ??
+ element.textContent?.trim() ??
+ '',
+ isButton: element.tagName === 'BUTTON',
+ cell: cell?.getAttribute('aria-label') ?? null,
+ insideRow:
+ cellRect != null &&
+ rect.top >= cellRect.top - 1 &&
+ rect.bottom <= cellRect.bottom + 1,
+ hiddenListItems: cell?.querySelectorAll('li').length ?? 0,
+ };
+ });
+ });
+}
+
+for (const [variant, globals] of [
+ ['ltr', undefined],
+ ['rtl-dark', 'direction:rtl;colorMode:dark'],
+] as const) {
+ test(`chips are named buttons in the cells where they start, inside their rows (${variant})`, async ({
+ page,
+ }) => {
+ await openStory(evidence, page, STORY, WIDE, globals);
+ const chips = await readChips(page);
+ await record(
+ evidence,
+ page,
+ `month-event-buttons-${variant}`,
+ STORY,
+ variant,
+ {chips},
+ );
+ expect(chips.length).toBeGreaterThan(0);
+ for (const reading of chips) {
+ expect(reading.insideRow, `${reading.name} stays in its row`).toBe(true);
+ expect(reading.hiddenListItems, `${reading.cell} repeats no list`).toBe(
+ 0,
+ );
+ }
+ const conference = chips.find(reading =>
+ reading.name.startsWith('Design conference,'),
+ );
+ expect(conference?.isButton).toBe(true);
+ expect(conference?.cell).toBe('Sunday, May 10, 2026');
+ expect(conference?.name).toMatch(
+ /^Design conference, all day, Design, May 10\s*–\s*13, 2026$/u,
+ );
+ const standup = chips.find(reading => reading.name.startsWith('Standup,'));
+ expect(standup?.isButton).toBe(true);
+ expect(standup?.cell).toBe(WEDNESDAY);
+ // Every chip paints, and takes the pointer, across all of its days: no
+ // later cell covers the part of a span that crosses it.
+ const covered = await page.evaluate(() =>
+ [...document.querySelectorAll<HTMLElement>('[data-schedule-month-chip]')]
+ .filter(chip => chip.tagName === 'BUTTON')
+ .flatMap(chip => {
+ const rect = chip.getBoundingClientRect();
+ return [0.1, 0.5, 0.9]
+ .map(share => {
+ const top = document.elementFromPoint(
+ rect.left + rect.width * share,
+ rect.top + rect.height / 2,
+ );
+ return top != null && chip.contains(top)
+ ? null
+ : `${chip.getAttribute('aria-label')} at ${share}`;
+ })
+ .filter(miss => miss != null);
+ }),
+ );
+ expect(covered, 'chips covered by a later cell').toEqual([]);
+ // A day the conference covers after Sunday names it as static text.
+ const tuesday = page.getByRole('cell', {name: 'Tuesday, May 12, 2026'});
+ await expect(tuesday).toContainText(
+ /Design conference, all day, Design, since Sunday, May 10, 2026/u,
+ );
+ await expect(
+ tuesday.getByRole('button', {name: /^Design conference,/}),
+ ).toHaveCount(0);
+ // The holiday has no content: static text with its name, never a button.
+ const holiday = chips.find(reading =>
+ reading.name.startsWith('Company holiday'),
+ );
+ expect(holiday?.isButton).toBe(false);
+ expect(holiday?.name).toContain(
+ 'Company holiday, all day, Holiday, Monday, May 25, 2026',
+ );
+ });
+}
+
+test('click and Enter open one popover named by the event, switch in one gesture, and Escape returns focus to the chip', async ({
+ page,
+}) => {
+ await openStory(evidence, page, STORY, WIDE);
+ const standup = chip(page, 'Standup');
+ await standup.click();
+ await expect
+ .poll(async () => (await readDialog(page)).details)
+ .toBe('standup');
+ const opened = await readDialog(page);
+ expect(opened).toMatchObject({openCount: 1, label: 'Standup'});
+ await expect(standup).toHaveAttribute('aria-expanded', 'true');
+
+ // Another chip while one is open: one gesture, one dialog.
+ await chip(page, 'Planning').click();
+ await expect
+ .poll(async () => (await readDialog(page)).details)
+ .toBe('planning');
+ await expect(standup).toHaveAttribute('aria-expanded', 'false');
+ expect((await readDialog(page)).openCount).toBe(1);
+
+ await page.keyboard.press('Escape');
+ await expect.poll(async () => (await readDialog(page)).openCount).toBe(0);
+ const returned = await readFocus(page);
+
+ // Keyboard: Enter on a focused chip opens it.
+ await chip(page, 'Design critique').focus();
+ await page.keyboard.press('Enter');
+ await expect
+ .poll(async () => (await readDialog(page)).details)
+ .toBe('critique');
+ await record(evidence, page, 'month-event-open', STORY, 'ltr', {
+ opened,
+ returned,
+ keyboard: await readDialog(page),
+ });
+ expect(returned.label).toMatch(/^Planning,/);
+});
+
+test('a row in a busy day\u2019s list hands its event to the same popover, and Escape returns focus to "+N more"', async ({
+ page,
+}) => {
+ await openStory(evidence, page, STORY, WIDE);
+ const more = page.getByRole('button', {name: `3 more events, ${WEDNESDAY}`});
+ await more.click();
+ await expect.poll(async () => (await readDialog(page)).label).toBe(WEDNESDAY);
+ await page
+ .getByRole('dialog')
+ .getByRole('button', {name: /^Incident review,/})
+ .click();
+ await expect
+ .poll(async () => (await readDialog(page)).details)
+ .toBe('incident-review');
+ const handedOver = await readDialog(page);
+ await expect(more).toHaveAttribute('aria-expanded', 'true');
+ await page.keyboard.press('Escape');
+ await expect.poll(async () => (await readDialog(page)).openCount).toBe(0);
+ const returned = await readFocus(page);
+ await record(evidence, page, 'month-event-handoff', STORY, 'ltr', {
+ handedOver,
+ returned,
+ });
+ expect(handedOver).toMatchObject({openCount: 1, label: 'Incident review'});
+ expect(returned.label).toBe(`3 more events, ${WEDNESDAY}`);
+});
+
+test('a focused chip paints its ring above its neighbours, and a chip that leaves while open sends focus to its start cell', async ({
+ page,
+}) => {
+ await openStory(evidence, page, STORY, WIDE);
+ // Keyboard focus shows the shared ring and lifts the chip locally.
+ await chip(page, 'Planning').focus();
+ await page.keyboard.press('Shift+Tab');
+ await page.keyboard.press('Tab');
+ const ring = await readFocus(page);
+
+ await page.keyboard.press('Enter');
+ await expect
+ .poll(async () => (await readDialog(page)).details)
+ .toBe('planning');
+ await page.evaluate(() => {
+ (
+ window as unknown as {
+ scheduleMonthOverflowStory: {removeEvent: (id: string) => void};
+ }
+ ).scheduleMonthOverflowStory.removeEvent('planning');
+ });
+ await expect.poll(async () => (await readDialog(page)).openCount).toBe(0);
+ const focus = await readFocus(page);
+ await record(evidence, page, 'month-event-removed', STORY, 'ltr', {
+ ring,
+ focus,
+ });
+ expect(ring).toMatchObject({outlineStyle: 'solid', zIndex: '2'});
+ expect(ring.label).toMatch(/^Planning,/);
+ expect(focus).toMatchObject({role: 'cell', label: FRIDAY, tabIndex: -1});
+ expect(focus.outlineStyle).toBe('solid');
+});
diff --git a/packages/lab/src/Schedule/__tests__/ScheduleMonthOverflow.a11y.chromium.spec.ts b/packages/lab/src/Schedule/__tests__/ScheduleMonthOverflow.a11y.chromium.spec.ts
index f9a32ee6b3..ce8194647c 100644
--- a/packages/lab/src/Schedule/__tests__/ScheduleMonthOverflow.a11y.chromium.spec.ts
+++ b/packages/lab/src/Schedule/__tests__/ScheduleMonthOverflow.a11y.chromium.spec.ts
@@ -69,7 +69,7 @@ interface MonthReading {
/**
* Reads the month by what it is: cells are the table's date-named cells,
- * chips are the painted children of the table's hidden event overlay, and a
+ * chips are the marked chips (or a build's hidden overlay children), and a
* day's "+N more" is the named button inside its cell.
*/
function readMonth(page: Page): Promise<MonthReading> {
@@ -109,6 +109,11 @@ function readMonth(page: Page): Promise<MonthReading> {
rect: cell.getBoundingClientRect(),
cell,
}));
+ // Chips carry a marker; a build without it paints them as the children
+ // of one hidden overlay.
+ const marked = [
+ ...grid.querySelectorAll<HTMLElement>('[data-schedule-month-chip]'),
+ ];
const overlay = [
...grid.querySelectorAll<HTMLElement>('[aria-hidden="true"]'),
].find(
@@ -116,7 +121,21 @@ function readMonth(page: Page): Promise<MonthReading> {
getComputedStyle(element).position === 'absolute' &&
element.children.length > 0,
);
- const chips = overlay == null ? [] : [...overlay.children];
+ const chips =
+ marked.length > 0
+ ? marked
+ : overlay == null
+ ? []
+ : [...overlay.children];
+ // The month surface is the cells' nearest isolating ancestor.
+ let surface: HTMLElement | null = cells[0]?.cell.parentElement ?? null;
+ while (
+ surface != null &&
+ surface !== grid &&
+ getComputedStyle(surface).isolation !== 'isolate'
+ ) {
+ surface = surface.parentElement;
+ }
const chipsOutsideRow = chips.flatMap(chip => {
const rect = chip.getBoundingClientRect();
const start = cells.find(
@@ -198,9 +217,9 @@ function readMonth(page: Page): Promise<MonthReading> {
countReadsInOrder,
days,
surfaceIsolation:
- overlay?.parentElement == null
- ? 'none'
- : getComputedStyle(overlay.parentElement).isolation,
+ surface == null || surface === grid
+ ? 'auto'
+ : getComputedStyle(surface).isolation,
};
},
[[WEDNESDAY, FRIDAY]] as const,
diff --git a/packages/lab/src/Schedule/shared.tsx b/packages/lab/src/Schedule/shared.tsx
index 92baf88c79..a745d89b99 100644
--- a/packages/lab/src/Schedule/shared.tsx
+++ b/packages/lab/src/Schedule/shared.tsx
@@ -801,14 +801,6 @@ export const styles = stylex.create({
monthGridRow: {
display: 'contents',
},
- monthEventOverlay: {
- position: 'absolute',
- inset: 0,
- display: 'grid',
- gridTemplateColumns: 'repeat(7, minmax(0, 1fr))',
- gridAutoRows: '128px',
- pointerEvents: 'none',
- },
monthCell: {
position: 'relative',
display: 'flex',
@@ -865,22 +857,33 @@ export const styles = stylex.create({
gap: spacingVars['--spacing-0-5'],
minWidth: 0,
},
- monthEventSpan: (
- week: number,
- columnStart: number,
- columnEnd: number,
- level: number,
- ) => ({
- gridRow: `${week + 1}`,
- gridColumn: `${columnStart + 1} / ${columnEnd + 2}`,
- alignSelf: 'start',
+ // A chip lives in the cell of its first day in the week and paints across
+ // its days from there, on its level: it starts a chip inset into that cell
+ // and ends a chip inset plus one border short of its last day's edge, so
+ // it clears each day's end border the way the cells do. It rises above the
+ // cells it crosses inside the isolated surface (component:Schedule FR15,
+ // FR19).
+ monthChip: (span: number, level: number) => ({
+ position: 'absolute',
+ insetInlineStart: spacingVars['--spacing-0-5'],
+ insetBlockStart: `${MONTH_CHIP_TOP + level * MONTH_LEVEL_PITCH}px`,
+ inlineSize: `calc(${span} * 100% + ${span - 1} * ${borderVars['--border-width']} - 2 * ${spacingVars['--spacing-0-5']})`,
minWidth: 0,
- marginInlineStart: spacingVars['--spacing-0-5'],
- marginInlineEnd: `calc(${spacingVars['--spacing-0-5']} + ${borderVars['--border-width']})`,
- marginBlockStart: `${MONTH_CHIP_TOP + level * MONTH_LEVEL_PITCH}px`,
- pointerEvents: 'auto',
zIndex: 1,
}),
+ // The last column's cell has no end border, so the same chip is one border
+ // narrower than its padding box.
+ monthChipInLastColumn: {
+ inlineSize: `calc(100% - 2 * ${spacingVars['--spacing-0-5']} - ${borderVars['--border-width']})`,
+ },
+ // A chip button stays above the cells it crosses, like any chip, and a
+ // focused one keeps its whole ring above the chips around it.
+ monthChipFocus: {
+ zIndex: {
+ default: 1,
+ ':focus-visible': 2,
+ },
+ },
// A busy day's "+N more" takes the slot of the level it stands in for, with
// a chip's insets and height, and keeps its focus ring above the chips.
monthMoreButton: {
@@ -927,6 +930,19 @@ export const styles = stylex.create({
gap: spacingVars['--spacing-2'],
maxInlineSize: '360px',
},
+ // A row of a day's list that opens its event: the whole row is the
+ // button, with the list row's look and the shared focus ring.
+ monthDayEventButton: {
+ inlineSize: '100%',
+ borderRadius: radiusVars['--radius-inner'],
+ backgroundColor: {
+ default: 'transparent',
+ ':hover:where(:not(:disabled,[aria-disabled="true"]))': {
+ default: null,
+ '@media (hover: hover)': colorVars['--color-overlay-hover'],
+ },
+ },
+ },
monthDayEventList: {
display: 'flex',
flexDirection: 'column',
diff --git a/packages/lab/src/Schedule/useScheduleViewPopover.ts b/packages/lab/src/Schedule/useScheduleViewPopover.ts
index d96d4b9760..96ef24dd41 100644
--- a/packages/lab/src/Schedule/useScheduleViewPopover.ts
+++ b/packages/lab/src/Schedule/useScheduleViewPopover.ts
@@ -7,10 +7,10 @@
* @input The dialog name for the open trigger's key, or for no open trigger,
* and where focus goes when the open trigger stops being painted
* @output One view-owned Popover with its open key, trigger props, the press
- * model that lets one gesture switch triggers, and a close when the open
- * trigger is no longer painted
+ * model that lets one gesture switch triggers, a switch of the open content
+ * inside the popover, and a close when the open trigger is no longer painted
* @position Internal hook for Schedule views that own a popover (the month
- * view's day popover, component:Schedule FR17); not exported
+ * view's popover, component:Schedule FR17, FR20); not exported
*/
import {
@@ -37,17 +37,31 @@ export interface ScheduleViewPopover {
};
/**
* Props of one trigger button. Calling it also marks the trigger as painted
- * this render; the popover closes when its trigger was not.
+ * this render; the popover closes when its trigger was not. A trigger may
+ * own open keys it did not open itself (`ownsOpenKey`): content switched to
+ * from inside its popover keeps it expanded and painted.
*/
- getTriggerProps: (key: string) => {
+ getTriggerProps: (
+ key: string,
+ ownsOpenKey?: (openKey: string) => boolean,
+ ) => {
'aria-haspopup': 'dialog';
'aria-expanded': boolean;
'aria-controls': string;
[TRIGGER_ATTRIBUTE]: string;
onClick: (event: ReactMouseEvent<HTMLButtonElement>) => void;
};
+ /**
+ * Shows `key`'s content in the open popover, in the same gesture, and moves
+ * focus into it. The popover keeps its trigger, so focus returns there.
+ */
+ switchTo: (key: string) => void;
}
+const FALLBACK_CLOSE = '[data-astryx-popover-fallback-close]';
+const FOCUSABLE =
+ 'button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
+
/**
* One popover for a view, opened from any of its trigger buttons. The popover
* is the system's standard Popover: a modal dialog named by `dialogLabelFor`
@@ -117,6 +131,34 @@ export function useScheduleViewPopover(
popover.show();
};
+ // Content switched to inside an open popover takes focus once it renders,
+ // the way the popover's own auto-focus does when it opens.
+ const focusSwitchedContentRef = useRef(false);
+ const switchTo = (key: string) => {
+ if (!popover.isOpen) {
+ return;
+ }
+ focusSwitchedContentRef.current = true;
+ setOpenKey(key);
+ };
+ useEffect(() => {
+ if (!focusSwitchedContentRef.current) {
+ return;
+ }
+ focusSwitchedContentRef.current = false;
+ const frame = requestAnimationFrame(() => {
+ const content = popoverRef.current.contentRef.current;
+ if (content == null) {
+ return;
+ }
+ const first = Array.from(
+ content.querySelectorAll<HTMLElement>(FOCUSABLE),
+ ).find(element => element.closest(FALLBACK_CLOSE) == null);
+ (first ?? content).focus();
+ });
+ return () => cancelAnimationFrame(frame);
+ }, [openKey]);
+
// Triggers painted this render; the popover may stay open only for one of
// them. When its trigger is gone, focus — inside the popover, or dropped
// to the page with the trigger — has nowhere to return to, so the view
@@ -142,15 +184,21 @@ export function useScheduleViewPopover(
popover,
openKey,
containerProps: {onPointerDownCapture, onKeyDownCapture},
- getTriggerProps: key => {
+ getTriggerProps: (key, ownsOpenKey) => {
paintedKeys.add(key);
+ const ownsOpen =
+ openKey != null && openKey !== key && (ownsOpenKey?.(openKey) ?? false);
+ if (ownsOpen) {
+ paintedKeys.add(openKey);
+ }
return {
'aria-haspopup': 'dialog',
- 'aria-expanded': popover.isOpen && openKey === key,
+ 'aria-expanded': popover.isOpen && (openKey === key || ownsOpen),
'aria-controls': popover.id,
[TRIGGER_ATTRIBUTE]: key,
onClick: event => toggle(key, event.currentTarget),
};
},
+ switchTo,
};
}