Skip to content

Commit

Permalink
Rework highlighting configuration and docs
Browse files Browse the repository at this point in the history
  • Loading branch information
bglw committed Nov 16, 2023
1 parent 9765f05 commit 162a090
Show file tree
Hide file tree
Showing 14 changed files with 196 additions and 105 deletions.
13 changes: 0 additions & 13 deletions docs/content/docs/_index.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,19 +53,6 @@ We can see that a bunch of content was indexed, and Pagefind will be running a p
Loading this in your browser, you should see a search input on your page. Try searching for some content and you will see results appear from your site.

## Highlighting

To highlight the search terms on results page, add the following snippet on every page that has been indexed

```html
<script src="/pagefind/pagefind-highlight.js"></script>
<script>
new PagefindHighlight();
<script>
```
See [Highlighting search terms](/docs/highlighting/) for more information.
The last required step is to run Pagefind after building your site on your CMS or hosting platform. If you're a CloudCannon user, add a [`.cloudcannon/postbuild`](https://cloudcannon.com/documentation/articles/extending-your-build-process-with-hooks/) file containing the npx command above (minus the `--serve` flag). For other platforms, set up an equivalent command to run after your site build — the end goal is that Pagefind will run after every build of your site before it is deployed.

For many use cases, you can stop here and mark it as complete. Or, you can dive deeper into Pagefind and configure it to your liking — check out [Configuring the index](/docs/indexing/) for some next steps.
6 changes: 3 additions & 3 deletions docs/content/docs/highlight-config.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ new PagefindHighlight({ markContext: "[data-pagefind-body]" })

The area in which to highlight text. Defaults to `[data-pagefind-body]` if any `[data-pagefind-body]` elements can be found, otherwise `document.body`. This can be a CSS selector string, a DOM element, an array of DOM elements, or a NodeList.

### pagefindQueryParamName
### highlightParam

```js
new PagefindHighlight({ pagefindQueryParamName: "pagefind-highlight" })
new PagefindHighlight({ highlightParam: "highlight" })
```

