bbcode - bbcodehtml/table.go
1 package bbcodehtml
2
3 import (
4 "strings"
5
6 "vimagination.zapto.org/bbcode"
7 )
8
9 type table struct{}
10
11 func (table) Name() string {
12 return "table"
13 }
14
15 var (
16 tableOpen = []byte("<table>")
17 tableClose = []byte("</table>")
18 tableHeadOpen = []byte("<thead>")
19 tableHeadClose = []byte("</thead>")
20 tableFootOpen = []byte("<tfoot>")
21 tableFootClose = []byte("</tfoot>")
22 trOpen = []byte("<tr>")
23 trClose = []byte("</tr>")
24 tdOpen = []byte("<td>")
25 tdClose = []byte("</td>")
26 thOpen = []byte("<th>")
27 thClose = []byte("</th>")
28 )
29
30 func (table) Handle(p *bbcode.Processor, attr string) {
31 p.Write(tableOpen)
32 tableHandle(p)
33 p.Write(tableClose)
34 }
35
36 func tableHandle(p *bbcode.Processor) {
37 var thead, tfoot bool
38 Loop:
39 for {
40 switch t := p.Get().(type) {
41 case bbcode.Text:
42 case bbcode.OpenTag:
43 if strings.EqualFold(t.Name, "thead") {
44 if !thead {
45 p.Write(tableHeadOpen)
46 tableIHandle(p, "thead")
47 p.Write(tableHeadClose)
48 thead = true
49 }
50 } else if strings.EqualFold(t.Name, "tfoot") {
51 if !tfoot {
52 p.Write(tableFootOpen)
53 tableIHandle(p, "tfoot")
54 p.Write(tableFootClose)
55 tfoot = true
56 }
57 } else if strings.EqualFold(t.Name, "row") || strings.EqualFold(t.Name, "tr") {
58 p.Write(trOpen)
59 tableRow(p, t.Name)
60 p.Write(trClose)
61 }
62 case bbcode.CloseTag:
63 if strings.EqualFold(t.Name, "table") {
64 break Loop
65 }
66 default:
67 break Loop
68 }
69 }
70 }
71
72 func tableIHandle(p *bbcode.Processor, tagName string) {
73 Loop:
74 for {
75 switch t := p.Get().(type) {
76 case bbcode.Text:
77 case bbcode.OpenTag:
78 if strings.EqualFold(t.Name, "row") || strings.EqualFold(t.Name, "tr") {
79 p.Write(trOpen)
80 tableRow(p, t.Name)
81 p.Write(trClose)
82 }
83 case bbcode.CloseTag:
84 if t.Name == tagName {
85 break Loop
86 }
87 default:
88 break Loop
89 }
90 }
91 }
92
93 func tableRow(p *bbcode.Processor, tagName string) {
94 Loop:
95 for {
96 switch t := p.Get().(type) {
97 case bbcode.Text:
98 case bbcode.OpenTag:
99 if strings.EqualFold(t.Name, "col") || strings.EqualFold(t.Name, "td") {
100 p.Write(tdOpen)
101 p.Process(t.Name)
102 p.Write(tdClose)
103 } else if strings.EqualFold(t.Name, "th") {
104 p.Write(thOpen)
105 p.Process(t.Name)
106 p.Write(thClose)
107 }
108 case bbcode.CloseTag:
109 if t.Name == tagName {
110 break Loop
111 }
112 default:
113 break Loop
114 }
115 }
116 }
117