-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtypography.go
More file actions
1086 lines (934 loc) · 34.1 KB
/
typography.go
File metadata and controls
1086 lines (934 loc) · 34.1 KB
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package herald
import (
"fmt"
"strings"
"charm.land/lipgloss/v2"
)
// Typography is the central renderer. It holds a Theme and exposes methods
// for every supported typographic element.
type Typography struct {
theme Theme
}
// New creates a new Typography instance with the default theme, then applies
// any provided functional options.
func New(opts ...Option) *Typography {
t := &Typography{
theme: DefaultTheme(),
}
for _, opt := range opts {
opt(t)
}
return t
}
// Theme returns a copy of the current theme.
func (t *Typography) Theme() Theme {
return t.theme
}
// ---------------------------------------------------------------------------
// Headings
// ---------------------------------------------------------------------------
// headingWithUnderline renders a heading with a repeated underline character
// beneath the text. The underline matches the visible width of the text.
func (t *Typography) headingWithUnderline(text string, style lipgloss.Style, char string) string {
noMargin := style.UnsetMarginBottom()
rendered := noMargin.Render(text)
underline := noMargin.Render(strings.Repeat(char, lipgloss.Width(text)))
return rendered + "\n" + underline + style.Render("")
}
// headingWithBar renders a heading prefixed by a vertical bar character.
func (t *Typography) headingWithBar(text string, style lipgloss.Style, bar string) string {
return style.Render(bar + " " + text)
}
// H1 renders text as a level-1 heading with a double-line underline.
func (t *Typography) H1(text string) string {
return t.headingWithUnderline(text, t.theme.H1, t.theme.H1UnderlineChar)
}
// H2 renders text as a level-2 heading with a single-line underline.
func (t *Typography) H2(text string) string {
return t.headingWithUnderline(text, t.theme.H2, t.theme.H2UnderlineChar)
}
// H3 renders text as a level-3 heading with a dotted underline.
func (t *Typography) H3(text string) string {
return t.headingWithUnderline(text, t.theme.H3, t.theme.H3UnderlineChar)
}
// H4 renders text as a level-4 heading with a bar prefix.
func (t *Typography) H4(text string) string {
return t.headingWithBar(text, t.theme.H4, t.theme.HeadingBarChar)
}
// H5 renders text as a level-5 heading with a bar prefix.
func (t *Typography) H5(text string) string {
return t.headingWithBar(text, t.theme.H5, t.theme.HeadingBarChar)
}
// H6 renders text as a level-6 heading with a bar prefix.
func (t *Typography) H6(text string) string {
return t.headingWithBar(text, t.theme.H6, t.theme.HeadingBarChar)
}
// ---------------------------------------------------------------------------
// Block elements
// ---------------------------------------------------------------------------
// P renders a paragraph.
func (t *Typography) P(text string) string {
return t.theme.Paragraph.Render(text)
}
// Blockquote renders a blockquote with a left border bar. Multi-line text
// is handled by prepending the bar to every line. The bar is styled
// separately from the text so it remains visually distinct.
func (t *Typography) Blockquote(text string) string {
bar := t.theme.BlockquoteBarStyle.Render(t.theme.BlockquoteBar)
lines := strings.Split(text, "\n")
quoted := make([]string, len(lines))
for i, line := range lines {
quoted[i] = bar + " " + t.theme.Blockquote.Render(line)
}
return strings.Join(quoted, "\n")
}
// UL renders an unordered (bulleted) list from the provided items.
func (t *Typography) UL(items ...string) string {
if len(items) == 0 {
return ""
}
bullet := t.theme.BulletChar
marker := t.theme.ListBullet.Render(bullet)
lines := make([]string, len(items))
for i, item := range items {
lines[i] = marker + " " + t.theme.ListItem.Render(item)
}
return strings.Join(lines, "\n")
}
// OL renders an ordered (numbered) list from the provided items.
func (t *Typography) OL(items ...string) string {
if len(items) == 0 {
return ""
}
lines := make([]string, len(items))
for i, item := range items {
num := fmt.Sprintf("%d.", i+1)
marker := t.theme.ListBullet.Render(num)
lines[i] = marker + " " + t.theme.ListItem.Render(item)
}
return strings.Join(lines, "\n")
}
// NestUL renders a nested unordered list from the provided ListItems.
func (t *Typography) NestUL(items ...ListItem) string {
return t.renderNestedList(items, Unordered, 0, "")
}
// NestOL renders a nested ordered list from the provided ListItems.
func (t *Typography) NestOL(items ...ListItem) string {
return t.renderNestedList(items, Ordered, 0, "")
}
// renderNestedList recursively renders a list at the given depth.
// The prefix parameter carries the parent number for hierarchical numbering
// (e.g. "2" so children become "2.1", "2.2").
const maxNestedListDepth = 64
func (t *Typography) renderNestedList(items []ListItem, kind ListKind, depth int, prefix string) string {
if len(items) == 0 || depth > maxNestedListDepth {
return ""
}
indent := strings.Repeat(" ", depth*t.theme.ListIndent)
lines := make([]string, 0, len(items))
for i, item := range items {
var marker string
var childPrefix string
if kind == Ordered {
num := fmt.Sprintf("%d", i+1)
if t.theme.HierarchicalNumbers && prefix != "" {
num = prefix + "." + num
}
marker = t.theme.ListBullet.Render(num + ".")
childPrefix = num
} else {
chars := t.theme.NestedBulletChars
if len(chars) == 0 {
chars = []string{"•"}
}
bullet := chars[depth%len(chars)]
marker = t.theme.ListBullet.Render(bullet)
childPrefix = ""
}
lines = append(lines, indent+marker+" "+t.theme.ListItem.Render(item.Text))
if len(item.Children) > 0 {
child := t.renderNestedList(item.Children, item.Kind, depth+1, childPrefix)
lines = append(lines, child)
}
}
return strings.Join(lines, "\n")
}
// Code renders inline code. If a language is provided and a CodeFormatter is
// set on the theme, the formatter is applied before wrapping in the style.
func (t *Typography) Code(text string, lang ...string) string {
content := text
if t.theme.CodeFormatter != nil && len(lang) > 0 && lang[0] != "" {
content = t.theme.CodeFormatter(text, lang[0])
}
return t.theme.CodeInline.Render(content)
}
// CodeBlock renders a fenced code block. If a language is provided and a
// CodeFormatter is set on the theme, the formatter is applied before wrapping
// in the style. When ShowLineNumbers is true, line numbers are prepended to
// each line after formatting.
func (t *Typography) CodeBlock(text string, lang ...string) string {
content := text
if t.theme.CodeFormatter != nil && len(lang) > 0 && lang[0] != "" {
content = t.theme.CodeFormatter(text, lang[0])
}
if t.theme.ShowLineNumbers {
return t.codeBlockWithLineNumbers(content)
}
return t.theme.CodeBlock.Render(content)
}
// codeBlockWithLineNumbers renders a code block with a line number gutter.
// It builds two separate columns (numbers+separator and code) and joins them
// horizontally so that each column is independently styled, avoiding nested
// Render calls that break background propagation.
func (t *Typography) codeBlockWithLineNumbers(content string) string {
lines := strings.Split(content, "\n")
offset := t.theme.CodeLineNumberOffset
lastNum := offset + len(lines) - 1
width := len(fmt.Sprintf("%d", lastNum))
bg := t.theme.CodeBlock.GetBackground()
// Build the gutter column: right-aligned numbers + separator.
gutter := make([]string, len(lines))
for i := range lines {
gutter[i] = fmt.Sprintf("%*d", width, offset+i) + t.theme.CodeLineNumberSep
}
gutterStyle := t.theme.CodeLineNumber.
Background(bg).
PaddingTop(1).
PaddingBottom(1).
PaddingLeft(2).
MarginBottom(t.theme.CodeBlock.GetMarginBottom())
// Build the code column with matching background and right padding.
codeStyle := lipgloss.NewStyle().
Foreground(t.theme.CodeBlock.GetForeground()).
Background(bg).
PaddingTop(1).
PaddingBottom(1).
PaddingRight(2).
PaddingLeft(1).
MarginBottom(t.theme.CodeBlock.GetMarginBottom())
return lipgloss.JoinHorizontal(lipgloss.Top,
gutterStyle.Render(strings.Join(gutter, "\n")),
codeStyle.Render(content),
)
}
// BR returns a line break, analogous to HTML <br/>.
func (t *Typography) BR() string {
return "\n"
}
// Section joins blocks with a single newline (no blank line between them),
// unlike Compose which uses double newlines. Use this when a heading should
// sit tight against its content, avoiding the extra blank line that Compose
// would insert between a heading with MarginBottom and the following block.
func (t *Typography) Section(blocks ...string) string {
non := make([]string, 0, len(blocks))
for _, b := range blocks {
trimmed := strings.TrimRight(b, "\n")
if trimmed != "" {
non = append(non, trimmed)
}
}
return strings.Join(non, "\n")
}
// HR renders a horizontal rule.
func (t *Typography) HR() string {
line := strings.Repeat(t.theme.HRChar, t.theme.HRWidth)
return t.theme.HR.Render(line)
}
// HRWithLabel renders a horizontal rule with a centered label.
// The label is styled separately from the rule characters.
// If label is empty, it falls back to a plain HR.
func (t *Typography) HRWithLabel(label string) string {
if label == "" {
return t.HR()
}
labelWidth := lipgloss.Width(label)
totalWidth := t.theme.HRWidth
if labelWidth+4 > totalWidth {
// Label too long - just render it styled
return t.theme.HRLabel.Render(label)
}
remaining := totalWidth - labelWidth - 2 // 2 spaces around label
leftWidth := remaining / 2
rightWidth := remaining - leftWidth
left := strings.Repeat(t.theme.HRChar, leftWidth)
right := strings.Repeat(t.theme.HRChar, rightWidth)
return t.theme.HR.Render(left) + " " + t.theme.HRLabel.Render(label) + " " + t.theme.HR.Render(right)
}
// ---------------------------------------------------------------------------
// Inline styles
// ---------------------------------------------------------------------------
// Bold renders bold text.
func (t *Typography) Bold(text string) string {
return t.theme.Bold.Render(text)
}
// Italic renders italic text.
func (t *Typography) Italic(text string) string {
return t.theme.Italic.Render(text)
}
// Underline renders underlined text.
func (t *Typography) Underline(text string) string {
return t.theme.Underline.Render(text)
}
// Strikethrough renders strikethrough text.
func (t *Typography) Strikethrough(text string) string {
return t.theme.Strikethrough.Render(text)
}
// Small renders small/faint text.
func (t *Typography) Small(text string) string {
return t.theme.Small.Render(text)
}
// Mark renders highlighted text.
func (t *Typography) Mark(text string) string {
return t.theme.Mark.Render(text)
}
// Link renders a styled URL or link text. If both label and url are provided,
// it renders as "label (url)". If only one argument is given, it is treated
// as both the label and the URL.
func (t *Typography) Link(label string, url ...string) string {
if len(url) > 0 && url[0] != "" && url[0] != label {
return t.theme.Link.Render(label) + " (" + t.theme.Small.Render(url[0]) + ")"
}
return t.theme.Link.Render(label)
}
// Kbd renders a keyboard key indicator.
func (t *Typography) Kbd(text string) string {
return t.theme.Kbd.Render(text)
}
// Abbr renders an abbreviation. If a description is provided it is shown in
// parentheses after the abbreviation.
func (t *Typography) Abbr(abbr string, desc ...string) string {
styled := t.theme.Abbr.Render(abbr)
if len(desc) > 0 && desc[0] != "" {
styled += " (" + desc[0] + ")"
}
return styled
}
// Sub renders a subscript marker. In a terminal we prefix with an underscore
// to visually indicate subscript.
func (t *Typography) Sub(text string) string {
return t.theme.Sub.Render("_" + text)
}
// Sup renders a superscript marker. In a terminal we prefix with a caret
// to visually indicate superscript.
func (t *Typography) Sup(text string) string {
return t.theme.Sup.Render("^" + text)
}
// Ins renders inserted (added) text with a prefix marker.
func (t *Typography) Ins(text string) string {
return t.theme.Ins.Render(t.theme.InsPrefix + text)
}
// Del renders deleted (removed) text with a prefix marker.
func (t *Typography) Del(text string) string {
return t.theme.Del.Render(t.theme.DelPrefix + text)
}
// Q renders an inline quotation wrapped in styled quotation marks.
func (t *Typography) Q(text string) string {
return t.theme.Q.Render(t.theme.QuoteOpen + text + t.theme.QuoteClose)
}
// Cite renders a citation reference, typically italic and muted.
func (t *Typography) Cite(text string) string {
return t.theme.Cite.Render(text)
}
// Samp renders sample program output, styled distinctly from CodeInline.
func (t *Typography) Samp(text string) string {
return t.theme.Samp.Render(text)
}
// Var renders a variable name, typically italic with an accent color.
func (t *Typography) Var(text string) string {
return t.theme.Var.Render(text)
}
// ---------------------------------------------------------------------------
// Figure
// ---------------------------------------------------------------------------
// Figure renders content with a styled caption. The caption position is
// determined by the theme's FigureCaptionPosition (default CaptionBottom).
func (t *Typography) Figure(content, caption string) string {
if t.theme.FigureCaptionPosition == CaptionTop {
return t.FigureTop(content, caption)
}
styled := t.theme.FigureCaption.Render(caption)
return content + "\n" + styled
}
// FigureTop renders content with the caption placed above the content.
func (t *Typography) FigureTop(content, caption string) string {
styled := t.theme.FigureCaption.Render(caption)
return styled + "\n\n" + content
}
// ---------------------------------------------------------------------------
// Alerts
// ---------------------------------------------------------------------------
// Alert renders a GitHub-style alert callout. The header line (bar + icon +
// label) is bold + colored; content lines have a colored bar but unstyled
// text, matching GitHub's visual style. If the alert type is not configured,
// it falls back to blockquote rendering.
func (t *Typography) Alert(at AlertType, text string) string {
cfg, ok := t.theme.Alerts[at]
if !ok {
return t.Blockquote(text)
}
bar := t.theme.AlertBar
style := cfg.Style
// Header: bar + icon + label, rendered bold + colored
headerStyle := style.Bold(true)
header := headerStyle.Render(bar + " " + cfg.Icon + " " + cfg.Label)
// Content: colored bar + unstyled text (matching GitHub alerts)
lines := strings.Split(text, "\n")
renderedBar := style.Render(bar)
content := make([]string, len(lines))
for i, line := range lines {
content[i] = renderedBar + " " + line
}
return header + "\n" + strings.Join(content, "\n")
}
// Note renders a blue informational alert.
func (t *Typography) Note(text string) string { return t.Alert(AlertNote, text) }
// Tip renders a green helpful-hint alert.
func (t *Typography) Tip(text string) string { return t.Alert(AlertTip, text) }
// Important renders a purple important-information alert.
func (t *Typography) Important(text string) string { return t.Alert(AlertImportant, text) }
// Warning renders a yellow/amber warning alert.
func (t *Typography) Warning(text string) string { return t.Alert(AlertWarning, text) }
// Caution renders a red caution/danger alert.
func (t *Typography) Caution(text string) string { return t.Alert(AlertCaution, text) }
// ---------------------------------------------------------------------------
// Table
// ---------------------------------------------------------------------------
// Alignment represents the horizontal alignment of text within a table cell.
type Alignment int
const (
// AlignLeft aligns cell content to the left (default).
AlignLeft Alignment = iota
// AlignCenter centers cell content horizontally.
AlignCenter
// AlignRight aligns cell content to the right.
AlignRight
)
// TableOption is a functional option for per-table configuration.
// It is distinct from Option, which configures the Typography instance.
type TableOption func(*tableConfig)
// CaptionPosition specifies where a caption is rendered relative to its content.
type CaptionPosition int
const (
// CaptionTop renders the caption above the content.
CaptionTop CaptionPosition = iota
// CaptionBottom renders the caption below the content.
CaptionBottom
)
// tableConfig holds per-table settings applied via TableOption.
type tableConfig struct {
alignments map[int]Alignment // column index -> alignment
rowSeparators bool // draw horizontal lines between body rows
stripedRows bool // alternate row styles for readability
caption string // optional caption text
captionPosition CaptionPosition // top or bottom
footerRow bool // treat last row as a footer
maxColWidth int // global max column width (0 = unlimited)
maxColWidths map[int]int // per-column max widths (overrides global)
}
// WithColumnAlign sets the alignment for a specific column (0-indexed).
// Columns without an explicit alignment default to AlignLeft.
func WithColumnAlign(col int, align Alignment) TableOption {
return func(cfg *tableConfig) {
if cfg.alignments == nil {
cfg.alignments = make(map[int]Alignment)
}
cfg.alignments[col] = align
}
}
// WithRowSeparators enables horizontal separator lines between every body row.
func WithRowSeparators(enabled bool) TableOption {
return func(cfg *tableConfig) {
cfg.rowSeparators = enabled
}
}
// WithStripedRows enables alternating row background styles for readability.
// Odd body rows use the TableStripedCell style instead of TableCell.
func WithStripedRows(enabled bool) TableOption {
return func(cfg *tableConfig) {
cfg.stripedRows = enabled
}
}
// WithCaption adds a caption above the table.
func WithCaption(text string) TableOption {
return func(cfg *tableConfig) {
cfg.caption = text
cfg.captionPosition = CaptionTop
}
}
// WithCaptionBottom adds a caption below the table.
func WithCaptionBottom(text string) TableOption {
return func(cfg *tableConfig) {
cfg.caption = text
cfg.captionPosition = CaptionBottom
}
}
// WithFooterRow treats the last row as a footer with a distinct separator
// and the TableFooter style.
func WithFooterRow(enabled bool) TableOption {
return func(cfg *tableConfig) {
cfg.footerRow = enabled
}
}
// WithMaxColumnWidth sets a global maximum visible width for all columns.
// Cells exceeding this width are truncated with "…". A value of 0 disables
// truncation. Per-column limits set via WithColumnMaxWidth take precedence.
func WithMaxColumnWidth(n int) TableOption {
return func(cfg *tableConfig) {
cfg.maxColWidth = n
}
}
// WithColumnMaxWidth sets the maximum visible width for a specific column
// (0-indexed). Cells exceeding this width are truncated with "…".
// This overrides the global WithMaxColumnWidth for the given column.
func WithColumnMaxWidth(col, n int) TableOption {
return func(cfg *tableConfig) {
if cfg.maxColWidths == nil {
cfg.maxColWidths = make(map[int]int)
}
cfg.maxColWidths[col] = n
}
}
// WithColumnAligns sets the alignment for columns 0, 1, 2, ... in order.
// Columns beyond the length of the slice default to AlignLeft.
func WithColumnAligns(aligns ...Alignment) TableOption {
return func(cfg *tableConfig) {
if cfg.alignments == nil {
cfg.alignments = make(map[int]Alignment)
}
for i, a := range aligns {
cfg.alignments[i] = a
}
}
}
// truncateCell truncates a string to maxWidth visible characters, appending "…"
// if truncation occurs. Returns the original string if it fits.
func truncateCell(s string, maxWidth int) string {
if maxWidth <= 0 || lipgloss.Width(s) <= maxWidth {
return s
}
runes := []rune(s)
// Reserve 1 character for the ellipsis.
for i := len(runes); i > 0; i-- {
candidate := string(runes[:i]) + "…"
if lipgloss.Width(candidate) <= maxWidth {
return candidate
}
}
return "…"
}
// truncateRows returns a copy of rows with cells truncated according to the
// config's max column width settings. The original rows are not modified.
func truncateRows(rows [][]string, cfg *tableConfig) [][]string {
if cfg.maxColWidth <= 0 && len(cfg.maxColWidths) == 0 {
return rows
}
out := make([][]string, len(rows))
for i, row := range rows {
newRow := make([]string, len(row))
for c, cell := range row {
maxW := cfg.maxColWidth
if w, ok := cfg.maxColWidths[c]; ok {
maxW = w
}
if maxW > 0 {
newRow[c] = truncateCell(cell, maxW)
} else {
newRow[c] = cell
}
}
out[i] = newRow
}
return out
}
// tableColumnWidths computes the maximum cell width per column across all rows.
func tableColumnWidths(rows [][]string, cols int) []int {
widths := make([]int, cols)
for _, row := range rows {
for c := range cols {
cell := ""
if c < len(row) {
cell = row[c]
}
if w := lipgloss.Width(cell); w > widths[c] {
widths[c] = w
}
}
}
return widths
}
// tableHLine builds a horizontal separator line for a table.
func (t *Typography) tableHLine(colWidths []int, pad int, left, fill, junction, right string) string {
segments := make([]string, len(colWidths))
for c, w := range colWidths {
segments[c] = strings.Repeat(fill, w+pad*2)
}
return t.theme.TableBorder.Render(left + strings.Join(segments, junction) + right)
}
// alignCell pads a rendered cell string to the given total width according to
// the specified alignment. The returned string has exactly totalWidth visible
// characters (excluding the surrounding padStr added by the caller).
func alignCell(rendered string, cellWidth, totalWidth int, align Alignment) string {
gap := totalWidth - cellWidth
if gap <= 0 {
return rendered
}
switch align {
case AlignRight:
return strings.Repeat(" ", gap) + rendered
case AlignCenter:
left := gap / 2
right := gap - left
return strings.Repeat(" ", left) + rendered + strings.Repeat(" ", right)
default: // AlignLeft
return rendered + strings.Repeat(" ", gap)
}
}
// tableRow renders a single data row with cell content and vertical separators.
func (t *Typography) tableRow(row []string, style lipgloss.Style, colWidths []int, padStr string, bordered bool, aligns map[int]Alignment) string {
bs := t.theme.TableBorderSet
cols := len(colWidths)
cells := make([]string, cols)
for c := range cols {
cell := ""
if c < len(row) {
cell = row[c]
}
rendered := style.Render(cell)
cellWidth := lipgloss.Width(cell)
align := AlignLeft
if a, ok := aligns[c]; ok {
align = a
}
cells[c] = padStr + alignCell(rendered, cellWidth, colWidths[c], align) + padStr
}
sep, end := "", ""
if bordered {
sep = t.theme.TableBorder.Render(bs.Left)
end = t.theme.TableBorder.Render(bs.Right)
}
colSep := bs.ColumnSep
if colSep == "" {
colSep = "│"
}
inner := t.theme.TableBorder.Render(colSep)
return sep + strings.Join(cells, inner) + end
}
// Table renders a table from a slice of rows. The first row is treated as the
// header. Each row is a slice of cell strings. Rows may have different lengths;
// shorter rows are padded with empty cells. Returns an empty string if rows is
// nil or empty.
func (t *Typography) Table(rows [][]string) string {
return t.renderTable(rows, &tableConfig{})
}
// TableWithOpts renders a table like Table but accepts per-table options such
// as column alignment. The first row is treated as the header.
//
// t.TableWithOpts(rows,
// herald.WithColumnAlign(0, herald.AlignCenter),
// herald.WithColumnAlign(2, herald.AlignRight),
// )
func (t *Typography) TableWithOpts(rows [][]string, opts ...TableOption) string {
cfg := &tableConfig{}
for _, o := range opts {
o(cfg)
}
return t.renderTable(rows, cfg)
}
// tableMaxCols returns the maximum number of columns across all rows.
func tableMaxCols(rows [][]string) int {
cols := 0
for _, row := range rows {
if len(row) > cols {
cols = len(row)
}
}
return cols
}
// renderTable is the shared implementation for Table and TableWithOpts.
func (t *Typography) renderTable(rows [][]string, cfg *tableConfig) string {
if len(rows) == 0 {
return ""
}
cols := tableMaxCols(rows)
if cols == 0 {
return ""
}
// Apply auto-truncation before computing widths.
rows = truncateRows(rows, cfg)
aligns := cfg.alignments
if aligns == nil {
aligns = make(map[int]Alignment)
}
bs := t.theme.TableBorderSet
pad := t.theme.TableCellPad
padStr := strings.Repeat(" ", pad)
colWidths := tableColumnWidths(rows, cols)
bordered := bs.TopLeft != ""
// Determine body range and footer row.
bodyEnd := len(rows)
hasFooter := cfg.footerRow && len(rows) > 2
if hasFooter {
bodyEnd = len(rows) - 1
}
var sb strings.Builder
// Caption (top).
t.writeCaption(&sb, cfg, CaptionTop, false)
// Top border.
if bordered {
sb.WriteString(t.tableHLine(colWidths, pad, bs.TopLeft, bs.Top, bs.TopJunction, bs.TopRight))
sb.WriteByte('\n')
}
// Header row.
sb.WriteString(t.tableRow(rows[0], t.theme.TableHeader, colWidths, padStr, bordered, aligns))
sb.WriteByte('\n')
sb.WriteString(t.tableHLine(colWidths, pad, bs.HeaderLeft, bs.Header, bs.HeaderCross, bs.HeaderRight))
// Body rows.
hasRowSep := cfg.rowSeparators && bs.Row != ""
t.renderTableBody(rows[1:bodyEnd], &sb, colWidths, padStr, bordered, aligns, hasRowSep, cfg.stripedRows)
// Footer row.
if hasFooter {
sb.WriteByte('\n')
sb.WriteString(t.tableHLine(colWidths, pad, bs.FooterLeft, bs.Header, bs.FooterCross, bs.FooterRight))
sb.WriteByte('\n')
sb.WriteString(t.tableRow(rows[len(rows)-1], t.theme.TableFooter, colWidths, padStr, bordered, aligns))
}
// Bottom border.
if bordered {
sb.WriteByte('\n')
sb.WriteString(t.tableHLine(colWidths, pad, bs.BottomLeft, bs.Bottom, bs.BottomJunction, bs.BottomRight))
}
// Caption (bottom).
t.writeCaption(&sb, cfg, CaptionBottom, true)
return sb.String()
}
// writeCaption writes the table caption to the builder if it matches the
// given position. When newlineBefore is true, a newline is prepended.
func (t *Typography) writeCaption(sb *strings.Builder, cfg *tableConfig, pos CaptionPosition, newlineBefore bool) {
if cfg.caption == "" || cfg.captionPosition != pos {
return
}
if newlineBefore {
sb.WriteByte('\n')
}
sb.WriteString(t.theme.TableCaption.Render(cfg.caption))
if !newlineBefore {
sb.WriteByte('\n')
}
}
// renderTableBody writes body rows to the builder, handling row separators and
// striped row styling.
func (t *Typography) renderTableBody(bodyRows [][]string, sb *strings.Builder, colWidths []int, padStr string, bordered bool, aligns map[int]Alignment, hasRowSep, striped bool) {
bs := t.theme.TableBorderSet
for i, row := range bodyRows {
sb.WriteByte('\n')
if hasRowSep && i > 0 {
left, right := bs.LeftJunction, bs.RightJunction
if !bordered {
left, right = "", ""
}
sb.WriteString(t.tableHLine(colWidths, t.theme.TableCellPad, left, bs.Row, bs.Cross, right))
sb.WriteByte('\n')
}
style := t.theme.TableCell
if striped && i%2 == 1 {
style = t.theme.TableStripedCell
}
sb.WriteString(t.tableRow(row, style, colWidths, padStr, bordered, aligns))
}
}
// ---------------------------------------------------------------------------
// Definition list
// ---------------------------------------------------------------------------
// DL renders a definition list from term-description pairs. Each pair is a
// two-element array: [term, description]. Odd-length slices ignore the last
// unpaired element.
func (t *Typography) DL(pairs [][2]string) string {
if len(pairs) == 0 {
return ""
}
lines := make([]string, 0, len(pairs)*2)
for _, pair := range pairs {
lines = append(lines, t.theme.DT.Render(pair[0]), t.theme.DD.Render(pair[1]))
}
return strings.Join(lines, "\n")
}
// DT renders a single definition term.
func (t *Typography) DT(text string) string {
return t.theme.DT.Render(text)
}
// DD renders a single definition description.
func (t *Typography) DD(text string) string {
return t.theme.DD.Render(text)
}
// ---------------------------------------------------------------------------
// Key-value pairs
// ---------------------------------------------------------------------------
// KV renders a single key-value pair as "key: value" with the key and value
// styled independently. The separator is taken from the theme's KVSeparator.
func (t *Typography) KV(key, value string) string {
return t.theme.KVKey.Render(key+t.theme.KVSeparator) + " " + t.theme.KVValue.Render(value)
}
// KVGroup renders multiple key-value pairs with keys right-padded so that
// values align vertically. Each pair is a two-element array [key, value].
// Returns an empty string for empty input.
func (t *Typography) KVGroup(pairs [][2]string) string {
return t.KVGroupWithOpts(pairs)
}
// KVGroupWithOpts renders key-value pairs like KVGroup but accepts functional
// options to customise the separator, styling, and indentation per call.
func (t *Typography) KVGroupWithOpts(pairs [][2]string, opts ...KVOption) string {
if len(pairs) == 0 {
return ""
}
cfg := &kvConfig{}
for _, opt := range opts {
opt(cfg)
}
sep := t.theme.KVSeparator
if cfg.separator != nil {
sep = *cfg.separator
}
indent := ""
if cfg.indent > 0 {
indent = strings.Repeat(" ", cfg.indent)
}
// Find max key width for alignment.
maxKeyWidth := 0
for _, pair := range pairs {
if w := lipgloss.Width(pair[0]); w > maxKeyWidth {
maxKeyWidth = w
}
}
lines := make([]string, len(pairs))
for i, pair := range pairs {
keyWidth := lipgloss.Width(pair[0])
padding := strings.Repeat(" ", maxKeyWidth-keyWidth)
key := pair[0] + padding + sep
if !cfg.rawKeys {
key = t.theme.KVKey.Render(key)
}
val := pair[1]
if !cfg.rawValues {
val = t.theme.KVValue.Render(val)
}
lines[i] = indent + key + " " + val
}
return strings.Join(lines, "\n")
}
// ---------------------------------------------------------------------------
// Address
// ---------------------------------------------------------------------------
// Address renders a styled contact/author information block.
func (t *Typography) Address(text string) string {
return t.theme.Address.Render(text)
}
// AddressCard renders a contact/author block inside a bordered card.
// The border color is taken from the AddressCardBorder theme style.
func (t *Typography) AddressCard(text string) string {
borderColor := t.theme.AddressCardBorder.GetForeground()
style := t.theme.AddressCard.
Border(lipgloss.RoundedBorder()).
BorderForeground(borderColor).
Padding(0, 1)
return style.Render(text)
}
// ---------------------------------------------------------------------------
// Badge
// ---------------------------------------------------------------------------
// Badge renders text as a styled pill/tag label.
func (t *Typography) Badge(text string) string {
return t.theme.Badge.Render(text)
}
// BadgeWithStyle renders a badge using a one-off style override, useful for
// semantic variants (success, warning, error) without changing the theme.
func (t *Typography) BadgeWithStyle(text string, style lipgloss.Style) string {
return style.Render(text)
}
// Tag renders text as a subtle pill/category label.
func (t *Typography) Tag(text string) string {
return t.theme.Tag.Render(text)
}
// TagWithStyle renders a tag using a one-off style override.
func (t *Typography) TagWithStyle(text string, style lipgloss.Style) string {
return style.Render(text)
}
// ---------------------------------------------------------------------------
// Semantic Badges
// ---------------------------------------------------------------------------
// SuccessBadge renders a badge styled for success/positive status.
func (t *Typography) SuccessBadge(text string) string {
return t.theme.SuccessBadge.Render(text)
}