Class: Panda::Editor::HtmlToEditorJsConverter

Inherits:
Object
  • Object
show all
Defined in:
app/services/panda/editor/html_to_editor_js_converter.rb

Defined Under Namespace

Classes: ConversionError

Class Method Summary collapse

Class Method Details

.convert(html) ⇒ Object



8
9
10
11
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
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
# File 'app/services/panda/editor/html_to_editor_js_converter.rb', line 8

def self.convert(html)
  return {} if html.blank?

  # If it's already in EditorJS format, return as is
  return html if html.is_a?(Hash) && (html['blocks'].present? || html[:blocks].present?)

  begin
    # Parse the HTML content
    doc = Nokogiri::HTML.fragment(html.to_s)
    raise ConversionError, 'Failed to parse HTML content' unless doc

    blocks = []
    current_text = ''

    doc.children.each do |node|
      case node.name
      when 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
        # Add any accumulated text as a paragraph before the header
        if current_text.present?
          blocks << create_paragraph_block(current_text)
          current_text = ''
        end

        blocks << {
          'type' => 'header',
          'data' => {
            'text' => node.text.strip,
            'level' => node.name[1].to_i
          }
        }
      when 'p', 'div'
        # Add any accumulated text first
        if current_text.present?
          blocks << create_paragraph_block(current_text)
          current_text = ''
        end

        if node.name == 'div'
          # Process div children separately
          node.children.each do |child|
            case child.name
            when 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
              blocks << {
                'type' => 'header',
                'data' => {
                  'text' => child.text.strip,
                  'level' => child.name[1].to_i
                }
              }
            when 'p'
              text = process_inline_elements(child)
              paragraphs = text.split(%r{<br\s*/?>\s*<br\s*/?>}).map(&:strip)
              paragraphs.each do |paragraph|
                blocks << create_paragraph_block(paragraph) if paragraph.present?
              end
            when 'ul', 'ol'
              items = child.css('li').map { |li| process_inline_elements(li) }
              next if items.empty?

              blocks << {
                'type' => 'list',
                'data' => {
                  'style' => child.name == 'ul' ? 'unordered' : 'ordered',
                  'items' => items
                }
              }
            when 'blockquote'
              blocks << {
                'type' => 'quote',
                'data' => {
                  'text' => process_inline_elements(child),
                  'caption' => '',
                  'alignment' => 'left'
                }
              }
            when 'text'
              text = child.text.strip
              current_text += text if text.present?
            end
          end
        else
          # Handle p with nested content
          text = process_inline_elements(node)
          paragraphs = text.split(%r{<br\s*/?>\s*<br\s*/?>}).map(&:strip)
          paragraphs.each do |paragraph|
            blocks << create_paragraph_block(paragraph) if paragraph.present?
          end
        end
      when 'br'
        current_text += "\n\n"
      when 'text'
        text = node.text.strip
        current_text += text if text.present?
      when 'ul', 'ol'
        # Add any accumulated text first
        if current_text.present?
          blocks << create_paragraph_block(current_text)
          current_text = ''
        end

        items = node.css('li').map { |li| process_inline_elements(li) }
        next if items.empty?

        blocks << {
          'type' => 'list',
          'data' => {
            'style' => node.name == 'ul' ? 'unordered' : 'ordered',
            'items' => items
          }
        }
      when 'blockquote'
        # Add any accumulated text first
        if current_text.present?
          blocks << create_paragraph_block(current_text)
          current_text = ''
        end

        blocks << {
          'type' => 'quote',
          'data' => {
            'text' => process_inline_elements(node),
            'caption' => '',
            'alignment' => 'left'
          }
        }
      end
    end

    # Add any remaining text
    blocks << create_paragraph_block(current_text) if current_text.present?

    # Return the complete EditorJS structure
    {
      'time' => Time.current.to_i * 1000,
      'blocks' => blocks,
      'version' => '2.28.2'
    }
  rescue StandardError => e
    Rails.logger.error "HTML to EditorJS conversion failed: #{e.message}"
    Rails.logger.error e.backtrace.join("\n")
    raise ConversionError, "Failed to convert HTML to EditorJS format: #{e.message}"
  end
end

.create_paragraph_block(text) ⇒ Object



152
153
154
155
156
157
158
159
# File 'app/services/panda/editor/html_to_editor_js_converter.rb', line 152

def self.create_paragraph_block(text)
  {
    'type' => 'paragraph',
    'data' => {
      'text' => text.strip
    }
  }
end

.process_inline_elements(node) ⇒ Object



161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'app/services/panda/editor/html_to_editor_js_converter.rb', line 161

def self.process_inline_elements(node)
  result = ''
  node.children.each do |child|
    case child.name
    when 'br'
      result += '<br>'
    when 'text'
      result += child.text
    when 'strong', 'b'
      result += "<b>#{child.text}</b>"
    when 'em', 'i'
      result += "<i>#{child.text}</i>"
    when 'a'
      href = child['href']
      text = child.text.strip
      # Handle email links specially
      if href&.start_with?('mailto:')
        email = href.sub('mailto:', '')
        result += "<a href=\"mailto:#{email}\">#{text}</a>"
      else
        result += "<a href=\"#{href}\">#{text}</a>"
      end
    else
      result += if child.text?
                  child.text
                else
                  child.to_html
                end
    end
  end
  result.strip
end