Class: Browser::DOM::Element

Inherits:
Node show all
Includes:
Event::Target
Defined in:
opal/browser/effects.rb,
opal/browser/dom/element.rb,
opal/browser/dom/element/data.rb,
opal/browser/dom/element/form.rb,
opal/browser/dom/element/size.rb,
opal/browser/dom/element/image.rb,
opal/browser/dom/element/input.rb,
opal/browser/dom/element/media.rb,
opal/browser/dom/element/button.rb,
opal/browser/dom/element/iframe.rb,
opal/browser/dom/element/offset.rb,
opal/browser/dom/element/scroll.rb,
opal/browser/dom/element/select.rb,
opal/browser/dom/element/editable.rb,
opal/browser/dom/element/position.rb,
opal/browser/dom/element/template.rb,
opal/browser/dom/element/textarea.rb,
opal/browser/dom/element/attributes.rb

Defined Under Namespace

Classes: Attributes, Audio, Button, Data, Form, Iframe, Image, Input, Media, Offset, Position, Scroll, Select, Size, Template, Textarea, Video

Constant Summary collapse

Img =
Image

Constants inherited from Node

Node::ATTRIBUTE_NODE, Node::CDATA_SECTION_NODE, Node::COMMENT_NODE, Node::DOCUMENT_FRAGMENT_NODE, Node::DOCUMENT_NODE, Node::DOCUMENT_TYPE_NODE, Node::ELEMENT_NODE, Node::ENTITY_NODE, Node::ENTITY_REFERENCE_NOCE, Node::NOTATION_NODE, Node::PROCESSING_INSTRUCTION_NODE, Node::TEXT_NODE

Instance Attribute Summary collapse

Attributes inherited from Node

#child, #children, #document, #element_children, #first_element_child, #inner_html, #last_element_child, #name, #namespace, #next, #next_element, #node_type, #parent, #previous, #previous_element, #value

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Event::Target

#off, #on, #on!, #one, #trigger, #trigger!

Methods inherited from Node

#<<, #==, #>>, #add_child, #add_next_sibling, #add_previous_sibling, #ancestors, #append_to, #blank?, #cdata?, #clear, #comment?, #content, #content=, #document?, #elem?, #fragment?, #initialize_copy, #parse, #path, #prepend_to, #remove, #remove_child, #replace, #text?, #traverse

Methods included from NativeCachedWrapper

#restricted?, #set_native_reference

Instance Attribute Details

#attribute_nodesNodeSet (readonly)

Returns the attribute nodes for the element.

Returns:

  • (NodeSet)

    the attribute nodes for the element


222
223
224
# File 'opal/browser/dom/element.rb', line 222

def attribute_nodes
  NodeSet[Native::Array.new(`#@native.attributes`, get: :item)]
end

#attributesAttributes (readonly)

Returns the attributes for the element.

Returns:


216
217
218
# File 'opal/browser/dom/element.rb', line 216

def attributes(options = {})
  Attributes.new(self, options)
end

#class_nameString (readonly)

Returns all the element class names.

Returns:

  • (String)

    all the element class names


228
# File 'opal/browser/dom/element.rb', line 228

alias_native :class_name, :className

#class_namesArray<String> (readonly)

Returns all the element class names.

Returns:

  • (Array<String>)

    all the element class names


232
233
234
# File 'opal/browser/dom/element.rb', line 232

def class_names
  `#@native.className`.split(/\s+/).reject(&:empty?)
end

#editableBoolean?

Returns the value of contentEditable for this element.

Returns:

  • (Boolean?)

    the value of contentEditable for this element


8
9
10
11
12
13
14
15
16
17
# File 'opal/browser/dom/element/editable.rb', line 8

def editable
  case `#@native.contentEditable`
  when "true"
    true
  when "false"
    false
  when "inherit"
    nil
  end
end

#heightInteger

Returns the height of the element.

Returns:

  • (Integer)

    the height of the element


298
299
300
# File 'opal/browser/dom/element.rb', line 298

def height
  size.height
end

#idString?

