Skip to content
Open
Show file tree
Hide file tree
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
49 changes: 40 additions & 9 deletions src/scripts/docs-search.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
// second one on the same page, which is why any of this is scoped at all.

import {
classify,
fixtureEngine,
type SearchEngine,
type SearchResult,
Expand All @@ -29,6 +30,17 @@ const DEBOUNCE_MS = 150;
const MIN_QUERY_LENGTH = 2;
const SITE_SEARCH = 'site';

/**
* The tab the site overlay opens on: the section the reader is already in, so a
* search from a guide is not led by an API page that happens to score higher.
* Uses the same path rules as the tabs themselves, so a page always opens on the
* tab it would be listed under. A page outside the docs has no section and opens
* on All.
*/
function sectionOf(pathname: string) {
return /^\/docs(\/|$)/.test(pathname) ? classify(pathname).facet : 'all';
}

function setup(dialog: HTMLDialogElement) {
const name = dialog.dataset.docsSearch || SITE_SEARCH;

Expand Down Expand Up @@ -78,6 +90,10 @@ function setup(dialog: HTMLDialogElement) {
? fixtureEngine(JSON.parse(demo))
: pagefindEngine(dialog.dataset.indexUrl ?? '/docs/pagefind/');

// The tab the reader wants: their section to begin with, then whichever tab
// they last picked. `facet` is the tab on screen, which drops to All while
// the wanted one has nothing for the query and returns once it does.
let preferred = name === SITE_SEARCH ? sectionOf(location.pathname) : 'all';
let facet = 'all';
let active = -1;
let debounce = 0;
Expand Down Expand Up @@ -275,6 +291,13 @@ function setup(dialog: HTMLDialogElement) {
setActive(0);
}

/** The reader picked a tab: it becomes the one to come back to. */
function chooseTab(key: string) {
preferred = key;
selectTab(key);
run();
}

function selectTab(key: string) {
facet = key;
for (const tab of facetTabs()) {
Expand All @@ -293,17 +316,21 @@ function setup(dialog: HTMLDialogElement) {
}

const mine = ++generation;
let response = await engine.search(input!.value, facet);
let shown = preferred;
let response = await engine.search(input!.value, shown);
if (mine !== generation) return;

// A narrowed tab the new query has nothing under would leave the panel
// looking empty while other sections hold results, so fall back to All.
if (facet !== 'all' && (response.counts[facet] ?? 0) === 0) {
selectTab('all');
response = await engine.search(input!.value, facet);
// looking empty while other sections hold results, so show All instead.
// `preferred` is left alone, so the next query that does reach the tab
// goes back to it.
if (shown !== 'all' && (response.counts[shown] ?? 0) === 0) {
shown = 'all';
response = await engine.search(input!.value, shown);
if (mine !== generation) return;
}

selectTab(shown);
render(response);
report();
}
Expand Down Expand Up @@ -354,6 +381,12 @@ function setup(dialog: HTMLDialogElement) {
if (input!.value.trim()) run();
}

// A section with no tab of its own on this overlay has nothing to narrow to.
if (!facetTabs().some((tab) => tab.dataset.facet === preferred)) {
preferred = 'all';
}
selectTab(preferred);

// --- Triggers ------------------------------------------------------------
// The nav trigger stays a real <input> inside a form that GETs a web search,
// so with scripting off it still submits. Opening happens on click and key,
Expand Down Expand Up @@ -463,11 +496,10 @@ function setup(dialog: HTMLDialogElement) {
event.preventDefault();
const next =
strip[(from + (forward ? 1 : -1) + strip.length) % strip.length];
selectTab(next.dataset.facet!);
chooseTab(next.dataset.facet!);
// Focus follows selection on a tab strip, but only when the strip already
// had it — driving from the input has to leave the query editable.
if (onTab) next.focus();
run();
}
});

Expand All @@ -478,8 +510,7 @@ function setup(dialog: HTMLDialogElement) {
const tab = target.closest<HTMLElement>('[data-facet]');
if (!tab) return;

selectTab(tab.dataset.facet!);
run();
chooseTab(tab.dataset.facet!);
});

dialog
Expand Down
208 changes: 170 additions & 38 deletions tests/docs-search.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,172 @@ test('a click outside the panel closes the overlay', async ({ page }) => {
const navField = (page: Page) =>
page.locator('input[data-docs-search-trigger]:visible').first();

/**
* Runs a query in the site overlay and widens it to All. The overlay opens on
* the reader's own section, and the ranking tests below are about the whole
* site, CLI and API included.
*/
async function searchAll(page: Page, query: string) {
await page.goto('/docs');

const site = siteOverlay(page);
await navField(page).click();
await expect(site).toBeVisible();

await site.locator('[data-docs-search-input]').fill(query);
await expect(site.locator('[role="option"]').first()).toBeVisible({
timeout: 20_000,
});

const all = site.locator('[data-docs-search-tabs] [data-facet="all"]');
await all.click();
await expect(all).toHaveAttribute('aria-selected', 'true');

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Claude: Major (test coverage). searchAll doesn't wait for the All results to arrive. chooseTab('all') sets aria-selected synchronously, so this assertion passes at once, while the list still holds the Docs-tab rows from the first search. The href assertions that follow retry until they match, so they can pass on those stale Docs rows before the All search lands.

That breaks the tests this helper was added for. In a guide beats a command of the same name, the Docs tab filters out CLI pages, so /docs/releases/creating-a-release/ will almost certainly be first there regardless of whole-site ranking. A regression that lets a CLI command win on All would go unnoticed. the page a query names comes first has the same problem, since namedPage promotes within the Docs filter too. a page pulled forward is not listed again can also flake: it may scroll and page the stale Docs list, then have the All response replace it mid-poll. Only a command wins when the query asks for one is safe, because its expected row can't appear on Docs.

One fix is to make the All query the only one in flight after the tab switch:

await all.click();
await expect(all).toHaveAttribute('aria-selected', 'true');
const input = site.locator('[data-docs-search-input]');
await input.fill('');          // renders empty synchronously and bumps the generation
await input.fill(query);
await expect(site.locator('[role="option"]').first()).toBeVisible({ timeout: 20_000 });

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Claude: Fixed in 76ca490. After clicking All, searchAll now clears the query (which empties the list straight away) and types it again, then waits for rows. Any row it checks came from the All search, so the ranking tests are checking whole-site results and the paged-scroll test no longer races the list being replaced.

// The tab is marked selected before its search lands, so the rows on screen
// are still the section's. Running the query again from empty means any row
// seen next came from All.
await rerun(site, query);
return site;
}

/**
* Clears the query and types it again, then waits for rows. Clearing empties
* the list at once, so the rows waited for belong to this search and not to
* whatever was on screen before it.
*/
async function rerun(site: ReturnType<typeof siteOverlay>, query: string) {
const input = site.locator('[data-docs-search-input]');
await input.fill('');
await expect(site.locator('[role="option"]')).toHaveCount(0);
await input.fill(query);
await expect(site.locator('[role="option"]').first()).toBeVisible({
timeout: 20_000,
});
}

const selectedTab = (page: Page) =>
siteOverlay(page).locator('[data-docs-search-tabs] [aria-selected="true"]');

async function searchFrom(page: Page, path: string, query: string) {
await page.goto(path);

const site = siteOverlay(page);
await navField(page).click();
await expect(site).toBeVisible();

await site.locator('[data-docs-search-input]').fill(query);
await expect(site.locator('[role="option"]').first()).toBeVisible({
timeout: 20_000,
});
return site;
}

// API and CLI reference pages often outscore the guide a reader was after, so
// the overlay opens on the section the top nav says they are in.
//
// Integrations is left out: every page under /docs/api-and-integration/ is a
// redirect today, so there is nowhere to search from.
for (const [path, facet] of [
['/docs/', 'docs'],
['/docs/api/', 'api'],
['/docs/cli/', 'cli'],
] as const) {
test(`a search from ${path} opens on the ${facet} tab`, async ({ page }) => {
const site = await searchFrom(page, path, 'release');

await expect(selectedTab(page)).toHaveAttribute('data-facet', facet);
const hrefs = await site
.locator('.docs-search__row')
.evaluateAll((rows) => rows.map((row) => row.getAttribute('href') ?? ''));
expect(hrefs.length).toBeGreaterThan(0);
for (const href of hrefs) {
if (facet === 'docs') {
expect(href).not.toMatch(/^\/docs\/(cli|api|api-and-integration)\//);
} else {
expect(href).toMatch(new RegExp(`^/docs/${facet}/`));
}
}
});
}

// The demo overlay on the gallery page is not the reader's search, so it has
// no section to start in. The gallery lives outside /docs, where every overlay
// opens on All anyway, so it is served from inside the CLI section here: the
// site overlay has to take up CLI while the demo stays on All.
test('the demo overlay opens on All', async ({ page, baseURL }) => {
const inCli = '/docs/cli/gallery-under-test';
await page.route(`**${inCli}`, async (route) =>
route.fulfill({ response: await route.fetch({ url: `${baseURL}${PAGE}` }) })
);
await page.goto(inCli);

const demo = await opened(page);
// A query the fixture has CLI rows for, so a demo overlay that took up the
// page's section would have a CLI tab to land on.
await demo.locator('[data-docs-search-input]').fill('octopus');
await expect(demo.locator('[role="option"]').first()).toBeVisible();
await expect(
demo.locator('[data-docs-search-tabs] [data-facet="cli"]')
).toBeVisible();
await expect(
demo.locator('[data-docs-search-tabs] [aria-selected="true"]')
).toHaveAttribute('data-facet', 'all');
await page.keyboard.press('Escape');

// And the page's own overlay did take up the section, or the above proves
// nothing about the demo being singled out.
await rerunFromNav(page, 'release');
await expect(selectedTab(page)).toHaveAttribute('data-facet', 'cli');
});

async function rerunFromNav(page: Page, query: string) {
const site = siteOverlay(page);
await navField(page).click();
await expect(site).toBeVisible();
await rerun(site, query);
}

// A query the section has nothing for shows All rather than an empty panel, and
// the section comes back once the query reaches it again.
test('the section tab returns once the query reaches it again', async ({
page,
}) => {
const site = await searchFrom(page, '/docs/cli/', 'release');
const input = site.locator('[data-docs-search-input]');
await expect(selectedTab(page)).toHaveAttribute('data-facet', 'cli');

// A Docs-only page title: nothing in the CLI reference mentions it.
await input.fill('octopus server sql database');
await expect(selectedTab(page)).toHaveAttribute('data-facet', 'all', {
timeout: 20_000,
});

await input.fill('release');
await expect(selectedTab(page)).toHaveAttribute('data-facet', 'cli', {
timeout: 20_000,
});
});

// A tab the reader picked outranks their section, for as long as they stay on
// the page.
test('a picked tab is kept when the overlay reopens', async ({ page }) => {
const site = await searchFrom(page, '/docs/cli/', 'release');

await site.locator('[data-docs-search-tabs] [data-facet="docs"]').click();
await expect(selectedTab(page)).toHaveAttribute('data-facet', 'docs');

await page.keyboard.press('Escape');
await expect(site).toBeHidden();

// From empty, so the tab checked is the one the reopened search settled on,
// not the one left over from before the overlay closed. `create release` has
// CLI rows, so a search that went back to the section would show it.
await rerunFromNav(page, 'create release');
await expect(
site.locator('[data-docs-search-tabs] [data-facet="cli"]')
).toBeVisible();
await expect(selectedTab(page)).toHaveAttribute('data-facet', 'docs');

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Claude: Minor (ineffective test). This doesn't wait for the reopened search. The rows from before the overlay closed are still in the list, so first().toBeVisible() passes at once. The tab was already docs before closing, so this assertion passes at once too, before the create release search resolves. The test only fails if something resets the tab synchronously on open. If run() started using the section instead of the picked tab, it would select cli only after its await, which is after this has passed. (The pre-PR code would pass this test too.)

Suggestion: clear the input before filling it (fill(''), then fill('create release')) so only fresh rows can show. Then also assert that no row href starts with /docs/cli/, the same way the per-section tests do.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Claude: Fixed in 76ca490. After reopening, the test clears the query and types create release again, so it checks the tab that search settled on. It also checks that the CLI tab is visible, so going back to the section would have a tab to land on. I confirmed it now fails if open() resets the tab to the section (Expected "docs", Received "cli").

});

test('the query is left in the field that opened the overlay', async ({
page,
}) => {
Expand Down Expand Up @@ -380,16 +546,7 @@ test('results stay on the host that served them', async ({ page }) => {
// overlay runs a second search over the shallow pages alone and puts the page the
// query names at the top. Without it the first result is a getting-started page.
test('the page a query names comes first', async ({ page }) => {
await page.goto('/docs');

const site = siteOverlay(page);
await navField(page).click();
await expect(site).toBeVisible();

await site.locator('[data-docs-search-input]').fill('deployment targets');
await expect(site.locator('[role="option"]').first()).toBeVisible({
timeout: 20_000,
});
const site = await searchAll(page, 'deployment targets');

await expect(site.locator('[role="option"]').first()).toHaveAttribute(
'href',
Expand Down Expand Up @@ -440,15 +597,8 @@ test('scrolling to the end of the results loads more', async ({ page }) => {
test('a page pulled forward is not listed again further down', async ({
page,
}) => {
await page.goto('/docs');

const site = siteOverlay(page);
await navField(page).click();
await expect(site).toBeVisible();

await site.locator('[data-docs-search-input]').fill('deployment targets');
const site = await searchAll(page, 'deployment targets');
const rows = site.locator('[role="option"]');
await expect(rows.first()).toBeVisible({ timeout: 20_000 });
await expect(rows.first()).toHaveAttribute(
'href',
'/docs/infrastructure/deployment-targets/'
Expand Down Expand Up @@ -519,16 +669,7 @@ test('a query with no answer still says no results', async ({ page }) => {
// page the query names would otherwise hand this to one of them. A reference page
// has to be asked for.
test('a guide beats a command of the same name', async ({ page }) => {
await page.goto('/docs');

const site = siteOverlay(page);
await navField(page).click();
await expect(site).toBeVisible();

await site.locator('[data-docs-search-input]').fill('create release');
await expect(site.locator('[role="option"]').first()).toBeVisible({
timeout: 20_000,
});
const site = await searchAll(page, 'create release');
await expect(site.locator('[role="option"]').first()).toHaveAttribute(
'href',
'/docs/releases/creating-a-release/'
Expand All @@ -539,16 +680,7 @@ test('a guide beats a command of the same name', async ({ page }) => {
// CLI page is titled `octopus <something>`, so a query opening that way counts as
// asking.
test('a command wins when the query asks for one', async ({ page }) => {
await page.goto('/docs');

const site = siteOverlay(page);
await navField(page).click();
await expect(site).toBeVisible();

await site.locator('[data-docs-search-input]').fill('octopus release create');
await expect(site.locator('[role="option"]').first()).toBeVisible({
timeout: 20_000,
});
const site = await searchAll(page, 'octopus release create');
await expect(site.locator('[role="option"]').first()).toHaveAttribute(
'href',
'/docs/cli/octopus-release-create/'
Expand Down