Last active
November 29, 2019 03:10
-
-
Save dmbaturin/23eae3e7afe873b836dd9ceb6261d667 to your computer and use it in GitHub Desktop.
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
-- Highlights the link to the current page/section in the navigation menu | |
-- If you have <a href="/about">, it will add a CSS class to it on page site/about.html | |
-- It assumes you are using relative links | |
-- | |
-- Sample configuration: | |
-- [plugins.active-link-hightlight] | |
-- active_link_class = "active" | |
-- nav_menu_selector = "nav" | |
-- | |
-- Minimum soupault version: 1.6 | |
-- Author: Daniil Baturin | |
-- License: MIT | |
active_link_class = config["active_link_class"] | |
nav_menu_selector = config["selector"] | |
if (not active_link_class) then | |
Log.warning("active_link_class option is not set, using default (\"active\")") | |
active_link_class = "active" | |
end | |
if (not nav_menu_selector) then | |
Log.warning("nav_menu_selector option is not set, using default (\"nav\")") | |
nav_menu_selector = "nav" | |
end | |
menu = HTML.select_one(page, nav_menu_selector) | |
if not menu then | |
Plugin.exit("Could not find an element matching the navigation menu selector") | |
end | |
links = HTML.select(menu, "a") | |
index, link = next(links) | |
while index do | |
href = strlower(HTML.get_attribute(link, "href")) | |
-- Remove leading and trailing slashes | |
href = Regex.replace_all(href, "(\\/?$|^\\/)", "") | |
page_url = Regex.replace_all(page_url, "(\\/?$|^\\/)", "") | |
-- Normalize slashes | |
href = Regex.replace_all(href, "\\/+", "\\/") | |
-- Edge case: the / link that becomes "" after normalization | |
-- Anything would match the empty string and higlight all links, | |
-- so we handle this case explicitly | |
if ((page_url == "") and (href == "")) | |
or ((href ~= "") and Regex.match(page_url, "^" .. href)) | |
then | |
HTML.add_class(link, active_link_class) | |
end | |
index, link = next(links, index) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment