commit: df559cd2ae5f082df962d5bdbb590725dc6b365b
parent b50bd58d707ccaae782b8118a38e3c4f165c3886
Author: rinpatch <rinpatch@sdf.org>
Date: Thu, 19 Nov 2020 19:25:18 +0000
Merge branch 'handle-href' into 'master'
Add handle_href option for href pre-processing
Closes #19
See merge request pleroma/elixir-libraries/linkify!31
Diffstat:
3 files changed, 16 insertions(+), 4 deletions(-)
diff --git 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
@@ -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
@@ -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(<a href="/redirect?to=http%3A%2F%2Fgoogle.com">google.com</a>)
+ end
end
describe "mentions" do