Class: Metanorma::Html::BaseRenderer

Inherits:
Object
  • Object
show all
Defined in:
lib/metanorma/html/base_renderer.rb

Overview

Renders BasicDocument components to HTML. Subclassed by StandardRenderer and flavor-specific renderers. Owns the full HTML document generation pipeline: body content, header, footer, ToC sidebar, CSS (via Theme), and JavaScript.

Direct Known Subclasses

StandardRenderer

Defined Under Namespace

Classes: RendererContext

Constant Summary collapse

LOGO_DIR =
File.expand_path("../../../data/logos", __dir__)
SPAN_ROLE_CLASSES =

HTML-specific class names for inline spans, keyed by the XML span role. The XML class_attr is INPUT only — we never emit it in HTML.

{
  "boldtitle" => "title-text",
  "nonboldtitle" => "subtitle-text",
  "citeapp" => "xref-app",
  "citefig" => "xref-fig",
  "citesec" => "xref-section",
  "citetbl" => "xref-table",
  "fmt-autonum-delim" => "number-delim",
  "fmt-caption-label" => "caption-label",
  "fmt-caption-delim" => "caption-delim",
  "fmt-element-name" => "element-label",
  "fmt-comma" => "comma",
  "fmt-conn" => "connector",
  "fmt-label-delim" => "label-delim",
  "fmt-obligation" => "obligation-text",
  "fmt-xref-container" => "xref-container",
  "fmt-xref-label" => "xref-label",
  "std_publisher" => "ref-publisher",
  "stdpublisher" => "ref-publisher-name",
  "stddocNumber" => "ref-doc-number",
  "stddocTitle" => "ref-title",
  "stddocPartNumber" => "ref-part-number",
  "stdyear" => "ref-year",
  "date" => "date",
  "smallcap" => "small-caps",
}.freeze
METANORMA_LOGO =
"metanorma-logo.svg"
TEMPLATE_CACHE =

— Document Assembly —

{}
TEMPLATE_CACHE_MUTEX =
Mutex.new

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeBaseRenderer

Returns a new instance of BaseRenderer.



72
73
74
75
76
77
78
79
80
81
# File 'lib/metanorma/html/base_renderer.rb', line 72

def initialize
  @output = +""
  @toc_entries = []
  @figure_entries = []
  @table_entries = []
  @index_term_collector = Component::IndexTermCollector.new
  @footnote_collector = Component::FootnoteCollector.new
  @current_section_id = nil
  @current_section_number = nil
end

Instance Attribute Details

#footnote_collectorObject (readonly)

Returns the value of attribute footnote_collector.



419
420
421
# File 'lib/metanorma/html/base_renderer.rb', line 419

def footnote_collector
  @footnote_collector
end

#index_term_collectorObject (readonly)

Returns the value of attribute index_term_collector.



419
420
421
# File 'lib/metanorma/html/base_renderer.rb', line 419

def index_term_collector
  @index_term_collector
end

Class Method Details

.inline_registryObject



63
64
65
# File 'lib/metanorma/html/base_renderer.rb', line 63

def inline_registry
  @inline_registry ||= {}
end

.register_inline_render(type_class, method_name) ⇒ Object



67
68
69
# File 'lib/metanorma/html/base_renderer.rb', line 67

def register_inline_render(type_class, method_name)
  inline_registry[type_class] = method_name
end

.register_render(type_class, method_name) ⇒ Object



59
60
61
# File 'lib/metanorma/html/base_renderer.rb', line 59

def register_render(type_class, method_name)
  render_registry[type_class] = method_name
end

.render_registryObject



55
56
57
# File 'lib/metanorma/html/base_renderer.rb', line 55

def render_registry
  @render_registry ||= {}
end

Instance Method Details

#assemble_document(body) ⇒ Object



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/metanorma/html/base_renderer.rb', line 181

def assemble_document(body)
  toc_html = build_toc_html(@toc_entries)
  header = build_header
  footer = build_footer

  render_liquid("document.html.liquid", {
                  "lang" => language,
                  "title" => html_title,
                  "font_url" => flavor_font_url,
                  "styles" => build_styles,
                  "header" => header,
                  "toc" => toc_html,
                  "body" => body,
                  "footer" => footer,
                  "scripts" => build_scripts,
                })
end


261
262
263
264
265
266
267
# File 'lib/metanorma/html/base_renderer.rb', line 261

