Skip to content

Commit

Permalink
extend config options to pagefind (#1365)
Browse files Browse the repository at this point in the history
Co-authored-by: Chris Swithinbank <swithinbank@gmail.com>
  • Loading branch information
kevinzunigacuellar and delucis committed Jan 29, 2024
1 parent 275f87f commit a0af7cc
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/silver-dots-guess.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@astrojs/starlight': patch
---

Correctly format Pagefind search result links when `trailingSlash: 'never'` is used
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
{
"name": "/_astro/*.js",
"path": "examples/basics/dist/_astro/*.js",
"limit": "22 kB"
"limit": "22.5 kB"
},
{
"name": "/_astro/*.css",
Expand Down
18 changes: 17 additions & 1 deletion packages/starlight/components/Search.astro
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
---
import '@pagefind/default-ui/css/ui.css';
import Icon from '../user-components/Icon.astro';
import project from 'virtual:starlight/project-context';
import type { Props } from '../props';
const { labels } = Astro.props;
Expand All @@ -15,7 +16,10 @@ const pagefindTranslations = {
};
---

<site-search data-translations={JSON.stringify(pagefindTranslations)}>
<site-search
data-translations={JSON.stringify(pagefindTranslations)}
data-strip-trailing-slash={project.trailingSlash === 'never'}
>
<button data-open-modal disabled>
{
/* The span is `aria-hidden` because it is not shown on small screens. Instead, the icon label is used for accessibility purposes. */
Expand Down Expand Up @@ -112,10 +116,15 @@ const pagefindTranslations = {
translations = JSON.parse(this.dataset.translations || '{}');
} catch {}

const shouldStrip = this.dataset.stripTrailingSlash !== undefined;
const stripTrailingSlash = (path: string) => path.replace(/(.)\/(#.*)?$/, '$1$2');
const formatURL = shouldStrip ? stripTrailingSlash : (path: string) => path;

window.addEventListener('DOMContentLoaded', () => {
if (import.meta.env.DEV) return;
const onIdle = window.requestIdleCallback || ((cb) => setTimeout(cb, 1));
onIdle(async () => {
// @ts-expect-error — Missing types for @pagefind/default-ui package.
const { PagefindUI } = await import('@pagefind/default-ui');
new PagefindUI({
element: '#starlight__search',
Expand All @@ -124,6 +133,13 @@ const pagefindTranslations = {
showImages: false,
translations,
showSubResults: true,
processResult: (result: { url: string; sub_results: Array<{ url: string }> }) => {
result.url = formatURL(result.url);
result.sub_results = result.sub_results.map((sub_result) => {
sub_result.url = formatURL(sub_result.url);
return sub_result;
});
},
});
});
});
Expand Down

0 comments on commit a0af7cc

Please sign in to comment.