b9c8e309e06557a8b64d35de630cb4152568237d
[rails.git] / app / helpers / social_share_button_helper.rb
1 module SocialShareButtonHelper
2   require "uri"
3
4   SOCIAL_SHARE_CONFIG = {
5     :email => "social_icons/email.svg",
6     :bluesky => "social_icons/bluesky.svg",
7     :facebook => "social_icons/facebook.svg",
8     :linkedin => "social_icons/linkedin.svg",
9     :mastodon => "social_icons/mastodon.svg",
10     :telegram => "social_icons/telegram.svg",
11     :x => "social_icons/x.svg"
12   }.freeze
13
14   # Generates a set of social share buttons based on the specified options.
15   def social_share_buttons(title:, url:)
16     tag.div(
17       :class => "social-share-buttons d-flex gap-1 align-items-end flex-wrap mb-3"
18     ) do
19       buttons = [
20         tag.button(:type => "button",
21                    :class => "btn btn-secondary p-1 border-1 rounded-circle",
22                    :title => I18n.t("application.share.share.title"),
23                    :hidden => true,
24                    :data => { :share_type => "native" }) do
25           image_tag("social_icons/share.svg", :alt => I18n.t("application.share.share.alt"), :size => 18, :class => "d-block")
26         end
27       ]
28
29       buttons << SOCIAL_SHARE_CONFIG.map do |site, icon|
30         link_options = {
31           :rel => "nofollow",
32           :class => "rounded-circle focus-ring",
33           :title => I18n.t("application.share.#{site}.title"),
34           :target => "_blank",
35           :data => { :share_type => site == :email ? "email" : "site" }
36         }
37
38         link_to generate_share_url(site, title, url), link_options do
39           image_tag(icon, :alt => I18n.t("application.share.#{site}.alt"), :size => 28)
40         end
41       end
42
43       safe_join(buttons, "\n")
44     end
45   end
46
47   private
48
49   def generate_share_url(site, title, url)
50     site = site.to_sym
51     title = URI.encode_uri_component(title)
52     url = URI.encode_uri_component(url)
53
54     case site
55     when :email
56       "mailto:?subject=#{title}&body=#{url}"
57     when :x
58       "https://x.com/intent/tweet?url=#{url}&text=#{title}"
59     when :linkedin
60       "https://www.linkedin.com/sharing/share-offsite/?url=#{url}"
61     when :facebook
62       "https://www.facebook.com/sharer/sharer.php?u=#{url}&t=#{title}"
63     when :mastodon
64       "https://mastodonshare.com/?text=#{title}&url=#{url}"
65     when :telegram
66       "https://t.me/share/url?url=#{url}&text=#{title}"
67     when :bluesky
68       "https://bsky.app/intent/compose?text=#{title}+#{url}"
69     else
70       raise ArgumentError, "Unsupported platform: #{platform}"
71     end
72   end
73 end