Skip to content

Commit

Permalink
fix(LocaleSelector): use closest <a> for hreflang (#221)
Browse files Browse the repository at this point in the history
# Changes

#182 [introduced elements within the locale selector
links](https://github.com/voorhoede/head-start/pull/182/files#diff-312432278fd76f34872189b8e676a79dd41e5abfe02c5f6fecb834c2abe399efR39),
causing the client-side script to break as it could no longer get the
`hreflang`. This in turn caused the `HEAD_START_LOCALE` cookie not to be
set.

This change fixes this by ensuring it always finds the closest <a> tag
first.

# Associated issue

N/A (found this bug testing upgrade to Astro v5)

# How to test

1. Open preview link
2. Switch locale using the locale selector
3. Verify the `HEAD_START_LOCALE` cookie contains the new value
4. Navigate to the root URL `/` again
5. Verify you're redirected to the locale you switched to before

# Checklist

- [x] I have performed a self-review of my own code
- [x] I have made sure that my PR is easy to review (not too big,
includes comments)
- ~I have made updated relevant documentation files (in project README,
docs/, etc)~
- ~I have added a decision log entry if the change affects the
architecture or changes a significant technology~
- ~I have notified a reviewer~ (minor change, self-reviewed to speed
things up)

<!-- Please strike through and check off all items that do not apply
(rather than removing them) -->
  • Loading branch information
jbmoelker authored Dec 5, 2024
1 parent 69243d9 commit 5a4e043
Showing 1 changed file with 5 additions and 8 deletions.
13 changes: 5 additions & 8 deletions src/components/LocaleSelector/LocaleSelector.client.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,16 @@
import { cookieName } from '../../lib/i18n';

class LocaleSelector extends HTMLElement {
constructor() {
super();
connectedCallback() {
this.addEventListener('click', (event: MouseEvent) => {
const target = event.target as HTMLAnchorElement;
if (!target || target.tagName !== 'A') {
return;
}
if (!target.hreflang) {
const target = event.target as HTMLElement;
const anchor = target?.closest('a');
if (!anchor?.hreflang) {
console.warn('LocaleSelector: missing required hreflang attribute', { target });
return;
}
// set the hreflang cookie to the selected locale:
document.cookie = `${cookieName}=${target.hreflang}; path=/`;
document.cookie = `${cookieName}=${anchor.hreflang}; path=/`;
});
}
}
Expand Down

0 comments on commit 5a4e043

Please sign in to comment.