Module: Dommy::Internal::ParentNode

Included in:
Element, Fragment, ShadowRoot
Defined in:
lib/dommy/internal/parent_node.rb

Overview

Shared ParentNode tree-mutation surface for Element, Fragment, and ShadowRoot. Includers must expose ‘@__node__` (the backing Nokogiri node) and `@document` (the owning Dommy::Document).

All child-list mutations funnel through ‘notify_child_list`, which forwards to MutationCoordinator#notify_child_list_mutation. That coordinator already no-ops on empty added/removed sets and on an unwrappable target, so callers may invoke it unconditionally.

Instance Method Summary collapse

Instance Method Details

#append(*args) ⇒ Object

ParentNode#append — mixed Node/String args appended in order.



25
26
27
28
29
30
# File 'lib/dommy/internal/parent_node.rb', line 25

def append(*args)
  nodes = args.flat_map { |arg| detach_dom_nodes(arg) }
  nodes.each { |n| @__node__.add_child(n) }
  notify_child_list(added: nodes)
  nil
end

#append_child(child) ⇒ Object

‘appendChild(child)` — detach the node(s) from any current parent and append to the end of this node’s child list.



16
17
18
19
20
21
22
# File 'lib/dommy/internal/parent_node.rb', line 16

def append_child(child)
  check_insertion!(child)
  nodes = detach_dom_nodes(child)
  nodes.each { |n| @__node__.add_child(n) }
  notify_child_list(added: nodes)
  child
end

#prepend(*args) ⇒ Object

ParentNode#prepend — insert before the current first child.



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/dommy/internal/parent_node.rb', line 33

def prepend(*args)
  nodes = args.flat_map { |arg| detach_dom_nodes(arg) }
  anchor = @__node__.children.first
  if anchor
    nodes.reverse_each { |n| anchor.add_previous_sibling(n) }
  else
    nodes.each { |n| @__node__.add_child(n) }
  end
  notify_child_list(added: nodes)
  nil
end

#replace_children(*args) ⇒ Object

ParentNode#replaceChildren — remove all existing children, then append the new set. One mutation record carries both sides.



47
48
49
50
51
52
53
54
# File 'lib/dommy/internal/parent_node.rb', line 47

def replace_children(*args)
  removed = @__node__.children.to_a
  removed.each(&:unlink)
  nodes = args.flat_map { |arg| detach_dom_nodes(arg) }
  nodes.each { |n| @__node__.add_child(n) }
  notify_child_list(added: nodes, removed: removed)
  nil
end