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.

chore: create search state separate from soup view context (#1525)

gbirmana73b0710db34
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
new file mode 100644
index 0000000000..f7050a87c6
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/soup-view/create-search-state.ts
@@ -0,0 +1,258 @@
+import type { SoupState } from '@app/component/next-soup/create-soup-state';
+import {
+ type FilterID,
+ getFolderFileTypes,
+} from '@app/component/next-soup/filters/filters';
+import { arrayEquals } from '@core/util/compareUtils';
+import { debouncedDependent } from '@core/util/debounce';
+import { fuzzyMatch } from '@core/util/fuzzy';
+import { mergeAdjacentMacroEmTags } from '@core/util/searchHighlight';
+import type { EntityData, WithSearch } from '@entity';
+import {
+ type SoupItemsQueryFilters,
+ type SoupItemsQueryArgs,
+ useSoupItemsQuery,
+} from '@queries/soup/items';
+import { useSearchSoupQuery } from '@queries/soup/search';
+import type {
+ UnifiedSearchIndex,
+ UnifiedSearchRequest,
+} from '@service-search/generated/models';
+import {
+ type Accessor,
+ createMemo,
+ createRenderEffect,
+ createSignal,
+} from 'solid-js';
+import { match } from 'ts-pattern';
+
+const SEARCH_SERVICE_DEBOUNCE_MS = 300;
+const LOCAL_FUZZY_SEARCH_DEBOUNCE_MS = 20;
+
+const NIL_UUID = '00000000-0000-0000-0000-000000000000';
+
+const CHANNEL_PRELOAD_ARGS: SoupItemsQueryArgs = {
+ params: { limit: 500, sort_method: 'updated_at' },
+ body: {
+ chat_filters: { chat_ids: [NIL_UUID] },
+ document_filters: { document_ids: [NIL_UUID] },
+ email_filters: { recipients: [NIL_UUID] },
+ project_filters: { project_ids: [NIL_UUID] },
+ channel_filters: {
+ channel_types: [],
+ },
+ },
+};
+
+function mergeEntityPools(
+ items: EntityData[],
+ extra: EntityData[]
+): EntityData[] {
+ if (extra.length === 0) return items;
+ const existingIds = new Set(items.map((e) => e.id));
+ const newItems = extra.filter((e) => !existingIds.has(e.id));
+ if (newItems.length === 0) return items;
+ return [...items, ...newItems];
+}
+
+interface CreateSearchStateArgs {
+ soup: SoupState;
+ queryFilters: Accessor<SoupItemsQueryFilters>;
+}
+
+export const createSearchState = ({
+ soup,
+ queryFilters,
+}: CreateSearchStateArgs) => {
+ const [searchText, setSearchText] = createSignal('');
+
+ const trimmedSearchText = createMemo(() => searchText().trim());
+
+ const debouncedSearchForLocal = debouncedDependent(
+ trimmedSearchText,
+ LOCAL_FUZZY_SEARCH_DEBOUNCE_MS
+ );
+
+ const debouncedSearchForService = debouncedDependent(
+ trimmedSearchText,
+ SEARCH_SERVICE_DEBOUNCE_MS
+ );
+
+ const isSearching = createMemo(() => trimmedSearchText().length > 0);
+
+ const unifiedSearchIncludeArray = createMemo<UnifiedSearchIndex[]>(
+ () => {
+ const types = soup.filters.activeIds() as FilterID[];
+ const includeArray: UnifiedSearchIndex[] = [];
+ for (const type of types) {
+ match(type)
+ .with('document', 'file', 'task', () => {
+ includeArray.push('documents');
+ })
+ .with('agent', () => {
+ includeArray.push('chats');
+ })
+ .with('people', 'teams', 'channels', () => {
+ includeArray.push('channels');
+ })
+ .with('email', () => {
+ includeArray.push('emails');
+ })
+ .with(
+ 'signal',
+ 'noise',
+ 'explicit-noise',
+ 'unread',
+ 'not-done',
+ () => {}
+ )
+ .exhaustive();
+ }
+ return Array.from(new Set(includeArray));
+ },
+ [],
+ { equals: arrayEquals }
+ );
+
+ const validSearchTerms = createMemo(
+ () => debouncedSearchForService().length >= 3
+ );
+ const isSearchDisabled = createMemo(() => !validSearchTerms());
+
+ const searchFilters = createMemo(() => {
+ const {
+ channel_filters,
+ chat_filters,
+ document_filters,
+ email_filters,
+ project_filters,
+ } = queryFilters();
+
+ let fileTypes = document_filters?.file_types;
+
+ if (soup.filters.isActive('file')) {
+ fileTypes = getFolderFileTypes('search');
+ }
+
+ return {
+ channel:
+ channel_filters?.channel_ids?.length ||
+ channel_filters?.channel_types?.length
+ ? channel_filters
+ : null,
+ chat:
+ chat_filters?.chat_ids?.length || chat_filters?.project_ids?.length
+ ? chat_filters
+ : null,
+ document:
+ document_filters?.document_ids?.length ||
+ document_filters?.project_ids?.length ||
+ document_filters?.file_types?.length
+ ? { ...document_filters, file_types: fileTypes }
+ : null,
+ email: email_filters?.recipients?.length ? email_filters : null,
+ project: project_filters?.project_ids?.length ? project_filters : null,
+ };
+ });
+
+ const searchUnifiedNameContentRequest = createMemo(
+ (): UnifiedSearchRequest => {
+ const terms = debouncedSearchForService();
+ const include = unifiedSearchIncludeArray();
+ const filters = searchFilters();
+
+ return {
+ search_on: 'name_content',
+ match_type: 'partial',
+ terms: terms.length > 0 ? [terms] : undefined,
+ include,
+ filters,
+ };
+ }
+ );
+
+ const itemsQuery = useSoupItemsQuery(
+ () => ({
+ params: {
+ limit: 100,
+ sort_method: soup.sort.active()[0]?.id ?? 'updated_at',
+ },
+ body: { ...queryFilters(), emailView: 'all' },
+ }),
+ () => ({
+ enabled: isSearchDisabled(),
+ })
+ );
+
+ const searchQuery = useSearchSoupQuery(
+ () => ({
+ params: {
+ page_size: 100,
+ },
+ body: {
+ ...searchUnifiedNameContentRequest(),
+ },
+ }),
+ () => ({
+ enabled:
+ !isSearchDisabled() &&
+ trimmedSearchText() === debouncedSearchForService(),
+ })
+ );
+
+ const channelItemsQuery = useSoupItemsQuery(() => CHANNEL_PRELOAD_ARGS);
+ createRenderEffect(() => {
+ if (
+ channelItemsQuery.hasNextPage &&
+ !channelItemsQuery.isFetchingNextPage
+ ) {
+ channelItemsQuery.fetchNextPage();
+ }
+ });
+
+ const nameFuzzySearchFilter = (items: EntityData[]) => {
+ const query = debouncedSearchForLocal();
+ if (!query || query.length === 0) return items;
+
+ const matchResults = fuzzyMatch(query, items, (item) => item.name);
+
+ return matchResults.map((result) => {
+ return {
+ ...result.item,
+ search: {
+ nameHighlight: mergeAdjacentMacroEmTags(result.nameHighlight),
+ contentHitData: null,
+ source: 'local',
+ },
+ } as WithSearch<EntityData>;
+ });
+ };
+
+ const localFuzzyResults = createMemo(() => {
+ const pool = mergeEntityPools(
+ itemsQuery.data ?? [],
+ channelItemsQuery.data ?? []
+ );
+ return nameFuzzySearchFilter(pool);
+ });
+
+ const freshSearchResults = createMemo<EntityData[]>(() => {
+ if (isSearchDisabled()) return [];
+ if (trimmedSearchText() !== debouncedSearchForService()) return [];
+ if (searchQuery.isFetching && !searchQuery.isFetchingNextPage) return [];
+ return searchQuery.data ?? [];
+ });
+
+ return {
+ searchText,
+ setSearchText,
+ isSearching,
+ isSearchDisabled,
+ localFuzzyResults,
+ freshSearchResults,
+ itemsQuery,
+ searchQuery,
+ };
+};
+
+export type SearchState = ReturnType<typeof createSearchState>;
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 3108ef4d6c..0b8db8eafc 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
@@ -3,28 +3,13 @@ import {
createSoupState,
type SoupState,
} from '@app/component/next-soup/create-soup-state';
-import {
- type FilterID,
- getFolderFileTypes,
-} from '@app/component/next-soup/filters/filters';
+import { createSearchState } from '@app/component/next-soup/soup-view/create-search-state';
import { sortEntitiesForSearch } from '@app/component/next-soup/soup-view/sort-options';
import { deduplicateEntities } from '@app/component/next-soup/utils';
-import { arrayEquals } from '@core/util/compareUtils';
-import { debouncedDependent } from '@core/util/debounce';
-import { fuzzyMatch } from '@core/util/fuzzy';
-import { mergeAdjacentMacroEmTags } from '@core/util/searchHighlight';
import type { EntityData, WithNotification, WithSearch } from '@entity';
+import { isWithNotification } from '@entity';
import { useNotificationsForEntity } from '@notifications';
-import {
- type SoupItemsQueryFilters,
- type SoupItemsQueryArgs,
- useSoupItemsQuery,
-} from '@queries/soup/items';
-import { useSearchSoupQuery } from '@queries/soup/search';
-import type {
- UnifiedSearchIndex,
- UnifiedSearchRequest,
-} from '@service-search/generated/models';
+import type { SoupItemsQueryFilters } from '@queries/soup/items';
import {
type Accessor,
createContext,
@@ -37,38 +22,6 @@ import {
Suspense,
useContext,
} from 'solid-js';
-import { isWithNotification } from '@entity';
-
-import { match } from 'ts-pattern';
-
-const SEARCH_SERVICE_DEBOUNCE_MS = 300;
-const LOCAL_FUZZY_SEARCH_DEBOUNCE_MS = 20;
-
-const NIL_UUID = '00000000-0000-0000-0000-000000000000';
-
-const CHANNEL_PRELOAD_ARGS: SoupItemsQueryArgs = {
- params: { limit: 500, sort_method: 'updated_at' },
- body: {
- chat_filters: { chat_ids: [NIL_UUID] },
- document_filters: { document_ids: [NIL_UUID] },
- email_filters: { recipients: [NIL_UUID] },
- project_filters: { project_ids: [NIL_UUID] },
- channel_filters: {
- channel_types: [],
- },
- },
-};
-
-function mergeEntityPools(
- items: EntityData[],
- extra: EntityData[]
-): EntityData[] {
- if (extra.length === 0) return items;
- const existingIds = new Set(items.map((e) => e.id));
- const newItems = extra.filter((e) => !existingIds.has(e.id));
- if (newItems.length === 0) return items;
- return [...items, ...newItems];
-}
type Row<T> = {
original: T;
@@ -131,71 +84,15 @@ export const SoupViewContextProvider: FlowComponent<
> = (props) => {
const soup = props.soup ?? createSoupState();
- const [searchText, setSearchText] = createSignal('');
const [internalQueryFilters, setQueryFilters] =
createSignal<SoupItemsQueryFilters>({});
- const trimmedSearchText = createMemo(() => searchText().trim());
-
- const debouncedSearchForLocal = debouncedDependent(
- trimmedSearchText,
- LOCAL_FUZZY_SEARCH_DEBOUNCE_MS
- );
-
- const debouncedSearchForService = debouncedDependent(
- trimmedSearchText,
- SEARCH_SERVICE_DEBOUNCE_MS
- );
-
- const isSearching = createMemo(() => trimmedSearchText().length > 0);
-
- const unifiedSearchIncludeArray = createMemo<UnifiedSearchIndex[]>(
- () => {
- const types = soup.filters.activeIds() as FilterID[];
- // NOTE: empty array means search all
- const includeArray: UnifiedSearchIndex[] = [];
- for (const type of types) {
- match(type)
- .with('document', 'file', 'task', () => {
- includeArray.push('documents');
- })
- .with('agent', () => {
- includeArray.push('chats');
- })
- .with('people', 'teams', 'channels', () => {
- includeArray.push('channels');
- })
- .with('email', () => {
- includeArray.push('emails');
- })
- .with(
- 'signal',
- 'noise',
- 'explicit-noise',
- 'unread',
- 'not-done',
- () => {}
- )
- .exhaustive();
- }
- return Array.from(new Set(includeArray));
- },
- [],
- { equals: arrayEquals }
- );
-
- const validSearchTerms = createMemo(
- () => debouncedSearchForService().length >= 3
- );
- const isSearchDisabled = createMemo(() => !validSearchTerms());
-
const queryFilters = createMemo(() => {
const base = internalQueryFilters();
return {
...base,
...props.queryFilters,
- // Deep merge individual filter objects if both exist
channel_filters: {
...base.channel_filters,
...props.queryFilters?.channel_filters,
@@ -219,113 +116,7 @@ export const SoupViewContextProvider: FlowComponent<
};
});
- const searchFilters = createMemo(() => {
- const {
- channel_filters,
- chat_filters,
- document_filters,
- email_filters,
- project_filters,
- } = queryFilters();
-
- let fileTypes = document_filters?.file_types;
-
- if (soup.filters.isActive('file')) {
- fileTypes = getFolderFileTypes('search');
- }
-
- return {
- channel:
- channel_filters?.channel_ids?.length ||
- channel_filters?.channel_types?.length
- ? channel_filters
- : null,
- chat:
- chat_filters?.chat_ids?.length || chat_filters?.project_ids?.length
- ? chat_filters
- : null,
- document:
- document_filters?.document_ids?.length ||
- document_filters?.project_ids?.length ||
- document_filters?.file_types?.length
- ? { ...document_filters, file_types: fileTypes }
- : null,
- email: email_filters?.recipients?.length ? email_filters : null,
- project: project_filters?.project_ids?.length ? project_filters : null,
- };
- });
-
- const searchUnifiedNameContentRequest = createMemo(
- (): UnifiedSearchRequest => {
- const terms = debouncedSearchForService();
- const include = unifiedSearchIncludeArray();
- const filters = searchFilters();
-
- return {
- search_on: 'name_content',
- match_type: 'partial',
- terms: terms.length > 0 ? [terms] : undefined,
- include,
- filters,
- };
- }
- );
-
- const itemsQuery = useSoupItemsQuery(
- () => ({
- params: {
- limit: 100,
- sort_method: soup.sort.active()[0]?.id ?? 'updated_at',
- },
- body: { ...queryFilters(), emailView: 'all' },
- }),
- () => ({
- enabled: isSearchDisabled(),
- })
- );
-
- const searchQuery = useSearchSoupQuery(
- () => ({
- params: {
- page_size: 100,
- },
- body: {
- ...searchUnifiedNameContentRequest(),
- },
- }),
- () => ({
- enabled: !isSearchDisabled(),
- })
- );
-
- // load all channels into memory for local search
- const channelItemsQuery = useSoupItemsQuery(() => CHANNEL_PRELOAD_ARGS);
- createRenderEffect(() => {
- if (
- channelItemsQuery.hasNextPage &&
- !channelItemsQuery.isFetchingNextPage
- ) {
- channelItemsQuery.fetchNextPage();
- }
- });
-
- const nameFuzzySearchFilter = (items: EntityData[]) => {
- const query = debouncedSearchForLocal();
- if (!query || query.length === 0) return items;
-
- const matchResults = fuzzyMatch(query, items, (item) => item.name);
-
- return matchResults.map((result) => {
- return {
- ...result.item,
- search: {
- nameHighlight: mergeAdjacentMacroEmTags(result.nameHighlight),
- contentHitData: null,
- source: 'local',
- },
- } as WithSearch<EntityData>;
- });
- };
+ const search = createSearchState({ soup, queryFilters });
const notificationSource = useGlobalNotificationSource();
@@ -362,34 +153,20 @@ export const SoupViewContextProvider: FlowComponent<
};
};
- const localFuzzyResults = createMemo(() => {
- const pool = mergeEntityPools(
- itemsQuery.data ?? [],
- channelItemsQuery.data ?? []
- );
- return nameFuzzySearchFilter(pool);
- });
-
- const freshSearchResults = createMemo<EntityData[]>(() => {
- if (isSearchDisabled()) return [];
- if (searchQuery.isFetching && !searchQuery.isFetchingNextPage) return [];
- return searchQuery.data ?? [];
- });
-
const items = createMemo<SoupEntity[]>(
(prev) => {
- const searching = isSearching();
+ const searching = search.isSearching();
if (!searching) {
- const data = itemsQuery.data;
+ const data = search.itemsQuery.data;
if (!data) return prev;
return data.map((e) =>
isWithNotification(e) ? e : attachNotifications(e)
) as SoupEntity[];
}
- const local = localFuzzyResults();
- const service = freshSearchResults();
+ const local = search.localFuzzyResults();
+ const service = search.freshSearchResults();
const merged: SoupEntity[] = [...service, ...local];
@@ -423,7 +200,7 @@ export const SoupViewContextProvider: FlowComponent<
transformed = deduplicateEntities(next);
- if (isSearching()) {
+ if (search.isSearching()) {
transformed.sort(sortEntitiesForSearch);
}
@@ -446,6 +223,8 @@ export const SoupViewContextProvider: FlowComponent<
return entities().map((e) => attachMethods(e));
});
+ const { itemsQuery, searchQuery } = search;
+
const context = {
soup,
source: {
@@ -475,9 +254,9 @@ export const SoupViewContextProvider: FlowComponent<
},
},
rows,
- searchText,
- setSearchText,
- isSearchDisabled,
+ searchText: search.searchText,
+ setSearchText: search.setSearchText,
+ isSearchDisabled: search.isSearchDisabled,
queryFilters,
setQueryFilters,
};