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: pdf + markdown search linking (#301)

gbirman6c27285c7a74
diff --git a/js/app/packages/app/component/UnifiedListView.tsx b/js/app/packages/app/component/UnifiedListView.tsx
index bc9312e199..33881f0f4b 100644
--- a/js/app/packages/app/component/UnifiedListView.tsx
+++ b/js/app/packages/app/component/UnifiedListView.tsx
@@ -6,6 +6,8 @@ import {
emailRefetchInterval,
useEmailLinksStatus,
} from '@app/signal/emailAuth';
+import { URL_PARAMS as MD_PARAMS } from '@block-md/constants';
+import { URL_PARAMS as PDF_PARAMS } from '@block-pdf/signal/location';
import { Button } from '@core/component/FormControls/Button';
import DropdownMenu from '@core/component/FormControls/DropdownMenu';
import { SegmentedControl } from '@core/component/FormControls/SegmentControls';
@@ -865,15 +867,41 @@ export function UnifiedListView(props: UnifiedListViewProps) {
setIsSearchLoading(loading);
});
- const documentEntityClickHandler: EntityClickHandler<DocumentEntity> = (
- { id, fileType },
- event
- ) => {
+ const documentEntityClickHandler: EntityClickHandler<
+ DocumentEntity | WithSearch<DocumentEntity>
+ > = async (entity, event) => {
+ const { id, fileType } = entity;
const blockName = fileTypeToBlockName(fileType);
const handle = event.altKey
? insertSplit({ type: blockName, id })
: replaceOrInsertSplit({ type: blockName, id });
- handle?.activate();
+
+ const location =
+ 'search' in entity && entity.search.contentHighlights?.at(0)?.location;
+ if (location) {
+ handle?.activate();
+ const blockHandle = await blockOrchestrator.getBlockHandle(id);
+ switch (location.type) {
+ case 'md':
+ await blockHandle?.goToLocationFromParams({
+ [MD_PARAMS.nodeId]: location.nodeId,
+ });
+ break;
+ case 'pdf':
+ console.log('go to pdf location', location);
+ await blockHandle?.goToLocationFromParams({
+ [PDF_PARAMS.searchPage]: location.searchPage.toString(),
+ [PDF_PARAMS.searchRawQuery]: location.searchRawQuery,
+ [PDF_PARAMS.searchHighlightTerms]: JSON.stringify(
+ location.highlightTerms
+ ),
+ [PDF_PARAMS.searchSnippet]: location.searchSnippet,
+ });
+ break;
+ }
+ } else {
+ handle?.activate();
+ }
};
const entityClickHandler: EntityClickHandler<EntityData> = (
diff --git a/js/app/packages/app/component/command/KonsoleItem.tsx b/js/app/packages/app/component/command/KonsoleItem.tsx
index d3d413d978..3eb6093063 100644
--- a/js/app/packages/app/component/command/KonsoleItem.tsx
+++ b/js/app/packages/app/component/command/KonsoleItem.tsx
@@ -203,6 +203,9 @@ export type SearchSnippet = {
fileType: string;
matchIndex?: number;
senderId?: string;
+ // PDF/DOCX-specific fields for search navigation
+ searchSnippet?: string;
+ highlightTerms?: string[];
};
type CommandItemBase = {
@@ -321,8 +324,11 @@ async function gotoSnippetLocation(
case 'docx':
handle.goToLocationFromParams({
[PDF_PARAMS.searchPage]: snippet.locationId,
- [PDF_PARAMS.searchMatchNumOnPage]: (snippet.matchIndex ?? 0).toString(),
- [PDF_PARAMS.searchTerm]: searchTerm,
+ [PDF_PARAMS.searchRawQuery]: searchTerm,
+ [PDF_PARAMS.searchHighlightTerms]: JSON.stringify(
+ snippet.highlightTerms
+ ),
+ [PDF_PARAMS.searchSnippet]: snippet.searchSnippet,
});
break;
case 'chat':
@@ -419,12 +425,15 @@ export interface CommandItemProps {
snippets?: Record<string, string>;
}
-function getCommandItemBlockName(item: CommandItemCard): BlockName | undefined {
+function getCommandItemBlockName(
+ item: CommandItemCard,
+ icon?: boolean
+): BlockName | undefined {
if (item.type === 'item') {
if (item.data.itemType === 'document' && item.data.fileType) {
- return fileTypeToBlockName(item.data.fileType);
+ return fileTypeToBlockName(item.data.fileType, icon);
}
- return fileTypeToBlockName(item.data.itemType) ?? 'unknown';
+ return fileTypeToBlockName(item.data.itemType, icon) ?? 'unknown';
} else if (item.type === 'channel') {
return 'channel';
} else if (item.type === 'email') {
@@ -503,7 +512,7 @@ export function filterItemByCategory(item: CommandItemCard) {
}
export function CommandItemCard(props: CommandItemProps) {
- const blockName = () => getCommandItemBlockName(props.item);
+ const blockName = () => getCommandItemBlockName(props.item, true);
const userId = useUserId();
const name = () => {
const name = getCommandItemName(props.item);
@@ -714,7 +723,7 @@ export function PinnedCommandItem(props: {
item: CommandItemCard;
itemAction: (item: CommandItemCard, action: ItemAction) => void;
}) {
- const type = () => getCommandItemBlockName(props.item);
+ const type = () => getCommandItemBlockName(props.item, true);
const name = () => getCommandItemName(props.item);
return (
diff --git a/js/app/packages/app/component/command/useSearchItems.ts b/js/app/packages/app/component/command/useSearchItems.ts
index 611e66b667..ab4ea287fb 100644
--- a/js/app/packages/app/component/command/useSearchItems.ts
+++ b/js/app/packages/app/component/command/useSearchItems.ts
@@ -1,6 +1,10 @@
import { ENABLE_SEARCH_SERVICE } from '@core/constant/featureFlags';
import { useSearch } from '@core/signal/search';
import { isErr } from '@core/util/maybeResult';
+import {
+ extractSearchSnippet,
+ extractSearchTerms,
+} from '@core/util/searchHighlight';
import type { BasicDocumentFileType } from '@service-storage/generated/schemas/basicDocumentFileType';
import { createEffect, createMemo, createSignal } from 'solid-js';
import { searchClient } from '../../../service-search/client';
@@ -41,6 +45,11 @@ function createDocumentItems(
locationId: result.node_id,
fileType: doc.file_type,
matchIndex: index,
+ // For PDF files, extract additional location data
+ ...(['docx', 'pdf'].includes(doc.file_type) && {
+ searchSnippet: extractSearchSnippet(content),
+ highlightTerms: extractSearchTerms(content),
+ }),
},
updatedAt: result.updated_at * 1000, // Convert Unix timestamp to milliseconds
});
diff --git a/js/app/packages/block-pdf/PdfViewer/EventBus.ts b/js/app/packages/block-pdf/PdfViewer/EventBus.ts
index 65a2302eba..5c086f192e 100644
--- a/js/app/packages/block-pdf/PdfViewer/EventBus.ts
+++ b/js/app/packages/block-pdf/PdfViewer/EventBus.ts
@@ -68,13 +68,22 @@ export interface IScrollMatchEvent extends ISourcedEvent {
}
export interface IFindEvent {
+ /** The object that initiated the find operation */
source: any;
+ /** Search type: '' for new search (with timeout), 'again' for repeat search (immediate) */
type: '' | 'again';
+ /** The search text/term to find in the PDF */
query: string;
+ /** If true, search for exact phrase; if false, match partial words */
phraseSearch: boolean;
+ /** If true, match case exactly; if false, ignore case differences */
caseSensitive: boolean;
+ /** If true, only match complete words; if false, match partial words.
+ * e.g. credit will match creditors if entireWord is false */
entireWord: boolean;
+ /** If true, highlight all matches in document; if false, only highlight current match */
highlightAll: boolean;
+ /** If true, search backwards (previous match); if false, search forwards (next match) */
findPrevious: boolean;
}
diff --git a/js/app/packages/block-pdf/PdfViewer/FindController.ts b/js/app/packages/block-pdf/PdfViewer/FindController.ts
index b02104a58f..42cb7c5e39 100644
--- a/js/app/packages/block-pdf/PdfViewer/FindController.ts
+++ b/js/app/packages/block-pdf/PdfViewer/FindController.ts
@@ -93,6 +93,55 @@ export class FindController extends PDFFindController {
this._updateMatch(/* found = */ true);
}
+ /**
+ * Extracts text content for a single page and stores it in the internal arrays.
+ * @param pageIndex - 0-indexed page number
+ */
+ private async _extractTextForPageIndex(pageIndex: number): Promise<void> {
+ if (!this._pdfDocument) {
+ throw new Error('No PDF document loaded');
+ }
+
+ // Initialize arrays if needed
+ if (!this._pageContents) this._pageContents = [];
+ if (!this._pageDiffs) this._pageDiffs = [];
+ if (!this._hasDiacritics) this._hasDiacritics = [];
+ if (!this._pageContentsAsTextLayer) this._pageContentsAsTextLayer = [];
+
+ try {
+ const pdfPage = await this._pdfDocument.getPage(pageIndex + 1);
+ const textContent: any = await pdfPage.getTextContent();
+ const textItems = textContent.items;
+ const strBuf: string[] = [];
+ const pageContentsAsTextLayerStrBuf: string[] = [];
+
+ for (const textItem of textItems) {
+ strBuf.push(textItem.str);
+ pageContentsAsTextLayerStrBuf.push(textItem.str);
+ if (textItem.hasEOL) {
+ strBuf.push('\n');
+ }
+ }
+
+ this._pageContentsAsTextLayer[pageIndex] = pageContentsAsTextLayerStrBuf;
+
+ [
+ this._pageContents[pageIndex],
+ this._pageDiffs[pageIndex],
+ this._hasDiacritics[pageIndex],
+ ] = normalize(strBuf.join(''));
+ } catch (reason) {
+ console.error(
+ `Unable to get text content for page ${pageIndex + 1}`,
+ reason
+ );
+ // Page error -- assuming no text content.
+ this._pageContents[pageIndex] = '';
+ this._pageDiffs[pageIndex] = null;
+ this._hasDiacritics[pageIndex] = false;
+ }
+ }
+
_extractText() {
if (!this._extractTextPromises) {
return;
@@ -108,62 +157,88 @@ export class FindController extends PDFFindController {
const extractTextCapability = createPromiseCapability<number>();
this._extractTextPromises[i] = extractTextCapability.promise;
- promise = promise.then(() => {
- if (!this._pdfDocument) {
+ promise = promise.then(async () => {
+ // Skip if this page was already extracted via warmSearchTextForPage
+ if (this._pageContents && this._pageContents[i] !== undefined) {
+ extractTextCapability.resolve(i);
return;
}
- return this._pdfDocument
- .getPage(i + 1)
- .then((pdfPage) => {
- return pdfPage.getTextContent();
- })
- .then(
- (textContent: any) => {
- const textItems = textContent.items;
- const strBuf: string[] = [];
-
- if (!this._pageContentsAsTextLayer) {
- this._pageContentsAsTextLayer = [];
- }
-
- const pageContentsAsTextLayerStrBuf: string[] = [];
-
- // Initialize _pageContentsAsTextLayer if needed
- if (!this._pageContentsAsTextLayer) {
- this._pageContentsAsTextLayer = [];
- }
-
- for (const textItem of textItems) {
- strBuf.push(textItem.str);
- pageContentsAsTextLayerStrBuf.push(textItem.str);
- if (textItem.hasEOL) {
- strBuf.push('\n');
- }
- }
-
- this._pageContentsAsTextLayer[i] = pageContentsAsTextLayerStrBuf;
-
- // Store the normalized page content (text items) as one string.
- [
- this._pageContents![i],
- this._pageDiffs![i],
- this._hasDiacritics![i],
- ] = normalize(strBuf.join(''));
- extractTextCapability.resolve(i);
- },
- (reason) => {
- console.error(
- `Unable to get text content for page ${i + 1}`,
- reason
- );
- // Page error -- assuming no text content.
- this._pageContents![i] = '';
- this._pageDiffs![i] = null;
- this._hasDiacritics![i] = false;
- extractTextCapability.resolve(i);
- }
- );
+
+ try {
+ await this._extractTextForPageIndex(i);
+ extractTextCapability.resolve(i);
+ } catch (_error) {
+ extractTextCapability.resolve(i);
+ }
});
}
}
+
+ /**
+ * Force a full text extraction for all pages.
+ * This clears the _extractTextPromises array and re-runs extraction.
+ * Useful after warmSearchTextForPage to ensure all pages are available for future searches.
+ */
+ forceFullExtraction() {
+ if (!this._extractTextPromises) {
+ return;
+ }
+
+ // Clear the promises array so _extractText() will run
+ this._extractTextPromises = [];
+
+ // Clear page contents that were set to empty strings by warmSearchTextForPage
+ // This ensures _extractText() will actually extract them instead of skipping
+ if (this._pageContents) {
+ for (let i = 0; i < this._pageContents.length; i++) {
+ if (this._pageContents[i] === '') {
+ this._pageContents[i] = undefined as any;
+ }
+ }
+ }
+
+ // Trigger full extraction
+ this._extractText();
+ }
+
+ /**
+ * Extract text for a specific page immediately and prevent full extraction.
+ * This populates the _extractTextPromises array so _extractText() won't run.
+ * After using this, call forceFullExtraction() to extract remaining pages.
+ * @param pageIndex - 0-indexed page number
+ * @returns Promise that resolves when text extraction is complete for that page
+ */
+ async warmSearchTextForPage(pageIndex: number): Promise<number | undefined> {
+ if (!this._pdfDocument || !this._extractTextPromises) {
+ return undefined;
+ }
+
+ // Check if this page is already extracted
+ if (this._pageContents && this._pageContents[pageIndex] !== undefined) {
+ return pageIndex;
+ }
+
+ // Populate _extractTextPromises with resolved promises to prevent _extractText() from running
+ // This is the key optimization - we tell the FindController that extraction is "done"
+ const pagesCount = this._linkService.pagesCount;
+ if (this._extractTextPromises.length === 0) {
+ // Initialize arrays
+ if (!this._pageContents) this._pageContents = [];
+ if (!this._pageDiffs) this._pageDiffs = [];
+ if (!this._hasDiacritics) this._hasDiacritics = [];
+
+ for (let i = 0; i < pagesCount; i++) {
+ // Mark all pages as "extracted" with empty content
+ // The target page will be filled with real content below
+ this._extractTextPromises[i] = Promise.resolve(i);
+ this._pageContents[i] = '';
+ this._pageDiffs[i] = null;
+ this._hasDiacritics[i] = false;
+ }
+ }
+
+ // Extract the target page using the shared extraction method
+ await this._extractTextForPageIndex(pageIndex);
+ return pageIndex;
+ }
}
diff --git a/js/app/packages/block-pdf/PdfViewer/InternalPDFViewer.ts b/js/app/packages/block-pdf/PdfViewer/InternalPDFViewer.ts
index 25a2635b6f..8b52bdd247 100644
--- a/js/app/packages/block-pdf/PdfViewer/InternalPDFViewer.ts
+++ b/js/app/packages/block-pdf/PdfViewer/InternalPDFViewer.ts
@@ -1571,6 +1571,12 @@ export class InternalPDFViewer {
},
};
}
+
+ markPageHighlightsSelected(pageIndex: number): void {
+ const pageView = this._viewer.getPageView(pageIndex);
+ if (!pageView) return;
+ markHighlightsSelected(pageView);
+ }
}
export function overlaysToElements(overlays: string[]) {
@@ -1610,3 +1616,14 @@ function enableTextLayer(pageView: PDFPageView) {
if (pageView.textLayer?.textLayerDiv == null) return;
pageView.textLayer.textLayerDiv.style.userSelect = '';
}
+
+function markHighlightsSelected(pageView: PDFPageView) {
+ const textLayerDiv = pageView.textLayer?.textLayerDiv;
+ if (!textLayerDiv) return;
+ const highlightSpans = textLayerDiv.querySelectorAll('.highlight.appended');
+ for (const span of highlightSpans) {
+ if (!span.classList.contains('selected')) {
+ span.classList.add('selected');
+ }
+ }
+}
diff --git a/js/app/packages/block-pdf/PdfViewer/index.ts b/js/app/packages/block-pdf/PdfViewer/index.ts
index e84ed1ab5c..d230f5b4fb 100644
--- a/js/app/packages/block-pdf/PdfViewer/index.ts
+++ b/js/app/packages/block-pdf/PdfViewer/index.ts
@@ -1,8 +1,9 @@
+import type { WithRequired } from '@core/util/withRequired';
import { debounce } from '@solid-primitives/scheduled';
import type { PDFDocumentProxy } from 'pdfjs-dist';
import type { PDFPageView } from 'pdfjs-dist/web/pdf_viewer';
import type { TDestArray } from './DestArray';
-import type { IPublicEventBus } from './EventBus';
+import type { IFindEvent, IPublicEventBus } from './EventBus';
import { InternalPDFViewer } from './InternalPDFViewer';
import {
correctScrollAfterWheelZoom,
@@ -39,6 +40,10 @@ export class PDFViewer extends InternalPDFViewer {
return this._viewer.pdfDocument;
}
+ get findController() {
+ return this._findController;
+ }
+
async destroy() {
super.destroy();
}
@@ -216,6 +221,17 @@ export class PDFViewer extends InternalPDFViewer {
100
);
+ /**
+ * Search for text in the PDF document and highlight matches.
+ *
+ * @param query - The search text/term to find in the PDF
+ * @param again - If true, repeat the previous search immediately without timeout (default: false)
+ * @param phraseSearch - If true, search for exact phrase; if false, match partial words (default: true)
+ * @param caseSensitive - If true, match case exactly; if false, ignore case differences (default: false)
+ * @param entireWord - If true, only match complete words; if false, match partial words (default: false)
+ * @param highlightAll - If true, highlight all matches in document; if false, only highlight current match (default: true)
+ * @param findPrevious - If true, search backwards (previous match); if false, search forwards (next match) (default: false)
+ */
search({
query,
again = false,
@@ -224,14 +240,8 @@ export class PDFViewer extends InternalPDFViewer {
entireWord = false,
highlightAll = true,
findPrevious = false,
- }: {
- query: string;
+ }: WithRequired<Partial<Omit<IFindEvent, 'source' | 'type'>>, 'query'> & {
again?: boolean;
- phraseSearch?: boolean;
- caseSensitive?: boolean;
- entireWord?: boolean;
- highlightAll?: boolean;
- findPrevious?: boolean;
}) {
this._eventBus.dispatch('find', {
source: this,
@@ -245,7 +255,7 @@ export class PDFViewer extends InternalPDFViewer {
});
}
- resetSearch() {
+ findBarClose() {
this._eventBus.dispatch('findbarclose', { source: this });
}
diff --git a/js/app/packages/block-pdf/component/Block.tsx b/js/app/packages/block-pdf/component/Block.tsx
index 7884844d69..db560c8507 100644
--- a/js/app/packages/block-pdf/component/Block.tsx
+++ b/js/app/packages/block-pdf/component/Block.tsx
@@ -1,6 +1,7 @@
import './block.css';
import {
+ type LocationBlockParams,
locationChangedSignal,
pendingLocationParamsSignal,
} from '@block-pdf/signal/location';
@@ -168,11 +169,11 @@ export default function BlockPdf() {
});
const blockHandle = blockHandleSignal.get;
+ const setPendingLocationParamsSignal = pendingLocationParamsSignal.set;
+ const setLocationChanged = locationChangedSignal.set;
const goToLocationFromParams = createCallback(
- (params: Record<string, any>) => {
+ (params: LocationBlockParams) => {
console.log('GO TO LOCATION FROM PARAMS', params);
- const setPendingLocationParamsSignal = pendingLocationParamsSignal.set;
- const setLocationChanged = locationChangedSignal.set;
setLocationChanged(true);
@@ -182,7 +183,7 @@ export default function BlockPdf() {
);
createMethodRegistration(blockHandle, {
- goToLocationFromParams: async (params: Record<string, any>) =>
+ goToLocationFromParams: async (params: LocationBlockParams) =>
goToLocationFromParams(params),
});
diff --git a/js/app/packages/block-pdf/component/Document.tsx b/js/app/packages/block-pdf/component/Document.tsx
index 60cfaa4fd5..4b319c3c09 100644
--- a/js/app/packages/block-pdf/component/Document.tsx
+++ b/js/app/packages/block-pdf/component/Document.tsx
@@ -55,10 +55,10 @@ import {
} from '../signal/document';
import {
generalPopupLocationSignal,
- goToLinkLocation,
type LocationSearchParams,
locationChangedSignal,
URL_PARAMS,
+ useGoToLinkLocation,
useGoToTempRedirect,
useSetLocationStore,
} from '../signal/location';
@@ -238,7 +238,7 @@ function InnerDocument() {
/** Shows the document loading spinner without unloading the PDF Viewer */
function LoadingDocumentSpinnerEffect() {
return (
- <Show when={!viewerHasVisiblePagesSignal()}>
+ <Show when={!viewerHasVisiblePagesSignal.get()}>
<div class="flex absolute w-full h-full z-viewer-document-loading-spinner">
<div class="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2">
<LoadingSpinner />
@@ -565,8 +565,9 @@ export function Document() {
return {
annotationId: searchParams[URL_PARAMS.annotationId],
searchPage: searchParams[URL_PARAMS.searchPage],
- searchMatchNumOnPage: searchParams[URL_PARAMS.searchMatchNumOnPage],
- searchTerm: searchParams[URL_PARAMS.searchTerm],
+ searchSnippet: searchParams[URL_PARAMS.searchSnippet],
+ searchRawQuery: searchParams[URL_PARAMS.searchRawQuery],
+ highlightTerms: searchParams[URL_PARAMS.searchHighlightTerms],
pageNumber: searchParams[URL_PARAMS.pageNumber],
yPos: searchParams[URL_PARAMS.yPos],
x: searchParams[URL_PARAMS.x],
@@ -575,6 +576,7 @@ export function Document() {
} as LocationSearchParams;
};
+ const goToLinkLocation = useGoToLinkLocation();
createEffect(() => {
if (locationChangedSignal() || !viewerReadySignal()) return;
let params = locationSearchParams();
diff --git a/js/app/packages/block-pdf/component/SimpleSearch.tsx b/js/app/packages/block-pdf/component/SimpleSearch.tsx
index 124351fe34..92db712f19 100644
--- a/js/app/packages/block-pdf/component/SimpleSearch.tsx
+++ b/js/app/packages/block-pdf/component/SimpleSearch.tsx
@@ -1,3 +1,4 @@
+import { searchLocationPendingSignal } from '@block-pdf/signal/location';
import { IconButton } from '@core/component/IconButton';
import { IS_MAC } from '@core/constant/isMac';
import { blockElementSignal } from '@core/signal/blockElement';
@@ -17,7 +18,7 @@ import {
isSearchOpenSignal,
searchSignal,
useJumpToResult,
- useSearchReset,
+ useSearchClose,
useSearchResults,
useSearchStart,
} from '../signal/search';
@@ -26,7 +27,8 @@ export function SimpleSearch() {
const searchStart = useSearchStart();
const searchResults = useSearchResults();
const jumpToResult = useJumpToResult();
- const resetSearch = useSearchReset();
+ const closeSearchBar = useSearchClose();
+ const locationPending = searchLocationPendingSignal.get;
let inputRef: HTMLInputElement | undefined;
const [isSearching, setIsSearching] = createSignal(false);
@@ -35,13 +37,15 @@ export function SimpleSearch() {
// search on open
createEffect(() => {
+ if (untrack(locationPending)) return;
const text = untrack(searchText);
if (isOpen()) searchStart({ query: text });
});
createEffect(() => {
const query = searchResults()?.query;
- if (query) {
+ if (untrack(locationPending)) return;
+ if (query != null) {
setSearchText(query);
}
@@ -76,7 +80,7 @@ export function SimpleSearch() {
};
const closeSearch = () => {
- resetSearch();
+ closeSearchBar();
setIsOpen(false);
};
@@ -110,7 +114,7 @@ export function SimpleSearch() {
if (isOpen()) {
if (inputRef === document.activeElement) {
- resetSearch();
+ closeSearch();
setIsOpen(false);
} else {
inputRef?.focus();
@@ -154,21 +158,20 @@ export function SimpleSearch() {
onInput={(e) => setSearchText(e.target.value)}
onKeyDown={inputKeyDownHandler}
/>
- <Show when={searchResults()}>
- {(result) => {
- const current = () => result().count.current;
- const total = () => result().count.total;
-
- return (
- <p class="flex-0 ml-auto mr-3 text-right w-24">
- {current()}/{total()}
- </p>
- );
- }}
- </Show>
- <Show when={!searchResults() && isSearching()}>
- <p class="flex-0 ml-auto mr-3 text-right w-24" />
- </Show>
+ <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>
<IconButton
icon={CaretUp}
theme="clear"
diff --git a/js/app/packages/block-pdf/component/Tabs.tsx b/js/app/packages/block-pdf/component/Tabs.tsx
index bbc67719c0..7feafa41a5 100644
--- a/js/app/packages/block-pdf/component/Tabs.tsx
+++ b/js/app/packages/block-pdf/component/Tabs.tsx
@@ -62,7 +62,7 @@ export function Tabs() {
const deleteTab = useDeleteTab();
const navigate = useNavigateToTab();
return (
- <Show when={viewerHasVisiblePagesSignal()}>
+ <Show when={viewerHasVisiblePagesSignal.get()}>
<div class="w-full h-7 rounded-full flex px-1.5 shrink items-center">
<For each={tabs}>
{(tab, index) => (
diff --git a/js/app/packages/block-pdf/signal/location.ts b/js/app/packages/block-pdf/signal/location.ts
index 035865eaf9..03c2c68983 100644
--- a/js/app/packages/block-pdf/signal/location.ts
+++ b/js/app/packages/block-pdf/signal/location.ts
@@ -1,4 +1,9 @@
-import { FindState } from '@block-pdf/PdfViewer/EventBus';
+import type { PDFViewer } from '@block-pdf/PdfViewer';
+import {
+ FindState,
+ type IUpdateFindControlStateEvent,
+} from '@block-pdf/PdfViewer/EventBus';
+import type { FindController } from '@block-pdf/PdfViewer/FindController';
import { useScrollToCommentThread } from '@block-pdf/store/comments/commentOperations';
import { activeCommentThreadSignal } from '@block-pdf/store/comments/commentStore';
import {
@@ -14,39 +19,51 @@ import {
import { buildSimpleEntityUrl } from '@core/util/url';
import { waitForSignal } from '@core/util/waitForSignal';
import { createCallback } from '@solid-primitives/rootless';
+import type { Accessor } from 'solid-js';
import { z } from 'zod';
import { pdfViewLocation } from './document';
import {
updateFindControlStateSignal,
useGetRootViewer,
+ viewerHasVisiblePagesSignal,
viewerReadySignal,
} from './pdfViewer';
-export const useGoToTempRedirect = () => {
- const [activeThreadId, setActiveThreadId] = activeCommentThreadSignal;
- const scrollToCommentThread = useScrollToCommentThread();
-
- return (documentId: string, state: TempRedirectLocation) => {
- if (state.itemId !== documentId) {
- return;
- }
- setTempRedirectLocation(undefined);
-
- const threadId = state.location?.threadId;
- if (!threadId) return;
-
- const prevActiveThreadId = activeThreadId();
- setActiveThreadId(threadId);
+export const URL_PARAMS = {
+ pageNumber: 'pdf_page_number',
+ yPos: 'pdf_page_y',
+ x: 'pdf_page_x',
+ width: 'pdf_width',
+ height: 'pdf_height',
+ annotationId: 'pdf_ann_id',
+ searchPage: 'pdf_search_page',
+ searchSnippet: 'pdf_search_snippet',
+ searchRawQuery: 'pdf_search_raw_query',
+ searchHighlightTerms: 'pdf_search_highlight_terms',
+} as const;
- // if the thread is already active, scroll to it directly
- // Note that there is already a block effect in comment operations that will
- // scroll to a new active thread signal on change
- if (prevActiveThreadId === threadId) {
- scrollToCommentThread(threadId);
- }
- };
+export type LocationSearchParams = {
+ annotationId?: string;
+ searchPage?: string;
+ searchMatchNumOnPage?: string;
+ searchSnippet?: string;
+ searchRawQuery?: string;
+ highlightTerms?: string;
+ pageNumber?: string;
+ yPos?: string;
+ x?: string;
+ width?: string;
+ height?: string;
};
+/**
+ * Type for location parameters received from block params (e.g., from URL query string).
+ * All values are strings as they come from URL parameters.
+ */
+export type LocationBlockParams = Partial<
+ Record<(typeof URL_PARAMS)[keyof typeof URL_PARAMS], string>
+>;
+
export enum LocationType {
General = 'general',
Precise = 'precise',
@@ -101,8 +118,9 @@ export interface AnnotationLocation {
export interface SearchLocation {
type: 'search';
pageIndex: number;
- matchNum: number;
- term: string;
+ snippet: string;
+ rawQuery: string;
+ highlightTerms: string[];
}
export type PdfLocation =
@@ -120,25 +138,26 @@ export type PdfOrderInfo = z.infer<typeof PdfOrderInfoSchema>;
export const locationChangedSignal = createBlockSignal<boolean>(false);
-// go to this location when it changes
-export const pendingLocationSignal = createBlockSignal<
- PdfLocation | undefined
->();
+export const pendingLocationParamsSignal =
+ createBlockSignal<LocationBlockParams>();
-export const pendingLocationParamsSignal = createBlockSignal<
- Record<string, string> | undefined
->();
+export const searchLocationPendingSignal = createBlockSignal<boolean>(false);
createBlockEffect(() => {
- const viewerReady = viewerReadySignal();
+ const getViewer = useGetRootViewer();
+ const goToLinkLocationFromParams = useGoToLinkLocationFromParams();
+
+ const viewerReady = viewerReadySignal() && viewerHasVisiblePagesSignal.get();
const params = pendingLocationParamsSignal();
+
if (viewerReady && params) {
- const getViewer = useGetRootViewer();
- const viewer = getViewer();
- viewer?.clearAllOverlays();
+ // TODO: do we need to clear all overlays here
+ getViewer()?.clearAllOverlays();
+
goToLinkLocationFromParams(params);
}
});
+
export const locationStore = createBlockStore<{
general: GeneralLocation | undefined;
precise: PreciseLocation | undefined;
@@ -151,14 +170,6 @@ export const locationStore = createBlockStore<{
search: undefined,
});
-createBlockEffect(() => {
- const viewerReady = viewerReadySignal();
- const location = pendingLocationSignal();
- if (viewerReady && location) {
- goToPdfLocation(location);
- }
-});
-
export function useSetLocationStore() {
const setLocationStore_ = locationStore.set;
@@ -189,18 +200,6 @@ export const generalPopupLocationSignal = createBlockSignal<{
hasComment?: boolean;
} | null>(null);
-export const URL_PARAMS = {
- pageNumber: 'pdf_page_number',
- yPos: 'pdf_page_y',
- x: 'pdf_page_x',
- width: 'pdf_width',
- height: 'pdf_height',
- annotationId: 'pdf_ann_id',
- searchPage: 'pdf_search_page', // 0 indexed page number of the search result
- searchMatchNumOnPage: 'pdf_search_match_num', // the index of the content from the search node that was clicked on. this loosely maps to match number since some highlights will contain multiple matches
- searchTerm: 'pdf_search_term', // the search term that was used. this is grabbed from the inside of the <em> tag of the highlight
-} as const;
-
/**
* Converts a location into URL parameters for sharing.
*
@@ -313,17 +312,23 @@ export function useCreateShareUrl() {
}
/**
- * Parses params into a PDF location.
+ * Internal helper to parse location parameters into a PDF location.
* Returns most precise location type possible based on available parameters.
- *
- * @param searchParams - URL search parameters to parse
- * @returns PDF location object or null if no valid location found
*/
-export function parseLocationFromBlockParams(
- params: Record<string, string>
-): PdfLocation | null {
+function parseLocationParams(params: {
+ annotationId?: string;
+ searchPage?: string;
+ searchSnippet?: string;
+ searchRawQuery?: string;
+ searchHighlightTerms?: string;
+ pageNumber?: string;
+ yPos?: string;
+ x?: string;
+ width?: string;
+ height?: string;
+}): PdfLocation | null {
// Check for annotation first as it's highest priority
- const id = params[URL_PARAMS.annotationId];
+ const id = params.annotationId;
if (id?.trim()) {
return {
type: 'annotation',
@@ -333,30 +338,34 @@ export function parseLocationFromBlockParams(
}
// Next highest priority is a search result
- const searchPage = params[URL_PARAMS.searchPage];
- const searchMatchNumOnPage = params[URL_PARAMS.searchMatchNumOnPage];
- const searchTerm = params[URL_PARAMS.searchTerm];
-
- if (searchPage && searchMatchNumOnPage && searchTerm) {
- // TODO: setup analytics?
+ const searchPage = params.searchPage;
+ const searchSnippet = params.searchSnippet;
+ const searchRawQuery = params.searchRawQuery;
+ const searchHighlightTermsString = params.searchHighlightTerms;
+ const searchHighlightTerms = searchHighlightTermsString
+ ? JSON.parse(searchHighlightTermsString)
+ : [];
+
+ if (searchPage && searchRawQuery && searchSnippet && searchHighlightTerms) {
return {
type: 'search',
pageIndex: Number(searchPage) + 1,
- matchNum: Number(searchMatchNumOnPage),
- term: searchTerm,
+ snippet: searchSnippet,
+ rawQuery: searchRawQuery,
+ highlightTerms: searchHighlightTerms,
};
}
- const pageIndex = Number(params[URL_PARAMS.pageNumber]);
- const y = Number(params[URL_PARAMS.yPos]);
+ const pageIndex = Number(params.pageNumber);
+ const y = Number(params.yPos);
if (isNaN(pageIndex) || isNaN(y) || pageIndex < 1) {
return null;
}
- const x = Number(params[URL_PARAMS.x]);
- const width = Number(params[URL_PARAMS.width]);
- const height = Number(params[URL_PARAMS.height]);
+ const x = Number(params.x);
+ const width = Number(params.width);
+ const height = Number(params.height);
if (!isNaN(x) && !isNaN(width) && !isNaN(height) && width > 0 && height > 0) {
return {
@@ -377,217 +386,392 @@ export function parseLocationFromBlockParams(
};
}
-export type LocationSearchParams = {
- annotationId?: string;
- searchPage?: string;
- searchMatchNumOnPage?: string;
- searchTerm?: string;
- pageNumber?: string;
- yPos?: string;
- x?: string;
- width?: string;
- height?: string;
-};
+/**
+ * Parses params into a PDF location.
+ * Returns most precise location type possible based on available parameters.
+ *
+ * @param params - Block parameters containing location information
+ * @returns PDF location object or null if no valid location found
+ */
+export function parseLocationFromBlockParams(
+ params: LocationBlockParams
+): PdfLocation | null {
+ return parseLocationParams({
+ annotationId: params[URL_PARAMS.annotationId],
+ searchPage: params[URL_PARAMS.searchPage],
+ searchSnippet: params[URL_PARAMS.searchSnippet],
+ searchRawQuery: params[URL_PARAMS.searchRawQuery],
+ searchHighlightTerms: params[URL_PARAMS.searchHighlightTerms],
+ pageNumber: params[URL_PARAMS.pageNumber],
+ yPos: params[URL_PARAMS.yPos],
+ x: params[URL_PARAMS.x],
+ width: params[URL_PARAMS.width],
+ height: params[URL_PARAMS.height],
+ });
+}
/**
* Parses URL search parameters into a PDF location.
* Returns most precise location type possible based on available parameters.
*
- * @param searchParams - URL search parameters to parse
+ * @param params - URL search parameters to parse
* @returns PDF location object or null if no valid location found
*/
export function parseLocationFromUrl(
params: LocationSearchParams
): PdfLocation | null {
- // Check for annotation first as it's highest priority
+ return parseLocationParams({
+ annotationId: params.annotationId,
+ searchPage: params.searchPage,
+ searchSnippet: params.searchSnippet,
+ searchRawQuery: params.searchRawQuery,
+ searchHighlightTerms: params.highlightTerms,
+ pageNumber: params.pageNumber,
+ yPos: params.yPos,
+ x: params.x,
+ width: params.width,
+ height: params.height,
+ });
+}
- const id = params.annotationId;
- if (id?.trim()) {
- return {
- type: 'annotation',
- pageIndex: 1,
- id,
- };
+/**
+ * Applies custom highlights using phraseSearch: false to highlight all macro_em terms
+ * in a single search pass, filtered to only matches within the snippet boundaries.
+ */
+async function applyCustomHighlights(
+ viewer: PDFViewer,
+ currentScrollTop: number,
+ currentScrollLeft: number,
+ findController: FindController,
+ findControllerStateEventSignal: Accessor<
+ IUpdateFindControlStateEvent | undefined
+ >,
+ pageIndex: number,
+ terms: string[],
+ snippetStartPos: number,
+ snippetEndPos: number
+) {
+ if (terms.length === 0) {
+ console.warn('No highlight terms found');
+ return;
}
- // Next highest priority is a search result
- const searchPage = params.searchPage;
- const searchMatchNumOnPage = params.searchMatchNumOnPage;
+ // Join all terms with spaces for multi-term search
+ // phraseSearch: false will create an alternation regex (term1|term2|term3)
+ const query = terms.join(' ');
+
+ // Perform single search with phraseSearch: false to highlight all terms
+ viewer.search({
+ query,
+ again: false,
+ phraseSearch: false,
+ caseSensitive: true,
+ entireWord: false,
+ highlightAll: true,
+ findPrevious: false,
+ });
+
+ // Wait for search to complete
+ const searchResult = await waitForSignal(
+ findControllerStateEventSignal,
+ (val) => {
+ return (
+ val?.state === FindState.FOUND || val?.state === FindState.NOT_FOUND
+ );
+ }
+ );
- const searchTerm = params.searchTerm;
+ // Restore the scroll position to where we were before the search
+ viewer.container().scrollTop = currentScrollTop;
+ viewer.container().scrollLeft = currentScrollLeft;
- if (searchPage && searchMatchNumOnPage && searchTerm) {
- // TODO: setup analytics?
- return {
- type: 'search',
- pageIndex: Number(searchPage) + 1,
- matchNum: Number(searchMatchNumOnPage),
- term: searchTerm,
- };
+ if (searchResult?.state === FindState.NOT_FOUND) {
+ console.warn('Terms not found:', terms);
+ return;
}
- const pageIndex = Number(params.pageNumber);
- const y = Number(params.yPos);
+ if (!searchResult) {
+ console.warn('Search result is undefined');
+ return;
+ }
- if (isNaN(pageIndex) || isNaN(y) || pageIndex < 1) {
- return null;
+ // Log pageMatches and pageMatchesLength for debugging
+ const pageMatches = findController.pageMatches;
+ const pageMatchesLength = findController.pageMatchesLength;
+
+ if (!pageMatches || !pageMatchesLength) {
+ console.warn('pageMatches or pageMatchesLength is undefined');
+ return;
}
- const x = Number(params.x);
- const width = Number(params.width);
- const height = Number(params.height);
+ const filteredMatches: number[] = [];
+ const filteredLengths: number[] = [];
- if (!isNaN(x) && !isNaN(width) && !isNaN(height) && width > 0 && height > 0) {
- return {
- type: 'precise',
- pageIndex,
- y,
- x,
- width,
- height,
- };
+ const targetPageMatches = pageMatches[pageIndex] || [];
+ const targetPageLengths = pageMatchesLength[pageIndex] || [];
+
+ for (let i = 0; i < targetPageMatches.length; i++) {
+ const matchStart = targetPageMatches[i];
+ const matchEnd = matchStart + targetPageLengths[i];
+
+ // Only keep matches that are completely within the snippet bounds
+ if (matchStart >= snippetStartPos && matchEnd <= snippetEndPos) {
+ filteredMatches.push(matchStart);
+ filteredLengths.push(targetPageLengths[i]);
+ }
}
- // Fall back to general location
- return {
- type: 'general',
- pageIndex,
- y,
- };
+ // Clear matches on all pages
+ if (findController._pageMatches && findController._pageMatchesLength) {
+ for (let i = 0; i < pageMatches.length; i++) {
+ findController._pageMatches[i] = [];
+ findController._pageMatchesLength[i] = [];
+ }
+
+ // Set only the filtered matches on the target page
+ findController._pageMatches[pageIndex] = filteredMatches;
+ findController._pageMatchesLength[pageIndex] = filteredLengths;
+ }
+
+ findController._matchesCountTotal = filteredMatches.length;
+
+ // Force re-render with the filtered matches
+ findController._updateAllPages();
+
+ viewer.markPageHighlightsSelected(pageIndex);
}
+export const useGoToTempRedirect = () => {
+ const [activeThreadId, setActiveThreadId] = activeCommentThreadSignal;
+ const scrollToCommentThread = useScrollToCommentThread();
+
+ return (documentId: string, state: TempRedirectLocation) => {
+ if (state.itemId !== documentId) {
+ return;
+ }
+ setTempRedirectLocation(undefined);
+
+ const threadId = state.location?.threadId;
+ if (!threadId) return;
+
+ const prevActiveThreadId = activeThreadId();
+ setActiveThreadId(threadId);
+
+ // if the thread is already active, scroll to it directly
+ // Note that there is already a block effect in comment operations that will
+ // scroll to a new active thread signal on change
+ if (prevActiveThreadId === threadId) {
+ scrollToCommentThread(threadId);
+ }
+ };
+};
+
/**
* Go to the given location in the pdf viewer
*
* @param location - The location to go to
*/
-export async function goToPdfLocation(location: PdfLocation) {
+function useGoToPdfLocation() {
const getRootViewer = useGetRootViewer();
- const viewer = getRootViewer();
- const documentId = useBlockId();
- const findControlelrStateEventSignal = updateFindControlStateSignal.get;
- if (!viewer || !documentId) return;
+ const findControllerStateEventSignal = updateFindControlStateSignal.get;
+ const setSearchLocationPending = searchLocationPendingSignal.set;
+
+ const go = async (location: PdfLocation): Promise<void> => {
+ const viewer = getRootViewer();
+ if (!viewer) return;
+
+ switch (location.type) {
+ case 'general':
+ await viewer.scrollTo({
+ pageNumber: location.pageIndex,
+ yPos: location.y,
+ });
+ return;
+ case 'precise':
+ await viewer.scrollTo({
+ pageNumber: location.pageIndex,
+ yPos: location.y,
+ });
+ viewer.generateOverlayForSelectionRect(
+ location.pageIndex - 1,
+ location
+ );
+ return;
+ case 'annotation':
+ // TODO: implement specific annotation navigation, e.g. comments
+ await viewer.scrollTo({
+ pageNumber: location.pageIndex,
+ yPos: 0,
+ });
+ return;
+ case 'search':
+ // Go to the page of the match
+ await viewer.scrollTo({
+ pageNumber: location.pageIndex,
+ yPos: 0,
+ });
+
+ // Save the current scroll position to restore after search
+ const currentScrollTop = viewer.container().scrollTop;
+ const currentScrollLeft = viewer.container().scrollLeft;
+
+ // Pre-warm text extraction for just the target page
+ const findController = viewer.findController;
+ const pageIdx = location.pageIndex - 1; // Convert to 0-indexed
+
+ await findController.warmSearchTextForPage(pageIdx);
+
+ // Use the snippet to find the location in the PDF
+ viewer.search({
+ query: location.snippet,
+ again: false,
+ phraseSearch: true,
+ caseSensitive: true,
+ entireWord: false,
+ highlightAll: false,
+ findPrevious: false,
+ });
+
+ // Wait for the find controller to be ready
+ const findControllerStateEvent = await waitForSignal(
+ findControllerStateEventSignal,
+ (val) =>
+ val?.state === FindState.FOUND ||
+ val?.state === FindState.NOT_FOUND,
+ 10000
+ ).catch((_e) => {
+ console.error('search timed out');
+ return undefined;
+ });
+
+ if (!findControllerStateEvent) {
+ return;
+ }
+
+ // Break early if we can't find the match
+ if (findControllerStateEvent.state === FindState.NOT_FOUND) {
+ console.warn('unable to find match', { location });
+ // TODO: fallback to raw query
+ return;
+ }
+
+ viewer.container().scrollTop = currentScrollTop;
+ viewer.container().scrollLeft = currentScrollLeft;
+
+ if (
+ !findController._selected ||
+ !findController._pageMatches ||
+ !findController._pageMatchesLength
+ ) {
+ console.error('FindController state is incomplete');
+ return;
+ }
+
+ const snippetMatchIdx = findController._selected.matchIdx;
+ const snippetStartPos =
+ findController._pageMatches[pageIdx]?.[snippetMatchIdx];
+ const snippetLength =
+ findController._pageMatchesLength[pageIdx]?.[snippetMatchIdx];
+
+ if (snippetStartPos === undefined || snippetLength === undefined) {
+ console.error('Could not find snippet position');
+ return;
+ }
+
+ const snippetEndPos = snippetStartPos + snippetLength;
+
+ // Clear the snippet search highlights without resetting state
+ // This preserves the findController's ability to emit events
+ findController._highlightMatches = false;
+ findController._updatePage(pageIdx);
+
+ // Apply custom highlights based on macro_em tags
+ await applyCustomHighlights(
+ viewer,
+ currentScrollTop,
+ currentScrollLeft,
+ findController,
+ findControllerStateEventSignal,
+ pageIdx,
+ location.highlightTerms,
+ snippetStartPos,
+ snippetEndPos
+ );
+
+ // Trigger full extraction in the background immediately
+ findController.forceFullExtraction();
+
+ // resets the highlight after a short delay
+ return new Promise((resolve) => {
+ setTimeout(() => {
+ viewer.findBarClose();
+ resolve();
+ }, 2000);
+ });
+ }
+ };
- switch (location.type) {
- case 'general':
- await viewer.scrollTo({
- pageNumber: location.pageIndex,
- yPos: location.y,
- });
- break;
- case 'precise':
- await viewer.scrollTo({
- pageNumber: location.pageIndex,
- yPos: location.y,
- });
- viewer.generateOverlayForSelectionRect(location.pageIndex - 1, location);
- break;
- case 'annotation':
- //TODO: @synoet @gbirman
- // once macrotations are implemented, this should be changed to
- // properly port over gotoMacrotation
- await viewer.scrollTo({
- pageNumber: location.pageIndex,
- yPos: 0,
- });
- break;
- case 'search':
- // Go to the page of the match
- // We need to scroll to the top of the page with the search result to ensure we can go to the correct search match relative to the page
- await viewer.scrollTo({
- pageNumber: location.pageIndex,
- yPos: 0,
- });
-
- // Perform initial search to goto the first match for the page
- viewer.search({
- query: location.term,
- again: false, // set type to ''
- phraseSearch: true,
- caseSensitive: false,
- entireWord: false,
- highlightAll: false, // we only want to highlight the actual match
- findPrevious: false,
- });
-
- // Wait for the find controller to be ready
- const findControllerStateEvent = await waitForSignal(
- findControlelrStateEventSignal,
- // NOTE: if we run into a race condition where find controller is not cleared a cleaner solution would be to set updateFindControlStateSignal to
- // undefined before you call hidden search then wait for search state to update
- (val) =>
- val?.state === FindState.FOUND || val?.state === FindState.NOT_FOUND
- );
+ return async (location: PdfLocation) => {
+ if (location.type === 'search') {
+ setSearchLocationPending(true);
+ await go(location);
+ setSearchLocationPending(false);
+ return;
+ }
- // Break early if we can't find the match
- if (findControllerStateEvent?.state === FindState.NOT_FOUND) {
- console.warn('unable to find match', { location });
- break;
- }
+ go(location);
+ };
+}
- // Since we have a FOUND state, we can jump to the correct match
- for (let i = 0; i < location.matchNum; i++) {
- findControllerStateEvent?.source._nextMatch();
- }
+const useGoToPreviousLocation = () => {
+ const getViewer = useGetRootViewer();
+ const getViewLocation = pdfViewLocation.get;
- break;
- }
-}
+ return async () => {
+ const viewer = getViewer();
-export async function goToLinkLocationFromSearchParams(
- searchPage: string,
- searchMatchNumOnPage: string,
- searchTerm: string
-) {
- const location = {
- type: 'search',
- pageIndex: Number(searchPage) + 1,
- matchNum: Number(searchMatchNumOnPage),
- term: searchTerm,
- } as PdfLocation;
-
- if (location) {
- return await goToPdfLocation(location);
- }
-}
+ await waitForSignal(getViewLocation, (location) => !!location, 300).then(
+ (prevLocationHash) => {
+ if (viewer && prevLocationHash) {
+ viewer.goToLocationHash(prevLocationHash);
+ }
+ }
+ );
+ };
+};
/**
* Go to the location in the pdf viewer based on the current url
*/
-export async function goToLinkLocation(params: LocationSearchParams) {
- //const params = makeLocationSearchParams(searchParams);
- const location = parseLocationFromUrl(params);
- if (location) {
- return await goToPdfLocation(location);
- }
+export function useGoToLinkLocation() {
+ const goToPreviousLocation = useGoToPreviousLocation();
+ const goToPdfLocation = useGoToPdfLocation();
+
+ return async (params: LocationSearchParams) => {
+ const location = parseLocationFromUrl(params);
+ if (location) {
+ await goToPdfLocation(location);
+ return;
+ }
- const getViewer = useGetRootViewer();
- const viewer = getViewer();
- // TODO: this should be a hook?
- const prevLocationHash = pdfViewLocation();
- if (viewer && prevLocationHash) {
- viewer.goToLocationHash(prevLocationHash);
- }
+ await goToPreviousLocation();
+ };
}
/**
* Go to the location in the pdf viewer based on the params
*/
-export async function goToLinkLocationFromParams(
- params: Record<string, string>
-) {
- console.log(' go to link location, ', params);
- const location = parseLocationFromBlockParams(params);
- console.log({ location });
- if (location) {
- return await goToPdfLocation(location);
- }
+export function useGoToLinkLocationFromParams() {
+ const goToPreviousLocation = useGoToPreviousLocation();
+ const goToPdfLocation = useGoToPdfLocation();
+
+ return async (params: LocationBlockParams) => {
+ const location = parseLocationFromBlockParams(params);
+ if (location) {
+ await goToPdfLocation(location);
+ return;
+ }
- const getViewer = useGetRootViewer();
- const viewer = getViewer();
- // TODO: this should be a hook?
- const prevLocationHash = pdfViewLocation();
- if (viewer && prevLocationHash) {
- viewer.goToLocationHash(prevLocationHash);
- }
+ await goToPreviousLocation();
+ };
}
diff --git a/js/app/packages/block-pdf/signal/pdfViewer.tsx b/js/app/packages/block-pdf/signal/pdfViewer.tsx
index 233f7eceac..5bbbaea115 100644
--- a/js/app/packages/block-pdf/signal/pdfViewer.tsx
+++ b/js/app/packages/block-pdf/signal/pdfViewer.tsx
@@ -258,12 +258,13 @@ export const useOverlayViewsChanged = () => {
isPopup ? overlayViewsChangedPopupSignal_() : overlayViewsChangedSignal_();
};
-// /** Indicates that at least one page is visible */
-export const viewerHasVisiblePagesSignal = createBlockMemo(() => {
+export const viewerHasVisiblePagesSignal = createBlockSignal<boolean>(false);
+
+createBlockEffect(() => {
const visiblePages = visiblePagesChangedSignal()?.visiblePages;
const loadedIds = visiblePages?.ids;
- if (!loadedIds) return false;
- return loadedIds.size > 0;
+ const hasVisiblePages = loadedIds ? loadedIds.size > 0 : false;
+ viewerHasVisiblePagesSignal.set(hasVisiblePages);
});
// /** Indicates that all pages have been loaded */
diff --git a/js/app/packages/block-pdf/signal/search.ts b/js/app/packages/block-pdf/signal/search.ts
index 5065b8b6db..9b3128765b 100644
--- a/js/app/packages/block-pdf/signal/search.ts
+++ b/js/app/packages/block-pdf/signal/search.ts
@@ -248,9 +248,9 @@ export function useJumpToResult() {
};
}
-export function useSearchReset() {
+export function useSearchClose() {
const getRootViewer = useGetRootViewer();
return () => {
- getRootViewer()?.resetSearch();
+ getRootViewer()?.findBarClose();
};
}
diff --git a/js/app/packages/core/util/searchHighlight.ts b/js/app/packages/core/util/searchHighlight.ts
new file mode 100644
index 0000000000..00f76d5d6c
--- /dev/null
+++ b/js/app/packages/core/util/searchHighlight.ts
@@ -0,0 +1,44 @@
+/**
+ * Utilities for extracting information from search highlight content
+ * that contains <macro_em> tags marking matched terms.
+ */
+
+/**
+ * Extracts terms from macro_em tags in the highlighted content.
+ * Returns array of text strings that should be highlighted, preserving order and duplicates.
+ *
+ * @param highlightedContent - Content with <macro_em> tags marking matches
+ * @returns Array of matched terms
+ *
+ * @example
+ * extractSearchTerms("The <macro_em>quick</macro_em> brown <macro_em>fox</macro_em>")
+ * // Returns: ["quick", "fox"]
+ */
+export function extractSearchTerms(highlightedContent: string): string[] {
+ const terms: string[] = [];
+ const macroEmRegex = /<macro_em>(.*?)<\/macro_em>/gs;
+ const matches = Array.from(highlightedContent.matchAll(macroEmRegex));
+
+ for (const match of matches) {
+ terms.push(match[1].trim());
+ }
+
+ return terms;
+}
+
+/**
+ * Extracts the full snippet from highlighted content by removing macro_em tags.
+ * Whitespace is normalized and trimmed.
+ * This provides context for the search result.
+ *
+ * @param highlightedContent - Content with <macro_em> tags marking matches
+ * @returns Clean text snippet with normalized whitespace
+ *
+ * @example
+ * extractSearchSnippet("The <macro_em>quick</macro_em>\n brown fox")
+ * // Returns: "The quick brown fox"
+ */
+export function extractSearchSnippet(highlightedContent: string): string {
+ const rawContent = highlightedContent.replace(/<\/?macro_em>/g, '');
+ return rawContent.replace(/\s+/g, ' ').trim();
+}
diff --git a/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx b/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx
index 7d2409495d..6598c41154 100644
--- a/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx
+++ b/js/app/packages/macro-entity/src/components/EntityWithEverything.tsx
@@ -510,7 +510,7 @@ export function EntityWithEverything(
{(highlight) => (
<div class="text-sm text-ink-muted truncate flex items-center">
<StaticMarkdown
- markdown={highlight}
+ markdown={highlight.content}
theme={unifiedListMarkdownTheme}
singleLine={true}
/>
diff --git a/js/app/packages/macro-entity/src/queries/search.ts b/js/app/packages/macro-entity/src/queries/search.ts
index f1eea463e2..86c2716bc9 100644
--- a/js/app/packages/macro-entity/src/queries/search.ts
+++ b/js/app/packages/macro-entity/src/queries/search.ts
@@ -1,6 +1,10 @@
import { useChannelsContext } from '@core/component/ChannelsProvider';
import { ENABLE_SEARCH_SERVICE } from '@core/constant/featureFlags';
import { isErr } from '@core/util/maybeResult';
+import {
+ extractSearchSnippet,
+ extractSearchTerms,
+} from '@core/util/searchHighlight';
import type { ChannelType } from '@service-comms/generated/models';
import { type PaginatedSearchArgs, searchClient } from '@service-search/client';
import type {
@@ -15,7 +19,11 @@ 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 {
+ FileTypeWithLocation,
+ SearchLocation,
+ WithSearch,
+} from '../types/search';
import type { EntityInfiniteQuery } from './entity';
import { queryKeys } from './key';
@@ -28,10 +36,64 @@ type InnerSearchResult =
| ChannelSearchResult
| ProjectSearchResult;
+const getLocationHighlights = (
+ innerResults: DocumentSearchResult[],
+ fileType: FileTypeWithLocation,
+ searchQuery: string
+) => {
+ const contentHighlights = innerResults.flatMap((r) => {
+ const contents = r.highlight.content ?? [];
+
+ return contents.map((content) => {
+ let location: SearchLocation | undefined;
+ switch (fileType) {
+ case 'md':
+ location = { type: 'md' as const, nodeId: r.node_id };
+ break;
+ case 'pdf':
+ try {
+ const searchPage = parseInt(r.node_id);
+ location = {
+ type: 'pdf' as const,
+ searchPage,
+ searchSnippet: extractSearchSnippet(content),
+ searchRawQuery: searchQuery,
+ highlightTerms: extractSearchTerms(content),
+ };
+ } catch (_e) {
+ console.error('Cannot parse pdf serach info', r);
+ location = undefined;
+ }
+ break;
+ }
+
+ return {
+ content,
+ location,
+ };
+ });
+ });
+
+ return {
+ nameHighlight: innerResults.at(0)?.highlight.name ?? null,
+ contentHighlights: contentHighlights.length > 0 ? contentHighlights : null,
+ source: 'service' as const,
+ };
+};
+
const getHighlights = (innerResults: InnerSearchResult[]) => {
+ const contentHighlights = innerResults.flatMap((r) => {
+ const contents = r.highlight.content ?? [];
+
+ return contents.map((content) => ({
+ content,
+ location: undefined,
+ }));
+ });
+
return {
nameHighlight: innerResults.at(0)?.highlight.name ?? null,
- contentHighlights: innerResults.flatMap((r) => r.highlight.content ?? []),
+ contentHighlights: contentHighlights.length > 0 ? contentHighlights : null,
source: 'service' as const,
};
};
@@ -42,11 +104,22 @@ const useMapSearchResponseItem = () => {
const history = useHistory();
- return (result: UnifiedSearchResponseItem): Entity | undefined => {
+ return (
+ result: UnifiedSearchResponseItem,
+ searchQuery: string
+ ): Entity | undefined => {
switch (result.type) {
case 'document': {
if (!result.metadata || result.metadata.deleted_at) return;
- const search = getHighlights(result.document_search_results);
+ const searchFileType =
+ result.file_type === 'docx' ? 'pdf' : result.file_type;
+ const search = ['md', 'pdf'].includes(searchFileType)
+ ? getLocationHighlights(
+ result.document_search_results,
+ searchFileType as FileTypeWithLocation,
+ searchQuery
+ )
+ : getHighlights(result.document_search_results);
return {
type: 'document',
id: result.document_id,
@@ -228,12 +301,14 @@ export function createUnifiedSearchInfiniteQuery(
page: lastPageParam.page + 1,
};
},
- select: (data) =>
- data.pages.flatMap((page) =>
+ select: (data) => {
+ const searchQuery = terms()[0];
+ return data.pages.flatMap((page) =>
page.results
- .map(mapSearchResponseItem)
+ .map((result) => mapSearchResponseItem(result, searchQuery))
.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
index d11ac06863..b952e51a54 100644
--- a/js/app/packages/macro-entity/src/types/search.ts
+++ b/js/app/packages/macro-entity/src/types/search.ts
@@ -1,7 +1,29 @@
+type MarkdownHighlightLocation = {
+ type: 'md';
+ nodeId: string;
+};
+
+type PdfHighlightLocation = {
+ type: 'pdf';
+ searchPage: number;
+ highlightTerms: string[];
+ searchSnippet: string;
+ searchRawQuery: string;
+};
+
+export type FileTypeWithLocation = 'md' | 'pdf';
+
+export type SearchLocation = MarkdownHighlightLocation | PdfHighlightLocation;
+
+type ContentHighlight = {
+ content: string;
+ location?: SearchLocation;
+};
+
export type WithSearch<T extends object> = T & {
search: {
nameHighlight: string | null;
- contentHighlights: string[] | null;
+ contentHighlights: ContentHighlight[] | null;
source: 'local' | 'service';
};
};