mirror of
https://github.com/GitbookIO/gitbook.git
synced 2026-11-24 09:12:05 +00:00
Track the clicked position in site search (#4823)
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Track the displayed position and search request ID when a visitor opens a search result.
|
||||
+3
-1
@@ -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(
|
||||
|
||||
@@ -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<HTMLDivElement>(null);
|
||||
|
||||
@@ -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<HTMLAnchorElement>
|
||||
) {
|
||||
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,
|
||||
|
||||
@@ -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<HTMLAnchorElement>
|
||||
) {
|
||||
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 (
|
||||
<SearchResultItem
|
||||
ref={ref}
|
||||
@@ -36,13 +48,7 @@ export const SearchRecordResultItem = React.forwardRef(function SearchRecordResu
|
||||
fallback={<Icon icon="memo" className="size-4" />}
|
||||
/>
|
||||
}
|
||||
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}
|
||||
|
||||
@@ -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`,
|
||||
|
||||
@@ -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),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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<Result extends OrderedComputedResult>(
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -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<DirectSearchOutcome> => {
|
||||
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,
|
||||
});
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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<typeof fetchSearchResults>[1]
|
||||
): Promise<OrderedComputedResult[]> =>
|
||||
): Promise<RemoteSearchResult[]> =>
|
||||
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<OrderedComputedResult[]> {
|
||||
): Promise<RemoteSearchResult[]> {
|
||||
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<OrderedComputedResult[]>;
|
||||
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('');
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -180,6 +180,7 @@ export interface GitBookDataFetcher {
|
||||
organizationId: string;
|
||||
siteId: string;
|
||||
query: string;
|
||||
searchId?: string;
|
||||
scope:
|
||||
| { mode: 'all' }
|
||||
| {
|
||||
|
||||
@@ -52,10 +52,12 @@ export type DirectSearchProps = {
|
||||
*/
|
||||
export function toSearchSiteContentBody(
|
||||
query: string,
|
||||
scope: SearchSiteContentScope
|
||||
): Parameters<GitBookAPI['orgs']['searchSiteContent']>[2] {
|
||||
scope: SearchSiteContentScope,
|
||||
searchId?: string
|
||||
): Parameters<GitBookAPI['orgs']['searchSiteContent']>[2] & { searchId?: string } {
|
||||
return {
|
||||
query,
|
||||
searchId,
|
||||
...(scope.mode === 'current' && scope.restrictTo
|
||||
? {
|
||||
// `restrictTo` only exists in the newer `scope` request shape,
|
||||
|
||||
Reference in New Issue
Block a user