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.

fix(calendar): polish in-calendar search (#6057)

gbirman9cd7f79a1a09
diff --git a/apps/web/src/features/block-calendar/components/CalendarSearch.tsx b/apps/web/src/features/block-calendar/components/CalendarSearch.tsx
index 703d8ed11b..45fddaa739 100644
--- a/apps/web/src/features/block-calendar/components/CalendarSearch.tsx
+++ b/apps/web/src/features/block-calendar/components/CalendarSearch.tsx
@@ -2,17 +2,36 @@ import { useCalendarView } from '@app/features/calendar/components/CalendarViewC
import { useCalendarSearchUiFlag } from '@app/features/calendar/hooks/use-calendar-ui-flag';
import type { CalendarTimeFormat } from '@app/features/calendar/types';
import { parseLocalDate } from '@app/features/calendar/utils/calendar-date';
+import { isCalendarRangeSupported } from '@app/features/calendar/utils/calendar-supported-range';
import { formatCalendarTime } from '@app/features/calendar/utils/time-format';
+import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
import { EntityIcon } from '@core/component/EntityIcon';
+import { IS_MAC } from '@core/constant/isMac';
+import { registerHotkey } from '@core/hotkey/hotkeys';
+import { TOKENS } from '@core/hotkey/tokens';
import { debouncedDependent } from '@core/util/debounce';
import type { EntityData, WithSearch } from '@entity';
import SearchIcon from '@icon/macro-magnifying-glass.svg';
import { Popover } from '@kobalte/core/popover';
+import CaretLeftIcon from '@phosphor/caret-left.svg';
+import RepeatIcon from '@phosphor/repeat.svg';
+import { useCalendarMentionPreviewQuery } from '@queries/calendar/mention-preview';
import { useSearchSoupQuery } from '@queries/soup/search';
import type { EntityFilters } from '@service-search/generated/models';
-import { Button, Layer } from '@ui';
-import { createMemo, createSignal, For, Show } from 'solid-js';
-import { openCalendarEventSplit } from '../open-calendar-event';
+import { Button, cn, Layer } from '@ui';
+import {
+ createMemo,
+ createSignal,
+ For,
+ onCleanup,
+ onMount,
+ Show,
+} from 'solid-js';
+import { createCalendarBlockRange } from '../calendar-range';
+import {
+ eventTimeFromOccurrenceKey,
+ openCalendarEventSplit,
+} from '../open-calendar-event';
type CalendarSearchResult = WithSearch<
Extract<EntityData, { type: 'calendar_event' }>
@@ -73,17 +92,122 @@ function formatEventWhen(
return `${formatDateLabel(start)} · ${formatCalendarTime(start, timeFormat)}`;
}
+/**
+ * Read-only card for a result the calendar cannot navigate to: occurrences
+ * older than the backend's rolling materialized window aren't fetchable, so
+ * there is nothing to focus and no editable event to open. The card's identity
+ * — title, when, organizer, recurrence — comes from the selected row so it
+ * always describes the instance the user picked; the mention preview only
+ * supplements the meeting-level location and guest count the row lacks.
+ */
+function CalendarEventPreviewContent(props: {
+ event: CalendarSearchResult;
+ timeFormat: CalendarTimeFormat;
+ onBack: () => void;
+}) {
+ let backRef: HTMLButtonElement | undefined;
+ // Pull focus into the card as it replaces the search body. A non-modal
+ // Kobalte popover dismisses on focus-outside, and the vacated input would
+ // otherwise drop focus to <body> and close the popover before it shows.
+ onMount(() => backRef?.focus());
+
+ // Supplemental meeting-level detail only. The preview's own `time` is
+ // deliberately unused: for an out-of-range hit the requested occurrence
+ // isn't materialized, so the endpoint resolves a DIFFERENT instance — the
+ // row already carries the occurrence the user selected.
+ const previewQuery = useCalendarMentionPreviewQuery(() => ({
+ eventId: props.event.id,
+ occurrenceKey: props.event.occurrenceKey,
+ }));
+
+ const when = () => formatEventWhen(props.event.time, props.timeFormat);
+ const organizer = () =>
+ props.event.organizer?.name || props.event.organizer?.email || '';
+ const detail = () => {
+ const preview = previewQuery.data;
+ if (!preview) return '';
+ const guests =
+ preview.attendeeCount > 0
+ ? `${preview.attendeeCount} guest${preview.attendeeCount === 1 ? '' : 's'}`
+ : '';
+ return [preview.location, guests].filter(Boolean).join(' · ');
+ };
+
+ return (
+ <div class="p-1">
+ <button
+ ref={backRef}
+ type="button"
+ onClick={props.onBack}
+ class="flex items-center gap-0.5 rounded-md px-2 py-1 text-xs text-ink-muted outline-none hover:text-ink"
+ >
+ <CaretLeftIcon class="size-3" />
+ Back to search
+ </button>
+ <div class="flex flex-col gap-1 px-2 pb-2">
+ <div class="flex items-center gap-2">
+ <span class="flex size-4 shrink-0 items-center justify-center">
+ <EntityIcon targetType="calendar" size="xs" theme="monochrome" />
+ </span>
+ <span class="min-w-0 flex-1 truncate text-sm font-medium text-ink">
+ {props.event.name || 'Untitled event'}
+ </span>
+ <Show when={props.event.isRecurring}>
+ <RepeatIcon
+ class="size-3 shrink-0 text-ink-muted"
+ aria-label="Repeats"
+ />
+ </Show>
+ </div>
+ <Show when={when()}>
+ {(label) => (
+ <span class="truncate text-xs text-ink-muted">{label()}</span>
+ )}
+ </Show>
+ <Show when={organizer()}>
+ {(name) => (
+ <span class="truncate text-xs text-ink-muted">{name()}</span>
+ )}
+ </Show>
+ <Show when={detail()}>
+ {(text) => (
+ <span class="truncate text-xs text-ink-muted">{text()}</span>
+ )}
+ </Show>
+ <span class="mt-1 border-t border-edge-muted pt-1.5 text-[11px] text-ink-extra-muted">
+ Outside the calendar's navigable range
+ </span>
+ </div>
+ </div>
+ );
+}
+
/**
* Keyword search over the caller's calendar events, opened from the calendar
* header. Selecting a result re-aims the singleton calendar block at that
* occurrence, the same navigation an event mention or soup row performs.
*/
export function CalendarSearch() {
- const calendarView = useCalendarView();
const searchEnabled = useCalendarSearchUiFlag();
+ return (
+ <Show when={searchEnabled()}>
+ <CalendarSearchControl />
+ </Show>
+ );
+}
+
+function CalendarSearchControl() {
+ const calendarView = useCalendarView();
+ const panel = useSplitPanelOrThrow();
const [open, setOpen] = createSignal(false);
const [rawQuery, setRawQuery] = createSignal('');
let inputRef: HTMLInputElement | undefined;
+ let listRef: HTMLDivElement | undefined;
+ const [activeRow, setActiveRow] = createSignal(0);
+ // Set to the chosen result when it falls outside the navigable range: the
+ // popover then floats a read-only preview of it in place of the search body.
+ const [previewTarget, setPreviewTarget] =
+ createSignal<CalendarSearchResult | null>(null);
const query = createMemo(() => rawQuery().trim());
const debouncedQuery = debouncedDependent(query, 250);
@@ -121,136 +245,237 @@ export function CalendarSearch() {
const isLoading = () => query().length >= MIN_QUERY_LENGTH && !isCurrent();
+ // Keyboard-highlighted result, clamped so it stays valid as results change.
+ const activeIndex = () => {
+ const len = results().length;
+ return len === 0 ? -1 : Math.min(Math.max(activeRow(), 0), len - 1);
+ };
+ const moveActive = (delta: number) => {
+ const len = results().length;
+ if (len === 0) return;
+ const next = Math.min(Math.max(activeIndex() + delta, 0), len - 1);
+ setActiveRow(next);
+ listRef
+ ?.querySelector(`[data-result-index="${next}"]`)
+ ?.scrollIntoView({ block: 'nearest' });
+ };
+
const openResult = (event: CalendarSearchResult) => {
- setOpen(false);
- setRawQuery('');
- // An occurrence key anchors the locator range on its own; without one the
- // master span stands in (a series with no occurrence in the window).
- void openCalendarEventSplit({
- eventId: event.id,
- occurrenceKey: event.occurrenceKey,
- time: event.occurrenceKey ? undefined : event.time,
- });
+ // Resolve the same locator range a go-to would build: the occurrence key
+ // anchors it on its own; without one the master's own time stands in.
+ const time = event.occurrenceKey
+ ? eventTimeFromOccurrenceKey(event.occurrenceKey)
+ : event.time;
+ const range = time ? createCalendarBlockRange(time) : undefined;
+
+ if (range && isCalendarRangeSupported(range)) {
+ setOpen(false);
+ setRawQuery('');
+ void openCalendarEventSplit({
+ eventId: event.id,
+ occurrenceKey: event.occurrenceKey,
+ time: event.occurrenceKey ? undefined : event.time,
+ });
+ return;
+ }
+
+ // Older than the backend's rolling window: the calendar can't navigate to
+ // this occurrence, so float a read-only preview instead of a dead click.
+ setPreviewTarget(event);
+ };
+
+ const closePreview = () => {
+ // The <Show> swaps the input back in synchronously, so the ref is live by
+ // the next line — no rAF needed to refocus.
+ setPreviewTarget(null);
+ focusInput();
+ };
+
+ const focusInput = () => {
+ inputRef?.focus();
+ inputRef?.select();
+ };
+
+ // Cmd+F opens the search, matching the channel block's find-bar. Registered
+ // only while this control is mounted, which the calendar-search flag gates.
+ // Once the popover is open its portal holds focus outside the split scope, so
+ // this split-scoped handler only fires to open it — the re-select-while-open
+ // case is handled by `handleContentKeyDown` on the portal content instead.
+ const searchHotkey = registerHotkey({
+ hotkey: 'cmd+f',
+ scopeId: panel.splitHotkeyScope,
+ hotkeyToken: TOKENS.calendar.search,
+ description: 'Search events',
+ runWithInputFocused: true,
+ keyDownHandler: () => {
+ if (open()) focusInput();
+ else setOpen(true);
+ return true;
+ },
+ });
+ onCleanup(searchHotkey.dispose);
+
+ // The portal content lives outside the split hotkey scope, so a second Cmd+F
+ // never reaches the split-scoped opener above — handle it here so it
+ // re-selects the query instead of falling through to the browser find dialog.
+ // Match the app's `cmd+f` semantics: the platform modifier (Cmd on Mac, not
+ // Ctrl) and a case-insensitive key so Caps Lock still hits.
+ const handleContentKeyDown = (event: KeyboardEvent) => {
+ const cmdPressed = IS_MAC ? event.metaKey : event.ctrlKey;
+ if (cmdPressed && event.key.toLowerCase() === 'f') {
+ event.preventDefault();
+ // The input is unmounted while the preview shows, so go back to it first.
+ if (previewTarget()) closePreview();
+ else focusInput();
+ }
};
return (
- <Show when={searchEnabled()}>
- <Popover
- open={open()}
- onOpenChange={(next) => {
- setOpen(next);
- if (!next) setRawQuery('');
- }}
- placement="bottom-end"
- gutter={6}
- flip
+ <Popover
+ open={open()}
+ onOpenChange={(next) => {
+ setOpen(next);
+ if (!next) {
+ setRawQuery('');
+ setActiveRow(0);
+ setPreviewTarget(null);
+ }
+ }}
+ placement="bottom-end"
+ gutter={6}
+ flip
+ >
+ <Popover.Trigger
+ as={Button}
+ variant="ghost"
+ size="icon-sm"
+ class="rounded-lg"
+ aria-label="Search events"
>
- <Popover.Trigger
- as={Button}
- variant="ghost"
- size="icon-sm"
- class="rounded-lg"
- aria-label="Search events"
- >
- <SearchIcon class="size-4" />
- </Popover.Trigger>
+ <SearchIcon class="size-4" />
+ </Popover.Trigger>
- <Popover.Portal>
- <Layer depth={3}>
- <Popover.Content
- class="portal-scope z-modal outline-none"
- onOpenAutoFocus={(event) => {
- event.preventDefault();
- inputRef?.focus();
- }}
- >
- <div class="w-80 max-w-[calc(100vw-2rem)] overflow-hidden rounded-xl bg-surface text-ink shadow-menu ring ring-edge-muted">
- <div class="flex items-center gap-2 border-b border-edge-muted px-3 py-2">
- <SearchIcon class="size-4 shrink-0 text-ink-muted" />
- <input
- ref={inputRef}
- type="text"
- value={rawQuery()}
- onInput={(event) => setRawQuery(event.currentTarget.value)}
- onKeyDown={(event) => {
- if (event.key === 'Enter') {
- const first = results()[0];
- if (first) openResult(first);
- }
- }}
- placeholder="Search events"
- class="min-w-0 flex-1 rounded-sm bg-transparent text-sm caret-accent outline-none placeholder:text-ink-placeholder focus-visible:ring-1 focus-visible:ring-accent"
- />
- </div>
+ <Popover.Portal>
+ <Layer depth={3}>
+ <Popover.Content
+ class="portal-scope z-modal outline-none"
+ onOpenAutoFocus={(event) => {
+ event.preventDefault();
+ inputRef?.focus();
+ }}
+ onKeyDown={handleContentKeyDown}
+ >
+ <div class="w-80 max-w-[calc(100vw-2rem)] overflow-hidden rounded-xl bg-surface text-ink shadow-menu ring ring-edge-muted">
+ <Show
+ when={previewTarget()}
+ fallback={
+ <>
+ <div class="flex items-center gap-2 px-3 py-2">
+ <SearchIcon class="size-4 shrink-0 text-ink-muted" />
+ <input
+ ref={inputRef}
+ type="text"
+ value={rawQuery()}
+ onInput={(event) => {
+ setRawQuery(event.currentTarget.value);
+ setActiveRow(0);
+ }}
+ onKeyDown={(event) => {
+ if (event.key === 'ArrowDown') {
+ event.preventDefault();
+ moveActive(1);
+ } else if (event.key === 'ArrowUp') {
+ event.preventDefault();
+ moveActive(-1);
+ } else if (event.key === 'Enter') {
+ const active = results()[activeIndex()];
+ if (active) openResult(active);
+ }
+ }}
+ placeholder="Search by event name"
+ class="min-w-0 flex-1 bg-transparent text-sm caret-accent outline-none placeholder:text-ink-placeholder"
+ />
+ </div>
- <div class="max-h-80 overflow-y-auto p-1">
- <Show
- when={query().length >= MIN_QUERY_LENGTH}
- fallback={
- <div class="px-2 py-3 text-center text-xs text-ink-muted">
- Type at least {MIN_QUERY_LENGTH} characters to search
- </div>
- }
- >
- <Show
- when={!isLoading()}
- fallback={
- <div class="px-2 py-3 text-center text-xs text-ink-muted">
- Searching…
- </div>
- }
- >
- <Show
- when={results().length > 0}
- fallback={
- <div class="px-2 py-3 text-center text-xs text-ink-muted">
- No events found
- </div>
- }
+ <Show when={query().length >= MIN_QUERY_LENGTH}>
+ <div
+ ref={listRef}
+ class="max-h-80 overflow-y-auto border-t border-edge-muted p-1"
>
- <For each={results()}>
- {(event) => (
- <button
- type="button"
- class="flex w-full items-center gap-2 rounded-lg p-1.5 px-2 text-left outline-none hover:bg-ink/5 focus-visible:bg-ink/5 focus-visible:ring-1 focus-visible:ring-accent"
- onClick={() => openResult(event)}
- >
- <span class="flex size-4 shrink-0 items-center justify-center">
- <EntityIcon
- targetType="calendar"
- size="xs"
- theme="monochrome"
- />
- </span>
- <span class="min-w-0 flex-1">
- <span class="block truncate text-sm text-ink">
- {event.name || 'Untitled event'}
- </span>
- <Show
- when={formatEventWhen(
- event.time,
- calendarView.displaySettings.timeFormat
+ <Show
+ when={!isLoading()}
+ fallback={
+ <div class="px-2 py-3 text-center text-xs text-ink-muted">
+ Searching…
+ </div>
+ }
+ >
+ <Show
+ when={results().length > 0}
+ fallback={
+ <div class="px-2 py-3 text-center text-xs text-ink-muted">
+ No events found
+ </div>
+ }
+ >
+ <For each={results()}>
+ {(event, index) => (
+ <button
+ type="button"
+ data-result-index={index()}
+ class={cn(
+ 'flex w-full items-center gap-2 rounded-lg p-1.5 px-2 text-left outline-none',
+ index() === activeIndex() && 'bg-ink/5'
)}
+ onMouseMove={() => setActiveRow(index())}
+ onClick={() => openResult(event)}
>
- {(label) => (
- <span class="block truncate text-xs text-ink-muted">
- {label()}
+ <span class="flex size-4 shrink-0 items-center justify-center">
+ <EntityIcon
+ targetType="calendar"
+ size="xs"
+ theme="monochrome"
+ />
+ </span>
+ <span class="min-w-0 flex-1">
+ <span class="block truncate text-sm text-ink">
+ {event.name || 'Untitled event'}
</span>
- )}
- </Show>
- </span>
- </button>
- )}
- </For>
- </Show>
+ <Show
+ when={formatEventWhen(
+ event.time,
+ calendarView.displaySettings.timeFormat
+ )}
+ >
+ {(label) => (
+ <span class="block truncate text-xs text-ink-muted">
+ {label()}
+ </span>
+ )}
+ </Show>
+ </span>
+ </button>
+ )}
+ </For>
+ </Show>
+ </Show>
+ </div>
</Show>
- </Show>
- </div>
- </div>
- </Popover.Content>
- </Layer>
- </Popover.Portal>
- </Popover>
- </Show>
+ </>
+ }
+ >
+ {(event) => (
+ <CalendarEventPreviewContent
+ event={event()}
+ timeFormat={calendarView.displaySettings.timeFormat}
+ onBack={closePreview}
+ />
+ )}
+ </Show>
+ </div>
+ </Popover.Content>
+ </Layer>
+ </Popover.Portal>
+ </Popover>
);
}
diff --git a/apps/web/src/lib/core/hotkey/tokens.ts b/apps/web/src/lib/core/hotkey/tokens.ts
index 24ff721617..fecf21ba19 100644
--- a/apps/web/src/lib/core/hotkey/tokens.ts
+++ b/apps/web/src/lib/core/hotkey/tokens.ts
@@ -90,6 +90,7 @@ export const TOKENS = {
next: 'calendar.period.next',
today: 'calendar.period.today',
},
+ search: 'calendar.search',
},
// global
diff --git a/apps/web/src/lib/queries/calendar/mention-preview.ts b/apps/web/src/lib/queries/calendar/mention-preview.ts
index 61072b9035..c141ef4277 100644
--- a/apps/web/src/lib/queries/calendar/mention-preview.ts
+++ b/apps/web/src/lib/queries/calendar/mention-preview.ts
@@ -1,10 +1,26 @@
import { queryClient } from '@queries/client';
import { storageServiceClient } from '@service-storage/client';
import type { CalendarMentionEvent } from '@service-storage/generated/schemas/calendarMentionEvent';
+import { useQuery } from '@tanstack/solid-query';
+import type { Accessor } from 'solid-js';
import { calendarKeys } from './keys';
const MENTION_PREVIEW_STALE_TIME = 60_000;
+async function fetchPreview(
+ eventId: string,
+ occurrenceKey?: string
+): Promise<CalendarMentionEvent | null> {
+ const result = await storageServiceClient.getBatchCalendarEventPreviews({
+ items: [{ eventId, occurrenceKey }],
+ });
+ if (result.isErr()) {
+ throw new Error('Failed to fetch calendar mention preview');
+ }
+ const item = result.value.items[0];
+ return item?.type === 'access' && item.event ? item.event : null;
+}
+
/**
* Resolve one mentioned event to the viewer's own copy of the meeting,
* occurrence-scoped when a key is given. Returns `null` when the viewer has
@@ -16,16 +32,41 @@ export async function fetchCalendarMentionPreview(
): Promise<CalendarMentionEvent | null> {
return queryClient.fetchQuery({
queryKey: calendarKeys.mentionPreview(eventId, occurrenceKey).queryKey,
- queryFn: async () => {
- const result = await storageServiceClient.getBatchCalendarEventPreviews({
- items: [{ eventId, occurrenceKey }],
- });
- if (result.isErr()) {
- throw new Error('Failed to fetch calendar mention preview');
- }
- const item = result.value.items[0];
- return item?.type === 'access' && item.event ? item.event : null;
- },
+ queryFn: () => fetchPreview(eventId, occurrenceKey),
staleTime: MENTION_PREVIEW_STALE_TIME,
});
}
+
+/** Target of a reactive mention-preview lookup. */
+export interface CalendarMentionPreviewInput {
+ eventId: string;
+ occurrenceKey?: string;
+}
+
+/**
+ * Reactive form of {@link fetchCalendarMentionPreview}: the viewer's copy of
+ * one event, refetched as the target changes. Shares the cache and stale
+ * window with the imperative fetch through the same query key.
+ */
+export function useCalendarMentionPreviewQuery(
+ input: Accessor<CalendarMentionPreviewInput | undefined>,
+ options?: Accessor<{ enabled?: boolean }>
+) {
+ return useQuery(() => {
+ const target = input();
+ return {
+ queryKey: calendarKeys.mentionPreview(
+ target?.eventId ?? '',
+ target?.occurrenceKey
+ ).queryKey,
+ queryFn: () => {
+ if (!target) {
+ throw new Error('Calendar mention preview target is unavailable');
+ }
+ return fetchPreview(target.eventId, target.occurrenceKey);
+ },
+ enabled: target !== undefined && options?.().enabled !== false,
+ staleTime: MENTION_PREVIEW_STALE_TIME,
+ };
+ });
+}