Class: Coradoc::Input::Html::Converters::A

Inherits:
Base
  • Object
show all
Defined in:
lib/coradoc/html/input/converters/a.rb

Constant Summary collapse

INSTANCE =
new

Instance Method Summary collapse

Methods inherited from Base

#extract_leading_trailing_whitespace, #extract_text_from_content, #extract_title, #node_has_ancestor?, #textnode_after_start_with?, #textnode_before_end_with?, #treat_children_coradoc, #treat_coradoc, #unconstrained_after?, #unconstrained_before?

Instance Method Details

#to_coradoc(node, state = {}) ⇒ Object



12
13
14
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
# File 'lib/coradoc/html/input/converters/a.rb', line 12

def to_coradoc(node, state = {})
  # Use treat_children_coradoc to get CoreModel elements
  content = treat_children_coradoc(node, state)

  href  = node['href']
  title = extract_title(node)
  id = node['id'] || node['name']

  id = id&.gsub(/\s/, '')&.gsub(/__+/, '_')
  id = nil if id&.empty?

  return nil if /^_Toc\d+$|^_GoBack$/.match?(id)

  # For inline anchors - return CoreModel InlineElement with format_type "anchor"
  if id
    return Coradoc::CoreModel::InlineElement.new(
      format_type: 'anchor',
      target: id
    )
  end

  # For cross-references
  if href.to_s.start_with?('#')
    ref_id = href.sub(/^#/, '').gsub(/\s/, '').gsub(/__+/, '_')
    content_str = extract_text_from_content(content)
    return Coradoc::CoreModel::CrossReferenceElement.new(
      target: ref_id,
      content: content_str.strip.empty? ? nil : content_str.strip
    )
  end

  return nil if href.to_s.empty?

  # For links
  ambigous_characters = /[\w.?&#=%;\[\u{ff}-\u{10ffff}]/
  right_constrain = textnode_after_start_with?(node, ambigous_characters)

  content_str = extract_text_from_content(content)

  out = []
  # Add leading space if needed
  if textnode_before_end_with?(node, ambigous_characters)
    out << Coradoc::CoreModel::TextElement.new(
      content: ' '
    )
  end

  # Create link element
  link = Coradoc::CoreModel::LinkElement.new(
    target: href,
    content: content_str.strip,
    metadata: {
      title: (title.strip unless title.to_s.strip.empty?),
      right_constrain: right_constrain
    }.compact
  )
  out << link

  # Return single element or array
  out.length == 1 ? out.first : out
end