Skip to content

Commit

Permalink
Merge pull request #22 from zwippie/master
Browse files Browse the repository at this point in the history
Add aria_current option that adds aria-current attribute to active link
  • Loading branch information
danhper authored Dec 19, 2023
2 parents 743d5df + d8a4d6f commit 8e236c8
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
10 changes: 10 additions & 0 deletions lib/phoenix_active_link.ex
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ defmodule PhoenixActiveLink do
* `:class_active` - The class to add when the link is active. Defaults to `"active"`
* `:class_inactive` - The class to add when the link is not active. Empty by default.
* `:active_disable` - Uses a `span` element instead of an anchor when not active.
* `:aria_current` - The `aria-current` value to add when the link is active. Empty by default.
## Examples
Expand All @@ -60,6 +61,7 @@ defmodule PhoenixActiveLink do
active? = active_path?(conn, opts)
extra_class = extra_class(active?, opts)
opts = append_class(opts, extra_class)
opts = aria_current(opts, active?)
link = make_link(active?, text, opts)
cond do
tag = opts[:wrap_tag] -> content_tag(tag, link, wrap_tag_opts(extra_class, opts))
Expand Down Expand Up @@ -215,6 +217,14 @@ defmodule PhoenixActiveLink do
Keyword.put(opts, :class, class)
end

defp aria_current(opts, active?) do
if active? do
opts
else
Keyword.delete(opts, :aria_current)
end
end

defp link_opts(opts) do
Enum.reject(opts, &(elem(&1, 0) in @opts))
end
Expand Down
10 changes: 9 additions & 1 deletion test/phoenix_active_link_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ defmodule PhoenixActiveLinkTest do
assert active_path?(conn, active: [{Foo, :any}])
refute active_path?(conn, active: [{Bar, Foo}])
end

test "active_link without :wrap_tag" do
assert active_link(conn(path: "/"), "Link", to: "/foo") == link("Link", to: "/foo", class: "")
assert active_link(conn(path: "/foo"), "Link", to: "/foo") == link("Link", to: "/foo", class: "active")
Expand Down Expand Up @@ -114,6 +114,14 @@ defmodule PhoenixActiveLinkTest do
assert link == expected
end

test "active_link with :aria_current" do
expected = content_tag(:li, link("Link", to: "/foo", class: "active", aria_current: "page"), class: "active")
assert active_link(conn(path: "/foo"), "Link", to: "/foo", wrap_tag: :li, aria_current: "page") == expected

expected = content_tag(:li, link("Link", to: "/foo", class: ""), class: "")
assert active_link(conn(path: "/bar"), "Link", to: "/foo", wrap_tag: :li, aria_current: "page") == expected
end

test "customize defaults" do
Application.put_env(:phoenix_active_link, :defaults, [wrap_tag: :li])
expected = content_tag(:li, link("Link", to: "/foo", class: "active"), class: "active")
Expand Down

0 comments on commit 8e236c8

Please sign in to comment.