summaryrefslogtreecommitdiff
path: root/lib/html_word_diff.rb
blob: aa0cb8660903b24a9e3253328e1ab6aa37f0283f (plain)
1
2
3
4
5
6
7
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
require 'diff/lcs'
require 'cgi'

module HtmlWordDiff
  TOKEN_REGEXP = /<[^>]*>|[[:space:]]+|[[:alnum:]]+|[^[:space:][:alnum:]<>]/

  def self.inline(old_html, new_html)
    html = +''
    each_change(old_html, new_html) do |action, old_token, new_token|
      case action
      when '='
        html << new_token
      when '-'
        html << wrap_removed(old_token)
      when '+'
        html << wrap_inserted(new_token)
      when '!'
        html << wrap_removed(old_token)
        html << wrap_inserted(new_token)
      end
    end
    html
  end

  def self.side_by_side(old_html, new_html)
    old_out = +''
    new_out = +''
    each_change(old_html, new_html) do |action, old_token, new_token|
      case action
      when '='
        old_out << old_token
        new_out << new_token
      when '-'
        old_out << wrap_removed(old_token)
      when '+'
        new_out << wrap_inserted(new_token)
      when '!'
        old_out << wrap_removed(old_token)
        new_out << wrap_inserted(new_token)
      end
    end
    [old_out, new_out]
  end

  def self.each_change(old_html, new_html)
    Diff::LCS.sdiff(tokenize(old_html), tokenize(new_html)).each do |change|
      yield change.action, change.old_element, change.new_element
    end
  end

  def self.tokenize(html)
    html.to_s.scan(TOKEN_REGEXP)
  end

  def self.tag_token?(token)
    token.to_s.match?(/\A<[^>]*>\z/)
  end

  def self.wrap_removed(token)
    if tag_token?(token)
      %(<del class="diff_structural" title="removed: #{CGI.escapeHTML(token)}">\u00b6</del>)
    else
      "<del>#{token}</del>"
    end
  end

  def self.wrap_inserted(token)
    if tag_token?(token)
      %(<ins class="diff_structural" title="added: #{CGI.escapeHTML(token)}">\u00b6</ins>)
    else
      "<ins>#{token}</ins>"
    end
  end
end