| 1 |
package renderer |
| 2 |
|
| 3 |
import ( |
| 4 |
"errors" |
| 5 |
"fmt" |
| 6 |
"html" |
| 7 |
"io" |
| 8 |
"strings" |
| 9 |
|
| 10 |
"github.com/olekukonko/ll" |
| 11 |
|
| 12 |
"github.com/olekukonko/tablewriter/tw" |
| 13 |
) |
| 14 |
|
| 15 |
// HTMLConfig defines settings for the HTML table renderer. |
| 16 |
type HTMLConfig struct { |
| 17 |
EscapeContent bool // Whether to escape cell content |
| 18 |
AddLinesTag bool // Whether to wrap multiline content in <lines> tags |
| 19 |
TableClass string // CSS class for <table> |
| 20 |
HeaderClass string // CSS class for <thead> |
| 21 |
BodyClass string // CSS class for <tbody> |
| 22 |
FooterClass string // CSS class for <tfoot> |
| 23 |
RowClass string // CSS class for <tr> in body |
| 24 |
HeaderRowClass string // CSS class for <tr> in header |
| 25 |
FooterRowClass string // CSS class for <tr> in footer |
| 26 |
} |
| 27 |
|
| 28 |
// HTML renders tables in HTML format with customizable classes and content handling. |
| 29 |
type HTML struct { |
| 30 |
config HTMLConfig // Renderer configuration |
| 31 |
w io.Writer // Output w |
| 32 |
trace []string // Debug trace messages |
| 33 |
debug bool // Enables debug logging |
| 34 |
tableStarted bool // Tracks if <table> tag is open |
| 35 |
tbodyStarted bool // Tracks if <tbody> tag is open |
| 36 |
tfootStarted bool // Tracks if <tfoot> tag is open |
| 37 |
vMergeTrack map[int]int // Tracks vertical merge spans by column index |
| 38 |
logger *ll.Logger |
| 39 |
} |
| 40 |
|
| 41 |
// NewHTML initializes an HTML renderer with the given w, debug setting, and optional configuration. |
| 42 |
// It panics if the w is nil and applies defaults for unset config fields. |
| 43 |
// Update: see https://github.com/olekukonko/tablewriter/issues/258 |
| 44 |
func NewHTML(configs ...HTMLConfig) *HTML { |
| 45 |
cfg := HTMLConfig{ |
| 46 |
EscapeContent: true, |
| 47 |
AddLinesTag: false, |
| 48 |
} |
| 49 |
if len(configs) > 0 { |
| 50 |
userCfg := configs[0] |
| 51 |
cfg.EscapeContent = userCfg.EscapeContent |
| 52 |
cfg.AddLinesTag = userCfg.AddLinesTag |
| 53 |
cfg.TableClass = userCfg.TableClass |
| 54 |
cfg.HeaderClass = userCfg.HeaderClass |
| 55 |
cfg.BodyClass = userCfg.BodyClass |
| 56 |
cfg.FooterClass = userCfg.FooterClass |
| 57 |
cfg.RowClass = userCfg.RowClass |
| 58 |
cfg.HeaderRowClass = userCfg.HeaderRowClass |
| 59 |
cfg.FooterRowClass = userCfg.FooterRowClass |
| 60 |
} |
| 61 |
return &HTML{ |
| 62 |
config: cfg, |
| 63 |
vMergeTrack: make(map[int]int), |
| 64 |
tableStarted: false, |
| 65 |
tbodyStarted: false, |
| 66 |
tfootStarted: false, |
| 67 |
logger: ll.New("html").Disable(), |
| 68 |
} |
| 69 |
} |
| 70 |
|
| 71 |
func (h *HTML) Logger(logger *ll.Logger) { |
| 72 |
h.logger = logger |
| 73 |
} |
| 74 |
|
| 75 |
// Config returns a Rendition representation of the current configuration. |
| 76 |
func (h *HTML) Config() tw.Rendition { |
| 77 |
return tw.Rendition{ |
| 78 |
Borders: tw.BorderNone, |
| 79 |
Symbols: tw.NewSymbols(tw.StyleNone), |
| 80 |
Settings: tw.Settings{}, |
| 81 |
Streaming: false, |
| 82 |
} |
| 83 |
} |
| 84 |
|
| 85 |
// debugLog appends a formatted message to the debug trace if debugging is enabled. |
| 86 |
// func (h *HTML) debugLog(format string, a ...interface{}) { |
| 87 |
// if h.debug { |
| 88 |
// msg := fmt.Sprintf(format, a...) |
| 89 |
// h.trace = append(h.trace, fmt.Sprintf("[HTML] %s", msg)) |
| 90 |
// } |
| 91 |
//} |
| 92 |
|
| 93 |
// Debug returns the accumulated debug trace messages. |
| 94 |
func (h *HTML) Debug() []string { |
| 95 |
return h.trace |
| 96 |
} |
| 97 |
|
| 98 |
// Start begins the HTML table rendering by opening the <table> tag. |
| 99 |
func (h *HTML) Start(w io.Writer) error { |
| 100 |
h.w = w |
| 101 |
h.Reset() |
| 102 |
h.logger.Debug("HTML.Start() called.") |
| 103 |
|
| 104 |
classAttr := tw.Empty |
| 105 |
if h.config.TableClass != tw.Empty { |
| 106 |
classAttr = fmt.Sprintf(` class="%s"`, h.config.TableClass) |
| 107 |
} |
| 108 |
h.logger.Debugf("Writing opening <table%s> tag", classAttr) |
| 109 |
_, err := fmt.Fprintf(h.w, "<table%s>\n", classAttr) |
| 110 |
if err != nil { |
| 111 |
return err |
| 112 |
} |
| 113 |
h.tableStarted = true |
| 114 |
return nil |
| 115 |
} |
| 116 |
|
| 117 |
// closePreviousSection closes any open <tbody> or <tfoot> sections. |
| 118 |
func (h *HTML) closePreviousSection() { |
| 119 |
if h.tbodyStarted { |
| 120 |
h.logger.Debug("Closing <tbody> tag") |
| 121 |
fmt.Fprintln(h.w, "</tbody>") |
| 122 |
h.tbodyStarted = false |
| 123 |
} |
| 124 |
if h.tfootStarted { |
| 125 |
h.logger.Debug("Closing <tfoot> tag") |
| 126 |
fmt.Fprintln(h.w, "</tfoot>") |
| 127 |
h.tfootStarted = false |
| 128 |
} |
| 129 |
} |
| 130 |
|
| 131 |
// Header renders the <thead> section with header rows, supporting horizontal merges. |
| 132 |
func (h *HTML) Header(headers [][]string, ctx tw.Formatting) { |
| 133 |
if !h.tableStarted { |
| 134 |
h.logger.Debug("WARN: Header called before Start") |
| 135 |
return |
| 136 |
} |
| 137 |
if len(headers) == 0 || len(headers[0]) == 0 { |
| 138 |
h.logger.Debug("Header: No headers") |
| 139 |
return |
| 140 |
} |
| 141 |
|
| 142 |
h.closePreviousSection() |
| 143 |
classAttr := tw.Empty |
| 144 |
if h.config.HeaderClass != tw.Empty { |
| 145 |
classAttr = fmt.Sprintf(` class="%s"`, h.config.HeaderClass) |
| 146 |
} |
| 147 |
fmt.Fprintf(h.w, "<thead%s>\n", classAttr) |
| 148 |
|
| 149 |
headerRow := headers[0] |
| 150 |
numCols := 0 |
| 151 |
if len(ctx.Row.Current) > 0 { |
| 152 |
maxKey := -1 |
| 153 |
for k := range ctx.Row.Current { |
| 154 |
if k > maxKey { |
| 155 |
maxKey = k |
| 156 |
} |
| 157 |
} |
| 158 |
numCols = maxKey + 1 |
| 159 |
} else if len(headerRow) > 0 { |
| 160 |
numCols = len(headerRow) |
| 161 |
} |
| 162 |
|
| 163 |
indent := " " |
| 164 |
rowClassAttr := tw.Empty |
| 165 |
if h.config.HeaderRowClass != tw.Empty { |
| 166 |
rowClassAttr = fmt.Sprintf(` class="%s"`, h.config.HeaderRowClass) |
| 167 |
} |
| 168 |
fmt.Fprintf(h.w, "%s<tr%s>", indent, rowClassAttr) |
| 169 |
|
| 170 |
renderedCols := 0 |
| 171 |
for colIdx := 0; renderedCols < numCols && colIdx < numCols; { |
| 172 |
// Skip columns consumed by vertical merges |
| 173 |
if remainingSpan, merging := h.vMergeTrack[colIdx]; merging && remainingSpan > 1 { |
| 174 |
h.logger.Debugf("Header: Skipping col %d due to vmerge", colIdx) |
| 175 |
h.vMergeTrack[colIdx]-- |
| 176 |
if h.vMergeTrack[colIdx] <= 1 { |
| 177 |
delete(h.vMergeTrack, colIdx) |
| 178 |
} |
| 179 |
colIdx++ |
| 180 |
continue |
| 181 |
} |
| 182 |
|
| 183 |
// Render cell |
| 184 |
cellCtx, ok := ctx.Row.Current[colIdx] |
| 185 |
if !ok { |
| 186 |
cellCtx = tw.CellContext{Align: tw.AlignCenter} |
| 187 |
} |
| 188 |
originalContent := tw.Empty |
| 189 |
if colIdx < len(headerRow) { |
| 190 |
originalContent = headerRow[colIdx] |
| 191 |
} |
| 192 |
|
| 193 |
tag, attributes, processedContent := h.renderRowCell(originalContent, cellCtx, true, colIdx) |
| 194 |
fmt.Fprintf(h.w, "<%s%s>%s</%s>", tag, attributes, processedContent, tag) |
| 195 |
renderedCols++ |
| 196 |
|
| 197 |
// Handle horizontal merges |
| 198 |
hSpan := 1 |
| 199 |
if cellCtx.Merge.Horizontal.Present && cellCtx.Merge.Horizontal.Start { |
| 200 |
hSpan = cellCtx.Merge.Horizontal.Span |
| 201 |
renderedCols += (hSpan - 1) |
| 202 |
} |
| 203 |
colIdx += hSpan |
| 204 |
} |
| 205 |
fmt.Fprintf(h.w, "</tr>\n") |
| 206 |
fmt.Fprintln(h.w, "</thead>") |
| 207 |
} |
| 208 |
|
| 209 |
// Row renders a <tr> element within <tbody>, supporting horizontal and vertical merges. |
| 210 |
func (h *HTML) Row(row []string, ctx tw.Formatting) { |
| 211 |
if !h.tableStarted { |
| 212 |
h.logger.Debug("WARN: Row called before Start") |
| 213 |
return |
| 214 |
} |
| 215 |
|
| 216 |
if !h.tbodyStarted { |
| 217 |
h.closePreviousSection() |
| 218 |
classAttr := tw.Empty |
| 219 |
if h.config.BodyClass != tw.Empty { |
| 220 |
classAttr = fmt.Sprintf(` class="%s"`, h.config.BodyClass) |
| 221 |
} |
| 222 |
h.logger.Debugf("Writing opening <tbody%s> tag", classAttr) |
| 223 |
fmt.Fprintf(h.w, "<tbody%s>\n", classAttr) |
| 224 |
h.tbodyStarted = true |
| 225 |
} |
| 226 |
|
| 227 |
h.logger.Debugf("Rendering row data: %v", row) |
| 228 |
numCols := 0 |
| 229 |
if len(ctx.Row.Current) > 0 { |
| 230 |
maxKey := -1 |
| 231 |
for k := range ctx.Row.Current { |
| 232 |
if k > maxKey { |
| 233 |
maxKey = k |
| 234 |
} |
| 235 |
} |
| 236 |
numCols = maxKey + 1 |
| 237 |
} else if len(row) > 0 { |
| 238 |
numCols = len(row) |
| 239 |
} |
| 240 |
|
| 241 |
indent := " " |
| 242 |
rowClassAttr := tw.Empty |
| 243 |
if h.config.RowClass != tw.Empty { |
| 244 |
rowClassAttr = fmt.Sprintf(` class="%s"`, h.config.RowClass) |
| 245 |
} |
| 246 |
fmt.Fprintf(h.w, "%s<tr%s>", indent, rowClassAttr) |
| 247 |
|
| 248 |
renderedCols := 0 |
| 249 |
for colIdx := 0; renderedCols < numCols && colIdx < numCols; { |
| 250 |
// Skip columns consumed by vertical merges |
| 251 |
if remainingSpan, merging := h.vMergeTrack[colIdx]; merging && remainingSpan > 1 { |
| 252 |
h.logger.Debugf("Row: Skipping render for col %d due to vertical merge (remaining %d)", colIdx, remainingSpan-1) |
| 253 |
h.vMergeTrack[colIdx]-- |
| 254 |
if h.vMergeTrack[colIdx] <= 1 { |
| 255 |
delete(h.vMergeTrack, colIdx) |
| 256 |
} |
| 257 |
colIdx++ |
| 258 |
continue |
| 259 |
} |
| 260 |
|
| 261 |
// Render cell |
| 262 |
cellCtx, ok := ctx.Row.Current[colIdx] |
| 263 |
if !ok { |
| 264 |
cellCtx = tw.CellContext{Align: tw.AlignLeft} |
| 265 |
} |
| 266 |
originalContent := tw.Empty |
| 267 |
if colIdx < len(row) { |
| 268 |
originalContent = row[colIdx] |
| 269 |
} |
| 270 |
|
| 271 |
tag, attributes, processedContent := h.renderRowCell(originalContent, cellCtx, false, colIdx) |
| 272 |
fmt.Fprintf(h.w, "<%s%s>%s</%s>", tag, attributes, processedContent, tag) |
| 273 |
renderedCols++ |
| 274 |
|
| 275 |
// Handle horizontal merges |
| 276 |
hSpan := 1 |
| 277 |
if cellCtx.Merge.Horizontal.Present && cellCtx.Merge.Horizontal.Start { |
| 278 |
hSpan = cellCtx.Merge.Horizontal.Span |
| 279 |
renderedCols += (hSpan - 1) |
| 280 |
} |
| 281 |
colIdx += hSpan |
| 282 |
} |
| 283 |
fmt.Fprintf(h.w, "</tr>\n") |
| 284 |
} |
| 285 |
|
| 286 |
// Footer renders the <tfoot> section with footer rows, supporting horizontal merges. |
| 287 |
func (h *HTML) Footer(footers [][]string, ctx tw.Formatting) { |
| 288 |
if !h.tableStarted { |
| 289 |
h.logger.Debug("WARN: Footer called before Start") |
| 290 |
return |
| 291 |
} |
| 292 |
if len(footers) == 0 || len(footers[0]) == 0 { |
| 293 |
h.logger.Debug("Footer: No footers") |
| 294 |
return |
| 295 |
} |
| 296 |
|
| 297 |
h.closePreviousSection() |
| 298 |
classAttr := tw.Empty |
| 299 |
if h.config.FooterClass != tw.Empty { |
| 300 |
classAttr = fmt.Sprintf(` class="%s"`, h.config.FooterClass) |
| 301 |
} |
| 302 |
fmt.Fprintf(h.w, "<tfoot%s>\n", classAttr) |
| 303 |
h.tfootStarted = true |
| 304 |
|
| 305 |
footerRow := footers[0] |
| 306 |
numCols := 0 |
| 307 |
if len(ctx.Row.Current) > 0 { |
| 308 |
maxKey := -1 |
| 309 |
for k := range ctx.Row.Current { |
| 310 |
if k > maxKey { |
| 311 |
maxKey = k |
| 312 |
} |
| 313 |
} |
| 314 |
numCols = maxKey + 1 |
| 315 |
} else if len(footerRow) > 0 { |
| 316 |
numCols = len(footerRow) |
| 317 |
} |
| 318 |
|
| 319 |
indent := " " |
| 320 |
rowClassAttr := tw.Empty |
| 321 |
if h.config.FooterRowClass != tw.Empty { |
| 322 |
rowClassAttr = fmt.Sprintf(` class="%s"`, h.config.FooterRowClass) |
| 323 |
} |
| 324 |
fmt.Fprintf(h.w, "%s<tr%s>", indent, rowClassAttr) |
| 325 |
|
| 326 |
renderedCols := 0 |
| 327 |
for colIdx := 0; renderedCols < numCols && colIdx < numCols; { |
| 328 |
cellCtx, ok := ctx.Row.Current[colIdx] |
| 329 |
if !ok { |
| 330 |
cellCtx = tw.CellContext{Align: tw.AlignRight} |
| 331 |
} |
| 332 |
originalContent := tw.Empty |
| 333 |
if colIdx < len(footerRow) { |
| 334 |
originalContent = footerRow[colIdx] |
| 335 |
} |
| 336 |
|
| 337 |
tag, attributes, processedContent := h.renderRowCell(originalContent, cellCtx, false, colIdx) |
| 338 |
fmt.Fprintf(h.w, "<%s%s>%s</%s>", tag, attributes, processedContent, tag) |
| 339 |
renderedCols++ |
| 340 |
|
| 341 |
hSpan := 1 |
| 342 |
if cellCtx.Merge.Horizontal.Present && cellCtx.Merge.Horizontal.Start { |
| 343 |
hSpan = cellCtx.Merge.Horizontal.Span |
| 344 |
renderedCols += (hSpan - 1) |
| 345 |
} |
| 346 |
colIdx += hSpan |
| 347 |
} |
| 348 |
fmt.Fprintf(h.w, "</tr>\n") |
| 349 |
fmt.Fprintln(h.w, "</tfoot>") |
| 350 |
h.tfootStarted = false |
| 351 |
} |
| 352 |
|
| 353 |
// renderRowCell generates HTML for a single cell, handling content escaping, merges, and alignment. |
| 354 |
func (h *HTML) renderRowCell(originalContent string, cellCtx tw.CellContext, isHeader bool, colIdx int) (tag, attributes, processedContent string) { |
| 355 |
tag = "td" |
| 356 |
if isHeader { |
| 357 |
tag = "th" |
| 358 |
} |
| 359 |
|
| 360 |
// Process content |
| 361 |
processedContent = originalContent |
| 362 |
containsNewline := strings.Contains(originalContent, "\n") |
| 363 |
|
| 364 |
if h.config.EscapeContent { |
| 365 |
if containsNewline { |
| 366 |
const newlinePlaceholder = "[[--HTML_RENDERER_BR_PLACEHOLDER--]]" |
| 367 |
tempContent := strings.ReplaceAll(originalContent, "\n", newlinePlaceholder) |
| 368 |
escapedContent := html.EscapeString(tempContent) |
| 369 |
processedContent = strings.ReplaceAll(escapedContent, newlinePlaceholder, "<br>") |
| 370 |
} else { |
| 371 |
processedContent = html.EscapeString(originalContent) |
| 372 |
} |
| 373 |
} else if containsNewline { |
| 374 |
processedContent = strings.ReplaceAll(originalContent, "\n", "<br>") |
| 375 |
} |
| 376 |
|
| 377 |
if containsNewline && h.config.AddLinesTag { |
| 378 |
processedContent = "<lines>" + processedContent + "</lines>" |
| 379 |
} |
| 380 |
|
| 381 |
// Build attributes |
| 382 |
var attrBuilder strings.Builder |
| 383 |
merge := cellCtx.Merge |
| 384 |
|
| 385 |
if merge.Horizontal.Present && merge.Horizontal.Start && merge.Horizontal.Span > 1 { |
| 386 |
fmt.Fprintf(&attrBuilder, ` colspan="%d"`, merge.Horizontal.Span) |
| 387 |
} |
| 388 |
|
| 389 |
vSpan := 0 |
| 390 |
if !isHeader { |
| 391 |
if merge.Vertical.Present && merge.Vertical.Start { |
| 392 |
vSpan = merge.Vertical.Span |
| 393 |
} else if merge.Hierarchical.Present && merge.Hierarchical.Start { |
| 394 |
vSpan = merge.Hierarchical.Span |
| 395 |
} |
| 396 |
if vSpan > 1 { |
| 397 |
fmt.Fprintf(&attrBuilder, ` rowspan="%d"`, vSpan) |
| 398 |
h.vMergeTrack[colIdx] = vSpan |
| 399 |
h.logger.Debugf("renderRowCell: Tracking rowspan=%d for col %d", vSpan, colIdx) |
| 400 |
} |
| 401 |
} |
| 402 |
|
| 403 |
if style := getHTMLStyle(cellCtx.Align); style != tw.Empty { |
| 404 |
attrBuilder.WriteString(style) |
| 405 |
} |
| 406 |
attributes = attrBuilder.String() |
| 407 |
return |
| 408 |
} |
| 409 |
|
| 410 |
// Line is a no-op for HTML rendering, as structural lines are handled by tags. |
| 411 |
func (h *HTML) Line(ctx tw.Formatting) {} |
| 412 |
|
| 413 |
// Reset clears the renderer's internal state, including debug traces and merge tracking. |
| 414 |
func (h *HTML) Reset() { |
| 415 |
h.logger.Debug("HTML.Reset() called.") |
| 416 |
h.tableStarted = false |
| 417 |
h.tbodyStarted = false |
| 418 |
h.tfootStarted = false |
| 419 |
h.vMergeTrack = make(map[int]int) |
| 420 |
h.trace = nil |
| 421 |
} |
| 422 |
|
| 423 |
// Close ensures all open HTML tags (<table>, <tbody>, <tfoot>) are properly closed. |
| 424 |
func (h *HTML) Close() error { |
| 425 |
if h.w == nil { |
| 426 |
return errors.New("HTML Renderer Close called on nil internal w") |
| 427 |
} |
| 428 |
|
| 429 |
if h.tableStarted { |
| 430 |
h.logger.Debug("HTML.Close() called.") |
| 431 |
h.closePreviousSection() |
| 432 |
h.logger.Debug("Closing <table> tag.") |
| 433 |
_, err := fmt.Fprintln(h.w, "</table>") |
| 434 |
h.tableStarted = false |
| 435 |
h.tbodyStarted = false |
| 436 |
h.tfootStarted = false |
| 437 |
h.vMergeTrack = make(map[int]int) |
| 438 |
return err |
| 439 |
} |
| 440 |
h.logger.Debug("HTML.Close() called, but table was not started (no-op).") |
| 441 |
return nil |
| 442 |
} |