Class: Sevgi::Graphics::Element

Inherits:
Object
  • Object
show all
Defined in:
lib/sevgi/graphics/element.rb

Overview

SVG element node used by the graphics DSL.

Dynamic SVG element methods accept text, content objects, and any number of attribute Hashes in one call. Hashes are applied from left to right; later values replace earlier values unless their names use the + update suffix.

Direct Known Subclasses

Document::Proto

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, parent:, attributes: {}, contents: []) { ... } ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Creates an element.

Parameters:

  • name (Symbol)

    SVG element name

  • parent (Sevgi::Graphics::Element, Object)

    parent element or root sentinel

  • attributes (Hash) (defaults to: {})

    SVG attributes

  • contents (Array<Sevgi::Graphics::Content>) (defaults to: [])

    content objects

Yields:

  • evaluates the drawing DSL in the new element

Yield Returns:

  • (Object)

    ignored block result

Raises:

  • (Sevgi::ArgumentError)

    when the parent has a different concrete element class

  • (Sevgi::ArgumentError)

    when the element name or an attribute is not valid XML



163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/sevgi/graphics/element.rb', line 163

def initialize(name, parent:, attributes: {}, contents: [], &block)
  Element.send(:validate_parent, self, parent)

  unless name.is_a?(::String) || name.is_a?(::Symbol)
    ArgumentError.("XML element name must be a String or Symbol")
  end

  @name = XML.name(name, context: "XML element name").to_sym
  @attributes = Attributes.new(attributes)
  @children = []
  @contents = contents.dup
  @parent = parent

  Element.send(:attach, self, parent) unless Element.root?(self)

  instance_exec(&block) if block
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *arguments) { ... } ⇒ Sevgi::Graphics::Element (private)

Dispatches SVG element DSL calls and caches valid element methods.

Parameters:

  • name (Symbol)

    missing method name

  • arguments (Array<Hash, String, Sevgi::Graphics::Content>)

    ordered content and attribute channels; later Hashes replace or update attributes assigned by earlier Hashes

Yields:

  • evaluates the drawing DSL in the dispatched child element

Yield Returns:

  • (Object)

    ignored block result

Returns:

Raises:

  • (NameError)

    when the name is not a valid SVG element

  • (Sevgi::ArgumentError)

    when an argument cannot be parsed as attributes or content



190
191
192
# File 'lib/sevgi/graphics/element.rb', line 190

def method_missing(name, *arguments, &block)
  Element.valid?(tag = Element.send(:id, name)) ? Dispatch.(self, name, tag, *arguments, &block) : super
end

Instance Attribute Details

#attributesSevgi::Graphics::Attributes

Returns the attribute store.



135
136
137
# File 'lib/sevgi/graphics/element.rb', line 135

def attributes
  @attributes
end

#childrenArray<Sevgi::Graphics::Element>

Returns a read-only snapshot of child elements in rendering order.

Returns:



139
# File 'lib/sevgi/graphics/element.rb', line 139

def children = @children.dup.freeze

#contentsArray<Sevgi::Graphics::Content>

Returns a read-only snapshot of element content objects in rendering order.

Returns:



143
# File 'lib/sevgi/graphics/element.rb', line 143

def contents = @contents.dup.freeze

#nameSymbol (readonly)

Returns the SVG element name.

Returns:

  • (Symbol)


131
132
133
# File 'lib/sevgi/graphics/element.rb', line 131

def name
  @name
end

#parentSevgi::Graphics::Element?

Note:

Use Root? to distinguish a document root from a detached subtree root.

Returns the parent element.

Returns:



148
149
150
# File 'lib/sevgi/graphics/element.rb', line 148

def parent
  @parent if @parent.is_a?(self.class)
end

Class Method Details

.element(name, *arguments, parent:) { ... } ⇒ Sevgi::Graphics::Element

Builds an element node.

Parameters:

Yields:

  • evaluates the drawing DSL in the new element

Yield Returns:

  • (Object)

    ignored block result

Returns:

Raises:

  • (Sevgi::ArgumentError)

    when an argument cannot be parsed as attributes or content

  • (Sevgi::ArgumentError)

    when the parent has a different concrete element class

  • (Sevgi::ArgumentError)

    when the element name or an attribute is not valid XML



27
28
29
30
# File 'lib/sevgi/graphics/element.rb', line 27

def self.element(name, *arguments, parent:, &block)
  validate_parent_class(self, parent)
  new(name, **Dispatch.parse(name, *arguments), parent:, &block)
end

.root(*arguments) { ... } ⇒ Sevgi::Graphics::Element

Builds an SVG root element.

Parameters:

Yields:

  • evaluates the drawing DSL in the root element

Yield Returns:

  • (Object)

    ignored block result

Returns:

