Skip to content

Commit

Permalink
Fix language selector invalid value (#2635)
Browse files Browse the repository at this point in the history
Co-authored-by: Chris Swithinbank <[email protected]>
Co-authored-by: Chris Swithinbank <[email protected]>
  • Loading branch information
3 people authored Dec 17, 2024
1 parent d127bfb commit ec4b851
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/rude-lobsters-destroy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@astrojs/starlight': patch
---

Fixes an issue where the language picker in multilingual sites could display the wrong language when navigating between pages with the browser back/forward buttons.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
{
"name": "/_astro/*.js",
"path": "examples/basics/dist/_astro/*.js",
"limit": "23 kB",
"limit": "23.5 kB",
"gzip": true
},
{
Expand Down
10 changes: 10 additions & 0 deletions packages/starlight/components/LanguageSelect.astro
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,16 @@ function localizedPathname(locale: string | undefined): string {
window.location.pathname = e.currentTarget.value;
}
});
window.addEventListener('pageshow', (event) => {
if (!event.persisted) return;
// If the page was loaded from a cache, the language select selected index might not be
// in sync with the current page.
const markupSelectedIndex =
select.querySelector<HTMLOptionElement>('option[selected]')?.index;
if (markupSelectedIndex !== select.selectedIndex) {
select.selectedIndex = markupSelectedIndex ?? 0;
}
});
}
}
}
Expand Down
11 changes: 10 additions & 1 deletion packages/starlight/components/Select.astro
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,21 @@ interface Props {
selected: boolean;
}>;
}
/**
* The `autocomplete="off"` attribute is used to prevent the browser from automatically selecting a
* value for this input, e.g. based on the user's previous selections, as this could lead to
* incorrect values being selected for example when the user switches between languages and uses
* the back button.
* Note that this attribute is only useful when a value is not restored at a later stage, e.g. the
* bfcache that ignores this attribute when restoring the value.
*/
---

<label style={`--sl-select-width: ${Astro.props.width}`}>
<span class="sr-only">{Astro.props.label}</span>
<Icon name={Astro.props.icon} class="icon label-icon" />
<select value={Astro.props.value}>
<select value={Astro.props.value} autocomplete="off">
{
Astro.props.options.map(({ value, selected, label }) => (
<option value={value} selected={selected} set:html={label} />
Expand Down

0 comments on commit ec4b851

Please sign in to comment.