Skip to content

A platform for community discussion. Free, open, simple.

4.7 KB
Raw Blame
# frozen_string_literal: true

module SvgSprite
  # Vendors the icon package's sprites. Names dropped upstream are kept in a
  # legacy sprite so existing references keep rendering: renamed icons use
  # their successor's artwork, removed icons keep their last vendored artwork.
  class FontAwesomeSync
    class UnsafeSpriteError < StandardError
    end

    STYLES = %w[solid regular brands].freeze
    CURRENT_DIRECTORY = "fontawesome"
    LEGACY_DIRECTORY = "fontawesome-legacy"

    # The bundled sprite is inserted into every page with innerHTML, so only plain
    # path artwork is accepted from the package.
    ALLOWED_ATTRIBUTES = { "symbol" => %w[id viewBox], "path" => %w[d] }.freeze

    # A fill on the path beats the fill inherited from the icon's <svg>, which is
    # how themes and plugins color icons.
    PATH_FILL = /\s+fill=(["'])currentcolor\1/i
    ICON_ID = /\A[a-z0-9]+(?:-[a-z0-9]+)*\z/

    LEGACY_HEADER = <<~XML
      <?xml version="1.0" encoding="UTF-8"?>
      <!--
      Icon names no longer in Font Awesome Free, kept for backwards compatibility.
      Generated by `bin/rake svgicons:update`, do not edit by hand.
      License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License)
      -->
      <svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
    XML

    def initialize(
      package_path: Rails.root.join("node_modules/@fortawesome/fontawesome-free"),
      vendor_path: Rails.root.join("vendor/assets/svg-icons")
    )
      @package_path = Pathname.new(package_path)
      @vendor_path = Pathname.new(vendor_path)
    end

    # Maps each vendored path to its expected content, or nil when it shouldn't exist.
    def files
      @files ||=
        STYLES.each_with_object({}) do |style, files|
          upstream = @package_path.join("sprites/#{style}.svg").read.gsub(PATH_FILL, "")
          upstream_symbols = symbols(upstream)
          verify!(style, upstream_symbols)

          files[current_path(style)] = upstream
          files[legacy_path(style)] = legacy_sprite(style, upstream_symbols)
        end
    end

    def stale_files
      files.filter_map { |path, content| path if read(path) != content }
    end

    def write!
      files.each do |path, content|
        if content
          path.dirname.mkpath
          path.write(content)
        elsif path.exist?
          path.delete
        end
      end
    end

    private

    def verify!(style, symbols)
      unsafe = symbols.reject { |id, symbol| safe_symbol?(id, symbol) }.keys
      return if unsafe.empty?

      raise UnsafeSpriteError,
            "#{style}.svg has icons with unexpected markup, refusing to vendor it: #{unsafe.first(10).join(", ")}"
    end

    def safe_symbol?(id, symbol)
      id.to_s.match?(ICON_ID) &&
        symbol
          .xpath("descendant-or-self::node()")
          .all? do |node|
            next node.content.strip.empty? if node.text?

            allowed = ALLOWED_ATTRIBUTES[node.name]
            node.element? && allowed.present? &&
              node.attribute_nodes.all? { |attribute| allowed.include?(attribute.name) }
          end
    end

    def legacy_sprite(style, upstream_symbols)
      candidates = symbols(read(legacy_path(style))).merge(symbols(read(current_path(style))))

      entries =
        candidates
          .except(*upstream_symbols.keys)
          .sort
          .map do |id, symbol|
            successor = aliases[id]

            if (successor_symbol = upstream_symbols[successor])
              ["#{id}: renamed to #{successor}", successor_symbol.dup.tap { _1["id"] = id }]
            else
              ["#{id}: removed, previous artwork kept", symbol]
            end
          end

      return if entries.empty?

      LEGACY_HEADER +
        entries.map { |comment, symbol| "<!-- #{comment} -->\n#{serialize(symbol)}\n" }.join +
        "</svg>\n"
    end

    def symbols(sprite)
      return {} if sprite.nil?

      doc = Nokogiri.XML(sprite) { |config| config.strict.noblanks }
      doc.remove_namespaces!
      doc.css("symbol").index_by { |symbol| symbol["id"] }
    end

    def serialize(symbol)
      symbol.to_xml(save_with: Nokogiri::XML::Node::SaveOptions::AS_XML)
    end

    def aliases
      @aliases ||=
        JSON
          .parse(@package_path.join("metadata/icon-families.json").read)
          .each_with_object({}) do |(id, icon), aliases|
            icon.dig("aliases", "names")&.each { |name| aliases[name] = id }
          end
    end

    def read(path)
      path.read if path.exist?
    end

    def current_path(style)
      @vendor_path.join(CURRENT_DIRECTORY, "#{style}.svg")
    end

    def legacy_path(style)
      @vendor_path.join(LEGACY_DIRECTORY, "#{style}.svg")
    end
  end
end