Class: SvgOptimizer::Plugins::CleanupId

Inherits:
Base
  • Object
show all
Defined in:
lib/svg_optimizer/plugins/cleanup_id.rb

Constant Summary collapse

LETTERS =
%w[
  a b c d e f g h i j k l m n o p q r s t u v w x y z
  A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
]
IDS =
LETTERS.concat(LETTERS.combination(2).to_a)

Instance Attribute Summary

Attributes inherited from Base

#xml

Instance Method Summary collapse

Methods inherited from Base

#initialize

Constructor Details

This class inherits a constructor from SvgOptimizer::Plugins::Base

Instance Method Details

#cleanup_id(node) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/svg_optimizer/plugins/cleanup_id.rb', line 23

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

#idsObject



11
12
13
# File 'lib/svg_optimizer/plugins/cleanup_id.rb', line 11

def ids
  @ids ||= IDS.dup
end

#processObject



15
16
17
18
19
20
21
# File 'lib/svg_optimizer/plugins/cleanup_id.rb', line 15

def process
  # If there a <script> or <style>, don't mess with ids.
  return if xml.css("script, style").any?

  # Replace the ids otherwise.
  xml.css("[id]").each(&method(:cleanup_id))
end

#remove_unused_id(node, has_url_refs, has_href_refs) ⇒ Object



39
40
41
42
43
# File 'lib/svg_optimizer/plugins/cleanup_id.rb', line 39

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) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
# File 'lib/svg_optimizer/plugins/cleanup_id.rb', line 57

def replace_href_references(old_id, new_id)
  nodes = xml.css("[href='##{old_id}'], [xlink|href='##{old_id}']")

  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) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
# File 'lib/svg_optimizer/plugins/cleanup_id.rb', line 45

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