Raises:

  • (Sevgi::ArgumentError)

    when an argument is not a Hash, String, or Content

  • (Sevgi::ArgumentError)

    when a root attribute or content value is not valid XML



39
# File 'lib/sevgi/graphics/element.rb', line 39

def self.root(*arguments, &block) = element(:svg, *arguments, parent: RootParent, &block)

.root?(element) ⇒ Boolean

Reports whether an element is the root element.

Parameters:

Returns:

  • (Boolean)


44
# File 'lib/sevgi/graphics/element.rb', line 44

def self.root?(element) = Element.send(:tree_parent, element).equal?(RootParent)

.valid?(name) ⇒ Boolean

Reports whether a candidate can dispatch as an SVG element name. With Standard loaded, the name must be known; standalone Graphics accepts any valid XML name.

Parameters:

  • name (Object)

    candidate element name

Returns:

  • (Boolean)


15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
# File 'lib/sevgi/graphics/element.rb', line 15

class Element
  # Builds an element node.
  # @param name [Symbol, String] SVG element name
  # @param arguments [Array<Hash, String, Sevgi::Graphics::Content>] ordered content and attribute channels; every
  #   Hash is applied through {Sevgi::Graphics::Attributes} from left to right
  # @param parent [Sevgi::Graphics::Element] parent element
  # @yield evaluates the drawing DSL in the new element
  # @yieldreturn [Object] ignored block result
  # @return [Sevgi::Graphics::Element]
  # @raise [Sevgi::ArgumentError] when an argument cannot be parsed as attributes or content
  # @raise [Sevgi::ArgumentError] when the parent has a different concrete element class
  # @raise [Sevgi::ArgumentError] when the element name or an attribute is not valid XML
  def self.element(name, *arguments, parent:, &block)
    validate_parent_class(self, parent)
    new(name, **Dispatch.parse(name, *arguments), parent:, &block)
  end

  # Builds an SVG root element.
  # @param arguments [Array<Hash, String, Sevgi::Graphics::Content>] ordered content and attribute channels
  # @yield evaluates the drawing DSL in the root element
  # @yieldreturn [Object] ignored block result
  # @return [Sevgi::Graphics::Element]
  # @raise [Sevgi::ArgumentError] when an argument is not a Hash, String, or Content
  # @raise [Sevgi::ArgumentError] when a root attribute or content value is not valid XML
  def self.root(*arguments, &block) = element(:svg, *arguments, parent: RootParent, &block)

  # Reports whether an element is the root element.
  # @param element [Sevgi::Graphics::Element] element to test
  # @return [Boolean]
  def self.root?(element) = Element.send(:tree_parent, element).equal?(RootParent)

  def self.element_method?(name) = Dispatch.cached?(name)

  private_class_method :element_method?

  class << self
    private

    def attach(element, parent, index: nil)
      children = tree_children(parent)
      index ? children.insert(index, element) : children << element
      element.instance_variable_set(:@parent, parent)
    end

    def detach(element)
      parent = tree_parent(element)
      tree_children(parent).delete(element) if parent.is_a?(element.class)
      element.instance_variable_set(:@parent, DetachedParent)
    end

    def tree_children(element) = element.instance_variable_get(:@children)

    def tree_parent(element) = element.instance_variable_get(:@parent)

    def validate_parent(element, parent)
      validate_parent_class(element.class, parent)
    end

    def validate_parent_class(element_class, parent)
      return if parent.equal?(RootParent) || parent.instance_of?(element_class)

      ArgumentError.("Element type does not match the parent type: #{element_class}")
    end
  end

  class << self
    require "sevgi/standard"

    # Reports whether a candidate can dispatch as a known SVG element name.
    # @param name [Object] candidate element name
    # @return [Boolean]
    def valid?(name)
      Standard.element?(name)
    rescue Sevgi::ArgumentError
      false
    end

  rescue ::LoadError => e
    raise unless e.path == "sevgi/standard"

    # Reports whether a candidate can dispatch as a valid XML element name.
    # @param name [Object] candidate element name
    # @return [Boolean]
    def valid?(name)
      return false unless name.is_a?(::String) || name.is_a?(::Symbol)

      XML.name(name, context: "SVG element name")
      true
    rescue Sevgi::ArgumentError
      false
    end
  end

  private_class_method :new

  # Sentinel parents used by root and detached elements.
  RootParent = Object.new.tap { def it.inspect = "RootParent" }.freeze
  DetachedParent = Object.new.tap { def it.inspect = "DetachedParent" }.freeze

  private_constant :DetachedParent, :RootParent

  # SVG element method-name normalization.
  # @api private
  module Ident
    # Normalizes a Ruby method name into an SVG element id.
    # @param given [Symbol, String] method name
    # @return [Symbol]
    def id(given) = (@id ||= {})[given] ||= given.to_s.tr("_", "-").to_sym
  end

  extend Ident
  private_class_method :id
  private_constant :Ident

  # Returns the SVG element name.
  # @return [Symbol]
  attr_reader :name

  # Returns the attribute store.
  # @return [Sevgi::Graphics::Attributes]
  attr_reader :attributes

  # Returns a read-only snapshot of child elements in rendering order.
  # @return [Array<Sevgi::Graphics::Element>] frozen child snapshot
  def children = @children.dup.freeze

  # Returns a read-only snapshot of element content objects in rendering order.
  # @return [Array<Sevgi::Graphics::Content>] frozen content snapshot
  def contents = @contents.dup.freeze

  # Returns the parent element.
  # @return [Sevgi::Graphics::Element, nil] parent element, or nil for a root or detached element
  # @note Use `Root?` to distinguish a document root from a detached subtree root.
  def parent
    @parent if @parent.is_a?(self.class)
  end

  # Creates an element.
  # @param name [Symbol] SVG element name
  # @param parent [Sevgi::Graphics::Element, Object] parent element or root sentinel
  # @param attributes [Hash] SVG attributes
  # @param contents [Array<Sevgi::Graphics::Content>] content objects
  # @yield evaluates the drawing DSL in the new element
  # @yieldreturn [Object] ignored block result
  # @return [void]
  # @raise [Sevgi::ArgumentError] when the parent has a different concrete element class
  # @raise [Sevgi::ArgumentError] when the element name or an attribute is not valid XML
  # @api private
  def initialize(name, parent:, attributes: {}, contents: [], &block)
    Element.send(:validate_parent, self, parent)

    unless name.is_a?(::String) || name.is_a?(::Symbol)
      ArgumentError.("XML element name must be a String or Symbol")
    end

    @name = XML.name(name, context: "XML element name").to_sym
    @attributes = Attributes.new(attributes)
    @children = []
    @contents = contents.dup
    @parent = parent

    Element.send(:attach, self, parent) unless Element.root?(self)

    instance_exec(&block) if block
  end

  # Dispatches SVG element DSL calls and caches valid element methods.
  # @param name [Symbol] missing method name
  # @param arguments [Array<Hash, String, Sevgi::Graphics::Content>] ordered content and attribute channels; later
  #   Hashes replace or update attributes assigned by earlier Hashes
  # @yield evaluates the drawing DSL in the dispatched child element
  # @yieldreturn [Object] ignored block result
  # @return [Sevgi::Graphics::Element]
  # @raise [NameError] when the name is not a valid SVG element
  # @raise [Sevgi::ArgumentError] when an argument cannot be parsed as attributes or content
  def method_missing(name, *arguments, &block)
    Element.valid?(tag = Element.send(:id, name)) ? Dispatch.(self, name, tag, *arguments, &block) : super
  end

  # Reports whether a missing method can dispatch to an SVG element.
  # @param name [Symbol] queried method name
  # @param include_private [Boolean] standard Ruby respond_to? flag
  # @return [Boolean]
  # @api private
  def respond_to_missing?(name, include_private = false)
    Element.valid?(Element.send(:id, name)) || super
  end

  private :method_missing, :respond_to_missing?

  # Element method-missing parser and cache.
  # @api private
  module Dispatch
    extend self

    # Dispatches an element DSL call.
    # @param element [Sevgi::Graphics::Element] parent element
    # @param method [Symbol] Ruby method name
    # @param tag [Symbol] SVG element name
    # @return [Sevgi::Graphics::Element]
    def call(element, method, tag, *, &)
      unless Element.method_defined?(method)
        Element.class_exec do
          define_method(method) { |*args, &block| self.class.element(tag, *args, parent: self, &block) }
        end

        (@methods ||= {})[method] = Element.instance_method(method)
      end

      element.public_send(method, *, &)
    end

    def cached?(method)
      cached = @methods&.[](method)

      cached && Element.method_defined?(method) && Element.instance_method(method) == cached
    end

    # Parses element DSL arguments.
    # @param name [Symbol] SVG element name
    # @param args [Array<Object>] positional DSL arguments; Hashes are imported from left to right
    # @return [Hash] parsed :attributes and :contents
    # @raise [Sevgi::ArgumentError] when an argument is not a Hash, String, or Content
    def parse(name, *args)
      attributes, contents = Attributes.new, []

      args.each do |arg|
        case arg
        when ::Hash
          attributes.merge!(arg)
        when ::String
          contents << Content.encoded(arg)
        when Content
          contents << arg
        else
          ArgumentError.("Argument of element '#{name}' must be a Hash, String, or Content: #{arg}")
        end
      end

      {attributes: attributes.to_h, contents:}
    end
  end

  private_constant :Dispatch

  protected

  attr_writer :attributes, :children, :contents, :parent
end