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: visualize search results (#115)

gbirmanfdd19dea35e5
diff --git a/js/app/packages/app/component/UnifiedListView.tsx b/js/app/packages/app/component/UnifiedListView.tsx
index 81a91570b1..70630dea22 100644
--- a/js/app/packages/app/component/UnifiedListView.tsx
+++ b/js/app/packages/app/component/UnifiedListView.tsx
@@ -32,6 +32,7 @@ import { TOKENS } from '@core/hotkey/tokens';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { isMobileWidth } from '@core/mobile/mobileWidth';
import { useCombinedRecipients } from '@core/signal/useCombinedRecipient';
+import { fuzzyNameMatch } from '@core/util/fuzzyName';
import SearchIcon from '@icon/regular/magnifying-glass.svg?component-solid';
import LoadingSpinner from '@icon/regular/spinner.svg?component-solid';
import XIcon from '@icon/regular/x.svg?component-solid';
@@ -62,6 +63,7 @@ import {
sortByViewedAt,
unreadFilterFn,
type WithNotification,
+ type WithSearch,
} from '@macro-entity';
import {
markNotificationsForEntityAsDone,
@@ -86,7 +88,6 @@ import type {
} from '@service-search/generated/models';
import type { GetItemsSoupParams } from '@service-storage/generated/schemas';
import { debounce } from '@solid-primitives/scheduled';
-import fuzzy from 'fuzzy';
import stringify from 'json-stable-stringify';
import {
type Accessor,
@@ -448,10 +449,28 @@ export function UnifiedListView(props: UnifiedListViewProps) {
rawSearchText()
? (items: WithNotification<EntityData>[]) => {
if (!searchText() || searchText().length === 0) return items;
- const fuzzyResults = fuzzy.filter(searchText(), items, {
- extract: (item) => item.name,
- });
- return fuzzyResults.map((result) => result.original);
+
+ const query = searchText();
+
+ return items
+ .map((item) => {
+ const matchResult = fuzzyNameMatch(query, item.name);
+
+ if (!matchResult) return null;
+
+ return {
+ ...item,
+ search: {
+ nameHighlight: matchResult.nameHighlight,
+ contentHighlights: null,
+ source: 'local',
+ },
+ } as WithNotification<WithSearch<EntityData>>;
+ })
+ .filter(
+ (item): item is WithNotification<WithSearch<EntityData>> =>
+ item !== null
+ );
}
: undefined
);
@@ -686,26 +705,25 @@ export function UnifiedListView(props: UnifiedListViewProps) {
return false;
});
- const disableSearchService = createMemo(() => {
- // we only need to use search service when we have some sort of search text/filter
- const validSearch = validSearchTerms() || validSearchFilters();
- return !validSearch;
- });
-
const isSearchActive = createMemo(() => {
return validSearchTerms() || validSearchFilters();
});
+ const disableSearchService = createMemo(() => {
+ return !isSearchActive();
+ });
+
const emailActive = useEmailLinksStatus();
const disableEmailQuery = createMemo(() => {
// NOTE: at the moment emails are not supported in project blocks
// so it doesn't make sense to do an expensive email query
if (projectFilter()) return true;
+ if (isSearchActive()) return true;
if (!emailActive()) return true;
const typeFilter = entityTypeFilter();
if (typeFilter.length > 0 && !typeFilter.includes('email')) return true;
- return !disableSearchService();
+ return false;
});
const disableDssInfiniteQuery = createMemo(() => {
@@ -801,7 +819,9 @@ export function UnifiedListView(props: UnifiedListViewProps) {
});
const { UnifiedListComponent, entities, isLoading } =
- createUnifiedInfiniteList<WithNotification<EntityData>>({
+ createUnifiedInfiniteList<
+ WithNotification<WithSearch<EntityData> | EntityData>
+ >({
entityInfiniteQueries: [
{
query: dssInfiniteQuery,
@@ -900,10 +920,6 @@ export function UnifiedListView(props: UnifiedListViewProps) {
}
});
- const hasRefinementsFromBase = createMemo(() => {
- return isViewConfigChanged() || validSearchTerms() || validSearchFilters();
- });
-
const onClickSaveViewConfigChanges = () => {
const view_ = view();
const config = currentViewConfigBase();
@@ -1178,7 +1194,7 @@ export function UnifiedListView(props: UnifiedListViewProps) {
entityListRef={setLocalEntityListRef}
virtualizerHandle={setVirtualizerHandle}
emptyState={<EmptyState view={view()?.view} />}
- hasRefinementsFromBase={hasRefinementsFromBase}
+ hasRefinementsFromBase={isViewConfigChanged}
>
{(innerProps) => {
const displayDoneButton = () => {
diff --git a/js/app/packages/app/component/command/KonsoleItem.tsx b/js/app/packages/app/component/command/KonsoleItem.tsx
index 0bdab14e73..3f71f91317 100644
--- a/js/app/packages/app/component/command/KonsoleItem.tsx
+++ b/js/app/packages/app/component/command/KonsoleItem.tsx
@@ -573,9 +573,7 @@ export function CommandItemCard(props: CommandItemProps) {
<StaticMarkdown
markdown={
// TODO: This should be <m-search-match>
- snippet.content
- .replaceAll('macro_em', 'macro-em')
- .replaceAll('\n', ' ')
+ snippet.content.replaceAll('\n', ' ')
}
/>
</Message.Body>
diff --git a/js/app/packages/core/component/LexicalMarkdown/theme.ts b/js/app/packages/core/component/LexicalMarkdown/theme.ts
index 93984e87c9..c87cabb8f5 100644
--- a/js/app/packages/core/component/LexicalMarkdown/theme.ts
+++ b/js/app/packages/core/component/LexicalMarkdown/theme.ts
@@ -206,6 +206,14 @@ export const unifiedListMarkdownTheme = createTheme({
'code-container': 'font-mono md-code-box no-accessory overflow-hidden',
},
paragraph: `${theme.paragraph} inline`,
+ heading: {
+ h1: 'text-[1em] font-semibold',
+ h2: 'text-[1em] font-semibold',
+ h3: 'text-[1em] font-semibold',
+ h4: 'text-[1em] font-medium',
+ h5: 'text-[1em] font-medium',
+ h6: 'text-[1em] font-medium',
+ },
// padding right to prevent italics being clipped by overflow properties such as truncation
root: `${theme.root} inline pr-[2px] cursor-default`,
});
diff --git a/js/app/packages/core/util/fuzzyName.ts b/js/app/packages/core/util/fuzzyName.ts
new file mode 100644
index 0000000000..dbf4c771e0
--- /dev/null
+++ b/js/app/packages/core/util/fuzzyName.ts
@@ -0,0 +1,53 @@
+import fuzzy from 'fuzzy';
+
+export interface FuzzyNameMatchResult {
+ nameHighlight: string;
+ score: number;
+}
+
+/**
+ * Performs fuzzy name matching with quality filtering.
+ * Returns null if no match or if the match is too scattered.
+ */
+export function fuzzyNameMatch(
+ query: string,
+ name: string
+): FuzzyNameMatchResult | null {
+ const matchResult = fuzzy.match(query, name, {
+ pre: '<macro_em>',
+ post: '</macro_em>',
+ });
+
+ if (!matchResult) return null;
+
+ // Merge adjacent highlight tags
+ const mergedHighlight = matchResult.rendered.replace(
+ /<\/macro_em><macro_em>/g,
+ ''
+ );
+
+ const nameLower = name.toLowerCase();
+ const queryLower = query.toLowerCase();
+
+ // Always include exact matches, starts-with, or substring matches
+ const isGoodMatch =
+ nameLower === queryLower ||
+ nameLower.startsWith(queryLower) ||
+ nameLower.includes(queryLower);
+
+ if (!isGoodMatch) {
+ // Count how many separate highlight segments there are
+ const highlightSegments = (mergedHighlight.match(/<macro_em>/g) || [])
+ .length;
+
+ // Reject if more than 50% of characters are individual segments (too scattered)
+ if (highlightSegments > query.length * 0.5) {
+ return null;
+ }
+ }
+
+ return {
+ nameHighlight: mergedHighlight,
+ score: matchResult.score,
+ };
+}
diff --git a/js/app/packages/lexical-core/transformers/transformers.ts b/js/app/packages/lexical-core/transformers/transformers.ts
index 1e7d082f58..04f925d0ec 100644
--- a/js/app/packages/lexical-core/transformers/transformers.ts
+++ b/js/app/packages/lexical-core/transformers/transformers.ts
@@ -210,8 +210,8 @@ export const SEARCH_MATCH: TextMatchTransformer = {
export: (_: LexicalNode) => {
return null;
},
- importRegExp: xmlMatcher('macro-em'),
- regExp: xmlMatcher('macro-em'),
+ importRegExp: xmlMatcher('macro_em'),
+ regExp: xmlMatcher('macro_em'),
replace: (textNode, match) => {
try {
const searchMatchNode = $createSearchMatchNode([]);
diff --git a/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx b/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx
index 72b3125c09..47de120d90 100644
--- a/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx
+++ b/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx
@@ -25,6 +25,7 @@ import { createProfilePictureQuery } from '../queries/auth';
import { createProjectQuery } from '../queries/project';
import type { EntityData } from '../types/entity';
import type { Notification, WithNotification } from '../types/notification';
+import type { WithSearch } from '../types/search';
import type { EntityClickHandler } from './Entity';
function UnreadIndicator(props: { active?: boolean }) {
@@ -81,9 +82,9 @@ interface EntityProps<T extends WithNotification<EntityData>>
ref?: Ref<HTMLDivElement>;
}
-export function EntityWithEverything<
- T extends WithNotification<EntityData> = WithNotification<EntityData>,
->(props: EntityProps<T>) {
+export function EntityWithEverything(
+ props: EntityProps<WithNotification<EntityData | WithSearch<EntityData>>>
+) {
const [showActionList, setShowActionList] = createSignal(false);
const [actionButtonRef, setActionButtonRef] =
createSignal<HTMLButtonElement | null>(null);
@@ -146,6 +147,14 @@ export function EntityWithEverything<
return notifications.filter(({ done }) => !done);
};
+ const searchHighlightName = () =>
+ 'search' in props.entity && props.entity.search.nameHighlight;
+
+ const contentHighlights = () => {
+ if (!('search' in props.entity)) return [];
+ return props.entity.search.contentHighlights ?? [];
+ };
+
const EntityTitle = () => {
if (props.entity.type === 'email') {
return (
@@ -168,7 +177,17 @@ export function EntityWithEverything<
{/* Subject */}
<ImportantBadge active={props.importantIndicatorActive} />
<div class="flex items-center w-full gap-4 flex-1 min-w-0">
- <div class="font-medium shrink-0 truncate">{props.entity.name}</div>
+ <div class="font-medium shrink-0 truncate">
+ <Show when={searchHighlightName()} fallback={props.entity.name}>
+ {(name) => (
+ <StaticMarkdown
+ markdown={name()}
+ theme={unifiedListMarkdownTheme}
+ singleLine={true}
+ />
+ )}
+ </Show>
+ </div>
{/* Body */}
<div class="truncate shrink grow opacity-60">
{props.entity.snippet}
@@ -210,7 +229,15 @@ export function EntityWithEverything<
'w-[20cqw]': hasNotifications() && !props.showUnrollNotifications,
}}
>
- {props.entity.name}
+ <Show when={searchHighlightName()} fallback={props.entity.name}>
+ {(name) => (
+ <StaticMarkdown
+ markdown={name()}
+ theme={unifiedListMarkdownTheme}
+ singleLine={true}
+ />
+ )}
+ </Show>
</span>
<Show
@@ -388,6 +415,28 @@ export function EntityWithEverything<
</Show>
</div>
</div>
+ {/* Content Highlights from Search */}
+ <Show when={contentHighlights().length > 0}>
+ <div
+ class="relative row-2 grid gap-2"
+ classList={{
+ 'col-[2/-1]': props.showLeftColumnIndicator,
+ 'col-[1/-1]': !props.showLeftColumnIndicator,
+ }}
+ >
+ <For each={contentHighlights()}>
+ {(highlight) => (
+ <div class="text-sm text-ink-muted truncate">
+ <StaticMarkdown
+ markdown={highlight}
+ theme={unifiedListMarkdownTheme}
+ singleLine={true}
+ />
+ </div>
+ )}
+ </For>
+ </div>
+ </Show>
{/* Notifications */}
<Show when={props.showUnrollNotifications && hasNotifications()}>
<div
diff --git a/js/app/packages/macro-entity/src/components/UnifiedInfiniteList.tsx b/js/app/packages/macro-entity/src/components/UnifiedInfiniteList.tsx
index d9564f1508..ff45bb83ee 100644
--- a/js/app/packages/macro-entity/src/components/UnifiedInfiniteList.tsx
+++ b/js/app/packages/macro-entity/src/components/UnifiedInfiniteList.tsx
@@ -35,8 +35,207 @@ import {
type EntityRenderer,
getEntityProjectId,
} from '../types/entity';
+import type { WithSearch } from '../types/search';
import { Entity } from './Entity';
+const isSearchEntity = (entity: EntityData): entity is WithSearch<EntityData> =>
+ 'search' in entity;
+
+/**
+ * Merges search data from two entities, preferring service source with local as fallback.
+ * - Uses service entity as base
+ * - Falls back to local nameHighlight if service doesn't have one
+ * - Falls back to local contentHighlights if service doesn't have any
+ */
+const mergeSearchEntities = <T extends EntityData>(
+ first: T & WithSearch<EntityData>,
+ second: T & WithSearch<EntityData>
+): T => {
+ const serviceEntity = first.search.source === 'service' ? first : second;
+ const localEntity = first.search.source === 'local' ? first : second;
+
+ return {
+ ...serviceEntity,
+ search: {
+ ...serviceEntity.search,
+ nameHighlight:
+ serviceEntity.search.nameHighlight || localEntity.search.nameHighlight,
+ contentHighlights: serviceEntity.search.contentHighlights?.length
+ ? serviceEntity.search.contentHighlights
+ : localEntity.search.contentHighlights,
+ },
+ } as T;
+};
+
+/**
+ * Gets the timestamp of an entity (updatedAt or createdAt)
+ */
+const getEntityTimestamp = (entity: EntityData): number => {
+ return entity.updatedAt ?? entity.createdAt ?? 0;
+};
+
+/**
+ * Returns true if the new entity should replace the existing one based on timestamp
+ */
+const isNewerEntity = (
+ newEntity: EntityData,
+ existing: EntityData
+): boolean => {
+ return getEntityTimestamp(newEntity) > getEntityTimestamp(existing);
+};
+
+/**
+ * Deduplicates entities by id, preferring entities with search data from 'service' source
+ * over 'local' source, and using latest timestamp as a tiebreaker.
+ * When preferring service results, merges local nameHighlight if service doesn't have one.
+ */
+const deduplicateEntities = <T extends EntityData>(entities: T[]): T[] => {
+ const entityMap = new Map<string, T>();
+
+ for (const entity of entities) {
+ const existing = entityMap.get(entity.id);
+
+ if (!existing) {
+ entityMap.set(entity.id, entity);
+ continue;
+ }
+
+ const existingHasSearch = isSearchEntity(existing);
+ const newHasSearch = isSearchEntity(entity);
+
+ // Prefer entities with search data
+ if (newHasSearch && !existingHasSearch) {
+ entityMap.set(entity.id, entity);
+ continue;
+ }
+
+ // If both have search data, prefer 'service' over 'local'
+ if (existingHasSearch && newHasSearch) {
+ const existingSource = existing.search.source;
+ const newSource = entity.search.source;
+
+ if (
+ (newSource === 'service' && existingSource === 'local') ||
+ (existingSource === 'service' && newSource === 'local')
+ ) {
+ // Merge service and local search data
+ entityMap.set(entity.id, mergeSearchEntities(entity, existing));
+ continue;
+ }
+
+ // If both are the same source, keep the one with latest timestamp
+ if (isNewerEntity(entity, existing)) {
+ entityMap.set(entity.id, entity);
+ }
+ continue;
+ }
+
+ // If neither has search, keep the one with latest timestamp
+ if (!existingHasSearch && !newHasSearch) {
+ if (isNewerEntity(entity, existing)) {
+ entityMap.set(entity.id, entity);
+ }
+ }
+ // Otherwise keep existing (it has search and new doesn't)
+ }
+
+ return Array.from(entityMap.values());
+};
+
+/**
+ * Calculates match quality score for local search results.
+ * Higher score = better match.
+ * Prioritizes: exact match > starts with > word boundary > fuzzy match
+ */
+const getLocalMatchScore = (
+ entityName: string,
+ nameHighlight: string | null
+): number => {
+ if (!nameHighlight) return 0;
+
+ const name = entityName.toLowerCase();
+
+ // Extract the search query from the highlighted text
+ // The highlighted portion is wrapped in <macro_em>...</macro_em>
+ const highlightedText = nameHighlight
+ .replace(/<\/?macro_em>/g, '')
+ .toLowerCase();
+
+ // Count number of highlight segments (fewer segments = more contiguous match)
+ const highlightSegments = (nameHighlight.match(/<macro_em>/g) || []).length;
+
+ // Exact match (highest priority)
+ if (name === highlightedText) return 1000;
+
+ // Starts with match
+ if (name.startsWith(highlightedText)) return 900;
+
+ // Single contiguous match (not scattered)
+ if (highlightSegments === 1) {
+ // Word boundary match (after space, comma, etc.)
+ if (
+ name.match(
+ new RegExp(
+ `[\\s,+]${highlightedText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`
+ )
+ )
+ ) {
+ return 800;
+ }
+ return 700; // Contiguous substring
+ }
+
+ // Multiple segments (fuzzy/scattered match) - penalize based on number of segments
+ return Math.max(100, 500 - highlightSegments * 50);
+};
+
+/**
+ * Sorts entities for search mode:
+ * 1. Channels first
+ * 2. Local search results before service results
+ * 3. Within local results, better name matches come first
+ */
+const sortEntitiesForSearch = <T extends EntityData>(a: T, b: T): number => {
+ const aHasSearch = isSearchEntity(a);
+ const bHasSearch = isSearchEntity(b);
+
+ if (aHasSearch && bHasSearch) {
+ // Channel results come before other results
+ const aIsChannel = a.type === 'channel';
+ const bIsChannel = b.type === 'channel';
+
+ if (aIsChannel && !bIsChannel) return -1;
+ if (!aIsChannel && bIsChannel) return 1;
+
+ // Local results come before service results
+ const aSource = a.search.source;
+ const bSource = b.search.source;
+
+ if (aSource === 'local' && bSource === 'service') return -1;
+ if (aSource === 'service' && bSource === 'local') return 1;
+
+ // Within local results, sort by match quality
+ if (
+ aSource === 'local' &&
+ bSource === 'local' &&
+ aIsChannel &&
+ bIsChannel
+ ) {
+ const aScore = getLocalMatchScore(a.name, a.search.nameHighlight);
+ const bScore = getLocalMatchScore(b.name, b.search.nameHighlight);
+
+ if (aScore !== bScore) {
+ return bScore - aScore; // Higher score first
+ }
+
+ // If same score, prefer shorter names (more focused match)
+ return a.name.length - b.name.length;
+ }
+ }
+
+ return 0;
+};
+
const DEBOUNCE_FETCH_MORE_MS = 50;
// note that this must be greater than DEBOUNCE_FETCH_MORE_MS
@@ -64,8 +263,13 @@ const getOperations = <T extends Partial<EntityQueryOperations>>(
interface UnifiedInfiniteListContext<T extends EntityData> {
showProjects: Accessor<boolean>;
- entityInfiniteQueries: Array<EntityQueryWithOperations<EntityInfiniteQuery>>;
- entityQueries?: Array<EntityQueryWithOperations<EntityQuery>>;
+ entityInfiniteQueries: Array<
+ EntityQueryWithOperations<
+ EntityData | WithSearch<EntityData>,
+ EntityInfiniteQuery
+ >
+ >;
+ entityQueries?: Array<EntityQueryWithOperations<EntityData, EntityQuery>>;
entityMapper?: EntityMapper<T>;
requiredFilter?: Accessor<EntityFilter<T>>;
optionalFilter?: Accessor<EntityFilter<T>>;
@@ -172,27 +376,9 @@ export function createUnifiedInfiniteList<T extends EntityData>({
return entities;
});
- // deduplicate by id, taking latest timestamp
- const deduplicatedEntities = createMemo(() => {
- const entityMap = new Map<string, T>();
- for (const entity of filteredEntities()) {
- const id = entity.id;
- const existing = entityMap.get(id);
-
- if (existing) {
- const existingTimestamp = existing.updatedAt ?? existing.createdAt ?? 0;
- const newTimestamp = entity.updatedAt ?? entity.createdAt ?? 0;
-
- if (newTimestamp > existingTimestamp) {
- entityMap.set(id, entity);
- }
- } else {
- entityMap.set(id, entity);
- }
- }
-
- return Array.from(entityMap.values());
- });
+ const deduplicatedEntities = createMemo(() =>
+ deduplicateEntities(filteredEntities())
+ );
const projectFilterEntities = createMemo(() => {
const entities = deduplicatedEntities();
@@ -218,12 +404,15 @@ export function createUnifiedInfiniteList<T extends EntityData>({
});
const sortedEntities = createMemo<T[]>(() => {
- // TODO: process entities in a pipeline
const entities = projectFilterEntities();
const sortFn = entitySort?.();
const searching = isSearchActive?.();
- if (!sortFn || searching) return entities;
+ if (searching) {
+ return entities.toSorted(sortEntitiesForSearch);
+ }
+
+ if (!sortFn) return entities;
return entities.toSorted(sortFn);
});
diff --git a/js/app/packages/macro-entity/src/index.tsx b/js/app/packages/macro-entity/src/index.tsx
index 3ae1913506..dc35af6556 100644
--- a/js/app/packages/macro-entity/src/index.tsx
+++ b/js/app/packages/macro-entity/src/index.tsx
@@ -33,5 +33,6 @@ export * from './queries/search';
export { createEmailSource, type EmailSource, useEmails } from './source/email';
export * from './types/entity';
export * from './types/notification';
+export * from './types/search';
export * from './utils/filter';
export { composeFilters, createFilterComposer } from './utils/filter';
diff --git a/js/app/packages/macro-entity/src/queries/entity.ts b/js/app/packages/macro-entity/src/queries/entity.ts
index f4dc6bab7a..5082210e24 100644
--- a/js/app/packages/macro-entity/src/queries/entity.ts
+++ b/js/app/packages/macro-entity/src/queries/entity.ts
@@ -10,9 +10,10 @@ export type EntityQueryOperations = {
};
export type EntityQueryWithOperations<
- Q extends EntityQuery | EntityInfiniteQuery =
+ T extends EntityData,
+ Q extends EntityQuery | EntityInfiniteQuery<T> =
| EntityQuery
- | EntityInfiniteQuery,
+ | EntityInfiniteQuery<T>,
> = {
query: Q;
operations?: Partial<EntityQueryOperations>;
@@ -20,7 +21,8 @@ export type EntityQueryWithOperations<
export type EntityQuery = UseQueryResult<EntityData[]>;
-export type EntityInfiniteQuery = UseInfiniteQueryResult<EntityData[]>;
+export type EntityInfiniteQuery<T extends EntityData = EntityData> =
+ UseInfiniteQueryResult<T[]>;
export type EntityList<T extends EntityData = EntityData> = {
data: T[];
diff --git a/js/app/packages/macro-entity/src/queries/search.ts b/js/app/packages/macro-entity/src/queries/search.ts
index f8836c586b..510fe387c4 100644
--- a/js/app/packages/macro-entity/src/queries/search.ts
+++ b/js/app/packages/macro-entity/src/queries/search.ts
@@ -3,20 +3,49 @@ import { ENABLE_SEARCH_SERVICE } from '@core/constant/featureFlags';
import { isErr } from '@core/util/maybeResult';
import type { ChannelType } from '@service-comms/generated/models';
import { type PaginatedSearchArgs, searchClient } from '@service-search/client';
-import type { UnifiedSearchResponseItem } from '@service-search/generated/models';
+import type {
+ ChannelSearchResult,
+ ChatMessageSearchResult,
+ DocumentSearchResult,
+ EmailSearchResult,
+ ProjectSearchResult,
+ UnifiedSearchResponseItem,
+} from '@service-search/generated/models';
+import { useHistory } from '@service-storage/history';
import { useInfiniteQuery } from '@tanstack/solid-query';
import { type Accessor, createMemo } from 'solid-js';
import type { EntityData } from '../types/entity';
+import type { WithSearch } from '../types/search';
import type { EntityInfiniteQuery } from './entity';
import { queryKeys } from './key';
+type Entity = WithSearch<EntityData>;
+
+type InnerSearchResult =
+ | DocumentSearchResult
+ | EmailSearchResult
+ | ChatMessageSearchResult
+ | ChannelSearchResult
+ | ProjectSearchResult;
+
+const getHighlights = (innerResults: InnerSearchResult[]) => {
+ return {
+ nameHighlight: innerResults.at(0)?.highlight.name ?? null,
+ contentHighlights: innerResults.flatMap((r) => r.highlight.content ?? []),
+ source: 'service' as const,
+ };
+};
+
const useMapSearchResponseItem = () => {
const channelsContext = useChannelsContext();
const channels = () => channelsContext.channels();
- return (result: UnifiedSearchResponseItem): EntityData | undefined => {
+ const history = useHistory();
+
+ return (result: UnifiedSearchResponseItem): Entity | undefined => {
switch (result.type) {
- case 'document':
+ case 'document': {
+ const search = getHighlights(result.document_search_results);
return {
type: 'document',
id: result.document_id,
@@ -26,14 +55,17 @@ const useMapSearchResponseItem = () => {
updatedAt: result.updated_at,
fileType: result.file_type || undefined,
projectId: result.project_id ?? undefined,
+ search,
};
-
- case 'email':
+ }
+ case 'email': {
const emailResult = result.email_message_search_results.at(0);
+ // TODO: distinguish email message result from thread result
if (!emailResult) {
console.error('Email result not found', result);
return;
}
+ const search = getHighlights(result.email_message_search_results);
return {
type: 'email',
id: result.thread_id,
@@ -46,37 +78,48 @@ const useMapSearchResponseItem = () => {
isImportant: emailResult.labels.includes('IMPORTANT'),
done: !emailResult.labels.includes('INBOX'),
senderName: emailResult.sender,
+ search,
};
-
- case 'chat':
+ }
+ case 'chat': {
+ const search = getHighlights(result.chat_search_results);
+ let name = result.name;
+ if (!name || name === 'New Chat') {
+ const chat = history().find((item) => item.id === result.chat_id);
+ if (chat) {
+ name = chat.name;
+ }
+ }
return {
type: 'chat',
id: result.chat_id,
- name: result.name,
+ name,
ownerId: result.user_id,
createdAt: result.created_at,
updatedAt: result.updated_at,
projectId: result.project_id ?? undefined,
+ search,
};
-
- case 'channel':
- // sort in ascending order by created at and take the last result
- const channelResult = result.channel_message_search_results
- .toSorted((a, b) => a.created_at - b.created_at)
- .at(-1);
-
+ }
+ case 'channel': {
const channelWithLatest = channels().find(
(c) => c.id === result.channel_id
);
- // TODO: distinguish latest message from content match
- const contentMatch = channelResult
+
+ // TODO: serialize correctly from backend
+ const latestMessage = channelWithLatest?.latest_message
? {
- content: channelResult?.highlight.content?.at(0) ?? '',
- senderId: channelResult?.sender_id,
- createdAt: channelResult?.created_at,
+ content: channelWithLatest.latest_message.content,
+ senderId: channelWithLatest.latest_message.sender_id,
+ createdAt:
+ new Date(
+ channelWithLatest.latest_message.created_at
+ ).getTime() / 1000,
}
: undefined;
+ const search = getHighlights(result.channel_message_search_results);
+
return {
type: 'channel',
// TODO: distinguish channel name match from channel message match
@@ -87,10 +130,13 @@ const useMapSearchResponseItem = () => {
updatedAt: result.updated_at,
channelType: result.channel_type as ChannelType,
interactedAt: result.interacted_at ?? undefined,
- latestMessage: contentMatch,
+ latestMessage,
+ search,
};
+ }
- case 'project':
+ case 'project': {
+ const search = getHighlights(result.project_search_results);
return {
type: 'project',
id: result.id,
@@ -99,7 +145,9 @@ const useMapSearchResponseItem = () => {
createdAt: result.created_at,
updatedAt: result.updated_at,
parentId: result.parent_project_id ?? undefined,
+ search,
};
+ }
}
};
};
@@ -116,7 +164,7 @@ export function createUnifiedSearchInfiniteQuery(
options?: {
disabled?: Accessor<boolean>;
}
-): EntityInfiniteQuery {
+): EntityInfiniteQuery<Entity> {
const params = createMemo(() => args());
const pageParams = createMemo(() => params().params);
const request = createMemo(() => params().request);
@@ -175,7 +223,7 @@ export function createUnifiedSearchInfiniteQuery(
data.pages.flatMap((page) =>
page.results
.map(mapSearchResponseItem)
- .filter((entity): entity is EntityData => !!entity)
+ .filter((entity): entity is Entity => !!entity)
),
enabled: enabled(),
}));
diff --git a/js/app/packages/macro-entity/src/types/search.ts b/js/app/packages/macro-entity/src/types/search.ts
new file mode 100644
index 0000000000..d11ac06863
--- /dev/null
+++ b/js/app/packages/macro-entity/src/types/search.ts
@@ -0,0 +1,7 @@
+export type WithSearch<T extends object> = T & {
+ search: {
+ nameHighlight: string | null;
+ contentHighlights: string[] | null;
+ source: 'local' | 'service';
+ };
+};