]> git.openstreetmap.org Git - rails.git/blob - lib/social_share_button_helper.rb
Merge pull request #5411 from tomhughes/bluesky-sharing
[rails.git] / lib / 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   def self.filter_allowed_sites(sites)
15     valid_sites = sites.empty? ? SOCIAL_SHARE_CONFIG.keys : sites.select { |site| valid_site?(site) }
16     invalid_sites = sites - valid_sites
17     [valid_sites, invalid_sites]
18   end
19
20   def self.icon_path(site)
21     SOCIAL_SHARE_CONFIG[site.to_sym] || ""
22   end
23
24   def self.valid_site?(site)
25     SOCIAL_SHARE_CONFIG.key?(site.to_sym)
26   end
27
28   def self.generate_share_url(site, params)
29     site = site.to_sym
30     case site
31     when :email
32       to = params[:to] || ""
33       subject = CGI.escape(params[:title])
34       body = CGI.escape(params[:url])
35       "mailto:#{to}?subject=#{subject}&body=#{body}"
36     when :x
37       via_str = params[:via] ? "&via=#{URI.encode_www_form_component(params[:via])}" : ""
38       hashtags_str = params[:hashtags] ? "&hashtags=#{URI.encode_www_form_component(params[:hashtags].join(','))}" : ""
39       "https://x.com/intent/tweet?url=#{URI.encode_www_form_component(params[:url])}&text=#{URI.encode_www_form_component(params[:title])}#{hashtags_str}#{via_str}"
40     when :linkedin
41       "https://www.linkedin.com/sharing/share-offsite/?url=#{URI.encode_www_form_component(params[:url])}"
42     when :facebook
43       "https://www.facebook.com/sharer/sharer.php?u=#{URI.encode_www_form_component(params[:url])}&t=#{URI.encode_www_form_component(params[:title])}"
44     when :mastodon
45       "https://mastodonshare.com/?text=#{URI.encode_www_form_component(params[:title])}&url=#{URI.encode_www_form_component(params[:url])}"
46     when :telegram
47       "https://t.me/share/url?url=#{URI.encode_www_form_component(params[:url])}&text=#{URI.encode_www_form_component(params[:title])}"
48     when :bluesky
49       "https://bsky.app/intent/compose?text=#{URI.encode_www_form_component(params[:title])}+#{URI.encode_www_form_component(params[:url])}"
50     else
51       raise ArgumentError, "Unsupported platform: #{platform}"
52     end
53   end
54 end