Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

perf(calendar): defer redraws and smooth event loading (#7266)

dev-rbffe14bc66cdd
diff --git a/apps/web/src/features/block-calendar/CalendarBlockAdapter.tsx b/apps/web/src/features/block-calendar/CalendarBlockAdapter.tsx
index 891ed0c6e5..d5503bf77b 100644
--- a/apps/web/src/features/block-calendar/CalendarBlockAdapter.tsx
+++ b/apps/web/src/features/block-calendar/CalendarBlockAdapter.tsx
@@ -87,7 +87,7 @@ function CalendarBlockAdapter(props: CalendarBlockProps) {
const request = targetRequest();
if (
!request ||
- occurrencesQuery.isLoading ||
+ !occurrencesQuery.isSuccess ||
occurrencesQuery.isPlaceholderData
) {
return undefined;
diff --git a/apps/web/src/features/calendar-view/calendar-view.tsx b/apps/web/src/features/calendar-view/calendar-view.tsx
index dbdbe95619..75132aa3d7 100644
--- a/apps/web/src/features/calendar-view/calendar-view.tsx
+++ b/apps/web/src/features/calendar-view/calendar-view.tsx
@@ -178,7 +178,7 @@ export function CalendarView(props: CalendarViewProps) {
const request = targetRequest();
if (
!request ||
- occurrencesQuery.isLoading ||
+ !occurrencesQuery.isSuccess ||
occurrencesQuery.isPlaceholderData
) {
return undefined;
diff --git a/apps/web/src/features/calendar-view/components/CalendarLoadingSkeleton.tsx b/apps/web/src/features/calendar-view/components/CalendarLoadingSkeleton.tsx
new file mode 100644
index 0000000000..d15686d30f
--- /dev/null
+++ b/apps/web/src/features/calendar-view/components/CalendarLoadingSkeleton.tsx
@@ -0,0 +1,380 @@
+import type { DatesSetArg } from '@fullcalendar/core';
+import { createEffect, createMemo, For, on, onCleanup, Show } from 'solid-js';
+import { createStore, reconcile } from 'solid-js/store';
+import { Portal } from 'solid-js/web';
+import { createCalendarLoadingTransition } from '../../calendar/primitives/create-calendar-loading-transition';
+
+const SKELETON_VARIANT_COUNT = 3;
+const TITLE_WIDTH_BASE_PERCENT = 50;
+const TITLE_WIDTH_STEP_PERCENT = 10;
+
+const TIMED_SKELETON = {
+ // Fractions of the rendered time range keep samples inside restricted grids.
+ sampleFractions: [0.375, 0.55, 0.69],
+ sparseEventCount: 2,
+ insetPx: 2,
+ minHeightPx: 12,
+ detailMinHeightPx: 44,
+};
+
+const DAY_GRID_SKELETON = {
+ rowHeightPx: 24,
+ eventHeightPx: 20,
+ topInsetPx: 4,
+ fallbackHeaderHeightPx: 28,
+};
+
+type SkeletonPlacement = {
+ kind: 'timed' | 'bar' | 'text';
+ top: number;
+ height: number;
+ titleWidth: number;
+};
+
+type SkeletonTarget = {
+ element: HTMLElement;
+ kind: 'timed' | 'month' | 'all-day';
+ placements: SkeletonPlacement[];
+};
+
+function skeletonVariant(date: string | undefined) {
+ const dayOfMonthText = date?.slice(-2);
+ const dayOfMonth = Number(dayOfMonthText);
+
+ return dayOfMonth % SKELETON_VARIANT_COUNT;
+}
+
+function skeletonTitleWidth(index: number, variant: number) {
+ const widthVariant = (index + variant) % SKELETON_VARIANT_COUNT;
+ const widthOffset = widthVariant * TITLE_WIDTH_STEP_PERCENT;
+
+ return TITLE_WIDTH_BASE_PERCENT + widthOffset;
+}
+
+function timedSkeletonTargets(element: HTMLElement): SkeletonTarget[] {
+ const slotElements = element.querySelectorAll<HTMLElement>(
+ '.fc-timegrid-slot-lane[data-time]'
+ );
+ const slots = Array.from(slotElements, (slot) =>
+ slot.getBoundingClientRect()
+ );
+ const origin = slots[0]?.top ?? 0;
+ const lastSlotIndex = slots.length - 1;
+
+ const frames = element.querySelectorAll<HTMLElement>(
+ '.fc-timegrid-col[data-date]:not(.fc-day-disabled) .fc-timegrid-col-frame'
+ );
+
+ return Array.from(frames, (frame): SkeletonTarget => {
+ const date = frame.closest<HTMLElement>('[data-date]')?.dataset.date ?? '';
+ const variant = skeletonVariant(date);
+
+ let samples = TIMED_SKELETON.sampleFractions;
+
+ if (variant === 0) {
+ samples = samples.slice(0, TIMED_SKELETON.sparseEventCount);
+ }
+
+ const starts = new Set<number>();
+
+ if (slots.length > 0) {
+ for (const fraction of samples) {
+ const sampleIndex = Math.floor(slots.length * fraction) + variant;
+ const startIndex = Math.min(lastSlotIndex, sampleIndex);
+
+ starts.add(startIndex);
+ }
+ }
+
+ const placements = Array.from(starts, (start, index): SkeletonPlacement => {
+ const additionalSlots = (index + variant) % SKELETON_VARIANT_COUNT;
+ const endIndex = Math.min(lastSlotIndex, start + additionalSlots);
+ const first = slots[start]!;
+ const last = slots[endIndex]!;
+
+ const top = first.top - origin + TIMED_SKELETON.insetPx;
+ const verticalInset = TIMED_SKELETON.insetPx * 2;
+ const availableHeight = last.bottom - first.top - verticalInset;
+ const height = Math.max(TIMED_SKELETON.minHeightPx, availableHeight);
+ const titleWidth = skeletonTitleWidth(index, variant);
+
+ return { kind: 'timed', top, height, titleWidth };
+ });
+
+ return { element: frame, kind: 'timed', placements };
+ });
+}
+
+function dayGridSkeletonTargets(element: HTMLElement): SkeletonTarget[] {
+ const isMonthView = element.querySelector('.fc-dayGridMonth-view') !== null;
+ const cells = element.querySelectorAll<HTMLElement>(
+ '.fc-daygrid-day[data-date]:not(.fc-day-disabled)'
+ );
+
+ return Array.from(cells, (cell): SkeletonTarget => {
+ const variant = skeletonVariant(cell.dataset.date);
+ const bounds = cell.getBoundingClientRect();
+ const header = cell.querySelector('.fc-daygrid-day-top');
+ const headerBounds = header?.getBoundingClientRect();
+
+ let top = DAY_GRID_SKELETON.topInsetPx;
+
+ if (isMonthView) {
+ let headerHeight = DAY_GRID_SKELETON.fallbackHeaderHeightPx;
+ const hasMeasuredHeader = headerBounds && headerBounds.height > 0;
+
+ if (hasMeasuredHeader) {
+ headerHeight = headerBounds.bottom - bounds.top;
+ }
+
+ top += headerHeight;
+ }
+
+ let requestedCount = 0;
+
+ if (isMonthView) {
+ requestedCount = 1 + variant;
+ } else if (variant !== 0) {
+ requestedCount = 1;
+ }
+
+ let count = requestedCount;
+
+ if (bounds.height > 0) {
+ const availableHeight = bounds.height - top;
+ const availableRows = Math.floor(
+ availableHeight / DAY_GRID_SKELETON.rowHeightPx
+ );
+ const rowCapacity = Math.max(0, availableRows);
+
+ count = Math.min(requestedCount, rowCapacity);
+ }
+
+ const placements = Array.from(
+ { length: count },
+ (_, index): SkeletonPlacement => {
+ const isTextRow = isMonthView && (index > 0 || variant !== 0);
+ const rowOffset = index * DAY_GRID_SKELETON.rowHeightPx;
+ const titleWidth = skeletonTitleWidth(index, variant);
+
+ return {
+ kind: isTextRow ? 'text' : 'bar',
+ top: top + rowOffset,
+ height: DAY_GRID_SKELETON.eventHeightPx,
+ titleWidth,
+ };
+ }
+ );
+
+ return {
+ element: cell,
+ kind: isMonthView ? 'month' : 'all-day',
+ placements,
+ };
+ });
+}
+
+/** A small, date-stable sample of event shapes, positioned in the live grid. */
+function skeletonTargets(element: HTMLElement): SkeletonTarget[] {
+ const timedTargets = timedSkeletonTargets(element);
+ const dayGridTargets = dayGridSkeletonTargets(element);
+ const targets = [...timedTargets, ...dayGridTargets];
+
+ return targets.filter((target) => target.placements.length > 0);
+}
+
+function EventSkeleton(props: { placement: SkeletonPlacement }) {
+ const isTextRow = () => props.placement.kind === 'text';
+
+ const showDetailLine = () => {
+ const isTimedEvent = props.placement.kind === 'timed';
+ const hasDetailSpace =
+ props.placement.height >= TIMED_SKELETON.detailMinHeightPx;
+
+ return isTimedEvent && hasDetailSpace;
+ };
+
+ return (
+ <div
+ data-calendar-loading-placeholder={props.placement.kind}
+ class="absolute inset-x-1.5 overflow-hidden"
+ style={{
+ top: `${props.placement.top}px`,
+ height: `${props.placement.height}px`,
+ }}
+ >
+ <Show
+ when={isTextRow()}
+ fallback={
+ <div class="flex size-full flex-col justify-center gap-1.5 rounded-md bg-skeleton px-1.5 py-1">
+ <div
+ class="h-2 shrink-0 rounded-sm bg-skeleton"
+ style={{ width: `${props.placement.titleWidth}%` }}
+ />
+ <Show when={showDetailLine()}>
+ <div class="h-1.5 w-1/2 shrink-0 rounded-sm bg-skeleton" />
+ </Show>
+ </div>
+ }
+ >
+ <div class="flex size-full items-center px-1.5">
+ <div
+ class="h-2 min-w-0 rounded-sm bg-skeleton/70"
+ style={{ width: `${props.placement.titleWidth}%` }}
+ />
+ </div>
+ </Show>
+ </div>
+ );
+}
+
+export function CalendarLoadingSkeleton(props: {
+ element: HTMLElement | undefined;
+ dateInfo: DatesSetArg | undefined;
+ loading: boolean;
+ disabled: boolean;
+ onBlockingChange?: (blocking: boolean) => void;
+}) {
+ const transition = createCalendarLoadingTransition((phase) => {
+ const blocksEventRendering = phase === 'waiting' || phase === 'visible';
+
+ props.onBlockingChange?.(blocksEventRendering);
+ });
+
+ const [targets, setTargets] = createStore<SkeletonTarget[]>([]);
+
+ const mounted = createMemo(() => {
+ const phase = transition.phase();
+
+ return phase === 'visible' || phase === 'leaving';
+ });
+
+ createEffect(
+ on(
+ () => [props.loading, props.disabled] as const,
+ ([loading, disabled]) => {
+ if (disabled) {
+ transition.reset();
+ return;
+ }
+
+ if (loading) {
+ transition.setLoading(true);
+ return;
+ }
+
+ // Let FullCalendar finish laying out events before revealing them.
+ const timer = setTimeout(() => transition.setLoading(false));
+
+ onCleanup(() => {
+ clearTimeout(timer);
+ });
+ }
+ )
+ );
+
+ createEffect(
+ on(
+ () => [props.element, props.dateInfo, mounted()] as const,
+ ([element, dateInfo, visible]) => {
+ const canMeasure =
+ element !== undefined && dateInfo !== undefined && visible;
+
+ if (!canMeasure) {
+ setTargets([]);
+ return;
+ }
+
+ const refresh = () => {
+ const isLeaving = transition.phase() === 'leaving';
+
+ if (isLeaving) {
+ return;
+ }
+
+ // Update placements in place without remounting portals.
+ const nextTargets = skeletonTargets(element);
+ const updateTargets = reconcile(nextTargets, {
+ key: 'element',
+ merge: true,
+ });
+
+ setTargets(updateTargets);
+ };
+
+ refresh();
+
+ let timer: ReturnType<typeof setTimeout> | undefined;
+
+ const observer = new ResizeObserver(() => {
+ clearTimeout(timer);
+ timer = setTimeout(refresh);
+ });
+
+ observer.observe(element);
+
+ const slots = element.querySelector('.fc-timegrid-slots');
+
+ if (slots) {
+ observer.observe(slots);
+ }
+
+ const cells = element.querySelectorAll(
+ '.fc-daygrid-day[data-date]:not(.fc-day-disabled)'
+ );
+
+ for (const cell of cells) {
+ observer.observe(cell);
+ }
+
+ onCleanup(() => {
+ observer.disconnect();
+ clearTimeout(timer);
+ });
+ }
+ )
+ );
+
+ createEffect(
+ on(
+ () => [props.element, transition.phase()] as const,
+ ([element, phase]) => {
+ if (!element) {
+ return;
+ }
+
+ const isRevealingEvents = phase === 'leaving';
+ const loadingState = isRevealingEvents ? 'revealing' : phase;
+
+ element.dataset.calendarLoadingState = loadingState;
+
+ onCleanup(() => {
+ delete element.dataset.calendarLoadingState;
+ });
+ }
+ )
+ );
+
+ return (
+ <For each={targets}>
+ {(target) => (
+ <Portal mount={target.element}>
+ <div
+ aria-hidden="true"
+ data-calendar-loading-skeleton={target.kind}
+ data-state={transition.phase()}
+ class="pointer-events-none absolute inset-0 z-1 overflow-hidden transition-opacity duration-180 motion-reduce:transition-none"
+ classList={{
+ 'opacity-0': transition.phase() === 'leaving',
+ 'opacity-100': transition.phase() === 'visible',
+ }}
+ >
+ <For each={target.placements}>
+ {(placement) => <EventSkeleton placement={placement} />}
+ </For>
+ </div>
+ </Portal>
+ )}
+ </For>
+ );
+}
diff --git a/apps/web/src/features/calendar-view/components/Header.tsx b/apps/web/src/features/calendar-view/components/Header.tsx
index b44fb70871..8613459f00 100644
--- a/apps/web/src/features/calendar-view/components/Header.tsx
+++ b/apps/web/src/features/calendar-view/components/Header.tsx
@@ -1,9 +1,6 @@
import { useViewShell, ViewShell } from '@app/components/view-shell';
import { CopyAvailabilityButton } from '@app/features/calendar/availability/CopyAvailabilityButton';
-import {
- type CalendarPageId,
- useCalendarPager,
-} from '@app/features/calendar/components/CalendarPagerContext';
+import { useCalendarPager } from '@app/features/calendar/components/CalendarPagerContext';
import { CalendarSettingsDropdown } from '@app/features/calendar/components/CalendarSettingsDropdown';
import { useCalendarView } from '@app/features/calendar/components/CalendarViewContext';
import { MonthDrawer } from '@app/features/calendar/components/MonthDrawer';
@@ -28,7 +25,6 @@ import ListIcon from '@phosphor/list.svg';
import PlusIcon from '@phosphor/plus.svg';
import { createElementSize } from '@solid-primitives/resize-observer';
import { Button, cn } from '@ui';
-import { usePager } from '@ui/components/Pager';
import { tourTarget } from '@ui/components/Tour';
import {
createMemo,
@@ -85,7 +81,6 @@ export function Header(props: { presentation: 'workspace' | 'preview' }) {
// PreviewFrame owns its own top bar and may sit inside another view shell.
const shell = props.presentation === 'workspace' ? useViewShell() : undefined;
const calendarPager = useCalendarPager();
- const pager = usePager<CalendarPageId>();
const calendarView = useCalendarView();
const initialDate = new Date();
const [headerElement, setHeaderElement] = createSignal<HTMLElement>();
@@ -146,13 +141,13 @@ export function Header(props: { presentation: 'workspace' | 'preview' }) {
useCalendarHotkeys({
scopeId: panel.splitHotkeyScope,
changeView: calendarPager.changeView,
- previousPeriod: pager.previous,
- nextPeriod: pager.next,
+ previousPeriod: calendarPager.previousPeriod,
+ nextPeriod: calendarPager.nextPeriod,
navigateToToday: calendarPager.navigateToToday,
});
const currentDate = createMemo(
- () => calendarPager.activeDateInfo()?.view.calendar.getDate() ?? initialDate
+ () => calendarPager.navigationDate() ?? initialDate
);
const dateTitle = createMemo(() => formatMonthTitle(currentDate()));
const periodLabel = createMemo(() =>
@@ -201,7 +196,7 @@ export function Header(props: { presentation: 'workspace' | 'preview' }) {
class="border-transparent bg-transparent"
label={`Previous ${periodLabel()}`}
hotkey={TOKENS.calendar.period.previous}
- onClick={() => void pager.previous()}
+ onClick={calendarPager.previousPeriod}
>
<CaretLeftIcon class="size-5" />
</Button>
@@ -213,7 +208,7 @@ export function Header(props: { presentation: 'workspace' | 'preview' }) {
class="border-transparent bg-transparent"
label={`Next ${periodLabel()}`}
hotkey={TOKENS.calendar.period.next}
- onClick={() => void pager.next()}
+ onClick={calendarPager.nextPeriod}
>
<CaretRightIcon class="size-5" />
</Button>
diff --git a/apps/web/src/features/calendar-view/components/Page.tsx b/apps/web/src/features/calendar-view/components/Page.tsx
index 41b8034506..522cd3c5dd 100644
--- a/apps/web/src/features/calendar-view/components/Page.tsx
+++ b/apps/web/src/features/calendar-view/components/Page.tsx
@@ -53,12 +53,14 @@ import {
onCleanup,
onMount,
Show,
+ untrack,
} from 'solid-js';
import { Portal } from 'solid-js/web';
import {
calendarFocusTargetId,
useCalendarFocus,
} from '../calendar-focus-target';
+import { CalendarLoadingSkeleton } from './CalendarLoadingSkeleton';
interface CalendarScrollTarget {
scrollElement: HTMLElement;
@@ -131,7 +133,12 @@ function CalendarScrollIndicators(props: {
);
}
-function CalendarPageDataStatus(props: { data: CalendarOccurrenceData }) {
+function CalendarPageDataStatus(props: {
+ data: CalendarOccurrenceData;
+ changingView: boolean;
+ grid: CalendarGridHandle;
+ onLoadingBlockingChange: (blocking: boolean) => void;
+}) {
const isRangeUnavailable = createMemo(() => {
const range = props.data.range();
return range !== undefined && !isCalendarRangeSupported(range);
@@ -140,7 +147,7 @@ function CalendarPageDataStatus(props: { data: CalendarOccurrenceData }) {
const showLoading = () =>
!isRangeUnavailable() &&
!props.data.occurrencesQuery.isError &&
- props.data.isLoading();
+ (props.changingView || props.data.isLoading());
const showBlockingState = () => {
if (isRangeUnavailable()) return false;
@@ -152,6 +159,13 @@ function CalendarPageDataStatus(props: { data: CalendarOccurrenceData }) {
return (
<>
+ <CalendarLoadingSkeleton
+ element={props.grid.element()}
+ dateInfo={props.grid.dateInfo()}
+ loading={showLoading()}
+ disabled={isRangeUnavailable() || props.data.occurrencesQuery.isError}
+ onBlockingChange={props.onLoadingBlockingChange}
+ />
<Show when={showBlockingState()}>
<div
class="absolute inset-0 z-20 flex items-center justify-center rounded-xl bg-surface/90 p-6 text-center"
@@ -186,13 +200,6 @@ function CalendarPageDataStatus(props: { data: CalendarOccurrenceData }) {
</div>
</Show>
- <Show when={showLoading()}>
- <div class="absolute top-2 left-2 z-10 flex items-center gap-1.5 rounded-full border border-edge-muted bg-surface px-2.5 py-1 text-xs text-ink-muted shadow-menu">
- <SpinnerIcon class="size-3 animate-spin" />
- Loading
- </div>
- </Show>
-
<Show
when={
!isRangeUnavailable() &&
@@ -219,11 +226,18 @@ export function Page(props: {
}) {
const pager = useCalendarPager();
const calendarView = useCalendarView();
+ const [loadingDecorationBlocking, setLoadingDecorationBlocking] =
+ createSignal(false);
+ // Keep the settings object independent of route-period changes. Otherwise
+ // reading any grid setting also subscribes FullCalendar to the whole object.
+ const initialView = untrack(() => calendarView.displaySettings.periodView);
const openEventComposer = useOpenEventComposer();
const quickCalls = useQuickCallsFlag();
const calendarsQuery = useVisibleCalendarsQuery();
const firstWritableCalendar = createMemo(() =>
- calendarsQuery.data?.find((calendar) => calendar.isWritable)
+ calendarsQuery.isSuccess
+ ? calendarsQuery.data?.find((calendar) => calendar.isWritable)
+ : undefined
);
const [range, setRange] = createSignal<CalendarOccurrenceQueryRange>();
const [selectionColor, setSelectionColor] = createSignal<string>();
@@ -340,40 +354,50 @@ export function Page(props: {
};
return (
- <CalendarGrid
- initialDate={props.initialDate}
- events={visibleEvents()}
- eventsById={eventsById()}
- settings={{
- initialView: calendarView.displaySettings.periodView,
- showWeekends: calendarView.displaySettings.showWeekends,
- weekStartsOn: calendarView.displaySettings.weekStartsOn,
- timeFormat: calendarView.displaySettings.timeFormat,
- useNarrowDayHeaders: useNarrowWeekdayHeaders(),
- useNarrowEventContent: props.useNarrowDayHeaders,
- }}
- selection={{
- color: effectiveSelectionColor(),
- eventId: isActive() ? calendarView.selectedEvent()?.id : undefined,
- onDateSelect: isMobile() ? undefined : handleSelect,
- onEventSelect: (event, element) => {
- if (isActive()) calendarView.selectEvent(event, element);
- },
- }}
- eventTimeChangePending={updateEventTime.isPending}
- onDatesSet={handleDatesSet}
- onEventTimeChange={handleEventTimeChange}
+ <div
+ class="relative size-full min-w-0 min-h-0"
+ aria-busy={
+ data.isLoading() ||
+ (isActive() && pager.isChangingView()) ||
+ loadingDecorationBlocking()
+ }
>
- {(grid) => (
- <CalendarPageHost
- id={props.id}
- data={data}
- teamEvents={teamOoo.visibleEvents}
- eventsById={eventsById}
- grid={grid}
- />
- )}
- </CalendarGrid>
+ <CalendarGrid
+ initialDate={props.initialDate}
+ events={visibleEvents()}
+ eventsById={eventsById()}
+ settings={{
+ initialView,
+ showWeekends: calendarView.displaySettings.showWeekends,
+ weekStartsOn: calendarView.displaySettings.weekStartsOn,
+ timeFormat: calendarView.displaySettings.timeFormat,
+ useNarrowDayHeaders: useNarrowWeekdayHeaders(),
+ useNarrowEventContent: props.useNarrowDayHeaders,
+ }}
+ selection={{
+ color: effectiveSelectionColor(),
+ eventId: isActive() ? calendarView.selectedEvent()?.id : undefined,
+ onDateSelect: isMobile() ? undefined : handleSelect,
+ onEventSelect: (event, element) => {
+ if (isActive()) calendarView.selectEvent(event, element);
+ },
+ }}
+ eventTimeChangePending={updateEventTime.isPending}
+ onDatesSet={handleDatesSet}
+ onEventTimeChange={handleEventTimeChange}
+ >
+ {(grid) => (
+ <CalendarPageHost
+ id={props.id}
+ data={data}
+ teamEvents={teamOoo.visibleEvents}
+ eventsById={eventsById}
+ grid={grid}
+ onLoadingBlockingChange={setLoadingDecorationBlocking}
+ />
+ )}
+ </CalendarGrid>
+ </div>
);
}
@@ -385,6 +409,7 @@ function CalendarPageHost(props: {
/** Occurrence events merged with the team out-of-office overlay. */
eventsById: Accessor<Map<string, CalendarEvent>>;
grid: CalendarGridHandle;
+ onLoadingBlockingChange: (blocking: boolean) => void;
}) {
const pager = useCalendarPager();
const calendarView = useCalendarView();
@@ -477,7 +502,12 @@ function CalendarPageHost(props: {
return (
<>
<CalendarScrollIndicators calendarElement={props.grid.element} />
- <CalendarPageDataStatus data={props.data} />
+ <CalendarPageDataStatus
+ data={props.data}
+ changingView={isActive() && pager.isChangingView()}
+ grid={props.grid}
+ onLoadingBlockingChange={props.onLoadingBlockingChange}
+ />
</>
);
}
diff --git a/apps/web/src/features/calendar-view/components/SelectedEventDetails.tsx b/apps/web/src/features/calendar-view/components/SelectedEventDetails.tsx
index 57d683524a..5abb4e0997 100644
--- a/apps/web/src/features/calendar-view/components/SelectedEventDetails.tsx
+++ b/apps/web/src/features/calendar-view/components/SelectedEventDetails.tsx
@@ -62,9 +62,11 @@ interface SelectedEventDetailsProps {
export function SelectedEventDetails(props: SelectedEventDetailsProps) {
const calendarsQuery = useVisibleCalendarsQuery();
const defaultReminders = (event: CalendarEvent) =>
- calendarsQuery.data?.find(
- (calendar) => calendar.id === reminderCalendarIdOf(event)
- )?.defaultReminders;
+ calendarsQuery.isSuccess
+ ? calendarsQuery.data?.find(
+ (calendar) => calendar.id === reminderCalendarIdOf(event)
+ )?.defaultReminders
+ : undefined;
const popoverSelection = createMemo(
() => {
const event = props.event();
diff --git a/apps/web/src/features/calendar/calendar.css b/apps/web/src/features/calendar/calendar.css
index 11a3125f0f..de86269e39 100644
--- a/apps/web/src/features/calendar/calendar.css
+++ b/apps/web/src/features/calendar/calendar.css
@@ -22,6 +22,47 @@
padding: 0.5rem;
}
+.calendar-view .fc .fc-daygrid-day:has([data-calendar-loading-skeleton]) {
+ position: relative;
+}
+
+/* Neighboring pages keep static loading feedback, without offscreen animation. */
+.pager-page[aria-hidden="true"] .calendar-view [data-calendar-loading-placeholder] {
+ animation: none;
+}
+@keyframes calendar-skeleton-pulse {
+ 0%,
+ 100% {
+ opacity: 0.55;
+ }
+ 50% {
+ opacity: 1;
+ }
+}
+/* Commit real event layout under the skeletons, then reveal both layers together. */
+.calendar-view-host[data-calendar-loading-state="visible"] .fc-event:not(.fc-event-mirror):not(.calendar-multi-day-selection-preview-event) {
+ opacity: 0;
+ visibility: hidden;
+ pointer-events: none;
+}
+@keyframes calendar-event-enter {
+ from {
+ opacity: 0;
+ }
+ to {
+ opacity: 1;
+ }
+}
+
+@media (prefers-reduced-motion: no-preference) {
+ .calendar-view [data-calendar-loading-placeholder] {
+ animation: calendar-skeleton-pulse 1.8s ease-in-out infinite;
+ }
+ .calendar-view-host[data-calendar-loading-state="revealing"] .fc-event:not(.fc-event-mirror) {
+ animation: calendar-event-enter 180ms ease-out;
+ }
+}
+
.calendar-view .fc {
color: var(--color-ink);
font-family: inherit;
diff --git a/apps/web/src/features/calendar/components/CalendarGrid.tsx b/apps/web/src/features/calendar/components/CalendarGrid.tsx
index db27ed82cf..16a49965c9 100644
--- a/apps/web/src/features/calendar/components/CalendarGrid.tsx
+++ b/apps/web/src/features/calendar/components/CalendarGrid.tsx
@@ -18,6 +18,7 @@ import {
createSignal,
type JSX,
Show,
+ untrack,
} from 'solid-js';
import { useTimeGridOpeningScroll } from '../hooks/use-time-grid-opening-scroll';
import {
@@ -152,6 +153,9 @@ function CalendarGridHost(props: {
/** Query-free, single-page calendar grid. */
export function CalendarGrid(props: CalendarGridProps) {
+ // FullCalendar only consumes initialView on mount. Tracking route changes
+ // here resets every page's options before the pager can schedule changeView.
+ const initialView = untrack(() => props.settings.initialView);
const mappedEvents = createMemo<EventInput[]>(() =>
mergeWorkingLocationEvents(props.events).map(({ event, occurrenceIds }) => {
const mapped = mapCalendarEventToFullCalendar(event);
@@ -226,7 +230,7 @@ export function CalendarGrid(props: CalendarGridProps) {
timeGridPlugin,
multiDaySelectionRenderingPlugin,
]}
- initialView={props.settings.initialView}
+ initialView={initialView}
initialDate={props.initialDate}
dayCount={props.settings.dayCount}
dateIncrement={
diff --git a/apps/web/src/features/calendar/components/CalendarPagerContext.tsx b/apps/web/src/features/calendar/components/CalendarPagerContext.tsx
index 2991a16a9f..277080b0eb 100644
--- a/apps/web/src/features/calendar/components/CalendarPagerContext.tsx
+++ b/apps/web/src/features/calendar/components/CalendarPagerContext.tsx
@@ -1,3 +1,4 @@
+import { createRenderQueue } from '@app/lib/utils/create-render-queue';
import { createAssertedContextProvider } from '@core/context/createContext';
import type { Calendar, DatesSetArg } from '@fullcalendar/core';
import { createPager, type PagerController } from '@ui/components/Pager';
@@ -47,6 +48,11 @@ const shiftedDateForView = (
return shifted;
};
+const navigateCalendar = (api: Calendar, view: string, date?: Date) => {
+ if (api.view.type !== view) api.changeView(view, date);
+ else if (date) api.gotoDate(date);
+};
+
interface CalendarPagerContextProps extends ParentProps {
[key: string]: unknown;
initialView: CalendarPeriodView;
@@ -84,6 +90,24 @@ function createCalendarPagerContext(props: CalendarPagerContextProps) {
const activePage = createMemo(() => pageHandle(activePageId()));
const activeData = createMemo(() => activePage()?.data);
const activeDateInfo = createMemo(() => activePage()?.dateInfo());
+ const renderQueue = createRenderQueue();
+ // Arrow clicks accumulate against the requested date, not the last grid that
+ // finished rendering. A newer request can replace an unfinished transition.
+ const [requestedDate, setRequestedDate] = createSignal<Date>();
+ let isDisposed = false;
+ onCleanup(() => {
+ isDisposed = true;
+ });
+ const navigationDate = () =>
+ requestedDate() ??
+ pageHandle(pager.targetPage() ?? activePageId())
+ ?.dateInfo()
+ ?.view.calendar.getDate();
+ const clearRequestedDate = (date: Date) => {
+ if (requestedDate() === date) setRequestedDate(undefined);
+ };
+ const periodView = () => props.initialView;
+ const isChangingView = () => activeDateInfo()?.view.type !== periodView();
const scrollElementFor = (handle: CalendarPageHandle | undefined) =>
timeGridScroller(handle?.element());
@@ -110,14 +134,8 @@ function createCalendarPagerContext(props: CalendarPagerContextProps) {
const sourceApi = source?.api();
if (!api || !sourceApi) return;
- const date = sourceApi.getDate();
- const view = sourceApi.view.type;
api.batchRendering(() => {
- if (api.view.type === view) {
- api.gotoDate(date);
- } else {
- api.changeView(view, date);
- }
+ navigateCalendar(api, sourceApi.view.type, sourceApi.getDate());
if (direction === 'previous') {
api.prev();
@@ -127,21 +145,24 @@ function createCalendarPagerContext(props: CalendarPagerContextProps) {
});
};
+ const queueBuffer = (id: CalendarPageId, direction: 'previous' | 'next') => {
+ const source = activePage();
+ renderQueue.enqueue(`buffer:${id}`, () => {
+ synchronizePage(pageHandle(id), source, direction);
+ copyActiveScrollPosition();
+ });
+ };
+
const synchronizeBuffers = () => {
const order = pageOrder();
const activeIndex = order.indexOf(activePageId());
- const current = activePage();
- const previousId = order[activeIndex - 1];
- const nextId = order[activeIndex + 1];
- if (previousId) {
- synchronizePage(pageHandle(previousId), current, 'previous');
- }
-
- if (nextId) {
- synchronizePage(pageHandle(nextId), current, 'next');
+ const neighbors = [
+ [order[activeIndex - 1], 'previous'],
+ [order[activeIndex + 1], 'next'],
+ ] as const;
+ for (const [id, direction] of neighbors) {
+ if (id) queueBuffer(id, direction);
}
-
- requestAnimationFrame(copyActiveScrollPosition);
};
const rotatePages = (
@@ -162,15 +183,16 @@ function createCalendarPagerContext(props: CalendarPagerContextProps) {
setActivePageId(() => destination);
});
- const current = pageHandle(destination);
- synchronizePage(pageHandle(recycledId), current, direction);
- requestAnimationFrame(copyActiveScrollPosition);
+ if (recycledId) queueBuffer(recycledId, direction);
};
const pager: PagerController<CalendarPageId> = createPager({
pageOrder,
activePage: activePageId,
- canChangePage: ({ to }) => pageHandle(to)?.api() !== undefined,
+ canChangePage: ({ to }) =>
+ !isChangingView() &&
+ !renderQueue.hasPending() &&
+ pageHandle(to)?.api() !== undefined,
onDragStart: copyActiveScrollPosition,
onTransitionStart: () => {
props.onNavigate();
@@ -221,15 +243,80 @@ function createCalendarPagerContext(props: CalendarPagerContextProps) {
}
};
- const gotoDate = (date: Date) => {
+ const scheduleActiveUpdate = () => {
pager.cancel();
+ renderQueue.clear();
+ renderQueue.enqueue(
+ 'active',
+ () => {
+ const api = activePage()?.api();
+ if (!api) return;
+ const date = requestedDate();
+ navigateCalendar(api, periodView(), date);
+ if (date) clearRequestedDate(date);
+ synchronizeBuffers();
+ },
+ true
+ );
+ };
+
+ const gotoDate = (date: Date) => {
+ setRequestedDate(date);
props.onNavigate();
- activePage()?.api()?.gotoDate(date);
- synchronizeBuffers();
+ scheduleActiveUpdate();
+ };
+
+ const finishDateNavigation = async (
+ transition: Promise<boolean>,
+ date: Date,
+ onCommit?: () => void
+ ) => {
+ const changed = await transition;
+ if (isDisposed || requestedDate() !== date) return;
+ if (changed) {
+ clearRequestedDate(date);
+ onCommit?.();
+ } else {
+ gotoDate(date);
+ }
+ };
+
+ const navigatePeriod = (direction: 'previous' | 'next') => {
+ const date = navigationDate();
+ if (!date) return;
+ const target = shiftedDateForView(
+ date,
+ periodView(),
+ direction === 'previous' ? -1 : 1
+ );
+ // Preserve the normal slide for a single click. Repeated clicks bypass the
+ // animation and stale buffers, coalescing directly to the latest date.
+ if (
+ requestedDate() ||
+ pager.phase() !== 'idle' ||
+ isChangingView() ||
+ renderQueue.hasPending()
+ ) {
+ gotoDate(target);
+ return;
+ }
+ setRequestedDate(target);
+ const transition =
+ direction === 'previous' ? pager.previous() : pager.next();
+ void finishDateNavigation(transition, target);
};
const navigateToDate = (date: Date) => {
+ // A date aim can arrive before a period's hidden buffers are ready. Page
+ // transitions reject that destination; aim the active grid directly instead.
+ if (requestedDate() || isChangingView() || renderQueue.hasPending()) {
+ gotoDate(date);
+ return;
+ }
pager.cancel();
+ // A newer date aim supersedes any deferred gotoDate, even when the newer
+ // aim uses a page transition rather than the active-grid navigation path.
+ renderQueue.clear();
const sourceApi = activePage()?.api();
if (!sourceApi) return;
@@ -258,49 +345,42 @@ function createCalendarPagerContext(props: CalendarPagerContextProps) {
return;
}
- destinationApi.batchRendering(() => {
- if (destinationApi.view.type === sourceApi.view.type) {
- destinationApi.gotoDate(date);
- } else {
- destinationApi.changeView(sourceApi.view.type, date);
- }
- });
+ setRequestedDate(date);
+ destinationApi.batchRendering(() =>
+ navigateCalendar(destinationApi, sourceApi.view.type, date)
+ );
const transition =
direction === 'previous' ? pager.previous() : pager.next();
- void transition.then(synchronizeBuffers);
+ void finishDateNavigation(transition, date, synchronizeBuffers);
};
const changeView = (view: CalendarPeriodView) => {
- props.onViewChange(view);
-
- const api = activePage()?.api();
- if (!api || api.view.type === view) return;
+ if (periodView() === view) return;
pager.cancel();
props.onNavigate();
- api.changeView(view);
- synchronizeBuffers();
+ props.onViewChange(view);
};
- // Browser history and direct URL navigation can change the route period
- // without going through `changeView`. Keep the mounted pager in sync without
- // emitting another route update or clearing an event that remains focused.
- createEffect(() => {
- const view = props.initialView;
- const api = activePage()?.api();
- if (!api || api.view.type === view) return;
- pager.cancel();
- api.changeView(view);
- synchronizeBuffers();
- });
+ // Route changes and date jumps share one coalesced active-grid update.
+ createEffect(
+ on([periodView, () => activePage()?.api()], ([view, api], previous) => {
+ if (!api) return;
+ if (api.view.type === view && (!previous || previous[0] === view)) return;
+ scheduleActiveUpdate();
+ })
+ );
return {
pager,
pageOrder,
+ periodView,
+ isChangingView,
activePageId,
activePage,
activeData,
activeDateInfo,
+ navigationDate,
activeTeamEvents: () => activePage()?.teamEvents?.() ?? [],
visibleRange: () => activeData()?.range(),
initialDateFor: (id: CalendarPageId) => initialDates[id],
@@ -310,6 +390,8 @@ function createCalendarPagerContext(props: CalendarPagerContextProps) {
gotoDate,
navigateToDate,
navigateToToday: () => navigateToDate(new Date()),
+ previousPeriod: () => navigatePeriod('previous'),
+ nextPeriod: () => navigatePeriod('next'),
changeView,
};
}
diff --git a/apps/web/src/features/calendar/components/PeriodSelector.tsx b/apps/web/src/features/calendar/components/PeriodSelector.tsx
index 4e572caa1f..f063a6a5de 100644
--- a/apps/web/src/features/calendar/components/PeriodSelector.tsx
+++ b/apps/web/src/features/calendar/components/PeriodSelector.tsx
@@ -48,12 +48,7 @@ function createCalendarPeriodControls(onSelect?: () => void) {
() => calendarPager.activeDateInfo()?.view.calendar.getDate() ?? initialDate
);
- const activeView = createMemo<CalendarPeriodView>(
- () =>
- (calendarPager.activeDateInfo()?.view.type as
- | CalendarPeriodView
- | undefined) ?? calendarView.displaySettings.periodView
- );
+ const activeView = calendarPager.periodView;
const highlightedRange = createMemo(() => {
const dateInfo = calendarPager.activeDateInfo();
@@ -75,7 +70,7 @@ function createCalendarPeriodControls(onSelect?: () => void) {
const changeView = (view: CalendarPeriodView) => {
setPickerState('open', false);
onSelect?.();
- if (calendarPager.activeDateInfo()?.view.type === view) return;
+ if (calendarPager.periodView() === view) return;
calendarPager.changeView(view);
};
diff --git a/apps/web/src/features/calendar/hooks/use-calendar-occurrence-data.ts b/apps/web/src/features/calendar/hooks/use-calendar-occurrence-data.ts
index 644765bc5d..c2840f5616 100644
--- a/apps/web/src/features/calendar/hooks/use-calendar-occurrence-data.ts
+++ b/apps/web/src/features/calendar/hooks/use-calendar-occurrence-data.ts
@@ -51,7 +51,12 @@ export function useCalendarOccurrenceData(
}
);
const events = createMemo(() => {
- if (!isRangeSupported()) return [];
+ if (
+ !isRangeSupported() ||
+ !occurrencesQuery.isSuccess ||
+ occurrencesQuery.isPlaceholderData
+ )
+ return [];
const sourceById = options.sourceById?.();
return (occurrencesQuery.data?.items ?? []).map((item) =>
mapCalendarOccurrence(item, {
@@ -73,6 +78,8 @@ export function useCalendarOccurrenceData(
(isRangeSupported() &&
(occurrencesQuery.isPending || occurrencesQuery.isPlaceholderData));
const isSyncing = () =>
+ occurrencesQuery.isSuccess &&
+ !occurrencesQuery.isPlaceholderData &&
occurrencesQuery.data?.syncStatus === CalendarSyncStatus.syncing;
return {
diff --git a/apps/web/src/features/calendar/hooks/use-calendar-sources.ts b/apps/web/src/features/calendar/hooks/use-calendar-sources.ts
index 5276bcf103..4dab363465 100644
--- a/apps/web/src/features/calendar/hooks/use-calendar-sources.ts
+++ b/apps/web/src/features/calendar/hooks/use-calendar-sources.ts
@@ -7,7 +7,9 @@ import { DEFAULT_CALENDAR_SOURCE } from '../types';
export function useCalendarSources() {
const calendarsQuery = useVisibleCalendarsQuery();
const sources = createMemo<CalendarSource[]>(() => {
- const calendars = calendarsQuery.data;
+ const calendars = calendarsQuery.isSuccess
+ ? calendarsQuery.data
+ : undefined;
if (!calendars || calendars.length === 0) {
return [DEFAULT_CALENDAR_SOURCE];
}
diff --git a/apps/web/src/features/calendar/hooks/use-team-ooo.ts b/apps/web/src/features/calendar/hooks/use-team-ooo.ts
index e9ac40337c..015146815d 100644
--- a/apps/web/src/features/calendar/hooks/use-team-ooo.ts
+++ b/apps/web/src/features/calendar/hooks/use-team-ooo.ts
@@ -104,10 +104,14 @@ export function useTeamOooEvents(
})
);
const events = createMemo(() => {
- // Read data only on success: a failed overlay fetch degrades to no events
- // since the grid's own state is driven by the occurrences query, and gating
- // on success keeps this off the pending/errored resource read that suspends.
- if (!teamOooEnabled() || !isRangeSupported() || !query.isSuccess) {
+ // Pending reads suspend, and placeholder data belongs to the previous
+ // range. Neither can supply events for the current viewport.
+ if (
+ !teamOooEnabled() ||
+ !isRangeSupported() ||
+ !query.isSuccess ||
+ query.isPlaceholderData
+ ) {
return [];
}
return query.data.map(mapTeamOooItem);
diff --git a/apps/web/src/features/calendar/primitives/create-calendar-loading-transition.ts b/apps/web/src/features/calendar/primitives/create-calendar-loading-transition.ts
new file mode 100644
index 0000000000..f220b43989
--- /dev/null
+++ b/apps/web/src/features/calendar/primitives/create-calendar-loading-transition.ts
@@ -0,0 +1,174 @@
+import type { Transition } from '@macro-inc/machine';
+import { createSolidMachine } from '@macro-inc/machine/solid';
+import { onCleanup } from 'solid-js';
+
+const SKELETON_SHOW_DELAY_MS = 120;
+const SKELETON_MIN_VISIBLE_MS = 240;
+// Matches the skeleton's duration-180 opacity transition.
+const SKELETON_FADE_OUT_MS = 180;
+
+type LoadingState =
+ | { t: 'hidden' }
+ | { t: 'waiting' }
+ | { t: 'visible'; visibleSince: number; loading: boolean }
+ | { t: 'leaving' };
+
+type LoadingEvent =
+ | { t: 'load-started'; now: number }
+ | { t: 'load-finished' }
+ | { t: 'delay-elapsed'; now: number }
+ | { t: 'minimum-elapsed' }
+ | { t: 'fade-elapsed' }
+ | { t: 'reset' };
+
+export type CalendarLoadingPhase = LoadingState['t'];
+
+function transitionTo(
+ state: LoadingState
+): Transition<LoadingState, CalendarLoadingPhase> {
+ return {
+ state,
+ commands: [state.t],
+ };
+}
+
+/** State scopes own timers, so interrupted loads cannot leave stale transitions. */
+export function createCalendarLoadingTransition(
+ onPhaseChange?: (phase: CalendarLoadingPhase) => void
+) {
+ const machine = createSolidMachine<
+ LoadingState,
+ LoadingEvent,
+ CalendarLoadingPhase
+ >({
+ initial: { t: 'hidden' },
+ def: {
+ hidden: {
+ on: (_state, event) => {
+ if (event.t === 'load-started') {
+ return transitionTo({ t: 'waiting' });
+ }
+
+ if (event.t === 'reset') {
+ return transitionTo({ t: 'hidden' });
+ }
+ },
+ },
+ waiting: {
+ on: (_state, event) => {
+ const shouldHide = event.t === 'load-finished' || event.t === 'reset';
+
+ if (shouldHide) {
+ return transitionTo({ t: 'hidden' });
+ }
+
+ if (event.t === 'delay-elapsed') {
+ return transitionTo({
+ t: 'visible',
+ visibleSince: event.now,
+ loading: true,
+ });
+ }
+ },
+ },
+ visible: {
+ on: (state, event) => {
+ if (event.t === 'reset') {
+ return transitionTo({ t: 'hidden' });
+ }
+
+ if (event.t === 'load-started' && !state.loading) {
+ return { state: { ...state, loading: true } };
+ }
+
+ if (event.t === 'load-finished' && state.loading) {
+ return { state: { ...state, loading: false } };
+ }
+
+ if (event.t === 'minimum-elapsed' && !state.loading) {
+ return transitionTo({ t: 'leaving' });
+ }
+ },
+ },
+ leaving: {
+ on: (_state, event) => {
+ if (event.t === 'load-started') {
+ return transitionTo({
+ t: 'visible',
+ visibleSince: event.now,
+ loading: true,
+ });
+ }
+
+ const shouldHide = event.t === 'fade-elapsed' || event.t === 'reset';
+
+ if (shouldHide) {
+ return transitionTo({ t: 'hidden' });
+ }
+ },
+ },
+ },
+ scopes: {
+ waiting: (_state, dispatch) => {
+ const timer = setTimeout(
+ () => dispatch({ t: 'delay-elapsed', now: Date.now() }),
+ SKELETON_SHOW_DELAY_MS
+ );
+
+ return () => clearTimeout(timer);
+ },
+ visible: (state, dispatch) => {
+ if (state.loading) {
+ return;
+ }
+
+ const elapsedMs = Date.now() - state.visibleSince;
+ const remainingMs = Math.max(0, SKELETON_MIN_VISIBLE_MS - elapsedMs);
+
+ if (remainingMs === 0) {
+ dispatch({ t: 'minimum-elapsed' });
+ return;
+ }
+
+ const timer = setTimeout(
+ () => dispatch({ t: 'minimum-elapsed' }),
+ remainingMs
+ );
+
+ return () => clearTimeout(timer);
+ },
+ leaving: (_state, dispatch) => {
+ const timer = setTimeout(
+ () => dispatch({ t: 'fade-elapsed' }),
+ SKELETON_FADE_OUT_MS
+ );
+
+ return () => clearTimeout(timer);
+ },
+ },
+ execute: (phase) => onPhaseChange?.(phase),
+ });
+
+ function reset() {
+ machine.dispatch({ t: 'reset' });
+ }
+
+ function setLoading(loading: boolean) {
+ if (!loading) {
+ return machine.dispatch({ t: 'load-finished' });
+ }
+
+ const now = Date.now();
+
+ return machine.dispatch({ t: 'load-started', now });
+ }
+
+ // Solid runs cleanups in reverse order: reset before the machine is disposed.
+ onCleanup(reset);
+
+ return {
+ phase: () => machine.state().t,
+ setLoading,
+ reset,
+ };
+}
diff --git a/apps/web/src/lib/fullcalendar-solid/FullCalendar.test.tsx b/apps/web/src/lib/fullcalendar-solid/FullCalendar.test.tsx
index e4729a93ae..e6457e1918 100644
--- a/apps/web/src/lib/fullcalendar-solid/FullCalendar.test.tsx
+++ b/apps/web/src/lib/fullcalendar-solid/FullCalendar.test.tsx
@@ -121,6 +121,7 @@ describe('FullCalendar Solid connector', () => {
.map((event) => event.title)
).toEqual(['First']);
+ const resetOptions = vi.spyOn(getCalendar(), 'resetOptions');
setEvents([{ id: 'first', title: 'Updated', start: '2025-01-16' }]);
await waitFor(() => {
@@ -130,6 +131,61 @@ describe('FullCalendar Solid connector', () => {
.map((event) => event.title)
).toEqual(['Updated']);
});
+ expect(resetOptions).toHaveBeenCalledOnce();
+ expect(resetOptions.mock.calls[0][1]).toEqual(['events']);
+ });
+
+ it('restores defaults when a reactive option is removed', () => {
+ const [options, setOptions] = createSignal<{ dayHeaders?: boolean }>({
+ dayHeaders: false,
+ });
+ const { container } = render(() => (
+ <FullCalendar.Root
+ {...options()}
+ plugins={[dayGridPlugin]}
+ initialView="dayGridMonth"
+ initialDate="2025-01-15"
+ headerToolbar={false}
+ handleWindowResize={false}
+ >
+ <FullCalendar.Host />
+ </FullCalendar.Root>
+ ));
+ expect(container.querySelector('.fc-col-header')).toBeNull();
+ setOptions({});
+ expect(container.querySelector('.fc-col-header')).not.toBeNull();
+ });
+
+ it('uses the latest datesSet callback without resetting unchanged options', () => {
+ const first = vi.fn();
+ const second = vi.fn();
+ const [callback, setCallback] =
+ createSignal<(info: DatesSetArg) => void>(first);
+ let calendarContext: ReturnType<typeof useFullCalendar> | undefined;
+ function Capture() {
+ calendarContext = useFullCalendar();
+ return null;
+ }
+ render(() => (
+ <FullCalendar.Root
+ plugins={[dayGridPlugin]}
+ initialView="dayGridMonth"
+ initialDate="2025-01-15"
+ headerToolbar={false}
+ handleWindowResize={false}
+ datesSet={callback()}
+ >
+ <Capture />
+ <FullCalendar.Host />
+ </FullCalendar.Root>
+ ));
+ const api = calendarContext!.api()!;
+ const resetOptions = vi.spyOn(api, 'resetOptions');
+ setCallback(() => second);
+ expect(resetOptions).not.toHaveBeenCalled();
+ api.next();
+ expect(first).toHaveBeenCalledOnce();
+ expect(second).toHaveBeenCalledOnce();
});
it('exposes date info before invoking the datesSet callback', () => {
diff --git a/apps/web/src/lib/fullcalendar-solid/FullCalendar.tsx b/apps/web/src/lib/fullcalendar-solid/FullCalendar.tsx
index 325ed86e69..d2f0b8e2a7 100644
--- a/apps/web/src/lib/fullcalendar-solid/FullCalendar.tsx
+++ b/apps/web/src/lib/fullcalendar-solid/FullCalendar.tsx
@@ -27,6 +27,7 @@ import {
on,
onCleanup,
splitProps,
+ untrack,
useContext,
} from 'solid-js';
import { render } from 'solid-js/web';
@@ -272,6 +273,22 @@ function createFullCalendarController(
>();
const [listenForContentRegistrationChange, notifyContentRegistrationChange] =
createSignal<void>(undefined, { equals: false });
+ let appliedOptions: CalendarOptions | undefined;
+ const handleDatesSet = (info: DatesSetArg) => {
+ setDateInfo(info);
+ untrack(getOptions).datesSet?.(info);
+ };
+ // Metadata identities must stay stable across event-only updates. Rebuilding
+ // them causes FullCalendar to remount unrelated headers and content slots.
+ const customRenderingMetaMap = createMemo(() => {
+ listenForContentRegistrationChange();
+ return Object.fromEntries(
+ [...contentRegistrations].map(([name, registration]) => [
+ name,
+ createSolidRenderingMeta(registration.generator, registration.owner),
+ ])
+ );
+ });
const requestResize = () => {
if (isUnmounting() || !calendar()) return;
@@ -294,12 +311,11 @@ function createFullCalendarController(
};
const buildOptions = createMemo(() => {
- listenForContentRegistrationChange();
return buildCalendarOptions(
getOptions(),
- contentRegistrations,
+ customRenderingMetaMap(),
handleCustomRendering,
- setDateInfo
+ handleDatesSet
);
});
@@ -308,8 +324,23 @@ function createFullCalendarController(
if (!calendarInstance) return;
const nextOptions = buildOptions();
+ const next = nextOptions.options as Record<string, unknown>;
+ const previous = (appliedOptions ?? {}) as Record<string, unknown>;
+ const changedOptionNames = Object.keys(next).filter(
+ (name) => !Object.is(previous[name], next[name])
+ );
+ const hasRemovedOption = Object.keys(previous).some(
+ (name) => !(name in next)
+ );
+ if (changedOptionNames.length === 0 && !hasRemovedOption) return;
+ appliedOptions = nextOptions.options;
customRenderingManager.retainGeneratorNames(nextOptions.contentOptionNames);
- calendarInstance.resetOptions(nextOptions.options);
+ // FullCalendar merges partial updates over existing overrides. Removing a prop
+ // needs a full replacement to restore defaults; otherwise refine only changes.
+ calendarInstance.resetOptions(
+ nextOptions.options,
+ hasRemovedOption ? undefined : changedOptionNames
+ );
};
createEffect(on(getOptions, resetOptions, { defer: true }));
@@ -324,6 +355,7 @@ function createFullCalendarController(
setResizeFrame(undefined);
}
calendar()?.destroy();
+ appliedOptions = undefined;
setCalendar(undefined);
setDateInfo(undefined);
setHostElement(undefined);
@@ -346,6 +378,7 @@ function createFullCalendarController(
setIsUnmounting(false);
setHostElement(element);
const initialOptions = buildOptions();
+ appliedOptions = initialOptions.options;
customRenderingManager.retainGeneratorNames(
initialOptions.contentOptionNames
);
@@ -389,24 +422,13 @@ function createFullCalendarController(
function buildCalendarOptions(
rootOptions: FullCalendarOptions,
- contentRegistrations: Map<SolidContentOptionName, ContentRegistration>,
+ customRenderingMetaMap: Record<string, SolidRenderingMeta>,
handleCustomRendering: (rendering: AnyCustomRendering) => void,
- setDateInfo: (dateInfo: DatesSetArg) => void
+ handleDatesSet: (dateInfo: DatesSetArg) => void
): BuiltCalendarOptions {
const options = { ...rootOptions } as Record<string, unknown>;
- const externalDatesSet = rootOptions.datesSet;
- const customRenderingMetaMap: Record<string, SolidRenderingMeta> = {};
-
- options.datesSet = (dateInfo: DatesSetArg) => {
- setDateInfo(dateInfo);
- externalDatesSet?.(dateInfo);
- };
-
- for (const [optionName, registration] of contentRegistrations) {
- customRenderingMetaMap[optionName] = createSolidRenderingMeta(
- registration.generator,
- registration.owner
- );
+ options.datesSet = handleDatesSet;
+ for (const optionName of Object.keys(customRenderingMetaMap)) {
delete options[optionName];
}
diff --git a/apps/web/src/lib/utils/create-render-queue.test.ts b/apps/web/src/lib/utils/create-render-queue.test.ts
new file mode 100644
index 0000000000..8c40609eea
--- /dev/null
+++ b/apps/web/src/lib/utils/create-render-queue.test.ts
@@ -0,0 +1,65 @@
+import { createRoot } from 'solid-js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { createRenderQueue } from './create-render-queue';
+
+beforeEach(() => vi.useFakeTimers());
+afterEach(() => vi.useRealTimers());
+
+describe('render queue', () => {
+ it('defers work, coalesces keyed changes, and prioritizes urgent jobs', async () => {
+ const calls: string[] = [];
+ const { queue, dispose } = createRoot((dispose) => ({
+ queue: createRenderQueue(),
+ dispose,
+ }));
+ queue.enqueue('buffer', () => calls.push('buffer'));
+ queue.enqueue('view', () => calls.push('month'), true);
+ queue.enqueue('view', () => calls.push('day'), true);
+ expect(calls).toEqual([]);
+ expect(queue.hasPending()).toBe(true);
+ await vi.advanceTimersByTimeAsync(16);
+ expect(calls).toEqual(['day']);
+ expect(queue.hasPending()).toBe(true);
+ await vi.advanceTimersByTimeAsync(16);
+ expect(calls).toEqual(['day', 'buffer']);
+ expect(queue.hasPending()).toBe(false);
+ dispose();
+ });
+
+ it('cancels queued jobs and pending work on disposal', async () => {
+ const run = vi.fn();
+ const { queue, dispose } = createRoot((dispose) => ({
+ queue: createRenderQueue(),
+ dispose,
+ }));
+ queue.enqueue('view', run);
+ queue.clear();
+ expect(queue.hasPending()).toBe(false);
+ await vi.runAllTimersAsync();
+ expect(run).not.toHaveBeenCalled();
+ queue.enqueue('view', run);
+ dispose();
+ await vi.runAllTimersAsync();
+ expect(run).not.toHaveBeenCalled();
+ });
+
+ it('services work queued by another job in a separate task', async () => {
+ const calls: string[] = [];
+ const { queue, dispose } = createRoot((dispose) => ({
+ queue: createRenderQueue(),
+ dispose,
+ }));
+ queue.enqueue('view', () => {
+ calls.push('view');
+ queue.enqueue('previous', () => calls.push('previous'));
+ queue.enqueue('next', () => calls.push('next'));
+ });
+ await vi.advanceTimersByTimeAsync(16);
+ expect(calls).toEqual(['view']);
+ await vi.advanceTimersByTimeAsync(16);
+ expect(calls).toEqual(['view', 'previous']);
+ await vi.advanceTimersByTimeAsync(16);
+ expect(calls).toEqual(['view', 'previous', 'next']);
+ dispose();
+ });
+});
diff --git a/apps/web/src/lib/utils/create-render-queue.ts b/apps/web/src/lib/utils/create-render-queue.ts
new file mode 100644
index 0000000000..057dca9292
--- /dev/null
+++ b/apps/web/src/lib/utils/create-render-queue.ts
@@ -0,0 +1,44 @@
+import { scheduleIdle, throttle } from '@solid-primitives/scheduled';
+import { onCleanup } from 'solid-js';
+
+/** Coalesces keyed render work and yields between jobs. */
+export function createRenderQueue() {
+ const jobs = new Map<string, { run: () => void; urgent: boolean }>();
+ const runNext = () => {
+ const next =
+ [...jobs].find(([, job]) => job.urgent) ?? jobs.entries().next().value;
+ if (!next) return;
+ const [key, job] = next;
+ jobs.delete(key);
+ try {
+ job.run();
+ } finally {
+ // The scheduler resets its throttled flag after the callback returns.
+ queueMicrotask(() => {
+ if (jobs.size > 0) schedule();
+ });
+ }
+ };
+ // Idle callbacks let controls paint first. A bounded timeout also services
+ // hidden/busy tabs. Safari gets a frame-length timer instead of idle work.
+ const schedule =
+ typeof requestIdleCallback === 'undefined'
+ ? throttle(runNext, 16)
+ : scheduleIdle(runNext, 50);
+
+ const clear = () => {
+ schedule.clear();
+ jobs.clear();
+ };
+ onCleanup(clear);
+
+ return {
+ enqueue(key: string, run: () => void, urgent = false) {
+ jobs.set(key, { run, urgent });
+ schedule();
+ },
+ /** Imperative status for deciding whether another interaction can use queued work. */
+ hasPending: () => jobs.size > 0,
+ clear,
+ };
+}
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index 270f5bc403..1d62c70a00 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -873,6 +873,32 @@ that path. Calendar navigation defaults to Day on phones and Week on desktop; th
recent choice is remembered locally for navigation that does not specify a period. An
opened event is reflected in the pane-owned `sN.calendar.eventId` search parameter.
+Period selection updates its label and route immediately. The active grid redraws
+on a deferred task; hidden neighboring periods follow on separate tasks. Calendar
+grids stay mounted and undimmed while occurrences load. An uncached range never
+shows events from the previous range. After a short delay, representative event
+skeletons appear without adding synthetic FullCalendar events. Week/Day use sparse
+blocks with varied start times and durations, plus separate all-day bars. Month mixes
+filled bars for all-day/multi-day-style entries with single subtle text lines for
+single-day timed-style entries, without placeholder dots or time chips. Patterns stay
+stable for each date and clear the date headers. Skeletons preserve the grid, scroll
+position, and navigation.
+Quick loads skip the skeletons. Real events lay out underneath during the brief
+minimum display, then fade in as the skeletons fade out. Changing period during a
+load carries feedback into the new cells without restarting the appearance delay.
+Background refreshes retain current events without skeletons or a transient loading
+pill. Provider sync and errors still show their own states. Verify delayed occurrence
+responses: switch Month/Week/Day rapidly and navigate without blanking the grid.
+Confirm mixed event shapes, stable positions, clean handoff, and an uncovered Retry.
+Reduced-motion mode disables pulses and transitions. The page stays busy until the
+handoff starts. Hidden pages do not animate. Resize to confirm skeleton alignment.
+
+A single period arrow retains its slide. Rapid arrow clicks and period hotkeys
+accumulate against the requested date and interrupt unfinished slides, without
+waiting for event responses or hidden-page redraws. Verify repeated forward clicks
+and mixed directions reach the cumulative date while events are still loading.
+Touch swipes retain their page-readiness gates.
+
Quick-call creation, incoming invitations, Live lists, Macro meeting links, and
the `/app/meet/*` routes require the PostHog flag `enable-quick-calls`. While the
flag loads or is off, those controls stay hidden and meeting routes do not mount