remove_last_empty_node.rb 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class HtmlSanitizer
  3. module Scrubber
  4. class RemoveLastEmptyNode < Base
  5. attr_reader :remove_empty_nodes, :remove_empty_last_nodes
  6. def initialize # rubocop:disable Lint/MissingSuper
  7. @direction = :bottom_up
  8. @remove_empty_nodes = %w[p div span small table]
  9. @remove_empty_last_nodes = %w[b i u small table]
  10. end
  11. def scrub(node)
  12. return scrub_children(node) if node.children.present?
  13. return if remove_empty_nodes.exclude?(node.name) && remove_empty_last_nodes.exclude?(node.name)
  14. return if node.content.present?
  15. return if node.attributes.present?
  16. node.remove
  17. STOP
  18. end
  19. private
  20. def scrub_children(node)
  21. return if !node.children.one?
  22. if matching_element_with_attributes?(node)
  23. replace_parent_with_attributes(node)
  24. elsif matching_element_sans_attributes?(node)
  25. replace_parent_sans_attributes(node)
  26. end
  27. end
  28. def matching_element_with_attributes?(node)
  29. return if node.name != node.children.first.name
  30. return if node.attributes.blank?
  31. return if node.children.first.attributes.present?
  32. true
  33. end
  34. def replace_parent_with_attributes(node)
  35. local_node_child = node.children.first
  36. node.attributes.each do |key, value|
  37. local_node_child.set_attribute(key, value)
  38. end
  39. node.replace local_node_child.to_s
  40. STOP
  41. end
  42. def matching_element_sans_attributes?(node)
  43. return if node.name != 'span' && node.name != node.children.first.name
  44. return if node.attributes.present?
  45. true
  46. end
  47. def replace_parent_sans_attributes(node)
  48. node.replace node.children.to_s
  49. STOP
  50. end
  51. end
  52. end
  53. end