Skip to content

Commit a4787ff

Browse files
authored
feat(lab): open Schedule day and week grids one hour before now (#6928)
The time grid always opened at the first hour of its window, so a 0–24 hour day opened on midnight with the current-time line off screen all afternoon, and when an async loader resolved the suspended fallback's viewport was replaced by a fresh one scrolled back to the top. When the rendered range's days include today in the schedule's timezone, the viewport now opens with the hour before now at the top of the column area, clamped to the grid; any other range opens at the window start. This happens once per rendered range — keyed by the range bounds, the timezone, and the hour window, never by object identity — and never again for that range: data arriving or refreshing, clock ticks, theme changes, and resizes leave the person's own scroll alone. Schedule keeps one scroll record above its suspense boundary, so the loaded content restores the offset the person chose while the fallback was showing instead of positioning again. No API: the position is derived from the clock and the range (AST-002 FR2). getInitialTimeGridOffset is pure and unit-tested; TimeGridView.test.tsx covers week/day/not-today, the tick and data-refresh no-yank, paging to a new range, and the suspense swap against mocked geometry; ScheduleTimeGridInitialPosition.a11y.chromium.spec.ts measures the real offsets with an installed clock in pr-a11y.
1 parent 1745a95 commit a4787ff

6 files changed

Lines changed: 671 additions & 28 deletions

File tree

‎packages/lab/src/Schedule/Schedule.doc.mjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ export const docs = {
8989
name: 'Current time line',
9090
required: false,
9191
description:
92-
'A line across the day or week time grid at the current time, on the current day only. It ticks once a minute and is absent during server rendering.',
92+
'A line across the day or week time grid at the current time, on the current day only. It ticks once a minute and is absent during server rendering. When the rendered range includes today, the grid opens scrolled to one hour before this line (clamped to the grid) once per range, and then leaves the scroll position alone until the person pages to another range or switches views.',
9393
},
9494
],
9595
},

‎packages/lab/src/Schedule/Schedule.tsx‎

Lines changed: 35 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
* - /apps/storybook/stories/Schedule.stories.tsx
1515
*/
1616

