Skip to content

Sidebar links with a hash or query string get a trailing slash or .html appended after the hash #4286

Open

Description

@sebxt

What happens

A manual sidebar link that contains a hash or a query string is formatted as if the whole string were a pathname. The trailing slash or .html extension is added to the end of the string, which puts it inside the fragment or query value.

With trailingSlash: 'always':

starlight({
  sidebar: [{ label: 'Tabs', link: '/guides/components/#tabs' }],
});

renders href="/guides/components/#tabs/". The browser looks for an element with id tabs/, so the link does not scroll to the section.

With build.format: 'file', the same link renders href="/guides/components/#tabs.html", which points at the directory URL and the wrong fragment.

Other examples from createPathFormatter():

options input output
directory, always /guides/components#tabs /guides/components#tabs/
directory, always /search?q=astro /search?q=astro/
directory, never /guides/components/#tabs /guides/components/#tabs (slash kept)
file, ignore /search?q=astro /search?q=astro.html
file, ignore /#_top /#_top.html

What should happen

Only the pathname should be formatted, and the query string and hash should be kept as is. For example /guides/components#tabs with trailingSlash: 'always' should become /guides/components/#tabs, and /search?q=astro with build.format: 'file' should become /search.html?q=astro.

Minimal repro

import { createPathFormatter } from './src/utils/createPathFormatter';

createPathFormatter({ format: 'directory', trailingSlash: 'always' })('/guides/components#tabs');
// '/guides/components#tabs/'

createPathFormatter({ format: 'file', trailingSlash: 'ignore' })('/guides/components/#tabs');
// '/guides/components/#tabs.html'

Root cause

formatPath() in packages/starlight/src/utils/createPathFormatter.ts passes the full href to ensureTrailingSlash(), stripTrailingSlash() and ensureHtmlExtension(). These helpers only look at the end of the string, so any ?query or #hash suffix ends up before the added slash or extension. makeSidebarLink() in navigation.ts runs every non absolute sidebar link through formatPath().

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    🐛 bugSomething isn't working

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions