From ebeab75f5862a7844558d7526db95ed1f720041b Mon Sep 17 00:00:00 2001 From: ydah <13041216+ydah@users.noreply.github.com> Date: Thu, 27 Jul 2023 21:38:03 +0900 Subject: [PATCH] Fix to not delete anything other than comments. --- lib/slim/embedded/minify/javascript.rb | 37 +++++++++++++++-- lib/slim/embedded/minify/tag.rb | 55 +++++++++++++++++++++++-- test/embedded/minify/javascript_test.rb | 12 +++--- test/embedded/minify/tag_test.rb | 3 +- 4 files changed, 93 insertions(+), 14 deletions(-) diff --git a/lib/slim/embedded/minify/javascript.rb b/lib/slim/embedded/minify/javascript.rb index 5247b95..1241964 100644 --- a/lib/slim/embedded/minify/javascript.rb +++ b/lib/slim/embedded/minify/javascript.rb @@ -10,12 +10,41 @@ def on_slim_embedded(engine, body, attrs) minified_body = minify(body) super(engine, minified_body, attrs) end + def remove_comments!(line) + need_deletion = false + need_deletion_all = false + inside_char = nil + line[-1] = line.last.chars.each_with_index.map do |char, index| + next if need_deletion_all - private + if char == '/' && next_char(line, index) == '*' && inside_char.nil? + if remaining_string_range(line, index).match?(/\*\//) + need_deletion = true + next + end + elsif char == '/' && prev_char(line, index) == '*' && inside_char.nil? && need_deletion + need_deletion = false + next + elsif char == '/' && next_char(line, index) == '/' && inside_char.nil? && !need_deletion + need_deletion_all = true + next + elsif char == '"' && !need_deletion + if inside_char == '"' + inside_char = nil + next char + end - def remove_comments!(line) - line.last.gsub!(/((? $(function() {}) - alert('hello')
Hi
+ alert('hello') + alert("argument /* argument")Hi
HTML end @@ -63,18 +66,17 @@ def test_render_with_javascript_and_singleline_comment $(function() {}); /* ... * comment / */ + /* comment */"/* string */"/* comment */ /* ... * comment / */alert("/* argument */")/*... * comment /*/ /* comment */alert("/* argument */")/*comment*/ - /* comment */alert("/* argument")/* comment - comment */ p Hi SLIM assert_html <<~HTML.chomp, sourceHi
+ alert("/* argument */")Hi
HTML end diff --git a/test/embedded/minify/tag_test.rb b/test/embedded/minify/tag_test.rb index af3ef44..41b2516 100644 --- a/test/embedded/minify/tag_test.rb +++ b/test/embedded/minify/tag_test.rb @@ -63,7 +63,8 @@ def test_render_with_css_and_multiple_comment */ h1 { color: blue;/* multiline - comment */ font-size: 12px; + comment */ font-size: 12px;/* comment + after */ } SLIM assert_html <<~HTML.chomp, source