17-
import {Suspense, useCallback, useMemo, useState} from 'react';
17+
import {Suspense, useCallback, useMemo, useRef, useState} from 'react';
1818
import * as stylex from '@stylexjs/stylex';
1919
import type {BaseProps} from '@astryxdesign/core';
2020
import {useLocale, type Locale} from '@astryxdesign/core/i18n';
@@ -23,6 +23,10 @@ import {eventOverlapsRange, getBrowserTimezoneID, sortEvents} from './dateMath';
2323
import {ScheduleContext} from './context';
2424
import {defaultSchedulePlugins} from './plugins';
2525
import {styles} from './shared';
26+
import {
27+
TimeGridScrollMemoryContext,
28+
type TimeGridScrollMemory,
29+
} from './timeGridScrollMemory';
2630
import {createZonedDateTime} from './zonedDateTime';
2731
import {themeProps} from '@astryxdesign/core/utils';
2832
import type {
@@ -271,6 +275,12 @@ export function Schedule({
271275
const onNextDate = useCallback(() => {
272276
shiftToRange(nextDateRange.range);
273277
}, [nextDateRange, shiftToRange]);
278+
// Lives above the suspense boundary so the fallback's viewport and the
279+
// loaded content's viewport share one scroll record per rendered range.
280+
const timeGridScrollMemory = useRef<TimeGridScrollMemory>({
281+
key: null,
282+
offset: 0,
283+
});
274284

275285
return (
276286
<div
@@ -281,16 +291,34 @@ export function Schedule({
281291
className,
282292
style,
283293
)}>
284-
<Suspense
285-
fallback={
294+
<TimeGridScrollMemoryContext.Provider value={timeGridScrollMemory}>
295+
<Suspense
296+
fallback={
297+
<ScheduleViewContent
298+
view={view}
299+
eventSource={[]}
300+
categories={categories}
301+
date={zonedDateTime}
302+
focusDate={focusZonedDateTime}
303+
locale={locale}
304+
isLoading
305+
onPreviousDate={onPreviousDate}
306+
previousDateLabel={previousDateRange.label}
307+
onToday={onToday}
308+
onNextDate={onNextDate}
309+
nextDateLabel={nextDateRange.label}
310+
plugins={plugins}
311+
headingLevel={headingLevel}
312+
/>
313+
}>
286314
<ScheduleViewContent
287315
view={view}
288-
eventSource={[]}
316+
eventSource={events}
289317
categories={categories}
290318
date={zonedDateTime}
291319
focusDate={focusZonedDateTime}
292320
locale={locale}
293-
isLoading
321+
isLoading={false}
294322
onPreviousDate={onPreviousDate}
295323
previousDateLabel={previousDateRange.label}
296324
onToday={onToday}
@@ -299,24 +327,8 @@ export function Schedule({
299327
plugins={plugins}
300328
headingLevel={headingLevel}
301329
/>
302-
}>
303-
<ScheduleViewContent
304-
view={view}
305-
eventSource={events}
306-
categories={categories}
307-
date={zonedDateTime}
308-
focusDate={focusZonedDateTime}
309-
locale={locale}
310-
isLoading={false}
311-
onPreviousDate={onPreviousDate}
312-
previousDateLabel={previousDateRange.label}
313-
onToday={onToday}
314-
onNextDate={onNextDate}
315-
nextDateLabel={nextDateRange.label}
316-
plugins={plugins}
317-
headingLevel={headingLevel}
318-
/>
319-
</Suspense>
330+
</Suspense>
331+
</TimeGridScrollMemoryContext.Provider>
320332
</div>
321333
);
322334
}
Lines changed: 268 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,268 @@
1+
// Copyright (c) Meta Platforms, Inc. and affiliates.
2+
3+
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
4+
import {act, fireEvent, render, screen, waitFor} from '@testing-library/react';
5+
import {useState} from 'react';
6+
import {createEventFromISO} from './CalendarEvent';
7+
import {Schedule} from './Schedule';
8+
import {createScheduleDayView} from './DayView';
9+
import {createScheduleWeeklyView} from './WeeklyView';
10+
import {getInitialTimeGridOffset} from './timeGridScrollMemory';
11+
import type {CalendarEvent, Instant, ScheduleEventSource} from './types';
12+
13+
const VIEWPORT = {clientWidth: 1000, clientHeight: 600, scrollWidth: 1000};
14+
// 24 hours at 100px plus the pinned header (56px) and all-day row (~27px).
15+
const SCROLL_HEIGHT = 2483;
16+
17+
const events: CalendarEvent[] = [
18+
createEventFromISO({
19+
id: 'visible',
20+
title: 'Visible sync',
21+
start: '2026-05-13T16:00:00.000Z',
22+
end: '2026-05-13T16:30:00.000Z',
23+
}),
24+
];
25+
26+
function isViewport(element: unknown): element is HTMLElement {
27+
return (
28+
element instanceof HTMLElement && element.hasAttribute('data-scroll-axis')
29+
);
30+
}
31+
32+
/**
33+
* jsdom lays out nothing, so the time-grid viewport is given the geometry a
34+
* browser would measure: 24 hours of content in a 600px-tall viewport.
35+
*/
36+
function mockViewportGeometry(scrollHeight = SCROLL_HEIGHT) {
37+
const geometry: Record<string, number> = {...VIEWPORT, scrollHeight};
38+
for (const key of Object.keys(geometry)) {
39+
Object.defineProperty(HTMLElement.prototype, key, {
40+
configurable: true,
41+
get(this: HTMLElement) {
42+
return isViewport(this) ? geometry[key] : 0;
43+
},
44+
});
45+
}
46+
const nativeGetComputedStyle = window.getComputedStyle.bind(window);
47+
vi.spyOn(window, 'getComputedStyle').mockImplementation(element => {
48+
const computed = nativeGetComputedStyle(element);
49+
if (!isViewport(element)) {
50+
return computed;
51+
}
52+
return new Proxy(computed, {
53+
get(target, property) {
54+
if (property === 'overflowX' || property === 'overflowY') {
55+
return 'auto';
56+
}
57+
return Reflect.get(target, property, target);
58+
},
59+
});
60+
});
61+
}
62+
63+
function restoreViewportGeometry() {
64+
for (const key of [...Object.keys(VIEWPORT), 'scrollHeight']) {
65+
// Deleting the shadowing getter exposes jsdom's own again.
66+
delete (HTMLElement.prototype as unknown as Record<string, unknown>)[key];
67+
}
68+
vi.restoreAllMocks();
69+
}
70+
71+
function viewport(): HTMLElement {
72+
return screen.getByRole('region', {name: /time grid$/});
73+
}
74+
75+
function Harness({
76+
initialDate,
77+
eventSource = events,
78+
view = createScheduleWeeklyView(),
79+
}: {
80+
initialDate: Instant;
81+
eventSource?: ScheduleEventSource;
82+
view?: ReturnType<typeof createScheduleWeeklyView>;
83+
}) {
84+
const [date, setDate] = useState<Instant>(initialDate);
85+
return (
86+
<Schedule
87+
view={view}
88+
events={eventSource}
89+
date={date}
90+
onChangeDate={setDate}
91+
timezoneID="UTC"
92+
/>
93+
);
94+
}
95+
96+
describe('getInitialTimeGridOffset', () => {
97+
const days = [
98+
{year: 2026, month: 5, day: 10},
99+
{year: 2026, month: 5, day: 11},
100+
{year: 2026, month: 5, day: 12},
101+
{year: 2026, month: 5, day: 13},
102+
];
103+
const geometry = {
104+
timezoneID: 'UTC',
105+
minHour: 0,
106+
hourHeight: 100,
107+
scrollHeight: SCROLL_HEIGHT,
108+
clientHeight: 600,
109+
};
110+
111+
it('opens one hour above now when today is in the range', () => {
112+
expect(
113+
getInitialTimeGridOffset({
114+
...geometry,
115+
currentTime: Date.UTC(2026, 4, 13, 14, 0),
116+
days,
117+
}),
118+
).toBe(1302);
119+
});
120+
121+
it('opens at the top when today is not in the range', () => {
122+
expect(
123+
getInitialTimeGridOffset({
124+
...geometry,
125+
currentTime: Date.UTC(2026, 6, 1, 14, 0),
126+
days,
127+
}),
128+
).toBe(0);
129+
});
130+
131+
it('clamps to the top shortly after the window starts', () => {
132+
expect(
133+
getInitialTimeGridOffset({
134+
...geometry,
135+
currentTime: Date.UTC(2026, 4, 13, 0, 20),
136+
days,
137+
}),
138+
).toBe(0);
139+
});
140+
141+
it('clamps to the end of the grid near midnight', () => {
142+
expect(
143+
getInitialTimeGridOffset({
144+
...geometry,
145+
currentTime: Date.UTC(2026, 4, 13, 23, 50),
146+
days,
147+
}),
148+
).toBe(SCROLL_HEIGHT - 600);
149+
});
150+
151+
it('measures from the configured first hour', () => {
152+
expect(
153+
getInitialTimeGridOffset({
154+
...geometry,
155+
minHour: 7,
156+
currentTime: Date.UTC(2026, 4, 13, 9, 0),
157+
days,
158+
}),
159+
).toBe(102);
160+
});
161+
});
162+
163+
describe('time grid initial position', () => {
164+
beforeEach(() => {
165+
mockViewportGeometry();
166+
});
167+
168+
afterEach(() => {
169+
restoreViewportGeometry();
170+
vi.useRealTimers();
171+
});
172+
173+
it('opens a week containing today one hour before now', () => {
174+
vi.setSystemTime(Date.UTC(2026, 4, 13, 14, 0));
175+
render(<Harness initialDate={Date.UTC(2026, 4, 13, 14, 0) as Instant} />);
176+
expect(viewport().scrollTop).toBe(1302);
177+
});
178+
179+
it('opens a day containing today one hour before now', () => {
180+
vi.setSystemTime(Date.UTC(2026, 4, 13, 9, 30));
181+
render(
182+
<Harness
183+
initialDate={Date.UTC(2026, 4, 13, 9, 30) as Instant}
184+
view={createScheduleDayView()}
185+
/>,
186+
);
187+
expect(viewport().scrollTop).toBe(852);
188+
});
189+
190+
it('opens a range without today at its configured start', () => {
191+
vi.setSystemTime(Date.UTC(2026, 6, 1, 14, 0));
192+
render(<Harness initialDate={Date.UTC(2026, 4, 13, 14, 0) as Instant} />);
193+
expect(viewport().scrollTop).toBe(0);
194+
});
195+
196+
it('leaves the person\u2019s own scroll alone across a clock tick and a data refresh', () => {
197+
vi.useFakeTimers();
198+
vi.setSystemTime(Date.UTC(2026, 4, 13, 14, 0));
199+
const {rerender} = render(
200+
<Harness initialDate={Date.UTC(2026, 4, 13, 14, 0) as Instant} />,
201+
);
202+
expect(viewport().scrollTop).toBe(1302);
203+
204+
viewport().scrollTop = 500;
205+
fireEvent.scroll(viewport());
206+
act(() => {
207+
vi.advanceTimersByTime(60_000);
208+
});
209+
expect(viewport().scrollTop).toBe(500);
210+
211+
rerender(
212+
<Harness
213+
initialDate={Date.UTC(2026, 4, 13, 14, 0) as Instant}
214+
eventSource={[...events]}
215+
/>,
216+
);
217+
expect(viewport().scrollTop).toBe(500);
218+
});
219+
220+
it('positions again when the person opens another range', () => {
221+
vi.setSystemTime(Date.UTC(2026, 4, 13, 14, 0));
222+
render(<Harness initialDate={Date.UTC(2026, 4, 13, 14, 0) as Instant} />);
223+
expect(viewport().scrollTop).toBe(1302);
224+
225+
fireEvent.click(screen.getByRole('button', {name: 'Next week'}));
226+
expect(viewport().scrollTop).toBe(0);
227+
228+
fireEvent.click(screen.getByRole('button', {name: 'Previous week'}));
229+
expect(viewport().scrollTop).toBe(1302);
230+
});
231+
232+
it('restores the offset when loaded content replaces the suspended fallback', async () => {
233+
vi.setSystemTime(Date.UTC(2026, 4, 13, 14, 0));
234+
let resolveEvents: (value: ReadonlyArray<CalendarEvent>) => void = () => {};
235+
const loader = vi.fn(
236+
() =>
237+
new Promise<ReadonlyArray<CalendarEvent>>(resolve => {
238+
resolveEvents = resolve;
239+
}),
240+
);
241+
render(
242+
<Harness
243+
initialDate={Date.UTC(2026, 4, 13, 14, 0) as Instant}
244+
eventSource={loader}
245+
/>,
246+
);
247+
const fallbackViewport = viewport();
248+
expect(fallbackViewport.scrollTop).toBe(1302);
249+
250+
fallbackViewport.scrollTop = 700;
251+
fireEvent.scroll(fallbackViewport);
252+
253+
// The loader is invoked in a microtask after the first render.
254+
await waitFor(() => {
255+
expect(loader).toHaveBeenCalled();
256+
});
257+
await act(async () => {
258+
resolveEvents(events);
259+
await Promise.resolve();
260+
});
261+
await waitFor(() => {
262+
expect(screen.getByText('Visible sync')).toBeInTheDocument();
263+
});
264+
const loadedViewport = viewport();
265+
expect(loadedViewport).not.toBe(fallbackViewport);
266+
expect(loadedViewport.scrollTop).toBe(700);
267+
});
268+
});

0 commit comments

Comments
 (0)