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

Excluding modals from Active link check #1942

Merged
merged 11 commits into from
Mar 19, 2024
6 changes: 5 additions & 1 deletion libs/blocks/global-navigation/utilities/utilities.js
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,11 @@ export const [hasActiveLink, setActiveLink, getActiveLink] = (() => {

[`${origin}${pathname}`, pathname].forEach((path) => {
Copy link
Contributor

Choose a reason for hiding this comment

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

With this new approach, I'd test a bit more to justify the necessity of the pathname check. Say we have the following element: <a href="/path/to/page">Page</a>. We needed the pathname check for the query selector, which would have been a[href = '/path/to/page']. So we were checking an attribute value, which could have been either a full URL or just a path. Moving to the el.href approach, pathname might be irrelevant, as its result would always be a full URL.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yes, I agree. I will make the necessary change and update the PR.

if (activeLink) return;
activeLink = area.querySelector(`a[href = '${path}'], a[href ^= '${path}?'], a[href ^= '${path}#']`);
const linkElements = area.querySelectorAll('a:not([data-modal-hash])');
activeLink = [...linkElements].find((el) => {
const regex = new RegExp(`^${path}(\\?[^#]*)?(#.*)?$`);
return regex.test(el.href);
});
Copy link
Contributor

Choose a reason for hiding this comment

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

This could be simplified if linkElements and regex are not cached:

activeLink = [...area.querySelectorAll('a:not([data-modal-hash])')].find((el) => {
    return new RegExp(`^${path}(\\?[^#]*)?(#.*)?$`).test(el.href);
});

Copy link
Contributor

Choose a reason for hiding this comment

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

And even a little further, since it doesn't need the return for the inner arrow function

activeLink = [...area.querySelectorAll('a:not([data-modal-hash])')].find((el) => new RegExp(`^${path}(\\?[^#]*)?(#.*)?$`).test(el.href));

});

if (!activeLink) return null;
Expand Down
Loading