Returns the ID of the element.

Returns:

  • (String?)

    the ID of the element


308
309
310
311
312
313
314
315
316
317
318
319
# File 'opal/browser/dom/element.rb', line 308

def id
  %x{
    var id = #@native.id;

    if (id === "") {
      return nil;
    }
    else {
      return id;
    }
  }
end

#offsetOffset

Returns the offset of the element.

Returns:

  • (Offset)

    the offset of the element


360
361
362
363
364
365
366
367
368
# File 'opal/browser/dom/element.rb', line 360

def offset(*values)
  off = Offset.new(self)

  unless values.empty?
    off.set(*values)
  end

  off
end

#positionPosition (readonly)

Returns the position of the element.

Returns:

  • (Position)

    the position of the element


376
377
378
# File 'opal/browser/dom/element.rb', line 376

def position
  @position ||= Position.new(self)
end

#scrollScroll (readonly)

Returns the scrolling for the element.

Returns:

  • (Scroll)

    the scrolling for the element


382
383
384
# File 'opal/browser/dom/element.rb', line 382

def scroll
  @scroll ||= Scroll.new(self)
end

#sizeSize (readonly)

Returns the size of the element.

Returns:

  • (Size)

    the size of the element


501
502
503
# File 'opal/browser/dom/element.rb', line 501

def size(*inc)
  Size.new(self, *inc)
end

#style!CSS::Declaration (readonly)

Returns get the computed style for the element.

Returns:

Raises:

  • (NotImplementedError)

470
471
472
# File 'opal/browser/dom/element.rb', line 470

def style!
  CSS::Declaration.new(`#{window.to_n}.getComputedStyle(#@native, null)`)
end

#widthInteger

Returns the width of the element.

Returns:

  • (Integer)

    the width of the element


519
520
521
# File 'opal/browser/dom/element.rb', line 519

def width
  size.width
end

#windowWindow (readonly)

Returns the window for the element.

Returns:

  • (Window)

    the window for the element


529
530
531
# File 'opal/browser/dom/element.rb', line 529

def window
  document.window
end

Class Method Details

.create(*args) ⇒ Object


6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'opal/browser/dom/element.rb', line 6

