Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
markdown: Convert HTML layout tables as blocks, not Markdown tables.
Aman Agrawal7bda9bb0e604
diff --git a/zerver/lib/markdown/from_html.py b/zerver/lib/markdown/from_html.pyindex febd46514de..46df1aaae7a 100644--- a/zerver/lib/markdown/from_html.py+++ b/zerver/lib/markdown/from_html.py@@ -5,7 +5,8 @@ import warningsfrom urllib.parse import urlsplitimport markdownify-from bs4 import MarkupResemblesLocatorWarning, Tag+from bs4 import BeautifulSoup, MarkupResemblesLocatorWarning, Tag+from typing_extensions import overridefrom zerver.lib.markdown import get_markdown_link_for_url, sanitize_url@@ -45,6 +46,20 @@ class ZulipMarkdownConverter(markdownify.MarkdownConverter):def convert_title(self, el: Tag, text: str, parent_tags: set[str]) -> str:return ""+ @override+ def convert_soup(self, soup: BeautifulSoup) -> str:+ # Markdown tables can't nest, and their cells can't hold block+ # content. A table containing another table is page layout, so+ # convert its own rows and cells as if they were <div>s.+ for table in soup.find_all("table"):+ if table.find("table") is None:+ continue+ for part in table.find_all(["thead", "tbody", "tfoot", "tr", "th", "td"]):+ if part.find_parent("table") is table:+ part.name = "div"+ table.name = "div"+ return super().convert_soup(soup)+def convert_html_to_markdown(html: str, *, converter_class: type[ZulipMarkdownConverter] = ZulipMarkdownConverterdiff --git a/zerver/tests/test_markdown.py b/zerver/tests/test_markdown.pyindex 3665f4bb512..90f36d049c0 100644--- a/zerver/tests/test_markdown.py+++ b/zerver/tests/test_markdown.py@@ -4098,3 +4098,50 @@ class TestHtmlToMarkdown(ZulipTestCase):self.assertEqual(convert_html_to_markdown("<p>line one<br>\nline two</p>"), "line one \nline two")++ def test_table(self) -> None:+ html = (+ "<table>"+ "<tr><th>Name</th><th>Role</th></tr>"+ "<tr><td>Alice</td><td>Admin</td></tr>"+ "</table>"+ )+ self.assertEqual(+ convert_html_to_markdown(html), "| Name | Role |\n| --- | --- |\n| Alice | Admin |"+ )++ def test_layout_table(self) -> None:+ # HTML emails often use an outer table for page layout, with other+ # tables nested inside it.+ html = (+ "<table>"+ "<tr><td>Left column</td><td>Right column</td></tr>"+ "<tr><td>"+ "<p>First paragraph</p>"+ "<p>Line one<br>Line two</p>"+ "<table><tr><th>Name</th></tr><tr><td>Alice</td></tr></table>"+ "</td></tr>"+ "</table>"+ )+ self.assertEqual(+ convert_html_to_markdown(html),+ "Left column\n\nRight column\n\n"+ "First paragraph\n\n"+ "Line one \nLine two\n\n"+ "| Name |\n| --- |\n| Alice |",+ )++ def test_nested_layout_tables(self) -> None:+ html = (+ "<table><tr><td>"+ "Outer layout"+ "<table><tr><td>"+ "Inner layout"+ "<table><tr><th>Name</th></tr><tr><td>Alice</td></tr></table>"+ "</td></tr></table>"+ "</td></tr></table>"+ )+ self.assertEqual(+ convert_html_to_markdown(html),+ "Outer layout\n\nInner layout\n\n| Name |\n| --- |\n| Alice |",+ )