@oaiz/app-kit 0.0.0-stage → 0.1.4128

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +143 -2
  3. package/THIRD_PARTY_NOTICES.md +76 -0
  4. package/package.json +139 -4
  5. package/registry.json +1847 -0
  6. package/src/components/activity-timeline.tsx +227 -0
  7. package/src/components/app-shell.tsx +622 -0
  8. package/src/components/bar-list.tsx +47 -0
  9. package/src/components/board.tsx +700 -0
  10. package/src/components/calendar-view.tsx +1388 -0
  11. package/src/components/card-grid.tsx +462 -0
  12. package/src/components/charts.tsx +701 -0
  13. package/src/components/chat-markdown.tsx +230 -0
  14. package/src/components/chat-panel.tsx +760 -0
  15. package/src/components/code-editor.tsx +276 -0
  16. package/src/components/collection-controls.tsx +226 -0
  17. package/src/components/command-palette.tsx +403 -0
  18. package/src/components/confirm-action.tsx +123 -0
  19. package/src/components/data-table.tsx +821 -0
  20. package/src/components/date-input.tsx +429 -0
  21. package/src/components/empty-state.tsx +31 -0
  22. package/src/components/error-state.tsx +37 -0
  23. package/src/components/file-upload.tsx +595 -0
  24. package/src/components/filter-bar.tsx +415 -0
  25. package/src/components/grouped-picker.tsx +250 -0
  26. package/src/components/line-items.tsx +601 -0
  27. package/src/components/list-view.tsx +491 -0
  28. package/src/components/metrics.tsx +53 -0
  29. package/src/components/page-header.tsx +33 -0
  30. package/src/components/property-picker.tsx +546 -0
  31. package/src/components/record-detail.tsx +416 -0
  32. package/src/components/record-form.tsx +295 -0
  33. package/src/components/record-name.tsx +85 -0
  34. package/src/components/save-bar.tsx +142 -0
  35. package/src/components/sign-in.tsx +179 -0
  36. package/src/components/split-view.tsx +128 -0
  37. package/src/components/status-dot.tsx +56 -0
  38. package/src/components/stepper.tsx +153 -0
  39. package/src/components/text-diff-model.ts +111 -0
  40. package/src/components/text-diff.tsx +98 -0
  41. package/src/components/time-zone-picker.tsx +69 -0
  42. package/src/components/ui/accordion.tsx +138 -0
  43. package/src/components/ui/alert-dialog.tsx +67 -0
  44. package/src/components/ui/alert.tsx +65 -0
  45. package/src/components/ui/avatar-group.tsx +119 -0
  46. package/src/components/ui/avatar.tsx +55 -0
  47. package/src/components/ui/badge.tsx +59 -0
  48. package/src/components/ui/bottom-navigation.tsx +102 -0
  49. package/src/components/ui/breadcrumb.tsx +117 -0
  50. package/src/components/ui/button.tsx +71 -0
  51. package/src/components/ui/card.tsx +95 -0
  52. package/src/components/ui/checkbox.tsx +31 -0
  53. package/src/components/ui/collapsible.tsx +27 -0
  54. package/src/components/ui/context-menu.tsx +270 -0
  55. package/src/components/ui/count-up.tsx +136 -0
  56. package/src/components/ui/detail-disclosure-section.tsx +109 -0
  57. package/src/components/ui/dialog.tsx +157 -0
  58. package/src/components/ui/dropdown-menu.tsx +273 -0
  59. package/src/components/ui/form-field.tsx +155 -0
  60. package/src/components/ui/heading.tsx +126 -0
  61. package/src/components/ui/hover-card.tsx +45 -0
  62. package/src/components/ui/input.tsx +50 -0
  63. package/src/components/ui/label.tsx +30 -0
  64. package/src/components/ui/orb-spinner.tsx +238 -0
  65. package/src/components/ui/popover.tsx +59 -0
  66. package/src/components/ui/progress-ring.tsx +125 -0
  67. package/src/components/ui/progress.tsx +38 -0
  68. package/src/components/ui/radio-group.tsx +124 -0
  69. package/src/components/ui/resizable.tsx +48 -0
  70. package/src/components/ui/scroll-fade.tsx +98 -0
  71. package/src/components/ui/segmented-control.tsx +70 -0
  72. package/src/components/ui/select.tsx +230 -0
  73. package/src/components/ui/separator.tsx +29 -0
  74. package/src/components/ui/sheet.tsx +170 -0
  75. package/src/components/ui/shimmer-text.tsx +87 -0
  76. package/src/components/ui/shortcut.tsx +39 -0
  77. package/src/components/ui/skeleton.tsx +15 -0
  78. package/src/components/ui/slider.tsx +48 -0
  79. package/src/components/ui/switch.tsx +44 -0
  80. package/src/components/ui/table.tsx +119 -0
  81. package/src/components/ui/tabs.tsx +80 -0
  82. package/src/components/ui/text.tsx +93 -0
  83. package/src/components/ui/textarea.tsx +51 -0
  84. package/src/components/ui/toast.tsx +141 -0
  85. package/src/components/ui/toaster.tsx +40 -0
  86. package/src/components/ui/tooltip.tsx +38 -0
  87. package/src/components/ui/top-banner.tsx +108 -0
  88. package/src/components/ui/tree-view.tsx +215 -0
  89. package/src/components/ui/use-toast.tsx +184 -0
  90. package/src/components/ui/voice-orb.tsx +252 -0
  91. package/src/hooks/oaiz-chat.tsx +530 -0
  92. package/src/hooks/oaiz-data.tsx +617 -0
  93. package/src/hooks/oaiz-session.tsx +63 -0
  94. package/src/hooks/use-arrivals.ts +19 -0
  95. package/src/hooks/use-breakpoint.ts +100 -0
  96. package/src/hooks/use-media-query.ts +36 -0
  97. package/src/hooks/use-theme.ts +67 -0
  98. package/src/hooks/use-url-state.ts +77 -0
  99. package/src/lib/breakpoints.ts +81 -0
  100. package/src/lib/csp-nonce.ts +15 -0
  101. package/src/lib/format.ts +291 -0
  102. package/src/lib/speech-level.ts +118 -0
  103. package/src/lib/utils.ts +109 -0
  104. package/src/styles/oaiz/app.css +21 -0
  105. package/src/styles/oaiz/scrollbars.css +20 -0
  106. package/src/styles/oaiz/tokens.css +952 -0
  107. package/src/styles/oaiz/voice-orb.css +39 -0
