Skip to content
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

Fix language selector invalid value #2635

Merged
merged 6 commits into from
Dec 17, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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) => {
delucis marked this conversation as resolved.
Show resolved Hide resolved
// 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;
delucis marked this conversation as resolved.
Show resolved Hide resolved
}
});
});
</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">
delucis marked this conversation as resolved.
Show resolved Hide resolved
{
Astro.props.options.map(({ value, selected, label }) => (
<option value={value} selected={selected} set:html={label} />
Expand Down
Loading