8000 Fix table header conversion and prettify markdown table output by letmutex · Pull Request #37 · letmutex/htmd · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Fix table header conversion and prettify markdown table output #37

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 17, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 30 additions & 31 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,37 +71,36 @@ assert_eq!("[Svg Image]", converter.convert("<svg></svg>").unwrap());
```rust
use htmd::convert;

fn main() {
let html = r#"
<table>
<thead>
<tr>
<th>Language</th>
<th>Type</th>
<th>Year</th>
</tr>
</thead>
<tbody>
<tr>
<td>Rust</td>
<td>Systems</td>
<td>2010</td>
</tr>
<tr>
<td>Python</td>
<td>Interpreted</td>
<td>1991</td>
</tr>
</tbody>
</table>
"#;

let markdown = convert(html).unwrap();
println!("{}", markdown);
// Output:
// | Rust |Systems |2010 |
// | Python |Interpreted |1991 |
}
let html = r#"
<table>
<thead>
<tr>
<th>Language</th>
<th>Type</th>
<th>Year</th>
</tr>
</thead>
<tbody>
<tr>
<td>Rust</td>
<td>Systems</td>
<td>2010</td>
</tr>
<tr>
<td>Python</td>
<td>Interpreted</td>
<td>1991</td>
</tr>
</tbody>
</table>
"#;

println!("{}", convert(html).unwrap());
// Output:
// | Language | Type | Year |
// | -------- | ----------- | ---- |
// | Rust | Systems | 2010 |
// | Python | Interpreted | 1991 |
```

### Multithreading
Expand Down
99 changes: 67 additions & 32 deletions src/element_handler/table.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::element_handler::Element;
use crate::node_util::{get_node_children, get_node_content};
use crate::node_util::{get_node_children, get_node_content, get_node_tag_name};
use crate::text_util::concat_strings;
use markup5ever_rcdom::NodeData;
use std::rc::Rc;
Expand Down Expand Up @@ -35,10 +35,22 @@ pub(crate) fn table_handler(element: Element) -> Option<String> {
captions.push(get_node_content(&child).trim().to_string());
}
"thead" => {
let tr = child
.children
.borrow()
.iter()
.find(|it| get_node_tag_name(it).is_some_and(|tag| tag == "tr"))
.cloned();

let row_node = match tr {
Some(tr) => tr,
None => child,
};

has_thead = true;
headers = extract_row_cells(&child, "th");
headers = extract_row_cells(&row_node, "th");
if headers.is_empty() {
headers = extract_row_cells(&child, "td");
headers = extract_row_cells(&row_node, "td");
}
}
"tbody" | "tfoot" => {
Expand Down Expand Up @@ -100,35 +112,14 @@ pub(crate) fn table_handler(element: Element) -> Option<String> {
table_md.push_str(&format!("{}\n", caption));
}

// Add header row if available
if !headers.is_empty() {
table_md.push_str("| ");
for (i, header) in headers.iter().enumerate() {
if i < num_columns {
table_md.push_str(&normalize_cell_content(header));
table_md.push_str(" |");
}
}
table_md.push('\n');
let col_widths = compute_column_widths(&headers, &rows, num_columns);

// Add separator row
table_md.push_str("| ");
for _ in 0..num_columns {
table_md.push_str("--- |");
}
table_md.push('\n');
if !headers.is_empty() {
table_md.push_str(&format_row_padded(&headers, num_columns, &col_widths));
table_md.push_str(&format_separator_padded(num_columns, &col_widths));
}

// Add data rows
for row in rows {
table_md.push_str("| ");
for i in 0..num_columns {
if i < row.len() {
table_md.push_str(&normalize_cell_content(&row[i]));
}
table_md.push_str(" |");
}
table_md.push('\n');
table_md.push_str(&format_row_padded(&row, num_columns, &col_widths));
}

table_md.push('\n');
Expand All @@ -153,8 +144,52 @@ fn extract_row_cells(row_node: &Rc<markup5ever_rcdom::Node>, cell_tag: &str) ->

/// Normalize cell content for Markdown table representation
fn normalize_cell_content(content: &str) -> String {
let content = content.replace('\n', " ").replace('\r', "");
let content = content.trim();
let content = content
.replace('\n', " ")
.replace('\r', "")
.replace('|', "&#124;");
content.trim().to_string()
}

content.to_string()
fn format_row_padded(row: &[String], num_columns: usize, col_widths: &[usize]) -> String {
let mut line = String::from("|");
for (i, col_width) in col_widths.iter().enumerate().take(num_columns) {
let cell = row
.get(i)
.map(|s| normalize_cell_content(s))
.unwrap_or_default();
let pad = col_width.saturating_sub(cell.chars().count());
line.push_str(&concat_strings!(" ", cell, " ".repeat(pad), " |"));
}
line.push('\n');
line
}

fn format_separator_padded(num_columns: usize, col_widths: &[usize]) -> String {
let mut line = String::from("|");
for (_, col_width) in col_widths.iter().enumerate().take(num_columns) {
line.push_str(&concat_strings!(" ", "-".repeat(*col_width), " |"));
}
line.push('\n');
line
}

fn compute_column_widths(
headers: &[String],
rows: &[Vec<String>],
num_columns: usize,
) -> Vec<usize> {
let mut widths = vec![0; num_columns];
for (i, header) in headers.iter().enumerate() {
widths[i] = header.chars().count();
}
for row in rows {
for (i, cell) in row.iter().enumerate().take(num_columns) {
let len = cell.chars().count();
if len > widths[i] {
widths[i] = len;
}
}
}
widths
}
14 changes: 8 additions & 6 deletions tests/table_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ mod table_tests_1 {
"#;

let expected = r#"
| Cell 1 |Cell 2 |
| Cell 3 |Cell 4 |
| Cell 1 | Cell 2 |
| Cell 3 | Cell 4 |
"#
.trim();

Expand Down Expand Up @@ -59,8 +59,10 @@ mod table_tests_1 {
"#;

let expected = r#"
| John |35 |New York |
| Jane |28 |San Francisco |
| Name | Age | Location |
| ---- | --- | ------------- |
| John | 35 | New York |
| Jane | 28 | San Francisco |
"#
.trim();

Expand Down Expand Up @@ -91,8 +93,8 @@ mod table_tests_1 {

let expected = r#"
Sample Table
| John |35 |New York |
| Jane |28 |San Francisco |
| John | 35 | New York |
| Jane | 28 | San Francisco |
"#
.trim();

Expand Down
0