Skip to content

Fix language selector invalid value #2635

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Dec 17, 2024
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.
14 changes: 14 additions & 0 deletions packages/starlight/components/LanguageSelect.astro
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,18 @@ function localizedPathname(locale: string | undefined): string {
}
}
customElements.define('starlight-lang-select', StarlightLanguageSelect);
window.addEventListener('pageshow', (event) => {
Copy link
Member Author

Choose a reason for hiding this comment

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

A better event would be resume from the Document API but it's not available in Safari at the moment.

if (!event.persisted) return;
document
.querySelectorAll<HTMLSelectElement>('starlight-lang-select select')
.forEach((select) => {
// 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;
}
});
});
</script>
2 changes: 1 addition & 1 deletion packages/starlight/components/Select.astro
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ interface Props {
<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
Loading