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
9 changes: 3 additions & 6 deletions libs/blocks/global-navigation/utilities/utilities.js
Original file line number Diff line number Diff line change
Expand Up @@ -259,12 +259,9 @@ export const [hasActiveLink, setActiveLink, getActiveLink] = (() => {
(area) => {
if (hasActiveLink() || !(area instanceof HTMLElement)) return null;
const { origin, pathname } = window.location;
let activeLink;

[`${origin}${pathname}`, pathname].forEach((path) => {
if (activeLink) return;
activeLink = area.querySelector(`a[href = '${path}'], a[href ^= '${path}?'], a[href ^= '${path}#']`);
});
const activeLink = [
...area.querySelectorAll('a:not([data-modal-hash])'),
].find((el) => new RegExp(`^${`${origin}${pathname}`}(\\?[^#]*)?(#.*)?$`).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.

I just realized that there may be some potential for improvement for the regular expression here. Let's just use this page's URL as an example.

var { origin, pathname } = window.location;
var regex = new RegExp(`^${`${origin}${pathname}`}(\\?[^#]*)?(#.*)?$`);
// regex will be: /^https:\/\/github.com\/adobecom\/milo\/pull\/1942\/files(\?[^#]*)?(#.*)?$/

The issue is that ., which in regular expression terms translates to any character. So regex.test('https://githubXcom/adobecom/milo/pull/1942/files'); would actually be true.

One way to solve this would be to call an additional .replaceAll('.', '\\.') on the string. Another would be to replace the regular expression with

const url = `${origin}${pathname}`;
const matches = endsWith(url) || startsWith(`${url}?`)  || startsWith(`${url}#`); // to be adapted, just a quick example

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@overmyheadandbody Thanks for the catch with . Will update the code as discussed.


if (!activeLink) return null;

Expand Down
Loading