]> git.openstreetmap.org Git - rails.git/blob - app/helpers/social_share_button_helper.rb
Merge remote-tracking branch 'upstream/pull/5937'
[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",
25                               :share_text => title,
26                               :share_url => url }) do
27           image_tag("social_icons/share.svg", :alt => I18n.t("application.share.share.alt"), :size => 18, :class => "d-block")
28         end
29       ]
30
31       buttons << SOCIAL_SHARE_CONFIG.map do |site, icon|
32         link_options = {
33           :rel => "nofollow",
34           :class => "rounded-circle focus-ring",
35           :title => I18n.t("application.share.#{site}.title"),
36           :target => "_blank",
37           :data => { :share_type => site == :email ? "email" : "site" }
38         }
39
40         link_to generate_share_url(site, title, url), link_options do
41           image_tag(icon, :alt => I18n.t("application.share.#{site}.alt"), :size => 28)
42         end
43       end
44
45       safe_join(buttons, "\n")
46     end
47   end
48
49   private
50
51   def generate_share_url(site, title, url)
52     site = site.to_sym
53     title = URI.encode_uri_component(title)
54     url = URI.encode_uri_component(url)
55
56     case site
57     when :email
58       "mailto:?subject=#{title}&body=#{url}"
59     when :x
60       "https://x.com/intent/tweet?url=#{url}&text=#{title}"
61     when :linkedin
62       "https://www.linkedin.com/sharing/share-offsite/?url=#{url}"
63     when :facebook
64       "https://www.facebook.com/sharer/sharer.php?u=#{url}&t=#{title}"
65     when :mastodon
66       "https://mastodonshare.com/?text=#{title}&url=#{url}"
67     when :telegram
68       "https://t.me/share/url?url=#{url}&text=#{title}"
69     when :bluesky
70       "https://bsky.app/intent/compose?text=#{title}+#{url}"
71     else
72       raise ArgumentError, "Unsupported platform: #{platform}"
73     end
74   end
75 end