def build_footer
   = load_logo_svg(METANORMA_LOGO, height: 20)
  render_liquid("_footer.html.liquid", {
                  "mn_logo" => ,
                  "generated_at" => Time.now.strftime("%Y-%m-%d %H:%M"),
                })
end

#build_headerObject

— Header and Footer —



201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/metanorma/html/base_renderer.rb', line 201

def build_header
  doc_id = extract_primary_doc_id
  pub_logos = build_publisher_logos
  pub_name = flavor_publisher_name
  display_id = if pub_name && doc_id && !doc_id.start_with?(pub_name)
                 "#{pub_name} #{doc_id}"
               else
                 doc_id
               end

  render_liquid("_header.html.liquid", {
                  "publisher_logos" => pub_logos,
                  "doc_id" => display_id,
                  "doc_title" => header_title_text,
                })
end

#build_publisher_logosObject



223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'lib/metanorma/html/base_renderer.rb', line 223

def build_publisher_logos
  publishers = flavor_publishers(extract_primary_doc_id)
  logo_map = publisher_logo_map
  return "" if publishers.empty? && logo_map.empty?

  # Use flavor-declared publishers; fall back to logo map keys
  display_pubs = publishers.empty? ? logo_map.keys : publishers

  display_pubs.filter_map do |pub|
    filename = logo_map[pub]
    next unless filename

    svg = load_logo_svg(filename, height: 26)
    next unless svg

    "<span class=\"brand-logo\" aria-label=\"#{pub} logo\">#{svg}</span>"
  end.join("\n")
end

#build_scriptsObject

— Scripts —



287
288
289
290
291
# File 'lib/metanorma/html/base_renderer.rb', line 287

def build_scripts
  pipeline = AssetPipeline.new
  compiled = pipeline.compile_js(flavor_js: flavor_js_module)
  "<script>\n#{compiled}\n</script>"
end

#build_stylesObject



301
302
303
304
305
# File 'lib/metanorma/html/base_renderer.rb', line 301

def build_styles
  pipeline = AssetPipeline.new
  css = pipeline.compile_css(flavor_css: flavor_css_module)
  "#{theme.to_css_root}\n#{css}\n#{theme.to_css_extras}"
end

#build_toc_html(entries) ⇒ Object

— ToC generation —



271
272
273
274
275
276
277
278
279
280
281
282
283
# File 'lib/metanorma/html/base_renderer.rb', line 271

def build_toc_html(entries)
  entry_drops = entries.map { |e| Drops::TocEntryDrop.new(e) }
  figure_drops = @figure_entries.map { |f| Drops::FigureListEntryDrop.new(f) }
  table_drops = @table_entries.map { |t| Drops::FigureListEntryDrop.new(t) }
  has_special_lists = !@figure_entries.empty? || !@table_entries.empty?

  render_liquid("_toc.html.liquid", {
                  "entries" => entry_drops,
                  "figures" => figure_drops,
                  "tables" => table_drops,
                  "has_special_lists" => has_special_lists,
                })
end

#check_presentation_markers(node) ⇒ Object



319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# File 'lib/metanorma/html/base_renderer.rb', line 319

def check_presentation_markers(node)
  return false unless node
  return false if node.is_a?(String)

  if node.is_a?(Metanorma::Document::Root) && node.type == "presentation"
    return true
  end

  if node.is_a?(Lutaml::Model::Serializable)
    return true if begin
      node.fmt_title
    rescue StandardError
      nil
    end
    return true if begin
      node.displayorder
    rescue StandardError
      nil
    end

    %i[preface sections annex bibliography].each do |attr|
      val = begin
        node.public_send(attr)
      rescue StandardError
        nil
      end
      next unless val

      Array(val).each { |v| return true if check_presentation_markers(v) }
    end

    node.each_mixed_content do |child|
      next if child.is_a?(String)
      return true if check_presentation_markers(child)
    end
  end

  false
end

#extract_plain_text(node) ⇒ Object



421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
# File 'lib/metanorma/html/base_renderer.rb', line 421

