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(channel): cmd+F find-bar for in-channel message search (#3100)

gbirmand49d4e57c0af
diff --git a/js/app/packages/app/component/PropertyFilter/FilterValueEntity.tsx b/js/app/packages/app/component/PropertyFilter/FilterValueEntity.tsx
index dd0bb811f2..6bcdc91d27 100644
--- a/js/app/packages/app/component/PropertyFilter/FilterValueEntity.tsx
+++ b/js/app/packages/app/component/PropertyFilter/FilterValueEntity.tsx
@@ -111,6 +111,7 @@ export const FilterValueEntity: Component<FilterValueEntityProps> = (props) => {
const emails = () => emailsQuery.data ?? [];
// Server-side email search
+ // TODO: fix this it doesn't work
const emailSearchQuery = useSearchSoupQuery(
() => ({
params: { page_size: 20 },
diff --git a/js/app/packages/block-pdf/component/Document.tsx b/js/app/packages/block-pdf/component/Document.tsx
index deec8282e8..9ad7a45242 100644
--- a/js/app/packages/block-pdf/component/Document.tsx
+++ b/js/app/packages/block-pdf/component/Document.tsx
@@ -652,7 +652,7 @@ export function Document() {
return (
<>
<Show when={!isNestedBlock}>
- <div class="absolute top-4 left-4 z-simple-search">
+ <div class="absolute top-4 right-4 z-simple-search">
<SimpleSearch />
</div>
</Show>
diff --git a/js/app/packages/block-pdf/component/SimpleSearch.tsx b/js/app/packages/block-pdf/component/SimpleSearch.tsx
index 9bb39d8ea9..3a57e82c25 100644
--- a/js/app/packages/block-pdf/component/SimpleSearch.tsx
+++ b/js/app/packages/block-pdf/component/SimpleSearch.tsx
@@ -1,19 +1,9 @@
import { searchLocationPendingSignal } from '@block-pdf/signal/location';
+import type { FindBarController } from '@core/component/createFindBarController';
+import { FindBar } from '@core/component/FindBar';
import { IS_MAC } from '@core/constant/isMac';
import { blockElementSignal } from '@core/signal/blockElement';
-import CaretDown from '@icon/regular/caret-down.svg';
-import CaretUp from '@icon/regular/caret-up.svg';
-import MagnifyingGlass from '@icon/regular/magnifying-glass.svg';
-import X from '@icon/regular/x.svg';
-import { Button, cn } from '@ui';
-import {
- createEffect,
- createSignal,
- type JSX,
- onCleanup,
- Show,
- untrack,
-} from 'solid-js';
+import { createEffect, createSignal, onCleanup, Show, untrack } from 'solid-js';
import {
isSearchOpenSignal,
searchSignal,
@@ -29,101 +19,97 @@ export function SimpleSearch() {
const jumpToResult = useJumpToResult();
const closeSearchBar = useSearchClose();
const locationPending = searchLocationPendingSignal.get;
- let inputRef: HTMLInputElement | undefined;
+ const [inputEl, setInputEl] = createSignal<HTMLInputElement>();
- const [isSearching, setIsSearching] = createSignal(false);
const [isOpen, setIsOpen] = isSearchOpenSignal;
const [searchText, setSearchText] = searchSignal;
+ const [isPending, setIsPending] = createSignal(false);
- // search on open
+ // Re-run the active search when the bar opens (or re-opens with prior text).
createEffect(() => {
if (untrack(locationPending)) return;
const text = untrack(searchText);
- if (isOpen()) searchStart({ query: text });
+ if (isOpen()) {
+ searchStart({ query: text });
+ if (text) setIsPending(true);
+ }
});
+ // Sync the input value when the search subsystem normalizes/echoes a query.
+ // Clear the pending flag once the results match the current query — guards
+ // against the controller emitting a stale matchesCount mid-transition.
createEffect(() => {
- const query = searchResults()?.query;
+ const r = searchResults();
if (untrack(locationPending)) return;
- if (query != null) {
- setSearchText(query);
- }
-
- if (searchResults()) {
- setIsSearching(false);
- }
+ if (r?.query != null) setSearchText(r.query);
+ if (r?.query === untrack(searchText)) setIsPending(false);
});
- const jumpTo = (dir: 'next' | 'prev') => {
- const result = searchResults();
- if (!result || result.count.total === 0) return;
+ const submittedQuery = () => searchResults()?.query ?? '';
+ const total = () => searchResults()?.count.total ?? 0;
+ const current = () => searchResults()?.count.current ?? 0;
- const {
- query,
- matches,
- count: { current, total },
- } = result;
+ const submit = () => {
+ const query = searchText();
+ searchStart({ query });
+ if (query) setIsPending(true);
+ };
- let index = 0;
- if (dir === 'next') {
- if (current === total) index = 0;
- else index = current;
- } else {
- if (current === 1) index = total - 1;
- else index = current - 2;
- }
- jumpToResult(matches[index]);
+ const next = () => {
+ const result = searchResults();
+ if (!result || result.count.total === 0) return;
+ const { matches, count } = result;
+ const idx = count.current === count.total ? 0 : count.current;
+ jumpToResult(matches[idx]);
+ };
- if (searchText() !== query) {
- setSearchText(query);
- }
+ const previous = () => {
+ const result = searchResults();
+ if (!result || result.count.total === 0) return;
+ const { matches, count } = result;
+ const idx = count.current === 1 ? count.total - 1 : count.current - 2;
+ jumpToResult(matches[idx]);
};
- const closeSearch = () => {
+ const close = () => {
closeSearchBar();
setIsOpen(false);
};
- const inputKeyDownHandler: JSX.EventHandler<
- HTMLInputElement,
- KeyboardEvent
- > = (e) => {
- const query = searchText();
- const result = searchResults();
- if (e.key === 'Enter') {
- if (result && result.query === query) {
- if (e.shiftKey) {
- jumpTo('prev');
- } else {
- jumpTo('next');
- }
- } else {
- searchStart({ query });
- if (!query) return;
- setIsSearching(true);
- }
- } else if (e.key === 'Escape') {
- closeSearch();
- }
+ // PDF.js owns the search state (queries, results, cursor). Expose it as a
+ // FindBarController so it can drive the shared <FindBar> UI.
+ const controller: FindBarController = {
+ isOpen,
+ query: searchText,
+ setQuery: setSearchText,
+ submittedQuery,
+ activeIndex: current,
+ hasUnsubmittedChanges: () => searchText() !== submittedQuery(),
+ isPending,
+ resultsCount: total,
+ open: () => setIsOpen(true),
+ close,
+ submit,
+ next,
+ previous,
+ setInputEl: (el) => setInputEl(el),
};
- const keyDownHandler = (e: KeyboardEvent) => {
- if ((IS_MAC ? e.metaKey : e.ctrlKey) && e.key === 'f') {
- e.stopPropagation();
- e.preventDefault();
-
- if (isOpen()) {
- if (inputRef === document.activeElement) {
- closeSearch();
- setIsOpen(false);
- } else {
- inputRef?.focus();
- inputRef?.select();
- }
+ const handleHotkey = (e: KeyboardEvent) => {
+ if (!((IS_MAC ? e.metaKey : e.ctrlKey) && e.key === 'f')) return;
+ e.stopPropagation();
+ e.preventDefault();
+ const input = inputEl();
+ if (isOpen()) {
+ if (input === document.activeElement) {
+ close();
} else {
- setIsOpen(true);
- inputRef?.focus();
+ input?.focus();
+ input?.select();
}
+ } else {
+ setIsOpen(true);
+ input?.focus();
}
};
@@ -131,60 +117,17 @@ export function SimpleSearch() {
createEffect(() => {
const element = blockElement();
if (!element) return;
-
- // the document event listener will act as a fallback to handle all splits for when the block element is not in focus
- element.addEventListener('keydown', keyDownHandler);
- document.addEventListener('keydown', keyDownHandler);
-
+ element.addEventListener('keydown', handleHotkey);
+ document.addEventListener('keydown', handleHotkey);
onCleanup(() => {
- element.removeEventListener('keydown', keyDownHandler);
- document.removeEventListener('keydown', keyDownHandler);
+ element.removeEventListener('keydown', handleHotkey);
+ document.removeEventListener('keydown', handleHotkey);
});
});
return (
<Show when={isOpen()}>
- <div class="flex items-center justify-start rounded-md border border-edge floating-hover p-1 focus-within:floating-input focus-within:border-accent">
- <div class="px-2">
- <MagnifyingGlass
- class={cn(
- 'size-4',
- isSearching() ? 'animate-pulse text-accent-ink' : 'text-ink'
- )}
- />
- </div>
- <input
- class="mx-0.5 flex-1 border-0 text-sm text-ink focus:outline-none focus:ring-0"
- type="text"
- ref={inputRef}
- value={searchText()}
- onInput={(e) => setSearchText(e.target.value)}
- onKeyDown={inputKeyDownHandler}
- />
- <div class="flex-0 ml-auto mr-3 text-right w-24">
- <Show when={!!searchText() && searchResults()}>
- {(result) => {
- const current = () => result().count.current;
- const total = () => result().count.total;
-
- return (
- <>
- {current()}/{total()}
- </>
- );
- }}
- </Show>
- </div>
- <Button variant="ghost" size="icon-md" onClick={() => jumpTo('prev')}>
- <CaretUp />
- </Button>
- <Button variant="ghost" size="icon-md" onClick={() => jumpTo('next')}>
- <CaretDown />
- </Button>
- <Button variant="ghost" size="icon-md" onClick={closeSearch}>
- <X />
- </Button>
- </div>
+ <FindBar controller={controller} />
</Show>
);
}
diff --git a/js/app/packages/channel/Channel/Channel.tsx b/js/app/packages/channel/Channel/Channel.tsx
index 00843f4197..48b10a8627 100644
--- a/js/app/packages/channel/Channel/Channel.tsx
+++ b/js/app/packages/channel/Channel/Channel.tsx
@@ -10,6 +10,7 @@ import {
} from '@channel/Input/utils/persistence';
import { MaybeMessageActionDrawerManager } from '@channel/Mobile/MessageActionDrawerManager';
import { useChannelParticipants } from '@channel/use-channel-participants';
+import { FindBar } from '@core/component/FindBar';
import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
import { toast } from '@core/component/Toast/Toast';
import { useChannelActivity, useChannelName } from '@core/context/channels';
@@ -64,6 +65,7 @@ import { hasSendableInputContent } from '../Input/utils/sendable-content';
import { ChannelThread } from '../Thread';
import { ChannelDropZone } from './ChannelDropZone';
import { createChannelDragState } from './create-channel-drag-state';
+import { createChannelFindBar } from './create-channel-find-bar';
import { createChannelHotkeys } from './create-channel-hotkeys';
import { createChannelMessageActions } from './create-channel-message-actions';
import { createInlineInputKeyboardHandler } from './create-inline-input-keyboard-handler';
@@ -298,6 +300,21 @@ export function Channel(props: ChannelProps) {
selection.clear();
};
+ const goToMessage: ChannelHandle['goToMessage'] = (messageId, replyId) => {
+ if (replyId) {
+ clearSelection();
+ } else {
+ selectMessage(messageId);
+ }
+ targetMessageController.goToMessage(messageId, replyId);
+ };
+
+ const findBar = createChannelFindBar({
+ channelId: () => props.channelId,
+ goToMessage,
+ clearSelection,
+ });
+
const { messageListScopeId, attachMessageListRef, attachInputRef } =
createChannelHotkeys({
selection,
@@ -308,6 +325,7 @@ export function Channel(props: ChannelProps) {
isEditing: () => !!messageEditor.state(),
isInputEmpty: () =>
(channelInputSnapshot()?.value.trim().length ?? 0) === 0,
+ onOpenFindBar: findBar.open,
});
const handleScrollToBottom = () => {
@@ -370,11 +388,6 @@ export function Channel(props: ChannelProps) {
);
};
- const goToMessage: ChannelHandle['goToMessage'] = (messageId, replyId) => {
- selectMessage(messageId);
- targetMessageController.goToMessage(messageId, replyId);
- };
-
createEffect(
on(isChannelReady, () => {
if (props.onHandleReady)
@@ -390,7 +403,7 @@ export function Channel(props: ChannelProps) {
<MaybeMessageActionDrawerManager>
<ChannelDropZone dragState={dragState}>
<div
- class="ph-no-capture relative flex-1 min-h-0 outline-none"
+ class="ph-no-capture relative flex-1 min-h-0 outline-none flex flex-col"
ref={(element) => {
setMessageListElement(element);
attachMessageListRef(element);
@@ -398,67 +411,79 @@ export function Channel(props: ChannelProps) {
tabIndex={-1}
data-channel-message-list
>
- <Show when={messages().length > 0}>
- <ThreadList
- keys={() => messageIndex.keys}
- initialScrollTarget={threadListInitialScrollTarget()}
- shift={shift}
- prepend={threadPaginator.isPrepending}
- onScrollNearTop={threadPaginator.shiftPaginate}
- onScrollNearBottom={threadPaginator.prependPaginate}
- onNavigationReady={setThreadListNavigation}
- onScrollStateChange={setThreadListScrollState}
- >
- {(item) => {
- const message = () => messageById().get(item.id);
- const state = threadManager.getOrCreateThreadState(item.id);
- const isNewestThread = () =>
- item.id === messageIndex.keys.at(-1);
-
- return (
- <Show when={message()}>
- {(m) => (
- <ChannelThread
- data={m}
- channelId={() => props.channelId}
- isNewestThread={isNewestThread()}
- getMessageActions={getMessageActions}
- targetReplyId={targetMessageController.pendingTargetReplyId()}
- onTargetReplyScrolled={(replyId) => {
- targetMessageController.completePendingReplyScroll(
- m().id,
- replyId
- );
- }}
- isExpanded={state.isExpanded}
- setIsExpanded={state.setIsExpanded}
- isReplying={state.isReplying}
- setIsReplying={state.setIsReplying}
- replyInputState={state.replyInputState}
- setReplyInputState={state.setReplyInputState}
- setReplyInputEl={state.setReplyInputEl}
- listMeta={listMetaByMessageId()[item.id]}
- messageEditor={messageEditor}
- threadActions={{
- onDismissNewMessages:
- activityTracker.dismissNewMessages,
- }}
- isNewMessage={activityTracker.isNewMessage}
- selectedMessageId={selection.selectedId}
- onSelectMessage={selectMessage}
- onClearSelection={clearSelection}
- messageListScopeId={messageListScopeId}
- />
- )}
- </Show>
- );
- }}
- </ThreadList>
- <ScrollToBottomOverlay
- scrollState={threadListScrollState}
- onScrollToBottom={handleScrollToBottom}
+ <Show when={findBar.isOpen()}>
+ <FindBar
+ class="absolute top-2 right-3 z-10 w-80 max-w-[calc(100%-1.5rem)]"
+ controller={findBar}
+ direction="desc"
/>
</Show>
+ <Show when={messages().length > 0}>
+ <div class="relative flex-1 min-h-0">
+ <ThreadList
+ keys={() => messageIndex.keys}
+ initialScrollTarget={threadListInitialScrollTarget()}
+ shift={shift}
+ prepend={threadPaginator.isPrepending}
+ onScrollNearTop={threadPaginator.shiftPaginate}
+ onScrollNearBottom={threadPaginator.prependPaginate}
+ onNavigationReady={setThreadListNavigation}
+ onScrollStateChange={setThreadListScrollState}
+ >
+ {(item) => {
+ const message = () => messageById().get(item.id);
+ const state = threadManager.getOrCreateThreadState(
+ item.id
+ );
+ const isNewestThread = () =>
+ item.id === messageIndex.keys.at(-1);
+
+ return (
+ <Show when={message()}>
+ {(m) => (
+ <ChannelThread
+ data={m}
+ channelId={() => props.channelId}
+ isNewestThread={isNewestThread()}
+ getMessageActions={getMessageActions}
+ targetReplyId={targetMessageController.pendingTargetReplyId()}
+ selectedReplyId={targetMessageController.activeTargetMessageReplyId()}
+ onTargetReplyScrolled={(replyId) => {
+ targetMessageController.completePendingReplyScroll(
+ m().id,
+ replyId
+ );
+ }}
+ isExpanded={state.isExpanded}
+ setIsExpanded={state.setIsExpanded}
+ isReplying={state.isReplying}
+ setIsReplying={state.setIsReplying}
+ replyInputState={state.replyInputState}
+ setReplyInputState={state.setReplyInputState}
+ setReplyInputEl={state.setReplyInputEl}
+ listMeta={listMetaByMessageId()[item.id]}
+ messageEditor={messageEditor}
+ threadActions={{
+ onDismissNewMessages:
+ activityTracker.dismissNewMessages,
+ }}
+ isNewMessage={activityTracker.isNewMessage}
+ selectedMessageId={selection.selectedId}
+ onSelectMessage={selectMessage}
+ onClearSelection={clearSelection}
+ messageListScopeId={messageListScopeId}
+ />
+ )}
+ </Show>
+ );
+ }}
+ </ThreadList>
+ <ScrollToBottomOverlay
+ scrollState={threadListScrollState}
+ onScrollToBottom={handleScrollToBottom}
+ />
+ </div>
+ </Show>
</div>
<DebugSuspense name="Channel.input">
<ChannelInputContainer
diff --git a/js/app/packages/channel/Channel/create-channel-find-bar.ts b/js/app/packages/channel/Channel/create-channel-find-bar.ts
new file mode 100644
index 0000000000..3af3fe2acb
--- /dev/null
+++ b/js/app/packages/channel/Channel/create-channel-find-bar.ts
@@ -0,0 +1,92 @@
+import {
+ createFindBarController,
+ type FindBarController,
+} from '@core/component/createFindBarController';
+import {
+ type ChannelMessageEntity,
+ isChannelMessageEntity,
+ type WithSearch,
+} from '@entity';
+import {
+ useSearchChannelQuery,
+ validateSearchServiceText,
+} from '@queries/soup/search';
+import { ChannelSortTimestamp } from '@service-search/generated/models';
+import { type Accessor, createEffect, createMemo } from 'solid-js';
+
+const FIND_BAR_PAGE_SIZE = 50;
+const FIND_BAR_PREFETCH_THRESHOLD = 10;
+
+type CreateChannelFindBarOptions = {
+ channelId: Accessor<string>;
+ goToMessage: (messageId: string, replyId?: string) => void;
+ clearSelection: () => void;
+};
+
+export type ChannelFindBar = FindBarController;
+
+export function createChannelFindBar(
+ options: CreateChannelFindBarOptions
+): ChannelFindBar {
+ return createFindBarController<WithSearch<ChannelMessageEntity>>(
+ ({ isOpen, submittedQuery, activeIndex }) => {
+ // Channel-only search with thread sort so results paginate monotonically
+ // through the channel's thread list (replies cluster with their parent
+ // thread instead of jumping around when sorted strictly by message_id).
+ const searchQuery = useSearchChannelQuery(
+ () => ({
+ params: { page_size: FIND_BAR_PAGE_SIZE },
+ body: {
+ match_type: 'partial',
+ query: submittedQuery(),
+ search_on: 'content',
+ channel_ids: [options.channelId()],
+ sort: ChannelSortTimestamp.thread,
+ },
+ }),
+ () => ({ enabled: isOpen() && submittedQuery().length > 0 })
+ );
+
+ const results = createMemo<WithSearch<ChannelMessageEntity>[]>(() => {
+ if (!submittedQuery()) return [];
+ if (searchQuery.isPlaceholderData) return [];
+ if (!searchQuery.isSuccess) return [];
+ const data = searchQuery.data;
+ if (!data) return [];
+ return data.filter(
+ (e): e is WithSearch<ChannelMessageEntity> =>
+ isChannelMessageEntity(e) && e.channelId === options.channelId()
+ );
+ });
+
+ // Prefetch the next page when the cursor approaches the end of the
+ // loaded results so navigating to the boundary doesn't stall on a
+ // network round-trip.
+ createEffect(() => {
+ const rs = results();
+ const idx = activeIndex();
+ if (idx === 0 || rs.length === 0) return;
+ if (!searchQuery.hasNextPage || searchQuery.isFetchingNextPage) return;
+ if (rs.length - idx <= FIND_BAR_PREFETCH_THRESHOLD) {
+ searchQuery.fetchNextPage();
+ }
+ });
+
+ return {
+ results,
+ isFetching: () => searchQuery.isFetching,
+ validateText: validateSearchServiceText,
+ navigate: (result) => {
+ if (result.threadId) {
+ options.goToMessage(result.threadId, result.messageId);
+ } else {
+ options.goToMessage(result.messageId);
+ }
+ },
+ };
+ },
+ {
+ onBeforeSubmit: () => options.clearSelection(),
+ }
+ );
+}
diff --git a/js/app/packages/channel/Channel/create-channel-hotkeys.ts b/js/app/packages/channel/Channel/create-channel-hotkeys.ts
index edac3c719e..a2d9789bce 100644
--- a/js/app/packages/channel/Channel/create-channel-hotkeys.ts
+++ b/js/app/packages/channel/Channel/create-channel-hotkeys.ts
@@ -14,6 +14,7 @@ type CreateChannelHotkeysOptions = {
userId: Accessor<string | undefined>;
isInputEmpty: Accessor<boolean>;
isEditing: Accessor<boolean>;
+ onOpenFindBar: () => void;
};
export function canReplyToSelectedMessageFromHotkey(input: {
@@ -188,6 +189,20 @@ export function createChannelHotkeys(options: CreateChannelHotkeysOptions) {
},
});
+ for (const scopeId of [messageListScope, inputScope]) {
+ registerHotkey({
+ scopeId,
+ hotkey: 'cmd+f',
+ hotkeyToken: TOKENS.channel.findInChannel,
+ description: 'Find in channel',
+ runWithInputFocused: true,
+ keyDownHandler: () => {
+ options.onOpenFindBar();
+ return true;
+ },
+ });
+ }
+
return {
messageListScopeId: messageListScope,
attachMessageListRef: (el: HTMLElement) => {
diff --git a/js/app/packages/channel/Channel/create-target-message-controller.ts b/js/app/packages/channel/Channel/create-target-message-controller.ts
index cf4866ba5a..aaf8575ca5 100644
--- a/js/app/packages/channel/Channel/create-target-message-controller.ts
+++ b/js/app/packages/channel/Channel/create-target-message-controller.ts
@@ -65,7 +65,11 @@ export function createTargetMessageController(
setTargetMessageData({
activeTargetMessageId: messageId,
activeTargetMessageReplyId: replyId,
- loadAroundMessageId: hasMessageLoaded(messageId) ? undefined : messageId,
+ // TODO: need a better approach where the load around should be undefined
+ // the current approach is a hack to fix rapid navigation race condition
+ loadAroundMessageId: hasMessageLoaded(messageId)
+ ? targetMessageData['loadAroundMessageId']
+ : messageId,
pendingScrollTargetId: messageId,
pendingTargetReplyId: replyId,
});
diff --git a/js/app/packages/channel/Channel/tests/create-target-message-controller.test.ts b/js/app/packages/channel/Channel/tests/create-target-message-controller.test.ts
index 27100b486b..3853db432f 100644
--- a/js/app/packages/channel/Channel/tests/create-target-message-controller.test.ts
+++ b/js/app/packages/channel/Channel/tests/create-target-message-controller.test.ts
@@ -76,7 +76,7 @@ describe('createTargetMessageController', () => {
expect(controller.activeTargetMessageId()).toBe('message-2');
expect(controller.pendingScrollTargetId()).toBe('message-2');
- expect(controller.loadAroundMessageId()).toBeUndefined();
+ expect(controller.loadAroundMessageId()).toBe('message-1');
dispose();
});
});
diff --git a/js/app/packages/channel/Thread/ChannelThread.tsx b/js/app/packages/channel/Thread/ChannelThread.tsx
index 5cc15d6616..9e864f3b63 100644
--- a/js/app/packages/channel/Thread/ChannelThread.tsx
+++ b/js/app/packages/channel/Thread/ChannelThread.tsx
@@ -5,7 +5,7 @@ import { deferredGate } from '@core/util/debounce';
import { MarkMessageNotifications } from '@notifications/components/MarkMessageNotifications';
import { useThreadRepliesQuery } from '@queries/channel/thread-replies';
import type { ApiThreadReply } from '@service-comms/client';
-import { createEffect, createSignal, on, Show } from 'solid-js';
+import { createEffect, createSignal, on, Show, untrack } from 'solid-js';
import { createMessageSelection } from '../Channel/create-message-selection';
import { ChannelMessage } from '../Message';
import { createThreadHotkeys } from './create-thread-hotkeys';
@@ -73,7 +73,19 @@ export function ChannelThread(props: ThreadProps) {
keys: () => activeReplies().map((r) => r.id),
});
- const isThreadFocused = () => isSelected() && !!replySelection.selectedId();
+ // Clears the local reply selection when the channel-level selection moves away
+ createEffect(
+ on(
+ () => props.selectedMessageId?.(),
+ (selectedId) => {
+ if (selectedId === props.data().id) return;
+ if (replySelection.selectedId()) replySelection.clear();
+ },
+ { defer: true }
+ )
+ );
+
+ const isThreadFocused = () => !!replySelection.selectedId();
const selectThreadMessage = () => {
if (isSelected() && !isThreadFocused()) {
props.onClearSelection?.();
@@ -142,50 +154,63 @@ export function ChannelThread(props: ThreadProps) {
const [replyListHandle, setReplyListHandle] =
createSignal<ThreadReplyListHandle>();
+ createEffect(
+ on(
+ [() => props.selectedReplyId, loadedReplies],
+ ([selectedReplyId, replies]) => {
+ if (!selectedReplyId) {
+ if (replySelection.selectedId()) replySelection.clear();
+ return;
+ }
+ const found = replies.some((r) => r.id === selectedReplyId);
+ if (!found) {
+ if (replySelection.selectedId()) replySelection.clear();
+ return;
+ }
+ props.onSelectMessage?.(props.data().id);
+ replySelection.select(selectedReplyId);
+ }
+ )
+ );
+
+ createEffect(
+ on(
+ [() => props.targetReplyId, displayReplies, props.isExpanded],
+ ([targetReplyId, rendered, isExpanded]) => {
+ if (!targetReplyId || isExpanded) return;
+ if (rendered.some((r) => r.id === targetReplyId)) return;
+ props.setIsExpanded(true);
+ }
+ )
+ );
+
+ // this stops re-scrolling to the same target
+ let lastScrolledReplyId: string | undefined;
createEffect(
on(
[
() => props.targetReplyId,
+ replyListHandle,
canScrollToTargetReply,
- loadedReplies,
- displayReplies,
props.isExpanded,
- replyListHandle,
],
- ([
- targetReplyId,
- canScroll,
- replies,
- renderedReplies,
- isExpanded,
- handle,
- ]) => {
- if (!targetReplyId) return;
- if (!canScroll) return;
-
- const targetReplyIndex = replies.findIndex(
- (reply) => reply.id === targetReplyId
- );
- if (targetReplyIndex === -1) return;
-
- props.onSelectMessage?.(props.data().id);
- replySelection.select(targetReplyId);
-
- if (!isExpanded) {
- const renderedTargetReplyIndex = renderedReplies.findIndex(
- (reply) => reply.id === targetReplyId
- );
- if (renderedTargetReplyIndex === -1) {
- props.setIsExpanded(true);
- return;
- }
-
- if (!handle?.scrollToIndex(renderedTargetReplyIndex)) return;
- props.onTargetReplyScrolled?.(targetReplyId);
+ ([targetReplyId, handle, canScroll, isExpanded]) => {
+ if (!targetReplyId) {
+ lastScrolledReplyId = undefined;
return;
}
+ if (lastScrolledReplyId === targetReplyId) return;
+ if (!canScroll || !handle) return;
+
+ // Untracked: channel-message reconciles must not re-fire scroll.
+ const replies = isExpanded
+ ? untrack(loadedReplies)
+ : untrack(displayReplies);
+ const index = replies.findIndex((r) => r.id === targetReplyId);
+ if (index === -1) return;
- if (!handle?.scrollToIndex(targetReplyIndex)) return;
+ if (!handle.scrollToIndex(index)) return;
+ lastScrolledReplyId = targetReplyId;
props.onTargetReplyScrolled?.(targetReplyId);
}
)
diff --git a/js/app/packages/channel/Thread/ThreadReplyList.tsx b/js/app/packages/channel/Thread/ThreadReplyList.tsx
index a1602c2358..e0b1ae61f4 100644
--- a/js/app/packages/channel/Thread/ThreadReplyList.tsx
+++ b/js/app/packages/channel/Thread/ThreadReplyList.tsx
@@ -43,7 +43,8 @@ export function ThreadReplyList(props: {
const scrollToIndex = (index: number): boolean => {
const element = getReplyElementAtIndex(replyElements, index);
if (!element) return false;
- element.scrollIntoView({ block: 'center' });
+ // NOTE: this rAF helps prevent situations where the deeply nested thread element is unmounted
+ requestAnimationFrame(() => element.scrollIntoView({ block: 'center' }));
return true;
};
diff --git a/js/app/packages/channel/Thread/types.ts b/js/app/packages/channel/Thread/types.ts
index 4483515aad..3cad6c9427 100644
--- a/js/app/packages/channel/Thread/types.ts
+++ b/js/app/packages/channel/Thread/types.ts
@@ -36,8 +36,11 @@ export type ThreadProps = {
listMeta?: ChannelMessageListMeta;
threadActions?: ThreadActions;
messageEditor?: MessageEditor;
+ /** One-shot scroll target. Caller must clear via `onTargetReplyScrolled`. */
targetReplyId?: string;
onTargetReplyScrolled?: (replyId: string) => void;
+ /** Persistent highlight target. */
+ selectedReplyId?: string;
isNewMessage?: (reply: NewMessageCheckable) => boolean;
selectedMessageId?: Accessor<string | undefined>;
onSelectMessage?: (messageId: string) => void;
diff --git a/js/app/packages/core/component/FindBar.tsx b/js/app/packages/core/component/FindBar.tsx
new file mode 100644
index 0000000000..125a2f6203
--- /dev/null
+++ b/js/app/packages/core/component/FindBar.tsx
@@ -0,0 +1,247 @@
+import CaretDown from '@icon/regular/caret-down.svg';
+import CaretUp from '@icon/regular/caret-up.svg';
+import MagnifyingGlass from '@icon/regular/magnifying-glass.svg';
+import X from '@icon/regular/x.svg';
+import { Button } from '@ui/components/Button';
+import { cn } from '@ui/utils/classname';
+import {
+ type Accessor,
+ createContext,
+ type JSX,
+ onCleanup,
+ onMount,
+ Show,
+ useContext,
+} from 'solid-js';
+import type { FindBarController } from './createFindBarController';
+
+/**
+ * Which physical key advances the cursor. `'asc'` — ArrowDown/Enter advance,
+ * ArrowUp/Shift+Enter retreat. `'desc'` — flipped, for surfaces where the
+ * natural reading direction is bottom-to-top (e.g. a chat channel).
+ */
+export type FindBarDirection = 'asc' | 'desc';
+
+type FindBarContextValue = {
+ controller: FindBarController;
+ direction: Accessor<FindBarDirection>;
+};
+
+const FindBarContext = createContext<FindBarContextValue>();
+
+function useFindBarContext(): FindBarContextValue {
+ const ctx = useContext(FindBarContext);
+ if (!ctx)
+ throw new Error('FindBar sub-components must render inside <FindBar>');
+ return ctx;
+}
+
+export type FindBarProps = {
+ controller: FindBarController;
+ direction?: FindBarDirection;
+ placeholder?: string;
+ autofocus?: boolean;
+ class?: string;
+ /**
+ * Override the default layout. Sub-components (`FindBar.SubmitButton`,
+ * `FindBar.Input`, etc.) read state from the FindBar context.
+ */
+ children?: JSX.Element;
+};
+
+export function FindBar(props: FindBarProps) {
+ const direction: Accessor<FindBarDirection> = () => props.direction ?? 'asc';
+
+ return (
+ <FindBarContext.Provider
+ value={{ controller: props.controller, direction }}
+ >
+ <div
+ class={cn(
+ 'flex items-center gap-1 rounded-md border border-edge bg-panel p-1 shadow-md focus-within:border-accent',
+ props.class
+ )}
+ >
+ <Show
+ when={props.children}
+ fallback={
+ <FindBarDefaultLayout
+ placeholder={props.placeholder}
+ autofocus={props.autofocus}
+ />
+ }
+ >
+ {props.children}
+ </Show>
+ </div>
+ </FindBarContext.Provider>
+ );
+}
+
+function FindBarDefaultLayout(props: {
+ placeholder?: string;
+ autofocus?: boolean;
+}) {
+ return (
+ <>
+ <FindBarSubmitButton />
+ <FindBarInput
+ placeholder={props.placeholder}
+ autofocus={props.autofocus}
+ />
+ <FindBarCount />
+ <FindBarPreviousButton />
+ <FindBarNextButton />
+ <FindBarCloseButton />
+ </>
+ );
+}
+
+function FindBarSubmitButton() {
+ const { controller } = useFindBarContext();
+ return (
+ <Button
+ size="icon-sm"
+ variant="ghost"
+ aria-label="Search"
+ onClick={() => controller.submit()}
+ classList={{
+ '!text-accent':
+ !controller.hasUnsubmittedChanges() && !!controller.query().trim(),
+ }}
+ >
+ <MagnifyingGlass />
+ </Button>
+ );
+}
+
+function FindBarInput(props: { placeholder?: string; autofocus?: boolean }) {
+ const { controller, direction } = useFindBarContext();
+ let inputEl: HTMLInputElement | undefined;
+
+ onMount(() => {
+ if (!inputEl) return;
+ controller.setInputEl(inputEl);
+ if (props.autofocus !== false) inputEl.focus();
+ });
+
+ onCleanup(() => controller.setInputEl(undefined));
+
+ const handleKeyDown: JSX.EventHandler<HTMLInputElement, KeyboardEvent> = (
+ e
+ ) => {
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ e.stopPropagation();
+ controller.close();
+ return;
+ }
+ if (e.key === 'Enter') {
+ e.preventDefault();
+ e.stopPropagation();
+ if (controller.hasUnsubmittedChanges() && !e.shiftKey) {
+ controller.submit();
+ } else if (e.shiftKey) {
+ controller.previous();
+ } else {
+ controller.next();
+ }
+ return;
+ }
+ if (e.key === 'ArrowDown') {
+ e.preventDefault();
+ e.stopPropagation();
+ if (direction() === 'desc') controller.previous();
+ else controller.next();
+ return;
+ }
+ if (e.key === 'ArrowUp') {
+ e.preventDefault();
+ e.stopPropagation();
+ if (direction() === 'desc') controller.next();
+ else controller.previous();
+ }
+ };
+
+ return (
+ <input
+ ref={inputEl}
+ type="text"
+ class="min-w-0 flex-1 bg-transparent border-0 px-1 text-sm text-ink placeholder:text-ink-muted focus:outline-none focus:ring-0"
+ placeholder={props.placeholder ?? 'Find'}
+ value={controller.query()}
+ onInput={(e) => controller.setQuery(e.currentTarget.value)}
+ onKeyDown={handleKeyDown}
+ />
+ );
+}
+
+function FindBarCount() {
+ const { controller } = useFindBarContext();
+ const showCount = () =>
+ !!controller.submittedQuery() &&
+ !controller.hasUnsubmittedChanges() &&
+ !controller.isPending();
+
+ return (
+ <span
+ class="px-1 text-xs text-ink-muted tabular-nums whitespace-nowrap"
+ classList={{ invisible: !showCount() }}
+ >
+ {controller.activeIndex()}/{controller.resultsCount()}
+ </span>
+ );
+}
+
+function FindBarPreviousButton() {
+ const { controller, direction } = useFindBarContext();
+ return (
+ <Button
+ size="icon-sm"
+ variant="ghost"
+ aria-label={direction() === 'desc' ? 'Next match' : 'Previous match'}
+ onClick={() =>
+ direction() === 'desc' ? controller.next() : controller.previous()
+ }
+ >
+ <CaretUp />
+ </Button>
+ );
+}
+
+function FindBarNextButton() {
+ const { controller, direction } = useFindBarContext();
+ return (
+ <Button
+ size="icon-sm"
+ variant="ghost"
+ aria-label={direction() === 'desc' ? 'Previous match' : 'Next match'}
+ onClick={() =>
+ direction() === 'desc' ? controller.previous() : controller.next()
+ }
+ >
+ <CaretDown />
+ </Button>
+ );
+}
+
+function FindBarCloseButton() {
+ const { controller } = useFindBarContext();
+ return (
+ <Button
+ size="icon-sm"
+ variant="ghost"
+ aria-label="Close find bar"
+ onClick={() => controller.close()}
+ >
+ <X />
+ </Button>
+ );
+}
+
+FindBar.SubmitButton = FindBarSubmitButton;
+FindBar.Input = FindBarInput;
+FindBar.Count = FindBarCount;
+FindBar.PreviousButton = FindBarPreviousButton;
+FindBar.NextButton = FindBarNextButton;
+FindBar.CloseButton = FindBarCloseButton;
diff --git a/js/app/packages/core/component/createFindBarController.ts b/js/app/packages/core/component/createFindBarController.ts
new file mode 100644
index 0000000000..12e42f953e
--- /dev/null
+++ b/js/app/packages/core/component/createFindBarController.ts
@@ -0,0 +1,130 @@
+import { type Accessor, createEffect, createSignal, on } from 'solid-js';
+
+export type FindBarSourceContext = {
+ isOpen: Accessor<boolean>;
+ submittedQuery: Accessor<string>;
+ activeIndex: Accessor<number>;
+};
+
+export type FindBarSource<T> = {
+ results: Accessor<T[]>;
+ isFetching: Accessor<boolean>;
+ navigate: (result: T) => void;
+ validateText?: (text: string) => boolean;
+};
+
+export type FindBarController = {
+ isOpen: Accessor<boolean>;
+ query: Accessor<string>;
+ setQuery: (value: string) => void;
+ submittedQuery: Accessor<string>;
+ activeIndex: Accessor<number>;
+ hasUnsubmittedChanges: Accessor<boolean>;
+ isPending: Accessor<boolean>;
+ resultsCount: Accessor<number>;
+ open: () => void;
+ close: () => void;
+ submit: () => void;
+ next: () => void;
+ previous: () => void;
+ setInputEl: (el: HTMLInputElement | undefined) => void;
+};
+
+export type FindBarControllerOptions = {
+ /**
+ * Fires synchronously inside `submit()` *before* `submittedQuery` updates.
+ * Lets callers run side-effects (e.g. clearing an existing selection)
+ * that must complete before downstream results-driven effects run.
+ */
+ onBeforeSubmit?: () => void;
+};
+
+export function createFindBarController<T>(
+ makeSource: (ctx: FindBarSourceContext) => FindBarSource<T>,
+ options: FindBarControllerOptions = {}
+): FindBarController {
+ const [isOpen, setIsOpen] = createSignal(false);
+ const [query, setQuery] = createSignal('');
+ const [submittedQuery, setSubmittedQuery] = createSignal('');
+ const [activeIndex, setActiveIndex] = createSignal(0);
+ const [inputEl, setInputEl] = createSignal<HTMLInputElement>();
+
+ const source = makeSource({ isOpen, submittedQuery, activeIndex });
+ const validateText = source.validateText ?? ((text) => text.length > 0);
+
+ createEffect(on(submittedQuery, () => setActiveIndex(0), { defer: true }));
+
+ createEffect(
+ on(source.results, (rs) => {
+ if (!isOpen()) return;
+ if (rs.length === 0) {
+ setActiveIndex(0);
+ return;
+ }
+ const current = activeIndex();
+ const nextIdx =
+ current === 0 ? 1 : Math.max(1, Math.min(current, rs.length));
+ setActiveIndex(nextIdx);
+ source.navigate(rs[nextIdx - 1]);
+ })
+ );
+
+ const next = () => {
+ const rs = source.results();
+ if (rs.length === 0) return;
+ const i = activeIndex() >= rs.length ? 1 : activeIndex() + 1;
+ setActiveIndex(i);
+ source.navigate(rs[i - 1]);
+ };
+
+ const previous = () => {
+ const rs = source.results();
+ if (rs.length === 0) return;
+ const i = activeIndex() <= 1 ? rs.length : activeIndex() - 1;
+ setActiveIndex(i);
+ source.navigate(rs[i - 1]);
+ };
+
+ const submit = () => {
+ const trimmed = query().trim();
+ options.onBeforeSubmit?.();
+ setSubmittedQuery(validateText(trimmed) ? trimmed : '');
+ };
+
+ const open = () => {
+ if (!isOpen()) {
+ setIsOpen(true);
+ return;
+ }
+ const el = inputEl();
+ if (el && document.activeElement === el) {
+ setIsOpen(false);
+ return;
+ }
+ el?.focus();
+ el?.select();
+ };
+
+ const close = () => {
+ setIsOpen(false);
+ setSubmittedQuery('');
+ setActiveIndex(0);
+ };
+
+ return {
+ isOpen,
+ query,
+ setQuery: (value) => setQuery(value),
+ submittedQuery,
+ activeIndex,
+ hasUnsubmittedChanges: () => query().trim() !== submittedQuery(),
+ isPending: () => !!submittedQuery() && source.isFetching(),
+ resultsCount: () => source.results().length,
+ open,
+ close,
+ submit,
+ next,
+ previous,
+ setInputEl: (el) => setInputEl(el),
+ };
+}
diff --git a/js/app/packages/core/hotkey/tokens.ts b/js/app/packages/core/hotkey/tokens.ts
index 76cbaad9c5..43279067a5 100644
--- a/js/app/packages/core/hotkey/tokens.ts
+++ b/js/app/packages/core/hotkey/tokens.ts
@@ -257,6 +257,7 @@ export const TOKENS = {
threadReply: 'channel.threadReply',
threadEditReply: 'channel.threadEditReply',
threadDeleteReply: 'channel.threadDeleteReply',
+ findInChannel: 'channel.findInChannel',
},
// drawer
diff --git a/js/app/packages/queries/channel/channel-messages.ts b/js/app/packages/queries/channel/channel-messages.ts
index c16ae427ff..de23935c53 100644
--- a/js/app/packages/queries/channel/channel-messages.ts
+++ b/js/app/packages/queries/channel/channel-messages.ts
@@ -742,7 +742,16 @@ export function createMessageIndex(
const [messageIndex, setMessageIndex] = createStore(buildIndex());
- createEffect(on(data, () => setMessageIndex(reconcile(buildIndex()))));
+ createEffect(
+ on(data, () => {
+ const next = buildIndex();
+ // The underlying query can briefly emit undefined data during a refetch
+ if (next.items.length === 0 && messageIndex.items.length > 0) {
+ return;
+ }
+ setMessageIndex(reconcile(next));
+ })
+ );
return messageIndex;
}
diff --git a/js/app/packages/queries/soup/search.ts b/js/app/packages/queries/soup/search.ts
index 29e89eafc3..f14e3afb33 100644
--- a/js/app/packages/queries/soup/search.ts
+++ b/js/app/packages/queries/soup/search.ts
@@ -1,9 +1,16 @@
import { ENABLE_SEARCH_SERVICE } from '@core/constant/featureFlags';
+import { useChannelsContext } from '@core/context/channels';
import { throwOnErr } from '@core/util/maybeResult';
-import type { EntityData, WithSearch } from '@entity';
+import type { ChannelMessageEntity, EntityData, WithSearch } from '@entity';
import { soupKeys } from '@queries/soup/keys';
-import { useSearchResponseItemMapper } from '@queries/soup/transform-utils';
-import { searchClient } from '@service-search/client';
+import {
+ mapChannelSearchResultItem,
+ useSearchResponseItemMapper,
+} from '@queries/soup/transform-utils';
+import {
+ type ChannelSearchRequest,
+ searchClient,
+} from '@service-search/client';
import type { UnifiedSearchRequest } from '@service-search/generated/models';
import { useInfiniteQuery } from '@tanstack/solid-query';
import { type Accessor, createMemo } from 'solid-js';
@@ -87,3 +94,79 @@ export const useSearchSoupQuery = (
meta: { normalize: false },
}));
};
+
+export type SearchChannelQueryArgs = {
+ params: {
+ cursor?: string | null;
+ page_size?: number;
+ };
+ body: ChannelSearchRequest;
+};
+
+/**
+ * Hits the channel-only `/search/channel` endpoint. Use this for the in-channel
+ * find-bar so we can pass `sort: 'thread'` (PR #3150) — unified search doesn't
+ * accept that field. Response transforms identical to the unified path's
+ * `channel` case via the shared `mapChannelSearchResultItem` helper.
+ */
+export const useSearchChannelQuery = (
+ args: Accessor<SearchChannelQueryArgs>,
+ options?: Accessor<SearchQueryOptions>
+) => {
+ const channelsContext = useChannelsContext();
+ const channels = channelsContext.channels;
+
+ const pageSize = createMemo(() => args().params.page_size);
+
+ const request = createMemo(() => {
+ const body = args().body;
+ return {
+ ...body,
+ query: body.query?.trim(),
+ };
+ });
+
+ const validSearch = createMemo(() => {
+ const q = request().query;
+ return !!q && validateSearchServiceText(q);
+ });
+
+ const enabled = createMemo(() => {
+ if (options?.().enabled === false) return false;
+ return ENABLE_SEARCH_SERVICE && validSearch();
+ });
+
+ return useInfiniteQuery(() => ({
+ queryKey: ['search-channel', args().params, request()] as const,
+ queryFn: async (ctx) => {
+ return throwOnErr(
+ async () =>
+ await searchClient.searchChannel({
+ params: ctx.pageParam,
+ request: { ...request() },
+ })
+ );
+ },
+ initialPageParam: {
+ cursor: null as string | null,
+ page_size: pageSize(),
+ },
+ getNextPageParam: (lastPage) => {
+ if (!lastPage.next_cursor) return;
+ return {
+ cursor: lastPage.next_cursor,
+ page_size: pageSize(),
+ };
+ },
+ select: (data) => {
+ return data.pages.flatMap((page) =>
+ page.results.flatMap((item) =>
+ mapChannelSearchResultItem(item, channels())
+ )
+ ) as WithSearch<ChannelMessageEntity>[];
+ },
+ enabled: enabled(),
+ placeholderData: (p) => p,
+ meta: { normalize: false },
+ }));
+};
diff --git a/js/app/packages/queries/soup/transform-utils.ts b/js/app/packages/queries/soup/transform-utils.ts
index 1b3acf4804..f1a1427753 100644
--- a/js/app/packages/queries/soup/transform-utils.ts
+++ b/js/app/packages/queries/soup/transform-utils.ts
@@ -210,6 +210,55 @@ const getSearchData = (data: TypedInnerSearchResult): SearchData => {
};
};
+/**
+ * Maps a single channel search response item into `ChannelMessageEntity`s.
+ * Shared between the unified search transform and the channel-only endpoint,
+ * both of which return the same per-channel shape.
+ */
+export function mapChannelSearchResultItem(
+ result: {
+ channel_id: string;
+ channel_type: string;
+ owner_id?: string | null;
+ channel_message_search_results: ChannelSearchResult[];
+ },
+ channels: ReadonlyArray<{ id: string; name?: string | null }>
+): WithSearch<ChannelMessageEntity>[] {
+ const channelWithLatest = channels.find((c) => c.id === result.channel_id);
+ const channelName =
+ channelWithLatest?.name ?? blockNameToDefaultFile('channel');
+ const channelType = result.channel_type as ChannelType;
+ const ownerId = result.owner_id ?? '';
+
+ return result.channel_message_search_results
+ .filter((msg) => !!msg.message_id)
+ .map((msg): WithSearch<ChannelMessageEntity> => {
+ const search = getSearchData({
+ type: 'channel',
+ results: [msg],
+ });
+
+ const content = search.contentHitData?.[0]?.content ?? '';
+
+ return {
+ type: 'channel_message',
+ id: `${result.channel_id}:${msg.message_id}`,
+ channelId: result.channel_id,
+ channelName,
+ channelType,
+ messageId: msg.message_id!,
+ threadId: msg.thread_id ?? undefined,
+ senderId: msg.sender_id!,
+ content,
+ name: channelName,
+ ownerId,
+ createdAt: msg.created_at,
+ updatedAt: msg.updated_at ?? msg.created_at,
+ search,
+ };
+ });
+}
+
export const useSearchResponseItemMapper = () => {
const channelsContext = useChannelsContext();
const channels = channelsContext.channels;
@@ -309,41 +358,16 @@ export const useSearchResponseItemMapper = () => {
];
}
case 'channel': {
- const channelWithLatest = channels().find(
- (c) => c.id === result.channel_id
+ return mapChannelSearchResultItem(
+ {
+ channel_id: result.channel_id,
+ channel_type: result.channel_type,
+ owner_id: result.owner_id,
+ channel_message_search_results:
+ result.channel_message_search_results,
+ },
+ channels()
);
- const channelName =
- channelWithLatest?.name ?? blockNameToDefaultFile('channel');
- const channelType = result.channel_type as ChannelType;
- const ownerId = result.owner_id ?? '';
-
- return result.channel_message_search_results
- .filter((msg) => !!msg.message_id)
- .map((msg): WithSearch<ChannelMessageEntity> => {
- const search = getSearchData({
- type: 'channel',
- results: [msg],
- });
-
- const content = search.contentHitData?.[0]?.content ?? '';
-
- return {
- type: 'channel_message',
- id: `${result.channel_id}:${msg.message_id}`,
- channelId: result.channel_id,
- channelName,
- channelType,
- messageId: msg.message_id!,
- threadId: msg.thread_id ?? undefined,
- senderId: msg.sender_id!,
- content,
- name: channelName,
- ownerId,
- createdAt: msg.created_at,
- updatedAt: msg.updated_at ?? msg.created_at,
- search,
- };
- });
}
case 'project': {
diff --git a/js/app/packages/service-clients/service-search/client.ts b/js/app/packages/service-clients/service-search/client.ts
index a9f8173a6e..461afd77ca 100644
--- a/js/app/packages/service-clients/service-search/client.ts
+++ b/js/app/packages/service-clients/service-search/client.ts
@@ -14,9 +14,13 @@ import type { SafeFetchInit } from '@core/util/safeFetch';
const searchServiceHost = `${SERVER_HOSTS['document-storage-service']}`;
+import type { ChannelSearchRequest } from './generated/models/channelSearchRequest';
+import type { ChannelSearchResponse } from './generated/models/channelSearchResponse';
import type { UnifiedSearchRequest } from './generated/models/unifiedSearchRequest';
import type { UnifiedSearchResponse } from './generated/models/unifiedSearchResponse';
+export type { ChannelSearchRequest, ChannelSearchResponse };
+
export function searchServiceFetch(
url: string,
init?: SafeFetchInit
@@ -44,20 +48,26 @@ export type SearchArgs = {
request: UnifiedSearchRequest;
};
-export const searchClient = {
- async search(args: SearchArgs, init?: SafeFetchInit) {
- const params = new URLSearchParams();
-
- if (args.params.page_size !== undefined) {
- params.append('page_size', args.params.page_size.toString());
- }
- if (args.params.cursor) {
- params.append('cursor', args.params.cursor);
- }
+export type ChannelSearchArgs = {
+ params: SearchParams;
+ request: ChannelSearchRequest;
+};
- const queryString = params.toString();
- const url = queryString ? `/search?${queryString}` : '/search';
+const buildSearchQuery = (params: SearchParams) => {
+ const qp = new URLSearchParams();
+ if (params.page_size !== undefined) {
+ qp.append('page_size', params.page_size.toString());
+ }
+ if (params.cursor) {
+ qp.append('cursor', params.cursor);
+ }
+ const qs = qp.toString();
+ return qs ? `?${qs}` : '';
+};
+export const searchClient = {
+ async search(args: SearchArgs, init?: SafeFetchInit) {
+ const url = `/search${buildSearchQuery(args.params)}`;
return mapOk(
await searchServiceFetch<UnifiedSearchResponse>(url, {
method: 'POST',
@@ -67,4 +77,16 @@ export const searchClient = {
(result) => result
);
},
+
+ async searchChannel(args: ChannelSearchArgs, init?: SafeFetchInit) {
+ const url = `/search/channel${buildSearchQuery(args.params)}`;
+ return mapOk(
+ await searchServiceFetch<ChannelSearchResponse>(url, {
+ method: 'POST',
+ body: JSON.stringify(args.request),
+ ...init,
+ }),
+ (result) => result
+ );
+ },
};