Skip to content

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

TypeScript

fix(lab): lay out simultaneous Schedule events side by side (#6927)

Cindy Zhangfdc76dc240a1
diff --git a/packages/lab/src/Schedule/TimeGridView.tsx b/packages/lab/src/Schedule/TimeGridView.tsx
index 16ad9ef87b..9fbe35c9e2 100644
--- a/packages/lab/src/Schedule/TimeGridView.tsx
+++ b/packages/lab/src/Schedule/TimeGridView.tsx
@@ -44,6 +44,7 @@ import {
isEventInPast,
styles,
} from './shared';
+import {layoutTimedEvents, type TimedEventPlacement} from './timeGridLayout';
import {useCurrentTime} from './useCurrentTime';
import type {
CalendarDayEvent,
@@ -249,44 +250,54 @@ export function TimeGridView({
timezoneID,
minHour: normalizedMinHour,
maxHour: normalizedMaxHour,
- }).map(({event, height, level, top}) => {
- const timeLabel = formatEventTime(
+ }).map(
+ ({
event,
- day,
- timezoneID,
- locale,
- );
- const category = getEventCategory(event, categories);
- return (
- <div
- key={event.id}
- {...stylex.props(
- styles.timedEvent,
- styles.timedEventPosition(
- clamp(top, 0, 100),
- clamp(height, 4, 100),
- level,
- ),
- isEventInPast(event, currentTime, timezoneID)
- ? eventPastSurfaceColorStyle(category.color)
- : eventSurfaceColorStyle(category.color),
- )}>
- <Text
- type="supporting"
- color="inherit"
- weight="bold"
- xstyle={styles.eventTitle}>
- {event.title}
- </Text>
- <Text
- type="supporting"
- color="inherit"
- xstyle={styles.eventTime}>
- {timeLabel}
- </Text>
- </div>
- );
- })}
+ height,
+ top,
+ columnStart,
+ columnSpan,
+ columnCount,
+ }) => {
+ const timeLabel = formatEventTime(
+ event,
+ day,
+ timezoneID,
+ locale,
+ );
+ const category = getEventCategory(event, categories);
+ return (
+ <div
+ key={event.id}
+ {...stylex.props(
+ styles.timedEvent,
+ styles.timedEventPosition(
+ clamp(top, 0, 100),
+ clamp(height, 4, 100),
+ (columnStart / columnCount) * 100,
+ (columnSpan / columnCount) * 100,
+ ),
+ isEventInPast(event, currentTime, timezoneID)
+ ? eventPastSurfaceColorStyle(category.color)
+ : eventSurfaceColorStyle(category.color),
+ )}>
+ <Text
+ type="supporting"
+ color="inherit"
+ weight="bold"
+ xstyle={styles.eventTitle}>
+ {event.title}
+ </Text>
+ <Text
+ type="supporting"
+ color="inherit"
+ xstyle={styles.eventTime}>
+ {timeLabel}
+ </Text>
+ </div>
+ );
+ },
+ )}
{plainDateIsEqual(day, currentDate) &&
currentTimeTop != null && (
<div
@@ -514,13 +525,6 @@ function getAvailableAllDayLevel(
return level >= 0 ? level : levels.length;
}
-interface TimedEventLayout {
- event: CalendarInstantEvent;
- top: number;
- height: number;
- level: number;
-}
-
function getTimedEventLayouts({
events,
day,
@@ -533,69 +537,26 @@ function getTimedEventLayouts({
timezoneID: string;
minHour: number;
maxHour: number;
-}): TimedEventLayout[] {
- const totalMinutes = (maxHour - minHour) * 60;
- const levelEndMinutes: number[] = [];
-
- return events
- .map(event => {
- const startDate = plainDateFromInstant(event.start, timezoneID);
- const rawStart = plainDateIsBefore(startDate, day)
- ? 0
- : getMinutesSinceStartOfDay(event.start, timezoneID);
- const rawEnd = eventSpansPastDay(event, day, timezoneID)
- ? 24 * 60
- : getMinutesSinceStartOfDay(event.end, timezoneID);
- const minMinute = minHour * 60;
- const maxMinute = maxHour * 60;
- if (rawEnd <= minMinute || rawStart >= maxMinute) {
- return null;
- }
- const visibleStart = Math.max(rawStart, minMinute);
- const visibleEnd = Math.min(
- maxMinute,
- Math.max(visibleStart + 15, rawEnd),
- );
- return {event, visibleStart, visibleEnd};
- })
- .filter(
- (
- layout,
- ): layout is {
- event: CalendarInstantEvent;
- visibleStart: number;
- visibleEnd: number;
- } => layout != null && layout.visibleEnd > layout.visibleStart,
- )
- .sort((a, b) => {
- if (a.visibleStart !== b.visibleStart) {
- return a.visibleStart - b.visibleStart;
- }
- return (
- a.visibleEnd - b.visibleEnd ||
- a.event.title.localeCompare(b.event.title)
- );
- })
- .map(({event, visibleEnd, visibleStart}) => {
- const level = getAvailableTimedEventLevel(levelEndMinutes, visibleStart);
- levelEndMinutes[level] = visibleEnd;
- return {
- event,
- level,
- top: ((visibleStart - minHour * 60) / totalMinutes) * 100,
- height: ((visibleEnd - visibleStart) / totalMinutes) * 100,
- };
- });
-}
-
-function getAvailableTimedEventLevel(
- levelEndMinutes: number[],
- visibleStart: number,
-): number {
- const level = levelEndMinutes.findIndex(
- endMinute => visibleStart >= endMinute,
- );
- return level >= 0 ? level : levelEndMinutes.length;
+}): TimedEventPlacement<CalendarInstantEvent>[] {
+ const minMinute = minHour * 60;
+ const maxMinute = maxHour * 60;
+ const intervals = events.flatMap(event => {
+ const startDate = plainDateFromInstant(event.start, timezoneID);
+ const rawStart = plainDateIsBefore(startDate, day)
+ ? 0
+ : getMinutesSinceStartOfDay(event.start, timezoneID);
+ const rawEnd = eventSpansPastDay(event, day, timezoneID)
+ ? 24 * 60
+ : getMinutesSinceStartOfDay(event.end, timezoneID);
+ if (rawEnd <= minMinute || rawStart >= maxMinute) {
+ return [];
+ }
+ const visibleStart = Math.max(rawStart, minMinute);
+ // A block is at least fifteen minutes tall so a short event stays legible.
+ const visibleEnd = Math.min(maxMinute, Math.max(visibleStart + 15, rawEnd));
+ return visibleEnd > visibleStart ? [{event, visibleStart, visibleEnd}] : [];
+ });
+ return layoutTimedEvents(intervals, minMinute, maxMinute);
}
function getCurrentTimeTop({
diff --git a/packages/lab/src/Schedule/__tests__/ScheduleTimeGridOverlap.a11y.chromium.spec.ts b/packages/lab/src/Schedule/__tests__/ScheduleTimeGridOverlap.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..229979bc64
--- /dev/null
+++ b/packages/lab/src/Schedule/__tests__/ScheduleTimeGridOverlap.a11y.chromium.spec.ts
@@ -0,0 +1,220 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ScheduleTimeGridOverlap.a11y.chromium.spec.ts
+ * @input The built Lab/Schedule overlapping-events fixture week in real Chromium
+ * @output Receipted paint rectangles proving simultaneous events sit side by
+ * side inside an isolated day column, with nothing covered or dropped
+ * @position Browser binding for `component:Schedule` FR7–FR10. The layout
+ * model is unit-tested in jsdom; whether the painted blocks actually overlap
+ * is a question only a layout engine can answer.
+ */
+
+import {expect, test} from '@playwright/test';
+import {
+ blockOverlap,
+ finishEvidence,
+ openStory,
+ OVERLAPPING,
+ readBlocks,
+ record,
+ startEvidence,
+ WIDE,
+ type BlockReading,
+ type Evidence,
+} from './timeGridProbe';
+
+let evidence: Evidence;
+test.beforeAll(async () => {
+ evidence = await startEvidence();
+});
+test.afterAll(async () => {
+ await finishEvidence(evidence, 'overlap');
+});
+
+const simultaneousGroups: ReadonlyArray<{name: string; titles: string[]}> = [
+ {name: 'two-tie', titles: ['Pair review', 'Pair review']},
+ {
+ name: 'three',
+ titles: ['Interview loop 1', 'Interview loop 2', 'Interview loop 3'],
+ },
+ {
+ name: 'five',
+ titles: [
+ 'Office hours A',
+ 'Office hours B',
+ 'Office hours C',
+ 'Office hours D',
+ 'Office hours E',
+ ],
+ },
+];
+const chain = ['Standup', 'Design sync', 'Retro'];
+const contained = ['Workshop', 'Coffee chat'];
+
+function coveredPercent(a: BlockReading, b: BlockReading): number {
+ const smaller = Math.min(
+ a.box.width * a.box.height,
+ b.box.width * b.box.height,
+ );
+ return smaller === 0
+ ? 0
+ : Math.round((blockOverlap(a.box, b.box) / smaller) * 100);
+}
+
+test('simultaneous events sit side by side and never cover one another', async ({
+ page,
+}) => {
+ await openStory(evidence, page, OVERLAPPING, WIDE);
+ const titles = [
+ ...simultaneousGroups.flatMap(group => group.titles),
+ ...chain,
+ ...contained,
+ 'Quick check-in',
+ ];
+ const blocks = await readBlocks(page, titles);
+ const byTitle = (title: string) =>
+ blocks.filter(block => block.title === title);
+
+ const groupResults = simultaneousGroups.map(group => {
+ const members = [...new Set(group.titles.flatMap(title => byTitle(title)))];
+ const pairs: Array<{a: string; b: string; coveredPercent: number}> = [];
+ for (let i = 0; i < members.length; i += 1) {
+ for (let j = i + 1; j < members.length; j += 1) {
+ pairs.push({
+ a: members[i].title,
+ b: members[j].title,
+ coveredPercent: coveredPercent(members[i], members[j]),
+ });
+ }
+ }
+ return {
+ name: group.name,
+ found: members.length,
+ expected: group.titles.length,
+ widths: members.map(block => Math.round(block.box.width)),
+ pairs,
+ isolation: members.map(block => block.columnIsolation),
+ };
+ });
+ const chainBlocks = chain.map(title => byTitle(title)[0]).filter(Boolean);
+ const containedBlocks = contained
+ .map(title => byTitle(title)[0])
+ .filter(Boolean);
+ const quarter = byTitle('Quick check-in')[0];
+ const measured = {
+ groups: groupResults,
+ chain:
+ chainBlocks.length === 3
+ ? {
+ standupVsDesignSyncPercent: coveredPercent(
+ chainBlocks[0],
+ chainBlocks[1],
+ ),
+ designSyncVsRetroPercent: coveredPercent(
+ chainBlocks[1],
+ chainBlocks[2],
+ ),
+ }
+ : null,
+ contained:
+ containedBlocks.length === 2
+ ? {
+ coffeeChatCoveredPercent: Math.round(
+ (blockOverlap(containedBlocks[0].box, containedBlocks[1].box) /
+ (containedBlocks[1].box.width *
+ containedBlocks[1].box.height)) *
+ 100,
+ ),
+ }
+ : null,
+ quarterHourHeight: quarter == null ? null : Math.round(quarter.box.height),
+ };
+ await record(
+ evidence,
+ page,
+ 'overlap-side-by-side',
+ OVERLAPPING,
+ 'ltr',
+ measured,
+ );
+
+ for (const group of groupResults) {
+ expect(group.found, `${group.name}: every event is painted`).toBe(
+ group.expected,
+ );
+ for (const width of group.widths) {
+ expect(
+ width,
+ `${group.name}: a block keeps a perceivable width`,
+ ).toBeGreaterThanOrEqual(16);
+ }
+ for (const pair of group.pairs) {
+ expect(
+ pair.coveredPercent,
+ `${group.name}: ${pair.a} vs ${pair.b} covered`,
+ ).toBeLessThanOrEqual(2);
+ }
+ for (const isolation of group.isolation) {
+ expect(
+ isolation,
+ `${group.name}: the column isolates its paint order`,
+ ).toBe('isolate');
+ }
+ }
+ expect(measured.chain).not.toBeNull();
+ expect(measured.chain?.standupVsDesignSyncPercent).toBeLessThanOrEqual(2);
+ expect(measured.chain?.designSyncVsRetroPercent).toBeLessThanOrEqual(2);
+ expect(measured.contained).not.toBeNull();
+ expect(measured.contained?.coffeeChatCoveredPercent).toBeLessThanOrEqual(2);
+ expect(measured.quarterHourHeight ?? 0).toBeGreaterThanOrEqual(20);
+});
+
+test('narrow tracks keep the title and drop the time line', async ({page}) => {
+ await openStory(evidence, page, OVERLAPPING, WIDE);
+ const readings = await page.evaluate(() => {
+ const root = document.querySelector<HTMLElement>('.astryx-schedule');
+ const leaves = [...(root?.querySelectorAll<HTMLElement>('*') ?? [])].filter(
+ element =>
+ element.children.length === 0 &&
+ /^Office hours [A-E]$/.test(element.textContent?.trim() ?? ''),
+ );
+ return leaves.map(title => {
+ let block: HTMLElement | null = title;
+ while (block != null && getComputedStyle(block).position !== 'absolute') {
+ block = block.parentElement;
+ }
+ const time = [...(block?.querySelectorAll<HTMLElement>('*') ?? [])].find(
+ element =>
+ element !== title &&
+ element.children.length === 0 &&
+ /\d/.test(element.textContent ?? ''),
+ );
+ return {
+ title: title.textContent?.trim(),
+ blockWidth:
+ block == null
+ ? null
+ : Math.round(block.getBoundingClientRect().width),
+ titleVisible:
+ getComputedStyle(title).display !== 'none' &&
+ title.getBoundingClientRect().height > 0,
+ timeDisplay: time == null ? null : getComputedStyle(time).display,
+ };
+ });
+ });
+ await record(evidence, page, 'overlap-narrow-tracks', OVERLAPPING, 'ltr', {
+ readings,
+ });
+ expect(readings).toHaveLength(5);
+ for (const reading of readings) {
+ expect(reading.titleVisible, `${reading.title} title stays`).toBe(true);
+ // Five tracks in a 140px column are ~24px each: below the time label's
+ // room, so the time line is gone rather than squeezing the title.
+ if ((reading.blockWidth ?? 0) <= 72) {
+ expect(reading.timeDisplay, `${reading.title} time line collapses`).toBe(
+ 'none',
+ );
+ }
+ }
+});
diff --git a/packages/lab/src/Schedule/shared.tsx b/packages/lab/src/Schedule/shared.tsx
index ac7f8a8331..51ece65e72 100644
--- a/packages/lab/src/Schedule/shared.tsx
+++ b/packages/lab/src/Schedule/shared.tsx
@@ -803,6 +803,10 @@ export const styles = stylex.create({
minWidth: 0,
},
eventTime: {
+ display: {
+ default: 'block',
+ '@container (max-width: 72px)': 'none',
+ },
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
@@ -1065,6 +1069,9 @@ export const styles = stylex.create({
minHeight: '24px',
minWidth: 0,
overflow: 'hidden',
+ // The block is a container so a narrow track can drop its time line
+ // (eventTime below) while the title keeps its single ellipsized line.
+ containerType: 'inline-size',
borderWidth: borderVars['--border-width'],
borderStyle: 'solid',
borderRadius: radiusVars['--radius-inner'],
@@ -1075,15 +1082,19 @@ export const styles = stylex.create({
lineHeight: typeScaleVars['--text-supporting-leading'],
fontWeight: fontWeightVars['--font-weight-medium'],
},
- timedEventPosition: (top: number, height: number, level: number) => ({
+ // Blocks in one overlap cluster split the column into equal tracks and never
+ // overlap, so they carry no z-index of their own; the 2px insets keep the
+ // same gutter a lone block has at the column's edges.
+ timedEventPosition: (
+ top: number,
+ height: number,
+ inlineStart: number,
+ inlineSize: number,
+ ) => ({
top: `calc(${top}% + 2px)`,
height: `calc(${height}% - 5px)`,
- insetInlineStart:
- level === 0
- ? spacingVars['--spacing-0-5']
- : `calc(${spacingVars['--spacing-0-5']} + ${level * 8}%)`,
- insetInlineEnd: spacingVars['--spacing-0-5'],
- zIndex: level + 1,
+ insetInlineStart: `calc(${inlineStart}% + ${spacingVars['--spacing-0-5']})`,
+ inlineSize: `calc(${inlineSize}% - ${spacingVars['--spacing-0-5']} * 2)`,
}),
currentTimeLine: (top: number) => ({
position: 'absolute',
@@ -1092,7 +1103,8 @@ export const styles = stylex.create({
borderTopWidth: '2px',
borderTopStyle: 'solid',
borderTopColor: colorVars['--color-border-orange'],
- zIndex: 20,
+ // Local to the isolated day column: above its blocks, nothing else.
+ zIndex: 1,
pointerEvents: 'none',
'::before': {
content: '""',
diff --git a/packages/lab/src/Schedule/timeGridLayout.test.ts b/packages/lab/src/Schedule/timeGridLayout.test.ts
new file mode 100644
index 0000000000..2a7fefaad4
--- /dev/null
+++ b/packages/lab/src/Schedule/timeGridLayout.test.ts
@@ -0,0 +1,216 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, it} from 'vitest';
+import {layoutTimedEvents, type TimedEventInterval} from './timeGridLayout';
+
+interface Item {
+ id: string;
+}
+
+function interval(
+ id: string,
+ visibleStart: number,
+ visibleEnd: number,
+): TimedEventInterval<Item> {
+ return {event: {id}, visibleStart, visibleEnd};
+}
+
+function placementsById(intervals: ReadonlyArray<TimedEventInterval<Item>>) {
+ return Object.fromEntries(
+ layoutTimedEvents(intervals, 8 * 60, 18 * 60).map(placement => [
+ placement.event.id,
+ {
+ top: placement.top,
+ height: placement.height,
+ columnStart: placement.columnStart,
+ columnSpan: placement.columnSpan,
+ columnCount: placement.columnCount,
+ },
+ ]),
+ );
+}
+
+describe('layoutTimedEvents', () => {
+ it('gives a lone event the whole column', () => {
+ expect(placementsById([interval('a', 9 * 60, 10 * 60)])).toEqual({
+ a: {top: 10, height: 10, columnStart: 0, columnSpan: 1, columnCount: 1},
+ });
+ });
+
+ it('splits an exact tie into two equal columns ordered by id', () => {
+ const placements = placementsById([
+ interval('tie-b', 9 * 60, 10 * 60),
+ interval('tie-a', 9 * 60, 10 * 60),
+ ]);
+ expect(placements['tie-a']).toMatchObject({
+ columnStart: 0,
+ columnSpan: 1,
+ columnCount: 2,
+ });
+ expect(placements['tie-b']).toMatchObject({
+ columnStart: 1,
+ columnSpan: 1,
+ columnCount: 2,
+ });
+ });
+
+ it('places three and five simultaneous events side by side', () => {
+ const three = placementsById([
+ interval('1', 13 * 60, 14 * 60),
+ interval('2', 13 * 60, 14 * 60),
+ interval('3', 13 * 60, 14 * 60),
+ ]);
+ expect(
+ Object.values(three)
+ .map(p => p.columnStart)
+ .sort(),
+ ).toEqual([0, 1, 2]);
+ expect(Object.values(three).every(p => p.columnCount === 3)).toBe(true);
+ expect(Object.values(three).every(p => p.columnSpan === 1)).toBe(true);
+
+ const five = placementsById(
+ ['1', '2', '3', '4', '5'].map(id => interval(id, 10 * 60, 11 * 60)),
+ );
+ expect(
+ Object.values(five)
+ .map(p => p.columnStart)
+ .sort(),
+ ).toEqual([0, 1, 2, 3, 4]);
+ expect(Object.values(five).every(p => p.columnCount === 5)).toBe(true);
+ });
+
+ it('is independent of input order', () => {
+ const items = [
+ interval('standup', 9 * 60, 10 * 60),
+ interval('design-sync', 9 * 60 + 30, 10 * 60 + 30),
+ interval('retro', 10 * 60, 11 * 60),
+ interval('workshop', 13 * 60, 16 * 60),
+ interval('coffee', 14 * 60, 14 * 60 + 30),
+ interval('tie-a', 12 * 60, 12 * 60 + 30),
+ interval('tie-b', 12 * 60, 12 * 60 + 30),
+ ];
+ const forward = placementsById(items);
+ const reversed = placementsById([...items].reverse());
+ const shuffled = placementsById([
+ items[4],
+ items[6],
+ items[0],
+ items[3],
+ items[2],
+ items[5],
+ items[1],
+ ]);
+ expect(reversed).toEqual(forward);
+ expect(shuffled).toEqual(forward);
+ });
+
+ it('keeps a chain in one cluster and lets its ends share a column', () => {
+ const placements = placementsById([
+ interval('standup', 9 * 60, 10 * 60),
+ interval('design-sync', 9 * 60 + 30, 10 * 60 + 30),
+ interval('retro', 10 * 60, 11 * 60),
+ ]);
+ // Standup and Retro never meet, so Retro reuses Standup's column; the
+ // cluster is two columns wide because Design sync overlaps both.
+ expect(placements.standup).toMatchObject({
+ columnStart: 0,
+ columnSpan: 1,
+ columnCount: 2,
+ });
+ expect(placements['design-sync']).toMatchObject({
+ columnStart: 1,
+ columnSpan: 1,
+ columnCount: 2,
+ });
+ expect(placements.retro).toMatchObject({
+ columnStart: 0,
+ columnSpan: 1,
+ columnCount: 2,
+ });
+ });
+
+ it('lays a contained event beside its container instead of over it', () => {
+ const placements = placementsById([
+ interval('coffee', 10 * 60, 10 * 60 + 30),
+ interval('workshop', 9 * 60, 12 * 60),
+ ]);
+ expect(placements.workshop).toMatchObject({
+ columnStart: 0,
+ columnSpan: 1,
+ columnCount: 2,
+ });
+ expect(placements.coffee).toMatchObject({
+ columnStart: 1,
+ columnSpan: 1,
+ columnCount: 2,
+ });
+ });
+
+ it('widens a block into following columns nothing occupies during its minutes', () => {
+ const placements = placementsById([
+ interval('a', 9 * 60, 10 * 60),
+ interval('b', 9 * 60, 10 * 60),
+ interval('c', 9 * 60 + 30, 11 * 60),
+ interval('d', 10 * 60, 11 * 60),
+ ]);
+ // d starts as a ends, so it takes column 0; column 1 (b) is free during
+ // its minutes, column 2 (c) is not, so it spans two of the three tracks.
+ expect(placements.a).toMatchObject({
+ columnStart: 0,
+ columnSpan: 1,
+ columnCount: 3,
+ });
+ expect(placements.b).toMatchObject({
+ columnStart: 1,
+ columnSpan: 1,
+ columnCount: 3,
+ });
+ expect(placements.c).toMatchObject({
+ columnStart: 2,
+ columnSpan: 1,
+ columnCount: 3,
+ });
+ expect(placements.d).toMatchObject({
+ columnStart: 0,
+ columnSpan: 2,
+ columnCount: 3,
+ });
+ });
+
+ it('starts a new cluster once every earlier event has ended', () => {
+ const placements = placementsById([
+ interval('morning-a', 9 * 60, 10 * 60),
+ interval('morning-b', 9 * 60, 10 * 60),
+ interval('afternoon', 15 * 60, 16 * 60),
+ ]);
+ expect(placements.afternoon).toMatchObject({
+ columnStart: 0,
+ columnSpan: 1,
+ columnCount: 1,
+ });
+ });
+
+ it('never lets two blocks in a cluster occupy the same track at the same time', () => {
+ const items = Array.from({length: 12}, (_, index) =>
+ interval(`e${index}`, 9 * 60 + index * 20, 9 * 60 + index * 20 + 50),
+ );
+ const placements = layoutTimedEvents(items, 8 * 60, 18 * 60);
+ for (const a of placements) {
+ for (const b of placements) {
+ if (a === b) {
+ continue;
+ }
+ const aStart = a.top;
+ const aEnd = a.top + a.height;
+ const bStart = b.top;
+ const bEnd = b.top + b.height;
+ const timeOverlap = aStart < bEnd && bStart < aEnd;
+ const aColEnd = a.columnStart + a.columnSpan;
+ const bColEnd = b.columnStart + b.columnSpan;
+ const columnOverlap =
+ a.columnStart < bColEnd && b.columnStart < aColEnd;
+ expect(timeOverlap && columnOverlap).toBe(false);
+ }
+ }
+ });
+});
diff --git a/packages/lab/src/Schedule/timeGridLayout.ts b/packages/lab/src/Schedule/timeGridLayout.ts
new file mode 100644
index 0000000000..f63835306e
--- /dev/null
+++ b/packages/lab/src/Schedule/timeGridLayout.ts
@@ -0,0 +1,119 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file timeGridLayout.ts
+ * @input Timed events already clipped to a day column's visible minutes
+ * @output Deterministic side-by-side placement: vertical extent as a share of
+ * the visible minutes, and a column start and span inside each overlap cluster
+ * @position Pure layout model for the time grid; no DOM, no dates, no styling
+ *
+ * Two events share a cluster when their minutes intersect directly or through a
+ * chain of intersecting events. Inside a cluster every event takes the first
+ * column whose last occupant has ended, then widens into the following columns
+ * that nothing occupies during its own minutes. Ordering is by start, then
+ * longer first, then `id`, so the same events produce the same layout in any
+ * input order and nothing depends on paint order.
+ */
+
+export interface TimedEventInterval<Event extends {id: string}> {
+ event: Event;
+ /** Minutes since the start of the day, after clipping to the visible window. */
+ visibleStart: number;
+ visibleEnd: number;
+}
+
+export interface TimedEventPlacement<Event extends {id: string}> {
+ event: Event;
+ /** Block-axis offset as a percentage of the visible minutes. */
+ top: number;
+ /** Block-axis size as a percentage of the visible minutes. */
+ height: number;
+ /** Zero-based column inside the event's overlap cluster. */
+ columnStart: number;
+ /** Columns the block widens across, including its own. */
+ columnSpan: number;
+ /** Columns in the event's overlap cluster. */
+ columnCount: number;
+}
+
+function compareIntervals<Event extends {id: string}>(
+ a: TimedEventInterval<Event>,
+ b: TimedEventInterval<Event>,
+): number {
+ if (a.visibleStart !== b.visibleStart) {
+ return a.visibleStart - b.visibleStart;
+ }
+ if (a.visibleEnd !== b.visibleEnd) {
+ return b.visibleEnd - a.visibleEnd;
+ }
+ return a.event.id < b.event.id ? -1 : a.event.id > b.event.id ? 1 : 0;
+}
+
+function overlaps<Event extends {id: string}>(
+ a: TimedEventInterval<Event>,
+ b: TimedEventInterval<Event>,
+): boolean {
+ return a.visibleStart < b.visibleEnd && b.visibleStart < a.visibleEnd;
+}
+
+export function layoutTimedEvents<Event extends {id: string}>(
+ intervals: ReadonlyArray<TimedEventInterval<Event>>,
+ minMinute: number,
+ maxMinute: number,
+): TimedEventPlacement<Event>[] {
+ const totalMinutes = Math.max(1, maxMinute - minMinute);
+ const sorted = [...intervals].sort(compareIntervals);
+
+ const clusters: TimedEventInterval<Event>[][] = [];
+ let clusterEnd = Number.NEGATIVE_INFINITY;
+ for (const interval of sorted) {
+ const current = clusters[clusters.length - 1];
+ if (current == null || interval.visibleStart >= clusterEnd) {
+ clusters.push([interval]);
+ clusterEnd = interval.visibleEnd;
+ } else {
+ current.push(interval);
+ clusterEnd = Math.max(clusterEnd, interval.visibleEnd);
+ }
+ }
+
+ const placements: TimedEventPlacement<Event>[] = [];
+ for (const cluster of clusters) {
+ const columns: TimedEventInterval<Event>[][] = [];
+ const columnOf = new Map<TimedEventInterval<Event>, number>();
+ for (const interval of cluster) {
+ let column = columns.findIndex(occupants => {
+ const last = occupants[occupants.length - 1];
+ return last.visibleEnd <= interval.visibleStart;
+ });
+ if (column < 0) {
+ column = columns.length;
+ columns.push([]);
+ }
+ columns[column].push(interval);
+ columnOf.set(interval, column);
+ }
+
+ for (const interval of cluster) {
+ const columnStart = columnOf.get(interval) ?? 0;
+ let columnSpan = 1;
+ for (let next = columnStart + 1; next < columns.length; next += 1) {
+ if (columns[next].some(occupant => overlaps(occupant, interval))) {
+ break;
+ }
+ columnSpan += 1;
+ }
+ placements.push({
+ event: interval.event,
+ top: ((interval.visibleStart - minMinute) / totalMinutes) * 100,
+ height:
+ ((interval.visibleEnd - interval.visibleStart) / totalMinutes) * 100,
+ columnStart,
+ columnSpan,
+ columnCount: columns.length,
+ });
+ }
+ }
+
+ return placements;
+}