-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
05ae91f
commit 01b1c1c
Showing
3 changed files
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
interface UrlLinkMatched { | ||
links: NodeListOf<HTMLAnchorElement>; | ||
callback: (link: HTMLAnchorElement) => void; | ||
} | ||
|
||
export const urlLinkMatched = ({ links, callback }: UrlLinkMatched): void => { | ||
links.forEach((link) => { | ||
const href = link.getAttribute("href"); | ||
if (!href) throw new Error("href attribute not defined on anchor element"); | ||
|
||
const linkHref = new URL(href, document.baseURI).href; | ||
if (location.href === linkHref) { | ||
callback(link); | ||
} | ||
}); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
import { getByText } from "@testing-library/dom"; | ||
import { urlLinkMatched } from "../src/urlLinkMatched"; | ||
|
||
const getExampleDOM = () => { | ||
const div = document.createElement("div"); | ||
|
||
const link1 = document.createElement("a"); | ||
link1.setAttribute("href", "./"); | ||
link1.innerHTML = "home"; | ||
|
||
const link2 = document.createElement("a"); | ||
link2.setAttribute("href", "./about"); | ||
link2.innerHTML = "about"; | ||
|
||
div.appendChild(link1); | ||
div.appendChild(link2); | ||
|
||
return div; | ||
}; | ||
|
||
test("urlLinkMatch should add class correctly", async () => { | ||
const className = "active"; | ||
const container = getExampleDOM(); | ||
// console.log(prettyDOM(container)); | ||
|
||
urlLinkMatched({ | ||
links: container.querySelectorAll("a"), | ||
callback: (link) => link.classList.add(className), | ||
}); | ||
|
||
expect(getByText(container, "home").getAttribute("class")).toBe(className); | ||
}); |