From 63a4a98384db0ea9fd4990584b082dce35cc56cd Mon Sep 17 00:00:00 2001 From: Peter White <1788320+peterwhite@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:28:04 +0100 Subject: [PATCH] Track the clicked position in site search (#4823) --- .changeset/search-click-rank.md | 5 +++ .../[siteData]/~gitbook/search/route.ts | 4 +- .../Embeddable/EmbeddableSearch.tsx | 9 +++-- .../Search/SearchPageResultItem.tsx | 12 ++++-- .../Search/SearchRecordResultItem.tsx | 26 +++++++----- .../src/components/Search/SearchResults.tsx | 4 ++ .../src/components/Search/filter.test.ts | 26 ++++++++++-- .../gitbook/src/components/Search/filter.ts | 33 ++++++++------- .../components/Search/search-pass-store.ts | 5 ++- .../src/components/Search/search-types.ts | 5 +++ .../src/components/Search/useSearchResults.ts | 40 ++++++++++++++----- packages/gitbook/src/lib/data/api.ts | 19 ++------- packages/gitbook/src/lib/data/types.ts | 1 + packages/gitbook/src/lib/search-results.ts | 6 ++- 14 files changed, 128 insertions(+), 67 deletions(-) create mode 100644 .changeset/search-click-rank.md diff --git a/.changeset/search-click-rank.md b/.changeset/search-click-rank.md new file mode 100644 index 000000000..24404212e --- /dev/null +++ b/.changeset/search-click-rank.md @@ -0,0 +1,5 @@ +--- +"gitbook": patch +--- + +Track the displayed position and search request ID when a visitor opens a search result. diff --git a/packages/gitbook/src/app/sites/dynamic/[mode]/[siteURL]/[siteData]/~gitbook/search/route.ts b/packages/gitbook/src/app/sites/dynamic/[mode]/[siteURL]/[siteData]/~gitbook/search/route.ts index b11980156..540279cc7 100644 --- a/packages/gitbook/src/app/sites/dynamic/[mode]/[siteURL]/[siteData]/~gitbook/search/route.ts +++ b/packages/gitbook/src/app/sites/dynamic/[mode]/[siteURL]/[siteData]/~gitbook/search/route.ts @@ -14,7 +14,8 @@ const SEARCH_FALLBACK_REASON = /^(\d{3}|expired|pass_request|network|timeout|invalid|unknown_space)$/; export async function POST(request: NextRequest) { - const { asEmbeddable, query, scope } = (await request.json()) as SearchSiteContentRequest; + const { asEmbeddable, query, scope, searchId } = + (await request.json()) as SearchSiteContentRequest; const [context, siteURLData] = await Promise.all([ getServerActionBaseContext({ isEmbeddable: asEmbeddable }), getSiteURLDataFromMiddleware(), @@ -40,6 +41,7 @@ export async function POST(request: NextRequest) { siteId: siteURLData.site, query, scope, + searchId, }) ), throwIfDataError( diff --git a/packages/gitbook/src/components/Embeddable/EmbeddableSearch.tsx b/packages/gitbook/src/components/Embeddable/EmbeddableSearch.tsx index cc8552955..e2f74e9b2 100644 --- a/packages/gitbook/src/components/Embeddable/EmbeddableSearch.tsx +++ b/packages/gitbook/src/components/Embeddable/EmbeddableSearch.tsx @@ -2,6 +2,8 @@ import React from 'react'; +import { SiteInsightsDisplayContext } from '@gitbook/api'; + import { useTrackEvent } from '../Insights'; import { LinkContext } from '../primitives'; import { useIsVisible } from '../VisibilityContext'; @@ -37,9 +39,10 @@ export function EmbeddableSearch(props: EmbeddableSearchProps) { return; } - trackEvent({ - type: 'search_open', - }); + trackEvent( + { type: 'search_open' }, + { pageId: null, displayContext: SiteInsightsDisplayContext.Embed } + ); }, [trackEvent, isVisible]); const tabsRef = React.useRef(null); diff --git a/packages/gitbook/src/components/Search/SearchPageResultItem.tsx b/packages/gitbook/src/components/Search/SearchPageResultItem.tsx index 6e35412f1..a9d1224ae 100644 --- a/packages/gitbook/src/components/Search/SearchPageResultItem.tsx +++ b/packages/gitbook/src/components/Search/SearchPageResultItem.tsx @@ -6,7 +6,7 @@ import { useResizeObserver } from '../hooks'; import { Tooltip } from '../primitives'; import { getPageResultPresentation } from './getPageResultHref'; import { HighlightQuery } from './HighlightQuery'; -import type { ComputedPageResult } from './search-types'; +import type { ComputedPageResult, SearchResultSource } from './search-types'; import { SearchResultItem } from './SearchResultItem'; import { tString, useLanguage } from '@/intl/client'; import { tcls } from '@/lib/tailwind'; @@ -14,13 +14,15 @@ import { tcls } from '@/lib/tailwind'; export const SearchPageResultItem = React.forwardRef(function SearchPageResultItem( props: { query: string; - item: ComputedPageResult; + item: ComputedPageResult & SearchResultSource; + position: number; + resultsCount: number; active: boolean; style?: React.CSSProperties; }, ref: React.Ref ) { - const { query, item, active, style, ...rest } = props; + const { query, item, active, position, resultsCount, style, ...rest } = props; const language = useLanguage(); const { preview: bestSection, description, href } = getPageResultPresentation(item); @@ -30,7 +32,9 @@ export const SearchPageResultItem = React.forwardRef(function SearchPageResultIt const insights = { type: 'search_open_result' as const, - query, + ...item.search, + position, + resultsCount, result: { pageId: item.pageId, spaceId: item.spaceId, diff --git a/packages/gitbook/src/components/Search/SearchRecordResultItem.tsx b/packages/gitbook/src/components/Search/SearchRecordResultItem.tsx index 3b7eb4798..b83fe7973 100644 --- a/packages/gitbook/src/components/Search/SearchRecordResultItem.tsx +++ b/packages/gitbook/src/components/Search/SearchRecordResultItem.tsx @@ -4,24 +4,36 @@ import { Icon } from '@gitbook/icons'; import { Favicon } from '../utils'; import { HighlightQuery } from './HighlightQuery'; -import type { ComputedRecordResult } from './search-types'; +import type { ComputedRecordResult, SearchResultSource } from './search-types'; import { SearchResultItem } from './SearchResultItem'; import { tString, useLanguage } from '@/intl/client'; export const SearchRecordResultItem = React.forwardRef(function SearchRecordResultItem( props: { query: string; - item: ComputedRecordResult; + item: ComputedRecordResult & SearchResultSource; + position: number; + resultsCount: number; active: boolean; style?: React.CSSProperties; }, ref: React.Ref ) { - const { query, item, active, style, ...rest } = props; + const { query, item, active, position, resultsCount, style, ...rest } = props; const language = useLanguage(); const domain = getDomain(item.href); + const insights = { + type: 'search_open_result' as const, + ...item.search, + position, + resultsCount, + result: { + recordId: item.id, + }, + }; + return ( } /> } - insights={{ - type: 'search_open_result', - query, - result: { - recordId: item.id, - }, - }} + insights={insights} aria-label={tString(language, 'search_page_result_title', item.title)} style={{ ...style }} {...rest} diff --git a/packages/gitbook/src/components/Search/SearchResults.tsx b/packages/gitbook/src/components/Search/SearchResults.tsx index 4b2e9a140..2f921f09b 100644 --- a/packages/gitbook/src/components/Search/SearchResults.tsx +++ b/packages/gitbook/src/components/Search/SearchResults.tsx @@ -271,6 +271,8 @@ export const SearchResults = React.forwardRef(function SearchResults( }} query={query} item={item} + position={index + 1} + resultsCount={results.length} active={index === cursor} style={{ animationDelay: `${index * 25}ms,${100 + index * 25}ms`, @@ -340,6 +342,8 @@ export const SearchResults = React.forwardRef(function SearchResults( key={itemKey} query={query} item={item} + position={index + 1} + resultsCount={results.length} active={index === cursor} style={{ animationDelay: `${index * 25}ms,${100 + index * 25}ms`, diff --git a/packages/gitbook/src/components/Search/filter.test.ts b/packages/gitbook/src/components/Search/filter.test.ts index 56594b23b..94d88819e 100644 --- a/packages/gitbook/src/components/Search/filter.test.ts +++ b/packages/gitbook/src/components/Search/filter.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'bun:test'; -import { computeFilterSiteSpaceIds, filterResultsBySiteSpaces } from './filter'; +import { computeFilterSiteSpaceIds, getDisplayedSearchResults } from './filter'; import type { OrderedComputedResult } from './search-types'; describe('computeFilterSiteSpaceIds', () => { @@ -36,7 +36,7 @@ describe('computeFilterSiteSpaceIds', () => { }); }); -describe('filterResultsBySiteSpaces', () => { +describe('getDisplayedSearchResults', () => { const page = (id: string, siteSpaceId?: string): OrderedComputedResult => ({ type: 'page', id, @@ -52,7 +52,7 @@ describe('filterResultsBySiteSpaces', () => { it('keeps the server order and drops pages outside the scope', () => { const results = [page('a', 'current'), page('b', 'other'), page('c', 'current'), page('d')]; - expect(filterResultsBySiteSpaces(results, ['current']).map((result) => result.id)).toEqual([ + expect(getDisplayedSearchResults(results, ['current']).map((result) => result.id)).toEqual([ 'a', 'c', ]); @@ -60,6 +60,24 @@ describe('filterResultsBySiteSpaces', () => { it('returns every result when the scope is unrestricted', () => { const results = [page('b', 'other'), page('a', 'current')]; - expect(filterResultsBySiteSpaces(results, undefined)).toBe(results); + expect(getDisplayedSearchResults(results, undefined)).toBe(results); + }); + + it('caps the displayed list after applying the site space filter', () => { + const pages = Array.from({ length: 10 }, (_, index) => page(`page-${index}`, 'current')); + const records = Array.from({ length: 11 }, (_, index): OrderedComputedResult => ({ + type: 'record', + id: `record-${index}`, + title: `Record ${index}`, + description: undefined, + href: `/record-${index}`, + score: 1, + })); + const results = [page('hidden', 'other'), ...pages, ...records]; + + expect(getDisplayedSearchResults(results, ['current'])).toEqual([ + ...pages, + ...records.slice(0, 10), + ]); }); }); diff --git a/packages/gitbook/src/components/Search/filter.ts b/packages/gitbook/src/components/Search/filter.ts index 4ffacef22..c52abae0e 100644 --- a/packages/gitbook/src/components/Search/filter.ts +++ b/packages/gitbook/src/components/Search/filter.ts @@ -1,6 +1,9 @@ import type { OrderedComputedResult } from './search-types'; import type { SearchScope } from './useSearch'; +// Keep aligned with SiteInsightsSearchResultNumber in the GitBook API schema. +const MAX_DISPLAYED_SEARCH_RESULTS = 20; + /** * Site spaces whose pages may be shown for a UI search scope, or `undefined` for no restriction. * @@ -29,20 +32,20 @@ export function computeFilterSiteSpaceIds( } } -/** Keep the server's order, dropping pages owned by a site space outside the scope. */ -export function filterResultsBySiteSpaces( - results: OrderedComputedResult[], +/** Keep the first results in server order within the selected site spaces. */ +export function getDisplayedSearchResults( + results: Result[], allowedSiteSpaceIds: string[] | undefined -): OrderedComputedResult[] { - if (!allowedSiteSpaceIds) { - return results; - } - - const allowed = new Set(allowedSiteSpaceIds); - - return results.filter( - (result) => - result.type === 'record' || - (result.siteSpaceId !== undefined && allowed.has(result.siteSpaceId)) - ); +): Result[] { + const allowed = allowedSiteSpaceIds && new Set(allowedSiteSpaceIds); + const matching = allowed + ? results.filter( + (result) => + result.type === 'record' || + (result.siteSpaceId !== undefined && allowed.has(result.siteSpaceId)) + ) + : results; + return matching.length > MAX_DISPLAYED_SEARCH_RESULTS + ? matching.slice(0, MAX_DISPLAYED_SEARCH_RESULTS) + : matching; } diff --git a/packages/gitbook/src/components/Search/search-pass-store.ts b/packages/gitbook/src/components/Search/search-pass-store.ts index 58ff025e3..9a10b2e65 100644 --- a/packages/gitbook/src/components/Search/search-pass-store.ts +++ b/packages/gitbook/src/components/Search/search-pass-store.ts @@ -124,11 +124,12 @@ export function createSearchPassStore(directSearch: DirectSearchProps | undefine const search = async (input: { query: string; + searchId?: string; scope: SearchSiteContentScope; signal: AbortSignal; asEmbeddable: boolean; }): Promise => { - const { query, scope, signal, asEmbeddable } = input; + const { query, searchId, scope, signal, asEmbeddable } = input; if (!directSearch) { return { type: 'route' }; } @@ -163,7 +164,7 @@ export function createSearchPassStore(directSearch: DirectSearchProps | undefine Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', }, - body: JSON.stringify(toSearchSiteContentBody(query, scope)), + body: JSON.stringify(toSearchSiteContentBody(query, scope, searchId)), credentials: 'omit', signal: request.signal, }); diff --git a/packages/gitbook/src/components/Search/search-types.ts b/packages/gitbook/src/components/Search/search-types.ts index dfdb36faf..238b9b75d 100644 --- a/packages/gitbook/src/components/Search/search-types.ts +++ b/packages/gitbook/src/components/Search/search-types.ts @@ -2,6 +2,10 @@ import type { IconName } from '@gitbook/icons'; export type OrderedComputedResult = ComputedPageResult | ComputedRecordResult; +export type SearchResultSource = { + search: { query: string; searchId: string | undefined }; +}; + export type BaseComputedResult = { id: string; title: string; @@ -55,6 +59,7 @@ export type SearchSiteContentScope = export interface SearchSiteContentRequest { asEmbeddable?: boolean; + searchId?: string; query: string; scope: SearchSiteContentScope; } diff --git a/packages/gitbook/src/components/Search/useSearchResults.ts b/packages/gitbook/src/components/Search/useSearchResults.ts index 3ae5f8373..5bc460b09 100644 --- a/packages/gitbook/src/components/Search/useSearchResults.ts +++ b/packages/gitbook/src/components/Search/useSearchResults.ts @@ -8,21 +8,29 @@ import { createRecommendedQuestionResult, getEmptySearchResults, } from './empty-search-results'; -import { computeFilterSiteSpaceIds, filterResultsBySiteSpaces } from './filter'; +import { computeFilterSiteSpaceIds, getDisplayedSearchResults } from './filter'; import { useRecentSearchQueries } from './recent-queries'; import { computeRemoteSearchScope } from './remote-scope'; import { SEARCH_FALLBACK_HEADER, type SearchPassStore } from './search-pass-store'; -import type { OrderedComputedResult, SearchSiteContentScope } from './search-types'; +import type { + OrderedComputedResult, + SearchResultSource, + SearchSiteContentScope, +} from './search-types'; import { streamRecommendedQuestions } from './server-actions'; import { type SearchScope, useSearchPass } from './useSearch'; import { useAI } from '@/components/AI'; -export type ResultType = OrderedComputedResult | RecommendedQuestionResult; +export type ResultType = RemoteSearchResult | RecommendedQuestionResult; + +const SEARCH_ID_BYTES = 16; + +type RemoteSearchResult = OrderedComputedResult & SearchResultSource; type SearchAnswer = { scopeKey: string; query: string; - results: OrderedComputedResult[]; + results: RemoteSearchResult[]; }; type RemoteSearchState = @@ -199,7 +207,7 @@ export function useSearchResults(props: { flushRef.current = null; const fetchSearch = ( scope: Parameters[1] - ): Promise => + ): Promise => fetchSearchResults( searchURL, scope, @@ -212,7 +220,7 @@ export function useSearchResults(props: { try { const resultsPromise = fetchSearch(remoteScope); - const onResults = (results: OrderedComputedResult[]) => { + const onResults = (results: RemoteSearchResult[]) => { if (cancelled) { return; } @@ -328,7 +336,7 @@ export function useSearchResults(props: { } return visibleAnswer - ? filterResultsBySiteSpaces(visibleAnswer.results, filterSiteSpaceIds) + ? getDisplayedSearchResults(visibleAnswer.results, filterSiteSpaceIds) : []; }, [ visibleAnswer, @@ -369,17 +377,21 @@ async function fetchSearchResults( signal: AbortSignal, asEmbeddable: boolean | undefined, searchPass: SearchPassStore | null -): Promise { +): Promise { + const directSearchId = generateSearchId(); const direct = await searchPass?.search({ query, + searchId: directSearchId, scope, signal, asEmbeddable: Boolean(asEmbeddable), }); if (direct?.type === 'results') { - return direct.results; + const search = { query, searchId: directSearchId }; + return direct.results.map((result) => ({ ...result, search })); } + const searchId = direct ? generateSearchId() : directSearchId; const response = await fetch(searchURL, { method: 'POST', headers: { @@ -389,6 +401,7 @@ async function fetchSearchResults( body: JSON.stringify({ asEmbeddable, query, + searchId, scope, }), signal, @@ -398,5 +411,12 @@ async function fetchSearchResults( throw new Error(`Search request failed: ${response.status}`); } - return response.json() as Promise; + const results: OrderedComputedResult[] = await response.json(); + const search = { query, searchId }; + return results.map((result) => ({ ...result, search })); +} + +function generateSearchId() { + const bytes = globalThis.crypto?.getRandomValues(new Uint8Array(SEARCH_ID_BYTES)); + return bytes && Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join(''); } diff --git a/packages/gitbook/src/lib/data/api.ts b/packages/gitbook/src/lib/data/api.ts index e8e9f3382..09f90bcbf 100644 --- a/packages/gitbook/src/lib/data/api.ts +++ b/packages/gitbook/src/lib/data/api.ts @@ -6,7 +6,6 @@ import { GitBookAPI, type HttpResponse, type RenderIntegrationUI, - type SiteSearchScope, } from '@gitbook/api'; import { getCacheTag, getComputedContentSourceCacheTags } from '@gitbook/cache-tags'; @@ -14,6 +13,7 @@ import { cache } from '../cache'; import { DataFetcherError, wrapDataFetcherError } from './errors'; import type { GitBookDataFetcher } from './types'; import { GITBOOK_API_TOKEN, GITBOOK_API_URL, GITBOOK_USER_AGENT } from '@/lib/env'; +import { toSearchSiteContentBody } from '@/lib/search-results'; import { trace } from '@/lib/tracing'; interface DataFetcherInput { @@ -793,25 +793,12 @@ async function searchSiteContent( return trace( `searchSiteContent(${params.organizationId}, ${params.siteId}, ${params.query})`, async () => { - const { organizationId, siteId, query, scope } = params; + const { organizationId, siteId, query, scope, searchId } = params; const api = apiClient(input); const res = await api.orgs.searchSiteContent( organizationId, siteId, - { - query, - ...(scope.mode === 'current' && scope.restrictTo - ? { - // `restrictTo` only exists in the newer `scope` request shape, - // and the published @gitbook/api types don't include it yet. - scope: { - mode: 'default', - currentSiteSpace: scope.siteSpaceId, - restrictTo: scope.restrictTo, - } as SiteSearchScope, - } - : scope), - }, + toSearchSiteContentBody(query, scope, searchId), {}, { ...noCacheFetchOptions, diff --git a/packages/gitbook/src/lib/data/types.ts b/packages/gitbook/src/lib/data/types.ts index 203b3cbbd..0a77b43c4 100644 --- a/packages/gitbook/src/lib/data/types.ts +++ b/packages/gitbook/src/lib/data/types.ts @@ -180,6 +180,7 @@ export interface GitBookDataFetcher { organizationId: string; siteId: string; query: string; + searchId?: string; scope: | { mode: 'all' } | { diff --git a/packages/gitbook/src/lib/search-results.ts b/packages/gitbook/src/lib/search-results.ts index 966f49baf..75ba2cae1 100644 --- a/packages/gitbook/src/lib/search-results.ts +++ b/packages/gitbook/src/lib/search-results.ts @@ -52,10 +52,12 @@ export type DirectSearchProps = { */ export function toSearchSiteContentBody( query: string, - scope: SearchSiteContentScope -): Parameters[2] { + scope: SearchSiteContentScope, + searchId?: string +): Parameters[2] & { searchId?: string } { return { query, + searchId, ...(scope.mode === 'current' && scope.restrictTo ? { // `restrictTo` only exists in the newer `scope` request shape,