~hristoast/hristoast

ref: 6c6b610011fd9b58d5c2baf47345899ba5ef360d hristoast/plugins/section-link-highlight.lua -rw-r--r-- 1.6 KiB
6c6b6100Hristos N. Triantafillou Proofreading edits 4 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
-- Highlights the link to the current page/section in the navigation menu
-- Quite hacky, if you ask me: it compares the href with the page path relative to site/
-- I.e. if you have <a href="/about">, it will add a class to it in 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"
--
-- Minimal 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)
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