Debian Codegraph @

renderer/svg.go

raw
1 package renderer
2
3 import (
4 "fmt"
5 "html"
6 "io"
7 "strings"
8
9 "github.com/olekukonko/ll"
10
11 "github.com/olekukonko/tablewriter/pkg/twwidth"
12 "github.com/olekukonko/tablewriter/tw"
13 )
14
15 // SVGConfig holds configuration for the SVG renderer.
16 // Fields include font, colors, padding, and merge rendering options.
17 // Used to customize SVG output appearance and behavior.
18 type SVGConfig struct {
19 FontFamily string // e.g., "Arial, sans-serif"
20 FontSize float64 // Base font size in SVG units
21 LineHeightFactor float64 // Factor for line height (e.g., 1.2)
22 Padding float64 // Padding inside cells
23 StrokeWidth float64 // Line width for borders
24 StrokeColor string // Color for strokes (e.g., "black")
25 HeaderBG string // Background color for header
26 RowBG string // Background color for rows
27 RowAltBG string // Alternating row background color
28 FooterBG string // Background color for footer
29 HeaderColor string // Text color for header
30 RowColor string // Text color for rows
31 FooterColor string // Text color for footer
32 ApproxCharWidthFactor float64 // Char width relative to FontSize
33 MinColWidth float64 // Minimum column width
34 RenderTWConfigOverrides bool // Override SVG alignments with tablewriter
35 Debug bool // Enable debug logging
36 ScaleFactor float64 // Scaling factor for SVG
37 }
38
39 // SVG implements tw.Renderer for SVG output.
40 // Manages SVG element generation and merge tracking.
41 type SVG struct {
42 config SVGConfig
43 trace []string
44
45 allVisualLineData [][][]string // [section][line][cell]
46 allVisualLineCtx [][]tw.Formatting // [section][line]Formatting
47
48 maxCols int
49 calculatedColWidths []float64
50 svgElements strings.Builder
51 currentY float64
52 dataRowCounter int
53 vMergeTrack map[int]int // Tracks vertical merge spans
54 numVisualRowsDrawn int
55 logger *ll.Logger
56 w io.Writer
57 }
58
59 const (
60 sectionTypeHeader = 0
61 sectionTypeRow = 1
62 sectionTypeFooter = 2
63 )
64
65 // NewSVG creates a new SVG renderer with configuration.
66 // Parameter configs provides optional SVGConfig; defaults used if empty.
67 // Returns a configured SVG instance.
68 func NewSVG(configs ...SVGConfig) *SVG {
69 cfg := SVGConfig{
70 FontFamily: "sans-serif",
71 FontSize: 12.0,
72 LineHeightFactor: 1.4,
73 Padding: 5.0,
74 StrokeWidth: 1.0,
75 StrokeColor: "black",
76 HeaderBG: "#F0F0F0",
77 RowBG: "white",
78 RowAltBG: "#F9F9F9",
79 FooterBG: "#F0F0F0",
80 HeaderColor: "black",
81 RowColor: "black",
82 FooterColor: "black",
83 ApproxCharWidthFactor: 0.6,
84 MinColWidth: 30.0,
85 ScaleFactor: 1.0,
86 RenderTWConfigOverrides: true,
87 Debug: false,
88 }
89 if len(configs) > 0 {
90 userCfg := configs[0]
91 if userCfg.FontFamily != tw.Empty {
92 cfg.FontFamily = userCfg.FontFamily
93 }
94 if userCfg.FontSize > 0 {
95 cfg.FontSize = userCfg.FontSize
96 }
97 if userCfg.LineHeightFactor > 0 {
98 cfg.LineHeightFactor = userCfg.LineHeightFactor
99 }
100 if userCfg.Padding >= 0 {
101 cfg.Padding = userCfg.Padding
102 }
103 if userCfg.StrokeWidth > 0 {
104 cfg.StrokeWidth = userCfg.StrokeWidth
105 }
106 if userCfg.StrokeColor != tw.Empty {
107 cfg.StrokeColor = userCfg.StrokeColor
108 }
109 if userCfg.HeaderBG != tw.Empty {
110 cfg.HeaderBG = userCfg.HeaderBG
111 }
112 if userCfg.RowBG != tw.Empty {
113 cfg.RowBG = userCfg.RowBG
114 }
115 cfg.RowAltBG = userCfg.RowAltBG
116 if userCfg.FooterBG != tw.Empty {
117 cfg.FooterBG = userCfg.FooterBG
118 }
119 if userCfg.HeaderColor != tw.Empty {
120 cfg.HeaderColor = userCfg.HeaderColor
121 }
122 if userCfg.RowColor != tw.Empty {
123 cfg.RowColor = userCfg.RowColor
124 }
125 if userCfg.FooterColor != tw.Empty {
126 cfg.FooterColor = userCfg.FooterColor
127 }
128 if userCfg.ApproxCharWidthFactor > 0 {
129 cfg.ApproxCharWidthFactor = userCfg.ApproxCharWidthFactor
130 }
131 if userCfg.MinColWidth >= 0 {
132 cfg.MinColWidth = userCfg.MinColWidth
133 }
134 cfg.RenderTWConfigOverrides = userCfg.RenderTWConfigOverrides
135 cfg.Debug = userCfg.Debug
136 }
137 r := &SVG{
138 config: cfg,
139 trace: make([]string, 0, 50),
140 allVisualLineData: make([][][]string, 3),
141 allVisualLineCtx: make([][]tw.Formatting, 3),
142 vMergeTrack: make(map[int]int),
143 logger: ll.New("svg").Disable(),
144 }
145 for i := 0; i < 3; i++ {
146 r.allVisualLineData[i] = make([][]string, 0)
147 r.allVisualLineCtx[i] = make([]tw.Formatting, 0)
148 }
149 return r
150 }
151
152 // calculateAllColumnWidths computes column widths based on content and merges.
153 // Uses content length and merge spans; handles horizontal merges by distributing width.
154 func (s *SVG) calculateAllColumnWidths() {
155 s.debug("Calculating column widths")
156 tempMaxCols := 0
157 for sectionIdx := 0; sectionIdx < 3; sectionIdx++ {
158 for lineIdx, lineCtx := range s.allVisualLineCtx[sectionIdx] {
159 if lineCtx.Row.Current != nil {
160 visualColCount := 0
161 for colIdx := 0; colIdx < len(lineCtx.Row.Current); {
162 cellCtx := lineCtx.Row.Current[colIdx]
163 if cellCtx.Merge.Horizontal.Present && !cellCtx.Merge.Horizontal.Start {
164 colIdx++ // Skip non-start merged cells
165 continue
166 }
167 visualColCount++
168 span := 1
169 if cellCtx.Merge.Horizontal.Present && cellCtx.Merge.Horizontal.Start {
170 span = cellCtx.Merge.Horizontal.Span
171 if span <= 0 {
172 span = 1
173 }
174 }
175 colIdx += span
176 }
177 s.debug("Section %d, line %d: Visual columns = %d", sectionIdx, lineIdx, visualColCount)
178 if visualColCount > tempMaxCols {
179 tempMaxCols = visualColCount
180 }
181 } else if lineIdx < len(s.allVisualLineData[sectionIdx]) {
182 if rawDataLen := len(s.allVisualLineData[sectionIdx][lineIdx]); rawDataLen > tempMaxCols {
183 tempMaxCols = rawDataLen
184 }
185 }
186 }
187 }
188 s.maxCols = tempMaxCols
189 s.debug("Max columns: %d", s.maxCols)
190 if s.maxCols == 0 {
191 s.calculatedColWidths = []float64{}
192 return
193 }
194 s.calculatedColWidths = make([]float64, s.maxCols)
195 for i := range s.calculatedColWidths {
196 s.calculatedColWidths[i] = s.config.MinColWidth
197 }
198
199 // Structure to track max width for each merge group
200 type mergeKey struct {
201 startCol int
202 span int
203 }
204 maxMergeWidths := make(map[mergeKey]float64)
205
206 processSectionForWidth := func(sectionIdx int) {
207 for lineIdx, visualLineData := range s.allVisualLineData[sectionIdx] {
208 if lineIdx >= len(s.allVisualLineCtx[sectionIdx]) {
209 s.debug("Warning: Missing context for section %d line %d", sectionIdx, lineIdx)
210 continue
211 }
212 lineCtx := s.allVisualLineCtx[sectionIdx][lineIdx]
213 currentTableCol := 0
214 currentVisualCol := 0
215 for currentVisualCol < len(visualLineData) && currentTableCol < s.maxCols {
216 cellContent := visualLineData[currentVisualCol]
217 cellCtx := tw.CellContext{}
218 if lineCtx.Row.Current != nil {
219 if c, ok := lineCtx.Row.Current[currentTableCol]; ok {
220 cellCtx = c
221 }
222 }
223 hSpan := 1
224 if cellCtx.Merge.Horizontal.Present {
225 if cellCtx.Merge.Horizontal.Start {
226 hSpan = cellCtx.Merge.Horizontal.Span
227 if hSpan <= 0 {
228 hSpan = 1
229 }
230 } else {
231 currentTableCol++
232 continue
233 }
234 }
235 textPixelWidth := s.estimateTextWidth(cellContent)
236 contentAndPaddingWidth := textPixelWidth + (2 * s.config.Padding)
237 if hSpan == 1 {
238 if currentTableCol < len(s.calculatedColWidths) && contentAndPaddingWidth > s.calculatedColWidths[currentTableCol] {
239 s.calculatedColWidths[currentTableCol] = contentAndPaddingWidth
240 }
241 } else {
242 totalMergedWidth := contentAndPaddingWidth + (float64(hSpan-1) * s.config.Padding * 2)
243 if totalMergedWidth < s.config.MinColWidth*float64(hSpan) {
244 totalMergedWidth = s.config.MinColWidth * float64(hSpan)
245 }
246 if currentTableCol < len(s.calculatedColWidths) {
247 key := mergeKey{currentTableCol, hSpan}
248 if currentWidth, ok := maxMergeWidths[key]; ok {
249 if totalMergedWidth > currentWidth {
250 maxMergeWidths[key] = totalMergedWidth
251 }
252 } else {
253 maxMergeWidths[key] = totalMergedWidth
254 }
255 s.debug("Horizontal merge at col %d, span %d: Total width %.2f", currentTableCol, hSpan, totalMergedWidth)
256 }
257 }
258 currentTableCol += hSpan
259 currentVisualCol++
260 }
261 }
262 }
263 processSectionForWidth(sectionTypeHeader)
264 processSectionForWidth(sectionTypeRow)
265 processSectionForWidth(sectionTypeFooter)
266
267 // Apply maximum widths for merged cells
268 for key, width := range maxMergeWidths {
269 s.calculatedColWidths[key.startCol] = width
270 for i := 1; i < key.span && (key.startCol+i) < len(s.calculatedColWidths); i++ {
271 s.calculatedColWidths[key.startCol+i] = 0
272 }
273 }
274
275 for i := range s.calculatedColWidths {
276 if s.calculatedColWidths[i] < s.config.MinColWidth && s.calculatedColWidths[i] != 0 {
277 s.calculatedColWidths[i] = s.config.MinColWidth
278 }
279 }
280 s.debug("Column widths: %v", s.calculatedColWidths)
281 }
282
283 // Close finalizes SVG rendering and writes output.
284 // Parameter w is the output w.
285 // Returns an error if writing fails.
286 func (s *SVG) Close() error {
287 s.debug("Finalizing SVG output")
288 s.calculateAllColumnWidths()
289 s.renderBufferedData()
290 if s.numVisualRowsDrawn == 0 && s.maxCols == 0 {
291 fmt.Fprintf(s.w, `<svg xmlns="http://www.w3.org/2000/svg" width="%.2f" height="%.2f"></svg>`, s.config.StrokeWidth*2, s.config.StrokeWidth*2)
292 return nil
293 }
294 totalWidth := s.config.StrokeWidth
295 if len(s.calculatedColWidths) > 0 {
296 for _, cw := range s.calculatedColWidths {
297 colWidth := cw
298 if colWidth <= 0 {
299 colWidth = s.config.MinColWidth
300 }
301 totalWidth += colWidth + s.config.StrokeWidth
302 }
303 } else if s.maxCols > 0 {
304 for i := 0; i < s.maxCols; i++ {
305 totalWidth += s.config.MinColWidth + s.config.StrokeWidth
306 }
307 } else {
308 totalWidth = s.config.StrokeWidth * 2
309 }
310 totalHeight := s.currentY
311 singleVisualRowHeight := s.config.FontSize*s.config.LineHeightFactor + (2 * s.config.Padding)
312 if s.numVisualRowsDrawn == 0 {
313 if s.maxCols > 0 {
314 totalHeight = s.config.StrokeWidth + singleVisualRowHeight + s.config.StrokeWidth
315 } else {
316 totalHeight = s.config.StrokeWidth * 2
317 }
318 }
319 fmt.Fprintf(s.w, `<svg xmlns="http://www.w3.org/2000/svg" width="%.2f" height="%.2f" font-family="%s" font-size="%.2f">`,
320 totalWidth, totalHeight, html.EscapeString(s.config.FontFamily), s.config.FontSize)
321 fmt.Fprintln(s.w)
322 fmt.Fprintln(s.w, "<style>text { stroke: none; }</style>")
323 if _, err := io.WriteString(s.w, s.svgElements.String()); err != nil {
324 fmt.Fprintln(s.w, `</svg>`)
325 return fmt.Errorf("failed to write SVG elements: %w", err)
326 }
327 if s.maxCols > 0 || s.numVisualRowsDrawn > 0 {
328 fmt.Fprintf(s.w, ` <g class="table-borders" stroke="%s" stroke-width="%.2f" stroke-linecap="square">`,
329 html.EscapeString(s.config.StrokeColor), s.config.StrokeWidth)
330 fmt.Fprintln(s.w)
331 yPos := s.config.StrokeWidth / 2.0
332 borderRowsToDraw := s.numVisualRowsDrawn
333 if borderRowsToDraw == 0 && s.maxCols > 0 {
334 borderRowsToDraw = 1
335 }
336 lineStartX := s.config.StrokeWidth / 2.0
337 lineEndX := s.config.StrokeWidth / 2.0
338 for _, width := range s.calculatedColWidths {
339 lineEndX += width + s.config.StrokeWidth
340 }
341 for i := 0; i <= borderRowsToDraw; i++ {
342 fmt.Fprintf(s.w, ` <line x1="%.2f" y1="%.2f" x2="%.2f" y2="%.2f" />%s`,
343 lineStartX, yPos, lineEndX, yPos, "\n")
344 if i < borderRowsToDraw {
345 yPos += singleVisualRowHeight + s.config.StrokeWidth
346 }
347 }
348 xPos := s.config.StrokeWidth / 2.0
349 borderLineStartY := s.config.StrokeWidth / 2.0
350 borderLineEndY := totalHeight - (s.config.StrokeWidth / 2.0)
351 for visualColIdx := 0; visualColIdx <= s.maxCols; visualColIdx++ {
352 fmt.Fprintf(s.w, ` <line x1="%.2f" y1="%.2f" x2="%.2f" y2="%.2f" />%s`,
353 xPos, borderLineStartY, xPos, borderLineEndY, "\n")
354 if visualColIdx < s.maxCols {
355 colWidth := s.config.MinColWidth
356 if visualColIdx < len(s.calculatedColWidths) && s.calculatedColWidths[visualColIdx] > 0 {
357 colWidth = s.calculatedColWidths[visualColIdx]
358 }
359 xPos += colWidth + s.config.StrokeWidth
360 }
361 }
362 fmt.Fprintln(s.w, " </g>")
363 }
364 fmt.Fprintln(s.w, `</svg>`)
365 return nil
366 }
367
368 // Config returns the renderer's configuration.
369 // No parameters are required.
370 // Returns a Rendition with border and debug settings.
371 func (s *SVG) Config() tw.Rendition {
372 return tw.Rendition{
373 Borders: tw.Border{Left: tw.On, Right: tw.On, Top: tw.On, Bottom: tw.On},
374 Settings: tw.Settings{},
375 Streaming: false,
376 }
377 }
378
379 // Debug returns the renderer's debug trace.
380 // No parameters are required.
381 // Returns a slice of debug messages.
382 func (s *SVG) Debug() []string {
383 return s.trace
384 }
385
386 // estimateTextWidth estimates text width in SVG units.
387 // Parameter text is the input string to measure.
388 // Returns the estimated width based on the text's display width, font size,
389 // and char factor. Display width is used (instead of the rune count) so that
390 // wide runes such as CJK characters, which occupy two cells, are sized as two
391 // columns rather than one.
392 func (s *SVG) estimateTextWidth(text string) float64 {
393 displayWidth := float64(twwidth.Width(text))
394 return displayWidth * s.config.FontSize * s.config.ApproxCharWidthFactor
395 }
396
397 // Footer buffers footer lines for SVG rendering.
398 // Parameters include w (w), footers (lines), and ctx (formatting).
399 // No return value; stores data for later rendering.
400 func (s *SVG) Footer(footers [][]string, ctx tw.Formatting) {
401 s.debug("Buffering %d footer lines", len(footers))
402 for i, line := range footers {
403 currentCtx := ctx
404 currentCtx.IsSubRow = (i > 0)
405 s.storeVisualLine(sectionTypeFooter, line, currentCtx)
406 }
407 }
408
409 // getSVGAnchorFromTW maps tablewriter alignment to SVG text-anchor.
410 // Parameter align is the tablewriter alignment setting.
411 // Returns the corresponding SVG text-anchor value or empty string.
412 func (s *SVG) getSVGAnchorFromTW(align tw.Align) string {
413 switch align {
414 case tw.AlignLeft:
415 return "start"
416 case tw.AlignCenter:
417 return "middle"
418 case tw.AlignRight:
419 return "end"
420 case tw.AlignNone, tw.Skip:
421 return tw.Empty
422 }
423 return tw.Empty
424 }
425
426 // Header buffers header lines for SVG rendering.
427 // Parameters include w (w), headers (lines), and ctx (formatting).
428 // No return value; stores data for later rendering.
429 func (s *SVG) Header(headers [][]string, ctx tw.Formatting) {
430 s.debug("Buffering %d header lines", len(headers))
431 for i, line := range headers {
432 currentCtx := ctx
433 currentCtx.IsSubRow = i > 0
434 s.storeVisualLine(sectionTypeHeader, line, currentCtx)
435 }
436 }
437
438 // Line handles border rendering (ignored in SVG renderer).
439 // Parameters include w (w) and ctx (formatting).
440 // No return value; SVG borders are drawn in Close.
441 func (s *SVG) Line(ctx tw.Formatting) {
442 s.debug("Line rendering ignored")
443 }
444
445 // padLineSVG pads a line to the specified column count.
446 // Parameters include line (input strings) and numCols (target length).
447 // Returns the padded line with empty strings as needed.
448 func padLineSVG(line []string, numCols int) []string {
449 if numCols <= 0 {
450 return []string{}
451 }
452 currentLen := len(line)
453 if currentLen == numCols {
454 return line
455 }
456 if currentLen > numCols {
457 return line[:numCols]
458 }
459 padded := make([]string, numCols)
460 copy(padded, line)
461 return padded
462 }
463
464 // renderBufferedData renders all buffered lines to SVG elements.
465 // No parameters are required.
466 // No return value; populates svgElements buffer.
467 func (s *SVG) renderBufferedData() {
468 s.debug("Rendering buffered data")
469 s.currentY = s.config.StrokeWidth
470 s.dataRowCounter = 0
471 s.vMergeTrack = make(map[int]int)
472 s.numVisualRowsDrawn = 0
473 renderSection := func(sectionIdx int, position tw.Position) {
474 for visualLineIdx, visualLineData := range s.allVisualLineData[sectionIdx] {
475 if visualLineIdx >= len(s.allVisualLineCtx[sectionIdx]) {
476 s.debug("Error: Missing context for section %d line %d", sectionIdx, visualLineIdx)
477 continue
478 }
479 s.renderVisualLine(visualLineData, s.allVisualLineCtx[sectionIdx][visualLineIdx], position)
480 }
481 }
482 renderSection(sectionTypeHeader, tw.Header)
483 renderSection(sectionTypeRow, tw.Row)
484 renderSection(sectionTypeFooter, tw.Footer)
485 }
486
487 // renderVisualLine renders a single visual line as SVG elements.
488 // Parameters include lineData (cell content), ctx (formatting), and position (section type).
489 // No return value; handles horizontal and vertical merges.
490 func (s *SVG) renderVisualLine(visualLineData []string, ctx tw.Formatting, position tw.Position) {
491 if s.maxCols == 0 || len(s.calculatedColWidths) == 0 {
492 s.debug("Skipping line rendering: maxCols=%d, widths=%d", s.maxCols, len(s.calculatedColWidths))
493 return
494 }
495 s.numVisualRowsDrawn++
496 s.debug("Rendering visual row %d", s.numVisualRowsDrawn)
497 singleVisualRowHeight := s.config.FontSize*s.config.LineHeightFactor + (2 * s.config.Padding)
498 bgColor := tw.Empty
499 textColor := tw.Empty
500 defaultTextAnchor := "start"
501 switch position {
502 case tw.Header:
503 bgColor = s.config.HeaderBG
504 textColor = s.config.HeaderColor
505 defaultTextAnchor = "middle"
506 case tw.Footer:
507 bgColor = s.config.FooterBG
508 textColor = s.config.FooterColor
509 defaultTextAnchor = "end"
510 default:
511 textColor = s.config.RowColor
512 if !ctx.IsSubRow {
513 if s.config.RowAltBG != tw.Empty && s.dataRowCounter%2 != 0 {
514 bgColor = s.config.RowAltBG
515 } else {
516 bgColor = s.config.RowBG
517 }
518 s.dataRowCounter++
519 } else {
520 parentDataRowStripeIndex := max(s.dataRowCounter-1, 0)
521 if s.config.RowAltBG != tw.Empty && parentDataRowStripeIndex%2 != 0 {
522 bgColor = s.config.RowAltBG
523 } else {
524 bgColor = s.config.RowBG
525 }
526 }
527 }
528 currentX := s.config.StrokeWidth
529 currentVisualCellIdx := 0
530 for tableColIdx := 0; tableColIdx < s.maxCols; {
531 if tableColIdx >= len(s.calculatedColWidths) {
532 s.debug("Table Col %d out of bounds for widths", tableColIdx)
533 tableColIdx++
534 continue
535 }
536 if remainingVSpan, isMerging := s.vMergeTrack[tableColIdx]; isMerging && remainingVSpan > 1 {
537 s.vMergeTrack[tableColIdx]--
538 if s.vMergeTrack[tableColIdx] <= 1 {
539 delete(s.vMergeTrack, tableColIdx)
540 }
541 currentX += s.calculatedColWidths[tableColIdx] + s.config.StrokeWidth
542 tableColIdx++
543 continue
544 }
545 cellContentFromVisualLine := tw.Empty
546 if currentVisualCellIdx < len(visualLineData) {
547 cellContentFromVisualLine = visualLineData[currentVisualCellIdx]
548 }
549 cellCtx := tw.CellContext{}
550 if ctx.Row.Current != nil {
551 if c, ok := ctx.Row.Current[tableColIdx]; ok {
552 cellCtx = c
553 }
554 }
555 textToRender := cellContentFromVisualLine
556 if cellCtx.Data != tw.Empty {
557 if !((cellCtx.Merge.Vertical.Present && !cellCtx.Merge.Vertical.Start) || (cellCtx.Merge.Hierarchical.Present && !cellCtx.Merge.Hierarchical.Start)) {
558 textToRender = cellCtx.Data
559 } else {
560 textToRender = tw.Empty
561 }
562 } else if (cellCtx.Merge.Vertical.Present && !cellCtx.Merge.Vertical.Start) || (cellCtx.Merge.Hierarchical.Present && !cellCtx.Merge.Hierarchical.Start) {
563 textToRender = tw.Empty
564 }
565 hSpan := 1
566 if cellCtx.Merge.Horizontal.Present {
567 if cellCtx.Merge.Horizontal.Start {
568 hSpan = cellCtx.Merge.Horizontal.Span
569 if hSpan <= 0 {
570 hSpan = 1
571 }
572 } else {
573 currentX += s.calculatedColWidths[tableColIdx] + s.config.StrokeWidth
574 tableColIdx++
575 continue
576 }
577 }
578 vSpan := 1
579 isVSpanStart := false
580 if cellCtx.Merge.Vertical.Present && cellCtx.Merge.Vertical.Start {
581 vSpan = cellCtx.Merge.Vertical.Span
582 isVSpanStart = true
583 } else if cellCtx.Merge.Hierarchical.Present && cellCtx.Merge.Hierarchical.Start {
584 vSpan = cellCtx.Merge.Hierarchical.Span
585 isVSpanStart = true
586 }
587 if vSpan <= 0 {
588 vSpan = 1
589 }
590 rectWidth := 0.0
591 for hs := 0; hs < hSpan && (tableColIdx+hs) < s.maxCols; hs++ {
592 if (tableColIdx + hs) < len(s.calculatedColWidths) {
593 rectWidth += s.calculatedColWidths[tableColIdx+hs]
594 } else {
595 rectWidth += s.config.MinColWidth
596 }
597 }
598 if hSpan > 1 {
599 rectWidth += float64(hSpan-1) * s.config.StrokeWidth
600 }
601 if rectWidth <= 0 {
602 tableColIdx += hSpan
603 if hSpan > 0 {
604 currentVisualCellIdx++
605 }
606 continue
607 }
608 rectHeight := singleVisualRowHeight
609 if isVSpanStart && vSpan > 1 {
610 rectHeight = float64(vSpan)*singleVisualRowHeight + float64(vSpan-1)*s.config.StrokeWidth
611 for hs := 0; hs < hSpan && (tableColIdx+hs) < s.maxCols; hs++ {
612 s.vMergeTrack[tableColIdx+hs] = vSpan
613 }
614 s.debug("Vertical merge at col %d, span %d, height %.2f", tableColIdx, vSpan, rectHeight)
615 } else if remainingVSpan, isMerging := s.vMergeTrack[tableColIdx]; isMerging && remainingVSpan > 1 {
616 rectHeight = singleVisualRowHeight
617 textToRender = tw.Empty
618 }
619 fmt.Fprintf(&s.svgElements, ` <rect x="%.2f" y="%.2f" width="%.2f" height="%.2f" fill="%s"/>%s`,
620 currentX, s.currentY, rectWidth, rectHeight, html.EscapeString(bgColor), "\n")
621 cellTextAnchor := defaultTextAnchor
622 if s.config.RenderTWConfigOverrides {
623 if al := s.getSVGAnchorFromTW(cellCtx.Align); al != tw.Empty {
624 cellTextAnchor = al
625 }
626 }
627 textX := currentX + s.config.Padding
628 switch cellTextAnchor {
629 case "middle":
630 textX = currentX + s.config.Padding + (rectWidth-2*s.config.Padding)/2.0
631 case "end":
632 textX = currentX + rectWidth - s.config.Padding
633 }
634 textY := s.currentY + rectHeight/2.0
635 escapedCell := html.EscapeString(textToRender)
636 fmt.Fprintf(&s.svgElements, ` <text x="%.2f" y="%.2f" fill="%s" text-anchor="%s" dominant-baseline="middle">%s</text>%s`,
637 textX, textY, html.EscapeString(textColor), cellTextAnchor, escapedCell, "\n")
638 currentX += rectWidth + s.config.StrokeWidth
639 tableColIdx += hSpan
640 currentVisualCellIdx++
641 }
642 s.currentY += singleVisualRowHeight + s.config.StrokeWidth
643 }
644
645 // Reset clears the renderer's internal state.
646 // No parameters are required.
647 // No return value; prepares for new rendering.
648 func (s *SVG) Reset() {
649 s.debug("Resetting state")
650 s.trace = make([]string, 0, 50)
651 for i := 0; i < 3; i++ {
652 s.allVisualLineData[i] = s.allVisualLineData[i][:0]
653 s.allVisualLineCtx[i] = s.allVisualLineCtx[i][:0]
654 }
655 s.maxCols = 0
656 s.calculatedColWidths = nil
657 s.svgElements.Reset()
658 s.currentY = 0
659 s.dataRowCounter = 0
660 s.vMergeTrack = make(map[int]int)
661 s.numVisualRowsDrawn = 0
662 }
663
664 // Row buffers a row line for SVG rendering.
665 // Parameters include w (w), rowLine (cells), and ctx (formatting).
666 // No return value; stores data for later rendering.
667 func (s *SVG) Row(rowLine []string, ctx tw.Formatting) {
668 s.debug("Buffering row line, IsSubRow: %v", ctx.IsSubRow)
669 s.storeVisualLine(sectionTypeRow, rowLine, ctx)
670 }
671
672 func (s *SVG) Logger(logger *ll.Logger) {
673 s.logger = logger.Namespace("svg")
674 }
675
676 // Start initializes SVG rendering.
677 // Parameter w is the output w.
678 // Returns nil; prepares internal state.
679 func (s *SVG) Start(w io.Writer) error {
680 s.w = w
681 s.debug("Starting SVG rendering")
682 s.Reset()
683 return nil
684 }
685
686 // debug logs a message if debugging is enabled.
687 // Parameters include format string and variadic arguments.
688 // No return value; appends to trace.
689 func (s *SVG) debug(format string, a ...interface{}) {
690 if s.config.Debug {
691 msg := fmt.Sprintf(format, a...)
692 s.trace = append(s.trace, "[SVG] "+msg)
693 }
694 }
695
696 // storeVisualLine stores a visual line for rendering.
697 // Parameters include sectionIdx, lineData (cells), and ctx (formatting).
698 // No return value; buffers data and context.
699 func (s *SVG) storeVisualLine(sectionIdx int, lineData []string, ctx tw.Formatting) {
700 copiedLineData := make([]string, len(lineData))
701 copy(copiedLineData, lineData)
702 s.allVisualLineData[sectionIdx] = append(s.allVisualLineData[sectionIdx], copiedLineData)
703 s.allVisualLineCtx[sectionIdx] = append(s.allVisualLineCtx[sectionIdx], ctx)
704 hasCurrent := ctx.Row.Current != nil
705 s.debug("Stored line in section %d, has context: %v", sectionIdx, hasCurrent)
706 }