diff --git a/lib/linkify.ex b/lib/linkify.ex index d15d01c..0f97ad5 100644 --- a/lib/linkify.ex +++ b/lib/linkify.ex @@ -34,13 +34,14 @@ defmodule Linkify do * `email` - link email links (default: `false`) * `mention` - link @mentions (when `true`, requires `mention_prefix` or `mention_handler` options to be set) (default: `false`) * `mention_prefix` - a prefix to build a link for a mention (example: `https://example.com/user/`, default: `nil`) - * `mention_handler` - a custom handler to validate and formart a mention (default: `nil`) + * `mention_handler` - a custom handler to validate and format a mention (default: `nil`) * `hashtag: false` - link #hashtags (when `true`, requires `hashtag_prefix` or `hashtag_handler` options to be set) * `hashtag_prefix: nil` - a prefix to build a link for a hashtag (example: `https://example.com/tag/`) - * `hashtag_handler: nil` - a custom handler to validate and formart a hashtag + * `hashtag_handler: nil` - a custom handler to validate and format a hashtag * `extra: false` - link urls with rarely used schemes (magnet, ipfs, irc, etc.) * `validate_tld: true` - Set to false to disable TLD validation for urls/emails, also can be set to :no_scheme to validate TLDs only for urls without a scheme (e.g `example.com` will be validated, but `http://example.loki` won't) * `iodata` - Set to `true` to return iodata as a result, or `:safe` for iodata with linkified anchor tags wrapped in Phoenix.HTML `:safe` tuples (removes need for further sanitization) + * `href_handler: nil` - a custom handler to process a url before it is set as the link href, useful for generating exit links """ def link(text, opts \\ []) do parse(text, opts) diff --git a/lib/linkify/builder.ex b/lib/linkify/builder.ex index 8edf7e8..0ce3661 100644 --- a/lib/linkify/builder.ex +++ b/lib/linkify/builder.ex @@ -42,8 +42,11 @@ defmodule Linkify.Builder do end end - defp build_attrs(attrs, url, _opts, :href) do - [{:href, url} | attrs] + defp build_attrs(attrs, url, opts, :href) do + case Map.get(opts, :href_handler) do + handler when is_function(handler) -> [{:href, handler.(url)} | attrs] + _ -> [{:href, url} | attrs] + end end defp add_scheme("http://" <> _ = url), do: url diff --git a/test/linkify_test.exs b/test/linkify_test.exs index 2568052..81f9688 100644 --- a/test/linkify_test.exs +++ b/test/linkify_test.exs @@ -339,6 +339,14 @@ defmodule LinkifyTest do assert MapSet.to_list(mentions) == [{"@friend", "friend"}] end + + test "href handler" do + text = ~s(google.com) + + result_text = Linkify.link(text, href_handler: &"/redirect?#{URI.encode_query(to: &1)}") + + assert result_text == ~s(google.com) + end end describe "mentions" do