Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix search in collection spaces leading to invalid urls #2253

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading