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.
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
Loading