| 1 |
package renderer |
| 2 |
|
| 3 |
import ( |
| 4 |
"io" |
| 5 |
"slices" |
| 6 |
"strings" |
| 7 |
|
| 8 |
"github.com/olekukonko/tablewriter/pkg/twwidth" |
| 9 |
|
| 10 |
"github.com/olekukonko/ll" |
| 11 |
"github.com/olekukonko/tablewriter/tw" |
| 12 |
) |
| 13 |
|
| 14 |
// OceanConfig defines configuration specific to the Ocean renderer. |
| 15 |
type OceanConfig struct{} |
| 16 |
|
| 17 |
// Ocean is a streaming table renderer that writes ASCII tables. |
| 18 |
type Ocean struct { |
| 19 |
config tw.Rendition |
| 20 |
oceanConfig OceanConfig |
| 21 |
fixedWidths tw.Mapper[int, int] |
| 22 |
widthsFinalized bool |
| 23 |
tableOutputStarted bool |
| 24 |
headerContentRendered bool // True if actual header *content* has been rendered by Ocean.Header |
| 25 |
logger *ll.Logger |
| 26 |
w io.Writer |
| 27 |
} |
| 28 |
|
| 29 |
func NewOcean(oceanConfig ...OceanConfig) *Ocean { |
| 30 |
cfg := defaultOceanRendererConfig() |
| 31 |
oCfg := OceanConfig{} |
| 32 |
if len(oceanConfig) > 0 { |
| 33 |
// Apply user-provided OceanConfig if necessary |
| 34 |
} |
| 35 |
r := &Ocean{ |
| 36 |
config: cfg, |
| 37 |
oceanConfig: oCfg, |
| 38 |
fixedWidths: tw.NewMapper[int, int](), |
| 39 |
logger: ll.New("ocean").Disable(), |
| 40 |
} |
| 41 |
r.resetState() |
| 42 |
return r |
| 43 |
} |
| 44 |
|
| 45 |
func (o *Ocean) resetState() { |
| 46 |
o.fixedWidths = tw.NewMapper[int, int]() |
| 47 |
o.widthsFinalized = false |
| 48 |
o.tableOutputStarted = false |
| 49 |
o.headerContentRendered = false |
| 50 |
o.logger.Debug("State reset.") |
| 51 |
} |
| 52 |
|
| 53 |
func (o *Ocean) Logger(logger *ll.Logger) { |
| 54 |
o.logger = logger.Namespace("ocean") |
| 55 |
} |
| 56 |
|
| 57 |
func (o *Ocean) Config() tw.Rendition { |
| 58 |
return o.config |
| 59 |
} |
| 60 |
|
| 61 |
func (o *Ocean) tryFinalizeWidths(ctx tw.Formatting) { |
| 62 |
if o.widthsFinalized { |
| 63 |
return |
| 64 |
} |
| 65 |
if ctx.Row.Widths != nil && ctx.Row.Widths.Len() > 0 { |
| 66 |
o.fixedWidths = ctx.Row.Widths.Clone() |
| 67 |
o.widthsFinalized = true |
| 68 |
o.logger.Debugf("Widths finalized from context: %v", o.fixedWidths) |
| 69 |
} else { |
| 70 |
o.logger.Warn("Attempted to finalize widths, but no width data in context.") |
| 71 |
} |
| 72 |
} |
| 73 |
|
| 74 |
func (o *Ocean) Start(w io.Writer) error { |
| 75 |
o.w = w |
| 76 |
o.logger.Debug("Start() called.") |
| 77 |
o.resetState() |
| 78 |
// Top border is drawn by the first component (Header or Row) that has widths |
| 79 |
// OR by an explicit Line() call from table.go's batch renderer. |
| 80 |
return nil |
| 81 |
} |
| 82 |
|
| 83 |
// renderTopBorderIfNeeded is called by Header or Row if it's the first to render |
| 84 |
// and tableOutputStarted is false. |
| 85 |
func (o *Ocean) renderTopBorderIfNeeded(currentPosition tw.Position, ctx tw.Formatting) { |
| 86 |
if !o.tableOutputStarted && o.widthsFinalized { |
| 87 |
// This renderer's config for Top border |
| 88 |
if o.config.Borders.Top.Enabled() && o.config.Settings.Lines.ShowTop.Enabled() { |
| 89 |
o.logger.Debugf("Ocean itself rendering top border (triggered by %s)", currentPosition) |
| 90 |
lineCtx := tw.Formatting{ // Construct specific context for this line |
| 91 |
Row: tw.RowContext{ |
| 92 |
Widths: o.fixedWidths, |
| 93 |
Location: tw.LocationFirst, |
| 94 |
Position: currentPosition, |
| 95 |
Next: ctx.Row.Current, // The actual first content is "Next" to the top border |
| 96 |
}, |
| 97 |
Level: tw.LevelHeader, |
| 98 |
} |
| 99 |
o.Line(lineCtx) |
| 100 |
o.tableOutputStarted = true |
| 101 |
} |
| 102 |
} |
| 103 |
} |
| 104 |
|
| 105 |
func (o *Ocean) Header(headers [][]string, ctx tw.Formatting) { |
| 106 |
o.logger.Debugf("Ocean.Header called: IsSubRow=%v, Location=%v, NumLines=%d", ctx.IsSubRow, ctx.Row.Location, len(headers)) |
| 107 |
|
| 108 |
if !o.widthsFinalized { |
| 109 |
o.tryFinalizeWidths(ctx) |
| 110 |
} |
| 111 |
|
| 112 |
if !o.widthsFinalized { |
| 113 |
o.logger.Error("Ocean.Header: Cannot render content, widths are not finalized.") |
| 114 |
return |
| 115 |
} |
| 116 |
|
| 117 |
if len(headers) > 0 && len(headers[0]) > 0 { |
| 118 |
for i, headerLineData := range headers { |
| 119 |
currentLineCtx := ctx |
| 120 |
currentLineCtx.Row.Widths = o.fixedWidths |
| 121 |
if i > 0 { |
| 122 |
currentLineCtx.IsSubRow = true |
| 123 |
} |
| 124 |
o.renderContentLine(currentLineCtx, headerLineData) |
| 125 |
o.tableOutputStarted = true // Content was written |
| 126 |
} |
| 127 |
o.headerContentRendered = true |
| 128 |
} else { |
| 129 |
o.logger.Debug("Ocean.Header: No actual header content lines to render.") |
| 130 |
} |
| 131 |
} |
| 132 |
|
| 133 |
func (o *Ocean) Row(row []string, ctx tw.Formatting) { |
| 134 |
o.logger.Debugf("Ocean.Row called: IsSubRow=%v, Location=%v, DataItems=%d", ctx.IsSubRow, ctx.Row.Location, len(row)) |
| 135 |
|
| 136 |
if !o.widthsFinalized { |
| 137 |
o.tryFinalizeWidths(ctx) |
| 138 |
} |
| 139 |
if !o.widthsFinalized { |
| 140 |
o.logger.Error("Ocean.Row: Cannot render content, widths are not finalized.") |
| 141 |
return |
| 142 |
} |
| 143 |
|
| 144 |
ctx.Row.Widths = o.fixedWidths |
| 145 |
o.renderContentLine(ctx, row) |
| 146 |
o.tableOutputStarted = true |
| 147 |
} |
| 148 |
|
| 149 |
func (o *Ocean) Footer(footers [][]string, ctx tw.Formatting) { |
| 150 |
o.logger.Debugf("Ocean.Footer called: IsSubRow=%v, Location=%v, NumLines=%d", ctx.IsSubRow, ctx.Row.Location, len(footers)) |
| 151 |
|
| 152 |
if !o.widthsFinalized { |
| 153 |
o.tryFinalizeWidths(ctx) |
| 154 |
o.logger.Warn("Ocean.Footer: Widths finalized at Footer stage (unusual).") |
| 155 |
} |
| 156 |
if !o.widthsFinalized { |
| 157 |
o.logger.Error("Ocean.Footer: Cannot render content, widths are not finalized.") |
| 158 |
return |
| 159 |
} |
| 160 |
|
| 161 |
if len(footers) > 0 && len(footers[0]) > 0 { |
| 162 |
for i, footerLineData := range footers { |
| 163 |
currentLineCtx := ctx |
| 164 |
currentLineCtx.Row.Widths = o.fixedWidths |
| 165 |
if i > 0 { |
| 166 |
currentLineCtx.IsSubRow = true |
| 167 |
} |
| 168 |
o.renderContentLine(currentLineCtx, footerLineData) |
| 169 |
o.tableOutputStarted = true |
| 170 |
} |
| 171 |
} else { |
| 172 |
o.logger.Debug("Ocean.Footer: No actual footer content lines to render.") |
| 173 |
} |
| 174 |
} |
| 175 |
|
| 176 |
func (o *Ocean) Line(ctx tw.Formatting) { |
| 177 |
if !o.widthsFinalized { |
| 178 |
o.tryFinalizeWidths(ctx) |
| 179 |
if !o.widthsFinalized { |
| 180 |
o.logger.Error("Ocean.Line: Called but widths could not be finalized. Skipping line rendering.") |
| 181 |
return |
| 182 |
} |
| 183 |
} |
| 184 |
|
| 185 |
// Ensure Line uses the consistent fixedWidths for drawing |
| 186 |
ctx.Row.Widths = o.fixedWidths |
| 187 |
o.logger.Debugf("Ocean.Line DRAWING: Level=%v, Loc=%s, Pos=%s, IsSubRow=%t, WidthsLen=%d", ctx.Level, ctx.Row.Location, ctx.Row.Position, ctx.IsSubRow, ctx.Row.Widths.Len()) |
| 188 |
|
| 189 |
jr := NewJunction(JunctionContext{ |
| 190 |
Symbols: o.config.Symbols, |
| 191 |
Ctx: ctx, |
| 192 |
ColIdx: 0, |
| 193 |
Logger: o.logger, |
| 194 |
BorderTint: Tint{}, |
| 195 |
SeparatorTint: Tint{}, |
| 196 |
}) |
| 197 |
|
| 198 |
var line strings.Builder |
| 199 |
sortedColIndices := o.fixedWidths.SortedKeys() |
| 200 |
|
| 201 |
if len(sortedColIndices) == 0 { |
| 202 |
drewEmptyBorders := false |
| 203 |
if o.config.Borders.Left.Enabled() { |
| 204 |
line.WriteString(jr.RenderLeft()) |
| 205 |
drewEmptyBorders = true |
| 206 |
} |
| 207 |
if o.config.Borders.Right.Enabled() { |
| 208 |
line.WriteString(jr.RenderRight(-1)) |
| 209 |
drewEmptyBorders = true |
| 210 |
} |
| 211 |
if drewEmptyBorders { |
| 212 |
line.WriteString(tw.NewLine) |
| 213 |
o.w.Write([]byte(line.String())) |
| 214 |
o.logger.Debug("Line: Drew empty table borders based on Line call.") |
| 215 |
} else { |
| 216 |
o.logger.Debug("Line: Handled empty table case (no columns, no borders).") |
| 217 |
} |
| 218 |
o.tableOutputStarted = drewEmptyBorders // A line counts as output |
| 219 |
return |
| 220 |
} |
| 221 |
|
| 222 |
if o.config.Borders.Left.Enabled() { |
| 223 |
line.WriteString(jr.RenderLeft()) |
| 224 |
} |
| 225 |
|
| 226 |
for i, colIdx := range sortedColIndices { |
| 227 |
jr.colIdx = colIdx |
| 228 |
segmentChar := jr.GetSegment() |
| 229 |
colVisualWidth := o.fixedWidths.Get(colIdx) |
| 230 |
|
| 231 |
if colVisualWidth <= 0 { |
| 232 |
// Still need to consider separators after zero-width columns |
| 233 |
} else { |
| 234 |
if segmentChar == tw.Empty { |
| 235 |
segmentChar = o.config.Symbols.Row() |
| 236 |
} |
| 237 |
segmentDisplayWidth := twwidth.Width(segmentChar) |
| 238 |
if segmentDisplayWidth <= 0 { |
| 239 |
segmentDisplayWidth = 1 |
| 240 |
} |
| 241 |
|
| 242 |
repeatCount := 0 |
| 243 |
if colVisualWidth > 0 { |
| 244 |
repeatCount = colVisualWidth / segmentDisplayWidth |
| 245 |
if repeatCount == 0 { |
| 246 |
repeatCount = 1 |
| 247 |
} |
| 248 |
} |
| 249 |
line.WriteString(strings.Repeat(segmentChar, repeatCount)) |
| 250 |
} |
| 251 |
|
| 252 |
if i < len(sortedColIndices)-1 && o.config.Settings.Separators.BetweenColumns.Enabled() { |
| 253 |
nextColIdx := sortedColIndices[i+1] |
| 254 |
line.WriteString(jr.RenderJunction(colIdx, nextColIdx)) |
| 255 |
} |
| 256 |
} |
| 257 |
|
| 258 |
if o.config.Borders.Right.Enabled() { |
| 259 |
lastColIdx := sortedColIndices[len(sortedColIndices)-1] |
| 260 |
line.WriteString(jr.RenderRight(lastColIdx)) |
| 261 |
} |
| 262 |
|
| 263 |
line.WriteString(tw.NewLine) |
| 264 |
o.w.Write([]byte(line.String())) |
| 265 |
o.tableOutputStarted = true |
| 266 |
o.logger.Debugf("Line rendered by explicit call: %s", strings.TrimSuffix(line.String(), tw.NewLine)) |
| 267 |
} |
| 268 |
|
| 269 |
func (o *Ocean) Close() error { |
| 270 |
o.logger.Debug("Ocean.Close() called.") |
| 271 |
o.resetState() |
| 272 |
return nil |
| 273 |
} |
| 274 |
|
| 275 |
func (o *Ocean) renderContentLine(ctx tw.Formatting, lineData []string) { |
| 276 |
if !o.widthsFinalized || o.fixedWidths.Len() == 0 { |
| 277 |
o.logger.Error("renderContentLine: Cannot render, fixedWidths not set or empty.") |
| 278 |
return |
| 279 |
} |
| 280 |
|
| 281 |
var output strings.Builder |
| 282 |
if o.config.Borders.Left.Enabled() { |
| 283 |
output.WriteString(o.config.Symbols.Column()) |
| 284 |
} |
| 285 |
|
| 286 |
sortedColIndices := o.fixedWidths.SortedKeys() |
| 287 |
|
| 288 |
for i, colIdx := range sortedColIndices { |
| 289 |
cellVisualWidth := o.fixedWidths.Get(colIdx) |
| 290 |
cellContent := tw.Empty |
| 291 |
align := tw.AlignDefault |
| 292 |
padding := tw.Padding{Left: tw.Space, Right: tw.Space} |
| 293 |
|
| 294 |
switch ctx.Row.Position { |
| 295 |
case tw.Header: |
| 296 |
align = tw.AlignCenter |
| 297 |
case tw.Footer: |
| 298 |
align = tw.AlignRight |
| 299 |
default: |
| 300 |
align = tw.AlignLeft |
| 301 |
} |
| 302 |
|
| 303 |
cellCtx, hasCellCtx := ctx.Row.Current[colIdx] |
| 304 |
if hasCellCtx { |
| 305 |
cellContent = cellCtx.Data |
| 306 |
if cellCtx.Align.Validate() == nil && cellCtx.Align != tw.AlignNone { |
| 307 |
align = cellCtx.Align |
| 308 |
} |
| 309 |
if cellCtx.Padding.Paddable() { |
| 310 |
padding = cellCtx.Padding |
| 311 |
} |
| 312 |
} else if colIdx < len(lineData) { |
| 313 |
cellContent = lineData[colIdx] |
| 314 |
} |
| 315 |
|
| 316 |
actualCellWidthToRender := cellVisualWidth |
| 317 |
isHMergeContinuation := false |
| 318 |
|
| 319 |
if hasCellCtx && cellCtx.Merge.Horizontal.Present { |
| 320 |
if cellCtx.Merge.Horizontal.Start { |
| 321 |
hSpan := cellCtx.Merge.Horizontal.Span |
| 322 |
if hSpan <= 0 { |
| 323 |
hSpan = 1 |
| 324 |
} |
| 325 |
|
| 326 |
currentMergeTotalRenderWidth := 0 |
| 327 |
for k := 0; k < hSpan; k++ { |
| 328 |
idxInMergeSpan := colIdx + k |
| 329 |
// Check if idxInMergeSpan is a defined column in fixedWidths |
| 330 |
foundInFixedWidths := false |
| 331 |
if slices.Contains(sortedColIndices, idxInMergeSpan) { |
| 332 |
currentMergeTotalRenderWidth += o.fixedWidths.Get(idxInMergeSpan) |
| 333 |
foundInFixedWidths = true |
| 334 |
} |
| 335 |
if !foundInFixedWidths && idxInMergeSpan <= sortedColIndices[len(sortedColIndices)-1] { |
| 336 |
o.logger.Debugf("Col %d in HMerge span not found in fixedWidths, assuming 0-width contribution.", idxInMergeSpan) |
| 337 |
} |
| 338 |
|
| 339 |
if k < hSpan-1 && o.config.Settings.Separators.BetweenColumns.Enabled() { |
| 340 |
currentMergeTotalRenderWidth += twwidth.Width(o.config.Symbols.Column()) |
| 341 |
} |
| 342 |
} |
| 343 |
actualCellWidthToRender = currentMergeTotalRenderWidth |
| 344 |
} else { |
| 345 |
isHMergeContinuation = true |
| 346 |
} |
| 347 |
} |
| 348 |
|
| 349 |
if isHMergeContinuation { |
| 350 |
o.logger.Debugf("renderContentLine: Col %d is HMerge continuation, skipping content render.", colIdx) |
| 351 |
// The separator logic below needs to handle this correctly. |
| 352 |
// If the *previous* column was the start of a merge that spans *this* column, |
| 353 |
// then the separator after the previous column should have been suppressed. |
| 354 |
} else if actualCellWidthToRender > 0 { |
| 355 |
formattedCell := o.formatCellContent(cellContent, actualCellWidthToRender, padding, align) |
| 356 |
output.WriteString(formattedCell) |
| 357 |
} else { |
| 358 |
o.logger.Debugf("renderContentLine: col %d has 0 render width, writing no content.", colIdx) |
| 359 |
} |
| 360 |
|
| 361 |
// Add column separator if: |
| 362 |
// 1. It's not the last column in sortedColIndices |
| 363 |
// 2. Separators are enabled |
| 364 |
// 3. This cell is NOT a horizontal merge start that spans over the next column. |
| 365 |
if i < len(sortedColIndices)-1 && o.config.Settings.Separators.BetweenColumns.Enabled() { |
| 366 |
shouldAddSeparator := true |
| 367 |
if hasCellCtx && cellCtx.Merge.Horizontal.Present && cellCtx.Merge.Horizontal.Start { |
| 368 |
// If this merge start spans beyond the current colIdx into the next sortedColIndex |
| 369 |
if colIdx+cellCtx.Merge.Horizontal.Span > sortedColIndices[i+1] { |
| 370 |
shouldAddSeparator = false // Separator is part of the merged cell's width |
| 371 |
o.logger.Debugf("renderContentLine: Suppressed separator after HMerge col %d.", colIdx) |
| 372 |
} |
| 373 |
} |
| 374 |
if shouldAddSeparator { |
| 375 |
output.WriteString(o.config.Symbols.Column()) |
| 376 |
} |
| 377 |
} |
| 378 |
} |
| 379 |
|
| 380 |
if o.config.Borders.Right.Enabled() { |
| 381 |
output.WriteString(o.config.Symbols.Column()) |
| 382 |
} |
| 383 |
|
| 384 |
output.WriteString(tw.NewLine) |
| 385 |
o.w.Write([]byte(output.String())) |
| 386 |
o.logger.Debugf("Content line rendered: %s", strings.TrimSuffix(output.String(), tw.NewLine)) |
| 387 |
} |
| 388 |
|
| 389 |
func (o *Ocean) formatCellContent(content string, cellVisualWidth int, padding tw.Padding, align tw.Align) string { |
| 390 |
if cellVisualWidth <= 0 { |
| 391 |
return tw.Empty |
| 392 |
} |
| 393 |
|
| 394 |
contentDisplayWidth := twwidth.Width(content) |
| 395 |
|
| 396 |
padLeftChar := padding.Left |
| 397 |
if padLeftChar == tw.Empty { |
| 398 |
padLeftChar = tw.Space |
| 399 |
} |
| 400 |
padRightChar := padding.Right |
| 401 |
if padRightChar == tw.Empty { |
| 402 |
padRightChar = tw.Space |
| 403 |
} |
| 404 |
|
| 405 |
padLeftDisplayWidth := twwidth.Width(padLeftChar) |
| 406 |
padRightDisplayWidth := twwidth.Width(padRightChar) |
| 407 |
|
| 408 |
spaceForContentAndAlignment := max(cellVisualWidth-padLeftDisplayWidth-padRightDisplayWidth, 0) |
| 409 |
|
| 410 |
if contentDisplayWidth > spaceForContentAndAlignment { |
| 411 |
content = twwidth.Truncate(content, spaceForContentAndAlignment) |
| 412 |
contentDisplayWidth = twwidth.Width(content) |
| 413 |
} |
| 414 |
|
| 415 |
remainingSpace := max(spaceForContentAndAlignment-contentDisplayWidth, 0) |
| 416 |
|
| 417 |
var PL, PR string |
| 418 |
switch align { |
| 419 |
case tw.AlignRight: |
| 420 |
PL = strings.Repeat(tw.Space, remainingSpace) |
| 421 |
case tw.AlignCenter: |
| 422 |
leftSpaces := remainingSpace / 2 |
| 423 |
rightSpaces := remainingSpace - leftSpaces |
| 424 |
PL = strings.Repeat(tw.Space, leftSpaces) |
| 425 |
PR = strings.Repeat(tw.Space, rightSpaces) |
| 426 |
default: |
| 427 |
PR = strings.Repeat(tw.Space, remainingSpace) |
| 428 |
} |
| 429 |
|
| 430 |
var sb strings.Builder |
| 431 |
sb.WriteString(padLeftChar) |
| 432 |
sb.WriteString(PL) |
| 433 |
sb.WriteString(content) |
| 434 |
sb.WriteString(PR) |
| 435 |
sb.WriteString(padRightChar) |
| 436 |
|
| 437 |
currentFormattedWidth := twwidth.Width(sb.String()) |
| 438 |
if currentFormattedWidth < cellVisualWidth { |
| 439 |
if align == tw.AlignRight { |
| 440 |
prefixSpaces := strings.Repeat(tw.Space, cellVisualWidth-currentFormattedWidth) |
| 441 |
finalStr := prefixSpaces + sb.String() |
| 442 |
sb.Reset() |
| 443 |
sb.WriteString(finalStr) |
| 444 |
} else { |
| 445 |
sb.WriteString(strings.Repeat(tw.Space, cellVisualWidth-currentFormattedWidth)) |
| 446 |
} |
| 447 |
} else if currentFormattedWidth > cellVisualWidth { |
| 448 |
tempStr := sb.String() |
| 449 |
sb.Reset() |
| 450 |
sb.WriteString(twwidth.Truncate(tempStr, cellVisualWidth)) |
| 451 |
o.logger.Warnf("formatCellContent: Final string '%s' (width %d) exceeded target %d. Force truncated.", tempStr, currentFormattedWidth, cellVisualWidth) |
| 452 |
} |
| 453 |
return sb.String() |
| 454 |
} |
| 455 |
|
| 456 |
func (o *Ocean) Rendition(config tw.Rendition) { |
| 457 |
o.config = mergeRendition(o.config, config) |
| 458 |
o.logger.Debugf("Blueprint.Rendition updated. New internal config: %+v", o.config) |
| 459 |
} |
| 460 |
|
| 461 |
// Ensure Blueprint implements tw.Renditioning |
| 462 |
var _ tw.Renditioning = (*Ocean)(nil) |