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