def self.create(*args)
  if self == Element
    $document.create_element(*args)
  elsif @tag_name
    $document.create_element(@tag_name)
  elsif @selector
    # That's crude, but should cover the most basic cases.
    # Just in case, you can override it safely.
    tag_name = (@selector.scan(/^[A-Za-z0-9_-]+/).first || "div").upcase
    classes = @selector.scan(/\.([A-Za-z0-9_-]+)/).flatten
    id = @selector.scan(/#([A-Za-z0-9_-]+)/).flatten.first
    attrs = @selector.scan(/\[([A-Za-z0-9_-]+)=((["'])(.*?)\3|[A-Za-z0-9_-]*)\]/).map { |a,b,_,d| [a,d||b] }.to_h
    $document.create_element(tag_name, classes: classes, id: id, attrs: attrs)
  else
    raise NotImplementedError
  end
end

.def_selector(selector) ⇒ Object

Define a selector for subclass dispatch

Example:

class CustomElement < Browser::DOM::Element
  def_selector "div.hello-world"
end

36
37
38
39
40
41
42
43
# File 'opal/browser/dom/element.rb', line 36

def self.def_selector(selector)
  Element.subclasses << self

  @selector = selector

  # A special case to speedup dispatch
  @tag_name = selector.upcase unless selector =~ /[^A-Za-z0-9_-]/
end

.native_matches?(native, selector) ⇒ Boolean

Returns:

  • (Boolean)

Raises:

  • (NotImplementedError)

84
85
86
# File 'opal/browser/dom/element.rb', line 84

def self.native_matches? (native, selector)
  `#{native}.matches(#{selector})`
end

.new(node) ⇒ Object


53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'opal/browser/dom/element.rb', line 53

def self.new(node)
  if self == Element
    subclass = Element.subclasses.select do |subclass|
      if subclass.tag_name
        subclass.tag_name == `node.nodeName`
      else
        Element.native_matches?(node, subclass.selector)
      end
    end.last

    if subclass
      subclass.new(node)
    else
      super
    end
  else
    super
  end
end

.selectorObject


45
46
47
# File 'opal/browser/dom/element.rb', line 45

def self.selector
  @selector
end

.subclassesObject


24
25
26
# File 'opal/browser/dom/element.rb', line 24

def self.subclasses
  @subclasses ||= []
end

.tag_nameObject


49
50
51
# File 'opal/browser/dom/element.rb', line 49

def self.tag_name
  @tag_name
end

Instance Method Details

#/(*paths) ⇒ NodeSet

Query for children with the given XPpaths.

Parameters:

  • paths (Array<String>)

    the XPaths to look for

Returns:


125
126
127
# File 'opal/browser/dom/element.rb', line 125

def /(*paths)
  NodeSet[paths.map { |path| xpath(path) }]
end

#=~(selector) ⇒ Object

Check whether the element matches the given selector.

Parameters:

  • selector (String)

    the CSS selector


116
117
118
# File 'opal/browser/dom/element.rb', line 116

def =~(selector)
  Element.native_matches?(@native, selector)
end

#[](name, options = {}) ⇒ String? Also known as: attr, attribute, get_attribute, get

Get the attribute with the given name.

Parameters:

  • name (String)

    the attribute name

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

    options for the attribute

Options Hash (options):

  • :namespace (String)

    the namespace for the attribute

Returns:


137
138
139
# File 'opal/browser/dom/element.rb', line 137

def [](name, options = {})
  attributes.get(name, options)
end

#[]=(name, value, options = {}) ⇒ Object Also known as: set, set_attribute

Set the attribute with the given name and value.

Parameters:

  • name (String)

    the attribute name

  • value (Object)

    the attribute value

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

    the options for the attribute

Options Hash (options):

  • :namespace (String)

    the namespace for the attribute


148
149
150
# File 'opal/browser/dom/element.rb', line 148

def []=(name, value, options = {})
  attributes.set(name, value, options)
end

#add_class(*names) ⇒ self

Add class names to the element.

Parameters:

  • names (Array<String>)

    class names to add

Returns:

  • (self)

157
158
159
160
161
162
163
164
165
# File 'opal/browser/dom/element.rb', line 157

def add_class(*names)
  classes = class_names + names

  unless classes.empty?
    `#@native.className = #{classes.uniq.join ' '}`
  end

  self
end

#animate(properties, duration: 0.4.s, easing: :ease, resolve: false, &block) ⇒ Object

Transform an element smoothly using CSS transitions, jQuery style. Yield a block afterwards if it's provided.


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
# File 'opal/browser/effects.rb', line 87

def animate(properties, duration: 0.4.s, easing: :ease, resolve: false, &block)
  animation_queue(resolve) do |res|
    duration = 0.6.s if duration == :slow
    duration = 0.2.s if duration == :fast

    original_value = style['transition']

    style['transition'] = [original_value,
                          *properties.keys.map do |key|
                            "#{key} #{duration} #{easing}"
                          end].compact.join(", ")

    properties.each do |key, value|
      style[key] = value
    end

    promise = Promise.new

    one :transitionend do |*args|
      style['transition'] = original_value

      yield(*args) if block_given?

      res.call
    end
  end
  self
end

#animation_queue(&block) ⇒ Object

Queue the block to happen when currently queued animations finish or during the next animation frame.


69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'opal/browser/effects.rb', line 69

def animation_queue &block
  promise = Promise.new

  promise_resolve = proc do
    @animation_promise = nil if @animation_promise == promise
    promise.resolve
  end

  @animation_promise = (@animation_promise || Promise.value(true)).then do
    animation_frame do
      yield promise_resolve
    end
    promise
  end
end

#at(path_or_selector) ⇒ Node?

Get the first node that matches the given CSS selector or XPath.

Parameters:

  • path_or_selector (String)

    an XPath or CSS selector

Returns:


172
173
174
# File 'opal/browser/dom/element.rb', line 172

def at(path_or_selector)
  xpath(path_or_selector).first || css(path_or_selector).first
end

#at_css(*rules) ⇒ Node?

Get the first node matching the given CSS selectors.

Parameters:

  • rules (Array<String>)

    the CSS selectors to match with

Returns:


181
182
183
184
185
186
187
188
189
190
191
# File 'opal/browser/dom/element.rb', line 181

def at_css(*rules)
  result = nil

  rules.each {|rule|
    if result = css(rule).first
      break
    end
  }

  result
end

#at_xpath(*paths) ⇒ Node?

Get the first node matching the given XPath.

Parameters:

  • paths (Array<String>)

    the XPath to match with

Returns:


198
199
200
201
202
203
204
205
206
207
208
# File 'opal/browser/dom/element.rb', line 198

def at_xpath(*paths)
  result = nil

  paths.each {|path|
    if result = xpath(path).first
      break
    end
  }

  result
end

#blurObject

Blur the focus from the element.


57
58
59
60
# File 'opal/browser/effects.rb', line 57

def blur
  `#@native.blur()`
  self
end

#clickObject

Click the element. it fires the element's click event.


260
261
262
263
# File 'opal/browser/dom/element.rb', line 260

def click
  `#@native.click()`
  self
end

#css(selector) ⇒ NodeSet

Query for children matching the given CSS selector.

Parameters:

  • selector (String)

    the CSS selector

Returns:

Raises:

  • (NotImplementedError)

254
255
256
257
258
# File 'opal/browser/dom/element.rb', line 254

def css(path)
  NodeSet[Native::Array.new(`#@native.querySelectorAll(path)`)]
rescue StandardError, JS::Error
  NodeSet[]
end

#dataData #data(hash) ⇒ self

Overloads:

  • #dataData

    Return the data for the element.

    Returns:

  • #data(hash) ⇒ self

    Set data on the element.

    Parameters:

    • hash (Hash)

      the data to set

    Returns:

    • (self)

278
279
280
281
282
283
284
285
286
287
288
289
290
# File 'opal/browser/dom/element.rb', line 278

def data(value = nil)
  data = Data.new(self)

  return data unless value

  if Hash === value
    data.assign(value)
  else
    raise ArgumentError, 'unknown data type'
  end

  self
end

#edit(command, value = nil) ⇒ Object

Execute a contentEditable command


36
37
38
39
40
41
42
43
44
45
46
# File 'opal/browser/dom/element/editable.rb', line 36

def edit(command, value=nil)
  command = command.gsub(/_./) { |i| i[1].upcase }
  
  focus

  if value
    `#{document}.native.execCommand(#{command}, false, #{value})`
  else
    `#{document}.native.execCommand(#{command}, false)`
  end
end

#editable?Boolean

Returns:

  • (Boolean)

31
32
33
# File 'opal/browser/dom/element/editable.rb', line 31

def editable?
  `#@native.isContentEditable`
end

#fade_in(**kwargs, &block) ⇒ Object

Show a hidden element with a "fade in" animation. Yield a block afterwards.


117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'opal/browser/effects.rb', line 117

def fade_in(**kwargs, &block)
  animation_queue do |resolve|
    if !visible?
      @virtually_visible = true
      show

      style[:opacity] = 0.0
      animate opacity: 1.0, **kwargs do |*args|
        @virtually_visible = nil
        style[:opacity] = nil
        yield(*args) if block_given?
      end
    end
    resolve.call
  end
  self
end

#fade_out(**kwargs, &block) ⇒ Object

Hide a visible element with a "fade out" animation. Yield a block afterwards.


136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'opal/browser/effects.rb', line 136

def fade_out(**kwargs, &block)
  animation_queue do |resolve|
    if visible?
      @virtually_visible = false

      style[:opacity] = 1.0
      animate opacity: 0.0, **kwargs do |*args|
        @virtually_visible = nil
        style[:opacity] = nil
        hide
        yield(*args) if block_given?
      end
    end
    resolve.call
  end
  self
end

#fade_toggle(**kwargs, &block) ⇒ Object

Toggle a visibility of an element with a "fade in"/"fade out" animation. Yield a block afterwards.


156
157
158
159
160
161
162
163
# File 'opal/browser/effects.rb', line 156

def fade_toggle(**kwargs, &block)
  if visible?
    fade_out(**kwargs, &block)
  else
    fade_in(**kwargs, &block)
  end
  self
end

#focusObject

Set the focus on the element.


51
52
53
54
# File 'opal/browser/effects.rb', line 51

def focus
  `#@native.focus()`
  self
end

#focused?Boolean

Check if the element is focused.

Returns:

  • (Boolean)

63
64
65
# File 'opal/browser/effects.rb', line 63

def focused?
  `#@native.hasFocus`
end

#hideObject

Hide the element.


24
25
26
27
# File 'opal/browser/effects.rb', line 24

def hide
  style[:display] = :none
  self
end

#inner_dom(&block) ⇒ Object

Set the inner DOM of the element using the Builder.


326
327
328
329
330
331
332
333
# File 'opal/browser/dom/element.rb', line 326

def inner_dom(&block)
  clear

  # FIXME: when block passing is fixed
  doc = document

  self << Builder.new(doc, self, &block).to_a
end

#inner_dom=(node) ⇒ Object

Set the inner DOM with the given node.

(see #append_child)


338
339
340
341
342
# File 'opal/browser/dom/element.rb', line 338

def inner_dom=(node)
  clear

  self << node
end

#inspectObject


344
345
346
347
348
349
350
351
352
353
354
355
356
# File 'opal/browser/dom/element.rb', line 344

def inspect
  inspect = name.downcase

  if id
    inspect += '.' + id + '!'
  end

  unless class_names.empty?
    inspect += '.' + class_names.join('.')
  end

  "#<DOM::Element: #{inspect}>"
end

#remove_attribute(name) ⇒ Object

Remove an attribute from the element.

Parameters:

  • name (String)

    the attribute name


478
479
480
# File 'opal/browser/dom/element.rb', line 478

def remove_attribute(name)
  `#@native.removeAttribute(name)`
end

#remove_class(*names) ⇒ self

Remove class names from the element.

Parameters:

  • names (Array<String>)

    class names to remove

Returns:

  • (self)

487
488
489
490
491
492
493
494
495
496
497
# File 'opal/browser/dom/element.rb', line 487

def remove_class(*names)
  classes = class_names - names

  if classes.empty?
    `#@native.removeAttribute('class')`
  else
    `#@native.className = #{classes.join ' '}`
  end

  self
end

#search(*selectors) ⇒ NodeSet

Search for all the children matching the given XPaths or CSS selectors.

Parameters:

  • selectors (Array<String>)

    mixed list of XPaths and CSS selectors

Returns:


391
392
393
394
395
# File 'opal/browser/dom/element.rb', line 391

def search(*selectors)
  NodeSet.new selectors.map {|selector|
    xpath(selector).to_a.concat(css(selector).to_a)
  }.flatten.uniq
end

#shadow(open = true) ⇒ ShadowRoot

Creates or accesses the shadow root of this element

Parameters:

  • open (Boolean) (defaults to: true)

    set to false if you want to create a closed shadow root

Returns:


407
408
409
410
411
412
413
# File 'opal/browser/dom/element.rb', line 407

def shadow (open = true)
  if root = `#@native.shadowRoot`
    DOM(root)
  else
    DOM(`#@native.attachShadow({mode: #{open ? "open" : "closed"}})`)
  end
end

#shadow?Boolean

Checks for a presence of a shadow root of this element

Returns:

  • (Boolean)

418
419
420
# File 'opal/browser/dom/element.rb', line 418

def shadow?
  `!!#@native.shadowRoot`
end

#show(what = :block) ⇒ Object

Show the element.

Parameters:

  • what (Symbol) (defaults to: :block)

    how to display it


18
19
20
21
# File 'opal/browser/effects.rb', line 18

def show(what = :block)
  style[:display] = what
  self
end

#slide_down(**kwargs, &block) ⇒ Object

Show a hidden element with a "slide down" animation. Yield a block afterwards.


166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'opal/browser/effects.rb', line 166

def slide_down(**kwargs, &block)
  animation_queue do |resolve|
    if !visible?
      @virtually_visible = true
      show
      height = size.height
      orig_height = style[:height]
      style[:height] = 0.px

      animate height: height.px, **kwargs do |*args|
        @virtually_visible = nil
        style[:height] = orig_height
        yield(*args) if block_given?
      end
    end
    resolve.call
  end
  self
end

#slide_toggle(**kwargs, &block) ⇒ Object

Toggle a visibility of an element with a "slide up"/"slide down" animation. Yield a block afterwards.


207
208
209
210
211
212
213
214
# File 'opal/browser/effects.rb', line 207

def slide_toggle(**kwargs, &block)
  if visible?
    slide_up(**kwargs, &block)
  else
    slide_down(**kwargs, &block)
  end
  self
end

#slide_up(**kwargs, &block) ⇒ Object

Hide a visible element with a "slide up" animation. Yield a block afterwards.


187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'opal/browser/effects.rb', line 187

def slide_up(**kwargs, &block)
  animation_queue do |resolve|
    if visible?
      @virtually_visible = false
      orig_height = style[:height]

      animate height: 0.px, **kwargs do |*args|
        @virtually_visible = nil
        style[:height] = orig_height
        hide
        yield(*args) if block_given?
      end
    end
    resolve.call
  end
  self
end

#styleCSS::Declaration #style(data) ⇒ self #style(&block) ⇒ self

Overloads:

  • #styleCSS::Declaration

    Return the style for the element.

    Returns:

  • #style(data) ⇒ self

    Set the CSS style as string or set of values.

    Parameters:

    Returns:

    • (self)
  • #style(&block) ⇒ self

    Set the CSS style from a CSS builder DSL.

    Returns:

    • (self)

441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
# File 'opal/browser/dom/element.rb', line 441

def style(data = nil, &block)
  style = CSS::Declaration.new(`#@native.style`)

  return style unless data || block

  if String === data
    style.replace(data)
  elsif Hash === data
    style.assign(data)
  elsif block
    style.apply(&block)
  else
    raise ArgumentError, 'unknown data type'
  end

  self
end

#toggle(what = :block) ⇒ Object

Toggle the visibility of the element, hide it if it's shown, show it if it's hidden.


41
42
43
44
45
46
47
48
# File 'opal/browser/effects.rb', line 41

def toggle(what = :block)
  if visible?
    hide
  else
    show(what)
  end
  self
end

#toggle_class(*names) ⇒ self

Toggle class names of the element.

Parameters:

  • names (Array<String>)

    class names to toggle

Returns:

  • (self)

510
511
512
513
514
515
# File 'opal/browser/dom/element.rb', line 510

def toggle_class(*names)
  to_remove, to_add = names.partition { |name| class_names.include? name }

  add_class(*to_add)
  remove_class(*to_remove)
end

#visible?Boolean

Returns:

  • (Boolean)

29
30
31
32
33
34
35
36
37
# File 'opal/browser/effects.rb', line 29

def visible?
  # Let's check if we want to lie about the real visibility of an element.
  # It could be wise to lie about it when it's in a process of animation...
  if !@virtually_visible.nil?
    @virtually_visible
  else
    style![:display] != :none
  end
end

#xpath(path) ⇒ NodeSet

Query for children matching the given XPath.

Parameters:

Returns:

Raises:

  • (NotImplementedError)

553
554
555
556
557
558
559
560
561
# File 'opal/browser/dom/element.rb', line 553

def xpath(path)
  NodeSet[Native::Array.new(
    `(#@native.ownerDocument || #@native).evaluate(path,
       #@native, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null)`,
    get:    :snapshotItem,
    length: :snapshotLength)]
rescue StandardError, JS::Error
  NodeSet[]
end