def extract_plain_text(node)
  return node.to_s if node.is_a?(String)
  return extract_text_value(node).to_s unless node.is_a?(Lutaml::Model::Serializable)

  parts = []
  xml_mapping = node.class.mappings_for(:xml, node.lutaml_register)

  if node.element_order.is_a?(Array) && xml_mapping
    element_to_attr = {}
    xml_mapping.mapping_elements_hash.each_value do |rule_or_array|
      Array(rule_or_array).each do |rule|
        element_to_attr[rule.name.to_s] = rule.to
      end
    end

    indices = Hash.new(0)
    node.element_order.each do |el|
      next unless el.is_a?(Lutaml::Xml::Element)

      if el.text?
        parts << el.text_content.to_s
      elsif el.name == "tab"
        parts << "\u00A0\u00A0"
      elsif el.name == "br"
        parts << " "
      elsif el.element?
        attr_name = element_to_attr[el.name]
        next unless attr_name

        coll = node.public_send(attr_name)
        obj = if coll.is_a?(Array)
                idx = indices[attr_name]
                indices[attr_name] += 1
                coll[idx]
              else
                coll
              end
        parts << extract_plain_text(obj) if obj
      end
    end
  end

  # Fallback: try .text
  if parts.join.strip.empty?
    t = safe_attr(node, :text)
    parts << (t.is_a?(Array) ? t.join : t.to_s) if t
  end

  parts.join.strip.gsub("\u00A0", " ")
end

#extract_primary_doc_idObject



387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
# File 'lib/metanorma/html/base_renderer.rb', line 387

def extract_primary_doc_id
  bibdata = @document.bibdata
  return nil unless bibdata

  identifiers = bibdata.doc_identifier
  return nil unless identifiers && !identifiers.empty?

  first_id = identifiers.first
  text = if first_id.is_a?(String)
           first_id
         elsif first_id.is_a?(Lutaml::Model::Serializable)
           Array(first_id.value).join
         else
           first_id.to_s
         end
  text.strip.empty? ? nil : text.strip
end

#flavor_css_moduleObject



297
298
299
# File 'lib/metanorma/html/base_renderer.rb', line 297

def flavor_css_module
  nil
end

#flavor_font_urlObject



163
164
165
# File 'lib/metanorma/html/base_renderer.rb', line 163

def flavor_font_url
  theme.font_url
end

#flavor_js_moduleObject



293
294
295
# File 'lib/metanorma/html/base_renderer.rb', line 293

def flavor_js_module
  nil
end

#flavor_publisher_nameObject



153
154
155
156
# File 'lib/metanorma/html/base_renderer.rb', line 153

def flavor_publisher_name
  pubs = flavor_publishers(extract_primary_doc_id)
  pubs.empty? ? nil : pubs.join("/")
end

#flavor_publishers(_doc_id) ⇒ Object



149
150
151
# File 'lib/metanorma/html/base_renderer.rb', line 149

def flavor_publishers(_doc_id)
  []
end

#generate_full_document(document) ⇒ Object

Generate a complete HTML document from a presentation XML document.



132
133
134
135
136
137
138
139
140
141
# File 'lib/metanorma/html/base_renderer.rb', line 132

def generate_full_document(document)
  @document = document
  validate_presentation_xml!

  # First pass: render body content (collects ToC entries as side effect)
  render(@document)
  body = @output

  assemble_document(body)
end

#header_title_textObject



218
219
220
221
# File 'lib/metanorma/html/base_renderer.rb', line 218

def header_title_text
  raw = html_title.to_s.split("").first.to_s.gsub(/<[^>]+>/, "")
  raw.length > 60 ? "#{raw[0, 57]}..." : raw
end

#html_titleObject



374
375
376
377
378
379
380
381
382
383
384
385
# File 'lib/metanorma/html/base_renderer.rb', line 374

def html_title
  bibdata = @document.bibdata
  return "Document" unless bibdata

  titles = bibdata.titles
  if titles
    title = bibdata.title_for("en")
    title.to_s
  else
    "Document"
  end
end

#languageObject

— Metadata extraction —



361
362
363
364
365
366
367
368
369
370
371
372
# File 'lib/metanorma/html/base_renderer.rb', line 361

def language
  bibdata = @document.bibdata
  return "en" unless bibdata

  langs = bibdata.language
  if langs && !langs.empty?
    lang = langs.find { |l| l.current == "true" } || langs.first
    lang.value || lang.to_s
  else
    "en"
  end
end

#load_logo_svg(filename, height: 32) ⇒ Object



242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/metanorma/html/base_renderer.rb', line 242

