Module: Emjay::Renderer

Defined in:
lib/emjay/renderer.rb

Constant Summary collapse

VOID_ELEMENTS_RE =

HTML void elements that need self-closing conversion for XML parsing.

/(<(?:br|hr|img|input|meta|link|area|base|col|embed|param|source|track|wbr)(?:\s[^>]*)?)>/i
RAW_LT_PLACEHOLDER =
"___MJML_RAW_LT___"
VOID_ELEMENTS =
%w[area base br col embed hr img input link meta param source track wbr].freeze

Class Method Summary collapse

Class Method Details

.call(mjml_string, options = {}) ⇒ Object



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
# File 'lib/emjay/renderer.rb', line 15

def self.call(mjml_string, options = {})
  # 1. Pre-process and parse MJML string with Nokogiri::XML.
  # Two fixups are needed to bridge MJML (which embeds HTML content) and XML:
  #   a) Convert HTML void elements to self-closing (e.g. <br> → <br/>)
  #      so XML parsing doesn't treat them as unclosed tags
  #   b) Escape bare < characters from template syntax in mj-raw
  #      (e.g. { if item < 5 }) so they don't break XML parsing
  preprocessed = mjml_string.gsub(VOID_ELEMENTS_RE, '\1/>')
  preprocessed = preprocessed.gsub(/<(?![a-zA-Z\/!?])/, RAW_LT_PLACEHOLDER)
  doc = Nokogiri::XML(preprocessed)
  mjml_root = doc.at_xpath("//mjml") || doc.root

  # 2. Build GlobalData
  global_data = GlobalData.new(options)

  # Extract lang/dir from root element
  if mjml_root
    owa = mjml_root["owa"]
    global_data.force_owa_desktop = (owa == "desktop") if owa
    global_data.lang = mjml_root["lang"] || "und"
    global_data.dir = mjml_root["dir"] || "auto"
  end

  # 3. Find mj-head and mj-body
  mj_head_el = mjml_root&.at_xpath("mj-head")
  mj_body_el = mjml_root&.at_xpath("mj-body")

  # Convert Nokogiri elements to our internal data structures (matching JS parsed format)
  components = Registry.components

  # Processing function (matches JS processing)
  apply_attributes = method(:apply_attributes_fn).curry[global_data]

  processing = lambda { |node, ctx|
    return unless node
    node = apply_attributes.call(node) if node.is_a?(Hash)

    component_class = ctx[:components]&.[](node[:tag_name])
    return unless component_class

    component = component_class.new(
      attributes: node[:attributes] || {},
      children: node[:children] || [],
      content: node[:content] || "",
      context: ctx,
      global_attributes: node[:global_attributes] || {},
      raw_attrs: node[:raw_attrs] || {}
    )

    if component.respond_to?(:handler)
      return component.handler
    end

    if component.respond_to?(:render)
      component.render
    end
  }

  # Head helpers context
  head_helpers = {
    components: components,
    global_data: global_data,
    add: ->(attr, *params) { global_data.add(attr, *params) }
  }

  # Process head
  if mj_head_el
    head_node = nokogiri_to_hash(mj_head_el)
    head_result = processing.call(head_node, head_helpers)
    global_data.head_raw = head_result if head_result.is_a?(Array)
  end

  # Body helpers context
  body_helpers = {
    components: components,
    global_data: global_data,
    container_width: "600px",
    add_media_query: ->(class_name, data) {
      pw = data[:parsed_width]
      pw = pw.to_i if pw == pw.to_i
      global_data.media_queries[class_name] =
        "{ width:#{pw}#{data[:unit]} !important; max-width: #{pw}#{data[:unit]}; }"
    },
    add_head_style: ->(identifier, head_style_fn) {
      global_data.head_style[identifier] = head_style_fn
    },
    add_component_head_style: ->(head_style_fn) {
      global_data.components_head_style << head_style_fn
    },
    processing: ->(node, ctx) {
      node = apply_attributes.call(node) if node.is_a?(Hash)
      processing.call(node, ctx)
    }
  }

  # Process body
  content = nil
  if mj_body_el
    body_node = nokogiri_to_hash(mj_body_el)
    body_node = apply_attributes.call(body_node)
    content = processing.call(body_node, body_helpers)
  end

  raise "Malformed MJML. Check that your structure is correct and enclosed in <mjml> tags." unless content

  # Minify outlook conditionals
  content = MinifyOutlookConditionals.call(content)

  # Handle mj-raw outside body (before-doctype)
  mjml_root&.xpath("mj-raw")&.each do |raw_el|
    if raw_el["position"] == "file-start"
      global_data.before_doctype += raw_el.inner_html.gsub(RAW_LT_PLACEHOLDER, "<")
    end
  end

  # Apply html_attributes via Nokogiri CSS selectors.
  # Use XML fragment for parsing (preserves table structure, unlike HTML5
  # which foster-parents text out of tables). Protect bare < from template
  # syntax (mj-raw) with placeholders so XML parsing succeeds. Use custom
  # serializer so text nodes (including > in templates) pass through raw.
  unless global_data.html_attributes.empty?
    escaped = content.gsub(/<(?![a-zA-Z\/!?])/, RAW_LT_PLACEHOLDER)
    content_doc = Nokogiri::XML.fragment(escaped)
    global_data.html_attributes.each do |selector, data|
      content_doc.css(selector).each do |node|
        data.each do |attr_name, value|
          node[attr_name] = value || ""
        end
      end
    end
    content = serialize_fragment(content_doc).gsub(RAW_LT_PLACEHOLDER, "<")
  end

  # Wrap in skeleton
  content = Skeleton.call(
    before_doctype: global_data.before_doctype,
    breakpoint: global_data.breakpoint,
    content: content,
    fonts: global_data.fonts,
    media_queries: global_data.media_queries,
    head_style: global_data.head_style,
    components_head_style: global_data.components_head_style,
    head_raw: global_data.head_raw.is_a?(Array) ? global_data.head_raw : [],
    title: global_data.title,
    style: global_data.style,
    force_owa_desktop: global_data.force_owa_desktop,
    printer_support: options[:printer_support] || false,
    inline_style: global_data.inline_style,
    lang: global_data.lang,
    dir: global_data.dir
  )

  # CSS inlining for <mj-style inline="inline">
  if global_data.inline_style.any?
    content = inline_css(content, global_data.inline_style.join("\n"))
  end

  # Merge outlook conditionals
  MergeOutlookConditionals.call(content)
end