1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
|
package table
import (
"bytes"
"github.com/JohannesKaufmann/dom"
"github.com/JohannesKaufmann/html-to-markdown/v2/converter"
"github.com/JohannesKaufmann/html-to-markdown/v2/marker"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
type tableContent struct {
Alignments []string
Rows [][][]byte
Caption []byte
}
func containsNewline(b []byte) bool {
return bytes.Contains(b, []byte("\n"))
}
func hasProblematicChildNode(node *html.Node) bool {
problematicNode := dom.FindFirstNode(node, func(n *html.Node) bool {
name := dom.NodeName(n)
if dom.NameIsHeading(name) {
return true
}
switch name {
case "table":
// This will be caught with the newline check anyway.
// But we can safe some effort by aborting early...
return true
case "hr", "ul", "ol", "blockquote":
return true
}
return false
})
return problematicNode != nil
}
func hasProblematicParentNode(node *html.Node) bool {
p := node.Parent
for p != nil {
name := dom.NodeName(p)
if name == "a" {
return true
}
if name == "strong" || name == "b" {
return true
}
if name == "em" || name == "i" {
return true
}
if name == "del" || name == "s" || name == "strike" {
return true
}
p = p.Parent
}
return false
}
func (p *tablePlugin) collectTableContent(ctx converter.Context, node *html.Node) *tableContent {
if role := dom.GetAttributeOr(node, "role", ""); role == "presentation" {
// In HTML-Emails many tables are used. Oftentimes these tables are nested
// which is not possible with markdown. But these tables are mostly used
// for *layout purposes* rather than displaying actual tabular data.
if !p.convertPresentationTables {
// So lets skip those with role="presentation" and focus on real tables...
return nil
}
}
if hasProblematicChildNode(node) {
// There are certain nodes (e.g. <hr />) that cannot be in a table.
// If we found one, we unfortunately cannot convert the table.
//
// Note: It is okay for a block node (e.g. <div>) to be in a table.
// However once it causes multiple lines, it does not work anymore.
// For that we have the `containsNewline` check below.
return nil
}
if hasProblematicParentNode(node) {
// There are certain parent nodes (e.g. <a>) that cannot contain a table.
// We would break the rendering of the link, so we unfortunately cannot convert the table.
return nil
}
headerRowNode := selectHeaderRowNode(node)
normalRowNodes := selectNormalRowNodes(node, headerRowNode)
rows := p.collectRows(ctx, headerRowNode, normalRowNodes)
if len(rows) == 0 {
return nil
}
for i, cells := range rows {
for j, cell := range cells {
if containsNewline(cell) {
if p.newlineBehavior == NewlineBehaviorPreserve {
// Replace newlines with <br /> tags
rows[i][j] = bytes.ReplaceAll(cell, []byte("\n"), []byte("<br />"))
continue
}
// We're configured to skip tables with newlines, return nil
return nil
}
}
}
return &tableContent{
Alignments: collectAlignments(headerRowNode, normalRowNodes),
Rows: rows,
Caption: collectCaption(ctx, node),
}
}
// Sometimes a cell wants to *span* over multiple columns or/and rows.
// What should be displayed in those other cells?
// Render exactly the same content OR an empty string?
func (p *tablePlugin) getContentForMergedCell(originalContent []byte) []byte {
if p.spanCellBehavior == SpanBehaviorMirror {
return originalContent
}
return []byte("")
}
func getFirstNode(node *html.Node, nodes ...*html.Node) *html.Node {
if node != nil {
return node
}
if len(nodes) >= 1 {
return nodes[0]
}
return nil
}
func collectAlignments(headerRowNode *html.Node, rowNodes []*html.Node) []string {
firstRow := getFirstNode(headerRowNode, rowNodes...)
if firstRow == nil {
return nil
}
cellNodes := dom.FindAllNodes(firstRow, func(node *html.Node) bool {
name := dom.NodeName(node)
return name == "th" || name == "td"
})
var alignments []string
for _, cellNode := range cellNodes {
align := dom.GetAttributeOr(cellNode, "align", "")
alignments = append(alignments, align)
}
return alignments
}
func (p *tablePlugin) collectCellsInRow(ctx converter.Context, rowIndex int, rowNode *html.Node) ([][]byte, []modification) {
cellNodes := dom.FindAllNodes(rowNode, func(node *html.Node) bool {
name := dom.NodeName(node)
return name == "th" || name == "td"
})
cellContents := make([][]byte, 0, len(cellNodes))
modifications := make([]modification, 0)
for index, cellNode := range cellNodes {
var buf bytes.Buffer
ctx.RenderNodes(ctx, &buf, cellNode)
content := buf.Bytes()
content = bytes.TrimSpace(content)
// The character "|" inside the content would mistakenly be recognized as part of the table. So we have to escape it.
content = bytes.Replace(content, []byte{byte(marker.MarkerEscaping), '|'}, []byte(`\|`), -1)
content = ctx.UnEscapeContent(content)
cellContents = append(cellContents, content)
// - - col / row span - - //
rowSpan := getNumberAttributeOr(cellNode, "rowspan", 1)
colSpan := getNumberAttributeOr(cellNode, "colspan", 1)
mods := calculateModifications(rowIndex, index, rowSpan, colSpan, p.getContentForMergedCell(content))
modifications = append(modifications, mods...)
}
return cellContents, modifications
}
func (p *tablePlugin) collectRows(ctx converter.Context, headerRowNode *html.Node, rowNodes []*html.Node) [][][]byte {
rowContents := make([][][]byte, 0, len(rowNodes)+1)
groupedModifications := make([][]modification, 0)
// - - 1. the header row - - //
if headerRowNode != nil {
cells, mods := p.collectCellsInRow(ctx, 0, headerRowNode)
rowContents = append(rowContents, cells)
groupedModifications = append(groupedModifications, mods)
} else {
// There needs to be *header* row so that the table is recognized.
// So it is better to have an empty header row...
rowContents = append(rowContents, [][]byte{})
}
// - - 2. the normal rows - - //
for index, rowNode := range rowNodes {
cells, mods := p.collectCellsInRow(ctx, index+1, rowNode)
rowContents = append(rowContents, cells)
groupedModifications = append(groupedModifications, mods)
}
// Sometimes a cell wants to *span* over multiple columns or/and rows.
// We collected these modifications and are now applying it,
// by shifting the cells around.
rowContents = applyGroupedModifications(rowContents, groupedModifications)
if p.skipEmptyRows {
rowContents = removeEmptyRows(rowContents)
}
if p.promoteFirstRowToHeader {
rowContents = removeFirstRowIfEmpty(rowContents)
}
return rowContents
}
func collectCaption(ctx converter.Context, node *html.Node) []byte {
captionNode := dom.FindFirstNode(node, func(node *html.Node) bool {
return node.DataAtom == atom.Caption
})
if captionNode == nil {
return nil
}
var buf bytes.Buffer
ctx.RenderNodes(ctx, &buf, captionNode)
content := buf.Bytes()
content = bytes.TrimSpace(content)
return content
}
|