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: soup query needs emails + soup optimize (#1568)

gbirmanb098a0c59f7d
diff --git a/js/app/packages/app/component/Root.tsx b/js/app/packages/app/component/Root.tsx
index b8f3455f6d..b8defe661d 100644
--- a/js/app/packages/app/component/Root.tsx
+++ b/js/app/packages/app/component/Root.tsx
@@ -72,6 +72,7 @@ import { Login } from './auth/Login';
import { setCookie } from './auth/Shared';
import { makeEmailAuthComponents } from './EmailAuth';
import { GlobalAppStateProvider } from './GlobalAppState';
+import { SearchProvider } from './next-soup/search-context';
import { Layout } from './Layout';
import MacroJump from './MacroJump';
import Onboarding from './Onboarding';
@@ -406,29 +407,31 @@ export function Root() {
<UserInfoSideEffects />
<ConfiguredGlobalAppStateProvider>
<ChannelsContextProvider>
- <TabAttachmentsInit />
- <ReactiveFavicon />
- <Title>{tabTitle()}</Title>
- <MacroJump />
- <Visor />
- <SuspenseContextComp fallback={<RootSuspenseFallback />}>
- <IsomorphicRouter
- transformUrl={transformShortIdInUrlPathname}
- root={Layout}
- rootPreload={rootPreload}
- base={ROUTER_BASE}
- >
- {{
- path: '/',
- component: TauriRouteListener,
- children: ROUTES,
- }}
- </IsomorphicRouter>
- </SuspenseContextComp>
- <ToastRegion />
- <Show when={ENABLE_WEBSOCKET_DEBUGGER}>
- <WebsocketDebugger />
- </Show>
+ <SearchProvider>
+ <TabAttachmentsInit />
+ <ReactiveFavicon />
+ <Title>{tabTitle()}</Title>
+ <MacroJump />
+ <Visor />
+ <SuspenseContextComp fallback={<RootSuspenseFallback />}>
+ <IsomorphicRouter
+ transformUrl={transformShortIdInUrlPathname}
+ root={Layout}
+ rootPreload={rootPreload}
+ base={ROUTER_BASE}
+ >
+ {{
+ path: '/',
+ component: TauriRouteListener,
+ children: ROUTES,
+ }}
+ </IsomorphicRouter>
+ </SuspenseContextComp>
+ <ToastRegion />
+ <Show when={ENABLE_WEBSOCKET_DEBUGGER}>
+ <WebsocketDebugger />
+ </Show>
+ </SearchProvider>
</ChannelsContextProvider>
</ConfiguredGlobalAppStateProvider>
</UserContextProvider>
diff --git a/js/app/packages/app/component/next-soup/create-soup-state.ts b/js/app/packages/app/component/next-soup/create-soup-state.ts
index 41e20f0ded..742a90c682 100644
--- a/js/app/packages/app/component/next-soup/create-soup-state.ts
+++ b/js/app/packages/app/component/next-soup/create-soup-state.ts
@@ -26,7 +26,6 @@ export type GroupConfig<T> = {
export type SortConfig<T> = {
id: string;
fn: (a: T, b: T) => number;
- desc?: boolean;
};
interface SoupContextOptions<
diff --git a/js/app/packages/app/component/next-soup/search-context.tsx b/js/app/packages/app/component/next-soup/search-context.tsx
new file mode 100644
index 0000000000..4a8d423bbc
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/search-context.tsx
@@ -0,0 +1,95 @@
+import { throttledDependent } from '@core/util/debounce';
+import type { EntityData } from '@entity';
+import {
+ type SoupItemsQueryArgs,
+ useSoupItemsQuery,
+} from '@queries/soup/items';
+import { EXCLUDE } from '@app/component/next-soup/filters/filters';
+import {
+ type Accessor,
+ createContext,
+ createDeferred,
+ createMemo,
+ type FlowComponent,
+ useContext,
+} from 'solid-js';
+import { throttle } from '@solid-primitives/scheduled';
+
+export const DEFAULT_SEARCH_SORT = 'updated_at';
+
+const CHANNEL_PRELOAD_ARGS: SoupItemsQueryArgs = {
+ params: { limit: 500, sort_method: DEFAULT_SEARCH_SORT },
+ body: {
+ chat_filters: { chat_ids: EXCLUDE },
+ document_filters: { document_ids: EXCLUDE },
+ email_filters: { recipients: EXCLUDE },
+ project_filters: { project_ids: EXCLUDE },
+ channel_filters: { channel_ids: [] },
+ },
+};
+
+const ITEM_PRELOAD_ARGS: SoupItemsQueryArgs = {
+ params: { limit: 500, sort_method: DEFAULT_SEARCH_SORT },
+ body: {
+ chat_filters: { chat_ids: [] },
+ document_filters: { document_ids: [] },
+ email_filters: { recipients: EXCLUDE },
+ project_filters: { project_ids: [] },
+ channel_filters: { channel_ids: EXCLUDE },
+ },
+};
+
+interface SearchContextValue {
+ entityPool: Accessor<EntityData[]>;
+}
+
+const SearchContext = createContext<SearchContextValue>();
+
+export const useSearchContext = () => {
+ const context = useContext(SearchContext);
+ if (!context) {
+ throw new Error('useSearchContext can only be used under a SearchProvider');
+ }
+ return context;
+};
+
+export const SearchProvider: FlowComponent = (props) => {
+ const itemsQuery = useSoupItemsQuery(() => ITEM_PRELOAD_ARGS);
+ const itemsFetchNextPage = throttle(() => itemsQuery.fetchNextPage(), 2000);
+ createDeferred(() => {
+ if (itemsQuery.hasNextPage && !itemsQuery.isFetchingNextPage) {
+ itemsFetchNextPage();
+ }
+ });
+
+ const channelItemsQuery = useSoupItemsQuery(() => CHANNEL_PRELOAD_ARGS);
+ const channelItemsFetchNextPage = throttle(
+ () => channelItemsQuery.fetchNextPage(),
+ 2000
+ );
+ createDeferred(() => {
+ if (
+ channelItemsQuery.hasNextPage &&
+ !channelItemsQuery.isFetchingNextPage
+ ) {
+ channelItemsFetchNextPage();
+ }
+ });
+
+ const itemsQueryData = throttledDependent(() => itemsQuery.data ?? [], 5000);
+ const channelItemsQueryData = throttledDependent(
+ () => channelItemsQuery.data ?? [],
+ 5000
+ );
+
+ const entityPool = createMemo<EntityData[]>(() => [
+ ...itemsQueryData(),
+ ...channelItemsQueryData(),
+ ]);
+
+ return (
+ <SearchContext.Provider value={{ entityPool }}>
+ {props.children}
+ </SearchContext.Provider>
+ );
+};
diff --git a/js/app/packages/app/component/next-soup/search-utils.test.ts b/js/app/packages/app/component/next-soup/search-utils.test.ts
new file mode 100644
index 0000000000..7ffd194f42
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/search-utils.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it } from 'vitest';
+import type { EntityData } from '@entity';
+import { intersectEntityPools } from './search-utils';
+
+const makeEntity = (id: string, name = id): EntityData =>
+ ({
+ type: 'document',
+ id,
+ name,
+ ownerId: 'test',
+ fileType: 'md',
+ }) as EntityData;
+
+describe('intersectEntityPools', () => {
+ it('returns empty array for no pools', () => {
+ expect(intersectEntityPools([])).toEqual([]);
+ });
+
+ it('returns the single pool as-is', () => {
+ const pool = [makeEntity('a'), makeEntity('b')];
+ expect(intersectEntityPools([pool])).toBe(pool);
+ });
+
+ it('returns entities present in all pools', () => {
+ const a = makeEntity('a');
+ const b = makeEntity('b');
+ const c = makeEntity('c');
+
+ const result = intersectEntityPools([
+ [a, b, c],
+ [b, c],
+ [c, b],
+ ]);
+
+ expect(result.map((e) => e.id)).toEqual(['b', 'c']);
+ });
+
+ it('returns empty when pools have no overlap', () => {
+ const result = intersectEntityPools([[makeEntity('a')], [makeEntity('b')]]);
+
+ expect(result).toEqual([]);
+ });
+
+ it('deduplicates within a pool', () => {
+ const a = makeEntity('a');
+
+ const result = intersectEntityPools([[a, a, a], [a]]);
+
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe('a');
+ });
+
+ it('keeps the first occurrence of a duplicated entity', () => {
+ const a1 = makeEntity('a', 'first');
+ const a2 = makeEntity('a', 'second');
+
+ const result = intersectEntityPools([[a1], [a2]]);
+
+ expect(result).toHaveLength(1);
+ expect(result[0].name).toBe('first');
+ });
+});
diff --git a/js/app/packages/app/component/next-soup/search-utils.ts b/js/app/packages/app/component/next-soup/search-utils.ts
new file mode 100644
index 0000000000..6e1ee8f6a3
--- /dev/null
+++ b/js/app/packages/app/component/next-soup/search-utils.ts
@@ -0,0 +1,91 @@
+import { fuzzyMatch } from '@core/util/fuzzy';
+import { mergeAdjacentMacroEmTags } from '@core/util/searchHighlight';
+import { createFreshSearch } from '@core/util/freshSort';
+import type { EntityData, WithSearch } from '@entity';
+import type { FilterConfig } from './filters/create-filter-state';
+
+/** Takes a list of entity pools and returns a list of unique entities that are present in all pools, deduplicating by id */
+export function intersectEntityPools(
+ pools: readonly EntityData[][]
+): EntityData[] {
+ if (pools.length === 0) return [];
+ if (pools.length === 1) return pools[0];
+
+ const idCounts = new Map<string, number>();
+ const entityById = new Map<string, EntityData>();
+
+ for (const pool of pools) {
+ const seen = new Set<string>();
+ for (const entity of pool) {
+ if (!seen.has(entity.id)) {
+ seen.add(entity.id);
+ idCounts.set(entity.id, (idCounts.get(entity.id) ?? 0) + 1);
+ if (!entityById.has(entity.id)) {
+ entityById.set(entity.id, entity);
+ }
+ }
+ }
+ }
+
+ const result: EntityData[] = [];
+ for (const [id, count] of idCounts) {
+ if (count === pools.length) {
+ result.push(entityById.get(id)!);
+ }
+ }
+
+ return result;
+}
+
+export const getValidSearchFilters = <T>(
+ filters: readonly FilterConfig<T>[]
+) => {
+ return filters.filter((f) => f.id !== 'explicit-noise');
+};
+
+/** Adds name highlight to item list based on fuzzy match */
+export const nameFuzzySearchFilter = (
+ items: EntityData[],
+ query: string
+): EntityData[] | WithSearch<EntityData>[] => {
+ if (!query || query.length === 0) return items;
+
+ const matchResults = fuzzyMatch(query, items, (item) => item.name, {
+ noSort: true,
+ });
+
+ const resultMap = new Map(
+ matchResults.map((r) => [
+ r.item.id,
+ { nameHighlight: r.nameHighlight, score: r.score },
+ ])
+ );
+ return items
+ .filter((item) => resultMap.has(item.id))
+ .map((item) => {
+ const matchResult = resultMap.get(item.id)!;
+ return {
+ ...item,
+ search: {
+ nameHighlight: mergeAdjacentMacroEmTags(matchResult.nameHighlight),
+ contentHitData: null,
+ source: 'local',
+ },
+ } as WithSearch<EntityData>;
+ });
+};
+
+export const createSoupFreshSearch = () =>
+ createFreshSearch<EntityData>(
+ {
+ useViewedAt: true,
+ channelBoost: 3,
+ fuzzyWeight: 0.7,
+ timeWeight: 0.3,
+ minFuzzyThreshold: 0.1,
+ commaSeparatedChannelMatch: true,
+ },
+ (item) => item.name,
+ (item) => item.type === 'channel',
+ (item) => item
+ );
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 fa2d0b64e2..56f67b1e29 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
@@ -3,61 +3,30 @@ import {
type FilterID,
getFileAssociations,
} from '@app/component/next-soup/filters/filters';
+import { useSearchContext } from '@app/component/next-soup/search-context';
+import {
+ createSoupFreshSearch,
+ getValidSearchFilters,
+ intersectEntityPools,
+ nameFuzzySearchFilter,
+} from '@app/component/next-soup/search-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 { createFreshSearch } from '@core/util/freshSort';
-import type { EntityData, WithSearch } from '@entity';
-import { isChannelEntity } from '@entity';
-import {
- type SoupItemsQueryFilters,
- type SoupItemsQueryArgs,
- useSoupItemsQuery,
-} from '@queries/soup/items';
+import type { EntityData } from '@entity';
+import type { SoupItemsQueryFilters } 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,
- on,
-} from 'solid-js';
+import { type Accessor, createMemo, createSignal, on } from 'solid-js';
import { match } from 'ts-pattern';
const SEARCH_SERVICE_DEBOUNCE_MS = 300;
const LOCAL_FUZZY_SEARCH_DEBOUNCE_MS = 20;
const FEATURED_COUNT = 3;
-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];
-}
+const freshSearch = createSoupFreshSearch();
interface CreateSearchStateArgs {
soup: SoupState;
@@ -84,6 +53,10 @@ export const createSearchState = ({
const isSearching = createMemo(() => trimmedSearchText().length > 0);
+ const isSearchServiceDebounceSettled = createMemo(
+ () => trimmedSearchText() === debouncedSearchForService()
+ );
+
const unifiedSearchIncludeArray = createMemo<UnifiedSearchIndex[]>(
() => {
const types = soup.filters.activeIds() as FilterID[];
@@ -113,7 +86,7 @@ export const createSearchState = ({
const validSearchTerms = createMemo(
() => debouncedSearchForService().length >= 3
);
- const isSearchDisabled = createMemo(() => !validSearchTerms());
+ const isSearchServiceDisabled = createMemo(() => !validSearchTerms());
const searchFilters = createMemo(() => {
const {
@@ -167,27 +140,6 @@ export const createSearchState = ({
}
);
- const emailExcludedQueryFilters = createMemo((): SoupItemsQueryFilters => {
- return {
- ...queryFilters(),
- email_filters: {
- recipients: [NIL_UUID],
- },
- };
- });
- const itemsQuery = useSoupItemsQuery(
- () => ({
- params: {
- limit: 50,
- sort_method: soup.sort.active()[0]?.id ?? 'updated_at',
- },
- body: { ...emailExcludedQueryFilters() },
- }),
- () => ({
- enabled: isSearchDisabled(),
- })
- );
-
const searchQuery = useSearchSoupQuery(
() => ({
params: {
@@ -198,98 +150,71 @@ export const createSearchState = ({
},
}),
() => ({
- enabled:
- !isSearchDisabled() &&
- trimmedSearchText() === debouncedSearchForService(),
+ enabled: !isSearchServiceDisabled() && isSearchServiceDebounceSettled(),
})
);
- const channelItemsQuery = useSoupItemsQuery(() => CHANNEL_PRELOAD_ARGS);
- createRenderEffect(() => {
- if (
- channelItemsQuery.hasNextPage &&
- !channelItemsQuery.isFetchingNextPage
- ) {
- channelItemsQuery.fetchNextPage();
+ const { entityPool } = useSearchContext();
+
+ const localFuzzyResults = createMemo(
+ on(debouncedSearchForLocal, (query) => {
+ if (!query || query.length === 0) return [];
+ const pool = entityPool();
+ // TODO: we can optimize fresh search for small feature counts since we
+ // don't need to sort everything, we just need the featured results
+ const freshSearchResults = freshSearch(pool, query);
+ // NOTE: this is a temporary hack because the fresh search fuzzy library
+ // does not give us the highlighted matches
+ const results = nameFuzzySearchFilter(
+ freshSearchResults.map((r) => r.item),
+ query
+ );
+ return results;
+ })
+ );
+
+ const allFiltersResults = createMemo((): Map<string, EntityData[]> => {
+ if (!localFuzzyResults()) return new Map();
+ const allFilters = getValidSearchFilters(soup.filters.available);
+ const filterToResultMap = new Map<string, EntityData[]>();
+ for (const filter of allFilters) {
+ filterToResultMap.set(
+ filter.id,
+ localFuzzyResults().filter((e) => filter.predicate(e))
+ );
}
+ return filterToResultMap;
});
- 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 filteredLocalFuzzyResults = createMemo(() => {
+ if (!localFuzzyResults()) return [];
+ const activeFilters = getValidSearchFilters(soup.filters.active());
+ if (activeFilters.length === 0)
+ return localFuzzyResults().slice(0, FEATURED_COUNT);
+ const pools = activeFilters.map((f) => allFiltersResults().get(f.id) ?? []);
+ const merged = intersectEntityPools(pools);
+ return merged.slice(0, FEATURED_COUNT);
});
- const freshSearchResults = createMemo<EntityData[]>(() => {
- if (isSearchDisabled()) return [];
- if (trimmedSearchText() !== debouncedSearchForService()) return [];
+ const serviceSearchResults = createMemo<EntityData[]>(() => {
+ if (isSearchServiceDisabled()) return [];
+ if (!isSearchServiceDebounceSettled()) return [];
if (searchQuery.isFetching && !searchQuery.isFetchingNextPage) return [];
return searchQuery.data ?? [];
});
- const freshSearch = createFreshSearch<EntityData>(
- {
- useViewedAt: true,
- channelBoost: 3,
- fuzzyWeight: 0.7,
- timeWeight: 0.3,
- minFuzzyThreshold: 0.1,
- commaSeparatedChannelMatch: true,
- },
- (item) => item.name,
- (item) => isChannelEntity(item),
- (item) => item
- );
-
- const createFeaturedIds = (pool: Accessor<EntityData[]>) => {
- const [frozen, setFrozen] = createSignal<string[]>([]);
- createRenderEffect(
- on(
- () =>
- [isSearching(), debouncedSearchForLocal(), queryFilters()] as const,
- ([searching, query]) => {
- if (!searching || !query) {
- setFrozen([]);
- return;
- }
- const results = freshSearch(pool(), query);
- setFrozen(results.slice(0, FEATURED_COUNT).map((r) => r.item.id));
- }
- )
- );
- return frozen;
- };
+ const featuredIds = createMemo(() => {
+ const ids = filteredLocalFuzzyResults().map((r) => r.id);
+ return ids;
+ });
return {
searchText,
setSearchText,
isSearching,
- isSearchDisabled,
- debouncedSearchForLocal,
- localFuzzyResults,
- freshSearchResults,
- createFeaturedIds,
- itemsQuery,
+ localFuzzyResults: filteredLocalFuzzyResults,
+ serviceSearchResults,
+ featuredIds,
searchQuery,
};
};
diff --git a/js/app/packages/app/component/next-soup/soup-view/sort-options.ts b/js/app/packages/app/component/next-soup/soup-view/sort-options.ts
index c0b428f5e2..0f78a9913a 100644
--- a/js/app/packages/app/component/next-soup/soup-view/sort-options.ts
+++ b/js/app/packages/app/component/next-soup/soup-view/sort-options.ts
@@ -1,11 +1,6 @@
import type { SortConfig } from '@app/component/next-soup/create-soup-state';
import type { SoupEntity } from '@app/component/next-soup/soup-view/soup-view-context';
-import {
- isSearchEntity,
- type WithSearch,
- type EntityData,
- type WithNotification,
-} from '@entity';
+import type { EntityData, WithNotification } from '@entity';
import { compareDateDesc } from '@core/util/date';
export type SystemSortOption =
@@ -66,29 +61,3 @@ export const SORT_CONFIGS = {
fn: sortByFrecencyScore,
},
} satisfies Record<string, SortConfig<SoupEntity>>;
-
-export const sortEntitiesForSearch = <T extends EntityData>(
- a: T,
- b: T
-): number => {
- if (!isSearchEntity(a) || !isSearchEntity(b)) {
- if (isSearchEntity(a)) return -1;
- if (isSearchEntity(b)) return 1;
- return 0;
- }
-
- const channelsWithNameMatchesFirst = (a: WithSearch<T>, b: WithSearch<T>) => {
- if (a.type === 'channel' && b.type !== 'channel' && a.search.nameHighlight)
- return -1;
- if (a.type !== 'channel' && b.type === 'channel' && b.search.nameHighlight)
- return 1;
- return 0;
- };
-
- // NOTE: backend returns items in descending order of updatedAt so we match that here
- const updatedAtDesc = (a: WithSearch<T>, b: WithSearch<T>) =>
- compareDateDesc(a.updatedAt, b.updatedAt);
-
- // TODO: we may want to sort exact name matches first for other items too
- return channelsWithNameMatchesFirst(a, b) || updatedAtDesc(a, b);
-};
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 1c56068d76..07ded595d0 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
@@ -4,7 +4,6 @@ import {
type SoupState,
} from '@app/component/next-soup/create-soup-state';
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 {
isTaskEntity,
@@ -16,7 +15,12 @@ import {
} from '@entity';
import { ENABLE_FEATURED_SEARCH_RESULTS } from '@core/constant/featureFlags';
import { useNotificationsForEntity } from '@notifications';
-import type { SoupItemsQueryFilters } from '@queries/soup/items';
+import {
+ type SoupParams,
+ useSoupItemsQuery,
+ type SoupItemsQueryFilters,
+ type SoupBody,
+} from '@queries/soup/items';
import {
type Accessor,
createContext,
@@ -61,8 +65,7 @@ interface SoupViewContextValues {
source: DataSource<EntityData>;
searchText: Accessor<string>;
setSearchText: (value: string) => void;
- isSearchDisabled: Accessor<boolean>;
- featuredCount: Accessor<number>;
+ featuredIds: Accessor<string[]>;
rows: Accessor<SoupRow[]>;
queryFilters: Accessor<SoupItemsQueryFilters>;
setQueryFilters: Setter<SoupItemsQueryFilters>;
@@ -98,6 +101,13 @@ export const SoupViewContextProvider: FlowComponent<
> = (props) => {
const soup = props.soup ?? createSoupState();
+ const soupParams = createMemo(
+ (): SoupParams => ({
+ limit: 100,
+ sort_method: soup.sort.active()[0]?.id ?? 'updated_at',
+ })
+ );
+
const [internalQueryFilters, setQueryFilters] =
createSignal<SoupItemsQueryFilters>({});
@@ -114,7 +124,7 @@ export const SoupViewContextProvider: FlowComponent<
}
});
- const queryFilters = createMemo(() => {
+ const queryFilters = createMemo((): SoupItemsQueryFilters => {
const base = internalQueryFilters();
return {
@@ -143,6 +153,13 @@ export const SoupViewContextProvider: FlowComponent<
};
});
+ const soupBody = createMemo(
+ (): SoupBody => ({
+ ...queryFilters(),
+ emailView: 'all',
+ })
+ );
+
const search = createSearchState({ soup, queryFilters });
const notificationSource = useGlobalNotificationSource();
@@ -180,12 +197,22 @@ export const SoupViewContextProvider: FlowComponent<
};
};
+ const itemsQuery = useSoupItemsQuery(
+ () => ({
+ params: soupParams(),
+ body: soupBody(),
+ }),
+ () => ({
+ enabled: !search.isSearching(),
+ })
+ );
+
const items = createMemo<SoupEntity[]>(
(prev) => {
const searching = search.isSearching();
if (!searching) {
- const data = search.itemsQuery.data;
+ const data = itemsQuery.data;
if (!data) return prev;
return data.map((e) =>
isWithNotification(e) ? e : attachNotifications(e)
@@ -193,7 +220,7 @@ export const SoupViewContextProvider: FlowComponent<
}
const local = search.localFuzzyResults();
- const service = search.freshSearchResults();
+ const service = search.serviceSearchResults();
const merged: SoupEntity[] = [...service, ...local];
@@ -246,12 +273,7 @@ export const SoupViewContextProvider: FlowComponent<
transformed = deduplicateEntities(next);
- if (search.isSearching()) {
- transformed.sort(sortEntitiesForSearch);
- }
-
const sorts = soup.sort.active();
-
if (sorts.length > 0) {
transformed.sort((a, b) => {
for (const sort of sorts) {
@@ -265,13 +287,11 @@ export const SoupViewContextProvider: FlowComponent<
return transformed;
};
- const frozenFeaturedIds = search.createFeaturedIds(baseEntities);
-
const entities = () => {
const base = baseEntities();
if (!ENABLE_FEATURED_SEARCH_RESULTS || !search.isSearching()) return base;
- const featuredIds = frozenFeaturedIds();
+ const featuredIds = search.featuredIds();
if (featuredIds.length === 0) return base;
const entityMap = new Map(base.map((e) => [e.id, e]));
@@ -285,23 +305,11 @@ export const SoupViewContextProvider: FlowComponent<
return [...featured, ...rest];
};
- const featuredCount = createMemo(() => {
- if (!ENABLE_FEATURED_SEARCH_RESULTS) return 0;
- if (!search.isSearching()) return 0;
- const featuredIdSet = new Set(frozenFeaturedIds());
- let count = 0;
- for (const e of entities()) {
- if (!featuredIdSet.has(e.id)) break;
- count++;
- }
- return count;
- });
-
const rows = createMemo(() => {
return entities().map((e) => attachMethods(e));
});
- const { itemsQuery, searchQuery } = search;
+ const { searchQuery } = search;
const context = {
soup,
@@ -309,33 +317,31 @@ export const SoupViewContextProvider: FlowComponent<
data: entities,
isLoading: () => {
if (itemsQuery.isLoading) return true;
- if (searchQuery.isLoading && !itemsQuery.data) return true;
+ if (searchQuery.isLoading) return true;
return false;
},
- isFetching: () => searchQuery.isFetching || itemsQuery.isFetching,
+ isFetching: () => itemsQuery.isFetching || searchQuery.isFetching,
isFetchingNextPage: () =>
- searchQuery.isFetchingNextPage || itemsQuery.isFetchingNextPage,
+ itemsQuery.isFetchingNextPage || searchQuery.isFetchingNextPage,
hasNextPage: () => {
return (
- (searchQuery.isEnabled && searchQuery.hasNextPage) ||
- (itemsQuery.isEnabled && itemsQuery.hasNextPage)
+ (itemsQuery.isEnabled && itemsQuery.hasNextPage) ||
+ (searchQuery.isEnabled && searchQuery.hasNextPage)
);
},
fetchNextPage: () => {
- if (searchQuery.isEnabled) {
- searchQuery.fetchNextPage();
- }
-
if (itemsQuery.isEnabled) {
itemsQuery.fetchNextPage();
}
+ if (searchQuery.isEnabled) {
+ searchQuery.fetchNextPage();
+ }
},
},
rows,
searchText: search.searchText,
setSearchText: search.setSearchText,
- isSearchDisabled: search.isSearchDisabled,
- featuredCount,
+ featuredIds: search.featuredIds,
queryFilters,
setQueryFilters,
statusFilter,
diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx
index 9cc4c6d26d..f382b50ef6 100644
--- a/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx
+++ b/js/app/packages/app/component/next-soup/soup-view/soup-view.tsx
@@ -177,7 +177,7 @@ export const SoupViewList = (props: SoupViewListProps) => {
setSearchText,
setQueryFilters,
queryFilters,
- featuredCount,
+ featuredIds,
} = useSoupView();
const { getSplitCount } = useSplitLayout();
@@ -215,8 +215,7 @@ export const SoupViewList = (props: SoupViewListProps) => {
createEffect(
on(
- () =>
- [soup.filters.activeIds(), searchText(), featuredCount()] as const,
+ () => [soup.filters.activeIds(), searchText(), featuredIds()] as const,
() => {
focusFirstEntity();
},
@@ -499,6 +498,8 @@ export const SoupViewList = (props: SoupViewListProps) => {
restoreState();
};
+ const featuredCount = createMemo(() => featuredIds().length);
+
return (
<div
class="size-full flex bracket-never"
@@ -567,9 +568,11 @@ export const SoupViewList = (props: SoupViewListProps) => {
}
};
- if (i() === Math.floor(rows().length * 0.8)) {
- debouncedFetchMore();
- }
+ createEffect(() => {
+ if (i() === Math.floor(rows().length * 0.8)) {
+ debouncedFetchMore();
+ }
+ });
return (
<>
diff --git a/js/app/packages/app/component/next-soup/utils.ts b/js/app/packages/app/component/next-soup/utils.ts
index f4bd7bdbdb..9905d8649e 100644
--- a/js/app/packages/app/component/next-soup/utils.ts
+++ b/js/app/packages/app/component/next-soup/utils.ts
@@ -49,6 +49,7 @@ const mergeSearchEntities = <T extends EntityData>(
}
return {
+ ...localEntity,
...serviceEntity,
search: {
...serviceEntity.search,
diff --git a/js/app/packages/core/util/fuzzy.ts b/js/app/packages/core/util/fuzzy.ts
index 5d617ce63e..eb4f32492d 100644
--- a/js/app/packages/core/util/fuzzy.ts
+++ b/js/app/packages/core/util/fuzzy.ts
@@ -73,7 +73,10 @@ export function highlightCommaSpaceSeparatedMatches(
export function fuzzyMatch<T>(
query: string,
items: T[],
- extract: (item: T) => string
+ extract: (item: T) => string,
+ options?: {
+ noSort?: boolean;
+ }
): FuzzyNameMatchResultWithItem<T>[] {
if (!query)
return items.map((item) => ({
@@ -143,8 +146,10 @@ export function fuzzyMatch<T>(
}
}
- // Sort by score (higher is better for both channels and non-channels)
- results.sort((a, b) => b.score - a.score);
+ if (!options?.noSort) {
+ // Sort by score (higher is better for both channels and non-channels)
+ results.sort((a, b) => b.score - a.score);
+ }
return results;
}
diff --git a/js/app/packages/queries/soup/items.ts b/js/app/packages/queries/soup/items.ts
index b416c8dfbc..afbb8ba01a 100644
--- a/js/app/packages/queries/soup/items.ts
+++ b/js/app/packages/queries/soup/items.ts
@@ -5,7 +5,7 @@ import { mapSoupPageToEntityList } from '@queries/soup/transform-utils';
import { useInstructionsMdIdQuery } from '@queries/storage/instructions-md';
import { storageServiceClient } from '@service-storage/client';
import type { EntityFilters } from '@service-storage/generated/schemas/entityFilters';
-import type { Params as SoupParams } from '@service-storage/generated/schemas/params';
+import type { Params } from '@service-storage/generated/schemas/params';
import type { PostSoupRequest } from '@service-storage/generated/schemas/postSoupRequest';
import {
useInfiniteQuery,
@@ -13,7 +13,9 @@ import {
} from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
-type SoupBody = Omit<PostSoupRequest, keyof SoupParams>;
+export type SoupParams = Params;
+
+export type SoupBody = Omit<PostSoupRequest, keyof SoupParams>;
export type SoupItemsQueryFilters = EntityFilters;
@@ -22,7 +24,7 @@ export type SoupItemsQueryArgs = {
body: SoupBody;
};
-export type UseSoupQueyResult = UseInfiniteQueryResult<EntityData[], Error>;
+export type UseSoupQueryResult = UseInfiniteQueryResult<EntityData[], Error>;
interface SoupItemsQueryOptions {
enabled: boolean;