def load_logo_svg(filename, height: 32)
  path = File.join(LOGO_DIR, filename)
  return nil unless File.exist?(path)

  svg = File.read(path)
  svg = svg.sub(/\A<\?xml[^?]*\?>\s*/, "")
  svg = svg.sub(/\A\s*<!--.*?-->\s*/m, "")
  svg = svg.sub(/<path[^>]*style="fill:#e3000f[^"]*"[^>]*\/>/, "")
  svg = svg.sub(/<svg\s/, '<svg class="header-logo" ')
  svg = if svg.match?(/<svg[^>]*\sheight="[^"]*"/)
          svg.sub(/(<svg[^>]*?)(\sheight="[^"]*")/, "\\1 height=\"#{height}\"")
        else
          svg.sub(/(<svg\b)/, "\\1 height=\"#{height}\"")
        end
  svg.sub(/(<svg[^>]*?)\swidth="[^"]*"/, '\1')
rescue StandardError
  nil
end

#publisher_logo_mapObject

Map of publisher name => logo filename. Override in flavor renderers.



159
160
161
# File 'lib/metanorma/html/base_renderer.rb', line 159

def publisher_logo_map
  {}
end

#register_figure_entry(id:, text:) ⇒ Object



411
412
413
# File 'lib/metanorma/html/base_renderer.rb', line 411

def register_figure_entry(id:, text:)
  @figure_entries << { id: id, text: text }
end

#register_table_entry(id:, text:) ⇒ Object



415
416
417
# File 'lib/metanorma/html/base_renderer.rb', line 415

def register_table_entry(id:, text:)
  @table_entries << { id: id, text: text }
end

#register_toc_entry(id:, level:, text:) ⇒ Object

— CSS loader —



407
408
409
# File 'lib/metanorma/html/base_renderer.rb', line 407

def register_toc_entry(id:, level:, text:)
  @toc_entries << { id: id, level: level, text: text }
end

#render(node) ⇒ Object

Dispatch to the appropriate render method via type registry. Lookups traverse the ancestor chain so subclasses inherit parent registrations and can override them independently.



475
476
477
478
479
480
# File 'lib/metanorma/html/base_renderer.rb', line 475

def render(node, **)
  return escape_html(node) if node.is_a?(String)

  method = lookup_dispatch(node.class, :render_registry)
  method ? send(method, node, **) : ""
end

#render_inline_element(element) ⇒ Object

Dispatch to the appropriate inline render method via type registry.



483
484
485
486
487
488
489
490
491
492
493
# File 'lib/metanorma/html/base_renderer.rb', line 483

def render_inline_element(element, **)
  return "" if element.nil?
  return escape_html(element) if element.is_a?(String)

  method = lookup_dispatch(element.class, :inline_registry)
  if method
    send(method, element)
  elsif element.is_a?(Lutaml::Model::Serializable) && element.mixed?
    render_mixed_inline(element)
  end
end

#render_liquid(template_name, assigns) ⇒ Object



172
173
174
175
176
177
178
179
# File 'lib/metanorma/html/base_renderer.rb', line 172

def render_liquid(template_name, assigns)
  template_path = File.join(TEMPLATES_ROOT, template_name)
  template = TEMPLATE_CACHE_MUTEX.synchronize do
    TEMPLATE_CACHE[template_path] ||= Liquid::Template.parse(File.read(template_path))
  end
  assigns = assigns.transform_keys(&:to_s) if assigns.is_a?(Hash)
  template.render(assigns)
end

#renderer_contextObject



119
120
121
# File 'lib/metanorma/html/base_renderer.rb', line 119

def renderer_context
  @renderer_context ||= RendererContext.new(self)
end

#themeObject

— Flavor configuration hooks (override in subclasses) —



145
146
147
# File 'lib/metanorma/html/base_renderer.rb', line 145

def theme
  @theme ||= Theme.new
end

#to_htmlObject



123
124
125
# File 'lib/metanorma/html/base_renderer.rb', line 123

def to_html
  @output
end

#toc_entriesObject



127
128
129
# File 'lib/metanorma/html/base_renderer.rb', line 127

def toc_entries
  @toc_entries
end

#validate_presentation_xml!Object

— Validation —

Raises:

  • (ArgumentError)


309
310
311
312
313
314
315
316
317
# File 'lib/metanorma/html/base_renderer.rb', line 309

def validate_presentation_xml!
  has_presentation = check_presentation_markers(@document)
  return if has_presentation

  raise ArgumentError,
        "HTML generation requires Presentation XML input. " \
        "Semantic XML does not contain formatting data needed for HTML. " \
        "Use a '.presentation.xml' file instead."
end