Skip to content

Commit

Permalink
Fix GH-256 Table alignment styling
Browse files Browse the repository at this point in the history
  • Loading branch information
mysticmind committed Aug 31, 2022
1 parent cec8623 commit b0dddbb
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
| Col1 | Col2 | Col2 |
| :--- | :---: | ---: |
| 1 | 2 | 3 |
8 changes: 8 additions & 0 deletions src/ReverseMarkdown.Test/ConverterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1303,5 +1303,13 @@ public Task Bug294_Table_bug_with_row_superfluous_newlines()

return CheckConversion(html);
}

[Fact]
public Task WhenTableHeadingWithAlignmentStyles_ThenTableHeaderShouldHaveProperAlignment()
{
var html =
$"<table><tr><th style=\"text-align:left\">Col1</th><th style=\"text-align:center\">Col2</th><th style=\"text-align:right\">Col2</th></tr><tr><td>1</td><td>2</td><td>3</td></tr></table>";
return CheckConversion(html);
}
}
}
23 changes: 19 additions & 4 deletions src/ReverseMarkdown/Converters/Tr.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,28 @@ private static bool IsTableHeaderRow(HtmlNode node)

private static string UnderlineFor(HtmlNode node, string indent)
{
var colCount = node.ChildNodes.Count(child => child.Name == "th" || child.Name == "td");
var nodes = node.ChildNodes.Where(x => x.Name == "th" || x.Name == "td").ToList();

var cols = new List<string>();

for (var i = 0; i < colCount; i++ )
foreach (var styles in nodes.Select(nd => StringUtils.ParseStyle(nd.GetAttributeValue("style", ""))))
{
cols.Add("---");
styles.TryGetValue("text-align", out var align);

switch (align)
{
case "left":
cols.Add(":---");
break;
case "right":
cols.Add("---:");
break;
case "center":
cols.Add(":---:");
break;
default:
cols.Add("---");
break;
}
}

var colsAggregated = string.Join(" | ", cols);
Expand Down
14 changes: 14 additions & 0 deletions src/ReverseMarkdown/StringUtils.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;

namespace ReverseMarkdown
Expand Down Expand Up @@ -62,5 +63,18 @@ internal static string EscapeLinkText(string rawText)
.Replace("[", @"\[")
.Replace("]", @"\]");
}

internal static Dictionary<string, string> ParseStyle(string style)
{
if (string.IsNullOrEmpty(style))
{
return new Dictionary<string, string>();
}

var styles = style.Split(';');
return styles.Select(styleItem => styleItem.Split(':'))
.Where(styleParts => styleParts.Length == 2)
.ToDictionary(styleParts => styleParts[0], styleParts => styleParts[1]);
}
}
}

0 comments on commit b0dddbb

Please sign in to comment.