The name of the query parameter that Pagefind uses to determine which terms to highlight. Defaults to `pagefind-highlight`. If the name is changed here, it *must* be changed in the [`PagefindUI` object](/docs/ui/#highlight-query-param-name) as well.
The name of the query parameter that Pagefind uses to determine which terms to highlight. This must match the [Pagefind highlightParam config](/docs/search-config/#highlight-query-parameter).

### markOptions

Expand Down
46 changes: 40 additions & 6 deletions docs/content/docs/highlighting.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,47 @@ nav_section: Searching
weight: 10
---

Pagefind allows you to highlight search terms on the result page. To enable this feature, import `/pagefind/pagefind-highlight.js` on the result page and create a new `PagefindHighlight` object.
Pagefind includes the ability to highlight search terms on the result page.

To enable this feature, first configure Pagefind to insert a query parameter on search results.

## Configuring highlighting via the Default UI

{{< diffcode >}}
```javascript
new PagefindUI({
element: "#search",
+ highlightParam: "highlight"
});
```
{{< /diffcode >}}

## Configuring highlighting via the JavaScript API

{{< diffcode >}}
```javascript
const pagefind = await import("/pagefind/pagefind.js");
await pagefind.options({
+ highlightParam: "highlight"
});
const search = await pagefind.search("static");
```
{{< /diffcode >}}

## Enabling highlights on result pages

Once Pagefind is configured to insert query parameters, pages on your site will need to opt-in to highlighting.
This is something you can implement for your own site by looking at the query parameter, but Pagefind provides a highlighting script for convenience.

To opt-in, import `/pagefind/pagefind-highlight.js` on all pages of your site and create a new `PagefindHighlight` object.

```html
<script src="/pagefind/pagefind-highlight.js"></script>
<script>
new PagefindHighlight();
<script>
<script type="module">
await import('/pagefind/pagefind-highlight.js');
new PagefindHighlight({ highlightParam: "highlight" });
</script>
```

To see the options available to PagefindHighlight, see [Highlight Config](/docs/highlight-config).
Ensure that the `highlightParam` configured here matches the `highlightParam` given to Pagefind when searching.

To see all options available to PagefindHighlight, see [Highlight Config](/docs/highlight-config).
12 changes: 12 additions & 0 deletions docs/content/docs/search-config.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,18 @@ Overrides the bundle directory. In most cases this should be automatically detec

Set the maximum length for generated excerpts. Defaults to `30`.

### Highlight query parameter

```json
{
"highlightParam": "highlight"
}
```

If set, Pagefind will add the search term as a query parameter under the same name.

If using the [Pagefind highlight script](/docs/highlighting/), make sure this is configured to match.

### Index weight

See [multisite search > weighting](/docs/multisite/#changing-the-weighting-of-individual-indexes)
Expand Down
13 changes: 0 additions & 13 deletions docs/content/docs/ui.md
Original file line number Diff line number Diff line change
Expand Up @@ -152,19 +152,6 @@ new PagefindUI({

The number of milliseconds to wait after a user stops typing before performing a search. Defaults to `300`. If you wish to disable this, set to `0`.

### Highlight query param name

{{< diffcode >}}
```javascript
new PagefindUI({
element: "#search",
+ highlightQueryParamName: 'highlight'
});
```
{{< /diffcode >}}

If the parameter is changed here, it *must* be changed in the [`PagefindHighlight` object](/docs/highlight-config/#pagefindQueryParamName) as well.

### Translations

{{< diffcode >}}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
Feature: Highlighting Tests
Feature: Highlighting Result Tests

Background:
Given I have the environment variables:
Expand Down Expand Up @@ -56,7 +56,7 @@ Feature: Highlighting Tests
<script type="module">
await import('/pagefind/pagefind-highlight.js');
new PagefindHighlight({
pagefindQueryParamName: 'custom-name',
highlightParam: 'custom-name',
markOptions: {
className: 'custom-class',
exclude: [
Expand Down
81 changes: 81 additions & 0 deletions pagefind/features/highlighting/highlighting_search.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
Feature: Highlighting Search Tests

Background:
Given I have the environment variables:
| PAGEFIND_SITE | public |
Given I have a "public/index.html" file with the body:
"""
<p data-url>Nothing</p>
"""
Given I have a "public/a/index.html" file with the body:
"""
<p>Hello World</p>
"""
Given I have a "public/b/index.html" file with the body:
"""
<h2 id="second">Second</h2>
<p>Second Page</p>
"""

Scenario: Query parameters can be inserted through the JS API
When I run my program
Then I should see "Running Pagefind" in stdout
Then I should see the file "public/pagefind/pagefind.js"
When I serve the "public" directory
When I load "/"
When I evaluate:
"""
async function() {
let pagefind = await import("/pagefind/pagefind.js");
await pagefind.options({ highlightParam: "hi" });
let search = await pagefind.search("world");
let data = await search.results[0].data();
document.querySelector('[data-url]').innerText = data.url;
}
"""
Then There should be no logs
Then The selector "[data-url]" should contain "/a/?hi=world"

Scenario: Multiple query parameters are inserted through the JS API
When I run my program
Then I should see "Running Pagefind" in stdout
Then I should see the file "public/pagefind/pagefind.js"
When I serve the "public" directory
When I load "/"
When I evaluate:
"""
async function() {
let pagefind = await import("/pagefind/pagefind.js");
await pagefind.options({ highlightParam: "hi" });
let search = await pagefind.search("hello world");
let data = await search.results[0].data();
document.querySelector('[data-url]').innerText = data.url;
}
"""
Then There should be no logs
Then The selector "[data-url]" should contain "/a/?hi=hello&amp;hi=world"

Scenario: Query parameters don't conflict with subresult anchors
When I run my program
Then I should see "Running Pagefind" in stdout
Then I should see the file "public/pagefind/pagefind.js"
When I serve the "public" directory
When I load "/"
When I evaluate:
"""
async function() {
let pagefind = await import("/pagefind/pagefind.js");
await pagefind.options({ highlightParam: "hi" });
let search = await pagefind.search("second");
let data = await search.results[0].data();
document.querySelector('[data-url]').innerText = data.sub_results[0].url;
}
"""
Then There should be no logs
Then The selector "[data-url]" should contain "/b/?hi=second#second"
31 changes: 11 additions & 20 deletions pagefind/features/ui/ui_highlight.feature
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@ Feature: Base UI Tests

Scenario: Pagefind UI adds highlight query params
Given I have a "public/index.html" file with the body:
"""
"""
<div id="search"></div>
<script src="/pagefind/pagefind-ui.js"></script>
<script>
window.pui = new PagefindUI({ element: "#search" });
window.pui = new PagefindUI({ element: "#search", highlightParam: "pagefind-highlight" });
</script>
"""
"""
Given I have a "public/cat/index.html" file with the body:
"""
<h1>hello world</h1>
Expand Down Expand Up @@ -53,18 +53,18 @@ Feature: Base UI Tests
}
"""
Then There should be no logs
Then The selector ".pagefind-ui__result-link[href$='?pagefind-highlight=hello&pagefind-highlight=world%21']" should contain "hello world"
Then The selector ".pagefind-ui__result-link[href$='?pagefind-highlight=hello&pagefind-highlight=world']" should contain "hello world"

Scenario: Pagefind UI does not add highlight query params
Scenario: Pagefind UI does not add highlight query params by default
Given I have a "public/index.html" file with the body:
"""
"""
<div id="search"></div>
<script src="/pagefind/pagefind-ui.js"></script>
<script>
window.pui = new PagefindUI({ element: "#search", highlightQueryParamName: null });
window.pui = new PagefindUI({ element: "#search" });
</script>
"""
"""
Given I have a "public/cat/index.html" file with the body:
"""
<h1>hello world</h1>
Expand Down Expand Up @@ -96,14 +96,14 @@ Feature: Base UI Tests

Scenario: Pagefind UI uses custom highlight query param name
Given I have a "public/index.html" file with the body:
"""
"""
<div id="search"></div>
<script src="/pagefind/pagefind-ui.js"></script>
<script>
window.pui = new PagefindUI({ element: "#search", highlightQueryParamName: 'custom-param' });
window.pui = new PagefindUI({ element: "#search", highlightParam: 'custom-param' });
</script>
"""
"""
Given I have a "public/cat/index.html" file with the body:
"""
<h1>hello world</h1>
Expand Down Expand Up @@ -132,12 +132,3 @@ Feature: Base UI Tests
"""
Then There should be no logs
Then The selector ".pagefind-ui__result-link[href$='?custom-param=hello&custom-param=world']" should contain "hello world"
When I evaluate:
"""
async function() {
window.pui.triggerSearch("hello world!");
await new Promise(r => setTimeout(r, 1500)); // TODO: await el in humane
}
"""
Then There should be no logs
Then The selector ".pagefind-ui__result-link[href$='?custom-param=hello&custom-param=world%21']" should contain "hello world"
3 changes: 1 addition & 2 deletions pagefind/features/ui/ui_hooks.feature
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@ Feature: UI Hooks
<script>
window.pui = new PagefindUI({
element: "#search",
processTerm: (t) => t.replace("word", "search"),
highlightQueryParamName: null
processTerm: (t) => t.replace("word", "search")
});
</script>
"""
Expand Down
31 changes: 2 additions & 29 deletions pagefind_ui/default/svelte/ui.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -34,26 +34,13 @@
export let merge_index = [];
export let trigger_search_term = "";
export let translations = {};
// this is the name of the query param which is used to highlight the search terms after the user has navigated to a result page
// consider exposing the prop in the constructor in camelCase if needed
export let highlight_query_param_name = "pagefind-highlight";
let val = "";
$: if (trigger_search_term) {
val = trigger_search_term;
trigger_search_term = "";
}
// this could be changed to not split if the value is quoted
// ex: val = `hello world "foo bar"` highlightWords = ["hello", "world", "foo bar"]
$: highlightWords = val.split(" ");
$: highlight_query_param = new URLSearchParams(
highlightWords.map((word) => {
return [highlight_query_param_name, word];
})
).toString();
let pagefind;
let input_el,
clear_el,
Expand Down Expand Up @@ -318,23 +305,9 @@
<ol class="pagefind-ui__results">
{#each searchResult.results.slice(0, show) as result (result.id)}
{#if show_sub_results}
<ResultWithSubs
{show_images}
{process_result}
{result}
highlight_query_param={highlight_query_param_name
? highlight_query_param
: null}
/>
<ResultWithSubs {show_images} {process_result} {result} />
{:else}
<Result
{show_images}
{process_result}
{result}
highlight_query_param={highlight_query_param_name
? highlight_query_param
: null}
/>
<Result {show_images} {process_result} {result} />
{/if}
{/each}
</ol>
Expand Down
6 changes: 0 additions & 6 deletions pagefind_ui/default/ui-core.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,6 @@ export class PagefindUI {
let debounceTimeoutMs = opts.debounceTimeoutMs ?? 300;
let mergeIndex = opts.mergeIndex ?? [];
let translations = opts.translations ?? [];
// setting the param to null should disable highlighting, hence this more complicated check
let highlightQueryParamName = "pagefind-highlight";
if (opts.highlightQueryParamName !== undefined) {
highlightQueryParamName = opts.highlightQueryParamName;
}

// Remove the UI-specific config before passing it along to the Pagefind backend
delete opts["element"];
Expand Down Expand Up @@ -67,7 +62,6 @@ export class PagefindUI {
debounce_timeout_ms: debounceTimeoutMs,
merge_index: mergeIndex,
translations,
highlight_query_param_name: highlightQueryParamName,
pagefind_options: opts,
},
});
Expand Down
Loading

0 comments on commit 162a090

Please sign in to comment.