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(search): add @mention support to search bar (#2517)

gbirmanc04254f947f4
diff --git a/js/app/packages/app/component/app-sidebar/sidebar.tsx b/js/app/packages/app/component/app-sidebar/sidebar.tsx
index 36bb6cbbb1..ac21091ac3 100644
--- a/js/app/packages/app/component/app-sidebar/sidebar.tsx
+++ b/js/app/packages/app/component/app-sidebar/sidebar.tsx
@@ -238,10 +238,13 @@ export const registerSidebarHotkeys = ({
const splitEl = document.querySelector(
`[data-split-id="${activeSplit.id}"]`
);
- const searchInput =
- splitEl?.querySelector<HTMLInputElement>('[data-soup-search]');
- if (searchInput) {
- searchInput.focus();
+ const searchContainer =
+ splitEl?.querySelector<HTMLElement>('[data-soup-search]');
+ if (searchContainer) {
+ const editable =
+ searchContainer.querySelector<HTMLElement>('[contenteditable]') ??
+ searchContainer;
+ editable.focus();
return true;
}
}
diff --git a/js/app/packages/app/component/next-soup/soup-view/create-search-state.ts b/js/app/packages/app/component/next-soup/soup-view/create-search-state.ts
index 97d62650b3..1dc78a07ca 100644
--- a/js/app/packages/app/component/next-soup/soup-view/create-search-state.ts
+++ b/js/app/packages/app/component/next-soup/soup-view/create-search-state.ts
@@ -29,12 +29,16 @@ interface CreateSearchStateArgs {
soup: SoupState;
queryFilters: Accessor<SoupItemsQueryFilters>;
disableLocalSearch?: boolean;
+ searchPaused?: Accessor<boolean>;
+ searchMentions?: Accessor<string[]>;
}
export const createSearchState = ({
soup,
queryFilters,
disableLocalSearch,
+ searchPaused,
+ searchMentions,
}: CreateSearchStateArgs) => {
const [searchText, setSearchText] = createSignal('');
@@ -61,12 +65,29 @@ export const createSearchState = ({
);
const searchUnifiedNameContentRequest = createMemo(
- (): UnifiedSearchRequest => ({
- search_on: 'name_content',
- match_type: 'partial',
- query: debouncedSearchForService(),
- filters: queryFilters(),
- })
+ (): UnifiedSearchRequest => {
+ const filters = queryFilters();
+ const query = debouncedSearchForService();
+ const mentionIds =
+ isSearchServiceDebounceSettled() && !isSearchServiceDisabled()
+ ? searchMentions?.()
+ : undefined;
+ return {
+ search_on: 'name_content',
+ match_type: 'partial',
+ query,
+ filters:
+ mentionIds && mentionIds.length > 0
+ ? {
+ ...filters,
+ channel_filters: {
+ ...filters.channel_filters,
+ mentions: mentionIds.map((id) => `user:${id}`),
+ },
+ }
+ : filters,
+ };
+ }
);
const searchQuery = useSearchSoupQuery(
@@ -79,7 +100,10 @@ export const createSearchState = ({
},
}),
() => ({
- enabled: !isSearchServiceDisabled() && isSearchServiceDebounceSettled(),
+ enabled:
+ !isSearchServiceDisabled() &&
+ isSearchServiceDebounceSettled() &&
+ !searchPaused?.(),
})
);
diff --git a/js/app/packages/app/component/next-soup/soup-view/filters-bar/soup-view-search-bar.tsx b/js/app/packages/app/component/next-soup/soup-view/filters-bar/soup-view-search-bar.tsx
index dc75048ceb..324caf2d0c 100644
--- a/js/app/packages/app/component/next-soup/soup-view/filters-bar/soup-view-search-bar.tsx
+++ b/js/app/packages/app/component/next-soup/soup-view/filters-bar/soup-view-search-bar.tsx
@@ -5,31 +5,11 @@ import { useSoupView } from '@app/component/next-soup/soup-view/soup-view-contex
import { useSplitPanelOrThrow } from '@app/component/split-layout/layoutUtils';
import { Hotkey } from '@core/component/Hotkey';
import { LabelAndHotKey, Tooltip } from '@core/component/Tooltip';
-import { ENABLE_SEARCH_QUERY_OPERATORS } from '@core/constant/featureFlags';
+import { buildConfig } from '@core/component/LexicalMarkdown/builder/MarkdownConfigBuilder';
+import { MarkdownShell } from '@core/component/LexicalMarkdown/builder/MarkdownShell';
+import { markdownToPlainText } from '@macro-inc/lexical-core/utils/parsers';
import { registerHotkey } from '@core/hotkey/hotkeys';
-import {
- createSignal,
- createEffect,
- onCleanup,
- Show,
- createMemo,
-} from 'solid-js';
-import { QUERY_FILTERS } from '@app/component/next-soup/filters/query-filters';
-import {
- detectActiveOperator,
- stripOperatorAtRange,
-} from './parse-search-operators';
-import {
- INDEX_OPTIONS,
- SearchOperatorAutocomplete,
- type AutocompleteOption,
-} from './search-operator-autocomplete';
-import { INDEX_OPTIONS as INDEX_OPTIONS_SOURCE } from './search-filter-controls';
-import type { OperatorType } from './parse-search-operators';
-
-const INDEX_QUERY_FILTERS = Object.fromEntries(
- INDEX_OPTIONS_SOURCE.map((o) => [o.value, o.queryFilters])
-);
+import { createSignal, createEffect, on, onCleanup, Show } from 'solid-js';
type SearchbarVariant = 'filled' | 'secondary';
@@ -47,199 +27,74 @@ const variantStyles: Record<SearchbarVariant, string> = {
};
export const SoupSearchbar = (props: SoupSearchbarProps) => {
- const { searchText, setSearchText, soup, setQueryFilters } = useSoupView();
+ const { setSearchText, setSearchPaused, setSearchMentions } = useSoupView();
const panel = useSplitPanelOrThrow();
- const [ref, setRef] = createSignal<HTMLInputElement | undefined>();
- let measureSpan: HTMLSpanElement | undefined;
-
- const [searchFocused, setSearchFocused] = createSignal(false);
- const [measuredWidth, setMeasuredWidth] = createSignal(0);
- const [cursorPos, setCursorPos] = createSignal(0);
- const [highlightedIndex, setHighlightedIndex] = createSignal(0);
-
- const activeOperator = createMemo(() => {
- if (!ENABLE_SEARCH_QUERY_OPERATORS) return null;
- if (!searchFocused()) return null;
- return detectActiveOperator(searchText(), cursorPos());
- });
+ const [hasContent, setHasContent] = createSignal(false);
+ const [latestMarkdown, setLatestMarkdown] = createSignal('');
+ const [mentions, setMentions] = createSignal<string[]>([]);
+
+ const editor = buildConfig('chat')
+ .namespace('soup-search-bar')
+ .singleLine()
+ .withMentions({
+ sources: ['users'],
+ disableMentionTracking: true,
+ onCreate: (mention) => {
+ if (mention.itemType !== 'user') return;
+ setMentions((prev) =>
+ prev.includes(mention.itemId) ? prev : [...prev, mention.itemId]
+ );
+ },
+ onRemove: (mention) => {
+ if (mention.itemType !== 'user') return;
+ setMentions((prev) => prev.filter((m) => m !== mention.itemId));
+ },
+ })
+ .withHistory({ timeGap: 400 })
+ .onChange((markdown) => {
+ setLatestMarkdown(markdown);
+ setHasContent(markdown.trim().length > 0);
+ })
+ .onEnter(() => {
+ if (menuIsOpen()) return false;
+ editor.controls.blur();
+ return true;
+ })
+ .onEscape(() => {
+ editor.controls.blur();
+ props.onDismiss?.();
+ return true;
+ });
- createEffect(() => {
- if (activeOperator()) {
- setHighlightedIndex(0);
- }
- });
+ // Sync search text + mention filters only when the mention menu is closed.
+ // This avoids cascading reactive updates during mention insertion and
+ // prevents search from firing while typing @partial.
+ const menuIsOpen = () => editor.controls.isMentionMenuOpen();
- const updateCursorPos = () => {
- const el = ref();
- if (el) setCursorPos(el.selectionStart ?? el.value.length);
- };
+ createEffect(() => setSearchPaused(menuIsOpen()));
- createEffect(() => {
- if (measureSpan) {
- measureSpan.textContent = searchText() || '';
- setMeasuredWidth(measureSpan.scrollWidth);
- }
- });
+ createEffect(
+ on(latestMarkdown, (markdown) => {
+ if (menuIsOpen()) return;
+ setSearchText(markdownToPlainText(markdown).trim());
+ })
+ );
- createEffect(() => {
- ref();
- if (props.autoFocus) {
- queueMicrotask(() => {
- ref()?.focus();
- });
- }
- });
+ createEffect(() => setSearchMentions(mentions()));
const searchHotkey = registerHotkey({
hotkey: ['cmd+f'],
scopeId: panel.splitHotkeyScope,
description: 'Search',
keyDownHandler: () => {
- ref()?.focus();
+ editor.controls.focus();
return true;
},
});
onCleanup(searchHotkey.dispose);
- const MIN_INPUT_WIDTH = 48;
-
- const inputWidth = () => {
- if (!searchText() && !searchFocused()) return 0;
- return Math.max(MIN_INPUT_WIDTH, measuredWidth());
- };
-
- const handleSelect = (type: OperatorType, option: AutocompleteOption) => {
- const op = activeOperator();
- if (!op) return;
-
- const newText = stripOperatorAtRange(
- searchText(),
- op.startIndex,
- op.endIndex
- );
- setSearchText(newText);
-
- switch (type) {
- case 'index': {
- for (const opt of INDEX_OPTIONS) {
- if (soup.filters.isActive(opt.id)) {
- soup.filters.toggle({ or: [opt.id] });
- }
- }
- soup.filters.toggle({ or: [option.id] });
- const qf = INDEX_QUERY_FILTERS[option.id];
- if (qf) setQueryFilters(qf);
- break;
- }
- case 'in': {
- if (!soup.filters.isActive('channels')) {
- for (const opt of INDEX_OPTIONS) {
- if (soup.filters.isActive(opt.id)) {
- soup.filters.toggle({ or: [opt.id] });
- }
- }
- soup.filters.toggle({ or: ['channels'] });
- setQueryFilters({
- ...QUERY_FILTERS.channels,
- channel_filters: {
- ...QUERY_FILTERS.channels.channel_filters,
- channel_ids: [option.id],
- },
- });
- } else {
- setQueryFilters((prev) => ({
- ...prev,
- channel_filters: {
- ...prev.channel_filters,
- channel_ids: [
- ...(prev.channel_filters?.channel_ids ?? []),
- option.id,
- ],
- },
- }));
- }
- break;
- }
- case 'from': {
- if (!soup.filters.isActive('channels')) {
- for (const opt of INDEX_OPTIONS) {
- if (soup.filters.isActive(opt.id)) {
- soup.filters.toggle({ or: [opt.id] });
- }
- }
- soup.filters.toggle({ or: ['channels'] });
- setQueryFilters({
- ...QUERY_FILTERS.channels,
- channel_filters: {
- ...QUERY_FILTERS.channels.channel_filters,
- sender_ids: [option.id],
- },
- });
- } else {
- setQueryFilters((prev) => ({
- ...prev,
- channel_filters: {
- ...prev.channel_filters,
- sender_ids: [
- ...(prev.channel_filters?.sender_ids ?? []),
- option.id,
- ],
- },
- }));
- }
- break;
- }
- }
-
- queueMicrotask(() => ref()?.focus());
- };
-
- const handleKeyDown = (e: KeyboardEvent) => {
- const input = e.currentTarget as HTMLInputElement | null;
- const op = activeOperator();
-
- if (op) {
- if (e.key === 'ArrowDown') {
- e.preventDefault();
- setHighlightedIndex((i) => i + 1);
- return;
- }
- if (e.key === 'ArrowUp') {
- e.preventDefault();
- setHighlightedIndex((i) => Math.max(0, i - 1));
- return;
- }
- if (e.key === 'Enter') {
- e.preventDefault();
- const dropdownEl = ref()
- ?.closest('[data-search-bar-wrapper]')
- ?.querySelector('[data-operator-dropdown]');
- if (dropdownEl) {
- const buttons = dropdownEl.querySelectorAll('button');
- const idx = highlightedIndex();
- if (buttons[idx]) {
- (buttons[idx] as HTMLButtonElement).click();
- }
- }
- return;
- }
- if (e.key === 'Escape') {
- e.preventDefault();
- input?.blur();
- props.onDismiss?.();
- return;
- }
- } else {
- if (e.key === 'Escape' || e.key === 'Enter' || e.key === 'ArrowDown') {
- e.preventDefault();
- input?.blur();
- if (e.key === 'Escape') props.onDismiss?.();
- }
- }
- };
-
return (
<div
class="w-full flex items-center shrink-0 grow min-w-0 mobile:-order-2"
@@ -255,75 +110,49 @@ export const SoupSearchbar = (props: SoupSearchbarProps) => {
'relative flex items-center gap-1 rounded-xs py-1.5 mobile:h-9 pl-2 pr-1 mobile:min-w-35 border text-xs',
variantStyles[props.variant ?? 'secondary']
)}
- onMouseDown={(e) => {
- if (e.target !== ref()) {
- e.preventDefault();
- ref()?.focus();
- }
- }}
>
<SearchIcon class="size-4 shrink-0" />
- <span
- ref={(el) => {
- measureSpan = el;
- }}
- class="invisible absolute whitespace-pre"
- aria-hidden="true"
- />
- <input
- ref={setRef}
+ <div
data-soup-search
- type="text"
- value={searchText()}
- onInput={(e) => {
- setSearchText(e.currentTarget.value);
- queueMicrotask(updateCursorPos);
- }}
- onClick={updateCursorPos}
- onFocus={() => {
- setSearchFocused(true);
- queueMicrotask(updateCursorPos);
+ class="flex-1 min-w-0 [&_[contenteditable]]:outline-none [&_[contenteditable]]:p-0 [&_p]:my-0"
+ onKeyDown={(e) => {
+ if (menuIsOpen()) return;
+ if (e.key === 'ArrowDown' || e.key === 'j') {
+ e.preventDefault();
+ editor.controls.blur();
+ }
}}
- onBlur={() => setSearchFocused(false)}
- onKeyDown={handleKeyDown}
- class="peer p-0 bg-transparent border-none outline-none ring-0 focus:outline-none focus:ring-0 cursor-default w-full"
- style={{ width: `${inputWidth()}px` }}
- />
- <Show when={!searchText()}>
- <span class="text-ink-placeholder leading-none pointer-events-none text-sm peer-focus:hidden">
- Search
- </span>
- </Show>
- <Show when={!searchText() && !props.onDismiss}>
- <div class="absolute -right-2 top-1/2 -translate-1/2 flex border border-edge-muted text-xs rounded-md items-center px-1 py-px peer-focus:hidden">
+ >
+ <MarkdownShell
+ config={editor}
+ placeholder="Search"
+ autofocus={props.autoFocus}
+ class="!min-h-0 !overflow-visible"
+ />
+ </div>
+ <Show when={!hasContent() && !props.onDismiss}>
+ <div class="absolute -right-2 top-1/2 -translate-1/2 flex border border-edge-muted text-xs rounded-md items-center px-1 py-px">
<Hotkey shortcut="cmd+f" />
</div>
</Show>
- <Show when={searchText() || props.onDismiss}>
+ <Show when={hasContent() || props.onDismiss}>
<button
type="button"
class="ml-auto size-4 mobile:size-6 shrink-0 hover:opacity-60"
onMouseDown={(e) => {
e.preventDefault();
e.stopPropagation();
+ editor.controls.clear();
setSearchText('');
+ setHasContent(false);
+ setMentions([]);
+ setSearchMentions([]);
props.onDismiss?.();
}}
>
<XIcon class="size-4 mobile:size-6" />
</button>
</Show>
- <Show when={activeOperator()}>
- {(op) => (
- <SearchOperatorAutocomplete
- activeOperator={op()}
- onSelect={handleSelect}
- onDismiss={() => ref()?.blur()}
- highlightedIndex={highlightedIndex}
- setHighlightedIndex={setHighlightedIndex}
- />
- )}
- </Show>
</div>
</Tooltip>
</div>
diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx
index ba74eb1603..d4c596288b 100644
--- a/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx
+++ b/js/app/packages/app/component/next-soup/soup-view/soup-view-context.tsx
@@ -68,6 +68,10 @@ interface SoupViewContextValues {
source: DataSource<EntityData>;
searchText: Accessor<string>;
setSearchText: (value: string) => void;
+ searchPaused: Accessor<boolean>;
+ setSearchPaused: Setter<boolean>;
+ searchMentions: Accessor<string[]>;
+ setSearchMentions: Setter<string[]>;
featuredIds: Accessor<string[]>;
rows: Accessor<SoupRow[]>;
isSearchServiceLoading: Accessor<boolean>;
@@ -134,6 +138,8 @@ export const SoupViewContextProvider: FlowComponent<
const [internalQueryFilters, setInternalQueryFilters] =
createSignal<SoupBody>({ ...(props.queryFilters ?? {}) });
+ const [searchPaused, setSearchPaused] = createSignal(false);
+ const [searchMentions, setSearchMentions] = createSignal<string[]>([]);
const [assigneeFilter, setAssigneeFilter] = createSignal<string[]>([]);
const [activeTab, setActiveTab] = createSignal<string | undefined>(undefined);
@@ -162,6 +168,8 @@ export const SoupViewContextProvider: FlowComponent<
soup,
queryFilters,
disableLocalSearch: props.disableLocalSearch,
+ searchPaused,
+ searchMentions,
});
const notificationSource = useGlobalNotificationSource();
@@ -367,6 +375,10 @@ export const SoupViewContextProvider: FlowComponent<
rows,
searchText: search.searchText,
setSearchText: search.setSearchText,
+ searchPaused,
+ setSearchPaused,
+ searchMentions,
+ setSearchMentions,
featuredIds: search.featuredIds,
isSearchServiceLoading: search.isSearchServiceLoading,
isLocalSearchSettling: search.isLocalSearchSettling,
diff --git a/js/app/packages/core/component/LexicalMarkdown/builder/MarkdownShell.tsx b/js/app/packages/core/component/LexicalMarkdown/builder/MarkdownShell.tsx
index 12865425c2..b51154ef5e 100644
--- a/js/app/packages/core/component/LexicalMarkdown/builder/MarkdownShell.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/builder/MarkdownShell.tsx
@@ -241,6 +241,7 @@ export const MarkdownShell: Component<
disableMentionTracking={
builderConfig.mentions?.disableMentionTracking
}
+ sources={builderConfig.mentions?.sources}
/>
)}
</Show>
diff --git a/js/app/packages/core/component/LexicalMarkdown/builder/buildHandleFromConfig.ts b/js/app/packages/core/component/LexicalMarkdown/builder/buildHandleFromConfig.ts
index ca5fad49b3..3a81e0ed7a 100644
--- a/js/app/packages/core/component/LexicalMarkdown/builder/buildHandleFromConfig.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/builder/buildHandleFromConfig.ts
@@ -251,6 +251,7 @@ export function buildHandleFromConfig(config: EditorConfig): EditorHandle {
setState: (state: SerializedEditorState) =>
initializeEditorWithState(editor, state),
getLexical: () => editor,
+ isMentionMenuOpen: () => mentionsMenuOps?.isOpen() ?? false,
};
return {
diff --git a/js/app/packages/core/component/LexicalMarkdown/builder/types.ts b/js/app/packages/core/component/LexicalMarkdown/builder/types.ts
index 2a44d60b7a..3f5006361c 100644
--- a/js/app/packages/core/component/LexicalMarkdown/builder/types.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/builder/types.ts
@@ -11,13 +11,14 @@ import type {
SelectionData,
} from '../plugins';
import type { createMenuOperations } from '../shared/inlineMenu';
+import type { MentionBucketId } from '../component/menu/MentionsMenu/MentionsMenuController';
export interface ActionsOptions {
useBlockBoundary?: boolean;
}
export interface MentionsOptions {
- sources?: Array<'users' | 'documents'>;
+ sources?: MentionBucketId[];
onRemove?: (mention: ItemMention) => void;
onCreate?: (mention: ItemMention) => void;
block?: string;
@@ -88,6 +89,7 @@ export interface EditorControls {
getState: () => SerializedEditorState;
setState: (state: SerializedEditorState) => void;
getLexical: () => LexicalEditor;
+ isMentionMenuOpen: () => boolean;
}
/**
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx
index 832b9e6387..79ad10bf3a 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx
+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx
@@ -34,7 +34,7 @@ import type {
import type { HistoryItem as Item } from '@queries/history/history';
import { ClippedPanel } from '@core/component/ClippedPanel';
import { debouncedDependent } from '@core/util/debounce';
-import type { BucketConfig } from './MentionsMenuController';
+import type { BucketConfig, MentionBucketId } from './MentionsMenuController';
import { useMentionsMenuController } from './MentionsMenuController';
import type { MentionItem } from '../../../utils/mentionsUtils';
import { ItemBin } from './components/ItemBin';
@@ -74,6 +74,8 @@ export type MentionsMenuProps = {
useSnapshotForDocuments?: boolean;
/** whether to show open tabs as a bucket in the menu */
showOpenTabs?: boolean;
+ /** restrict which mention source buckets to show (e.g. ['users'] for user-only mentions) */
+ sources?: MentionBucketId[];
};
export function MentionsMenu(props: MentionsMenuProps) {
@@ -269,7 +271,12 @@ function MentionsMenuInner(props: MentionsMenuProps) {
});
}
- return buckets.filter((bucket) => bucket.getFullCount() > 0);
+ const sourcesFilter = props.sources;
+ const filtered = sourcesFilter
+ ? buckets.filter((bucket) => sourcesFilter.includes(bucket.id as any))
+ : buckets;
+
+ return filtered.filter((bucket) => bucket.getFullCount() > 0);
});
const controller = useMentionsMenuController(bucketConfigs, {
diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenuController.ts b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenuController.ts
index 97fea5bdb3..bafa5b8421 100644
--- a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenuController.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenuController.ts
@@ -3,8 +3,17 @@ import { createSignal } from 'solid-js';
import { createLazyMemo } from '@solid-primitives/memo';
import type { MentionItem } from '../../../utils/mentionsUtils';
+export type MentionBucketId =
+ | 'all'
+ | 'users'
+ | 'documents'
+ | 'channels'
+ | 'emails'
+ | 'dates'
+ | 'openTabs';
+
export interface BucketConfig<T extends MentionItem = MentionItem> {
- id: string;
+ id: MentionBucketId;
label: string;
getData: () => T[];
getFullCount: () => number;