Module: Fontico::Helper

Defined in:
lib/fontico/helper.rb

Overview

The whole point of the manifest: templates say what they mean, and never name a vendor. icon("save") and icon("logo") are the same call.

Instance Method Summary collapse

Instance Method Details

#icon(name, size: nil, variant: nil, **options) ⇒ Object

A glyph inherits font-size and colour from the text around it; an does not. width/height of 1em restores the first, currentColor baked into every body restores the second, and the generated stylesheet puts it on the baseline. Pass size: to override, or a CSS class — classes win over the attributes, so class: "size-6" works untouched.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/fontico/helper.rb', line 12

def icon(name, size: nil, variant: nil, **options)
  Fontico.check!(name.to_s)
  entry = Fontico.manifest[name.to_s]
  return missing(name) if entry.nil?

  symbol = entry.key
  attrs = {
    class: [Fontico.css_class, options.delete(:class)].compact.join(" "),
    width: size || "1em",
    height: size || "1em",
    style: inline_size(size, options.delete(:style)),
    "aria-hidden": options.key?(:title) ? nil : "true",
    role: options.key?(:title) ? "img" : nil
  }.merge(options).compact

  title = attrs.delete(:title)
  body = +""
  body << "<title>#{ERB::Util.html_escape(title)}</title>" if title
  body << %(<use href="#{sprite_path(variant)}##{symbol}"></use>)

  tag = %(<svg #{attrs.map { |k, v| %(#{k}="#{ERB::Util.html_escape(v)}") }.join(" ")}>#{body}</svg>)
  tag.respond_to?(:html_safe) ? tag.html_safe : tag
end

#icon_href(name) ⇒ Object

The <use href> for one icon, for markup this helper doesn't build — a Vue or Stimulus template, a JSON blob on its way to the client. Both halves are things a template shouldn't have to know: the sprite carries an asset digest, and a dotted manifest name is a dashed symbol id inside the file.

icon_href("game.aim")  # => "/assets/icons-ac89a32b.svg#game-aim"

Hand it to the client rather than reconstructing it there; see icons_sprite for the inline case, where the path half is empty and the fragment resolves against the current document.

Raises:



47
48
49
50
51
52
53
# File 'lib/fontico/helper.rb', line 47

def icon_href(name)
  Fontico.check!(name.to_s)
  entry = Fontico.manifest[name.to_s]
  raise Fontico::Error, "no icon named #{name.inspect} in #{Fontico.manifest_path}" if entry.nil?

  "#{sprite_path}##{entry.key}"
end

#icons_spriteObject

Embeds the symbol definitions directly, for pages served from a CDN where a cross-origin would silently render nothing.



57
58
59
60
61
# File 'lib/fontico/helper.rb', line 57

def icons_sprite
  Fontico.check!
  svg = File.read(Fontico.sprite_file)
  svg.respond_to?(:html_safe) ? svg.html_safe : svg
end