@@ -0,0 +1,1388 @@
1
+ import {
2
+ createContext,
3
+ useContext,
4
+ useEffect,
5
+ useId,
6
+ useLayoutEffect,
7
+ useRef,
8
+ useState,
9
+ type KeyboardEvent,
10
+ type MouseEvent,
11
+ type ReactNode,
12
+ } from 'react';
13
+ import { Plus } from 'lucide-react';
14
+ import { Temporal } from 'temporal-polyfill';
15
+
16
+ import { useBreakpointBelow } from '../hooks/use-breakpoint';
17
+ import {
18
+ formatDate,
19
+ formatDay,
20
+ formatTime,
21
+ formatWeekday,
22
+ localDay,
23
+ parseLocalDay,
24
+ } from '../lib/format';
25
+ import { cn } from '../lib/utils';
26
+ import { EmptyState } from './empty-state';
27
+ import { ErrorState } from './error-state';
28
+ import { TimeInput } from './date-input';
29
+ import { Button } from './ui/button';
30
+ import { Heading } from './ui/heading';
31
+ import { Popover, PopoverContent, PopoverTrigger } from './ui/popover';
32
+ import { Skeleton } from './ui/skeleton';
33
+ import { Text } from './ui/text';
34
+ import { Label } from './ui/label';
35
+ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';
36
+
37
+ /** A day of the member's own calendar as `YYYY-MM-DD`, as `localDay()` writes it. */
38
+ export type CalendarDay = string;
39
+
40
+ export type CalendarEvent = {
41
+ id: string | number;
42
+ title: string;
43
+ /** When it starts: a `Date`, or an ISO timestamp such as a `timestamptz` column holds. */
44
+ start: Date | string;
45
+ /** When it ends. An all-day event ends at the midnight after its last day. */
46
+ end: Date | string;
47
+ allDay?: boolean;
48
+ /** Its colour, one of the theme's five chart colours from 0; give each resource or person one. */
49
+ color?: number;
50
+ /** A second line, such as the room or the person. */
51
+ detail?: string;
52
+ };
53
+
54
+ export type CalendarViewProps = {
55
+ /** What the grid is of, such as "Bookings"; the grid's accessible name. */
56
+ label: string;
57
+ view: 'month' | 'week';
58
+ locale?: string;
59
+ /** IANA timezone used for event dates and times; defaults to the browser's timezone. */
60
+ timeZone?: string;
61
+ weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6;
62
+ messages?: Partial<CalendarMessages>;
63
+ onRetry?: () => void;
64
+ /** A day of the month or week on screen. */
65
+ date: CalendarDay;
66
+ events: CalendarEvent[];
67
+ /**
68
+ * A click on a day's free space, Enter on a focused day, or a click on an hour of the week view,
69
+ * which also passes that hour as `HH:MM`.
70
+ */
71
+ onSelectDay?: (day: CalendarDay, time?: string) => void;
72
+ onSelectEvent?: (event: CalendarEvent) => void;
73
+ /** The arrow keys left the month on screen: show the month of `day`. */
74
+ onDateChange?: (day: CalendarDay) => void;
75
+ /** The accessible name of a button that selects a day, such as "Book on Monday 9 November". */
76
+ selectDayLabel?: (day: CalendarDay) => string;
77
+ /** `auto` lists the days as an agenda on a phone and draws the grid on a wider screen. */
78
+ layout?: 'auto' | 'grid' | 'agenda';
79
+ onLayoutChange?: (layout: 'grid' | 'agenda') => void;
80
+ showLayoutControl?: boolean;
81
+ /** The most events a month day shows before "+N more". */
82
+ maxPerDay?: number;
83
+ loading?: boolean;
84
+ error?: { message: string } | null;
85
+ /** What the agenda shows when no event falls in the period. */
86
+ empty?: ReactNode;
87
+ /** The day marked as today; the member's today when omitted. */
88
+ today?: CalendarDay;
89
+ className?: string;
90
+ };
91
+
92
+ // ---------------------------------------------------------------------------------------------
93
+ // Date maths on local calendar days. Each step goes through `new Date(year, month, day)`, so a day
94
+ // is always a calendar day of the member's zone, also across a daylight saving change.
95
+
96
+ function dateOf(day: CalendarDay): Date {
97
+ return parseLocalDay(day) ?? new Date(Number.NaN);
98
+ }
99
+
100
+ function toDate(value: Date | string): Date {
101
+ return value instanceof Date ? value : new Date(value);
102
+ }
103
+
104
+ /** The day `amount` calendar days after `day`; negative goes back. */
105
+ export function addDays(day: CalendarDay, amount: number): CalendarDay {
106
+ const date = dateOf(day);
107
+ return localDay(
108
+ new Date(date.getFullYear(), date.getMonth(), date.getDate() + amount),
109
+ );
110
+ }
111
+
112
+ /** How many calendar days `to` is after `from`; negative when it is before. */
113
+ export function daysBetween(from: CalendarDay, to: CalendarDay): number {
114
+ const a = dateOf(from);
115
+ const b = dateOf(to);
116
+ // Whole days in UTC, where no day is 23 or 25 hours long.
117
+ return Math.round(
118
+ (Date.UTC(b.getFullYear(), b.getMonth(), b.getDate()) -
119
+ Date.UTC(a.getFullYear(), a.getMonth(), a.getDate())) /
120
+ 86_400_000,
121
+ );
122
+ }
123
+
124
+ /** The same day `amount` months later, held to the last day of a shorter month: 31 Jan + 1 is 28 Feb. */
125
+ export function addMonths(day: CalendarDay, amount: number): CalendarDay {
126
+ const date = dateOf(day);
127
+ const last = new Date(
128
+ date.getFullYear(),
129
+ date.getMonth() + amount + 1,
130
+ 0,
131
+ ).getDate();
132
+ return localDay(
133
+ new Date(
134
+ date.getFullYear(),
135
+ date.getMonth() + amount,
136
+ Math.min(date.getDate(), last),
137
+ ),
138
+ );
139
+ }
140
+
141
+ /** The first day of the week containing `day`; Monday by default. */
142
+ export function startOfWeek(day: CalendarDay, weekStartsOn = 1): CalendarDay {
143
+ return addDays(day, -((dateOf(day).getDay() - weekStartsOn + 7) % 7));
144
+ }
145
+
146
+ /** The seven days of the configured week containing `day`. */
147
+ export function weekDays(day: CalendarDay, weekStartsOn = 1): CalendarDay[] {
148
+ const monday = startOfWeek(day, weekStartsOn);
149
+ return Array.from({ length: 7 }, (_, index) => addDays(monday, index));
150
+ }
151
+
152
+ /** Whole weeks surrounding the month, using the configured first weekday. */
153
+ export function monthWeeks(
154
+ day: CalendarDay,
155
+ weekStartsOn = 1,
156
+ ): CalendarDay[][] {
157
+ const first = `${day.slice(0, 7)}-01`;
158
+ const weeks: CalendarDay[][] = [];
159
+ let monday = startOfWeek(first, weekStartsOn);
160
+ while (weeks.length === 0 || sameMonth(monday, first)) {
161
+ weeks.push(weekDays(monday, weekStartsOn));
162
+ monday = addDays(monday, 7);
163
+ }
164
+ return weeks;
165
+ }
166
+
167
+ export function sameMonth(a: CalendarDay, b: CalendarDay): boolean {
168
+ return a.slice(0, 7) === b.slice(0, 7);
169
+ }
170
+
171
+ /** The first day a view draws and the day after its last, for a query of the events it shows. */
172
+ export function visibleRange(
173
+ view: 'month' | 'week',
174
+ day: CalendarDay,
175
+ weekStartsOn = 1,
176
+ ): { from: CalendarDay; to: CalendarDay } {
177
+ if (view === 'week') {
178
+ const monday = startOfWeek(day, weekStartsOn);
179
+ return { from: monday, to: addDays(monday, 7) };
180
+ }
181
+ const weeks = monthWeeks(day, weekStartsOn);
182
+ return { from: weeks[0]![0]!, to: addDays(weeks[weeks.length - 1]![6]!, 1) };
183
+ }
184
+
185
+ function zoned(value: Date | string, timeZone: string) {
186
+ return Temporal.Instant.fromEpochMilliseconds(
187
+ toDate(value).getTime(),
188
+ ).toZonedDateTimeISO(timeZone);
189
+ }
190
+
191
+ /** Days in the display timezone. A midnight end belongs to the preceding day. */
192
+ export function eventDays(
193
+ event: Pick<CalendarEvent, 'start' | 'end'>,
194
+ timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone,
195
+ ): CalendarDay[] {
196
+ if (
197
+ !Number.isFinite(toDate(event.start).getTime()) ||
198
+ !Number.isFinite(toDate(event.end).getTime())
199
+ )
200
+ return [];
201
+ const start = zoned(event.start, timeZone);
202
+ const end = zoned(event.end, timeZone);
203
+ const first = start.toPlainDate().toString();
204
+ const midnight =
205
+ end.hour === 0 &&
206
+ end.minute === 0 &&
207
+ end.second === 0 &&
208
+ end.millisecond === 0;
209
+ const last =
210
+ midnight && end.epochMilliseconds > start.epochMilliseconds
211
+ ? end.toPlainDate().subtract({ days: 1 }).toString()
212
+ : end.toPlainDate().toString();
213
+ const days: CalendarDay[] = [];
214
+ for (let day = first; day <= last && days.length < 366; day = addDays(day, 1))
215
+ days.push(day);
216
+ return days.length > 0 ? days : [first];
217
+ }
218
+
219
+ function byStart(a: CalendarEvent, b: CalendarEvent): number {
220
+ if (Boolean(a.allDay) !== Boolean(b.allDay)) return a.allDay ? -1 : 1;
221
+ const diff = toDate(a.start).getTime() - toDate(b.start).getTime();
222
+ return diff !== 0 ? diff : a.title.localeCompare(b.title);
223
+ }
224
+
225
+ /** The events of each of `days`, all-day events first and then by start. */
226
+ export function eventsByDay(
227
+ events: CalendarEvent[],
228
+ days: CalendarDay[],
229
+ timeZone?: string,
230
+ ): Map<CalendarDay, CalendarEvent[]> {
231
+ const shown = new Set(days);
232
+ const map = new Map<CalendarDay, CalendarEvent[]>(
233
+ days.map((day) => [day, []]),
234
+ );
235
+ for (const event of events) {
236
+ for (const day of eventDays(event, timeZone)) {
237
+ if (shown.has(day)) map.get(day)!.push(event);
238
+ }
239
+ }
240
+ for (const list of map.values()) list.sort(byStart);
241
+ return map;
242
+ }
243
+
244
+ /** The events whose time overlaps `[start, end)`; one that ends as the other starts does not. */
245
+ export function findOverlaps<
246
+ Event extends Pick<CalendarEvent, 'start' | 'end'>,
247
+ >(
248
+ range: { start: Date | string; end: Date | string },
249
+ events: Event[],
250
+ ): Event[] {
251
+ const start = toDate(range.start).getTime();
252
+ const end = toDate(range.end).getTime();
253
+ return events.filter(
254
+ (event) =>
255
+ toDate(event.start).getTime() < end &&
256
+ start < toDate(event.end).getTime(),
257
+ );
258
+ }
259
+
260
+ export type TimedPlacement = {
261
+ event: CalendarEvent;
262
+ /** Minutes after midnight on the member's clock where it starts and ends on this day. */
263
+ top: number;
264
+ bottom: number;
265
+ /** Its column among the events it overlaps, from 0, and how many columns they share. */
266
+ column: number;
267
+ columns: number;
268
+ };
269
+
270
+ /** The shortest an event draws in the week view, in minutes, so a short one stays clickable. */
271
+ const MIN_MINUTES = 30;
272
+
273
+ /**
274
+ * Places the timed events of `day` by the hour: an event that overlaps others sits beside them in
275
+ * the first free column. Minutes come from the clock, so an hour lost or gained to daylight saving
276
+ * leaves every later event at its written time.
277
+ */
278
+ export function layoutDay(
279
+ events: CalendarEvent[],
280
+ day: CalendarDay,
281
+ timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone,
282
+ ): TimedPlacement[] {
283
+ const placed = events
284
+ .filter((event) => !event.allDay)
285
+ .flatMap((event) => {
286
+ if (!eventDays(event, timeZone).includes(day)) return [];
287
+ const start = zoned(event.start, timeZone);
288
+ const end = zoned(event.end, timeZone);
289
+ const top =
290
+ start.toPlainDate().toString() < day
291
+ ? 0
292
+ : start.hour * 60 + start.minute;
293
+ const bottom =
294
+ end.toPlainDate().toString() > day
295
+ ? 24 * 60
296
+ : end.hour * 60 + end.minute;
297
+ const drawnTop = Math.min(top, 24 * 60 - MIN_MINUTES);
298
+ return [
299
+ {
300
+ event,
301
+ top: drawnTop,
302
+ bottom: Math.min(24 * 60, Math.max(bottom, drawnTop + MIN_MINUTES)),
303
+ column: 0,
304
+ columns: 1,
305
+ },
306
+ ];
307
+ })
308
+ .sort((a, b) => a.top - b.top || b.bottom - a.bottom);
309
+
310
+ let cluster: TimedPlacement[] = [];
311
+ let ends: number[] = [];
312
+ let clusterEnd = -1;
313
+ const close = () => {
314
+ for (const each of cluster) each.columns = ends.length;
315
+ cluster = [];
316
+ ends = [];
317
+ };
318
+ for (const each of placed) {
319
+ if (each.top >= clusterEnd) close();
320
+ let column = ends.findIndex((end) => end <= each.top);
321
+ if (column === -1) column = ends.push(0) - 1;
322
+ ends[column] = each.bottom;
323
+ each.column = column;
324
+ cluster.push(each);
325
+ clusterEnd = Math.max(clusterEnd, each.bottom);
326
+ }
327
+ close();
328
+ return placed;
329
+ }
330
+
331
+ // ---------------------------------------------------------------------------------------------
332
+ // Colours
333
+
334
+ // Whole class names, so Tailwind generates them: the chart tokens reach the page only through
335
+ // the utilities that use them.
336
+ const COLORS = [
337
+ { dot: 'bg-chart-1', tint: 'bg-chart-1/15', bar: 'border-chart-1' },
338
+ { dot: 'bg-chart-2', tint: 'bg-chart-2/15', bar: 'border-chart-2' },
339
+ { dot: 'bg-chart-3', tint: 'bg-chart-3/15', bar: 'border-chart-3' },
340
+ { dot: 'bg-chart-4', tint: 'bg-chart-4/15', bar: 'border-chart-4' },
341
+ { dot: 'bg-chart-5', tint: 'bg-chart-5/15', bar: 'border-chart-5' },
342
+ ] as const;
343
+
344
+ function colorOf(index = 0) {
345
+ return COLORS[((index % COLORS.length) + COLORS.length) % COLORS.length]!;
346
+ }
347
+
348
+ export type CalendarLegendItem = {
349
+ key: string | number;
350
+ label: ReactNode;
351
+ color: number;
352
+ };
353
+
354
+ /**
355
+ * What each event colour stands for, in one row that scrolls sideways on a phone. With `onToggle` each item is a button that shows or hides
356
+ * its events; `hidden` holds the keys hidden.
357
+ */
358
+ export function CalendarLegend({
359
+ label,
360
+ items,
361
+ hidden,
362
+ onToggle,
363
+ className,
364
+ }: {
365
+ label: string;
366
+ items: CalendarLegendItem[];
367
+ hidden?: ReadonlySet<string | number>;
368
+ onToggle?: (key: string | number) => void;
369
+ className?: string;
370
+ }) {
371
+ return (
372
+ <ul
373
+ aria-label={label}
374
+ tabIndex={0}
375
+ className={cn(
376
+ 'flex flex-wrap items-center gap-x-stack gap-y-1 outline-none focus-visible:ring-2 focus-visible:ring-ring max-mobile:flex-nowrap max-mobile:overflow-x-auto',
377
+ className,
378
+ )}
379
+ >
380
+ {items.map((item) => {
381
+ const off = hidden?.has(item.key) ?? false;
382
+ const content = (
383
+ <>
384
+ <span
385
+ aria-hidden="true"
386
+ className={cn(
387
+ 'size-2.5 shrink-0 rounded-full',
388
+ colorOf(item.color).dot,
389
+ off && 'opacity-30',
390
+ )}
391
+ />
392
+ <Text
393
+ as="span"
394
+ size="xs"
395
+ variant={off ? 'muted' : 'default'}
396
+ className={cn(off && 'line-through')}
397
+ >
398
+ {item.label}
399
+ </Text>
400
+ </>
401
+ );
402
+ return (
403
+ <li key={item.key} className="shrink-0">
404
+ {onToggle ? (
405
+ <Button variant="plain" size={null}
406
+ type="button"
407
+ aria-pressed={!off}
408
+ onClick={() => onToggle(item.key)}
409
+ className="flex min-h-6 items-center gap-1.5 rounded-sm px-1 outline-none hover:bg-surface-hover focus-visible:ring-2 focus-visible:ring-ring max-mobile:min-h-11"
410
+ >
411
+ {content}
412
+ </Button>
413
+ ) : (
414
+ <span className="flex items-center gap-1.5 px-1">{content}</span>
415
+ )}
416
+ </li>
417
+ );
418
+ })}
419
+ </ul>
420
+ );
421
+ }
422
+
423
+ // ---------------------------------------------------------------------------------------------
424
+ // The view
425
+
426
+ export type CalendarMessages = {
427
+ grid: string;
428
+ agenda: string;
429
+ layout: string;
430
+ allDay: string;
431
+ today: string;
432
+ empty: string;
433
+ emptyDay: string;
434
+ to: string;
435
+ time: string;
436
+ book: string;
437
+ retry: string;
438
+ zone: (timeZone: string) => string;
439
+ more: (count: number) => string;
440
+ moreOn: (count: number, day: string) => string;
441
+ selectDay: (day: string) => string;
442
+ };
443
+ const CALENDAR_MESSAGES: CalendarMessages = {
444
+ grid: 'Grid',
445
+ agenda: 'Agenda',
446
+ layout: 'Calendar layout',
447
+ allDay: 'All day',
448
+ today: 'Today',
449
+ empty: 'Nothing on these days',
450
+ emptyDay: 'No events',
451
+ to: 'to',
452
+ time: 'Time',
453
+ book: 'Select time',
454
+ retry: 'Retry',
455
+ zone: (zone) => `Time zone: ${zone}`,
456
+ more: (count) => `+${count} more`,
457
+ moreOn: (count, day) => `${count} more on ${day}`,
458
+ selectDay: (day) => `Add on ${day}`,
459
+ };
460
+ const CalendarContext = createContext({
461
+ locale: undefined as string | undefined,
462
+ timeZone: 'UTC',
463
+ weekStartsOn: 1,
464
+ messages: CALENDAR_MESSAGES,
465
+ });
466
+ function useCalendar() {
467
+ const context = useContext(CalendarContext);
468
+ return {
469
+ ...context,
470
+ dayLabel: (day: string) => formatDay(day, { locale: context.locale }),
471
+ dateLabel: (day: string) => formatDate(day, { locale: context.locale }),
472
+ weekday: (day: string, style: 'short' | 'long' = 'short') =>
473
+ formatWeekday(day, { locale: context.locale, style }),
474
+ time: (value: Date | string) =>
475
+ formatTime(value, { locale: context.locale, timeZone: context.timeZone }),
476
+ };
477
+ }
478
+
479
+ /**
480
+ * A month or week of events. The month is a grid of days in which the arrow keys move
481
+ * between days, Page Up and Page Down between months, and Enter selects the day; a day with more
482
+ * events than fit shows "+N more". The week lays timed events out by the hour, side by side where
483
+ * they overlap, under a row of all-day events. On a phone the days are an agenda list. Times show
484
+ * in the requested IANA timezone.
485
+ */
486
+ export function CalendarView({
487
+ label,
488
+ view,
489
+ date,
490
+ events,
491
+ onSelectDay,
492
+ onSelectEvent,
493
+ onDateChange,
494
+ selectDayLabel,
495
+ layout = 'auto',
496
+ onLayoutChange,
497
+ showLayoutControl = true,
498
+ locale,
499
+ timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone,
500
+ weekStartsOn = 1,
501
+ messages: overrides,
502
+ onRetry,
503
+ maxPerDay = 3,
504
+ loading = false,
505
+ error,
506
+ empty,
507
+ today,
508
+ className,
509
+ }: CalendarViewProps) {
510
+ const phone = useBreakpointBelow('mobile');
511
+ const [chosen, setChosen] = useState<'grid' | 'agenda' | null>(null);
512
+ const activeLayout = onLayoutChange ? layout : (chosen ?? layout);
513
+ const agenda =
514
+ activeLayout === 'agenda' || (activeLayout === 'auto' && phone);
515
+ const messages = { ...CALENDAR_MESSAGES, ...overrides };
516
+ const currentDay = today ?? Temporal.Now.plainDateISO(timeZone).toString();
517
+ const shared = {
518
+ label,
519
+ date,
520
+ events: loading ? [] : events,
521
+ onSelectDay,
522
+ onSelectEvent,
523
+ selectDayLabel,
524
+ loading,
525
+ today: currentDay,
526
+ };
527
+ return (
528
+ <CalendarContext.Provider
529
+ value={{ locale, timeZone, weekStartsOn, messages }}
530
+ >
531
+ <div className={cn('flex min-h-0 flex-col gap-inline', className)}>
532
+ {showLayoutControl && (
533
+ <div
534
+ role="group"
535
+ aria-label={messages.layout}
536
+ className="flex flex-wrap gap-inline"
537
+ >
538
+ {(['grid', 'agenda'] as const).map((choice) => (
539
+ <Button
540
+ key={choice}
541
+ variant="outline"
542
+ size="sm"
543
+ aria-pressed={choice === (agenda ? 'agenda' : 'grid')}
544
+ onClick={() => {
545
+ if (onLayoutChange) onLayoutChange(choice);
546
+ else setChosen(choice);
547
+ }}
548
+ >
549
+ {messages[choice]}
550
+ </Button>
551
+ ))}
552
+ </div>
553
+ )}
554
+ <Text size="xs" variant="muted">
555
+ {messages.zone(timeZone)}
556
+ </Text>
557
+ {error && (
558
+ <ErrorState
559
+ error={error}
560
+ onRetry={onRetry}
561
+ labels={{ retry: messages.retry }}
562
+ />
563
+ )}
564
+ {agenda ? (
565
+ <Agenda {...shared} view={view} empty={empty} />
566
+ ) : view === 'month' ? (
567
+ <MonthGrid
568
+ {...shared}
569
+ maxPerDay={maxPerDay}
570
+ onDateChange={onDateChange}
571
+ />
572
+ ) : (
573
+ <WeekGrid {...shared} />
574
+ )}
575
+ </div>
576
+ </CalendarContext.Provider>
577
+ );
578
+ }
579
+
580
+ type SharedProps = Pick<
581
+ CalendarViewProps,
582
+ | 'label'
583
+ | 'date'
584
+ | 'events'
585
+ | 'onSelectDay'
586
+ | 'onSelectEvent'
587
+ | 'selectDayLabel'
588
+ | 'loading'
589
+ > & { today: CalendarDay };
590
+
591
+ function EventChip({
592
+ event,
593
+ tabbable,
594
+ onSelectEvent,
595
+ }: {
596
+ event: CalendarEvent;
597
+ tabbable: boolean;
598
+ onSelectEvent?: (event: CalendarEvent) => void;
599
+ }) {
600
+ const { time } = useCalendar();
601
+ const color = colorOf(event.color);
602
+ return (
603
+ <Button variant="plain" size={null}
604
+ type="button"
605
+ tabIndex={tabbable ? 0 : -1}
606
+ onClick={() => onSelectEvent?.(event)}
607
+ className={cn(
608
+ 'flex min-h-6 w-full min-w-0 items-center gap-1 rounded-sm px-1 text-left outline-none transition-colors duration-fast ease-move focus-visible:ring-2 focus-visible:ring-ring',
609
+ event.allDay
610
+ ? cn(color.tint, 'hover:brightness-95 dark:hover:brightness-125')
611
+ : 'hover:bg-surface-hover',
612
+ )}
613
+ >
614
+ {event.allDay ? (
615
+ <span
616
+ aria-hidden="true"
617
+ className={cn('h-3 w-0.5 shrink-0 rounded-full', color.dot)}
618
+ />
619
+ ) : (
620
+ <span
621
+ aria-hidden="true"
622
+ className={cn('size-2 shrink-0 rounded-full', color.dot)}
623
+ />
624
+ )}
625
+ {!event.allDay && (
626
+ // A narrow day gives its room to the title; the time stays in the button's name.
627
+ <Text
628
+ as="span"
629
+ size="xs"
630
+ variant="muted"
631
+ className="sr-only shrink-0 tabular-nums @min-[9rem]:not-sr-only"
632
+ >
633
+ {time(event.start)}
634
+ </Text>
635
+ )}
636
+ <Text as="span" size="xs" className="min-w-0 truncate">
637
+ {event.title}
638
+ </Text>
639
+ {event.detail && <span className="sr-only">, {event.detail}</span>}
640
+ </Button>
641
+ );
642
+ }
643
+
644
+ function MonthGrid({
645
+ label,
646
+ date,
647
+ events,
648
+ onSelectDay,
649
+ onSelectEvent,
650
+ onDateChange,
651
+ loading,
652
+ today,
653
+ maxPerDay,
654
+ }: SharedProps & {
655
+ maxPerDay: number;
656
+ onDateChange?: (day: CalendarDay) => void;
657
+ }) {
658
+ const { weekStartsOn, timeZone, dayLabel, dateLabel, weekday } =
659
+ useCalendar();
660
+ const weeks = monthWeeks(date, weekStartsOn);
661
+ const days = weeks.flat();
662
+ const byDay = eventsByDay(events, days, timeZone);
663
+ const [focused, setFocused] = useState<CalendarDay | null>(null);
664
+ const active =
665
+ focused !== null && days.includes(focused)
666
+ ? focused
667
+ : sameMonth(today, date)
668
+ ? today
669
+ : date;
670
+ const cells = useRef(new Map<CalendarDay, HTMLDivElement>());
671
+ // The day a key moved to; it takes focus once it is on screen, which may be after a new month renders.
672
+ const moveTo = useRef<CalendarDay | null>(null);
673
+
674
+ useEffect(() => {
675
+ const target = moveTo.current;
676
+ const cell = target === null ? undefined : cells.current.get(target);
677
+ if (cell) {
678
+ moveTo.current = null;
679
+ cell.focus();
680
+ cell.scrollIntoView({ block: 'nearest', inline: 'nearest' });
681
+ }
682
+ });
683
+
684
+ function move(next: CalendarDay) {
685
+ if (!days.includes(next)) {
686
+ if (!onDateChange) return;
687
+ onDateChange(next);
688
+ }
689
+ moveTo.current = next;
690
+ setFocused(next);
691
+ }
692
+
693
+ function onKeyDown(event: KeyboardEvent<HTMLDivElement>, day: CalendarDay) {
694
+ if (
695
+ event.target !== event.currentTarget ||
696
+ event.altKey ||
697
+ event.ctrlKey ||
698
+ event.metaKey
699
+ )
700
+ return;
701
+ const monday = startOfWeek(day, weekStartsOn);
702
+ const next: Record<string, CalendarDay> = {
703
+ ArrowLeft: addDays(day, -1),
704
+ ArrowRight: addDays(day, 1),
705
+ ArrowUp: addDays(day, -7),
706
+ ArrowDown: addDays(day, 7),
707
+ Home: monday,
708
+ End: addDays(monday, 6),
709
+ PageUp: addMonths(day, -1),
710
+ PageDown: addMonths(day, 1),
711
+ };
712
+ if (event.key in next) {
713
+ event.preventDefault();
714
+ move(next[event.key]!);
715
+ } else if (event.key === 'Enter' || event.key === ' ') {
716
+ event.preventDefault();
717
+ onSelectDay?.(day);
718
+ }
719
+ }
720
+
721
+ function onClick(event: MouseEvent<HTMLDivElement>, day: CalendarDay) {
722
+ // Clicks on an event or in a portalled "+N more" list reach here through React's tree.
723
+ const target = event.target as HTMLElement;
724
+ if (!event.currentTarget.contains(target) || target.closest('button'))
725
+ return;
726
+ setFocused(day);
727
+ onSelectDay?.(day);
728
+ }
729
+
730
+ return (
731
+ <div
732
+ role="grid"
733
+ aria-label={label}
734
+ aria-busy={loading || undefined}
735
+ className="grid min-h-0 flex-1 overflow-y-auto rounded-md border"
736
+ style={{
737
+ gridTemplateRows: `auto repeat(${weeks.length}, minmax(6.5rem, 1fr))`,
738
+ }}
739
+ >
740
+ <div role="row" className="grid grid-cols-7 border-b bg-muted/40">
741
+ {weeks[0]!.map((day) => (
742
+ <div
743
+ key={day}
744
+ role="columnheader"
745
+ aria-label={weekday(day, 'long')}
746
+ className="px-inline py-1"
747
+ >
748
+ <Text as="span" size="xs" variant="muted" weight="medium">
749
+ {weekday(day)}
750
+ </Text>
751
+ </div>
752
+ ))}
753
+ </div>
754
+ {weeks.map((week, row) => (
755
+ <div
756
+ key={week[0]}
757
+ role="row"
758
+ className={cn(
759
+ 'grid min-h-0 grid-cols-7',
760
+ row < weeks.length - 1 && 'border-b',
761
+ )}
762
+ >
763
+ {week.map((day, column) => {
764
+ const list = byDay.get(day) ?? [];
765
+ const fits = list.length > maxPerDay ? maxPerDay - 1 : list.length;
766
+ const outside = !sameMonth(day, date);
767
+ const isToday = day === today;
768
+ const isActive = day === active;
769
+ return (
770
+ <div
771
+ key={day}
772
+ role="gridcell"
773
+ ref={(element) => {
774
+ if (element) cells.current.set(day, element);
775
+ else cells.current.delete(day);
776
+ }}
777
+ tabIndex={isActive ? 0 : -1}
778
+ aria-current={isToday ? 'date' : undefined}
779
+ onKeyDown={(event) => onKeyDown(event, day)}
780
+ onClick={(event) => onClick(event, day)}
781
+ className={cn(
782
+ '@container flex min-h-0 min-w-0 cursor-pointer flex-col gap-0.5 overflow-hidden p-1 outline-none transition-colors duration-fast ease-move hover:bg-surface-hover/60 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring',
783
+ column < 6 && 'border-r',
784
+ outside && 'bg-muted/40',
785
+ )}
786
+ >
787
+ <span className="sr-only">{dateLabel(day)}</span>
788
+ <Text
789
+ as="span"
790
+ size="xs"
791
+ weight={isToday ? 'semibold' : 'medium'}
792
+ variant={isToday ? 'inverse' : outside ? 'muted' : 'default'}
793
+ aria-hidden="true"
794
+ className={cn(
795
+ 'flex size-6 shrink-0 items-center justify-center rounded-full tabular-nums',
796
+ isToday && 'bg-primary',
797
+ )}
798
+ >
799
+ {dateOf(day).getDate()}
800
+ </Text>
801
+ {loading && (row + column) % 3 === 0 && (
802
+ <Skeleton className="h-4 w-4/5" />
803
+ )}
804
+ {list.slice(0, fits).map((event) => (
805
+ <EventChip
806
+ key={event.id}
807
+ event={event}
808
+ tabbable={isActive}
809
+ onSelectEvent={onSelectEvent}
810
+ />
811
+ ))}
812
+ {list.length > fits && (
813
+ <MoreEvents
814
+ day={day}
815
+ events={list}
816
+ hiddenCount={list.length - fits}
817
+ tabbable={isActive}
818
+ onSelectEvent={onSelectEvent}
819
+ />
820
+ )}
821
+ </div>
822
+ );
823
+ })}
824
+ </div>
825
+ ))}
826
+ </div>
827
+ );
828
+ }
829
+
830
+ function MoreEvents({
831
+ day,
832
+ events,
833
+ hiddenCount,
834
+ tabbable,
835
+ onSelectEvent,
836
+ }: {
837
+ day: CalendarDay;
838
+ events: CalendarEvent[];
839
+ hiddenCount: number;
840
+ tabbable: boolean;
841
+ onSelectEvent?: (event: CalendarEvent) => void;
842
+ }) {
843
+ const { messages, dayLabel, dateLabel } = useCalendar();
844
+ const [open, setOpen] = useState(false);
845
+ return (
846
+ <Popover open={open} onOpenChange={setOpen}>
847
+ <PopoverTrigger asChild>
848
+ <Button variant="plain" size={null}
849
+ type="button"
850
+ tabIndex={tabbable ? 0 : -1}
851
+ aria-label={messages.moreOn(hiddenCount, dateLabel(day))}
852
+ className="flex min-h-6 items-center rounded-sm px-1 text-left outline-none hover:bg-surface-hover focus-visible:ring-2 focus-visible:ring-ring"
853
+ >
854
+ <Text as="span" size="xs" variant="muted" weight="medium">
855
+ {messages.more(hiddenCount)}
856
+ </Text>
857
+ </Button>
858
+ </PopoverTrigger>
859
+ <PopoverContent
860
+ aria-label={dayLabel(day)}
861
+ align="start"
862
+ className="@container flex w-64 flex-col gap-1 p-inline"
863
+ >
864
+ <Heading level={2} size="sm" className="px-1 pb-1">
865
+ {dayLabel(day)}
866
+ </Heading>
867
+ {events.map((event) => (
868
+ <EventChip
869
+ key={event.id}
870
+ event={event}
871
+ tabbable
872
+ onSelectEvent={(chosen) => {
873
+ setOpen(false);
874
+ onSelectEvent?.(chosen);
875
+ }}
876
+ />
877
+ ))}
878
+ </PopoverContent>
879
+ </Popover>
880
+ );
881
+ }
882
+
883
+ /** The height of one hour in the week view, in rem. */
884
+ const HOUR_REM = 3;
885
+
886
+ function WeekGrid({
887
+ label,
888
+ date,
889
+ events,
890
+ onSelectDay,
891
+ onSelectEvent,
892
+ selectDayLabel,
893
+ loading,
894
+ today,
895
+ }: SharedProps) {
896
+ const { weekStartsOn, timeZone, locale, messages, weekday, dayLabel, time } =
897
+ useCalendar();
898
+ const days = weekDays(date, weekStartsOn);
899
+ const byDay = eventsByDay(events, days, timeZone);
900
+ const scroller = useRef<HTMLDivElement>(null);
901
+ const [now, setNow] = useState(() => new Date());
902
+ const first = days[0];
903
+ const firstHour = Math.min(
904
+ 8,
905
+ ...days.flatMap((day) =>
906
+ layoutDay(byDay.get(day) ?? [], day, timeZone).map((each) =>
907
+ Math.floor(each.top / 60),
908
+ ),
909
+ ),
910
+ );
911
+
912
+ const openAt = useRef(firstHour);
913
+ openAt.current = firstHour;
914
+
915
+ // The day opens at eight, or at the week's first event when that is earlier. It scrolls when the
916
+ // week changes, not when its events refetch.
917
+ useLayoutEffect(() => {
918
+ const element = scroller.current;
919
+ if (!element) return;
920
+ const rem = Number.parseFloat(getComputedStyle(element).fontSize) || 16;
921
+ // Half a rem above the hour, so its label shows whole.
922
+ element.scrollTop = Math.max(0, (openAt.current * HOUR_REM - 0.5) * rem);
923
+ }, [first]);
924
+
925
+ useEffect(() => {
926
+ const timer = setInterval(() => setNow(new Date()), 60_000);
927
+ return () => clearInterval(timer);
928
+ }, []);
929
+
930
+ const hasAllDay = days.some((day) =>
931
+ (byDay.get(day) ?? []).some((event) => event.allDay),
932
+ );
933
+ const columns =
934
+ 'grid min-w-[56rem] grid-cols-[4.5rem_repeat(7,minmax(0,1fr))]';
935
+
936
+ function onColumnClick(event: MouseEvent<HTMLDivElement>, day: CalendarDay) {
937
+ if (event.target !== event.currentTarget || !onSelectDay) return;
938
+ const box = event.currentTarget.getBoundingClientRect();
939
+ const hour = Math.min(
940
+ 23,
941
+ Math.max(0, Math.floor(((event.clientY - box.top) / box.height) * 24)),
942
+ );
943
+ onSelectDay(day, `${String(hour).padStart(2, '0')}:00`);
944
+ }
945
+
946
+ return (
947
+ <section
948
+ aria-label={label}
949
+ aria-busy={loading || undefined}
950
+ className="flex min-h-0 flex-1 flex-col overflow-x-auto rounded-md border"
951
+ >
952
+ <div className={cn(columns, 'border-b bg-muted/40')}>
953
+ <span />
954
+ {days.map((day) => {
955
+ const isToday = day === today;
956
+ const content = (
957
+ <>
958
+ <Text as="span" size="xs" variant="muted" weight="medium">
959
+ {weekday(day)}
960
+ </Text>
961
+ <Text
962
+ as="span"
963
+ size="sm"
964
+ weight="semibold"
965
+ variant={isToday ? 'inverse' : 'default'}
966
+ className={cn(
967
+ 'flex size-7 items-center justify-center rounded-full tabular-nums',
968
+ isToday && 'bg-primary',
969
+ )}
970
+ >
971
+ {dateOf(day).getDate()}
972
+ </Text>
973
+ </>
974
+ );
975
+ return onSelectDay ? (
976
+ <Button variant="plain" size={null}
977
+ key={day}
978
+ type="button"
979
+ aria-label={
980
+ selectDayLabel?.(day) ?? messages.selectDay(dayLabel(day))
981
+ }
982
+ aria-current={isToday ? 'date' : undefined}
983
+ onClick={() => onSelectDay(day, '09:00')}
984
+ className="flex min-h-8 items-center justify-center gap-1.5 border-l py-1 outline-none hover:bg-surface-hover focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
985
+ >
986
+ {content}
987
+ </Button>
988
+ ) : (
989
+ <div
990
+ key={day}
991
+ aria-current={isToday ? 'date' : undefined}
992
+ className="flex items-center justify-center gap-1.5 border-l py-1"
993
+ >
994
+ {content}
995
+ </div>
996
+ );
997
+ })}
998
+ </div>
999
+ {onSelectDay && <BookingTime days={days} onSelectDay={onSelectDay} />}
1000
+ {hasAllDay && (
1001
+ <div className={cn(columns, 'border-b')}>
1002
+ <Text
1003
+ as="span"
1004
+ size="xs"
1005
+ variant="muted"
1006
+ className="self-center px-1 text-right"
1007
+ >
1008
+ {messages.allDay}
1009
+ </Text>
1010
+ {days.map((day) => (
1011
+ <div
1012
+ key={day}
1013
+ className="flex min-w-0 flex-col gap-0.5 border-l p-0.5"
1014
+ >
1015
+ {(byDay.get(day) ?? [])
1016
+ .filter((event) => event.allDay)
1017
+ .map((event) => (
1018
+ <EventChip
1019
+ key={event.id}
1020
+ event={event}
1021
+ tabbable
1022
+ onSelectEvent={onSelectEvent}
1023
+ />
1024
+ ))}
1025
+ </div>
1026
+ ))}
1027
+ </div>
1028
+ )}
1029
+ <div
1030
+ ref={scroller}
1031
+ tabIndex={0}
1032
+ aria-label={label}
1033
+ className="min-h-0 flex-1 overflow-y-auto outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
1034
+ >
1035
+ <div
1036
+ className={cn(columns, 'relative')}
1037
+ style={{ height: `${24 * HOUR_REM}rem` }}
1038
+ >
1039
+ <div className="relative">
1040
+ {Array.from({ length: 23 }, (_, index) => (
1041
+ <Text
1042
+ key={index}
1043
+ as="span"
1044
+ size="xs"
1045
+ variant="muted"
1046
+ className="absolute right-1 -translate-y-1/2 whitespace-nowrap tabular-nums"
1047
+ style={{ top: `${(index + 1) * HOUR_REM}rem` }}
1048
+ >
1049
+ {formatTime(new Date(2000, 0, 1, index + 1), { locale })}
1050
+ </Text>
1051
+ ))}
1052
+ </div>
1053
+ {days.map((day, dayIndex) => {
1054
+ const placed = layoutDay(byDay.get(day) ?? [], day, timeZone);
1055
+ const nowInZone = zoned(now, timeZone);
1056
+ const minutesNow = nowInZone.hour * 60 + nowInZone.minute;
1057
+ return (
1058
+ <div
1059
+ key={day}
1060
+ onClick={(event) => onColumnClick(event, day)}
1061
+ className={cn(
1062
+ 'relative border-l',
1063
+ onSelectDay && 'cursor-pointer',
1064
+ )}
1065
+ style={{
1066
+ backgroundImage: `repeating-linear-gradient(to bottom, transparent 0, transparent calc(${HOUR_REM}rem - 1px), var(--color-border) calc(${HOUR_REM}rem - 1px), var(--color-border) ${HOUR_REM}rem)`,
1067
+ }}
1068
+ >
1069
+ {loading && dayIndex % 2 === 0 && (
1070
+ <Skeleton
1071
+ className="absolute inset-x-1"
1072
+ style={{
1073
+ top: `${(9 + dayIndex / 2) * HOUR_REM}rem`,
1074
+ height: `${HOUR_REM}rem`,
1075
+ }}
1076
+ />
1077
+ )}
1078
+ {placed.some((item) => item.columns > 3) && (
1079
+ <div className="absolute inset-x-1 top-1 z-10 bg-background">
1080
+ <MoreEvents
1081
+ day={day}
1082
+ events={byDay.get(day) ?? []}
1083
+ hiddenCount={placed.length}
1084
+ tabbable
1085
+ onSelectEvent={onSelectEvent}
1086
+ />
1087
+ </div>
1088
+ )}
1089
+ {placed
1090
+ .filter((item) => item.columns <= 3)
1091
+ .map(({ event, top, bottom, column, columns: count }) => {
1092
+ const color = colorOf(event.color);
1093
+ const tall = bottom - top >= 45;
1094
+ return (
1095
+ <Button variant="plain" size={null}
1096
+ key={event.id}
1097
+ type="button"
1098
+ onClick={() => onSelectEvent?.(event)}
1099
+ className="absolute overflow-hidden rounded-sm bg-background text-left outline-none ring-1 ring-background focus-visible:z-10 focus-visible:ring-2 focus-visible:ring-ring"
1100
+ style={{
1101
+ top: `${(top / 60) * HOUR_REM}rem`,
1102
+ height: `${((bottom - top) / 60) * HOUR_REM}rem`,
1103
+ left: `calc(${(column / count) * 100}% + 1px)`,
1104
+ width: `calc(${100 / count}% - 2px)`,
1105
+ }}
1106
+ >
1107
+ <span
1108
+ aria-hidden="true"
1109
+ className={cn(
1110
+ 'absolute inset-0 border-l-2',
1111
+ color.tint,
1112
+ color.bar,
1113
+ )}
1114
+ />
1115
+ <span
1116
+ className={cn(
1117
+ 'relative flex min-w-0 px-1 py-0.5',
1118
+ tall ? 'flex-col' : 'items-center gap-1',
1119
+ )}
1120
+ >
1121
+ <Text
1122
+ as="span"
1123
+ size="xs"
1124
+ weight="medium"
1125
+ className="min-w-0 truncate"
1126
+ >
1127
+ {event.title}
1128
+ </Text>
1129
+ <Text
1130
+ as="span"
1131
+ size="xs"
1132
+ variant="muted"
1133
+ className="truncate tabular-nums"
1134
+ >
1135
+ {tall
1136
+ ? `${time(event.start)} – ${time(event.end)}`
1137
+ : time(event.start)}
1138
+ </Text>
1139
+ {event.detail && (
1140
+ <span className="sr-only">, {event.detail}</span>
1141
+ )}
1142
+ </span>
1143
+ </Button>
1144
+ );
1145
+ })}
1146
+ {day === nowInZone.toPlainDate().toString() && (
1147
+ <span
1148
+ aria-hidden="true"
1149
+ className="pointer-events-none absolute inset-x-0 z-10 h-0.5 bg-destructive"
1150
+ style={{ top: `${(minutesNow / 60) * HOUR_REM}rem` }}
1151
+ />
1152
+ )}
1153
+ </div>
1154
+ );
1155
+ })}
1156
+ </div>
1157
+ </div>
1158
+ </section>
1159
+ );
1160
+ }
1161
+
1162
+ function Agenda({
1163
+ label,
1164
+ view,
1165
+ date,
1166
+ events,
1167
+ onSelectDay,
1168
+ onSelectEvent,
1169
+ selectDayLabel,
1170
+ loading,
1171
+ today,
1172
+ empty,
1173
+ }: SharedProps & { view: 'month' | 'week'; empty?: ReactNode }) {
1174
+ const { weekStartsOn, timeZone, messages, dayLabel, time } = useCalendar();
1175
+ const days =
1176
+ view === 'week'
1177
+ ? weekDays(date, weekStartsOn)
1178
+ : monthWeeks(date, weekStartsOn)
1179
+ .flat()
1180
+ .filter((day) => sameMonth(day, date));
1181
+ const byDay = eventsByDay(events, days, timeZone);
1182
+ const shown = onSelectDay
1183
+ ? days
1184
+ : days.filter((day) => (byDay.get(day) ?? []).length > 0);
1185
+ const id = useId();
1186
+ const list = useRef<HTMLDivElement>(null);
1187
+ // The list opens at today, or at the first day after it, when the period holds one.
1188
+ const start = shown.find((day) => day >= today);
1189
+ useLayoutEffect(() => {
1190
+ const element = list.current;
1191
+ const section =
1192
+ start === undefined
1193
+ ? null
1194
+ : element?.querySelector<HTMLElement>(`[data-day="${start}"]`);
1195
+ // The list is the sections' offset parent.
1196
+ if (element && section) element.scrollTop = section.offsetTop;
1197
+ }, [start, loading]);
1198
+
1199
+ if (loading) {
1200
+ return (
1201
+ <div
1202
+ role="region"
1203
+ aria-label={label}
1204
+ aria-busy="true"
1205
+ className="flex flex-col gap-stack"
1206
+ >
1207
+ {[0, 1, 2].map((index) => (
1208
+ <div key={index} className="flex flex-col gap-inline">
1209
+ <Skeleton className="h-4 w-32" />
1210
+ <Skeleton className="h-11 w-full" />
1211
+ </div>
1212
+ ))}
1213
+ </div>
1214
+ );
1215
+ }
1216
+
1217
+ if (shown.length === 0) {
1218
+ return (
1219
+ <div role="region" aria-label={label}>
1220
+ {empty ?? <EmptyState title={messages.empty} />}
1221
+ </div>
1222
+ );
1223
+ }
1224
+
1225
+ return (
1226
+ <div
1227
+ ref={list}
1228
+ role="region"
1229
+ aria-label={label}
1230
+ className="relative flex min-h-0 flex-1 flex-col gap-stack overflow-y-auto"
1231
+ >
1232
+ {shown.map((day) => (
1233
+ <div
1234
+ role="group"
1235
+ key={day}
1236
+ data-day={day}
1237
+ aria-labelledby={`${id}-${day}`}
1238
+ className="flex flex-col gap-1"
1239
+ >
1240
+ <div className="flex items-center justify-between gap-inline">
1241
+ <Heading
1242
+ id={`${id}-${day}`}
1243
+ level={2}
1244
+ size="sm"
1245
+ variant={day < today ? 'muted' : 'default'}
1246
+ aria-current={day === today ? 'date' : undefined}
1247
+ >
1248
+ {dayLabel(day)}
1249
+ {day === today && (
1250
+ <Text
1251
+ as="span"
1252
+ size="xs"
1253
+ variant="primary"
1254
+ weight="medium"
1255
+ className="ml-inline"
1256
+ >
1257
+ {messages.today}
1258
+ </Text>
1259
+ )}
1260
+ </Heading>
1261
+ {onSelectDay && (
1262
+ <Button
1263
+ variant="ghost"
1264
+ size="icon"
1265
+ aria-label={
1266
+ selectDayLabel?.(day) ?? messages.selectDay(dayLabel(day))
1267
+ }
1268
+ onClick={() => onSelectDay(day)}
1269
+ className="max-mobile:size-11"
1270
+ >
1271
+ <Plus />
1272
+ </Button>
1273
+ )}
1274
+ </div>
1275
+ {(byDay.get(day) ?? []).length === 0 && (
1276
+ <Text size="sm" variant="muted">
1277
+ {messages.emptyDay}
1278
+ </Text>
1279
+ )}
1280
+ <ul className="flex flex-col overflow-hidden rounded-md border">
1281
+ {(byDay.get(day) ?? []).map((event) => {
1282
+ const color = colorOf(event.color);
1283
+ return (
1284
+ <li key={event.id} className="border-b last:border-b-0">
1285
+ <Button variant="plain" size={null}
1286
+ type="button"
1287
+ onClick={() => onSelectEvent?.(event)}
1288
+ className="flex min-h-11 w-full items-center gap-inset px-inset py-inline text-left outline-none hover:bg-surface-hover focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
1289
+ >
1290
+ <span
1291
+ aria-hidden="true"
1292
+ className={cn('w-1 self-stretch rounded-full', color.dot)}
1293
+ />
1294
+ {event.allDay ? (
1295
+ <Text
1296
+ as="span"
1297
+ size="xs"
1298
+ variant="muted"
1299
+ className="w-16 shrink-0"
1300
+ >
1301
+ {messages.allDay}
1302
+ </Text>
1303
+ ) : (
1304
+ <span className="flex w-16 shrink-0 flex-col">
1305
+ <Text as="span" size="xs" className="tabular-nums">
1306
+ {time(event.start)}
1307
+ </Text>
1308
+ <Text
1309
+ as="span"
1310
+ size="xs"
1311
+ variant="muted"
1312
+ className="tabular-nums"
1313
+ >
1314
+ <span className="sr-only">{messages.to} </span>
1315
+ {time(event.end)}
1316
+ </Text>
1317
+ </span>
1318
+ )}
1319
+ <span className="flex min-w-0 flex-1 flex-col">
1320
+ <Text
1321
+ as="span"
1322
+ size="sm"
1323
+ weight="medium"
1324
+ className="truncate"
1325
+ >
1326
+ {event.title}
1327
+ </Text>
1328
+ {event.detail && (
1329
+ <Text
1330
+ as="span"
1331
+ size="xs"
1332
+ variant="muted"
1333
+ className="truncate"
1334
+ >
1335
+ {event.detail}
1336
+ </Text>
1337
+ )}
1338
+ </span>
1339
+ </Button>
1340
+ </li>
1341
+ );
1342
+ })}
1343
+ </ul>
1344
+ </div>
1345
+ ))}
1346
+ </div>
1347
+ );
1348
+ }
1349
+
1350
+ function BookingTime({
1351
+ days,
1352
+ onSelectDay,
1353
+ }: {
1354
+ days: string[];
1355
+ onSelectDay: (day: string, time?: string) => void;
1356
+ }) {
1357
+ const { dayLabel, messages } = useCalendar();
1358
+ const [day, setDay] = useState(days[0]!);
1359
+ const [time, setTime] = useState('09:00');
1360
+ const id = useId();
1361
+ const selectedDay = days.includes(day) ? day : days[0]!;
1362
+ return (
1363
+ <div className="flex min-w-[56rem] items-end gap-inline border-b p-inline">
1364
+ <div className="flex flex-col gap-1.5">
1365
+ <Label htmlFor={id}>{messages.book}</Label>
1366
+ <Select
1367
+ value={selectedDay}
1368
+ onValueChange={setDay}
1369
+ >
1370
+ <SelectTrigger id={id}><SelectValue /></SelectTrigger>
1371
+ <SelectContent aria-label={messages.book}>{days.map((value) => (
1372
+ <SelectItem key={value} value={value}>
1373
+ {dayLabel(value)}
1374
+ </SelectItem>
1375
+ ))}</SelectContent>
1376
+ </Select>
1377
+ </div>
1378
+ <TimeInput label={messages.time} value={time} onChange={setTime} />
1379
+ <Button
1380
+ variant="outline"
1381
+ disabled={!time}
1382
+ onClick={() => onSelectDay(selectedDay, time)}
1383
+ >
1384
+ {messages.book}
1385
+ </Button>
1386
+ </div>
1387
+ );
1388
+ }