diff --git a/packages/starlight/__tests__/basics/format-path.test.ts b/packages/starlight/__tests__/basics/format-path.test.ts --- a/packages/starlight/__tests__/basics/format-path.test.ts +++ b/packages/starlight/__tests__/basics/format-path.test.ts @@ -137,3 +137,46 @@ }); } ); + +describe.each<{ + options: FormatPathOptions; + query: string; + hash: string; + expected: string; +}>([ + { + options: { format: 'file', trailingSlash: 'ignore' }, + query: '/reference/configuration?filter=stable', + hash: '/reference/configuration#filter=stable', + expected: '/reference/configuration.html', + }, + { + options: { format: 'directory', trailingSlash: 'always' }, + query: '/reference/configuration?filter=stable', + hash: '/reference/configuration#filter=stable', + expected: '/reference/configuration/', + }, + { + options: { format: 'directory', trailingSlash: 'never' }, + query: '/reference/configuration?filter=stable', + hash: '/reference/configuration#filter=stable', + expected: '/reference/configuration', + }, + { + options: { format: 'directory', trailingSlash: 'ignore' }, + query: '/reference/configuration?filter=stable', + hash: '/reference/configuration#filter=stable', + expected: '/reference/configuration', + }, +])( + 'formatPath() preserves the query string or hash with { format: $options.format, trailingSlash: $options.trailingSlash }', + ({ options, query, hash, expected }) => { + test('preserves the query string', () => { + expect(formatPath(query, options)).toBe(expected + '?filter=stable'); + }); + + test('preserves the hash', () => { + expect(formatPath(hash, options)).toBe(expected + '#filter=stable'); + }); + } +); diff --git a/packages/starlight/src/utils/createPathFormatter.ts b/packages/starlight/src/utils/createPathFormatter.ts --- a/packages/starlight/src/utils/createPathFormatter.ts +++ b/packages/starlight/src/utils/createPathFormatter.ts @@ -40,6 +40,12 @@ const formatStrategy = formatStrategies[format]; const trailingSlashStrategy = trailingSlashStrategies[trailingSlash]; + // Split off any query string and hash so that path formatting (adding an extension, a trailing + // slash, etc.) only affects the pathname and leaves the query string and hash untouched. + const suffixIndex = href.search(/[?#]/); + const suffix = suffixIndex === -1 ? '' : href.slice(suffixIndex); + href = suffixIndex === -1 ? href : href.slice(0, suffixIndex); + // Handle extension href = formatStrategy.handleExtension(href); @@ -47,12 +53,12 @@ href = formatStrategy.addBase(href); // Skip trailing slash handling for `build.format: 'file'` - if (format === 'file') return href; + if (format === 'file') return href + suffix; // Handle trailing slash href = href === '/' ? href : trailingSlashStrategy(href); - return href; + return href + suffix; } export function createPathFormatter(opts: FormatPathOptions) {