class SvgOptimizer::Plugins::CleanupId

Constants

IDS
LETTERS

Public Instance Methods

cleanup_id(node) click to toggle source
# File lib/svg_optimizer/plugins/cleanup_id.rb, line 30
def cleanup_id(node)
  # Keep ids if there's no available id.
  # This means that 1300+ ids have been used so far. CRAZY!
  return if ids.empty?

  old_id = node[:id]
  new_id = ids.shift
  node[:id] = new_id

  remove_unused_id(
    node,
    replace_url_references(old_id, new_id),
    replace_href_references(old_id, new_id)
  )
end
ids() click to toggle source
# File lib/svg_optimizer/plugins/cleanup_id.rb, line 14
def ids
  @ids ||= IDS.dup
end
process() click to toggle source
# File lib/svg_optimizer/plugins/cleanup_id.rb, line 18
def process
  # If there's a <script> or <style>, don't mess with ids.
  return if xml.css("script, style").any?

  # SVG can have ids as arrays.
  # Skip id optimization if that's the case.
  return if xml.css("[id^='[']").size.nonzero?

  # Replace the ids otherwise.
  xml.css("[id]").each(&method(:cleanup_id))
end
remove_unused_id(node, has_url_refs, has_href_refs) click to toggle source
# File lib/svg_optimizer/plugins/cleanup_id.rb, line 46
def remove_unused_id(node, has_url_refs, has_href_refs)
  return if has_url_refs
  return if has_href_refs

  node.remove_attribute("id")
end
replace_href_references(old_id, new_id) click to toggle source
# File lib/svg_optimizer/plugins/cleanup_id.rb, line 69
def replace_href_references(old_id, new_id)
  scopes = ["[href='##{old_id}']"]
  scopes << "[xlink|href='##{old_id}']" if xlink_namespace?

  nodes = xml.css(scopes.join(","))

  nodes.each do |node|
    node.attributes.map(&:last).each do |attr|
      attr.value = "##{new_id}" if attr.value == "##{old_id}"
    end
  end

  nodes.any?
end
replace_url_references(old_id, new_id) click to toggle source
# File lib/svg_optimizer/plugins/cleanup_id.rb, line 53
def replace_url_references(old_id, new_id)
  nodes = xml.xpath(%{//*[@*="url(##{old_id})"]})

  nodes.each do |node|
    node.attributes.map(&:last).each do |attr|
      attr.value = %[url(##{new_id})] if attr.value == %[url(##{old_id})]
    end
  end

  nodes.any?
end