Skip to content

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

TypeScript

fix(lab): give the Schedule time grid one scroll owner with pinned header, all-day row, and gutter (#6926)

Cindy Zhang77a62df7eae6
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 378d0655e8..b4454d609e 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1185,6 +1185,36 @@ jobs:
retention-days: 30
if-no-files-found: ignore
+ # The Schedule time grid owns scroll geometry — pinned header and gutter
+ # alignment under classic scrollbars, inline scroll ownership, keyboard
+ # reach and its focus ring — none of which exists in jsdom. Every
+ # contract file under the Schedule tests directory runs here, in the
+ # same real Chromium artifact, whenever the PR scope names Schedule.
+ - name: Run Schedule time-grid contract
+ if: github.event_name == 'pull_request'
+ env:
+ ASTRYX_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
+ run: |
+ COMPONENTS=$(node .github/scripts/a11y-pr-scope.mjs analysis.json)
+ case ",${COMPONENTS}," in
+ *,lab/Schedule,*)
+ pnpm exec playwright test \
+ packages/lab/src/Schedule/__tests__/ \
+ --project chromium \
+ --output schedule-time-grid-output
+ ;;
+ *) echo "Schedule not in PR scope; skipping time-grid evidence." ;;
+ esac
+
+ - name: Upload Schedule time-grid evidence
+ if: always() && github.event_name == 'pull_request'
+ uses: actions/upload-artifact@v7
+ with:
+ name: schedule-time-grid-evidence-${{ needs.build-storybook.outputs.short_hash }}
+ path: test-results/schedule-time-grid-evidence/
+ retention-days: 30
+ if-no-files-found: ignore
+
# ChatMessageBubble is nested under the shared Chat source directory, so
# the generic stable-visual owner cannot select its dedicated fixture.
# Run the component's bounded evidence matrix only when the PR scope names
diff --git a/apps/storybook/stories/Schedule.stories.tsx b/apps/storybook/stories/Schedule.stories.tsx
index 0fddd28ca5..e840579e73 100644
--- a/apps/storybook/stories/Schedule.stories.tsx
+++ b/apps/storybook/stories/Schedule.stories.tsx
@@ -343,6 +343,210 @@ export const AsyncLoader: Story = {
},
};
+// A fixed week in UTC, so the overlap layout is identical on every machine and
+// in CI. Each day exercises one overlap shape of the time grid.
+const FIXTURE_TIMEZONE = 'UTC';
+const FIXTURE_DATE = Date.UTC(2026, 4, 13, 12) as Instant;
+
+function fixtureEvent({
+ id,
+ title,
+ category,
+ day,
+ start,
+ end,
+}: {
+ id: string;
+ title: string;
+ category: string;
+ day: number;
+ start: [hour: number, minute?: number];
+ end: [hour: number, minute?: number];
+}): CalendarEvent {
+ const iso = ([hour, minute = 0]: [number, number?]) =>
+ `2026-05-${String(day).padStart(2, '0')}T${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:00.000Z`;
+ return createEventFromISO({
+ id,
+ title,
+ category,
+ start: iso(start),
+ end: iso(end),
+ });
+}
+
+const overlappingEvents: CalendarEvent[] = [
+ // Monday: an exact tie — same title, same minutes, different ids.
+ fixtureEvent({
+ id: 'tie-a',
+ title: 'Pair review',
+ category: 'Design',
+ day: 11,
+ start: [9],
+ end: [10],
+ }),
+ fixtureEvent({
+ id: 'tie-b',
+ title: 'Pair review',
+ category: 'Design',
+ day: 11,
+ start: [9],
+ end: [10],
+ }),
+ // Tuesday: three simultaneous events.
+ fixtureEvent({
+ id: 'trio-1',
+ title: 'Interview loop 1',
+ category: 'Company',
+ day: 12,
+ start: [13],
+ end: [14],
+ }),
+ fixtureEvent({
+ id: 'trio-2',
+ title: 'Interview loop 2',
+ category: 'Launch',
+ day: 12,
+ start: [13],
+ end: [14],
+ }),
+ fixtureEvent({
+ id: 'trio-3',
+ title: 'Interview loop 3',
+ category: 'Focus',
+ day: 12,
+ start: [13],
+ end: [14],
+ }),
+ // Wednesday: five simultaneous events.
+ fixtureEvent({
+ id: 'quint-1',
+ title: 'Office hours A',
+ category: 'Company',
+ day: 13,
+ start: [10],
+ end: [11],
+ }),
+ fixtureEvent({
+ id: 'quint-2',
+ title: 'Office hours B',
+ category: 'Design',
+ day: 13,
+ start: [10],
+ end: [11],
+ }),
+ fixtureEvent({
+ id: 'quint-3',
+ title: 'Office hours C',
+ category: 'Launch',
+ day: 13,
+ start: [10],
+ end: [11],
+ }),
+ fixtureEvent({
+ id: 'quint-4',
+ title: 'Office hours D',
+ category: 'Focus',
+ day: 13,
+ start: [10],
+ end: [11],
+ }),
+ fixtureEvent({
+ id: 'quint-5',
+ title: 'Office hours E',
+ category: 'Retro',
+ day: 13,
+ start: [10],
+ end: [11],
+ }),
+ // Thursday: a chain — the first and last do not overlap each other.
+ fixtureEvent({
+ id: 'chain-1',
+ title: 'Standup',
+ category: 'Company',
+ day: 14,
+ start: [9],
+ end: [10],
+ }),
+ fixtureEvent({
+ id: 'chain-2',
+ title: 'Design sync',
+ category: 'Design',
+ day: 14,
+ start: [9, 30],
+ end: [10, 30],
+ }),
+ fixtureEvent({
+ id: 'chain-3',
+ title: 'Retro',
+ category: 'Retro',
+ day: 14,
+ start: [10],
+ end: [11],
+ }),
+ // Friday: containment plus the shortest block the grid draws.
+ fixtureEvent({
+ id: 'contain-long',
+ title: 'Workshop',
+ category: 'Launch',
+ day: 15,
+ start: [9],
+ end: [12],
+ }),
+ fixtureEvent({
+ id: 'contain-short',
+ title: 'Coffee chat',
+ category: 'Focus',
+ day: 15,
+ start: [10],
+ end: [10, 30],
+ }),
+ fixtureEvent({
+ id: 'quarter',
+ title: 'Quick check-in',
+ category: 'Company',
+ day: 15,
+ start: [14],
+ end: [14, 15],
+ }),
+ // All-day spans that overlap each other.
+ createEventFromISO({
+ id: 'offsite',
+ title: 'Offsite',
+ category: 'Company',
+ start: '2026-05-11',
+ end: '2026-05-12',
+ }),
+ createEventFromISO({
+ id: 'hack-week',
+ title: 'Hack week',
+ category: 'Launch',
+ start: '2026-05-12',
+ end: '2026-05-13',
+ }),
+];
+
+export const OverlappingEvents: Story = {
+ render: () => {
+ const [date, setDate] = useState<Instant>(FIXTURE_DATE);
+ const view = useMemo(
+ () => createScheduleWeeklyView({minHour: 8, maxHour: 18}),
+ [],
+ );
+
+ return (
+ <Schedule
+ view={view}
+ events={overlappingEvents}
+ 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/DayView.tsx b/packages/lab/src/Schedule/DayView.tsx
index 69ec5c9ef4..add4a908e8 100644
--- a/packages/lab/src/Schedule/DayView.tsx
+++ b/packages/lab/src/Schedule/DayView.tsx
@@ -58,6 +58,7 @@ function ScheduleDayView({
minHour={minHour}
maxHour={maxHour}
hourHeight={hourHeight}
+ label={titleLabel}
/>
</ScheduleFrame>
);
diff --git a/packages/lab/src/Schedule/Schedule.doc.mjs b/packages/lab/src/Schedule/Schedule.doc.mjs
index b8f6b06302..318fdb7977 100644
--- a/packages/lab/src/Schedule/Schedule.doc.mjs
+++ b/packages/lab/src/Schedule/Schedule.doc.mjs
@@ -77,7 +77,7 @@ export const docs = {
name: 'View body',
required: true,
description:
- 'Whatever the view renders: a month grid, a day/week time grid with an hour gutter and an all-day row, or a list grouped under day headings. Grid views expose ARIA grid, columnheader, and gridcell roles and are marked aria-readonly.',
+ 'Whatever the view renders: a month grid, a day/week time grid with an hour gutter and an all-day row, or a list grouped under day headings. Grid views expose ARIA grid, columnheader, and gridcell roles and are marked aria-readonly. The day/week time grid scrolls inside one keyboard-reachable region named after the range; its day header, all-day row, and hour gutter stay pinned while the columns scroll.',
},
{
name: 'Event',
diff --git a/packages/lab/src/Schedule/Schedule.test.tsx b/packages/lab/src/Schedule/Schedule.test.tsx
index f556e73560..91a6de35f2 100644
--- a/packages/lab/src/Schedule/Schedule.test.tsx
+++ b/packages/lab/src/Schedule/Schedule.test.tsx
@@ -401,6 +401,69 @@ describe('Schedule', () => {
).toBeInTheDocument();
});
+ it('renders the time grid inside one named scroll viewport', () => {
+ render(
+ <Schedule
+ view={createScheduleWeeklyView({minHour: 8, maxHour: 17})}
+ events={events}
+ categories={categories}
+ date={Date.UTC(2026, 4, 13)}
+ focusDate={Date.UTC(2026, 4, 13)}
+ timezoneID="UTC"
+ />,
+ );
+
+ const viewport = screen.getByRole('region', {name: 'May 2026 time grid'});
+ const content = viewport.querySelector('[data-scroll-content]');
+ expect(content).not.toBeNull();
+ // Header cells, the all-day row, the hour gutter, and the day columns are
+ // items of the same grid, so no part of the painted header lives outside
+ // the viewport's own scrolling content.
+ const headerCells = viewport.querySelectorAll('h3');
+ expect(headerCells).toHaveLength(7);
+ headerCells.forEach(cell => {
+ expect(cell.parentElement?.parentElement).toBe(content);
+ });
+ expect(
+ screen.getByText('Visible sync').closest('[data-scroll-content]'),
+ ).toBe(content);
+ // The hidden read-only grid repeats the hour as a row header; the painted
+ // gutter label is the one inside the viewport.
+ const gutterLabel = screen
+ .getAllByText('9 AM')
+ .find(label => viewport.contains(label));
+ expect(gutterLabel?.closest('[data-scroll-content]')).toBe(content);
+ });
+
+ it('keeps every painted time-grid part hidden from assistive technology', () => {
+ render(
+ <Schedule
+ view={createScheduleWeeklyView({minHour: 8, maxHour: 10})}
+ events={events}
+ categories={categories}
+ date={Date.UTC(2026, 4, 13)}
+ timezoneID="UTC"
+ />,
+ );
+
+ const viewport = screen.getByRole('region', {name: 'May 2026 time grid'});
+ const content = viewport.querySelector('[data-scroll-content]');
+ expect(content).not.toBeNull();
+ const parts = Array.from(content?.children ?? []);
+ // corner + 7 header cells + all-day label + all-day row + gutter + 7 columns
+ expect(parts).toHaveLength(18);
+ parts.forEach(part => {
+ expect(part).toHaveAttribute('aria-hidden', 'true');
+ });
+ // The read-only grid stays the accessible representation of the events.
+ expect(
+ screen.getByRole('gridcell', {
+ name: 'Wednesday, May 13, 2026 all day. Design review, Design, all day',
+ }),
+ ).toBeInTheDocument();
+ expect(screen.queryByRole('button', {name: /Visible sync/})).toBeNull();
+ });
+
it('labels list day headings with the full date', () => {
render(
<Schedule
diff --git a/packages/lab/src/Schedule/TimeGridView.tsx b/packages/lab/src/Schedule/TimeGridView.tsx
index b46ce8988a..16ad9ef87b 100644
--- a/packages/lab/src/Schedule/TimeGridView.tsx
+++ b/packages/lab/src/Schedule/TimeGridView.tsx
@@ -4,8 +4,9 @@
/**
* @file TimeGridView.tsx
- * @input Schedule context, visible days, timezone, and hour bounds
- * @output Shared weekly/day time-grid layout
+ * @input Schedule context, visible days, timezone, hour bounds, and the range label
+ * @output Shared weekly/day time-grid layout: one scroll viewport whose sticky
+ * day header, all-day row, and hour gutter share the day columns' grid tracks
* @position Internal view primitive shared by WeeklyView and DayView
*/
@@ -20,9 +21,11 @@ import {
plainDateToISO,
type PlainDate,
} from '@astryxdesign/core/utils';
+import {useScrollableArea} from '@astryxdesign/core/hooks';
import {Heading, Text} from '@astryxdesign/core/Text';
import {useScheduleContext} from './context';
import {eventOccursOnDate, isDayEvent} from './dateMath';
+import {timeGridViewportScope} from './schedule.stylex';
import {
clamp,
EventPill,
@@ -57,6 +60,7 @@ export function TimeGridView({
minHour,
maxHour,
hourHeight,
+ label,
}: {
days: PlainDate[];
events: ReadonlyArray<CalendarEvent>;
@@ -65,6 +69,8 @@ export function TimeGridView({
minHour: number;
maxHour: number;
hourHeight: number;
+ /** Accessible name of the rendered range; names the scroll viewport. */
+ label: string;
}) {
const {categories, headingLevel, locale} = useScheduleContext();
const normalizedMinHour = Math.max(0, Math.min(23, Math.floor(minHour)));
@@ -93,6 +99,25 @@ export function TimeGridView({
locale,
);
+ const {getViewportProps, getContentProps} = useScrollableArea({
+ axis: 'both',
+ keyboardAccess: {
+ owner: 'viewport',
+ label: `${label} time grid`,
+ role: 'region',
+ },
+ });
+ const viewportProps = getViewportProps<HTMLDivElement>(
+ stylex.props(styles.timeGridViewport, timeGridViewportScope),
+ );
+ const contentProps = getContentProps<HTMLDivElement>(
+ stylex.props(styles.timeGridContent(days.length)),
+ );
+
+ // Everything painted below is decoration for sighted users; the hidden grid
+ // above is what assistive technology reads. Each painted part is hidden on
+ // its own, rather than the whole viewport, so the viewport itself can stay
+ // a reachable, named keyboard scroll owner.
return (
<>
<TimeGridAccessibilityGrid
@@ -106,58 +131,56 @@ export function TimeGridView({
timezoneID={timezoneID}
timezoneLabel={timezoneLabel}
/>
- <div aria-hidden {...stylex.props(styles.timeGrid)}>
- <div {...stylex.props(styles.timeGridCorner)} />
- <div {...stylex.props(styles.timeGridHeader)}>
- {days.map((day, index) => (
- <div
- key={plainDateToISO(day)}
- {...stylex.props(
- styles.timeGridHeaderCell,
- index === days.length - 1 && styles.timeGridHeaderCellLast,
- )}>
- <Heading
- level={headingLevel}
- color="secondary"
- display="block"
- xstyle={styles.timeGridHeaderHeading}>
- <span {...stylex.props(styles.timeGridHeaderHeadingContent)}>
- {formatWeekday(day, timezoneID, 'short', locale)}
- <span
- {...stylex.props(
- styles.timeGridDayNumber,
- plainDateIsEqual(day, focusDate) &&
- styles.timeGridCurrentDayPill,
- )}>
- {formatDayNumber(day, timezoneID, locale)}
+ <div {...stylex.props(styles.timeGridFrame)}>
+ <div {...viewportProps}>
+ <div {...contentProps}>
+ <div aria-hidden {...stylex.props(styles.timeGridCorner)} />
+ {days.map((day, index) => (
+ <div
+ key={plainDateToISO(day)}
+ aria-hidden
+ {...stylex.props(
+ styles.timeGridHeaderCell,
+ styles.dayColumnPlacement(index),
+ index === days.length - 1 && styles.timeGridHeaderCellLast,
+ )}>
+ <Heading
+ level={headingLevel}
+ color="secondary"
+ display="block"
+ xstyle={styles.timeGridHeaderHeading}>
+ <span {...stylex.props(styles.timeGridHeaderHeadingContent)}>
+ {formatWeekday(day, timezoneID, 'short', locale)}
+ <span
+ {...stylex.props(
+ styles.timeGridDayNumber,
+ plainDateIsEqual(day, focusDate) &&
+ styles.timeGridCurrentDayPill,
+ )}>
+ {formatDayNumber(day, timezoneID, locale)}
+ </span>
</span>
- </span>
- </Heading>
+ </Heading>
+ </div>
+ ))}
+ <div aria-hidden {...stylex.props(styles.allDayLabel)}>
+ <Text type="supporting" color="secondary" weight="bold">
+ {timezoneLabel}
+ </Text>
</div>
- ))}
- </div>
- <div {...stylex.props(styles.allDayLabel)}>
- <Text type="supporting" color="secondary" weight="bold">
- {timezoneLabel}
- </Text>
- </div>
- <div {...stylex.props(styles.allDayRow)}>
- <div
- {...stylex.props(
- styles.allDayRowSurface(days.length, allDayLevelCount),
- )}>
- <div {...stylex.props(styles.allDayCellGrid(days.length))}>
+ <div
+ aria-hidden
+ {...stylex.props(styles.allDayRow(allDayLevelCount))}>
{days.map((day, index) => (
<div
key={plainDateToISO(day)}
{...stylex.props(
styles.allDayCell,
+ styles.allDaySubgridPlacement(index),
index === days.length - 1 && styles.allDayCellLast,
)}
/>
))}
- </div>
- <div {...stylex.props(styles.allDayEventOverlay(days.length))}>
{allDaySegments.map(segment => (
<div
key={`${segment.event.id}:${segment.columnStart}`}
@@ -179,22 +202,18 @@ export function TimeGridView({
</div>
))}
</div>
- </div>
- </div>
- <div {...stylex.props(styles.timeGridBody)}>
- <div {...stylex.props(styles.timeLabels)}>
- {hours.slice(1).map((hour, index) => (
- <div
- key={hour}
- {...stylex.props(
- styles.timeLabel,
- styles.timeLabelPosition(index + 1, hourHeight),
- )}>
- {formatHour(hour, locale)}
- </div>
- ))}
- </div>
- <div {...stylex.props(styles.timeColumns)}>
+ <div aria-hidden {...stylex.props(styles.timeLabels)}>
+ {hours.slice(1).map((hour, index) => (
+ <div
+ key={hour}
+ {...stylex.props(
+ styles.timeLabel,
+ styles.timeLabelPosition(index + 1, hourHeight),
+ )}>
+ {formatHour(hour, locale)}
+ </div>
+ ))}
+ </div>
{days.map((day, index) => {
const currentTimeTop = getCurrentTimeTop({
currentTime,
@@ -206,17 +225,19 @@ export function TimeGridView({
return (
<div
key={plainDateToISO(day)}
+ aria-hidden
{...stylex.props(
styles.timeColumn,
+ styles.dayColumnPlacement(index),
styles.timeColumnRows(hourHeight),
index === days.length - 1 && styles.timeColumnLast,
)}>
- {hours.map((hour, index) => (
+ {hours.map((hour, hourIndex) => (
<div
key={hour}
{...stylex.props(
styles.hourSlot,
- index === hours.length - 1 && styles.hourSlotLast,
+ hourIndex === hours.length - 1 && styles.hourSlotLast,
)}
/>
))}
@@ -269,7 +290,6 @@ export function TimeGridView({
{plainDateIsEqual(day, currentDate) &&
currentTimeTop != null && (
<div
- aria-hidden
{...stylex.props(
styles.currentTimeLine(currentTimeTop),
)}
@@ -280,6 +300,7 @@ export function TimeGridView({
})}
</div>
</div>
+ <div aria-hidden {...stylex.props(styles.timeGridFocusRing)} />
</div>
</>
);
diff --git a/packages/lab/src/Schedule/WeeklyView.tsx b/packages/lab/src/Schedule/WeeklyView.tsx
index 54acf8de17..091893d8d8 100644
--- a/packages/lab/src/Schedule/WeeklyView.tsx
+++ b/packages/lab/src/Schedule/WeeklyView.tsx
@@ -69,6 +69,7 @@ function ScheduleWeeklyView({
minHour={minHour}
maxHour={maxHour}
hourHeight={hourHeight}
+ label={titleLabel}
/>
</ScheduleFrame>
);
diff --git a/packages/lab/src/Schedule/__tests__/ScheduleTimeGridGeometry.a11y.chromium.spec.ts b/packages/lab/src/Schedule/__tests__/ScheduleTimeGridGeometry.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..2a68c7b387
--- /dev/null
+++ b/packages/lab/src/Schedule/__tests__/ScheduleTimeGridGeometry.a11y.chromium.spec.ts
@@ -0,0 +1,304 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ScheduleTimeGridGeometry.a11y.chromium.spec.ts
+ * @input The built Lab/Schedule week stories in real Chromium, with the classic
+ * space-taking scrollbars Playwright's headless default hides
+ * @output Receipted evidence that the time grid has one scroll owner whose
+ * header, gutter, and columns stay aligned, and that a keyboard reaches it
+ * @position Browser binding for `component:Schedule` FR1–FR3 and AR1. jsdom
+ * lays out nothing, so scrollbar width, sticky alignment, and inline scroll
+ * ownership are checkable only here.
+ */
+
+import {expect, test} from '@playwright/test';
+import pixelmatch from 'pixelmatch';
+// @ts-expect-error -- pngjs ships no declarations; runtime support is pinned.
+import {PNG} from 'pngjs';
+import {
+ columnDeltas,
+ finishEvidence,
+ NARROW,
+ openStory,
+ readTimeGrid,
+ record,
+ ringEdgeCoverage,
+ setScrollLeft,
+ setScrollTop,
+ startEvidence,
+ WEEKLY,
+ WEEKLY_FIXED_HEIGHT,
+ WIDE,
+ type Evidence,
+} from './timeGridProbe';
+
+// Linux Chromium paints classic 15px scrollbars once Playwright's
+// `--hide-scrollbars` is dropped: the Windows / "always show scroll bars"
+// case this geometry contract exists for.
+test.use({launchOptions: {ignoreDefaultArgs: ['--hide-scrollbars']}});
+
+let evidence: Evidence;
+test.beforeAll(async () => {
+ evidence = await startEvidence();
+});
+test.afterAll(async () => {
+ await finishEvidence(evidence, 'geometry');
+});
+
+for (const direction of ['ltr', 'rtl'] as const) {
+ test(`header and body columns share one geometry with classic scrollbars (${direction})`, async ({
+ page,
+ }) => {
+ await openStory(
+ evidence,
+ page,
+ WEEKLY_FIXED_HEIGHT,
+ WIDE,
+ direction === 'rtl' ? 'direction:rtl' : undefined,
+ );
+ const reading = await readTimeGrid(page);
+ const deltas = columnDeltas(reading);
+ await record(
+ evidence,
+ page,
+ `geometry-classic-scrollbar-${direction}`,
+ WEEKLY_FIXED_HEIGHT,
+ direction,
+ {
+ scrollbarWidth: reading.scroller?.verticalScrollbarWidth,
+ horizontalScrollers: reading.horizontalScrollerCount,
+ deltas,
+ },
+ );
+
+ expect(
+ reading.scroller,
+ 'the time grid has a block-axis scroll owner',
+ ).not.toBeNull();
+ expect(reading.headerCells).toHaveLength(7);
+ expect(reading.bodyColumns).toHaveLength(7);
+ // The scrollbar must be a real, space-taking one for this evidence to
+ // mean anything; the launch option above is what provides it.
+ expect(
+ reading.scroller?.verticalScrollbarWidth ?? 0,
+ ).toBeGreaterThanOrEqual(8);
+ for (const delta of deltas) {
+ expect(
+ delta.deltaLeft,
+ `column ${delta.index} inline-start edge`,
+ ).toBeLessThanOrEqual(1);
+ expect(
+ delta.deltaRight,
+ `column ${delta.index} inline-end edge`,
+ ).toBeLessThanOrEqual(1);
+ }
+ expect(reading.pageOverflows, 'no whole-page overflow').toBe(false);
+ });
+}
+
+test('a narrow viewport scrolls header, gutter, and columns as one owner', async ({
+ page,
+}) => {
+ await openStory(evidence, page, WEEKLY, NARROW);
+ const before = await readTimeGrid(page);
+ await setScrollLeft(page, 160);
+ await page.waitForTimeout(50);
+ const after = await readTimeGrid(page);
+ const deltas = columnDeltas(after);
+ const labelDrift = after.hourLabels.map((label, index) => ({
+ text: label.text,
+ drift: Math.abs(
+ label.left - (before.hourLabels[index]?.left ?? Number.NaN),
+ ),
+ }));
+ await record(
+ evidence,
+ page,
+ 'geometry-narrow-horizontal-scroll',
+ WEEKLY,
+ after.direction,
+ {
+ horizontalScrollersBefore: before.horizontalScrollerCount,
+ scrollLeftApplied: after.scroller?.scrollLeft,
+ deltas,
+ labelDrift,
+ pageOverflows: after.pageOverflows,
+ },
+ );
+
+ expect(
+ after.scroller?.scrollLeft ?? 0,
+ 'the owner actually scrolled',
+ ).toBeGreaterThan(100);
+ expect(
+ before.horizontalScrollerCount,
+ 'exactly one inline-axis scroll owner',
+ ).toBe(1);
+ for (const delta of deltas) {
+ expect(
+ delta.deltaLeft,
+ `column ${delta.index} inline-start edge after scroll`,
+ ).toBeLessThanOrEqual(1);
+ expect(
+ delta.deltaRight,
+ `column ${delta.index} inline-end edge after scroll`,
+ ).toBeLessThanOrEqual(1);
+ }
+ expect(labelDrift.length).toBeGreaterThan(0);
+ for (const label of labelDrift) {
+ expect(
+ label.drift,
+ `hour label ${label.text} stays pinned`,
+ ).toBeLessThanOrEqual(1);
+ }
+ expect(after.pageOverflows, 'no whole-page overflow').toBe(false);
+});
+
+function decode(buffer: Buffer): {
+ width: number;
+ height: number;
+ data: Buffer;
+} {
+ return PNG.sync.read(buffer) as {width: number; height: number; data: Buffer};
+}
+
+test('Tab reaches the time grid after the header controls', async ({page}) => {
+ await openStory(evidence, page, WEEKLY, WIDE);
+ const rest = await readTimeGrid(page);
+ const clip = rest.scroller?.box;
+ const restFrame =
+ clip == null
+ ? null
+ : await page.screenshot({
+ clip: {
+ x: clip.left,
+ y: clip.top,
+ width: clip.width,
+ height: clip.height,
+ },
+ });
+ const sequence: Array<{
+ tag: string;
+ role: string | null;
+ label: string | null;
+ text: string;
+ insideTimeGrid: boolean;
+ }> = [];
+ for (let press = 0; press < 12; press += 1) {
+ await page.keyboard.press('Tab');
+ const focused = await page.evaluate(() => {
+ const element = document.activeElement as HTMLElement | null;
+ if (element == null || element === document.body) {
+ return {
+ tag: 'body',
+ role: null,
+ label: null,
+ text: '',
+ insideTimeGrid: false,
+ };
+ }
+ const root = document.querySelector('.astryx-schedule');
+ const headerRow =
+ root?.querySelector('h2')?.closest('div')?.parentElement ?? null;
+ const insideTimeGrid =
+ root != null &&
+ root.contains(element) &&
+ !(headerRow != null && headerRow.contains(element));
+ return {
+ tag: element.tagName.toLowerCase(),
+ role: element.getAttribute('role'),
+ label: element.getAttribute('aria-label'),
+ text: (element.textContent ?? '').trim().slice(0, 40),
+ insideTimeGrid,
+ };
+ });
+ sequence.push(focused);
+ if (focused.insideTimeGrid || focused.tag === 'body') {
+ break;
+ }
+ }
+ // The ring must be visible pixels on every edge, not just a computed
+ // outline: the frame clips its own border box, and the viewport's own
+ // outline would sit under its pinned header and gutter, so the ring is an
+ // overlay laid over the focused viewport.
+ const ring = await page.evaluate(() => {
+ const element = document.activeElement as HTMLElement | null;
+ const overlay = element?.nextElementSibling;
+ if (element == null || overlay == null) {
+ return null;
+ }
+ const style = getComputedStyle(overlay);
+ return {
+ viewportOutline: getComputedStyle(element).outlineStyle,
+ outlineStyle: style.outlineStyle,
+ outlineWidth: Number.parseFloat(style.outlineWidth),
+ outlineOffset: Number.parseFloat(style.outlineOffset),
+ };
+ });
+ const focusedFrame =
+ clip == null
+ ? null
+ : await page.screenshot({
+ clip: {
+ x: clip.left,
+ y: clip.top,
+ width: clip.width,
+ height: clip.height,
+ },
+ });
+ let ringPixels = 0;
+ let edges = {top: 0, bottom: 0, left: 0, right: 0};
+ if (restFrame != null && focusedFrame != null) {
+ const before = decode(restFrame);
+ const after = decode(focusedFrame);
+ ringPixels = pixelmatch(
+ before.data,
+ after.data,
+ undefined,
+ before.width,
+ before.height,
+ {threshold: 0.1},
+ );
+ edges = ringEdgeCoverage(before, after);
+ }
+ await record(evidence, page, 'keyboard-reach', WEEKLY, 'ltr', {
+ sequence,
+ ring,
+ ringPixels,
+ edges,
+ });
+ const reached = sequence.find(stop => stop.insideTimeGrid);
+ expect(
+ reached,
+ 'a keyboard user can reach the time grid (its scroll owner or an event)',
+ ).toBeDefined();
+ // The scroll owner is the named region AST-025 prescribes, and Arrow keys
+ // move it.
+ expect(reached?.role).toBe('region');
+ expect(reached?.label).toMatch(/time grid$/);
+ expect(ring?.outlineStyle).not.toBe('none');
+ expect(ring?.outlineWidth ?? 0).toBeGreaterThan(0);
+ expect(
+ ring?.outlineOffset ?? 1,
+ 'the ring sits inside the clipped frame',
+ ).toBeLessThanOrEqual(0);
+ // A complete ring: at least a one-pixel perimeter of changed pixels, and
+ // every edge — including the ones over the pinned header and gutter —
+ // mostly changed.
+ expect(ringPixels).toBeGreaterThan(
+ 2 * ((clip?.width ?? 0) + (clip?.height ?? 0)),
+ );
+ for (const [edge, coverage] of Object.entries(edges)) {
+ expect(
+ coverage,
+ `${edge} edge of the focus ring is painted`,
+ ).toBeGreaterThan(0.9);
+ }
+ // Start from the top so the key has somewhere to go whatever offset the
+ // grid opened at.
+ await setScrollTop(page, 0);
+ await page.keyboard.press('ArrowDown');
+ await page.waitForTimeout(150);
+ const after = await readTimeGrid(page);
+ expect(after.scroller?.scrollTop ?? 0).toBeGreaterThan(0);
+});
diff --git a/packages/lab/src/Schedule/__tests__/timeGridProbe.ts b/packages/lab/src/Schedule/__tests__/timeGridProbe.ts
new file mode 100644
index 0000000000..ae175c7f00
--- /dev/null
+++ b/packages/lab/src/Schedule/__tests__/timeGridProbe.ts
@@ -0,0 +1,503 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file timeGridProbe.ts
+ * @input A Playwright page showing a built Lab/Schedule week or day story
+ * @output Geometry, block, and focus readings of the painted time grid, plus a
+ * receipt writer that pairs each reading with a screenshot
+ * @position Shared by the Schedule time-grid browser contracts. Every lookup
+ * works from text, computed style, and geometry rather than class names, so
+ * the same readings describe a build that predates a contract and one that
+ * implements it.
+ */
+
+import {execFileSync} from 'node:child_process';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import type {Page} from '@playwright/test';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+export const OUTPUT = path.resolve('test-results/schedule-time-grid-evidence');
+export const WEEKLY = 'lab-schedule--weekly';
+export const WEEKLY_FIXED_HEIGHT = 'lab-schedule--weekly-fixed-height';
+export const DAY = 'lab-schedule--day';
+export const OVERLAPPING = 'lab-schedule--overlapping-events';
+export const WIDE = {width: 1280, height: 900};
+export const NARROW = {width: 760, height: 700};
+// One hour of the week/day stories; the contract's lead context is one hour.
+export const HOUR_HEIGHT = 100;
+
+export interface Box {
+ readonly left: number;
+ readonly right: number;
+ readonly top: number;
+ readonly bottom: number;
+ readonly width: number;
+ readonly height: number;
+}
+
+export interface TimeGridReading {
+ readonly direction: 'ltr' | 'rtl';
+ readonly scroller: {
+ readonly box: Box;
+ readonly scrollTop: number;
+ readonly scrollLeft: number;
+ readonly scrollHeight: number;
+ readonly clientHeight: number;
+ readonly scrollWidth: number;
+ readonly clientWidth: number;
+ readonly verticalScrollbarWidth: number;
+ } | null;
+ readonly headerCells: ReadonlyArray<Box>;
+ readonly bodyColumns: ReadonlyArray<Box>;
+ readonly hourLabels: ReadonlyArray<{
+ readonly text: string;
+ readonly left: number;
+ }>;
+ readonly nowLine: {readonly topInContent: number} | null;
+ readonly firstColumnTopInContent: number | null;
+ readonly horizontalScrollerCount: number;
+ readonly pageOverflows: boolean;
+}
+
+export interface Receipt {
+ readonly test: string;
+ readonly story: string;
+ readonly viewport: {readonly width: number; readonly height: number};
+ readonly direction: 'ltr' | 'rtl';
+ readonly browser: string;
+ readonly checkout: string;
+ readonly head: string;
+ readonly measured: unknown;
+ readonly screenshot: string;
+}
+
+export interface Evidence {
+ readonly storybook: StaticServer;
+ readonly checkoutSha: string;
+ readonly receipts: Receipt[];
+}
+
+/** Serves the built Storybook and prepares the evidence directory. */
+export async function startEvidence(): Promise<Evidence> {
+ const checkoutSha = execFileSync('git', ['rev-parse', 'HEAD'], {
+ encoding: 'utf8',
+ }).trim();
+ fs.mkdirSync(OUTPUT, {recursive: true});
+ const storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+ return {storybook, checkoutSha, receipts: []};
+}
+
+/** Writes the receipts of one contract file and stops the server. */
+export async function finishEvidence(
+ evidence: Evidence | undefined,
+ name: string,
+): Promise<void> {
+ if (evidence == null) {
+ return;
+ }
+ fs.writeFileSync(
+ path.join(OUTPUT, `receipts-${name}.json`),
+ `${JSON.stringify(evidence.receipts, null, 2)}\n`,
+ );
+ await evidence.storybook.close();
+}
+
+export function storyUrl(
+ evidence: Evidence,
+ id: string,
+ globals?: string,
+): string {
+ const query = globals == null ? '' : `&globals=${globals}`;
+ return `${evidence.storybook.origin}/iframe.html?id=${id}&viewMode=story${query}`;
+}
+
+export async function openStory(
+ evidence: Evidence,
+ page: Page,
+ id: string,
+ viewport: {width: number; height: number},
+ globals?: string,
+): Promise<void> {
+ await page.setViewportSize(viewport);
+ await page.goto(storyUrl(evidence, id, globals), {waitUntil: 'load'});
+ await page.locator('.astryx-schedule').waitFor();
+ // Fonts and the first layout pass settle before anything is measured.
+ await page.evaluate(() => document.fonts.ready);
+ await page.waitForTimeout(100);
+}
+
+/**
+ * Reads the painted time grid by what it is, not by how it is classed: the
+ * scroll owner is the first element whose block axis overflows, header cells
+ * hold the day headings, body columns are the stacks of empty hour slots, and
+ * the now-line is the two-pixel rule.
+ */
+export function readTimeGrid(page: Page): Promise<TimeGridReading> {
+ return page.evaluate((hourHeight): TimeGridReading => {
+ const toBox = (rect: DOMRect) => ({
+ left: rect.left,
+ right: rect.right,
+ top: rect.top,
+ bottom: rect.bottom,
+ width: rect.width,
+ height: rect.height,
+ });
+ const root = document.querySelector<HTMLElement>('.astryx-schedule');
+ if (root == null) {
+ throw new Error('No Schedule root in the story');
+ }
+ const direction: 'ltr' | 'rtl' =
+ getComputedStyle(root).direction === 'rtl' ? 'rtl' : 'ltr';
+ const all = [...root.querySelectorAll<HTMLElement>('*')];
+ const scrollsOn = (element: HTMLElement, axis: 'x' | 'y') => {
+ const style = getComputedStyle(element);
+ const overflow = axis === 'x' ? style.overflowX : style.overflowY;
+ const excess =
+ axis === 'x'
+ ? element.scrollWidth - element.clientWidth
+ : element.scrollHeight - element.clientHeight;
+ return (overflow === 'auto' || overflow === 'scroll') && excess > 1;
+ };
+ const scrollerElement =
+ all.find(element => scrollsOn(element, 'y')) ?? null;
+ const scrollerBox = scrollerElement?.getBoundingClientRect();
+ const inScroller = (element: Element) =>
+ scrollerElement != null && scrollerElement.contains(element);
+
+ const headerCells = [...root.querySelectorAll<HTMLElement>('h3')]
+ .map(heading => heading.parentElement)
+ .filter((cell): cell is HTMLElement => cell != null)
+ .map(cell => toBox(cell.getBoundingClientRect()));
+
+ const isEmptyBox = (element: HTMLElement) =>
+ element.children.length === 0 && element.textContent?.trim() === '';
+ const slots = all.filter(element => {
+ if (!inScroller(element) || !isEmptyBox(element)) {
+ return false;
+ }
+ const rect = element.getBoundingClientRect();
+ return Math.abs(rect.height - hourHeight) <= 2 && rect.width > 20;
+ });
+ const columnsByLeft = new Map<number, Box>();
+ for (const slot of slots) {
+ const rect = slot.getBoundingClientRect();
+ const key = Math.round(rect.left);
+ const existing = columnsByLeft.get(key);
+ if (existing == null) {
+ columnsByLeft.set(key, toBox(rect));
+ } else {
+ columnsByLeft.set(key, {
+ ...existing,
+ top: Math.min(existing.top, rect.top),
+ bottom: Math.max(existing.bottom, rect.bottom),
+ });
+ }
+ }
+ const bodyColumns = [...columnsByLeft.values()].sort((a, b) =>
+ direction === 'rtl' ? b.left - a.left : a.left - b.left,
+ );
+ const sortedHeaderCells = [...headerCells].sort((a, b) =>
+ direction === 'rtl' ? b.left - a.left : a.left - b.left,
+ );
+
+ const hourLabels = all
+ .filter(
+ element =>
+ inScroller(element) &&
+ element.children.length === 0 &&
+ /^\d{1,2}(:\d{2})?\s?(AM|PM)$/i.test(
+ element.textContent?.trim() ?? '',
+ ),
+ )
+ .map(element => ({
+ text: element.textContent?.trim() ?? '',
+ left: element.getBoundingClientRect().left,
+ }));
+
+ const nowLineElement = all.find(element => {
+ if (!inScroller(element) || !isEmptyBox(element)) {
+ return false;
+ }
+ const style = getComputedStyle(element);
+ return (
+ style.position === 'absolute' &&
+ style.borderTopWidth === '2px' &&
+ element.getBoundingClientRect().height <= 2
+ );
+ });
+ const contentTop = (element: Element) =>
+ scrollerElement == null || scrollerBox == null
+ ? null
+ : element.getBoundingClientRect().top -
+ scrollerBox.top +
+ scrollerElement.scrollTop;
+ const firstSlotOfFirstColumn = slots
+ .map(slot => ({slot, rect: slot.getBoundingClientRect()}))
+ .filter(
+ ({rect}) =>
+ bodyColumns[0] != null &&
+ Math.round(rect.left) === Math.round(bodyColumns[0].left),
+ )
+ .sort((a, b) => a.rect.top - b.rect.top)[0]?.slot;
+
+ const horizontalScrollerCount = all.filter(element =>
+ scrollsOn(element, 'x'),
+ ).length;
+
+ return {
+ direction,
+ scroller:
+ scrollerElement == null || scrollerBox == null
+ ? null
+ : {
+ box: toBox(scrollerBox),
+ scrollTop: scrollerElement.scrollTop,
+ scrollLeft: scrollerElement.scrollLeft,
+ scrollHeight: scrollerElement.scrollHeight,
+ clientHeight: scrollerElement.clientHeight,
+ scrollWidth: scrollerElement.scrollWidth,
+ clientWidth: scrollerElement.clientWidth,
+ verticalScrollbarWidth:
+ scrollerElement.offsetWidth - scrollerElement.clientWidth,
+ },
+ headerCells: sortedHeaderCells,
+ bodyColumns,
+ hourLabels,
+ nowLine:
+ nowLineElement == null
+ ? null
+ : {topInContent: contentTop(nowLineElement) ?? Number.NaN},
+ firstColumnTopInContent:
+ firstSlotOfFirstColumn == null
+ ? null
+ : contentTop(firstSlotOfFirstColumn),
+ horizontalScrollerCount,
+ pageOverflows:
+ document.documentElement.scrollWidth >
+ document.documentElement.clientWidth,
+ };
+ }, HOUR_HEIGHT);
+}
+
+export function columnDeltas(reading: TimeGridReading) {
+ return reading.headerCells.map((cell, index) => {
+ const column = reading.bodyColumns[index];
+ return {
+ index,
+ header: [Math.round(cell.left), Math.round(cell.right)],
+ body:
+ column == null
+ ? null
+ : [Math.round(column.left), Math.round(column.right)],
+ deltaLeft: column == null ? null : Math.abs(cell.left - column.left),
+ deltaRight: column == null ? null : Math.abs(cell.right - column.right),
+ };
+ });
+}
+
+export function setScrollLeft(page: Page, value: number): Promise<void> {
+ return page.evaluate(scrollLeft => {
+ const root = document.querySelector<HTMLElement>('.astryx-schedule');
+ const scroller = [...(root?.querySelectorAll<HTMLElement>('*') ?? [])].find(
+ element => {
+ const style = getComputedStyle(element);
+ return (
+ (style.overflowY === 'auto' || style.overflowY === 'scroll') &&
+ element.scrollHeight - element.clientHeight > 1
+ );
+ },
+ );
+ if (scroller != null) {
+ scroller.scrollLeft = scrollLeft;
+ }
+ }, value);
+}
+
+export function setScrollTop(page: Page, value: number): Promise<void> {
+ return page.evaluate(scrollTop => {
+ const root = document.querySelector<HTMLElement>('.astryx-schedule');
+ const scroller = [...(root?.querySelectorAll<HTMLElement>('*') ?? [])].find(
+ element => {
+ const style = getComputedStyle(element);
+ return (
+ (style.overflowY === 'auto' || style.overflowY === 'scroll') &&
+ element.scrollHeight - element.clientHeight > 1
+ );
+ },
+ );
+ if (scroller != null) {
+ scroller.scrollTop = scrollTop;
+ }
+ }, value);
+}
+
+export async function record(
+ evidence: Evidence,
+ page: Page,
+ name: string,
+ story: string,
+ direction: 'ltr' | 'rtl',
+ measured: unknown,
+): Promise<void> {
+ const viewport = page.viewportSize() ?? WIDE;
+ const file = `${name}.png`;
+ await page.screenshot({path: path.join(OUTPUT, file), fullPage: false});
+ evidence.receipts.push({
+ test: name,
+ story,
+ viewport,
+ direction,
+ browser: page.context().browser()?.version() ?? 'unknown',
+ checkout: evidence.checkoutSha,
+ head: process.env.ASTRYX_HEAD_SHA ?? evidence.checkoutSha,
+ measured,
+ screenshot: file,
+ });
+ // The job log is the durable copy of each measurement when artifacts expire.
+ // eslint-disable-next-line no-console
+ console.log(`[schedule-time-grid] ${name}: ${JSON.stringify(measured)}`);
+}
+
+export interface BlockReading {
+ readonly title: string;
+ readonly box: Box;
+ readonly columnIsolation: string;
+}
+
+export function readBlocks(
+ page: Page,
+ titles: ReadonlyArray<string>,
+): Promise<BlockReading[]> {
+ return page.evaluate((wanted): BlockReading[] => {
+ const root = document.querySelector<HTMLElement>('.astryx-schedule');
+ if (root == null) {
+ throw new Error('No Schedule root in the story');
+ }
+ const leaves = [...root.querySelectorAll<HTMLElement>('*')].filter(
+ element =>
+ element.children.length === 0 &&
+ wanted.includes(element.textContent?.trim() ?? ''),
+ );
+ const seen = new Set<HTMLElement>();
+ const blocks: Array<{title: string; box: Box; columnIsolation: string}> =
+ [];
+ for (const leaf of leaves) {
+ let block: HTMLElement | null = leaf;
+ while (block != null && getComputedStyle(block).position !== 'absolute') {
+ block = block.parentElement;
+ }
+ if (block == null || seen.has(block)) {
+ continue;
+ }
+ // The hidden read-only grid repeats titles inside aria-labels, never as
+ // text nodes, so a text leaf is always a painted block.
+ seen.add(block);
+ const rect = block.getBoundingClientRect();
+ blocks.push({
+ title: leaf.textContent?.trim() ?? '',
+ box: {
+ left: rect.left,
+ right: rect.right,
+ top: rect.top,
+ bottom: rect.bottom,
+ width: rect.width,
+ height: rect.height,
+ },
+ columnIsolation:
+ block.parentElement == null
+ ? ''
+ : getComputedStyle(block.parentElement).isolation,
+ });
+ }
+ return blocks;
+ }, titles);
+}
+
+export function inlineOverlap(a: Box, b: Box): number {
+ return Math.max(0, Math.min(a.right, b.right) - Math.max(a.left, b.left));
+}
+
+export function blockOverlap(a: Box, b: Box): number {
+ const horizontal = inlineOverlap(a, b);
+ const vertical = Math.max(
+ 0,
+ Math.min(a.bottom, b.bottom) - Math.max(a.top, b.top),
+ );
+ return horizontal * vertical;
+}
+
+/**
+ * How much of each edge of a frame changed between two same-size PNG
+ * buffers: the share of columns (top/bottom) or rows (left/right) in a
+ * 4-pixel band along that edge with at least one changed pixel. A complete
+ * focus ring scores near 1 on all four edges; a ring hidden under a pinned
+ * part scores near 0 there.
+ */
+export function ringEdgeCoverage(
+ before: {width: number; height: number; data: Uint8Array},
+ after: {width: number; height: number; data: Uint8Array},
+ band = 4,
+): {top: number; bottom: number; left: number; right: number} {
+ const {width, height} = before;
+ const changed = (x: number, y: number) => {
+ const index = (y * width + x) * 4;
+ for (let channel = 0; channel < 3; channel += 1) {
+ if (
+ Math.abs(before.data[index + channel] - after.data[index + channel]) >
+ 24
+ ) {
+ return true;
+ }
+ }
+ return false;
+ };
+ const columnChanged = (x: number, fromY: number, toY: number) => {
+ for (let y = fromY; y < toY; y += 1) {
+ if (changed(x, y)) {
+ return true;
+ }
+ }
+ return false;
+ };
+ const rowChanged = (y: number, fromX: number, toX: number) => {
+ for (let x = fromX; x < toX; x += 1) {
+ if (changed(x, y)) {
+ return true;
+ }
+ }
+ return false;
+ };
+ let top = 0;
+ let bottom = 0;
+ for (let x = 0; x < width; x += 1) {
+ if (columnChanged(x, 0, band)) {
+ top += 1;
+ }
+ if (columnChanged(x, height - band, height)) {
+ bottom += 1;
+ }
+ }
+ let left = 0;
+ let right = 0;
+ for (let y = 0; y < height; y += 1) {
+ if (rowChanged(y, 0, band)) {
+ left += 1;
+ }
+ if (rowChanged(y, width - band, width)) {
+ right += 1;
+ }
+ }
+ return {
+ top: top / width,
+ bottom: bottom / width,
+ left: left / height,
+ right: right / height,
+ };
+}
diff --git a/packages/lab/src/Schedule/schedule.stylex.ts b/packages/lab/src/Schedule/schedule.stylex.ts
new file mode 100644
index 0000000000..6a55dbe668
--- /dev/null
+++ b/packages/lab/src/Schedule/schedule.stylex.ts
@@ -0,0 +1,12 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import * as stylex from '@stylexjs/stylex';
+
+/**
+ * Marker the time-grid scroll viewport carries so a sibling can react to its
+ * keyboard focus in CSS. The viewport's own outline paints underneath its
+ * pinned header and gutter, so the focus ring is drawn by an overlay that reads
+ * `stylex.when.siblingBefore(':focus-visible', timeGridViewportScope)`.
+ */
+export const timeGridViewportScope: ReturnType<typeof stylex.defineMarker> =
+ stylex.defineMarker();
diff --git a/packages/lab/src/Schedule/shared.tsx b/packages/lab/src/Schedule/shared.tsx
index 6f3459d6a2..ac7f8a8331 100644
--- a/packages/lab/src/Schedule/shared.tsx
+++ b/packages/lab/src/Schedule/shared.tsx
@@ -15,6 +15,7 @@ import type {Locale} from '@astryxdesign/core/i18n';
import {
borderVars,
colorVars,
+ focusVars,
fontWeightVars,
radiusVars,
spacingVars,
@@ -33,6 +34,7 @@ import {
} from '@astryxdesign/core/utils';
import {isDayEvent} from './dateMath';
import {useScheduleContext} from './context';
+import {timeGridViewportScope} from './schedule.stylex';
import type {
CalendarEvent,
CalendarInstantEvent,
@@ -813,18 +815,85 @@ export const styles = stylex.create({
fontSize: typeScaleVars['--text-supporting-size'],
lineHeight: typeScaleVars['--text-supporting-leading'],
},
- timeGrid: {
- flex: 1,
- display: 'grid',
- gridTemplateColumns: '60px minmax(0, 1fr)',
- gridTemplateRows: '56px auto 1fr',
- height: '640px',
+ // The time grid is one scroll viewport. Its day header, all-day row, hour
+ // gutter, and day columns are items of a single grid inside it, pinned with
+ // position: sticky, so a scrollbar, a zoom level, or an inline scroll cannot
+ // separate header tracks from body tracks. Local z-index values order the
+ // pinned parts inside the isolated viewport only.
+ // A 640px flex basis, not a height: inside the frame's indefinite-height
+ // column a `height` with `flex: 1` resolves to content size, so the grid
+ // would grow to its full hours and the page, not the viewport, would scroll.
+ // The basis gives a 640px scrolling viewport by default and still fills or
+ // shrinks to a root the caller sizes.
+ timeGridFrame: {
+ position: 'relative',
+ display: 'flex',
+ flexDirection: 'column',
+ flexGrow: 1,
+ flexShrink: 1,
+ flexBasis: '640px',
minHeight: 0,
- overflow: 'hidden',
+ minWidth: 0,
},
+ // The viewport paints no focus outline of its own: the frame clips outside
+ // its border box, and an inset outline is painted under the viewport's
+ // pinned header and gutter. The ring is the overlay below instead.
+ timeGridViewport: {
+ flexGrow: 1,
+ flexShrink: 1,
+ flexBasis: 0,
+ minHeight: 0,
+ minWidth: 0,
+ scrollbarGutter: 'stable',
+ isolation: 'isolate',
+ outlineStyle: 'none',
+ },
+ // The keyboard focus ring of the viewport: a pointer-transparent overlay
+ // laid over the whole viewport (scrollbar included) and painted after the
+ // viewport's stacking context, so every edge of the ring is visible above
+ // the pinned parts. It shows while the viewport before it has keyboard
+ // focus, drawn just inside the edge the frame clips at.
+ timeGridFocusRing: {
+ position: 'absolute',
+ inset: 0,
+ pointerEvents: 'none',
+ outlineWidth: {
+ default: 0,
+ [stylex.when.siblingBefore(':focus-visible', timeGridViewportScope)]:
+ focusVars['--focus-outline-width'],
+ },
+ outlineStyle: {
+ default: 'none',
+ [stylex.when.siblingBefore(':focus-visible', timeGridViewportScope)]:
+ focusVars['--focus-outline-style'],
+ },
+ outlineColor: {
+ default: 'transparent',
+ [stylex.when.siblingBefore(':focus-visible', timeGridViewportScope)]:
+ focusVars['--focus-outline-color'],
+ },
+ outlineOffset: `calc(-1 * ${focusVars['--focus-outline-width']})`,
+ },
+ // The minimum width keeps the grid box as wide as its tracks when the
+ // viewport is narrower, so the pinned gutter has the whole scrolled extent as
+ // its sticky containing block instead of only the first viewport width.
+ timeGridContent: (columnCount: number) => ({
+ display: 'grid',
+ gridTemplateColumns: `60px repeat(${Math.max(1, columnCount)}, minmax(140px, 1fr))`,
+ gridTemplateRows: '56px auto auto',
+ minWidth: `${60 + Math.max(1, columnCount) * 140}px`,
+ }),
+ dayColumnPlacement: (index: number) => ({
+ gridColumn: `${index + 2}`,
+ }),
timeGridCorner: {
gridColumn: 1,
gridRow: 1,
+ position: 'sticky',
+ insetBlockStart: 0,
+ insetInlineStart: 0,
+ zIndex: 3,
+ backgroundColor: colorVars['--color-background-card'],
borderInlineEndWidth: borderVars['--border-width'],
borderInlineEndStyle: 'solid',
borderInlineEndColor: colorVars['--color-border'],
@@ -832,25 +901,24 @@ export const styles = stylex.create({
borderBottomStyle: 'solid',
borderBottomColor: colorVars['--color-border'],
},
- timeGridHeader: {
- gridColumn: 2,
- gridRow: 1,
- display: 'grid',
- gridAutoFlow: 'column',
- gridAutoColumns: 'minmax(140px, 1fr)',
- borderBottomWidth: borderVars['--border-width'],
- borderBottomStyle: 'solid',
- borderBottomColor: colorVars['--color-border'],
- },
timeGridHeaderCell: {
+ gridRow: 1,
+ position: 'sticky',
+ insetBlockStart: 0,
+ zIndex: 2,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
gap: spacingVars['--spacing-0-5'],
+ minWidth: 0,
+ backgroundColor: colorVars['--color-background-card'],
borderInlineEndWidth: borderVars['--border-width'],
borderInlineEndStyle: 'solid',
borderInlineEndColor: colorVars['--color-border'],
+ borderBottomWidth: borderVars['--border-width'],
+ borderBottomStyle: 'solid',
+ borderBottomColor: colorVars['--color-border'],
},
timeGridHeaderCellLast: {
borderInlineEndWidth: 0,
@@ -880,11 +948,16 @@ export const styles = stylex.create({
allDayLabel: {
gridColumn: 1,
gridRow: 2,
+ position: 'sticky',
+ insetBlockStart: '56px',
+ insetInlineStart: 0,
+ zIndex: 3,
paddingBlock: spacingVars['--spacing-1'],
paddingInline: spacingVars['--spacing-2'],
display: 'flex',
alignItems: 'center',
justifyContent: 'flex-end',
+ backgroundColor: colorVars['--color-background-card'],
borderInlineEndWidth: borderVars['--border-width'],
borderInlineEndStyle: 'solid',
borderInlineEndColor: colorVars['--color-border'],
@@ -892,35 +965,28 @@ export const styles = stylex.create({
borderBottomStyle: 'solid',
borderBottomColor: colorVars['--color-border'],
},
- allDayRow: {
- gridColumn: 2,
+ // A subgrid, so all-day cells and spans sit on the day columns' own tracks.
+ allDayRow: (levelCount: number) => ({
+ gridColumn: '2 / -1',
gridRow: 2,
- overflowX: 'auto',
- minHeight: 0,
+ display: 'grid',
+ gridTemplateColumns: 'subgrid',
+ position: 'sticky',
+ insetBlockStart: '56px',
+ zIndex: 2,
+ isolation: 'isolate',
+ minHeight: levelCount > 0 ? `${3 + levelCount * 27}px` : '26px',
+ minWidth: 0,
+ backgroundColor: colorVars['--color-background-card'],
borderBottomWidth: borderVars['--border-width'],
borderBottomStyle: 'solid',
borderBottomColor: colorVars['--color-border'],
- },
- allDayRowSurface: (columnCount: number, levelCount: number) => ({
- position: 'relative',
- width: '100%',
- minWidth: `${Math.max(1, columnCount) * 140}px`,
- minHeight: levelCount > 0 ? `${3 + levelCount * 27}px` : '26px',
- }),
- allDayCellGrid: (columnCount: number) => ({
- position: 'absolute',
- inset: 0,
- display: 'grid',
- gridTemplateColumns: `repeat(${Math.max(1, columnCount)}, minmax(0, 1fr))`,
}),
- allDayEventOverlay: (columnCount: number) => ({
- position: 'absolute',
- inset: 0,
- display: 'grid',
- gridTemplateColumns: `repeat(${Math.max(1, columnCount)}, minmax(0, 1fr))`,
- pointerEvents: 'none',
+ allDaySubgridPlacement: (index: number) => ({
+ gridColumn: `${index + 1}`,
}),
allDayCell: {
+ gridRow: 1,
minWidth: 0,
borderInlineEndWidth: borderVars['--border-width'],
borderInlineEndStyle: 'solid',
@@ -930,25 +996,21 @@ export const styles = stylex.create({
borderInlineEndWidth: 0,
},
allDayEventSpan: (columnStart: number, columnEnd: number, level: number) => ({
+ gridRow: 1,
gridColumn: `${columnStart + 1} / ${columnEnd + 2}`,
alignSelf: 'start',
minWidth: 0,
marginInlineStart: spacingVars['--spacing-0-5'],
marginInlineEnd: `calc(${spacingVars['--spacing-0-5']} + ${borderVars['--border-width']})`,
marginBlockStart: `${2 + level * 27}px`,
- pointerEvents: 'auto',
}),
- timeGridBody: {
- gridColumn: '1 / -1',
- gridRow: 3,
- display: 'grid',
- gridTemplateColumns: '60px minmax(0, 1fr)',
- overflow: 'auto',
- minHeight: 0,
- },
timeLabels: {
gridColumn: 1,
- position: 'relative',
+ gridRow: 3,
+ position: 'sticky',
+ insetInlineStart: 0,
+ zIndex: 2,
+ backgroundColor: colorVars['--color-background-card'],
borderInlineEndWidth: borderVars['--border-width'],
borderInlineEndStyle: 'solid',
borderInlineEndColor: colorVars['--color-border'],
@@ -968,15 +1030,12 @@ export const styles = stylex.create({
timeLabelPosition: (index: number, hourHeight: number) => ({
top: `${index * hourHeight - 1}px`,
}),
- timeColumns: {
- gridColumn: 2,
- display: 'grid',
- gridAutoFlow: 'column',
- gridAutoColumns: 'minmax(140px, 1fr)',
- minWidth: 0,
- },
+ // Each day column isolates its own paint order: blocks, the now-line, and a
+ // raised focused block never rank against anything outside the column.
timeColumn: {
+ gridRow: 3,
position: 'relative',
+ isolation: 'isolate',
display: 'grid',
minWidth: 0,
borderInlineEndWidth: borderVars['--border-width'],