An open source design system that's fully customizable and agent ready
TypeScript
feat(lab): open Schedule day and week grids one hour before now (#6928)
Cindy Zhanga4787ffbd3ba
diff --git a/packages/lab/src/Schedule/Schedule.doc.mjs b/packages/lab/src/Schedule/Schedule.doc.mjsindex 318fdb7977..80e34b8e62 100644--- a/packages/lab/src/Schedule/Schedule.doc.mjs+++ b/packages/lab/src/Schedule/Schedule.doc.mjs@@ -89,7 +89,7 @@ export const docs = {name: 'Current time line',required: false,description:- '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.',+ '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.',},],},diff --git a/packages/lab/src/Schedule/Schedule.tsx b/packages/lab/src/Schedule/Schedule.tsxindex b5486aae78..074436bfca 100644--- a/packages/lab/src/Schedule/Schedule.tsx+++ b/packages/lab/src/Schedule/Schedule.tsx@@ -14,7 +14,7 @@* - /apps/storybook/stories/Schedule.stories.tsx*/-import {Suspense, useCallback, useMemo, useState} from 'react';+import {Suspense, useCallback, useMemo, useRef, useState} from 'react';import * as stylex from '@stylexjs/stylex';import type {BaseProps} from '@astryxdesign/core';import {useLocale, type Locale} from '@astryxdesign/core/i18n';@@ -23,6 +23,10 @@ import {eventOverlapsRange, getBrowserTimezoneID, sortEvents} from './dateMath';import {ScheduleContext} from './context';import {defaultSchedulePlugins} from './plugins';import {styles} from './shared';+import {+ TimeGridScrollMemoryContext,+ type TimeGridScrollMemory,+} from './timeGridScrollMemory';import {createZonedDateTime} from './zonedDateTime';import {themeProps} from '@astryxdesign/core/utils';import type {@@ -271,6 +275,12 @@ export function Schedule({const onNextDate = useCallback(() => {shiftToRange(nextDateRange.range);}, [nextDateRange, shiftToRange]);+ // Lives above the suspense boundary so the fallback's viewport and the+ // loaded content's viewport share one scroll record per rendered range.+ const timeGridScrollMemory = useRef<TimeGridScrollMemory>({+ key: null,+ offset: 0,+ });return (<div@@ -281,16 +291,34 @@ export function Schedule({className,style,)}>- <Suspense- fallback={+ <TimeGridScrollMemoryContext.Provider value={timeGridScrollMemory}>+ <Suspense+ fallback={+ <ScheduleViewContent+ view={view}+ eventSource={[]}+ categories={categories}+ date={zonedDateTime}+ focusDate={focusZonedDateTime}+ locale={locale}+ isLoading+ onPreviousDate={onPreviousDate}+ previousDateLabel={previousDateRange.label}+ onToday={onToday}+ onNextDate={onNextDate}+ nextDateLabel={nextDateRange.label}+ plugins={plugins}+ headingLevel={headingLevel}+ />+ }><ScheduleViewContentview={view}- eventSource={[]}+ eventSource={events}categories={categories}date={zonedDateTime}focusDate={focusZonedDateTime}locale={locale}- isLoading+ isLoading={false}onPreviousDate={onPreviousDate}previousDateLabel={previousDateRange.label}onToday={onToday}@@ -299,24 +327,8 @@ export function Schedule({plugins={plugins}headingLevel={headingLevel}/>- }>- <ScheduleViewContent- view={view}- eventSource={events}- categories={categories}- date={zonedDateTime}- focusDate={focusZonedDateTime}- locale={locale}- isLoading={false}- onPreviousDate={onPreviousDate}- previousDateLabel={previousDateRange.label}- onToday={onToday}- onNextDate={onNextDate}- nextDateLabel={nextDateRange.label}- plugins={plugins}- headingLevel={headingLevel}- />- </Suspense>+ </Suspense>+ </TimeGridScrollMemoryContext.Provider></div>);}diff --git a/packages/lab/src/Schedule/TimeGridView.test.tsx b/packages/lab/src/Schedule/TimeGridView.test.tsxnew file mode 100644index 0000000000..e9edfdf68a--- /dev/null+++ b/packages/lab/src/Schedule/TimeGridView.test.tsx@@ -0,0 +1,268 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';+import {act, fireEvent, render, screen, waitFor} from '@testing-library/react';+import {useState} from 'react';+import {createEventFromISO} from './CalendarEvent';+import {Schedule} from './Schedule';+import {createScheduleDayView} from './DayView';+import {createScheduleWeeklyView} from './WeeklyView';+import {getInitialTimeGridOffset} from './timeGridScrollMemory';+import type {CalendarEvent, Instant, ScheduleEventSource} from './types';++const VIEWPORT = {clientWidth: 1000, clientHeight: 600, scrollWidth: 1000};+// 24 hours at 100px plus the pinned header (56px) and all-day row (~27px).+const SCROLL_HEIGHT = 2483;++const events: CalendarEvent[] = [+ createEventFromISO({+ id: 'visible',+ title: 'Visible sync',+ start: '2026-05-13T16:00:00.000Z',+ end: '2026-05-13T16:30:00.000Z',+ }),+];++function isViewport(element: unknown): element is HTMLElement {+ return (+ element instanceof HTMLElement && element.hasAttribute('data-scroll-axis')+ );+}++/**+ * jsdom lays out nothing, so the time-grid viewport is given the geometry a+ * browser would measure: 24 hours of content in a 600px-tall viewport.+ */+function mockViewportGeometry(scrollHeight = SCROLL_HEIGHT) {+ const geometry: Record<string, number> = {...VIEWPORT, scrollHeight};+ for (const key of Object.keys(geometry)) {+ Object.defineProperty(HTMLElement.prototype, key, {+ configurable: true,+ get(this: HTMLElement) {+ return isViewport(this) ? geometry[key] : 0;+ },+ });+ }+ const nativeGetComputedStyle = window.getComputedStyle.bind(window);+ vi.spyOn(window, 'getComputedStyle').mockImplementation(element => {+ const computed = nativeGetComputedStyle(element);+ if (!isViewport(element)) {+ return computed;+ }+ return new Proxy(computed, {+ get(target, property) {+ if (property === 'overflowX' || property === 'overflowY') {+ return 'auto';+ }+ return Reflect.get(target, property, target);+ },+ });+ });+}++function restoreViewportGeometry() {+ for (const key of [...Object.keys(VIEWPORT), 'scrollHeight']) {+ // Deleting the shadowing getter exposes jsdom's own again.+ delete (HTMLElement.prototype as unknown as Record<string, unknown>)[key];+ }+ vi.restoreAllMocks();+}++function viewport(): HTMLElement {+ return screen.getByRole('region', {name: /time grid$/});+}++function Harness({+ initialDate,+ eventSource = events,+ view = createScheduleWeeklyView(),+}: {+ initialDate: Instant;+ eventSource?: ScheduleEventSource;+ view?: ReturnType<typeof createScheduleWeeklyView>;+}) {+ const [date, setDate] = useState<Instant>(initialDate);+ return (+ <Schedule+ view={view}+ events={eventSource}+ date={date}+ onChangeDate={setDate}+ timezoneID="UTC"+ />+ );+}++describe('getInitialTimeGridOffset', () => {+ const days = [+ {year: 2026, month: 5, day: 10},+ {year: 2026, month: 5, day: 11},+ {year: 2026, month: 5, day: 12},+ {year: 2026, month: 5, day: 13},+ ];+ const geometry = {+ timezoneID: 'UTC',+ minHour: 0,+ hourHeight: 100,+ scrollHeight: SCROLL_HEIGHT,+ clientHeight: 600,+ };++ it('opens one hour above now when today is in the range', () => {+ expect(+ getInitialTimeGridOffset({+ ...geometry,+ currentTime: Date.UTC(2026, 4, 13, 14, 0),+ days,+ }),+ ).toBe(1302);+ });++ it('opens at the top when today is not in the range', () => {+ expect(+ getInitialTimeGridOffset({+ ...geometry,+ currentTime: Date.UTC(2026, 6, 1, 14, 0),+ days,+ }),+ ).toBe(0);+ });++ it('clamps to the top shortly after the window starts', () => {+ expect(+ getInitialTimeGridOffset({+ ...geometry,+ currentTime: Date.UTC(2026, 4, 13, 0, 20),+ days,+ }),+ ).toBe(0);+ });++ it('clamps to the end of the grid near midnight', () => {+ expect(+ getInitialTimeGridOffset({+ ...geometry,+ currentTime: Date.UTC(2026, 4, 13, 23, 50),+ days,+ }),+ ).toBe(SCROLL_HEIGHT - 600);+ });++ it('measures from the configured first hour', () => {+ expect(+ getInitialTimeGridOffset({+ ...geometry,+ minHour: 7,+ currentTime: Date.UTC(2026, 4, 13, 9, 0),+ days,+ }),+ ).toBe(102);+ });+});++describe('time grid initial position', () => {+ beforeEach(() => {+ mockViewportGeometry();+ });++ afterEach(() => {+ restoreViewportGeometry();+ vi.useRealTimers();+ });++ it('opens a week containing today one hour before now', () => {+ vi.setSystemTime(Date.UTC(2026, 4, 13, 14, 0));+ render(<Harness initialDate={Date.UTC(2026, 4, 13, 14, 0) as Instant} />);+ expect(viewport().scrollTop).toBe(1302);+ });++ it('opens a day containing today one hour before now', () => {+ vi.setSystemTime(Date.UTC(2026, 4, 13, 9, 30));+ render(+ <Harness+ initialDate={Date.UTC(2026, 4, 13, 9, 30) as Instant}+ view={createScheduleDayView()}+ />,+ );+ expect(viewport().scrollTop).toBe(852);+ });++ it('opens a range without today at its configured start', () => {+ vi.setSystemTime(Date.UTC(2026, 6, 1, 14, 0));+ render(<Harness initialDate={Date.UTC(2026, 4, 13, 14, 0) as Instant} />);+ expect(viewport().scrollTop).toBe(0);+ });++ it('leaves the person\u2019s own scroll alone across a clock tick and a data refresh', () => {+ vi.useFakeTimers();+ vi.setSystemTime(Date.UTC(2026, 4, 13, 14, 0));+ const {rerender} = render(+ <Harness initialDate={Date.UTC(2026, 4, 13, 14, 0) as Instant} />,+ );+ expect(viewport().scrollTop).toBe(1302);++ viewport().scrollTop = 500;+ fireEvent.scroll(viewport());+ act(() => {+ vi.advanceTimersByTime(60_000);+ });+ expect(viewport().scrollTop).toBe(500);++ rerender(+ <Harness+ initialDate={Date.UTC(2026, 4, 13, 14, 0) as Instant}+ eventSource={[...events]}+ />,+ );+ expect(viewport().scrollTop).toBe(500);+ });++ it('positions again when the person opens another range', () => {+ vi.setSystemTime(Date.UTC(2026, 4, 13, 14, 0));+ render(<Harness initialDate={Date.UTC(2026, 4, 13, 14, 0) as Instant} />);+ expect(viewport().scrollTop).toBe(1302);++ fireEvent.click(screen.getByRole('button', {name: 'Next week'}));+ expect(viewport().scrollTop).toBe(0);++ fireEvent.click(screen.getByRole('button', {name: 'Previous week'}));+ expect(viewport().scrollTop).toBe(1302);+ });++ it('restores the offset when loaded content replaces the suspended fallback', async () => {+ vi.setSystemTime(Date.UTC(2026, 4, 13, 14, 0));+ let resolveEvents: (value: ReadonlyArray<CalendarEvent>) => void = () => {};+ const loader = vi.fn(+ () =>+ new Promise<ReadonlyArray<CalendarEvent>>(resolve => {+ resolveEvents = resolve;+ }),+ );+ render(+ <Harness+ initialDate={Date.UTC(2026, 4, 13, 14, 0) as Instant}+ eventSource={loader}+ />,+ );+ const fallbackViewport = viewport();+ expect(fallbackViewport.scrollTop).toBe(1302);++ fallbackViewport.scrollTop = 700;+ fireEvent.scroll(fallbackViewport);++ // The loader is invoked in a microtask after the first render.+ await waitFor(() => {+ expect(loader).toHaveBeenCalled();+ });+ await act(async () => {+ resolveEvents(events);+ await Promise.resolve();+ });+ await waitFor(() => {+ expect(screen.getByText('Visible sync')).toBeInTheDocument();+ });+ const loadedViewport = viewport();+ expect(loadedViewport).not.toBe(fallbackViewport);+ expect(loadedViewport.scrollTop).toBe(700);+ });+});diff --git a/packages/lab/src/Schedule/TimeGridView.tsx b/packages/lab/src/Schedule/TimeGridView.tsxindex 9fbe35c9e2..9290eab038 100644--- a/packages/lab/src/Schedule/TimeGridView.tsx+++ b/packages/lab/src/Schedule/TimeGridView.tsx@@ -10,6 +10,13 @@* @position Internal view primitive shared by WeeklyView and DayView*/+import {+ useContext,+ useLayoutEffect,+ useMemo,+ useRef,+ type UIEvent,+} from 'react';import * as stylex from '@stylexjs/stylex';import type {Locale} from '@astryxdesign/core/i18n';import {@@ -45,6 +52,12 @@ import {styles,} from './shared';import {layoutTimedEvents, type TimedEventPlacement} from './timeGridLayout';+import {+ getInitialTimeGridOffset,+ isSameRangeKey,+ TimeGridScrollMemoryContext,+ type TimeGridScrollMemory,+} from './timeGridScrollMemory';import {useCurrentTime} from './useCurrentTime';import type {CalendarDayEvent,@@ -73,7 +86,7 @@ export function TimeGridView({/** Accessible name of the rendered range; names the scroll viewport. */label: string;}) {- const {categories, headingLevel, locale} = useScheduleContext();+ const {categories, headingLevel, locale, range} = useScheduleContext();const normalizedMinHour = Math.max(0, Math.min(23, Math.floor(minHour)));const normalizedMaxHour = Math.max(normalizedMinHour + 1,@@ -100,7 +113,11 @@ export function TimeGridView({locale,);- const {getViewportProps, getContentProps} = useScrollableArea({+ const {+ getViewportProps,+ getContentProps,+ state: scrollState,+ } = useScrollableArea({axis: 'both',keyboardAccess: {owner: 'viewport',@@ -108,9 +125,97 @@ export function TimeGridView({role: 'region',},});- const viewportProps = getViewportProps<HTMLDivElement>(- stylex.props(styles.timeGridViewport, timeGridViewportScope),++ // Initial position (component:Schedule FR4–FR6): once per rendered range,+ // the viewport opens one hour above now when the range includes today, or+ // at the top of the hour window. The record is shared with the suspended+ // fallback's viewport, so a late loader restores the person's own offset+ // instead of positioning again; clock ticks, data, theme, and resizes never+ // reach this effect because the key does not change.+ const sharedScrollMemory = useContext(TimeGridScrollMemoryContext);+ const localScrollMemory = useRef<TimeGridScrollMemory>({+ key: null,+ offset: 0,+ });+ const scrollMemory = sharedScrollMemory ?? localScrollMemory;+ const viewportRef = useRef<HTMLDivElement>(null);+ const rangeKey = useMemo(+ () => ({+ start: range.start,+ end: range.end,+ timezoneID,+ minHour: normalizedMinHour,+ maxHour: normalizedMaxHour,+ hourHeight,+ }),+ [+ hourHeight,+ normalizedMaxHour,+ normalizedMinHour,+ range.end,+ range.start,+ timezoneID,+ ],);+ const positioning = useRef({+ currentTime,+ days,+ minHour: normalizedMinHour,+ hourHeight,+ });+ positioning.current = {+ currentTime,+ days,+ minHour: normalizedMinHour,+ hourHeight,+ };+ const isBlockScrollable = scrollState.block.isScrollable;+ // The clock is 0 only in the server snapshot; wait for the client's.+ const hasClock = currentTime !== 0;+ useLayoutEffect(() => {+ const viewport = viewportRef.current;+ if (viewport == null || !isBlockScrollable || !hasClock) {+ return;+ }+ const memory = scrollMemory.current;+ if (+ memory != null &&+ memory.key != null &&+ isSameRangeKey(memory.key, rangeKey)+ ) {+ if (Math.abs(viewport.scrollTop - memory.offset) > 1) {+ viewport.scrollTop = memory.offset;+ }+ return;+ }+ const offset = getInitialTimeGridOffset({+ ...positioning.current,+ timezoneID,+ scrollHeight: viewport.scrollHeight,+ clientHeight: viewport.clientHeight,+ });+ viewport.scrollTop = offset;+ if (memory != null) {+ memory.key = rangeKey;+ memory.offset = offset;+ }+ }, [hasClock, isBlockScrollable, rangeKey, scrollMemory, timezoneID]);+ const rememberScroll = (event: UIEvent<HTMLDivElement>) => {+ const memory = scrollMemory.current;+ if (+ memory != null &&+ memory.key != null &&+ isSameRangeKey(memory.key, rangeKey)+ ) {+ memory.offset = event.currentTarget.scrollTop;+ }+ };++ const viewportProps = getViewportProps<HTMLDivElement>({+ ref: viewportRef,+ onScroll: rememberScroll,+ ...stylex.props(styles.timeGridViewport, timeGridViewportScope),+ });const contentProps = getContentProps<HTMLDivElement>(stylex.props(styles.timeGridContent(days.length)),);diff --git a/packages/lab/src/Schedule/__tests__/ScheduleTimeGridInitialPosition.a11y.chromium.spec.ts b/packages/lab/src/Schedule/__tests__/ScheduleTimeGridInitialPosition.a11y.chromium.spec.tsnew file mode 100644index 0000000000..c5c77dd996--- /dev/null+++ b/packages/lab/src/Schedule/__tests__/ScheduleTimeGridInitialPosition.a11y.chromium.spec.ts@@ -0,0 +1,164 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file ScheduleTimeGridInitialPosition.a11y.chromium.spec.ts+ * @input The built Lab/Schedule week and day stories in real Chromium with an+ * installed clock+ * @output Receipted scroll offsets proving a range containing today opens one+ * hour before now, clamps at the grid's end, leaves other ranges at their+ * start, and never moves the person's own scroll afterwards+ * @position Browser binding for `component:Schedule` FR4–FR6. jsdom proves the+ * arithmetic against mocked geometry; only a layout engine shows the offset+ * the viewport really lands on.+ */++import {expect, test, type Page} from '@playwright/test';+import {+ DAY,+ finishEvidence,+ HOUR_HEIGHT,+ openStory,+ OVERLAPPING,+ readTimeGrid,+ record,+ setScrollTop,+ startEvidence,+ WEEKLY,+ WIDE,+ type Evidence,+} from './timeGridProbe';++let evidence: Evidence;+test.beforeAll(async () => {+ evidence = await startEvidence();+});+test.afterAll(async () => {+ await finishEvidence(evidence, 'initial-position');+});++async function expectedInitialScrollTop(page: Page) {+ const reading = await readTimeGrid(page);+ const {scroller, nowLine, firstColumnTopInContent} = reading;+ if (scroller == null || nowLine == null || firstColumnTopInContent == null) {+ return {reading, expected: null, max: null};+ }+ const max = scroller.scrollHeight - scroller.clientHeight;+ // The pinned rows above the columns occupy the top of the viewport, so the+ // one-hour lead is measured from the column's own top, not the scroller's.+ const lead = nowLine.topInContent - firstColumnTopInContent - HOUR_HEIGHT;+ const expected = Math.min(max, Math.max(0, lead));+ return {reading, expected, max};+}++test('a week containing today opens one hour before now and stays put', async ({+ page,+}) => {+ // 22:00Z is 15:00 in the story's America/Los_Angeles week (07:00–19:00).+ await page.clock.install({time: new Date('2026-05-13T22:00:00Z')});+ await openStory(evidence, page, WEEKLY, WIDE);+ const {reading, expected, max} = await expectedInitialScrollTop(page);+ await record(+ evidence,+ page,+ 'initial-scroll-week-today',+ WEEKLY,+ reading.direction,+ {+ scrollTop: reading.scroller?.scrollTop,+ expected,+ max,+ nowLineTopInContent: reading.nowLine?.topInContent,+ columnTopInContent: reading.firstColumnTopInContent,+ },+ );+ expect(expected, 'the now-line is painted').not.toBeNull();+ expect(+ Math.abs((reading.scroller?.scrollTop ?? 0) - (expected ?? 0)),+ ).toBeLessThanOrEqual(2);++ // The position is set once per range open: a clock tick, a theme change,+ // and a resize all re-render the grid and leave the person's scroll alone.+ await setScrollTop(page, 123);+ await page.clock.pauseAt(new Date('2026-05-13T22:05:00Z'));+ await page.clock.runFor(61_000);+ await page.evaluate(() => {+ (+ window as unknown as {+ __STORYBOOK_ADDONS_CHANNEL__: {+ emit: (event: string, payload: unknown) => void;+ };+ }+ ).__STORYBOOK_ADDONS_CHANNEL__.emit('updateGlobals', {+ globals: {colorMode: 'dark'},+ });+ });+ await page.setViewportSize({width: 1180, height: 820});+ await page.waitForTimeout(250);+ const afterTick = await readTimeGrid(page);+ await record(+ evidence,+ page,+ 'initial-scroll-week-today-after-tick',+ WEEKLY,+ afterTick.direction,+ {scrollTop: afterTick.scroller?.scrollTop},+ );+ expect(afterTick.scroller?.scrollTop).toBe(123);+});++test('a day containing today opens one hour before now', async ({page}) => {+ // 20:00Z is 13:00 in the story's America/Los_Angeles day (00:00–24:00).+ await page.clock.install({time: new Date('2026-05-13T20:00:00Z')});+ await openStory(evidence, page, DAY, WIDE);+ const {reading, expected, max} = await expectedInitialScrollTop(page);+ await record(+ evidence,+ page,+ 'initial-scroll-day-today',+ DAY,+ reading.direction,+ {scrollTop: reading.scroller?.scrollTop, expected, max},+ );+ expect(expected).not.toBeNull();+ expect(+ Math.abs((reading.scroller?.scrollTop ?? 0) - (expected ?? 0)),+ ).toBeLessThanOrEqual(2);+});++test('near midnight the position clamps to the end of the grid', async ({+ page,+}) => {+ // 06:50Z is 23:50 the previous evening in America/Los_Angeles.+ await page.clock.install({time: new Date('2026-05-14T06:50:00Z')});+ await openStory(evidence, page, DAY, WIDE);+ const {reading, expected, max} = await expectedInitialScrollTop(page);+ await record(+ evidence,+ page,+ 'initial-scroll-day-near-midnight',+ DAY,+ reading.direction,+ {scrollTop: reading.scroller?.scrollTop, expected, max},+ );+ expect(expected).not.toBeNull();+ expect(expected).toBe(max);+ expect(+ Math.abs((reading.scroller?.scrollTop ?? 0) - (expected ?? 0)),+ ).toBeLessThanOrEqual(2);+});++test('a range without today opens at its configured start', async ({page}) => {+ await page.clock.install({time: new Date('2026-06-01T17:00:00Z')});+ await openStory(evidence, page, OVERLAPPING, WIDE);+ const reading = await readTimeGrid(page);+ await record(+ evidence,+ page,+ 'initial-scroll-not-today',+ OVERLAPPING,+ reading.direction,+ {scrollTop: reading.scroller?.scrollTop, nowLine: reading.nowLine},+ );+ expect(reading.nowLine).toBeNull();+ expect(reading.scroller?.scrollTop ?? 0).toBe(0);+});diff --git a/packages/lab/src/Schedule/timeGridScrollMemory.ts b/packages/lab/src/Schedule/timeGridScrollMemory.tsnew file mode 100644index 0000000000..832b3c8a47--- /dev/null+++ b/packages/lab/src/Schedule/timeGridScrollMemory.ts@@ -0,0 +1,94 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file timeGridScrollMemory.ts+ * @input The rendered range, the clock, the hour window, and viewport geometry+ * @output Where a time-grid viewport opens for a range, and the memory that+ * keeps a person's scroll offset for that range across the suspended fallback+ * @position Internal to the time-grid views; Schedule owns the memory above its+ * suspense boundary so the fallback and the loaded content share one record+ */++import {createContext, type RefObject} from 'react';+import {+ plainDateFromInstant,+ plainDateIsEqual,+ type PlainDate,+} from '@astryxdesign/core/utils';+import {getMinutesSinceStartOfDay} from './shared';+import type {Instant} from './types';++/**+ * Identifies one intentional open of a time grid: the range's bounds, the+ * zone, and the hour window the offset was computed for. Object identities+ * are deliberately absent so a caller that rebuilds its view object on every+ * render cannot turn a data refresh into a new open.+ */+export interface TimeGridRangeKey {+ start: Instant;+ end: Instant;+ timezoneID: string;+ minHour: number;+ maxHour: number;+ hourHeight: number;+}++export interface TimeGridScrollMemory {+ key: TimeGridRangeKey | null;+ /** The viewport's last known scroll offset for `key`. */+ offset: number;+}++export const TimeGridScrollMemoryContext =+ createContext<RefObject<TimeGridScrollMemory> | null>(null);++export function isSameRangeKey(+ a: TimeGridRangeKey,+ b: TimeGridRangeKey,+): boolean {+ return (+ a.start === b.start &&+ a.end === b.end &&+ a.timezoneID === b.timezoneID &&+ a.minHour === b.minHour &&+ a.maxHour === b.maxHour &&+ a.hourHeight === b.hourHeight+ );+}++/**+ * The offset a time-grid viewport opens at for a range it has not shown yet:+ * one hour above the current minute when the range's days include today, so+ * what just happened and what is next are both in view; otherwise the top of+ * the configured hour window. Clamped to what the viewport can scroll.+ */+export function getInitialTimeGridOffset({+ currentTime,+ days,+ timezoneID,+ minHour,+ hourHeight,+ scrollHeight,+ clientHeight,+}: {+ currentTime: Instant;+ days: ReadonlyArray<PlainDate>;+ timezoneID: string;+ minHour: number;+ hourHeight: number;+ scrollHeight: number;+ clientHeight: number;+}): number {+ const maxOffset = Math.max(0, scrollHeight - clientHeight);+ const today = plainDateFromInstant(currentTime, timezoneID);+ if (!days.some(day => plainDateIsEqual(day, today))) {+ return 0;+ }+ const currentMinute = getMinutesSinceStartOfDay(currentTime, timezoneID);+ // The now-line sits at `calc(<minutes since minHour>% + 2px)` inside the+ // column; the hour above it is the lead.+ const nowOffset = ((currentMinute - minHour * 60) / 60) * hourHeight + 2;+ return Math.min(maxOffset, Math.max(0, Math.round(nowOffset - hourHeight)));+}