diff --git a/.chronus/changes/astro-utils-search-highlights.md b/.chronus/changes/astro-utils-search-highlights.md new file mode 100644 index 00000000000..9f61fdd2f90 --- /dev/null +++ b/.chronus/changes/astro-utils-search-highlights.md @@ -0,0 +1,12 @@ +--- +changeKind: feature +packages: + - "@typespec/astro-utils" +--- + +Highlight search terms on destination pages using Pagefind's built-in highlighting. Search links preserve heading anchors, and scoped searches highlight the terms without the selector prefix. + +```text +api: isHttpFile +-> https://typespec.io/docs/libraries/http/reference/typekits/?highlight=ishttpfile#ishttpfile +``` diff --git a/packages/astro-utils/README.md b/packages/astro-utils/README.md index a24e0faac6b..b461b5af001 100644 --- a/packages/astro-utils/README.md +++ b/packages/astro-utils/README.md @@ -24,6 +24,15 @@ The component uses the site's base path, Fluent theme tokens, and Starlight sear (with English defaults on non-Starlight pages). It supports Up/Down result navigation and Enter activation, and avoids favoring short generated API pages over longer documentation. +### Highlighting result pages + +Search result links include a `highlight` query parameter. On the destination page, +the component loads Pagefind's built-in highlighting script to mark matching text +in the indexed content. Heading links retain their anchors, and scoped searches +highlight the search terms without the `api:` or `all:` selector. + +Pages without a highlight query and development mode do not load the highlighting script. + ### Search scopes Use `` for prefix-based search: diff --git a/packages/astro-utils/src/components/search.astro b/packages/astro-utils/src/components/search.astro index 93b1c31928f..db4dbf0699c 100644 --- a/packages/astro-utils/src/components/search.astro +++ b/packages/astro-utils/src/components/search.astro @@ -121,6 +121,7 @@ const devWarning = window.PagefindComponents.configureInstance("default", { baseUrl, bundlePath, + highlightParam: "highlight", ranking: { // Avoid favoring short generated API pages over guides and decorator references. pageLength: 0, @@ -266,6 +267,10 @@ const devWarning = } const template = document.querySelector(".pagefind-search template"); template.replaceWith(template.content.cloneNode(true)); + if (new URLSearchParams(window.location.search).get("highlight")) { + await import(`${bundlePath}pagefind-highlight.js`); + new window.PagefindHighlight({ highlightParam: "highlight" }); + } ) : (