Class: Ruact::HtmlConverter

Inherits:
Object
  • Object
show all
Defined in:
lib/ruact/html_converter.rb

Overview

Converts an HTML string (ERB output) into a ReactElement tree.

Rules:

  • HTML attributes → React equivalents (class→className, for→htmlFor, etc.)

  • data-react-key=“x” → becomes the React key on the element

  • HTML comments matching RSC_N tokens → replaced by client component refs

  • Text nodes → plain Ruby strings

  • Multiple root nodes → wrapped in a Fragment (array)

Constant Summary collapse

HTML_TO_REACT =

HTML attribute → React prop name mapping

{
  "class" => "className",
  "for" => "htmlFor",
  "tabindex" => "tabIndex",
  "readonly" => "readOnly",
  "maxlength" => "maxLength",
  "cellpadding" => "cellPadding",
  "cellspacing" => "cellSpacing",
  "rowspan" => "rowSpan",
  "colspan" => "colSpan",
  "crossorigin" => "crossOrigin",
  "autocomplete" => "autoComplete",
  "autofocus" => "autoFocus",
  "accesskey" => "accessKey",
  "contenteditable" => "contentEditable",
  "enctype" => "encType",
  "formaction" => "formAction",
  "novalidate" => "noValidate",
  "spellcheck" => "spellCheck"
}.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(component_registry) ⇒ HtmlConverter

Returns a new instance of HtmlConverter.



43
44
45
# File 'lib/ruact/html_converter.rb', line 43

def initialize(component_registry)
  @registry = component_registry
end

Class Method Details

.convert(html, component_registry = []) ⇒ Object

Convert an HTML string into a ReactElement tree. component_registry is an array of { token:, name:, ref: ClientReference, props: Hash }



39
40
41
# File 'lib/ruact/html_converter.rb', line 39

def self.convert(html, component_registry = [])
  new(component_registry).convert(html)
end

Instance Method Details

#convert(html) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/ruact/html_converter.rb', line 47

def convert(html)
  # Wrap in a fragment container so Nokogiri gives us a consistent root.
  # Use HTML4 fragment parser (universally available, no libgumbo needed).
  doc = Nokogiri::HTML::DocumentFragment.parse(html)
  children = doc.children.reject { |n| ignorable?(n) }.filter_map { |n| convert_node(n) }

  case children.length
  when 0 then nil
  when 1 then children.first
  else        children # Fragment: array of elements
  end
end