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.

feat(calendar): add copy availability feature for calendar sharing (#5888)

Jacob Beckerman6cd2e841f989
diff --git a/apps/web/src/features/block-calendar/components/Header.tsx b/apps/web/src/features/block-calendar/components/Header.tsx
index 833032ac6d..8175a8c199 100644
--- a/apps/web/src/features/block-calendar/components/Header.tsx
+++ b/apps/web/src/features/block-calendar/components/Header.tsx
@@ -1,3 +1,4 @@
+import { CopyAvailabilityButton } from '@app/features/calendar/availability/CopyAvailabilityButton';
import {
type CalendarPageId,
useCalendarPager,
@@ -103,9 +104,12 @@ export function Header() {
<Show
when={isMobile()}
fallback={
- <span class="min-w-0 truncate text-base font-semibold text-ink">
- {dateTitle()}
- </span>
+ <>
+ <span class="min-w-0 truncate text-base font-semibold text-ink">
+ {dateTitle()}
+ </span>
+ <CopyAvailabilityButton class="ml-2" />
+ </>
}
>
<MonthDrawer month={currentDate()} />
diff --git a/apps/web/src/features/calendar/availability/CopyAvailabilityButton.tsx b/apps/web/src/features/calendar/availability/CopyAvailabilityButton.tsx
new file mode 100644
index 0000000000..702b46cecd
--- /dev/null
+++ b/apps/web/src/features/calendar/availability/CopyAvailabilityButton.tsx
@@ -0,0 +1,203 @@
+import { toast } from '@core/component/Toast/Toast';
+import { writeClipboardData } from '@core/util/dataTransfer';
+import CalendarCheckIcon from '@phosphor/calendar-check.svg';
+import CaretRightIcon from '@phosphor/caret-right.svg';
+import CheckIcon from '@phosphor/check.svg';
+import GearIcon from '@phosphor/gear.svg';
+import { ButtonGroup, cn, Dropdown } from '@ui';
+import { For, Show } from 'solid-js';
+import { useCalendarConnectedInboxes } from '../hooks/use-calendar-connected-inboxes';
+import {
+ AVAILABILITY_RANGE_OPTIONS,
+ type AvailabilityRangeKey,
+} from './availability';
+import { useAvailabilitySettings } from './settings';
+import { useAvailabilityText } from './use-availability-text';
+
+interface TimeOption {
+ value: string;
+ label: string;
+}
+
+const timeLabelFormatter = new Intl.DateTimeFormat(undefined, {
+ hour: 'numeric',
+ minute: '2-digit',
+});
+
+/** Half-hour choices between two local hours (inclusive). */
+function timeOptions(fromHour: number, toHour: number): TimeOption[] {
+ const options: TimeOption[] = [];
+ for (let minutes = fromHour * 60; minutes <= toHour * 60; minutes += 30) {
+ const hour = Math.floor(minutes / 60);
+ const minute = minutes % 60;
+ options.push({
+ value: `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`,
+ label: timeLabelFormatter.format(new Date(2000, 0, 1, hour, minute)),
+ });
+ }
+ return options;
+}
+
+const START_TIME_OPTIONS = timeOptions(6, 12);
+const END_TIME_OPTIONS = timeOptions(12, 22);
+
+function timeOptionLabel(options: TimeOption[], value: string): string {
+ const known = options.find((option) => option.value === value)?.label;
+ if (known) return known;
+ const [hour = 0, minute = 0] = value.split(':').map(Number);
+ return timeLabelFormatter.format(new Date(2000, 0, 1, hour, minute));
+}
+
+function TimeRadioGroup(props: {
+ options: TimeOption[];
+ value: string;
+ onChange: (value: string) => void;
+}) {
+ return (
+ <Dropdown.RadioGroup value={props.value} onChange={props.onChange}>
+ <For each={props.options}>
+ {(option) => (
+ <Dropdown.RadioItem closeOnSelect value={option.value}>
+ <span class="flex-1">{option.label}</span>
+ <Dropdown.ItemIndicator>
+ <CheckIcon class="size-3.5 text-accent" />
+ </Dropdown.ItemIndicator>
+ </Dropdown.RadioItem>
+ )}
+ </For>
+ </Dropdown.RadioGroup>
+ );
+}
+
+/**
+ * Split control for sharing availability: the labeled half opens a range
+ * menu ("Today" … "Next 14 days") that copies the viewer's free slots as
+ * text; the gear half opens the feature's settings (workday start/end,
+ * exclude weekends).
+ */
+export function CopyAvailabilityButton(props: { class?: string }) {
+ const getAvailabilityText = useAvailabilityText();
+ const { settings, setStartTime, setEndTime, setExcludeWeekends } =
+ useAvailabilitySettings();
+ // Without a calendar-connected inbox every range would read as fully
+ // free, so the control offers nothing useful and stays hidden.
+ const connectedInboxes = useCalendarConnectedInboxes();
+
+ const startTimeLabel = () =>
+ timeOptionLabel(START_TIME_OPTIONS, settings().startTime);
+ const endTimeLabel = () =>
+ timeOptionLabel(END_TIME_OPTIONS, settings().endTime);
+
+ const copyRange = async (rangeKey: AvailabilityRangeKey) => {
+ try {
+ const text = await getAvailabilityText(rangeKey);
+ if (!text) {
+ toast.alert('No free time in that range');
+ return;
+ }
+ if (await writeClipboardData({ 'text/plain': text })) {
+ toast.success('Availability copied');
+ } else {
+ toast.failure('Failed to copy availability');
+ }
+ } catch {
+ toast.failure('Failed to load availability');
+ }
+ };
+
+ return (
+ <Show when={connectedInboxes().length > 0}>
+ <ButtonGroup
+ variant="ghost"
+ size="sm"
+ class={cn('shrink-0 rounded-lg border border-edge-muted', props.class)}
+ >
+ <Dropdown placement="bottom-start">
+ <Dropdown.Trigger class="gap-1.5 bg-transparent px-2 hover:bg-ink/[0.04]">
+ <CalendarCheckIcon class="size-3.5 shrink-0" />
+ <span class="truncate text-xs font-medium">Copy availability</span>
+ </Dropdown.Trigger>
+ <Dropdown.Content class="min-w-40">
+ <Dropdown.Group>
+ <For each={AVAILABILITY_RANGE_OPTIONS}>
+ {(option) => (
+ <Dropdown.Item
+ closeOnSelect
+ onSelect={() => void copyRange(option.key)}
+ >
+ <span class="flex-1 truncate">{option.label}</span>
+ </Dropdown.Item>
+ )}
+ </For>
+ </Dropdown.Group>
+ </Dropdown.Content>
+ </Dropdown>
+
+ <ButtonGroup.Divider />
+
+ <Dropdown placement="bottom-end">
+ <Dropdown.Trigger
+ class="bg-transparent p-1 hover:bg-ink/[0.04]"
+ label="Availability settings"
+ >
+ <GearIcon class="size-3.5" />
+ </Dropdown.Trigger>
+ <Dropdown.Content class="w-56 max-w-[calc(100vw-1rem)]">
+ <Dropdown.Group>
+ <Dropdown.GroupLabel>Availability</Dropdown.GroupLabel>
+ <Dropdown.CheckboxItem
+ checked={settings().excludeWeekends}
+ closeOnSelect={false}
+ onChange={setExcludeWeekends}
+ >
+ <span class="flex-1 truncate">Exclude weekends</span>
+ </Dropdown.CheckboxItem>
+
+ <Dropdown.Sub>
+ <Dropdown.SubTrigger>
+ <span class="min-w-0 flex-1 truncate text-xs text-ink-muted">
+ Start time
+ </span>
+ <span class="text-sm font-medium text-ink">
+ {startTimeLabel()}
+ </span>
+ <CaretRightIcon class="size-3 shrink-0 text-ink-muted" />
+ </Dropdown.SubTrigger>
+ <Dropdown.SubContent class="max-h-72 min-w-36 overflow-y-auto">
+ <Dropdown.Group>
+ <TimeRadioGroup
+ options={START_TIME_OPTIONS}
+ value={settings().startTime}
+ onChange={setStartTime}
+ />
+ </Dropdown.Group>
+ </Dropdown.SubContent>
+ </Dropdown.Sub>
+
+ <Dropdown.Sub>
+ <Dropdown.SubTrigger>
+ <span class="min-w-0 flex-1 truncate text-xs text-ink-muted">
+ End time
+ </span>
+ <span class="text-sm font-medium text-ink">
+ {endTimeLabel()}
+ </span>
+ <CaretRightIcon class="size-3 shrink-0 text-ink-muted" />
+ </Dropdown.SubTrigger>
+ <Dropdown.SubContent class="max-h-72 min-w-36 overflow-y-auto">
+ <Dropdown.Group>
+ <TimeRadioGroup
+ options={END_TIME_OPTIONS}
+ value={settings().endTime}
+ onChange={setEndTime}
+ />
+ </Dropdown.Group>
+ </Dropdown.SubContent>
+ </Dropdown.Sub>
+ </Dropdown.Group>
+ </Dropdown.Content>
+ </Dropdown>
+ </ButtonGroup>
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/calendar/availability/availability.test.ts b/apps/web/src/features/calendar/availability/availability.test.ts
new file mode 100644
index 0000000000..eef720c04c
--- /dev/null
+++ b/apps/web/src/features/calendar/availability/availability.test.ts
@@ -0,0 +1,371 @@
+import type { CalendarOccurrenceItem } from '@service-storage/generated/schemas/calendarOccurrenceItem';
+import { describe, expect, it } from 'vitest';
+import {
+ type AvailabilitySettings,
+ busyIntervalsFromOccurrences,
+ computeAvailability,
+ DEFAULT_AVAILABILITY_SETTINGS,
+ formatAvailabilityText,
+ resolveAvailabilityWindow,
+ sanitizeAvailabilitySettings,
+} from './availability';
+import { rangeTimeZoneLabel } from './zone-label';
+
+// Mon Aug 24 2026, 10:00 local.
+const MONDAY_10AM = new Date(2026, 7, 24, 10, 0);
+
+const SETTINGS: AvailabilitySettings = {
+ startTime: '09:00',
+ endTime: '18:00',
+ excludeWeekends: true,
+};
+
+function timedItem(options: {
+ start: Date;
+ end: Date;
+ isCancelled?: boolean;
+ status?: string;
+ transparency?: string;
+ selfResponseStatus?: string;
+}): CalendarOccurrenceItem {
+ return {
+ event: {
+ status: options.status ?? 'confirmed',
+ transparency: options.transparency ?? 'opaque',
+ attendees: options.selfResponseStatus
+ ? [
+ {
+ email: '[email protected]',
+ isSelf: true,
+ isOptional: false,
+ isOrganizer: false,
+ responseStatus: options.selfResponseStatus,
+ },
+ ]
+ : [],
+ },
+ occurrence: {
+ isCancelled: options.isCancelled ?? false,
+ time: {
+ kind: 'timed',
+ startsAt: options.start.toISOString(),
+ endsAt: options.end.toISOString(),
+ },
+ },
+ } as unknown as CalendarOccurrenceItem;
+}
+
+function allDayItem(): CalendarOccurrenceItem {
+ return {
+ event: { status: 'confirmed', transparency: 'opaque', attendees: [] },
+ occurrence: {
+ isCancelled: false,
+ time: { kind: 'allDay', startDate: '2026-08-24', endDate: '2026-08-25' },
+ },
+ } as unknown as CalendarOccurrenceItem;
+}
+
+function localDay(year: number, month: number, day: number) {
+ return new Date(year, month, day).getTime();
+}
+
+describe('resolveAvailabilityWindow', () => {
+ it('covers only today for the today range', () => {
+ const window = resolveAvailabilityWindow('today', MONDAY_10AM);
+ expect(window.start.getTime()).toBe(localDay(2026, 7, 24));
+ expect(window.endExclusive.getTime()).toBe(localDay(2026, 7, 25));
+ });
+
+ it('runs through the coming Friday for this week', () => {
+ const window = resolveAvailabilityWindow('thisWeek', MONDAY_10AM);
+ // Mon Aug 24 → Fri Aug 28 inclusive.
+ expect(window.endExclusive.getTime()).toBe(localDay(2026, 7, 29));
+ });
+
+ it('treats a Friday as the last day of this week', () => {
+ const friday = new Date(2026, 7, 28, 10, 0);
+ const window = resolveAvailabilityWindow('thisWeek', friday);
+ expect(window.start.getTime()).toBe(localDay(2026, 7, 28));
+ expect(window.endExclusive.getTime()).toBe(localDay(2026, 7, 29));
+ });
+
+ it('reaches the next Friday when started on a Saturday', () => {
+ const saturday = new Date(2026, 7, 29, 10, 0);
+ const window = resolveAvailabilityWindow('thisWeek', saturday);
+ // Sat Aug 29 → Fri Sep 4 inclusive.
+ expect(window.endExclusive.getTime()).toBe(localDay(2026, 8, 5));
+ });
+
+ it('runs through the same weekday for the day-based ranges', () => {
+ expect(
+ resolveAvailabilityWindow('next7Days', MONDAY_10AM).endExclusive.getTime()
+ ).toBe(localDay(2026, 8, 1)); // through Mon Aug 31
+ expect(
+ resolveAvailabilityWindow(
+ 'next14Days',
+ MONDAY_10AM
+ ).endExclusive.getTime()
+ ).toBe(localDay(2026, 8, 8)); // through Mon Sep 7
+ });
+});
+
+describe('busyIntervalsFromOccurrences', () => {
+ const start = new Date(2026, 7, 24, 11, 0);
+ const end = new Date(2026, 7, 24, 12, 0);
+
+ it('keeps confirmed timed events', () => {
+ expect(busyIntervalsFromOccurrences([timedItem({ start, end })])).toEqual([
+ { start: start.getTime(), end: end.getTime() },
+ ]);
+ });
+
+ it('ignores events that do not block time', () => {
+ const items = [
+ timedItem({ start, end, isCancelled: true }),
+ timedItem({ start, end, status: 'cancelled' }),
+ timedItem({ start, end, transparency: 'transparent' }),
+ timedItem({ start, end, selfResponseStatus: 'declined' }),
+ allDayItem(),
+ ];
+ expect(busyIntervalsFromOccurrences(items)).toEqual([]);
+ });
+
+ it('keeps events the viewer accepted or has not answered', () => {
+ const items = [
+ timedItem({ start, end, selfResponseStatus: 'accepted' }),
+ timedItem({ start, end, selfResponseStatus: 'needs_action' }),
+ ];
+ expect(busyIntervalsFromOccurrences(items)).toHaveLength(2);
+ });
+});
+
+describe('computeAvailability', () => {
+ it('returns the whole remaining workday when nothing is booked', () => {
+ const days = computeAvailability({
+ rangeKey: 'today',
+ settings: SETTINGS,
+ busyIntervals: [],
+ now: MONDAY_10AM,
+ });
+ expect(days).toHaveLength(1);
+ expect(days[0].slots).toEqual([
+ {
+ start: new Date(2026, 7, 24, 10, 0),
+ end: new Date(2026, 7, 24, 18, 0),
+ },
+ ]);
+ });
+
+ it('rounds a mid-quarter start up to the next quarter hour', () => {
+ const days = computeAvailability({
+ rangeKey: 'today',
+ settings: SETTINGS,
+ busyIntervals: [],
+ now: new Date(2026, 7, 24, 10, 7),
+ });
+ expect(days[0].slots[0].start).toEqual(new Date(2026, 7, 24, 10, 15));
+ });
+
+ it('splits the day around busy intervals and drops slivers', () => {
+ const busy = [
+ // 11:00–12:00 meeting.
+ {
+ start: new Date(2026, 7, 24, 11, 0).getTime(),
+ end: new Date(2026, 7, 24, 12, 0).getTime(),
+ },
+ // Overlapping 11:30–13:00 meeting merges into the block above.
+ {
+ start: new Date(2026, 7, 24, 11, 30).getTime(),
+ end: new Date(2026, 7, 24, 13, 0).getTime(),
+ },
+ // 13:10–18:00: leaves a 10-minute sliver after 13:00, dropped.
+ {
+ start: new Date(2026, 7, 24, 13, 10).getTime(),
+ end: new Date(2026, 7, 24, 18, 0).getTime(),
+ },
+ ];
+ const days = computeAvailability({
+ rangeKey: 'today',
+ settings: SETTINGS,
+ busyIntervals: busy,
+ now: MONDAY_10AM,
+ });
+ expect(days[0].slots).toEqual([
+ {
+ start: new Date(2026, 7, 24, 10, 0),
+ end: new Date(2026, 7, 24, 11, 0),
+ },
+ ]);
+ });
+
+ it('skips weekends when excluded and includes them otherwise', () => {
+ const excluded = computeAvailability({
+ rangeKey: 'next7Days',
+ settings: SETTINGS,
+ busyIntervals: [],
+ now: MONDAY_10AM,
+ });
+ // Mon–Mon inclusive minus Sat/Sun.
+ expect(excluded).toHaveLength(6);
+ expect(excluded.every((day) => ![0, 6].includes(day.date.getDay()))).toBe(
+ true
+ );
+
+ const included = computeAvailability({
+ rangeKey: 'next7Days',
+ settings: { ...SETTINGS, excludeWeekends: false },
+ busyIntervals: [],
+ now: MONDAY_10AM,
+ });
+ expect(included).toHaveLength(8);
+ });
+
+ it('omits a fully booked day', () => {
+ const busy = [
+ {
+ start: new Date(2026, 7, 24, 9, 0).getTime(),
+ end: new Date(2026, 7, 24, 18, 0).getTime(),
+ },
+ ];
+ expect(
+ computeAvailability({
+ rangeKey: 'today',
+ settings: SETTINGS,
+ busyIntervals: busy,
+ now: MONDAY_10AM,
+ })
+ ).toEqual([]);
+ });
+
+ it('returns nothing after the workday has ended', () => {
+ expect(
+ computeAvailability({
+ rangeKey: 'today',
+ settings: SETTINGS,
+ busyIntervals: [],
+ now: new Date(2026, 7, 24, 18, 30),
+ })
+ ).toEqual([]);
+ });
+
+ it('returns nothing for an inverted workday window', () => {
+ expect(
+ computeAvailability({
+ rangeKey: 'today',
+ settings: { ...SETTINGS, startTime: '18:00', endTime: '09:00' },
+ busyIntervals: [],
+ now: MONDAY_10AM,
+ })
+ ).toEqual([]);
+ });
+
+ it('uses defaults of 9:00–18:00 excluding weekends', () => {
+ expect(DEFAULT_AVAILABILITY_SETTINGS).toEqual({
+ startTime: '09:00',
+ endTime: '18:00',
+ excludeWeekends: true,
+ });
+ });
+});
+
+describe('sanitizeAvailabilitySettings', () => {
+ it('keeps valid persisted values', () => {
+ const stored = {
+ startTime: '07:30',
+ endTime: '16:00',
+ excludeWeekends: false,
+ };
+ expect(sanitizeAvailabilitySettings(stored)).toEqual(stored);
+ });
+
+ it('replaces malformed fields with defaults', () => {
+ expect(
+ sanitizeAvailabilitySettings({
+ startTime: 'banana',
+ endTime: 42,
+ excludeWeekends: 'yes',
+ })
+ ).toEqual(DEFAULT_AVAILABILITY_SETTINGS);
+ expect(sanitizeAvailabilitySettings(null)).toEqual(
+ DEFAULT_AVAILABILITY_SETTINGS
+ );
+ expect(sanitizeAvailabilitySettings('true')).toEqual(
+ DEFAULT_AVAILABILITY_SETTINGS
+ );
+ });
+
+ it('fills missing fields from older builds with defaults', () => {
+ expect(sanitizeAvailabilitySettings({ endTime: '17:00' })).toEqual({
+ ...DEFAULT_AVAILABILITY_SETTINGS,
+ endTime: '17:00',
+ });
+ });
+
+ it('resets an inverted workday but keeps the weekend preference', () => {
+ expect(
+ sanitizeAvailabilitySettings({
+ startTime: '18:00',
+ endTime: '09:00',
+ excludeWeekends: false,
+ })
+ ).toEqual({ ...DEFAULT_AVAILABILITY_SETTINGS, excludeWeekends: false });
+ });
+});
+
+describe('rangeTimeZoneLabel', () => {
+ // US DST ends Sun Nov 1 2026; these instants sit on either side of it.
+ const beforeTransition = new Date(Date.UTC(2026, 9, 30, 14, 0));
+ const afterTransition = new Date(Date.UTC(2026, 10, 3, 15, 0));
+ const ZONE = 'America/New_York';
+
+ it('keeps the specific abbreviation while the offset is constant', () => {
+ const single = rangeTimeZoneLabel([beforeTransition], ZONE);
+ expect(single).toBeTruthy();
+ expect(
+ rangeTimeZoneLabel(
+ [beforeTransition, new Date(Date.UTC(2026, 9, 31, 14, 0))],
+ ZONE
+ )
+ ).toBe(single);
+ });
+
+ it('uses a DST-agnostic label across a daylight-saving change', () => {
+ const before = rangeTimeZoneLabel([beforeTransition], ZONE);
+ const after = rangeTimeZoneLabel([afterTransition], ZONE);
+ expect(before).not.toBe(after); // sanity: the range crosses a transition
+
+ const label = rangeTimeZoneLabel([beforeTransition, afterTransition], ZONE);
+ expect(label).toBeTruthy();
+ expect(label).not.toBe(before);
+ expect(label).not.toBe(after);
+ });
+
+ it('returns nothing for an empty range', () => {
+ expect(rangeTimeZoneLabel([], ZONE)).toBeUndefined();
+ });
+});
+
+describe('formatAvailabilityText', () => {
+ it('renders a header line plus one line per day', () => {
+ const days = computeAvailability({
+ rangeKey: 'thisWeek',
+ settings: SETTINGS,
+ busyIntervals: [
+ {
+ start: new Date(2026, 7, 25, 9, 0).getTime(),
+ end: new Date(2026, 7, 25, 12, 0).getTime(),
+ },
+ ],
+ now: MONDAY_10AM,
+ });
+ const text = formatAvailabilityText(days, '12-hour', MONDAY_10AM);
+ const lines = text.split('\n');
+
+ expect(lines[0]).toMatch(/^My availability/);
+ expect(lines).toHaveLength(1 + 5); // Mon–Fri
+ // Every day line pairs a date label with at least one time range.
+ for (const line of lines.slice(1)) {
+ expect(line).toMatch(/: .+ – .+$/);
+ }
+ });
+});
diff --git a/apps/web/src/features/calendar/availability/availability.ts b/apps/web/src/features/calendar/availability/availability.ts
new file mode 100644
index 0000000000..5fd4e0547c
--- /dev/null
+++ b/apps/web/src/features/calendar/availability/availability.ts
@@ -0,0 +1,293 @@
+/**
+ * Copy-availability domain logic: derives the viewer's free time slots from
+ * calendar occurrences and formats them as shareable plain text. Everything
+ * is computed in the viewer's local timezone.
+ */
+
+import type { CalendarOccurrenceItem } from '@service-storage/generated/schemas/calendarOccurrenceItem';
+import type { CalendarTimeFormat } from '../types';
+import { formatCalendarTime } from '../utils/time-format';
+import { rangeTimeZoneLabel } from './zone-label';
+
+/** Supported share ranges, in menu order. */
+export type AvailabilityRangeKey =
+ | 'today'
+ | 'thisWeek'
+ | 'next7Days'
+ | 'next14Days';
+
+export const AVAILABILITY_RANGE_OPTIONS: Array<{
+ key: AvailabilityRangeKey;
+ label: string;
+}> = [
+ { key: 'today', label: 'Today' },
+ { key: 'thisWeek', label: 'This week' },
+ { key: 'next7Days', label: 'Next 7 days' },
+ { key: 'next14Days', label: 'Next 14 days' },
+];
+
+/** Personal copy-availability preferences. Times are local 'HH:MM'. */
+export interface AvailabilitySettings {
+ /** Workday start; slots never begin before this. */
+ startTime: string;
+ /** Workday end; slots never extend past this. */
+ endTime: string;
+ /** Whether Saturday and Sunday are omitted entirely. */
+ excludeWeekends: boolean;
+}
+
+export const DEFAULT_AVAILABILITY_SETTINGS: AvailabilitySettings = {
+ startTime: '09:00',
+ endTime: '18:00',
+ excludeWeekends: true,
+};
+
+const TIME_PATTERN = /^([01]\d|2[0-3]):[0-5]\d$/;
+
+/**
+ * Coerces a persisted (and therefore untrusted) settings value into a valid
+ * shape: malformed fields fall back to their defaults, and an inverted or
+ * empty workday falls back entirely (keeping a valid weekend preference).
+ */
+export function sanitizeAvailabilitySettings(
+ value: unknown
+): AvailabilitySettings {
+ const stored = (
+ typeof value === 'object' && value !== null ? value : {}
+ ) as Partial<Record<keyof AvailabilitySettings, unknown>>;
+ const startTime =
+ typeof stored.startTime === 'string' && TIME_PATTERN.test(stored.startTime)
+ ? stored.startTime
+ : DEFAULT_AVAILABILITY_SETTINGS.startTime;
+ const endTime =
+ typeof stored.endTime === 'string' && TIME_PATTERN.test(stored.endTime)
+ ? stored.endTime
+ : DEFAULT_AVAILABILITY_SETTINGS.endTime;
+ const excludeWeekends =
+ typeof stored.excludeWeekends === 'boolean'
+ ? stored.excludeWeekends
+ : DEFAULT_AVAILABILITY_SETTINGS.excludeWeekends;
+
+ // 'HH:MM' strings order lexicographically, so <= is a time comparison.
+ if (endTime <= startTime) {
+ return { ...DEFAULT_AVAILABILITY_SETTINGS, excludeWeekends };
+ }
+ return { startTime, endTime, excludeWeekends };
+}
+
+/** One contiguous free interval within a single day. */
+interface AvailabilitySlot {
+ start: Date;
+ end: Date;
+}
+
+/** A day's free slots; days with no free time are omitted from results. */
+export interface AvailabilityDay {
+ date: Date;
+ slots: AvailabilitySlot[];
+}
+
+interface BusyInterval {
+ start: number;
+ end: number;
+}
+
+/** Free slots shorter than this read as noise, not availability. */
+const MIN_SLOT_MS = 15 * 60_000;
+/** "From now" starts get rounded up to this grain so times look natural. */
+const NOW_ROUNDING_MS = 15 * 60_000;
+
+function parseTimeToMinutes(time: string): number {
+ const [hours = 0, minutes = 0] = time.split(':').map(Number);
+ return hours * 60 + minutes;
+}
+
+function startOfLocalDay(date: Date): Date {
+ const day = new Date(date);
+ day.setHours(0, 0, 0, 0);
+ return day;
+}
+
+function addDays(date: Date, days: number): Date {
+ const next = new Date(date);
+ next.setDate(next.getDate() + days);
+ return next;
+}
+
+function isWeekend(date: Date): boolean {
+ const day = date.getDay();
+ return day === 0 || day === 6;
+}
+
+/** Local wall-clock instant `minutes` past midnight on `day` (DST-safe). */
+function atMinutes(day: Date, minutes: number): number {
+ return new Date(
+ day.getFullYear(),
+ day.getMonth(),
+ day.getDate(),
+ 0,
+ minutes
+ ).getTime();
+}
+
+/**
+ * The local-day span a range covers: `start` is the start of today and
+ * `endExclusive` is the start of the day after the last included day.
+ * "This week" runs through the coming Friday (today, when today is Friday);
+ * the day-based ranges run through the same weekday 1–2 weeks out.
+ */
+export function resolveAvailabilityWindow(
+ rangeKey: AvailabilityRangeKey,
+ now: Date
+): { start: Date; endExclusive: Date } {
+ const start = startOfLocalDay(now);
+ const lastDayOffset = (() => {
+ switch (rangeKey) {
+ case 'today':
+ return 0;
+ case 'thisWeek':
+ return (5 - now.getDay() + 7) % 7;
+ case 'next7Days':
+ return 7;
+ case 'next14Days':
+ return 14;
+ }
+ })();
+
+ return { start, endExclusive: addDays(start, lastDayOffset + 1) };
+}
+
+/**
+ * Occurrences that actually block time: timed (all-day events are treated
+ * as informational), not cancelled, not marked free (`transparent`), and
+ * not declined by the viewer.
+ */
+export function busyIntervalsFromOccurrences(
+ items: CalendarOccurrenceItem[]
+): BusyInterval[] {
+ const intervals: BusyInterval[] = [];
+ for (const { event, occurrence } of items) {
+ if (occurrence.time.kind !== 'timed') continue;
+ if (occurrence.isCancelled || event.status === 'cancelled') continue;
+ if (event.transparency === 'transparent') continue;
+ const self = event.attendees?.find((attendee) => attendee.isSelf);
+ if (self?.responseStatus === 'declined') continue;
+
+ const start = Date.parse(occurrence.time.startsAt);
+ const end = Date.parse(occurrence.time.endsAt);
+ if (Number.isNaN(start) || Number.isNaN(end) || end <= start) continue;
+ intervals.push({ start, end });
+ }
+ return intervals;
+}
+
+function subtractBusy(
+ windowStart: number,
+ windowEnd: number,
+ busy: BusyInterval[]
+): AvailabilitySlot[] {
+ const overlapping = busy
+ .filter(
+ (interval) => interval.end > windowStart && interval.start < windowEnd
+ )
+ .sort((a, b) => a.start - b.start);
+
+ const slots: AvailabilitySlot[] = [];
+ let cursor = windowStart;
+ for (const interval of overlapping) {
+ if (interval.start - cursor >= MIN_SLOT_MS) {
+ slots.push({ start: new Date(cursor), end: new Date(interval.start) });
+ }
+ cursor = Math.max(cursor, interval.end);
+ if (cursor >= windowEnd) return slots;
+ }
+ if (windowEnd - cursor >= MIN_SLOT_MS) {
+ slots.push({ start: new Date(cursor), end: new Date(windowEnd) });
+ }
+ return slots;
+}
+
+/**
+ * Free slots per day for a range: each day's workday window minus busy
+ * intervals, weekends optionally excluded, and today's window starting no
+ * earlier than `now` (rounded up to the next quarter hour). Days without
+ * any free slot are omitted.
+ */
+export function computeAvailability(options: {
+ rangeKey: AvailabilityRangeKey;
+ settings: AvailabilitySettings;
+ busyIntervals: BusyInterval[];
+ now: Date;
+}): AvailabilityDay[] {
+ const { rangeKey, settings, busyIntervals, now } = options;
+ const window = resolveAvailabilityWindow(rangeKey, now);
+ const dayStartMinutes = parseTimeToMinutes(settings.startTime);
+ const dayEndMinutes = parseTimeToMinutes(settings.endTime);
+ if (dayEndMinutes <= dayStartMinutes) return [];
+
+ const days: AvailabilityDay[] = [];
+ for (
+ let day = window.start;
+ day < window.endExclusive;
+ day = addDays(day, 1)
+ ) {
+ if (settings.excludeWeekends && isWeekend(day)) continue;
+
+ let windowStart = atMinutes(day, dayStartMinutes);
+ const windowEnd = atMinutes(day, dayEndMinutes);
+ if (windowStart < now.getTime()) {
+ windowStart =
+ Math.ceil(now.getTime() / NOW_ROUNDING_MS) * NOW_ROUNDING_MS;
+ }
+ if (windowEnd - windowStart < MIN_SLOT_MS) continue;
+
+ const slots = subtractBusy(windowStart, windowEnd, busyIntervals);
+ if (slots.length > 0) days.push({ date: day, slots });
+ }
+ return days;
+}
+
+const dayLabelFormatter = new Intl.DateTimeFormat(undefined, {
+ weekday: 'short',
+ month: 'short',
+ day: 'numeric',
+});
+
+/**
+ * Formats availability as plain text ready for an email:
+ *
+ * ```
+ * My availability (EDT):
+ * Mon, Aug 24: 2:15 PM – 6:00 PM
+ * Tue, Aug 25: 9:00 AM – 11:00 AM, 1:30 PM – 6:00 PM
+ * ```
+ *
+ * The header label covers every listed slot: a range that spans a
+ * daylight-saving transition gets a DST-agnostic label instead of the
+ * abbreviation that only holds at copy time.
+ */
+export function formatAvailabilityText(
+ days: AvailabilityDay[],
+ timeFormat: CalendarTimeFormat,
+ now: Date
+): string {
+ const boundaries = days.flatMap((day) =>
+ day.slots.flatMap((slot) => [slot.start, slot.end])
+ );
+ const timeZone = rangeTimeZoneLabel(
+ boundaries.length > 0 ? boundaries : [now]
+ );
+ const header = timeZone
+ ? `My availability (${timeZone}):`
+ : 'My availability:';
+ const lines = days.map((day) => {
+ const slots = day.slots
+ .map(
+ (slot) =>
+ `${formatCalendarTime(slot.start, timeFormat)} – ${formatCalendarTime(slot.end, timeFormat)}`
+ )
+ .join(', ');
+ return `${dayLabelFormatter.format(day.date)}: ${slots}`;
+ });
+ return [header, ...lines].join('\n');
+}
diff --git a/apps/web/src/features/calendar/availability/settings.ts b/apps/web/src/features/calendar/availability/settings.ts
new file mode 100644
index 0000000000..63fbab136b
--- /dev/null
+++ b/apps/web/src/features/calendar/availability/settings.ts
@@ -0,0 +1,102 @@
+/**
+ * Persisted copy-availability preferences. One module-level shared signal so
+ * the calendar header and the email composer see the same values and react
+ * to each other's changes immediately (`usePreference` would give each
+ * surface its own signal that only shares the localStorage key).
+ */
+
+import { makePersisted } from '@solid-primitives/storage';
+import { createSignal } from 'solid-js';
+import { CALENDAR_PREFERENCES_KEY } from '../components/CalendarViewContext';
+import type { CalendarTimeFormat } from '../types';
+import { getDefaultCalendarTimeFormat } from '../utils/time-format';
+import {
+ type AvailabilitySettings,
+ DEFAULT_AVAILABILITY_SETTINGS,
+ sanitizeAvailabilitySettings,
+} from './availability';
+
+const [storedSettings, setStoredSettings] = makePersisted(
+ createSignal<AvailabilitySettings>(DEFAULT_AVAILABILITY_SETTINGS),
+ {
+ name: 'macro:pref:calendar:availability',
+ // Persisted storage is user-editable and may predate fields added later:
+ // malformed JSON or invalid values must never throw or reach the time
+ // formatters, so everything read back is sanitized to a valid shape.
+ deserialize: (raw) => {
+ try {
+ return sanitizeAvailabilitySettings(JSON.parse(raw));
+ } catch {
+ return DEFAULT_AVAILABILITY_SETTINGS;
+ }
+ },
+ }
+);
+
+/** Keeps the workday at least an hour long when one edge crosses the other. */
+function shiftTime(time: string, deltaMinutes: number): string {
+ const [hours = 0, minutes = 0] = time.split(':').map(Number);
+ const total = Math.min(
+ Math.max(hours * 60 + minutes + deltaMinutes, 0),
+ 23 * 60 + 30
+ );
+ return `${String(Math.floor(total / 60)).padStart(2, '0')}:${String(total % 60).padStart(2, '0')}`;
+}
+
+/** Shared accessor + setters for the copy-availability settings menu. */
+export function useAvailabilitySettings() {
+ const settings = (): AvailabilitySettings =>
+ sanitizeAvailabilitySettings(storedSettings());
+
+ const setStartTime = (startTime: string) => {
+ const current = settings();
+ setStoredSettings({
+ ...current,
+ startTime,
+ // 'HH:MM' strings order lexicographically, so >= is a time comparison.
+ endTime:
+ startTime >= current.endTime
+ ? shiftTime(startTime, 60)
+ : current.endTime,
+ });
+ };
+
+ const setEndTime = (endTime: string) => {
+ const current = settings();
+ setStoredSettings({
+ ...current,
+ endTime,
+ startTime:
+ endTime <= current.startTime
+ ? shiftTime(endTime, -60)
+ : current.startTime,
+ });
+ };
+
+ const setExcludeWeekends = (excludeWeekends: boolean) =>
+ setStoredSettings({ ...settings(), excludeWeekends });
+
+ return { settings, setStartTime, setEndTime, setExcludeWeekends };
+}
+
+/**
+ * The calendar's persisted 12/24-hour preference, readable outside the
+ * calendar block (the email composer has no CalendarViewContext). Read at
+ * copy time, so a preference change applies to the next copy.
+ */
+export function getPersistedCalendarTimeFormat(): CalendarTimeFormat {
+ try {
+ const raw = localStorage.getItem(CALENDAR_PREFERENCES_KEY);
+ if (raw) {
+ const timeFormat = (
+ JSON.parse(raw) as { timeFormat?: CalendarTimeFormat }
+ ).timeFormat;
+ if (timeFormat === '12-hour' || timeFormat === '24-hour') {
+ return timeFormat;
+ }
+ }
+ } catch {
+ // Unreadable storage falls through to the locale default.
+ }
+ return getDefaultCalendarTimeFormat();
+}
diff --git a/apps/web/src/features/calendar/availability/use-availability-text.ts b/apps/web/src/features/calendar/availability/use-availability-text.ts
new file mode 100644
index 0000000000..31ccb9d913
--- /dev/null
+++ b/apps/web/src/features/calendar/availability/use-availability-text.ts
@@ -0,0 +1,60 @@
+/**
+ * Bridges the availability domain logic to calendar occurrence data. Shares
+ * the calendar's occurrence query cache, so repeat copies are instant and a
+ * freshly viewed range never refetches.
+ */
+
+import { useUserId } from '@core/context/user';
+import { calendarKeys } from '@queries/calendar/keys';
+import {
+ createCalendarOccurrenceQueryRange,
+ fetchCalendarOccurrences,
+} from '@queries/calendar/occurrences';
+import { queryClient } from '@queries/client';
+import {
+ type AvailabilityRangeKey,
+ busyIntervalsFromOccurrences,
+ computeAvailability,
+ formatAvailabilityText,
+ resolveAvailabilityWindow,
+} from './availability';
+import {
+ getPersistedCalendarTimeFormat,
+ useAvailabilitySettings,
+} from './settings';
+
+const AVAILABILITY_STALE_TIME = 60_000;
+
+/**
+ * Returns an async provider mapping a share range to formatted availability
+ * text, or `undefined` when the range holds no free time.
+ */
+export function useAvailabilityText() {
+ const userId = useUserId();
+ const { settings } = useAvailabilitySettings();
+
+ return async (
+ rangeKey: AvailabilityRangeKey
+ ): Promise<string | undefined> => {
+ const now = new Date();
+ const window = resolveAvailabilityWindow(rangeKey, now);
+ const range = createCalendarOccurrenceQueryRange(
+ window.start,
+ window.endExclusive
+ );
+ const data = await queryClient.fetchQuery({
+ queryKey: calendarKeys.occurrences(userId() ?? '', range).queryKey,
+ queryFn: ({ signal }) => fetchCalendarOccurrences(range, signal),
+ staleTime: AVAILABILITY_STALE_TIME,
+ });
+
+ const days = computeAvailability({
+ rangeKey,
+ settings: settings(),
+ busyIntervals: busyIntervalsFromOccurrences(data.items),
+ now,
+ });
+ if (days.length === 0) return undefined;
+ return formatAvailabilityText(days, getPersistedCalendarTimeFormat(), now);
+ };
+}
diff --git a/apps/web/src/features/calendar/availability/zone-label.ts b/apps/web/src/features/calendar/availability/zone-label.ts
new file mode 100644
index 0000000000..424a7c8824
--- /dev/null
+++ b/apps/web/src/features/calendar/availability/zone-label.ts
@@ -0,0 +1,50 @@
+/**
+ * Timezone labeling for shared availability text. Lives apart from the
+ * slot math so the label logic can be exercised against explicit zones.
+ */
+
+function timeZonePart(
+ formatter: Intl.DateTimeFormat,
+ instant: Date
+): string | undefined {
+ return formatter
+ .formatToParts(instant)
+ .find((part) => part.type === 'timeZoneName')?.value;
+}
+
+/**
+ * A timezone label valid for every given instant: the specific abbreviation
+ * (e.g. "EDT") when it is constant across them, otherwise a DST-agnostic
+ * label — the generic short name ("ET") where supported, the IANA
+ * identifier as a last resort — so a range spanning a daylight-saving
+ * transition never claims a single offset for all of its times.
+ * `timeZone` overrides the environment zone (used by tests).
+ */
+export function rangeTimeZoneLabel(
+ instants: Date[],
+ timeZone?: string
+): string | undefined {
+ if (instants.length === 0) return undefined;
+ const specific = new Intl.DateTimeFormat(undefined, {
+ timeZoneName: 'short',
+ timeZone,
+ });
+ const labels = new Set(
+ instants.map((instant) => timeZonePart(specific, instant))
+ );
+ const [firstLabel] = labels;
+ if (labels.size === 1) return firstLabel;
+
+ try {
+ const generic = new Intl.DateTimeFormat(undefined, {
+ timeZoneName: 'shortGeneric',
+ timeZone,
+ });
+ return (
+ timeZonePart(generic, instants[0]) ?? specific.resolvedOptions().timeZone
+ );
+ } catch {
+ // Environments without 'shortGeneric' support still get a stable label.
+ return specific.resolvedOptions().timeZone;
+ }
+}
diff --git a/apps/web/src/features/calendar/components/CalendarViewContext.tsx b/apps/web/src/features/calendar/components/CalendarViewContext.tsx
index 85e7278943..c540feb234 100644
--- a/apps/web/src/features/calendar/components/CalendarViewContext.tsx
+++ b/apps/web/src/features/calendar/components/CalendarViewContext.tsx
@@ -27,7 +27,9 @@ interface CalendarPreferences {
timeFormat: CalendarTimeFormat;
}
-const CALENDAR_PREFERENCES_KEY = 'macro:pref:calendar:settings';
+/** Storage key for calendar display preferences (also read at copy time by
+ * the availability feature, which runs outside this context). */
+export const CALENDAR_PREFERENCES_KEY = 'macro:pref:calendar:settings';
function createCalendarEventSelection() {
const [event, setEvent] = createSignal<CalendarEvent>();