Skip to content

Commit

Permalink
Fix search in collection spaces leading to invalid urls
Browse files Browse the repository at this point in the history
  • Loading branch information
SamyPesse committed Mar 31, 2024
1 parent 3144b2f commit 9551108
Showing 1 changed file with 28 additions and 7 deletions.
35 changes: 28 additions & 7 deletions src/components/Search/server-actions.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use server';

import { RevisionPage, SearchAIAnswer, SearchPageResult } from '@gitbook/api';
import { RevisionPage, SearchAIAnswer, SearchPageResult, Space } from '@gitbook/api';

import { streamResponse } from '@/lib/actions';
import * as api from '@/lib/api';
Expand Down Expand Up @@ -61,11 +61,15 @@ export async function searchCollectionContent(
collectionId: string,
query: string,
): Promise<OrderedComputedResult[]> {
const data = await api.searchCollectionContent(collectionId, query);
const [data, collectionSpaces] = await Promise.all([
api.searchCollectionContent(collectionId, query),
api.getCollectionSpaces(collectionId),
]);

return data.items
.map((spaceItem) => {
return spaceItem.pages.map((item) => transformPageResult(item, spaceItem.title));
const space = collectionSpaces.find((space) => space.id === spaceItem.id);
return spaceItem.pages.map((item) => transformPageResult(item, space));
})
.flat(2);
}
Expand Down Expand Up @@ -136,22 +140,39 @@ function transformAnswer(
};
}

function transformPageResult(item: SearchPageResult, spaceTitle?: string) {
function transformPageResult(item: SearchPageResult, space?: Space) {
// Resolve a relative path to an absolute URL
// if the search result is relative to another space, we use the space URL
const getURL = (path: string) => {
if (space) {
let url = space.urls.published ?? space.urls.app;
if (!url.endsWith('/')) {
url += '/';
}
if (path.startsWith('/')) {
path = path.slice(1);
}
return url + path;
} else {
return absoluteHref(path);
}
};

const sections =
item.sections?.map<ComputedSectionResult>((section) => ({
type: 'section',
id: item.id + '/' + section.id,
title: section.title,
href: absoluteHref(section.path),
href: getURL(section.path),
body: section.body,
})) ?? [];

const page: ComputedPageResult = {
type: 'page',
id: item.id,
title: item.title,
href: absoluteHref(item.path),
spaceTitle,
href: getURL(item.path),
spaceTitle: space?.title,
};

return [page, ...sections];
Expand Down

0 comments on commit 9551108

Please sign in to comment.