An open source design system that's fully customizable and agent ready
TypeScript
fix(lab): a busy Schedule month day shows +N more instead of losing events (#7050)
Cindy Zhang9eed5cb1300f
diff --git a/apps/storybook/stories/Schedule.stories.tsx b/apps/storybook/stories/Schedule.stories.tsxindex 18b22b5bf5..914f421540 100644--- a/apps/storybook/stories/Schedule.stories.tsx+++ b/apps/storybook/stories/Schedule.stories.tsx@@ -1,6 +1,6 @@// Copyright (c) Meta Platforms, Inc. and affiliates.-import {useMemo, useState} from 'react';+import {useEffect, useMemo, useState, useSyncExternalStore} from 'react';import type {Meta, StoryObj} from '@storybook/react';import {Text} from '@astryxdesign/core';import {InternationalizationProvider} from '@astryxdesign/core/i18n';@@ -670,6 +670,125 @@ export const EventEndingAtMidnight: Story = {},};+// A fixed UTC month for the month view's overflow contract: Wednesday May 13+// needs five levels (a three-day span sits on its third) and Friday May 15+// needs four, so both trade their third level for "+N more"; the other days+// fit and paint every chip.+function monthFixtureEvent(+ id: string,+ title: string,+ category: string,+ day: number,+ hour: number,+): CalendarEvent {+ const pad = (value: number) => String(value).padStart(2, '0');+ return createEventFromISO({+ id,+ title,+ category,+ start: `2026-05-${pad(day)}T${pad(hour)}:00:00.000Z`,+ end: `2026-05-${pad(day)}T${pad(hour + 1)}:00:00.000Z`,+ });+}++const busyMonthEvents: CalendarEvent[] = [+ createEventFromISO({+ id: 'conference',+ title: 'Design conference',+ category: 'Design',+ 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: 'Team offsite',+ category: 'Company',+ start: '2026-05-11',+ end: '2026-05-13',+ }),+ monthFixtureEvent('standup', 'Standup', 'Company', 13, 9),+ monthFixtureEvent('incident-review', 'Incident review', 'Incident', 13, 11),+ monthFixtureEvent('launch-check', 'Launch check', 'Launch', 13, 14),+ monthFixtureEvent('planning', 'Planning', 'Company', 15, 9),+ monthFixtureEvent('critique', 'Design critique', 'Design', 15, 10),+ monthFixtureEvent('retro', 'Weekly retro', 'Retro', 15, 13),+ monthFixtureEvent('focus', 'Focus block', 'Focus', 15, 15),+ monthFixtureEvent('one-on-one', '1:1', 'Company', 5, 10),+ createEventFromISO({+ id: 'holiday',+ title: 'Company holiday',+ category: 'Holiday',+ start: '2026-05-25',+ end: '2026-05-25',+ }),+];++/**+ * A week row of the month paints 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.+ */+// Test seam for the month-overflow browser contract: removes an event the way+// a data refresh would, while a day's popover stays open. The events live in+// one module-level store so the removal reaches every rendered copy of the+// story.+let monthOverflowEvents: ReadonlyArray<CalendarEvent> = busyMonthEvents;+const monthOverflowListeners = new Set<() => void>();++function subscribeToMonthOverflowEvents(listener: () => void): () => void {+ monthOverflowListeners.add(listener);+ return () => {+ monthOverflowListeners.delete(listener);+ };+}++function getMonthOverflowEvents(): ReadonlyArray<CalendarEvent> {+ return monthOverflowEvents;+}++function removeMonthOverflowEvent(id: string): void {+ monthOverflowEvents = monthOverflowEvents.filter(event => event.id !== id);+ monthOverflowListeners.forEach(listener => listener());+}++export const MonthOverflow: Story = {+ render: () => {+ const [date, setDate] = useState<Instant>(FIXTURE_DATE);+ const monthEvents = useSyncExternalStore(+ subscribeToMonthOverflowEvents,+ getMonthOverflowEvents,+ getMonthOverflowEvents,+ );+ const view = useMemo(() => createScheduleMonthlyView(), []);+ 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.tsxindex b390d86317..b057db09ad 100644--- a/packages/lab/src/Schedule/MonthlyView.tsx+++ b/packages/lab/src/Schedule/MonthlyView.tsx@@ -5,15 +5,20 @@/*** @file MonthlyView.tsx* @input Schedule context and monthly view options- * @output Month grid schedule view factory+ * @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* @position Concrete schedule view; exported as createScheduleMonthlyView*/+import {useRef} from 'react';import * as stylex from '@stylexjs/stylex';+import {layerAnimations} from '@astryxdesign/core/Layer';+import {spacingVars} from '@astryxdesign/core/theme/tokens.stylex';import {+ focusOutlineStyles,plainDateAddDays,plainDateAddMonths,- plainDateFromInstant,plainDateIsAfter,plainDateIsBefore,plainDateIsEqual,@@ -24,25 +29,29 @@ import {type PlainDate,} from '@astryxdesign/core/utils';import {Heading, Text} from '@astryxdesign/core/Text';-import {- enumerateDates,- getScheduleRangeFromDates,- isDayEvent,-} from './dateMath';+import {enumerateDates, getScheduleRangeFromDates} from './dateMath';import {useScheduleContext} from './context';+import {+ getEventDateSpan,+ layoutMonthEvents,+ MONTH_VISIBLE_LEVELS,+} from './monthLayout';import {formatDayNumber,formatEventAccessibilityLabel,formatFullDate,formatMonthTitle,formatWeekday,+ formatWeekRange,isEventInPast,+ ListEventRow,MonthEventPill,ScheduleFrame,ScheduleMonthTitle,styles,} from './shared';import {useCurrentTime} from './useCurrentTime';+import {useScheduleViewPopover} from './useScheduleViewPopover';import {scheduleRangeToZonedDateTimeRange} from './zonedDateTime';import type {CalendarEvent,@@ -73,30 +82,66 @@ function ScheduleMonthlyView(const currentTime = useCurrentTime();const days = enumerateDates(range.startDate, range.endDate);const weeks = getWeeks(days);- const eventSegments = getMonthEventSegments(events, days, timezoneID);+ const layout = layoutMonthEvents(events, days, timezoneID);+ const overflowByDay = new Map(+ 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>(+ days.map(day => [plainDateToISO(day), day]),+ );+ const monthTitle = formatMonthTitle(rangeDate, timezoneID, locale);+ const tableRef = useRef<HTMLDivElement>(null);+ const dayPopover = useScheduleViewPopover(+ key => {+ const day = key == null ? undefined : dayByKey.get(key);+ return day == null ? monthTitle : formatFullDate(day, timezoneID, locale);+ },+ // A day that stops being busy takes its "+N more" with it; focus lands+ // on that day's cell instead of the page.+ key => {+ tableRef.current+ ?.querySelector<HTMLElement>(`[data-schedule-day="${key}"]`)+ ?.focus();+ },+ );+ const openDay =+ dayPopover.openKey == null ? null : dayByKey.get(dayPopover.openKey);return (<ScheduleFrametitle={<ScheduleMonthTitle date={rangeDate} timezoneID={timezoneID} />}- titleLabel={formatMonthTitle(rangeDate, timezoneID, locale)}+ titleLabel={monthTitle}isLoading={isLoading}>+ {/* A table, not an interactive grid (component:Schedule AR7): weekday+ column headers, week row headers, cells named by their full date,+ and no arrow-key promise, so a busy day's "+N more" is an ordinary+ Tab stop. The table scrolls horizontally at narrow viewports and a+ month without a busy day has no focusable descendants, so it is+ focusable itself for keyboard scrolling (axe:+ scrollable-region-focusable). */}<div- role="grid"- aria-label={formatMonthTitle(rangeDate, timezoneID, locale)}- aria-readonly- // The grid scrolls horizontally at narrow viewports and contains no- // focusable descendants, so it must be focusable itself for keyboard- // scrolling (axe: scrollable-region-focusable).+ ref={tableRef}+ role="table"+ aria-label={monthTitle}tabIndex={0}+ {...dayPopover.containerProps}{...stylex.props(styles.monthGrid)}><div role="row" {...stylex.props(styles.weekHeader)}>+ <div+ role="columnheader"+ aria-colindex={1}+ {...stylex.props(styles.visuallyHidden)}>+ Week+ </div>{days.slice(0, 7).map((day, index) => (<divkey={plainDateToISO(day)}role="columnheader"aria-label={formatWeekday(day, timezoneID, 'long', locale)}- aria-colindex={index + 1}+ aria-colindex={index + 2}{...stylex.props(styles.weekdayLabel)}><Headinglevel={headingLevel}@@ -115,17 +160,32 @@ function ScheduleMonthlyView(key={plainDateToISO(week[0])}role="row"{...stylex.props(styles.monthGridRow)}>+ <div+ role="rowheader"+ aria-colindex={1}+ {...stylex.props(styles.visuallyHidden)}>+ {formatWeekRange(+ week[0],+ week[week.length - 1],+ timezoneID,+ locale,+ )}+ </div>{week.map((day, dayIndex) => {const index = weekIndex * 7 + dayIndex;const isOutsideMonth = day.month !== rangeDate.month;- const dayEvents =- eventsByDay.get(plainDateToISO(day)) ?? EMPTY_EVENTS;+ const dayISO = plainDateToISO(day);+ const dayEvents = eventsByDay.get(dayISO) ?? EMPTY_EVENTS;+ const hiddenCount = overflowByDay.get(index);return (<divkey={plainDateToISO(day)}- role="gridcell"+ role="cell"aria-label={formatFullDate(day, timezoneID, locale)}- aria-colindex={dayIndex + 1}+ aria-colindex={dayIndex + 2}+ // Focus lands here when the day's "+N more" goes away.+ tabIndex={-1}+ data-schedule-day={dayISO}aria-current={plainDateIsEqual(day, highlightedDate)? 'date'@@ -136,6 +196,8 @@ function ScheduleMonthlyView(index % 7 === 6 && styles.monthCellLastColumn,index >= days.length - 7 && styles.monthCellLastRow,isOutsideMonth && styles.monthCellOutside,+ focusOutlineStyles.focusVisible,+ styles.monthCellFocus,)}><div{...stylex.props(@@ -166,6 +228,26 @@ function ScheduleMonthlyView())}</ul>)}+ {hiddenCount != null && (+ <button+ type="button"+ aria-label={`${hiddenCount} more ${+ hiddenCount === 1 ? 'event' : 'events'+ }, ${formatFullDate(day, timezoneID, locale)}`}+ {...dayPopover.getTriggerProps(dayISO)}+ {...stylex.props(+ styles.eventButtonReset,+ styles.monthMoreButton,+ styles.monthMoreButtonPosition(+ MONTH_VISIBLE_LEVELS - 1,+ ),+ focusOutlineStyles.focusVisible,+ )}>+ {/* Isolated, so the count reads "+3 more" in either+ direction. */}+ <bdi>+{hiddenCount} more</bdi>+ </button>+ )}</div>);})}@@ -173,7 +255,7 @@ function ScheduleMonthlyView())}</div><div aria-hidden {...stylex.props(styles.monthEventOverlay)}>- {eventSegments.map(segment => (+ {layout.chips.map(segment => (<divkey={`${segment.event.id}:${segment.week}:${segment.columnStart}`}{...stylex.props(@@ -194,10 +276,54 @@ function ScheduleMonthlyView(</div></div></div>+ {dayPopover.popover.render(+ openDay == null ? null : (+ <MonthDayEvents+ day={openDay}+ events={eventsByDay.get(plainDateToISO(openDay)) ?? EMPTY_EVENTS}+ />+ ),+ {+ placement: 'below',+ alignment: 'start',+ offset: spacingVars['--spacing-1'],+ xstyle: [styles.eventPopover, layerAnimations.below],+ },+ )}</ScheduleFrame>);}+/** The day popover's content: every event of one day, in start order. */+function MonthDayEvents({+ day,+ events,+}: {+ day: PlainDate;+ events: ReadonlyArray<CalendarEvent>;+}) {+ const {timezoneID, locale} = useScheduleContext();+ const currentTime = useCurrentTime();+ return (+ <div {...stylex.props(styles.monthDayEvents)}>+ <Text type="supporting" weight="bold" color="secondary">+ {formatFullDate(day, timezoneID, locale)}+ </Text>+ <ul {...stylex.props(styles.monthDayEventList)}>+ {events.map(event => (+ <li key={event.id}>+ <ListEventRow+ event={event}+ timezoneID={timezoneID}+ isPast={isEventInPast(event, currentTime, timezoneID)}+ />+ </li>+ ))}+ </ul>+ </div>+ );+}+function getWeeks(days: ReadonlyArray<PlainDate>): PlainDate[][] {const weeks: PlainDate[][] = [];for (let index = 0; index < days.length; index += 7) {@@ -245,115 +371,6 @@ function getMonthEventsByDay(return eventsByDay;}-interface MonthEventSegment {- event: CalendarEvent;- week: number;- columnStart: number;- columnEnd: number;- level: number;-}--const MAX_MONTH_EVENT_LEVELS = 4;--function getMonthEventSegments(- events: ReadonlyArray<CalendarEvent>,- days: ReadonlyArray<PlainDate>,- timezoneID: string,-): MonthEventSegment[] {- const segments: MonthEventSegment[] = [];- const levelsByWeek: Array<number[]> = [];- const monthEvents = events- .map(event => {- const [eventStart, eventEnd] = getEventDateSpan(event, timezoneID);- const startIndex = days.findIndex(- day => !plainDateIsBefore(day, eventStart),- );- const endIndexFromRight = [...days]- .reverse()- .findIndex(day => !plainDateIsAfter(day, eventEnd));- if (startIndex < 0 || endIndexFromRight < 0) {- return null;- }- const endIndex = days.length - 1 - endIndexFromRight;- return {- event,- startIndex,- endIndex,- isPriority: isDayEvent(event) || endIndex > startIndex,- };- })- .filter(- (- record,- ): record is {- event: CalendarEvent;- startIndex: number;- endIndex: number;- isPriority: boolean;- } => record != null,- )- .sort((a, b) => {- if (a.startIndex !== b.startIndex) {- return a.startIndex - b.startIndex;- }- if (a.isPriority !== b.isPriority) {- return a.isPriority ? -1 : 1;- }- const aDuration = a.endIndex - a.startIndex;- const bDuration = b.endIndex - b.startIndex;- if (aDuration !== bDuration) {- return bDuration - aDuration;- }- return a.event.title.localeCompare(b.event.title);- });-- monthEvents.forEach(({event, startIndex, endIndex}) => {- const [eventStart, eventEnd] = getEventDateSpan(event, timezoneID);- if (- plainDateIsBefore(eventEnd, days[0]) ||- plainDateIsAfter(eventStart, days[days.length - 1])- ) {- return;- }-- for (- let week = Math.floor(startIndex / 7);- week <= Math.floor(endIndex / 7);- week += 1- ) {- const columnStart =- week === Math.floor(startIndex / 7) ? startIndex % 7 : 0;- const columnEnd = week === Math.floor(endIndex / 7) ? endIndex % 7 : 6;- const weekLevels = (levelsByWeek[week] ??= []);- const level = getAvailableLevel(weekLevels, columnStart);- if (level < MAX_MONTH_EVENT_LEVELS) {- weekLevels[level] = columnEnd;- segments.push({event, week, columnStart, columnEnd, level});- }- }- });-- return segments;-}--function getEventDateSpan(- event: CalendarEvent,- timezoneID: string,-): [PlainDate, PlainDate] {- if (isDayEvent(event)) {- return [event.start, event.end];- }- return [- plainDateFromInstant(event.start, timezoneID),- plainDateFromInstant(Math.max(event.end - 1, event.start), timezoneID),- ];-}--function getAvailableLevel(levels: number[], columnStart: number): number {- const level = levels.findIndex(columnEnd => columnStart > columnEnd);- return level >= 0 ? level : levels.length;-}-export function createScheduleMonthlyView({weekStartsOn = 0,}: ScheduleMonthlyViewOptions = {}): ScheduleView<ScheduleMonthlyViewOptions> {diff --git a/packages/lab/src/Schedule/Schedule.doc.mjs b/packages/lab/src/Schedule/Schedule.doc.mjsindex 498ce12b03..c871d41de2 100644--- a/packages/lab/src/Schedule/Schedule.doc.mjs+++ b/packages/lab/src/Schedule/Schedule.doc.mjs@@ -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.",+ '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.',},{name: 'Current time line',diff --git a/packages/lab/src/Schedule/Schedule.test.tsx b/packages/lab/src/Schedule/Schedule.test.tsxindex 4fbc0832d4..e493e35cee 100644--- a/packages/lab/src/Schedule/Schedule.test.tsx+++ b/packages/lab/src/Schedule/Schedule.test.tsx@@ -152,7 +152,7 @@ describe('Schedule', () => {);expect(screen.getByRole('heading', {name: 'mai 2026'})).toBeInTheDocument();- expect(screen.getByRole('grid', {name: 'mai 2026'})).toBeInTheDocument();+ expect(screen.getByRole('table', {name: 'mai 2026'})).toBeInTheDocument();expect(screen.getByRole('columnheader', {name: 'mercredi'}),).toBeInTheDocument();@@ -317,7 +317,7 @@ describe('Schedule', () => {expect(screen.getByRole('region', {name: 'May 2026'})).toBeInTheDocument();});- it('exposes monthly view as an ARIA grid', () => {+ it('exposes the month view as a table with week row headers and date-named cells', () => {render(<Scheduleview={createScheduleMonthlyView()}@@ -329,18 +329,29 @@ describe('Schedule', () => {/>,);- expect(screen.getByRole('grid', {name: 'May 2026'})).toBeInTheDocument();+ // component:Schedule AR7: a table, not an interactive grid.+ const table = screen.getByRole('table', {name: 'May 2026'});+ expect(table).not.toHaveAttribute('aria-readonly');+ expect(screen.queryByRole('grid')).toBeNull();expect(- screen.getByRole('columnheader', {name: 'Wednesday'}),- ).toBeInTheDocument();+ screen.getAllByRole('columnheader').map(header => header.textContent),+ ).toEqual(['Week', 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']);expect(screen.getByRole('columnheader', {name: 'Wednesday'}),- ).toHaveAttribute('aria-colindex', '4');+ ).toHaveAttribute('aria-colindex', '5');+ const rowHeaders = screen.getAllByRole('rowheader');+ expect(rowHeaders).toHaveLength(6);+ expect(rowHeaders[2].textContent).toMatch(/^May 10\s*–\s*16, 2026$/);+ expect(screen.getAllByRole('row')).toHaveLength(7);+ for (const row of screen.getAllByRole('row').slice(1)) {+ expect(row.querySelectorAll('[role="rowheader"]')).toHaveLength(1);+ expect(row.querySelectorAll('[role="cell"]')).toHaveLength(7);+ }expect(- screen.getByRole('gridcell', {name: 'Wednesday, May 13, 2026'}),+ screen.getByRole('cell', {name: 'Wednesday, May 13, 2026'}),).toBeInTheDocument();expect(- screen.getByRole('gridcell', {name: 'Wednesday, May 13, 2026'}),+ screen.getByRole('cell', {name: 'Wednesday, May 13, 2026'}),).toHaveAttribute('aria-current', 'date');expect(screen.getByText('Visible sync, Sync, 4:00 PM - 4:30 PM'),@@ -350,9 +361,9 @@ describe('Schedule', () => {).toBeInTheDocument();});- it('makes the scrollable monthly grid keyboard-focusable', () => {- // The month grid is a horizontal scroll container with no focusable- // descendants, so it needs tabindex="0" itself for+ it('makes the scrollable month table keyboard-focusable', () => {+ // The month table is a horizontal scroll container that may hold no+ // focusable descendants, so it needs tabindex="0" itself for// scrollable-region-focusable to pass and for keyboard scrolling.render(<Schedule@@ -365,7 +376,7 @@ describe('Schedule', () => {/>,);- expect(screen.getByRole('grid', {name: 'May 2026'})).toHaveAttribute(+ expect(screen.getByRole('table', {name: 'May 2026'})).toHaveAttribute('tabindex','0',);@@ -969,3 +980,200 @@ describe('Schedule event popover', () => {expect(dialogOf(earlier)).toHaveTextContent('Details for Earlier sync');});});++describe('Schedule month overflow', () => {+ // component:Schedule FR15–FR17 and AR7. May 2026 in UTC: Wednesday May 13+ // holds five events and needs five levels; Friday May 15 holds four.+ 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),+ timed('friday-1', 'Friday one', 15, 9),+ timed('friday-2', 'Friday two', 15, 10),+ timed('friday-3', 'Friday three', 15, 11),+ timed('friday-4', 'Friday four', 15, 12),+ ];++ function MonthAt({source = events}: {source?: ReadonlyArray<CalendarEvent>}) {+ const [date, setDate] = useState<Instant>(Date.UTC(2026, 4, 13));+ const view = useMemo(() => createScheduleMonthlyView(), []);+ return (+ <Schedule+ view={view}+ events={source}+ categories={categories}+ date={date}+ focusDate={Date.UTC(2026, 4, 13)}+ onChangeDate={setDate}+ timezoneID="UTC"+ />+ );+ }++ function dialogOf(button: HTMLElement): HTMLElement {+ const layer = document.getElementById(+ button.getAttribute('aria-controls') ?? '',+ );+ expect(layer).not.toBeNull();+ const dialog =+ layer?.getAttribute('role') === 'dialog'+ ? layer+ : layer?.querySelector<HTMLElement>('[role="dialog"]');+ expect(dialog).not.toBeNull();+ return dialog as HTMLElement;+ }++ it('gives a busy day a named "+N more" button in its cell', () => {+ render(<MonthAt />);+ const wednesday = screen.getByRole('button', {+ name: '3 more events, Wednesday, May 13, 2026',+ });+ expect(wednesday).toHaveTextContent('+3 more');+ expect(wednesday).toHaveAttribute('type', 'button');+ expect(wednesday).toHaveAttribute('aria-haspopup', 'dialog');+ expect(wednesday).toHaveAttribute('aria-expanded', 'false');+ expect(wednesday.getAttribute('aria-controls')).toBeTruthy();+ expect(wednesday.closest('[role="cell"]')).toHaveAttribute(+ 'aria-label',+ 'Wednesday, May 13, 2026',+ );+ expect(wednesday.closest('[aria-hidden="true"]')).toBeNull();+ expect(+ screen.getByRole('button', {name: '2 more events, Friday, May 15, 2026'}),+ ).toHaveTextContent('+2 more');+ // Monday needs three levels and Thursday one: nothing is counted there.+ expect(screen.getAllByRole('button', {name: /more events?,/})).toHaveLength(+ 2,+ );+ // The cell's hidden list still names every event of the busy day.+ const cell = wednesday.closest('[role="cell"]') as HTMLElement;+ expect(cell.querySelectorAll('li')).toHaveLength(5);+ });++ it('opens one popover named by the day that lists every event of it, switches days, and closes on Escape', () => {+ render(<MonthAt />);+ const wednesday = screen.getByRole('button', {name: /^3 more events,/});+ const friday = screen.getByRole('button', {name: /^2 more events,/});++ fireEvent.click(wednesday);+ expect(wednesday).toHaveAttribute('aria-expanded', 'true');+ const dialog = dialogOf(wednesday);+ expect(dialog).toHaveAttribute('aria-label', 'Wednesday, May 13, 2026');+ expect(+ Array.from(dialog.querySelectorAll('li')).map(item => item.textContent),+ ).toEqual([+ 'All dayConference',+ 'All dayOffsite',+ '9:00 AM - 10:00 AM' + 'Alpha review',+ '11:00 AM - 12:00 PM' + 'Bravo sync',+ '2:00 PM - 3:00 PM' + 'Charlie demo',+ ]);+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1);++ // A press on another day's button closes the popover ahead of the+ // browser's light dismiss; the click that follows opens that day.+ fireEvent.pointerDown(friday);+ expect(wednesday).toHaveAttribute('aria-expanded', 'false');+ fireEvent.click(friday);+ expect(friday).toHaveAttribute('aria-expanded', 'true');+ expect(dialogOf(friday)).toHaveAttribute(+ 'aria-label',+ 'Friday, May 15, 2026',+ );+ expect(dialogOf(friday).querySelectorAll('li')).toHaveLength(4);+ expect(document.querySelectorAll('[role="dialog"]')).toHaveLength(1);++ fireEvent.keyDown(dialogOf(friday), {key: 'Escape'});+ expect(friday).toHaveAttribute('aria-expanded', 'false');+ });++ it('closes when the open day is pressed again, dismissed, or paged away', () => {+ render(<MonthAt />);+ const wednesday = screen.getByRole('button', {name: /^3 more events,/});+ fireEvent.pointerDown(wednesday);+ fireEvent.click(wednesday);+ expect(wednesday).toHaveAttribute('aria-expanded', 'true');+ fireEvent.pointerDown(wednesday);+ fireEvent.click(wednesday);+ expect(wednesday).toHaveAttribute('aria-expanded', 'false');++ fireEvent.click(wednesday);+ expect(wednesday).toHaveAttribute('aria-expanded', 'true');+ const layer = document.getElementById(+ wednesday.getAttribute('aria-controls') ?? '',+ ) as HTMLElement;+ const toggle = new Event('toggle');+ Object.defineProperty(toggle, 'newState', {value: 'closed'});+ fireEvent(layer, toggle);+ expect(wednesday).toHaveAttribute('aria-expanded', 'false');++ fireEvent.click(wednesday);+ expect(dialogOf(wednesday)).toHaveAttribute(+ 'aria-label',+ 'Wednesday, May 13, 2026',+ );+ fireEvent.click(screen.getByRole('button', {name: 'Next month'}));+ expect(screen.queryByRole('button', {name: /more events?,/})).toBeNull();+ expect(screen.queryByText('Alpha review')).toBeNull();+ });++ it('closes when the open day stops being busy and moves focus to that day', () => {+ const {rerender} = render(<MonthAt />);+ const friday = screen.getByRole('button', {name: /^2 more events,/});+ fireEvent.click(friday);+ expect(friday).toHaveAttribute('aria-expanded', 'true');+ // Focus is inside the open dialog, as Popover's auto-focus leaves it.+ const dialog = dialogOf(friday);+ const focusTarget = dialog.querySelector<HTMLElement>('button, [tabindex]');+ (focusTarget ?? dialog).focus();+ rerender(+ <MonthAt source={events.filter(event => event.id !== 'friday-4')} />,+ );+ expect(+ screen.queryByRole('button', {name: /Friday, May 15, 2026$/}),+ ).toBeNull();+ expect(document.querySelector('[role="dialog"] li')).toBeNull();+ expect(document.activeElement).toBe(+ screen.getByRole('cell', {name: 'Friday, May 15, 2026'}),+ );+ });++ it('adds no button to a month whose days fit in three levels', () => {+ render(<MonthAt source={events.slice(0, 4)} />);+ expect(screen.queryByRole('button', {name: /more events?,/})).toBeNull();+ expect(screen.queryByRole('dialog')).toBeNull();+ });+});diff --git a/packages/lab/src/Schedule/__tests__/ScheduleMonthOverflow.a11y.chromium.spec.ts b/packages/lab/src/Schedule/__tests__/ScheduleMonthOverflow.a11y.chromium.spec.tsnew file mode 100644index 0000000000..f9a32ee6b3--- /dev/null+++ b/packages/lab/src/Schedule/__tests__/ScheduleMonthOverflow.a11y.chromium.spec.ts@@ -0,0 +1,669 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ScheduleMonthOverflow.a11y.chromium.spec.ts+ * @input The built Lab/Schedule month-overflow story in real Chromium+ * @output Receipted evidence that the month is a table with weekday column+ * headers, week row headers and date-named cells; that a week row keeps+ * every chip inside it; that each busy day paints or counts every one of+ * its events; and that a day's "+N more" is a named Tab stop opening one+ * view-owned popover that lists the whole day: by keyboard and pointer,+ * switching days in one gesture, closing on Escape, light dismiss and+ * paging, with a full focus ring; in LTR and RTL, light and dark, wide and+ * narrow+ * @position Browser binding for `component:Schedule` FR15–FR17 and AR7. jsdom+ * has no layout or Tab order, cannot show a native popover, return focus+ * through it, or paint a focus ring.+ */++import {expect, test, type Page} from '@playwright/test';+import pixelmatch from 'pixelmatch';+// @ts-expect-error -- pngjs ships no declarations; runtime support is pinned.+import {PNG} from 'pngjs';+import {+ finishEvidence,+ openStory,+ record,+ startEvidence,+ WIDE,+ type Evidence,+} from './timeGridProbe';++const STORY = 'lab-schedule--month-overflow';+// Narrower than the month grid's 784px minimum plus the story's padding, so+// the grid scrolls on the inline axis.+const NARROW_MONTH = {width: 800, height: 900};+const WEDNESDAY = 'Wednesday, May 13, 2026';+const FRIDAY = 'Friday, May 15, 2026';+// The story's fixture: how many events each busy day holds.+const EVENTS_ON = {[WEDNESDAY]: 5, [FRIDAY]: 4} as const;++let evidence: Evidence;+test.beforeAll(async () => {+ evidence = await startEvidence();+});+test.afterAll(async () => {+ await finishEvidence(evidence, 'month-overflow');+});++interface MonthReading {+ /** Chips that paint below the bottom of the week row they start in. */+ readonly chipsOutsideRow: ReadonlyArray<{+ readonly text: string;+ readonly overflowPx: number;+ }>;+ readonly chipCount: number;+ /** Whether the "+" of a "+N more" paints before its "more", as read. */+ readonly countReadsInOrder: boolean | null;+ /** Per busy day: chips painted across its cell and its "+N more" count. */+ readonly days: Record<+ string,+ {+ readonly paintedChips: number;+ readonly counted: number;+ readonly moreInsideCell: boolean;+ }+ >;+ readonly surfaceIsolation: string;+}++/**+ * 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+ * day's "+N more" is the named button inside its cell.+ */+function readMonth(page: Page): Promise<MonthReading> {+ return page.evaluate(+ ([dayNames]) => {+ // The label's text can span several nodes ("+", "3", " more"), so+ // each glyph run is found on its own.+ const rectOf = (root: Node, needle: string): DOMRect | null => {+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);+ for (+ let node = walker.nextNode();+ node != null;+ node = walker.nextNode()+ ) {+ const at = (node.textContent ?? '').indexOf(needle);+ if (at >= 0) {+ const range = document.createRange();+ range.setStart(node, at);+ range.setEnd(node, at + needle.length);+ return range.getBoundingClientRect();+ }+ }+ return null;+ };+ const grid = document.querySelector<HTMLElement>(+ '.astryx-schedule [role="table"], .astryx-schedule [role="grid"]',+ );+ if (grid == null) {+ throw new Error('no month table');+ }+ const cells = [+ ...grid.querySelectorAll<HTMLElement>(+ '[role="cell"], [role="gridcell"]',+ ),+ ].map(cell => ({+ label: cell.getAttribute('aria-label') ?? '',+ rect: cell.getBoundingClientRect(),+ cell,+ }));+ const overlay = [+ ...grid.querySelectorAll<HTMLElement>('[aria-hidden="true"]'),+ ].find(+ element =>+ getComputedStyle(element).position === 'absolute' &&+ element.children.length > 0,+ );+ const chips = overlay == null ? [] : [...overlay.children];+ const chipsOutsideRow = chips.flatMap(chip => {+ const rect = chip.getBoundingClientRect();+ const start = cells.find(+ ({rect: cell}) =>+ rect.left + 2 >= cell.left - 1 &&+ rect.left + 2 <= cell.right + 1 &&+ rect.top >= cell.top - 1 &&+ rect.top <= cell.bottom,+ );+ const startEnd = cells.find(+ ({rect: cell}) =>+ rect.right - 2 >= cell.left - 1 &&+ rect.right - 2 <= cell.right + 1 &&+ rect.top >= cell.top - 1 &&+ rect.top <= cell.bottom,+ );+ const row = start ?? startEnd;+ if (row == null) {+ return [{text: chip.textContent ?? '', overflowPx: Infinity}];+ }+ const overflowPx = rect.bottom - row.rect.bottom;+ return overflowPx > 1+ ? [{text: chip.textContent ?? '', overflowPx}]+ : [];+ });+ const days: Record<+ string,+ {paintedChips: number; counted: number; moreInsideCell: boolean}+ > = {};+ for (const name of dayNames) {+ const day = cells.find(cell => cell.label === name);+ if (day == null) {+ throw new Error(`no cell named ${name}`);+ }+ const paintedChips = chips.filter(chip => {+ const rect = chip.getBoundingClientRect();+ const inlineOverlap =+ Math.min(rect.right, day.rect.right) -+ Math.max(rect.left, day.rect.left);+ return (+ inlineOverlap > 2 &&+ rect.top >= day.rect.top - 1 &&+ rect.top < day.rect.bottom+ );+ }).length;+ const more = [...day.cell.querySelectorAll<HTMLElement>('button')].find(+ button =>+ /more events?,/.test(button.getAttribute('aria-label') ?? ''),+ );+ const moreRect = more?.getBoundingClientRect();+ days[name] = {+ paintedChips,+ counted:+ more == null+ ? 0+ : Number.parseInt(+ (more.getAttribute('aria-label') ?? '').split(' ')[0],+ 10,+ ),+ moreInsideCell:+ moreRect != null &&+ moreRect.left >= day.rect.left - 1 &&+ moreRect.right <= day.rect.right + 1 &&+ moreRect.top >= day.rect.top - 1 &&+ moreRect.bottom <= day.rect.bottom + 1,+ };+ }+ // The visual order of the count's "+" and its "more" in the label.+ const wednesdayMore = [...grid.querySelectorAll('button')].find(button =>+ /^3 more events,/.test(button.getAttribute('aria-label') ?? ''),+ );+ const plus = wednesdayMore == null ? null : rectOf(wednesdayMore, '+');+ const more = wednesdayMore == null ? null : rectOf(wednesdayMore, 'more');+ const countReadsInOrder =+ plus == null || more == null ? null : plus.right <= more.left + 1;+ return {+ chipsOutsideRow,+ chipCount: chips.length,+ countReadsInOrder,+ days,+ surfaceIsolation:+ overlay?.parentElement == null+ ? 'none'+ : getComputedStyle(overlay.parentElement).isolation,+ };+ },+ [[WEDNESDAY, FRIDAY]] as const,+ );+}++/** The open dialog as assistive technology sees it. */+function readDialog(page: Page) {+ return page.evaluate(() => {+ const open = [+ ...document.querySelectorAll<HTMLElement>('[role="dialog"]'),+ ].filter(dialog =>+ dialog.closest<HTMLElement>('[popover]')?.matches(':popover-open'),+ );+ const dialog = open[0];+ return {+ openCount: open.length,+ label: dialog?.getAttribute('aria-label') ?? null,+ layerID: dialog?.closest<HTMLElement>('[popover]')?.id ?? null,+ items: dialog == null ? 0 : dialog.querySelectorAll('li').length,+ focusInside:+ dialog != null && document.activeElement != null+ ? dialog.contains(document.activeElement)+ : false,+ };+ });+}++function readMore(page: Page, day: string) {+ return page.evaluate(name => {+ const button = [...document.querySelectorAll('button')].find(candidate =>+ candidate.getAttribute('aria-label')?.endsWith(`, ${name}`),+ );+ if (button == null) {+ throw new Error(`no "+N more" for ${name}`);+ }+ return {+ label: button.getAttribute('aria-label'),+ text: button.textContent,+ expanded: button.getAttribute('aria-expanded'),+ haspopup: button.getAttribute('aria-haspopup'),+ controls: button.getAttribute('aria-controls'),+ isActive: document.activeElement === button,+ };+ }, day);+}++function expectNothingLost(reading: MonthReading) {+ expect(reading.chipsOutsideRow).toEqual([]);+ expect(reading.countReadsInOrder, '"+N more" reads in order').toBe(true);+ expect(reading.surfaceIsolation).toBe('isolate');+ for (const [day, total] of Object.entries(EVENTS_ON)) {+ const {paintedChips, counted, moreInsideCell} = reading.days[day];+ expect(paintedChips + counted, `${day}: painted + counted`).toBe(total);+ expect(counted, `${day}: counted`).toBeGreaterThan(0);+ expect(moreInsideCell, `${day}: "+N more" inside its cell`).toBe(true);+ }+}++test('the month is a table: weekday and week headers, date-named cells, and "+N more" in the Tab order after the table', async ({+ page,+}) => {+ await openStory(evidence, page, STORY, WIDE);+ const table = page.getByRole('table', {name: 'May 2026'});+ await expect(table).toBeVisible();+ const tree = await table.ariaSnapshot();+ const reading = await page.evaluate(() => {+ const table = document.querySelector('.astryx-schedule [role="table"]');+ const rows = [...(table?.querySelectorAll('[role="row"]') ?? [])];+ return {+ gridRoles: document.querySelectorAll(+ '.astryx-schedule [role="grid"], .astryx-schedule [role="gridcell"]',+ ).length,+ readonly: table?.getAttribute('aria-readonly') ?? null,+ columnHeaders: [+ ...(table?.querySelectorAll('[role="columnheader"]') ?? []),+ ].map(header => header.getAttribute('aria-label') ?? header.textContent),+ rowHeaders: rows+ .slice(1)+ .map(+ row => row.querySelector('[role="rowheader"]')?.textContent ?? null,+ ),+ cellsPerRow: rows+ .slice(1)+ .map(row => row.querySelectorAll('[role="cell"]').length),+ wednesdayCell:+ table+ ?.querySelector('[role="cell"][aria-current="date"]')+ ?.getAttribute('aria-label') ?? null,+ // One real header-to-cell association: the column header at the+ // Sunday cell's position in its row, by DOM position and by index.+ sunday: (() => {+ const cell = table?.querySelector(+ '[role="cell"][aria-label="Sunday, May 10, 2026"]',+ );+ const row = cell?.closest('[role="row"]');+ const position =+ row == null || cell == null+ ? -1+ : [...row.children].indexOf(cell as Element);+ const headers = [+ ...(rows[0]?.querySelectorAll('[role="columnheader"]') ?? []),+ ];+ const header = headers[position];+ return {+ header: header?.getAttribute('aria-label') ?? header?.textContent,+ cellIndex: cell?.getAttribute('aria-colindex') ?? null,+ headerIndex: header?.getAttribute('aria-colindex') ?? null,+ };+ })(),+ moreButtons: [...(table?.querySelectorAll('button') ?? [])].map(+ button => ({+ name: button.getAttribute('aria-label'),+ cell: button.closest('[role="cell"]')?.getAttribute('aria-label'),+ tabIndex: button.tabIndex,+ }),+ ),+ };+ });+ const stops: string[] = [];+ for (let press = 0; press < 7; press += 1) {+ await page.keyboard.press('Tab');+ stops.push(+ await page.evaluate(+ () =>+ `${document.activeElement?.getAttribute('role') ?? document.activeElement?.tagName.toLowerCase()}:${document.activeElement?.getAttribute('aria-label') ?? document.activeElement?.textContent ?? ''}`,+ ),+ );+ }+ await record(evidence, page, 'month-table-structure', STORY, 'ltr', {+ reading,+ stops,+ tree,+ });+ expect(reading.gridRoles).toBe(0);+ expect(reading.readonly).toBeNull();+ expect(reading.columnHeaders).toEqual([+ 'Week',+ 'Sunday',+ 'Monday',+ 'Tuesday',+ 'Wednesday',+ 'Thursday',+ 'Friday',+ 'Saturday',+ ]);+ expect(reading.rowHeaders).toHaveLength(6);+ for (const header of reading.rowHeaders) {+ expect(header).toMatch(/\d+\s*–\s*.*\d{4}$/);+ }+ expect(reading.cellsPerRow).toEqual([7, 7, 7, 7, 7, 7]);+ expect(reading.wednesdayCell).toBe(WEDNESDAY);+ expect(reading.sunday).toEqual({+ header: 'Sunday',+ cellIndex: '2',+ headerIndex: '2',+ });+ expect(reading.moreButtons).toEqual([+ {name: `3 more events, ${WEDNESDAY}`, cell: WEDNESDAY, tabIndex: 0},+ {name: `2 more events, ${FRIDAY}`, cell: FRIDAY, tabIndex: 0},+ ]);+ // Tab: the pager, the table itself (it scrolls), then each "+N more" in+ // reading order.+ const tableStop = stops.indexOf('table:May 2026');+ expect(tableStop, stops.join(' → ')).toBeGreaterThan(0);+ expect(stops.slice(tableStop + 1, tableStop + 3)).toEqual([+ `button:3 more events, ${WEDNESDAY}`,+ `button:2 more events, ${FRIDAY}`,+ ]);+});++test('every chip stays in its week row and each busy day paints or counts all of its events', async ({+ page,+}) => {+ for (const [name, viewport] of [+ ['wide', WIDE],+ ['narrow', NARROW_MONTH],+ ] as const) {+ await openStory(evidence, page, STORY, viewport);+ const reading = await readMonth(page);+ await record(evidence, page, `month-rows-${name}`, STORY, 'ltr', reading);+ expectNothingLost(reading);+ expect(reading.days[WEDNESDAY]).toMatchObject({+ paintedChips: 2,+ counted: 3,+ });+ expect(reading.days[FRIDAY]).toMatchObject({paintedChips: 2, counted: 2});+ }+});++test('the same holds right-to-left and in dark mode', async ({page}) => {+ for (const [name, globals] of [+ ['rtl', 'direction:rtl'],+ ['dark', 'colorMode:dark'],+ ['rtl-dark', 'direction:rtl;colorMode:dark'],+ ] as const) {+ await openStory(evidence, page, STORY, WIDE, globals);+ const reading = await readMonth(page);+ await record(+ evidence,+ page,+ `month-rows-${name}`,+ STORY,+ name.startsWith('rtl') ? 'rtl' : 'ltr',+ reading,+ );+ expectNothingLost(reading);+ }+});++test('Tab reaches "+N more", Enter opens the day popover, and Escape returns focus to it', async ({+ page,+}) => {+ await openStory(evidence, page, STORY, WIDE);+ const stops: string[] = [];+ let reached = false;+ for (let press = 0; press < 10 && !reached; press += 1) {+ await page.keyboard.press('Tab');+ const label = await page.evaluate(+ () =>+ document.activeElement?.getAttribute('aria-label') ??+ document.activeElement?.tagName.toLowerCase() ??+ null,+ );+ stops.push(label ?? 'other');+ reached = /more events?,/.test(label ?? '');+ }+ expect(reached, `Tab reached "+N more": ${stops.join(' → ')}`).toBe(true);+ const before = await readMore(page, WEDNESDAY);+ expect(before).toMatchObject({+ label: `3 more events, ${WEDNESDAY}`,+ text: '+3 more',+ expanded: 'false',+ haspopup: 'dialog',+ isActive: true,+ });++ await page.keyboard.press('Enter');+ await expect.poll(async () => (await readDialog(page)).openCount).toBe(1);+ const dialog = await readDialog(page);+ const opened = await readMore(page, WEDNESDAY);+ await record(evidence, page, 'month-popover-keyboard', STORY, 'ltr', {+ stops,+ button: opened,+ dialog,+ });+ expect(opened.expanded).toBe('true');+ expect(dialog).toMatchObject({+ label: WEDNESDAY,+ layerID: before.controls,+ items: EVENTS_ON[WEDNESDAY],+ focusInside: true,+ });++ await page.keyboard.press('Escape');+ await expect.poll(async () => (await readDialog(page)).openCount).toBe(0);+ await expect+ .poll(async () => (await readMore(page, WEDNESDAY)).expanded)+ .toBe('false');+ expect((await readMore(page, WEDNESDAY)).isActive).toBe(true);+});++test('click switches days in one gesture; light dismiss and paging close the popover', async ({+ page,+}) => {+ await openStory(evidence, page, STORY, WIDE);+ const wednesday = page.getByRole('button', {+ name: `3 more events, ${WEDNESDAY}`,+ });+ const friday = page.getByRole('button', {name: `2 more events, ${FRIDAY}`});++ await wednesday.click();+ await expect.poll(async () => (await readDialog(page)).label).toBe(WEDNESDAY);+ await friday.click();+ await expect.poll(async () => (await readDialog(page)).label).toBe(FRIDAY);+ const afterSwitch = {+ wednesday: await readMore(page, WEDNESDAY),+ friday: await readMore(page, FRIDAY),+ dialog: await readDialog(page),+ };+ await record(+ evidence,+ page,+ 'month-popover-switch',+ STORY,+ 'ltr',+ afterSwitch,+ );+ expect(afterSwitch.wednesday.expanded).toBe('false');+ expect(afterSwitch.friday.expanded).toBe('true');+ expect(afterSwitch.dialog).toMatchObject({openCount: 1, items: 4});++ // Light dismiss: a click on the header, outside the dialog.+ const title = await page.locator('.astryx-schedule h2').first().boundingBox();+ await page.mouse.click(+ (title?.x ?? 0) + (title?.width ?? 0) / 2,+ (title?.y ?? 0) + (title?.height ?? 0) / 2,+ );+ await expect.poll(async () => (await readDialog(page)).openCount).toBe(0);+ await expect+ .poll(async () => (await readMore(page, FRIDAY)).expanded)+ .toBe('false');++ // Paging away closes an open day and leaves no dialog or error behind.+ const errors: string[] = [];+ page.on('pageerror', error => errors.push(error.message));+ page.on('console', message => {+ if (message.type() === 'error') {+ errors.push(message.text());+ }+ });+ await wednesday.click();+ await expect.poll(async () => (await readDialog(page)).openCount).toBe(1);+ await page.getByRole('button', {name: 'Next month'}).click();+ await expect.poll(async () => (await readDialog(page)).openCount).toBe(0);+ const afterPaging = await page.evaluate(() => ({+ moreButtons: [...document.querySelectorAll('button')].filter(button =>+ /more events?,/.test(button.getAttribute('aria-label') ?? ''),+ ).length,+ expanded: document.querySelectorAll('[aria-expanded="true"]').length,+ }));+ await record(evidence, page, 'month-popover-paged', STORY, 'ltr', {+ afterPaging,+ errors,+ });+ expect(afterPaging).toEqual({moreButtons: 0, expanded: 0});+ expect(errors).toEqual([]);+});++test('a focused "+N more" paints its whole focus ring above the chips', async ({+ page,+}) => {+ await openStory(evidence, page, STORY, WIDE);+ const button = page.getByRole('button', {+ name: `3 more events, ${WEDNESDAY}`,+ });+ const box = await button.boundingBox();+ expect(box).not.toBeNull();+ const clip = {+ x: (box?.x ?? 0) - 8,+ y: (box?.y ?? 0) - 8,+ width: (box?.width ?? 0) + 16,+ height: (box?.height ?? 0) + 16,+ };+ const rest = await page.screenshot({clip});+ await button.focus();+ // Focus from script does not match :focus-visible; a key press does.+ await page.keyboard.press('Shift');+ const focused = await page.screenshot({clip});+ const decode = (png: Buffer) =>+ PNG.sync.read(png) as {width: number; height: number; data: Buffer};+ const before = decode(rest);+ const after = decode(focused);+ const ringPixels = pixelmatch(+ before.data,+ after.data,+ undefined,+ before.width,+ before.height,+ {threshold: 0.1},+ );+ const style = await page.evaluate(() => {+ const element = document.activeElement as HTMLElement;+ const computed = getComputedStyle(element);+ return {+ outlineStyle: computed.outlineStyle,+ outlineWidth: Number.parseFloat(computed.outlineWidth),+ zIndex: computed.zIndex,+ };+ });+ await record(evidence, page, 'month-more-focus-ring', STORY, 'ltr', {+ ringPixels,+ style,+ });+ expect(style.outlineStyle).not.toBe('none');+ expect(style.outlineWidth).toBeGreaterThan(0);+ expect(style.zIndex).toBe('2');+ expect(ringPixels).toBeGreaterThan(+ ((box?.width ?? 0) + (box?.height ?? 0)) * 2,+ );+});++test('when a refresh takes away an open day\'s "+N more", focus lands on that day\'s cell with the ring', async ({+ page,+}) => {+ await openStory(evidence, page, STORY, WIDE);+ const stops: string[] = [];+ let reached = false;+ for (let press = 0; press < 10 && !reached; press += 1) {+ await page.keyboard.press('Tab');+ const label = await page.evaluate(+ () => document.activeElement?.getAttribute('aria-label') ?? null,+ );+ stops.push(label ?? 'other');+ reached = label === `2 more events, ${FRIDAY}`;+ }+ expect(reached, `Tab reached Friday's "+N more": ${stops.join(' → ')}`).toBe(+ true,+ );+ await page.keyboard.press('Enter');+ await expect.poll(async () => (await readDialog(page)).label).toBe(FRIDAY);+ expect((await readDialog(page)).focusInside).toBe(true);++ // Friday drops to three levels: its "+N more" is no longer rendered.+ await page.evaluate(() => {+ (+ window as unknown as {+ scheduleMonthOverflowStory: {removeEvent: (id: string) => void};+ }+ ).scheduleMonthOverflowStory.removeEvent('focus');+ });+ await expect.poll(async () => (await readDialog(page)).openCount).toBe(0);+ const focus = await page.evaluate(day => {+ const active = document.activeElement as HTMLElement | null;+ const computed = active == null ? null : getComputedStyle(active);+ return {+ role: active?.getAttribute('role') ?? null,+ label: active?.getAttribute('aria-label') ?? null,+ tabIndex: active?.tabIndex ?? null,+ outlineStyle: computed?.outlineStyle ?? null,+ outlineWidth: Number.parseFloat(computed?.outlineWidth ?? '0'),+ fridayMore: [...document.querySelectorAll('button')].some(button =>+ button.getAttribute('aria-label')?.endsWith(`, ${day}`),+ ),+ };+ }, FRIDAY);+ const cell = page.getByRole('cell', {name: FRIDAY});+ const box = await cell.boundingBox();+ expect(box).not.toBeNull();+ const clip = {+ x: box?.x ?? 0,+ y: box?.y ?? 0,+ width: box?.width ?? 0,+ height: box?.height ?? 0,+ };+ const ringed = await page.screenshot({clip});+ // The same cell without focus, for the ring's pixels.+ await page.evaluate(() => (document.activeElement as HTMLElement).blur());+ const plain = await page.screenshot({clip});+ const decode = (png: Buffer) =>+ PNG.sync.read(png) as {width: number; height: number; data: Buffer};+ const ringPixels = pixelmatch(+ decode(plain).data,+ decode(ringed).data,+ undefined,+ decode(plain).width,+ decode(plain).height,+ {threshold: 0.1},+ );+ await record(evidence, page, 'month-refresh-focus', STORY, 'ltr', {+ stops,+ focus,+ ringPixels,+ });+ expect(focus).toMatchObject({+ role: 'cell',+ label: FRIDAY,+ tabIndex: -1,+ fridayMore: false,+ });+ expect(focus.outlineStyle).not.toBe('none');+ expect(focus.outlineWidth).toBeGreaterThan(0);+ expect(ringPixels).toBeGreaterThan(+ ((box?.width ?? 0) + (box?.height ?? 0)) * 2,+ );+});diff --git a/packages/lab/src/Schedule/monthLayout.test.ts b/packages/lab/src/Schedule/monthLayout.test.tsnew file mode 100644index 0000000000..272cae3e2b--- /dev/null+++ b/packages/lab/src/Schedule/monthLayout.test.ts@@ -0,0 +1,298 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it} from 'vitest';+import {plainDateFromISO, type ISODateString} from '@astryxdesign/core/utils';+import {createEventFromISO} from './CalendarEvent';+import {enumerateDates} from './dateMath';+import {layoutMonthEvents, type MonthLayout} from './monthLayout';+import type {CalendarEvent} from './types';++// component:Schedule FR15–FR16. One UTC week, Sunday May 10 to Saturday+// May 16, 2026: column 0 is Sunday and column 3 is Wednesday.+const TIMEZONE = 'UTC';+const WEEK = enumerateDates(+ plainDateFromISO('2026-05-10' as ISODateString),+ plainDateFromISO('2026-05-16' as ISODateString),+);+const TWO_WEEKS = enumerateDates(+ plainDateFromISO('2026-05-10' as ISODateString),+ plainDateFromISO('2026-05-23' as ISODateString),+);++function allDay(id: string, start: string, end: string): CalendarEvent {+ return createEventFromISO({id, title: id, start, end});+}++function timed(+ id: string,+ day: string,+ hour: number,+ title: string = id,+): CalendarEvent {+ const pad = (value: number) => String(value).padStart(2, '0');+ return createEventFromISO({+ id,+ title,+ start: `${day}T${pad(hour)}:00:00.000Z`,+ end: `${day}T${pad(hour + 1)}:00:00.000Z`,+ });+}++/** Chips as `id@week:start-end/level`, in a stable order for comparison. */+function chipKeys(layout: MonthLayout): string[] {+ return layout.chips+ .map(+ chip =>+ `${chip.event.id}@${chip.week}:${chip.columnStart}-${chip.columnEnd}/${chip.level}`,+ )+ .sort();+}++function overflowKeys(layout: MonthLayout): string[] {+ return layout.overflow.map(day => `${day.dayIndex}+${day.count}`);+}++/** Every event of a day is painted on that day or counted there (FR16). */+function expectEveryEventPaintedOrCounted(+ layout: MonthLayout,+ events: ReadonlyArray<CalendarEvent>,+ days: typeof WEEK,+) {+ days.forEach((day, dayIndex) => {+ const week = Math.floor(dayIndex / 7);+ const column = dayIndex % 7;+ const onDay = events.filter(event => {+ const visible = layoutMonthEvents([event], days, TIMEZONE);+ return visible.chips.some(+ chip =>+ chip.week === week &&+ chip.columnStart <= column &&+ column <= chip.columnEnd,+ );+ });+ const painted = layout.chips.filter(+ chip =>+ chip.week === week &&+ chip.columnStart <= column &&+ column <= chip.columnEnd,+ ).length;+ const counted =+ layout.overflow.find(overflowDay => overflowDay.dayIndex === dayIndex)+ ?.count ?? 0;+ expect(painted + counted, `day ${dayIndex}`).toBe(onDay.length);+ });+}++// Wednesday holds five events: two of the three spans that cover it and three+// timed events of its own, which need levels one to five.+const BUSY_WEDNESDAY: CalendarEvent[] = [+ allDay('conference', '2026-05-10', '2026-05-13'),+ allDay('hack-week', '2026-05-10', '2026-05-12'),+ allDay('offsite', '2026-05-11', '2026-05-13'),+ timed('alpha', '2026-05-13', 9),+ timed('bravo', '2026-05-13', 11),+ timed('charlie', '2026-05-13', 14),+];++describe('layoutMonthEvents', () => {+ it('paints two chips and counts three on a day that needs five levels', () => {+ const layout = layoutMonthEvents(BUSY_WEDNESDAY, WEEK, TIMEZONE);+ expect(chipKeys(layout)).toEqual([+ 'alpha@0:3-3/1',+ 'conference@0:0-3/0',+ 'hack-week@0:0-2/1',+ // The third-level span is painted on its other days only.+ 'offsite@0:1-2/2',+ ]);+ expect(overflowKeys(layout)).toEqual(['3+3']);+ expect(layout.chips.every(chip => chip.level < 3)).toBe(true);+ expectEveryEventPaintedOrCounted(layout, BUSY_WEDNESDAY, WEEK);+ });++ it('paints a day with three levels whole and counts nothing', () => {+ const events = BUSY_WEDNESDAY.slice(0, 3);+ const layout = layoutMonthEvents(events, WEEK, TIMEZONE);+ expect(chipKeys(layout)).toEqual([+ 'conference@0:0-3/0',+ 'hack-week@0:0-2/1',+ 'offsite@0:1-3/2',+ ]);+ expect(layout.overflow).toEqual([]);+ });++ it('counts by level, so an empty third level on a busy day still holds the count', () => {+ // Monday to Wednesday need four levels; Wednesday's third level is empty+ // because its span ended Tuesday.+ const events = [+ allDay('e1', '2026-05-10', '2026-05-13'),+ allDay('e2', '2026-05-10', '2026-05-13'),+ allDay('e3', '2026-05-10', '2026-05-12'),+ allDay('e4', '2026-05-11', '2026-05-13'),+ ];+ const layout = layoutMonthEvents(events, WEEK, TIMEZONE);+ expect(chipKeys(layout)).toEqual([+ 'e1@0:0-3/0',+ 'e2@0:0-3/1',+ 'e3@0:0-0/2',+ ]);+ expect(overflowKeys(layout)).toEqual(['1+2', '2+2', '3+1']);+ expectEveryEventPaintedOrCounted(layout, events, WEEK);+ });++ it('gives the same layout for any input order', () => {+ const expected = layoutMonthEvents(BUSY_WEDNESDAY, WEEK, TIMEZONE);+ const orders = [+ [...BUSY_WEDNESDAY].reverse(),+ [+ BUSY_WEDNESDAY[3],+ BUSY_WEDNESDAY[0],+ BUSY_WEDNESDAY[5],+ BUSY_WEDNESDAY[2],+ BUSY_WEDNESDAY[4],+ BUSY_WEDNESDAY[1],+ ],+ ];+ for (const order of orders) {+ const layout = layoutMonthEvents(order, WEEK, TIMEZONE);+ expect(chipKeys(layout)).toEqual(chipKeys(expected));+ expect(overflowKeys(layout)).toEqual(overflowKeys(expected));+ }+ });++ it('paints the earliest events of a busy day, whatever their titles', () => {+ // Title order and start order disagree: Zulu is first by start time.+ const events = [+ ...BUSY_WEDNESDAY.slice(0, 3),+ timed('zulu', '2026-05-13', 8, 'Zulu standup'),+ timed('alpha-late', '2026-05-13', 16, 'Alpha retro'),+ timed('mike', '2026-05-13', 12, 'Mike lunch'),+ ];+ const layout = layoutMonthEvents(events, WEEK, TIMEZONE);+ expect(+ layout.chips+ .filter(chip => chip.week === 0 && chip.columnStart === 3)+ .map(chip => chip.event.id),+ ).toEqual(['zulu']);+ expect(overflowKeys(layout)).toEqual(['3+3']);+ });++ it('never hides a timed event that starts before a painted one on the same day', () => {+ // A seeded walk through many busy fortnights: on every day, each+ // single-day timed event behind "+N more" starts no earlier than every+ // single-day timed chip painted that day.+ let seed = 7;+ const random = () => {+ seed = (seed * 1103515245 + 12345) % 2147483648;+ return seed / 2147483648;+ };+ for (let run = 0; run < 200; run += 1) {+ const events: CalendarEvent[] = [];+ const count = 4 + Math.floor(random() * 14);+ for (let index = 0; index < count; index += 1) {+ const startDay = 10 + Math.floor(random() * 14);+ const day = `2026-05-${String(startDay).padStart(2, '0')}`;+ if (random() < 0.3) {+ const endDay = Math.min(23, startDay + Math.floor(random() * 4));+ events.push(+ allDay(+ `span-${index}`,+ day,+ `2026-05-${String(endDay).padStart(2, '0')}`,+ ),+ );+ } else {+ events.push(+ timed(+ `timed-${index}`,+ day,+ Math.floor(random() * 23),+ `${String.fromCharCode(90 - index)} meeting`,+ ),+ );+ }+ }+ const layout = layoutMonthEvents(events, TWO_WEEKS, TIMEZONE);+ // The days each event covers, from its layout alone.+ const covered = new Map(+ events.map(event => [+ event.id,+ new Set(+ layoutMonthEvents([event], TWO_WEEKS, TIMEZONE).chips.flatMap(+ chip =>+ Array.from(+ {length: chip.columnEnd - chip.columnStart + 1},+ (_, offset) => chip.week * 7 + chip.columnStart + offset,+ ),+ ),+ ),+ ]),+ );+ TWO_WEEKS.forEach((_, dayIndex) => {+ const week = Math.floor(dayIndex / 7);+ const column = dayIndex % 7;+ const timedOnDay = events.filter(+ event =>+ typeof event.start === 'number' &&+ new Date(event.start).getUTCDate() === 10 + dayIndex,+ );+ const paintedIDs = new Set(+ layout.chips+ .filter(+ chip =>+ chip.week === week &&+ chip.columnStart <= column &&+ column <= chip.columnEnd,+ )+ .map(chip => chip.event.id),+ );+ // Every event of the day is painted or counted (FR16).+ const onDay = events.filter(event =>+ covered.get(event.id)?.has(dayIndex),+ ).length;+ const counted =+ layout.overflow.find(day => day.dayIndex === dayIndex)?.count ?? 0;+ expect(paintedIDs.size + counted, `run ${run}, day ${dayIndex}`).toBe(+ onDay,+ );+ const painted = timedOnDay.filter(event => paintedIDs.has(event.id));+ const hidden = timedOnDay.filter(event => !paintedIDs.has(event.id));+ const latestPainted = Math.max(+ ...painted.map(event => Number(event.start)),+ );+ for (const event of hidden) {+ expect(+ Number(event.start),+ `run ${run}, day ${dayIndex}: ${event.id} is hidden behind a later chip`,+ ).toBeGreaterThanOrEqual(latestPainted);+ }+ });+ }+ });++ it('orders identical events by id', () => {+ const events = [+ timed('pair-b', '2026-05-12', 9, 'Pair review'),+ timed('pair-a', '2026-05-12', 9, 'Pair review'),+ ];+ const layout = layoutMonthEvents(events, WEEK, TIMEZONE);+ expect(chipKeys(layout)).toEqual(['pair-a@0:2-2/0', 'pair-b@0:2-2/1']);+ });++ it('paints one chip per week a span covers', () => {+ const events = [allDay('sprint', '2026-05-14', '2026-05-19')];+ const layout = layoutMonthEvents(events, TWO_WEEKS, TIMEZONE);+ expect(chipKeys(layout)).toEqual(['sprint@0:4-6/0', 'sprint@1:0-2/0']);+ });++ it('lays out nothing for no events and leaves out events outside the range', () => {+ expect(layoutMonthEvents([], WEEK, TIMEZONE)).toEqual({+ chips: [],+ overflow: [],+ });+ const outside = [allDay('later', '2026-06-01', '2026-06-02')];+ expect(layoutMonthEvents(outside, WEEK, TIMEZONE)).toEqual({+ chips: [],+ overflow: [],+ });+ });+});diff --git a/packages/lab/src/Schedule/monthLayout.ts b/packages/lab/src/Schedule/monthLayout.tsnew file mode 100644index 0000000000..3a3d011b6e--- /dev/null+++ b/packages/lab/src/Schedule/monthLayout.ts@@ -0,0 +1,246 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file monthLayout.ts+ * @input The rendered range's events, its days (whole weeks), and the timezone+ * @output Month chip placements by week and level, cut around busy days, and+ * each busy day's "+N more" count+ * @position Internal pure layout for MonthlyView (component:Schedule FR15–FR16,+ * ORD4, PR4); no DOM reads, runs during render+ */++import {+ plainDateFromInstant,+ plainDateIsAfter,+ plainDateIsBefore,+ plainDateToInstant,+ type PlainDate,+} from '@astryxdesign/core/utils';+import {isDayEvent} from './dateMath';+import type {CalendarEvent} from './types';++/** A week row paints at most this many levels of chips. */+export const MONTH_VISIBLE_LEVELS = 3;++const DAYS_PER_WEEK = 7;++/** One painted chip: an event's run of days on one level of one week row. */+export interface MonthChipPlacement {+ readonly event: CalendarEvent;+ readonly week: number;+ readonly columnStart: number;+ readonly columnEnd: number;+ readonly level: number;+}++/** A day whose events need more levels than its week row paints. */+export interface MonthDayOverflow {+ readonly dayIndex: number;+ readonly week: number;+ readonly column: number;+ /** That day's events without a painted chip on that day. */+ readonly count: number;+}++export interface MonthLayout {+ readonly chips: ReadonlyArray<MonthChipPlacement>;+ readonly overflow: ReadonlyArray<MonthDayOverflow>;+}++interface RangedEvent {+ readonly event: CalendarEvent;+ readonly startIndex: number;+ readonly endIndex: number;+ readonly isPriority: boolean;+ /** The event's start instant; a date-only event starts at its first midnight. */+ readonly start: number;+}++/**+ * Lays out the month: every event takes, in each week it covers, the lowest+ * level free on all its days there. A day with an event on level four or+ * higher gives its third level to "+N more", which counts that day's events on+ * level three or higher; a third-level chip that crosses such a day is painted+ * on its other days only. Every event of a day is therefore painted on that+ * day or counted there, and no chip sits below the third level.+ */+export function layoutMonthEvents(+ events: ReadonlyArray<CalendarEvent>,+ days: ReadonlyArray<PlainDate>,+ timezoneID: string,+): MonthLayout {+ const firstDay = days[0];+ const lastDay = days[days.length - 1];+ if (firstDay == null || lastDay == null) {+ return {chips: [], overflow: []};+ }++ const ranged = events+ .flatMap((event): RangedEvent[] => {+ const [eventStart, eventEnd] = getEventDateSpan(event, timezoneID);+ if (+ plainDateIsBefore(eventEnd, firstDay) ||+ plainDateIsAfter(eventStart, lastDay)+ ) {+ return [];+ }+ const startIndex = days.findIndex(+ day => !plainDateIsBefore(day, eventStart),+ );+ let endIndex = days.length - 1;+ while (endIndex > 0 && plainDateIsAfter(days[endIndex], eventEnd)) {+ endIndex -= 1;+ }+ if (startIndex < 0 || endIndex < startIndex) {+ return [];+ }+ return [+ {+ event,+ startIndex,+ endIndex,+ isPriority: isDayEvent(event) || endIndex > startIndex,+ start: isDayEvent(event)+ ? plainDateToInstant(event.start, timezoneID)+ : event.start,+ },+ ];+ })+ .sort(compareRangedEvents);++ // Levels, per week, by the last column each level is occupied to. Events+ // arrive in first-day order, so each week sees its runs in start order and+ // a level whose last run ends before this run starts is free on every day+ // of it.+ const levelsByWeek: number[][] = [];+ const placements: MonthChipPlacement[] = [];+ for (const {event, startIndex, endIndex} of ranged) {+ const firstWeek = Math.floor(startIndex / DAYS_PER_WEEK);+ const lastWeek = Math.floor(endIndex / DAYS_PER_WEEK);+ for (let week = firstWeek; week <= lastWeek; week += 1) {+ const columnStart = week === firstWeek ? startIndex % DAYS_PER_WEEK : 0;+ const columnEnd =+ week === lastWeek ? endIndex % DAYS_PER_WEEK : DAYS_PER_WEEK - 1;+ const weekLevels = (levelsByWeek[week] ??= []);+ const freeLevel = weekLevels.findIndex(+ occupiedTo => occupiedTo < columnStart,+ );+ const level = freeLevel >= 0 ? freeLevel : weekLevels.length;+ weekLevels[level] = columnEnd;+ placements.push({event, week, columnStart, columnEnd, level});+ }+ }++ const lastPaintedLevel = MONTH_VISIBLE_LEVELS - 1;+ const isBusy = Array.from({length: days.length}, () => false);+ const countedOnDay = Array.from({length: days.length}, () => 0);+ for (const placement of placements) {+ forEachDay(placement, dayIndex => {+ if (placement.level > lastPaintedLevel) {+ isBusy[dayIndex] = true;+ }+ if (placement.level >= lastPaintedLevel) {+ countedOnDay[dayIndex] += 1;+ }+ });+ }++ const chips: MonthChipPlacement[] = [];+ for (const placement of placements) {+ if (placement.level < lastPaintedLevel) {+ chips.push(placement);+ } else if (placement.level === lastPaintedLevel) {+ // The third level belongs to "+N more" on a busy day, so the chip is+ // cut into the runs of days around it.+ let runStart: number | null = null;+ for (+ let column = placement.columnStart;+ column <= placement.columnEnd + 1;+ column += 1+ ) {+ const isFree =+ column <= placement.columnEnd &&+ !isBusy[placement.week * DAYS_PER_WEEK + column];+ if (isFree && runStart == null) {+ runStart = column;+ } else if (!isFree && runStart != null) {+ chips.push({+ ...placement,+ columnStart: runStart,+ columnEnd: column - 1,+ });+ runStart = null;+ }+ }+ }+ }++ const overflow: MonthDayOverflow[] = [];+ isBusy.forEach((busy, dayIndex) => {+ if (busy) {+ overflow.push({+ dayIndex,+ week: Math.floor(dayIndex / DAYS_PER_WEEK),+ column: dayIndex % DAYS_PER_WEEK,+ count: countedOnDay[dayIndex],+ });+ }+ });++ return {chips, overflow};+}++/**+ * First day, then all-day and multi-day events before single-day timed ones,+ * then events covering more days, then earlier starts, then title, then id.+ * The layout depends on the data alone, never on input order, and a busy day+ * paints its earliest events.+ */+function compareRangedEvents(a: RangedEvent, b: RangedEvent): number {+ if (a.startIndex !== b.startIndex) {+ return a.startIndex - b.startIndex;+ }+ if (a.isPriority !== b.isPriority) {+ return a.isPriority ? -1 : 1;+ }+ const durationDifference =+ b.endIndex - b.startIndex - (a.endIndex - a.startIndex);+ if (durationDifference !== 0) {+ return durationDifference;+ }+ if (a.start !== b.start) {+ return a.start - b.start;+ }+ const titleOrder = a.event.title.localeCompare(b.event.title);+ if (titleOrder !== 0) {+ return titleOrder;+ }+ return a.event.id < b.event.id ? -1 : a.event.id > b.event.id ? 1 : 0;+}++function forEachDay(+ placement: MonthChipPlacement,+ visit: (dayIndex: number) => void,+): void {+ for (+ let column = placement.columnStart;+ column <= placement.columnEnd;+ column += 1+ ) {+ visit(placement.week * DAYS_PER_WEEK + column);+ }+}++/** The calendar days an event covers in the schedule's timezone. */+export function getEventDateSpan(+ event: CalendarEvent,+ timezoneID: string,+): [PlainDate, PlainDate] {+ if (isDayEvent(event)) {+ return [event.start, event.end];+ }+ return [+ plainDateFromInstant(event.start, timezoneID),+ plainDateFromInstant(Math.max(event.end - 1, event.start), timezoneID),+ ];+}diff --git a/packages/lab/src/Schedule/shared.tsx b/packages/lab/src/Schedule/shared.tsxindex e90cad6720..84d3031ffe 100644--- a/packages/lab/src/Schedule/shared.tsx+++ b/packages/lab/src/Schedule/shared.tsx@@ -48,6 +48,12 @@ const DEFAULT_EVENT_CATEGORY: ScheduleCategory = {color: 'blue',};+// Month week rows are 128px. A chip level starts below the day number and the+// next one a chip's height plus a gap further down, so three levels fit in a+// row in every shipped theme.+const MONTH_CHIP_TOP = 30;+const MONTH_LEVEL_PITCH = 29;+export function ScheduleFrame({title,titleLabel,@@ -476,6 +482,25 @@ export function formatFullDate();}+/** A week row's dates, such as "May 10 – 16, 2026", for its row header. */+export function formatWeekRange(+ start: PlainDate,+ end: PlainDate,+ timezoneID: string,+ locale: Locale,+): string {+ return new Intl.DateTimeFormat(locale, {+ month: 'long',+ day: 'numeric',+ year: 'numeric',+ timeZone: timezoneID,+ calendar: 'gregory',+ }).formatRange(+ new Date(plainDateToInstant(start, timezoneID, 12)),+ new Date(plainDateToInstant(end, timezoneID, 12)),+ );+}+export function formatWeekday(date: PlainDate,timezoneID: string,@@ -698,10 +723,14 @@ export const styles = stylex.create({monthGrid: {overflowX: 'auto',},+ // The month surface isolates its paint order: chips rise above the cells+ // and a focused "+N more" above the chips, and nothing outside the surface+ // can see either value.monthGridSurface: {position: 'relative',width: '100%',minWidth: '784px',+ isolation: 'isolate',},monthCellGrid: {display: 'grid',@@ -720,6 +749,7 @@ export const styles = stylex.create({pointerEvents: 'none',},monthCell: {+ position: 'relative',display: 'flex',flexDirection: 'column',gap: spacingVars['--spacing-1'],@@ -733,6 +763,15 @@ export const styles = stylex.create({borderBlockEndColor: colorVars['--color-border'],backgroundColor: colorVars['--color-background-card'],},+ // A day cell takes focus only when its "+N more" goes away while its+ // popover is open. The shared ring sits inset, so the table's scroll edge+ // never clips it, and the cell stays under the chips it holds.+ monthCellFocus: {+ outlineOffset: {+ default: null,+ ':focus-visible': `calc(-1 * ${focusVars['--focus-outline-width']})`,+ },+ },monthCellLastColumn: {borderInlineEndWidth: 0,},@@ -777,10 +816,64 @@ export const styles = stylex.create({minWidth: 0,marginInlineStart: spacingVars['--spacing-0-5'],marginInlineEnd: `calc(${spacingVars['--spacing-0-5']} + ${borderVars['--border-width']})`,- marginBlockStart: `${30 + level * 29}px`,+ marginBlockStart: `${MONTH_CHIP_TOP + level * MONTH_LEVEL_PITCH}px`,pointerEvents: 'auto',zIndex: 1,}),+ // 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: {+ position: 'absolute',+ insetInlineStart: spacingVars['--spacing-0-5'],+ insetInlineEnd: `calc(${spacingVars['--spacing-0-5']} + ${borderVars['--border-width']})`,+ display: 'flex',+ alignItems: 'center',+ minWidth: 0,+ overflow: 'hidden',+ borderWidth: borderVars['--border-width'],+ borderStyle: 'solid',+ borderColor: 'transparent',+ borderRadius: radiusVars['--radius-inner'],+ paddingBlock: spacingVars['--spacing-0-5'],+ paddingInline: spacingVars['--spacing-1-5'],+ fontFamily: typographyVars['--font-family-body'],+ fontSize: typeScaleVars['--text-supporting-size'],+ lineHeight: typeScaleVars['--text-supporting-leading'],+ fontWeight: fontWeightVars['--font-weight-medium'],+ color: colorVars['--color-text-secondary'],+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ backgroundColor: {+ default: 'transparent',+ ':hover:where(:not(:disabled,[aria-disabled="true"]))': {+ default: null,+ '@media (hover: hover)': colorVars['--color-overlay-hover'],+ },+ },+ zIndex: {+ default: null,+ ':focus-visible': 2,+ },+ },+ monthMoreButtonPosition: (level: number) => ({+ insetBlockStart: `${MONTH_CHIP_TOP + level * MONTH_LEVEL_PITCH}px`,+ }),+ // The day popover lists rows that ellipsize their titles, so its content+ // has a cap for the titles to fit within.+ monthDayEvents: {+ display: 'flex',+ flexDirection: 'column',+ gap: spacingVars['--spacing-2'],+ maxInlineSize: '360px',+ },+ monthDayEventList: {+ display: 'flex',+ flexDirection: 'column',+ gap: spacingVars['--spacing-2'],+ margin: 0,+ padding: 0,+ listStyle: 'none',+ },eventPill: {...baseText,display: 'flex',diff --git a/packages/lab/src/Schedule/useScheduleViewPopover.ts b/packages/lab/src/Schedule/useScheduleViewPopover.tsnew file mode 100644index 0000000000..d96d4b9760--- /dev/null+++ b/packages/lab/src/Schedule/useScheduleViewPopover.ts@@ -0,0 +1,156 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file useScheduleViewPopover.ts+ * @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+ * @position Internal hook for Schedule views that own a popover (the month+ * view's day popover, component:Schedule FR17); not exported+ */++import {+ useCallback,+ useEffect,+ useRef,+ useState,+ type MouseEvent as ReactMouseEvent,+ type PointerEvent as ReactPointerEvent,+} from 'react';+import {usePopover, type UsePopoverReturn} from '@astryxdesign/core/Popover';++const TRIGGER_ATTRIBUTE = 'data-schedule-popover-trigger';++export interface ScheduleViewPopover {+ /** The view's one popover. Render it with `popover.render(content, …)`. */+ readonly popover: UsePopoverReturn;+ /** Key of the trigger whose popover is open, or null. */+ readonly openKey: string | null;+ /** Spread on an element that contains every trigger. */+ readonly containerProps: {+ onPointerDownCapture: (event: ReactPointerEvent<HTMLElement>) => void;+ onKeyDownCapture: () => void;+ };+ /**+ * Props of one trigger button. Calling it also marks the trigger as painted+ * this render; the popover closes when its trigger was not.+ */+ getTriggerProps: (key: string) => {+ 'aria-haspopup': 'dialog';+ 'aria-expanded': boolean;+ 'aria-controls': string;+ [TRIGGER_ATTRIBUTE]: string;+ onClick: (event: ReactMouseEvent<HTMLButtonElement>) => void;+ };+}++/**+ * 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`+ * of the open key, auto-focus, a hidden fallback close, Escape and light+ * dismiss, focus return, and the standard surface and padding. While nothing+ * is open the dialog is not shown, but it still carries a name, so the view+ * never mounts an unnamed dialog.+ */+export function useScheduleViewPopover(+ dialogLabelFor: (key: string | null) => string,+ onTriggerLost?: (key: string) => void,+): ScheduleViewPopover {+ const [openKey, setOpenKey] = useState<string | null>(null);+ const openKeyRef = useRef(openKey);+ openKeyRef.current = openKey;+ const popover = usePopover({+ dialogLabel: dialogLabelFor(openKey),+ // Popover's own defaults, spelled out where the hook's differ.+ padding: 3,+ surfaceTarget: 'popover',+ onHide: useCallback(() => {+ setOpenKey(null);+ }, []),+ });+ const popoverRef = useRef(popover);+ popoverRef.current = popover;++ // A pointer press on a trigger while the popover is open would close it by+ // the browser's light dismiss before the click arrives, and the layer then+ // absorbs a show() from that same press. So the press itself decides: a+ // press on another trigger closes the popover here, ahead of the browser,+ // and the click that follows opens the pressed trigger; a press on the open+ // trigger is remembered so its click ends closed, whichever of the two+ // closed it. A key press starts a new gesture and forgets the press.+ const openKeyAtPressRef = useRef<string | null>(null);+ const onPointerDownCapture = (event: ReactPointerEvent<HTMLElement>) => {+ const target = event.target as Element | null;+ const pressedKey =+ target+ ?.closest(`[${TRIGGER_ATTRIBUTE}]`)+ ?.getAttribute(TRIGGER_ATTRIBUTE) ?? null;+ const currentKey = openKeyRef.current;+ openKeyAtPressRef.current = pressedKey == null ? null : currentKey;+ if (+ pressedKey != null &&+ currentKey != null &&+ pressedKey !== currentKey &&+ popover.isOpen+ ) {+ popover.hide();+ }+ };+ const onKeyDownCapture = () => {+ openKeyAtPressRef.current = null;+ };+ const toggle = (key: string, button: HTMLButtonElement) => {+ const openAtPress = openKeyAtPressRef.current;+ openKeyAtPressRef.current = null;+ if (openAtPress === key || (openKeyRef.current === key && popover.isOpen)) {+ if (popover.isOpen) {+ popover.hide();+ }+ return;+ }+ setOpenKey(key);+ popover.triggerRef(button);+ popover.show();+ };++ // 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+ // decides where it lands.+ const paintedKeys = new Set<string>();+ useEffect(() => {+ if (openKey != null && !paintedKeys.has(openKey)) {+ const content = popoverRef.current.contentRef.current;+ const active = document.activeElement;+ const hadFocus =+ active == null ||+ active === document.body ||+ (content?.contains(active) ?? false);+ popoverRef.current.hide();+ setOpenKey(null);+ if (hadFocus) {+ onTriggerLost?.(openKey);+ }+ }+ });++ return {+ popover,+ openKey,+ containerProps: {onPointerDownCapture, onKeyDownCapture},+ getTriggerProps: key => {+ paintedKeys.add(key);+ return {+ 'aria-haspopup': 'dialog',+ 'aria-expanded': popover.isOpen && openKey === key,+ 'aria-controls': popover.id,+ [TRIGGER_ATTRIBUTE]: key,+ onClick: event => toggle(key, event.currentTarget),+ };+ },+ };+}