]> git.openstreetmap.org Git - rails.git/blob - app/helpers/svg_helper.rb
Merge pull request #5932 from tomhughes/frozen-strings
[rails.git] / app / helpers / svg_helper.rb
1 # frozen_string_literal: true
2
3 module SvgHelper
4   def previous_page_svg_tag(**)
5     adjacent_page_svg_tag(dir == "rtl" ? 1 : -1, **)
6   end
7
8   def next_page_svg_tag(**)
9     adjacent_page_svg_tag(dir == "rtl" ? -1 : 1, **)
10   end
11
12   def legend_svg_tag(**options)
13     border_width = options["border"] ? (options["border-width"] || 1) : 0
14     rect_attrs = {
15       :width => "100%",
16       :height => "100%",
17       :fill => options["fill"] || "none"
18     }
19     if border_width.positive?
20       rect_attrs[:x] = rect_attrs[:y] = format("%g", 0.5 * border_width)
21       rect_attrs[:width] = options["width"] - border_width
22       rect_attrs[:height] = options["height"] - border_width
23     end
24     svg_attrs = options.slice("width", "height", "opacity", :class)
25
26     tag.svg(**svg_attrs) do
27       horizontal = "H#{options['width']}"
28       concat tag.rect(**rect_attrs, **stroke_attrs(options, "border")) if options["fill"] || options["border"]
29       if options["line"]
30         y_middle = format("%g", 0.5 * options["height"])
31         concat tag.path(:d => "M0,#{y_middle} #{horizontal}", **stroke_attrs(options, "line"))
32       end
33       if options["casing"]
34         casing_width = options["casing-width"] || 1
35         y_top = format("%g", 0.5 * casing_width)
36         y_bottom = format("%g", options["height"] - (0.5 * casing_width))
37         concat tag.path(:d => "M0,#{y_top} #{horizontal} M0,#{y_bottom} #{horizontal}", **stroke_attrs(options, "casing"))
38       end
39     end
40   end
41
42   private
43
44   # returns "<" shape if side == -1; ">" if side == 1
45   def adjacent_page_svg_tag(side, **options)
46     count = options[:count] || 1
47     height = options[:height] || 15
48     pad = 2
49     segment = (0.5 * height) - pad
50     width = (segment + (2 * count * pad)).ceil
51     angled_line_data = "l#{side * segment},#{segment} l#{-side * segment},#{segment}"
52     path_data = Array.new(count) { |i| "M#{side * ((2 * i) + 1) * pad},#{pad} #{angled_line_data}" }.join(" ")
53     path_tag = tag.path :d => path_data, :fill => "none", :stroke => "currentColor", :"stroke-width" => 1.5
54     view_box = "#{-width} 0 #{width} #{height}" if side.negative?
55     tag.svg path_tag, :width => width, :height => height, :viewBox => view_box, :class => options[:class]
56   end
57
58   def stroke_attrs(attrs, prefix)
59     attrs.select { |key| key.start_with?(prefix) }.transform_keys { |key| key.delete_prefix(prefix).prepend("stroke") }
60   end
61 end