-
-
Notifications
You must be signed in to change notification settings - Fork 273
/
generator.go
1469 lines (1394 loc) · 40.5 KB
/
generator.go
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 generator
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"html"
"io"
"path/filepath"
"reflect"
"strconv"
"strings"
"time"
"unicode"
_ "embed"
"github.com/a-h/templ/parser/v2"
)
type GenerateOpt func(g *generator) error
// WithVersion enables the version to be included in the generated code.
func WithVersion(v string) GenerateOpt {
return func(g *generator) error {
g.version = v
return nil
}
}
// WithTimestamp enables the generated date to be included in the generated code.
func WithTimestamp(d time.Time) GenerateOpt {
return func(g *generator) error {
g.generatedDate = d.Format(time.RFC3339)
return nil
}
}
// WithFileName sets the filename of the templ file in template rendering error messages.
func WithFileName(name string) GenerateOpt {
return func(g *generator) error {
if filepath.IsAbs(name) {
_, g.fileName = filepath.Split(name)
return nil
}
g.fileName = name
return nil
}
}
func WithExtractStrings() GenerateOpt {
return func(g *generator) error {
g.w.literalWriter = &watchLiteralWriter{
builder: &strings.Builder{},
}
return nil
}
}
// Generate generates Go code from the input template file to w, and returns a map of the location of Go expressions in the template
// to the location of the generated Go code in the output.
func Generate(template parser.TemplateFile, w io.Writer, opts ...GenerateOpt) (sm *parser.SourceMap, literals string, err error) {
g := &generator{
tf: template,
w: NewRangeWriter(w),
sourceMap: parser.NewSourceMap(),
}
for _, opt := range opts {
if err = opt(g); err != nil {
return
}
}
err = g.generate()
sm = g.sourceMap
literals = g.w.literalWriter.literals()
return
}
type generator struct {
tf parser.TemplateFile
w *RangeWriter
sourceMap *parser.SourceMap
variableID int
childrenVar string
// version of templ.
version string
// generatedDate to include as a comment.
generatedDate string
// fileName to include in error messages if string expressions return an error.
fileName string
}
func (g *generator) generate() (err error) {
if err = g.writeCodeGeneratedComment(); err != nil {
return
}
if err = g.writeVersionComment(); err != nil {
return
}
if err = g.writeGeneratedDateComment(); err != nil {
return
}
if err = g.writePackage(); err != nil {
return
}
if err = g.writeImports(); err != nil {
return
}
if err = g.writeTemplateNodes(); err != nil {
return
}
return err
}
func (g *generator) writeCodeGeneratedComment() (err error) {
_, err = g.w.Write("// Code generated by templ - DO NOT EDIT.\n\n")
return err
}
func (g *generator) writeVersionComment() (err error) {
if g.version != "" {
_, err = g.w.Write("// templ: version: " + g.version + "\n")
}
return err
}
func (g *generator) writeGeneratedDateComment() (err error) {
if g.generatedDate != "" {
_, err = g.w.Write("// templ: generated: " + g.generatedDate + "\n")
}
return err
}
func (g *generator) writePackage() error {
var r parser.Range
var err error
// package ...
if r, err = g.w.Write(g.tf.Package.Expression.Value + "\n\n"); err != nil {
return err
}
g.sourceMap.Add(g.tf.Package.Expression, r)
if _, err = g.w.Write("//lint:file-ignore SA4006 This context is only used if a nested component is present.\n\n"); err != nil {
return err
}
return nil
}
func (g *generator) templateNodeInfo() (hasTemplates bool, hasCSS bool) {
for _, n := range g.tf.Nodes {
switch n.(type) {
case parser.HTMLTemplate:
hasTemplates = true
case parser.CSSTemplate:
hasCSS = true
}
if hasTemplates && hasCSS {
return
}
}
return
}
func (g *generator) writeImports() error {
var err error
// Always import templ because it's the interface type of all templates.
if _, err = g.w.Write("import \"github.com/a-h/templ\"\n"); err != nil {
return err
}
hasTemplates, hasCSS := g.templateNodeInfo()
if hasTemplates {
// The first parameter of a template function.
if _, err = g.w.Write("import \"context\"\n"); err != nil {
return err
}
// The second parameter of a template function.
if _, err = g.w.Write("import \"io\"\n"); err != nil {
return err
}
// Buffer namespace.
if _, err = g.w.Write("import \"bytes\"\n"); err != nil {
return err
}
}
if hasCSS {
// strings.Builder is used to create CSS.
if _, err = g.w.Write("import \"strings\"\n"); err != nil {
return err
}
}
if _, err = g.w.Write("\n"); err != nil {
return err
}
return nil
}
func (g *generator) writeTemplateNodes() error {
for i := 0; i < len(g.tf.Nodes); i++ {
switch n := g.tf.Nodes[i].(type) {
case parser.TemplateFileGoExpression:
if err := g.writeGoExpression(n); err != nil {
return err
}
case parser.HTMLTemplate:
if err := g.writeTemplate(i, n); err != nil {
return err
}
case parser.CSSTemplate:
if err := g.writeCSS(n); err != nil {
return err
}
case parser.ScriptTemplate:
if err := g.writeScript(n); err != nil {
return err
}
default:
return fmt.Errorf("unknown node type: %v", reflect.TypeOf(n))
}
}
return nil
}
func (g *generator) writeCSS(n parser.CSSTemplate) error {
var r parser.Range
var err error
var indentLevel int
// func
if _, err = g.w.Write("func "); err != nil {
return err
}
if r, err = g.w.Write(n.Expression.Value); err != nil {
return err
}
g.sourceMap.Add(n.Expression, r)
// templ.CSSClass {
if _, err = g.w.Write(" templ.CSSClass {\n"); err != nil {
return err
}
{
indentLevel++
// var templ_7745c5c3_CSSBuilder strings.Builder
if _, err = g.w.WriteIndent(indentLevel, "var templ_7745c5c3_CSSBuilder strings.Builder\n"); err != nil {
return err
}
for i := 0; i < len(n.Properties); i++ {
switch p := n.Properties[i].(type) {
case parser.ConstantCSSProperty:
// Constant CSS property values are not sanitized.
if _, err = g.w.WriteIndent(indentLevel, "templ_7745c5c3_CSSBuilder.WriteString("+createGoString(p.String(true))+")\n"); err != nil {
return err
}
case parser.ExpressionCSSProperty:
// templ_7745c5c3_CSSBuilder.WriteString(templ.SanitizeCSS('name', p.Expression()))
if _, err = g.w.WriteIndent(indentLevel, fmt.Sprintf("templ_7745c5c3_CSSBuilder.WriteString(string(templ.SanitizeCSS(`%s`, ", p.Name)); err != nil {
return err
}
if r, err = g.w.Write(p.Value.Expression.Value); err != nil {
return err
}
g.sourceMap.Add(p.Value.Expression, r)
if _, err = g.w.Write(")))\n"); err != nil {
return err
}
default:
return fmt.Errorf("unknown CSS property type: %v", reflect.TypeOf(p))
}
}
if _, err = g.w.WriteIndent(indentLevel, fmt.Sprintf("templ_7745c5c3_CSSID := templ.CSSID(`%s`, templ_7745c5c3_CSSBuilder.String())\n", n.Name)); err != nil {
return err
}
// return templ.CSS {
if _, err = g.w.WriteIndent(indentLevel, "return templ.ComponentCSSClass{\n"); err != nil {
return err
}
{
indentLevel++
// ID: templ_7745c5c3_CSSID,
if _, err = g.w.WriteIndent(indentLevel, "ID: templ_7745c5c3_CSSID,\n"); err != nil {
return err
}
// Class: templ.SafeCSS(".cssID{" + templ.CSSBuilder.String() + "}"),
if _, err = g.w.WriteIndent(indentLevel, "Class: templ.SafeCSS(`.` + templ_7745c5c3_CSSID + `{` + templ_7745c5c3_CSSBuilder.String() + `}`),\n"); err != nil {
return err
}
indentLevel--
}
if _, err = g.w.WriteIndent(indentLevel, "}\n"); err != nil {
return err
}
indentLevel--
}
// }
if _, err = g.w.WriteIndent(indentLevel, "}\n\n"); err != nil {
return err
}
return nil
}
func (g *generator) writeGoExpression(n parser.TemplateFileGoExpression) (err error) {
r, err := g.w.Write(n.Expression.Value)
if err != nil {
return err
}
g.sourceMap.Add(n.Expression, r)
v := n.Expression.Value
lineSlice := strings.Split(v, "\n")
lastLine := lineSlice[len(lineSlice)-1]
if strings.HasPrefix(lastLine, "//") {
if _, err = g.w.WriteIndent(0, "\n"); err != nil {
return err
}
return err
}
if _, err = g.w.WriteIndent(0, "\n\n"); err != nil {
return err
}
return err
}
func (g *generator) writeTemplBuffer(indentLevel int) (err error) {
// templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := w.(*bytes.Buffer)
if _, err = g.w.WriteIndent(indentLevel, "templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templ_7745c5c3_W.(*bytes.Buffer)\n"); err != nil {
return err
}
if _, err = g.w.WriteIndent(indentLevel, "if !templ_7745c5c3_IsBuffer {\n"); err != nil {
return err
}
{
indentLevel++
// templ_7745c5c3_Buffer = templ.GetBuffer()
if _, err = g.w.WriteIndent(indentLevel, "templ_7745c5c3_Buffer = templ.GetBuffer()\n"); err != nil {
return err
}
// defer templ.ReleaseBuffer(templ_7745c5c3_Buffer)
if _, err = g.w.WriteIndent(indentLevel, "defer templ.ReleaseBuffer(templ_7745c5c3_Buffer)\n"); err != nil {
return err
}
indentLevel--
}
if _, err = g.w.WriteIndent(indentLevel, "}\n"); err != nil {
return err
}
return
}
func (g *generator) writeTemplate(nodeIdx int, t parser.HTMLTemplate) error {
var r parser.Range
var err error
var indentLevel int
// func
if _, err = g.w.Write("func "); err != nil {
return err
}
// (r *Receiver) Name(params []string)
if r, err = g.w.Write(t.Expression.Value); err != nil {
return err
}
g.sourceMap.Add(t.Expression, r)
// templ.Component {
if _, err = g.w.Write(" templ.Component {\n"); err != nil {
return err
}
indentLevel++
// return templ.ComponentFunc(func(ctx context.Context, w io.Writer) error {
if _, err = g.w.WriteIndent(indentLevel, "return templ.ComponentFunc(func(ctx context.Context, templ_7745c5c3_W io.Writer) (templ_7745c5c3_Err error) {\n"); err != nil {
return err
}
{
indentLevel++
if err := g.writeTemplBuffer(indentLevel); err != nil {
return err
}
// ctx = templ.InitializeContext(ctx)
if _, err = g.w.WriteIndent(indentLevel, "ctx = templ.InitializeContext(ctx)\n"); err != nil {
return err
}
g.childrenVar = g.createVariableName()
// templ_7745c5c3_Var1 := templ.GetChildren(ctx)
// if templ_7745c5c3_Var1 == nil {
// templ_7745c5c3_Var1 = templ.NopComponent
// }
if _, err = g.w.WriteIndent(indentLevel, fmt.Sprintf("%s := templ.GetChildren(ctx)\n", g.childrenVar)); err != nil {
return err
}
if _, err = g.w.WriteIndent(indentLevel, fmt.Sprintf("if %s == nil {\n", g.childrenVar)); err != nil {
return err
}
{
indentLevel++
if _, err = g.w.WriteIndent(indentLevel, fmt.Sprintf("%s = templ.NopComponent\n", g.childrenVar)); err != nil {
return err
}
indentLevel--
}
if _, err = g.w.WriteIndent(indentLevel, "}\n"); err != nil {
return err
}
// ctx = templ.ClearChildren(children)
if _, err = g.w.WriteIndent(indentLevel, "ctx = templ.ClearChildren(ctx)\n"); err != nil {
return err
}
// Nodes.
if err = g.writeNodes(indentLevel, stripWhitespace(t.Children), nil); err != nil {
return err
}
// Return the buffer.
if _, err = g.w.WriteIndent(indentLevel, "if !templ_7745c5c3_IsBuffer {\n"); err != nil {
return err
}
{
indentLevel++
// _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteTo(templ_7745c5c3_W)
if _, err = g.w.WriteIndent(indentLevel, "_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteTo(templ_7745c5c3_W)\n"); err != nil {
return err
}
indentLevel--
}
if _, err = g.w.WriteIndent(indentLevel, "}\n"); err != nil {
return err
}
// return templ_7745c5c3_Err
if _, err = g.w.WriteIndent(indentLevel, "return templ_7745c5c3_Err\n"); err != nil {
return err
}
indentLevel--
}
// })
if _, err = g.w.WriteIndent(indentLevel, "})\n"); err != nil {
return err
}
indentLevel--
// }
// Note: gofmt wants to remove a single empty line at the end of a file
// so we have to make sure we don't output one if this is the last node.
closingBrace := "}\n\n"
if nodeIdx+1 >= len(g.tf.Nodes) {
closingBrace = "}\n"
}
if _, err = g.w.WriteIndent(indentLevel, closingBrace); err != nil {
return err
}
return nil
}
func stripWhitespace(input []parser.Node) (output []parser.Node) {
for i, n := range input {
if _, isWhiteSpace := n.(parser.Whitespace); !isWhiteSpace {
output = append(output, input[i])
}
}
return output
}
func stripLeadingWhitespace(nodes []parser.Node) []parser.Node {
for i := 0; i < len(nodes); i++ {
n := nodes[i]
if _, isWhiteSpace := n.(parser.Whitespace); !isWhiteSpace {
return nodes[i:]
}
}
return []parser.Node{}
}
func stripTrailingWhitespace(nodes []parser.Node) []parser.Node {
for i := len(nodes) - 1; i >= 0; i-- {
n := nodes[i]
if _, isWhiteSpace := n.(parser.Whitespace); !isWhiteSpace {
return nodes[0 : i+1]
}
}
return []parser.Node{}
}
func stripLeadingAndTrailingWhitespace(nodes []parser.Node) []parser.Node {
return stripTrailingWhitespace(stripLeadingWhitespace(nodes))
}
func (g *generator) writeNodes(indentLevel int, nodes []parser.Node, next parser.Node) error {
for i, curr := range nodes {
var nextNode parser.Node
if i+1 < len(nodes) {
nextNode = nodes[i+1]
}
if nextNode == nil {
nextNode = next
}
if err := g.writeNode(indentLevel, curr, nextNode); err != nil {
return err
}
}
return nil
}
func (g *generator) writeNode(indentLevel int, current parser.Node, next parser.Node) (err error) {
switch n := current.(type) {
case parser.DocType:
err = g.writeDocType(indentLevel, n)
case parser.Element:
err = g.writeElement(indentLevel, n)
case parser.HTMLComment:
err = g.writeComment(indentLevel, n)
case parser.ChildrenExpression:
err = g.writeChildrenExpression(indentLevel)
case parser.RawElement:
err = g.writeRawElement(indentLevel, n)
case parser.ForExpression:
err = g.writeForExpression(indentLevel, n, next)
case parser.CallTemplateExpression:
err = g.writeCallTemplateExpression(indentLevel, n)
case parser.TemplElementExpression:
err = g.writeTemplElementExpression(indentLevel, n)
case parser.IfExpression:
err = g.writeIfExpression(indentLevel, n, next)
case parser.SwitchExpression:
err = g.writeSwitchExpression(indentLevel, n, next)
case parser.StringExpression:
err = g.writeStringExpression(indentLevel, n.Expression)
case parser.Whitespace:
err = g.writeWhitespace(indentLevel, n)
case parser.Text:
err = g.writeText(indentLevel, n)
case parser.GoComment:
// Do not render Go comments in the output HTML.
return
default:
return fmt.Errorf("unhandled type: %v", reflect.TypeOf(n))
}
// Write trailing whitespace, if there is a next node that might need the space.
// If the next node is inline or text, we might need it.
// If the current node is a block element, we don't need it.
needed := (isInlineOrText(current) && isInlineOrText(next))
if ws, ok := current.(parser.WhitespaceTrailer); ok && needed {
if err := g.writeWhitespaceTrailer(indentLevel, ws.Trailing()); err != nil {
return err
}
}
return
}
func isInlineOrText(next parser.Node) bool {
// While these are formatted as blocks when they're written in the HTML template.
// They're inline - i.e. there's no whitespace rendered around them at runtime for minification.
if next == nil {
return false
}
switch n := next.(type) {
case parser.IfExpression:
return true
case parser.SwitchExpression:
return true
case parser.ForExpression:
return true
case parser.Element:
return !n.IsBlockElement()
case parser.Text:
return true
case parser.StringExpression:
return true
}
return false
}
func (g *generator) writeWhitespaceTrailer(indentLevel int, n parser.TrailingSpace) (err error) {
if n == parser.SpaceNone {
return nil
}
// Normalize whitespace for minified output. In HTML, a single space is equivalent to
// any number of spaces, tabs, or newlines.
if n == parser.SpaceVertical {
n = parser.SpaceHorizontal
}
if _, err = g.w.WriteStringLiteral(indentLevel, string(n)); err != nil {
return err
}
return nil
}
func (g *generator) writeDocType(indentLevel int, n parser.DocType) (err error) {
if _, err = g.w.WriteStringLiteral(indentLevel, fmt.Sprintf("<!doctype %s>", n.Value)); err != nil {
return err
}
return nil
}
func (g *generator) writeIfExpression(indentLevel int, n parser.IfExpression, nextNode parser.Node) (err error) {
var r parser.Range
// if
if _, err = g.w.WriteIndent(indentLevel, `if `); err != nil {
return err
}
// x == y {
if r, err = g.w.Write(n.Expression.Value); err != nil {
return err
}
g.sourceMap.Add(n.Expression, r)
// {
if _, err = g.w.Write(` {` + "\n"); err != nil {
return err
}
{
indentLevel++
if err = g.writeNodes(indentLevel, stripLeadingAndTrailingWhitespace(n.Then), nextNode); err != nil {
return err
}
indentLevel--
}
for _, elseIf := range n.ElseIfs {
// } else if {
if _, err = g.w.WriteIndent(indentLevel, `} else if `); err != nil {
return err
}
// x == y {
if r, err = g.w.Write(elseIf.Expression.Value); err != nil {
return err
}
g.sourceMap.Add(elseIf.Expression, r)
// {
if _, err = g.w.Write(` {` + "\n"); err != nil {
return err
}
{
indentLevel++
if err = g.writeNodes(indentLevel, stripLeadingAndTrailingWhitespace(elseIf.Then), nextNode); err != nil {
return err
}
indentLevel--
}
}
if len(n.Else) > 0 {
// } else {
if _, err = g.w.WriteIndent(indentLevel, `} else {`+"\n"); err != nil {
return err
}
{
indentLevel++
if err = g.writeNodes(indentLevel, stripLeadingAndTrailingWhitespace(n.Else), nextNode); err != nil {
return err
}
indentLevel--
}
}
// }
if _, err = g.w.WriteIndent(indentLevel, `}`+"\n"); err != nil {
return err
}
return nil
}
func (g *generator) writeSwitchExpression(indentLevel int, n parser.SwitchExpression, next parser.Node) (err error) {
var r parser.Range
// switch
if _, err = g.w.WriteIndent(indentLevel, `switch `); err != nil {
return err
}
// val
if r, err = g.w.Write(n.Expression.Value); err != nil {
return err
}
g.sourceMap.Add(n.Expression, r)
// {
if _, err = g.w.Write(` {` + "\n"); err != nil {
return err
}
if len(n.Cases) > 0 {
for _, c := range n.Cases {
// case x:
// default:
if r, err = g.w.WriteIndent(indentLevel, c.Expression.Value); err != nil {
return err
}
g.sourceMap.Add(c.Expression, r)
indentLevel++
if err = g.writeNodes(indentLevel, stripLeadingAndTrailingWhitespace(c.Children), next); err != nil {
return err
}
indentLevel--
}
}
// }
if _, err = g.w.WriteIndent(indentLevel, `}`+"\n"); err != nil {
return err
}
return nil
}
func (g *generator) writeChildrenExpression(indentLevel int) (err error) {
if _, err = g.w.WriteIndent(indentLevel, fmt.Sprintf("templ_7745c5c3_Err = %s.Render(ctx, templ_7745c5c3_Buffer)\n", g.childrenVar)); err != nil {
return err
}
if err = g.writeErrorHandler(indentLevel); err != nil {
return err
}
return nil
}
func (g *generator) writeTemplElementExpression(indentLevel int, n parser.TemplElementExpression) (err error) {
if len(n.Children) == 0 {
return g.writeSelfClosingTemplElementExpression(indentLevel, n)
}
return g.writeBlockTemplElementExpression(indentLevel, n)
}
func (g *generator) writeBlockTemplElementExpression(indentLevel int, n parser.TemplElementExpression) (err error) {
var r parser.Range
childrenName := g.createVariableName()
if _, err = g.w.WriteIndent(indentLevel, childrenName+" := templ.ComponentFunc(func(ctx context.Context, templ_7745c5c3_W io.Writer) (templ_7745c5c3_Err error) {\n"); err != nil {
return err
}
indentLevel++
if err := g.writeTemplBuffer(indentLevel); err != nil {
return err
}
if err = g.writeNodes(indentLevel, stripLeadingAndTrailingWhitespace(n.Children), nil); err != nil {
return err
}
// Return the buffer.
if _, err = g.w.WriteIndent(indentLevel, "if !templ_7745c5c3_IsBuffer {\n"); err != nil {
return err
}
{
indentLevel++
// _, templ_7745c5c3_Err = io.Copy(templ_7745c5c3_W, templ_7745c5c3_Buffer)
if _, err = g.w.WriteIndent(indentLevel, "_, templ_7745c5c3_Err = io.Copy(templ_7745c5c3_W, templ_7745c5c3_Buffer)\n"); err != nil {
return err
}
indentLevel--
}
if _, err = g.w.WriteIndent(indentLevel, "}\n"); err != nil {
return err
}
// return nil
if _, err = g.w.WriteIndent(indentLevel, "return templ_7745c5c3_Err\n"); err != nil {
return err
}
indentLevel--
if _, err = g.w.WriteIndent(indentLevel, "})\n"); err != nil {
return err
}
if _, err = g.w.WriteIndent(indentLevel, `templ_7745c5c3_Err = `); err != nil {
return err
}
if r, err = g.w.Write(n.Expression.Value); err != nil {
return err
}
g.sourceMap.Add(n.Expression, r)
// .Render(templ.WithChildren(ctx, children), templ_7745c5c3_Buffer)
if _, err = g.w.Write(".Render(templ.WithChildren(ctx, " + childrenName + "), templ_7745c5c3_Buffer)\n"); err != nil {
return err
}
if err = g.writeErrorHandler(indentLevel); err != nil {
return err
}
return nil
}
func (g *generator) writeSelfClosingTemplElementExpression(indentLevel int, n parser.TemplElementExpression) (err error) {
if _, err = g.w.WriteIndent(indentLevel, `templ_7745c5c3_Err = `); err != nil {
return err
}
// Template expression.
var r parser.Range
if r, err = g.w.Write(n.Expression.Value); err != nil {
return err
}
g.sourceMap.Add(n.Expression, r)
// .Render(ctx, templ_7745c5c3_Buffer)
if _, err = g.w.Write(".Render(ctx, templ_7745c5c3_Buffer)\n"); err != nil {
return err
}
if err = g.writeErrorHandler(indentLevel); err != nil {
return err
}
return nil
}
func (g *generator) writeCallTemplateExpression(indentLevel int, n parser.CallTemplateExpression) (err error) {
if _, err = g.w.WriteIndent(indentLevel, `templ_7745c5c3_Err = `); err != nil {
return err
}
// Template expression.
var r parser.Range
if r, err = g.w.Write(n.Expression.Value); err != nil {
return err
}
g.sourceMap.Add(n.Expression, r)
// .Render(ctx, templ_7745c5c3_Buffer)
if _, err = g.w.Write(".Render(ctx, templ_7745c5c3_Buffer)\n"); err != nil {
return err
}
if err = g.writeErrorHandler(indentLevel); err != nil {
return err
}
return nil
}
func (g *generator) writeForExpression(indentLevel int, n parser.ForExpression, next parser.Node) (err error) {
var r parser.Range
// for
if _, err = g.w.WriteIndent(indentLevel, `for `); err != nil {
return err
}
// i, v := range p.Stuff
if r, err = g.w.Write(n.Expression.Value); err != nil {
return err
}
g.sourceMap.Add(n.Expression, r)
// {
if _, err = g.w.Write(` {` + "\n"); err != nil {
return err
}
// Children.
indentLevel++
if err = g.writeNodes(indentLevel, stripLeadingAndTrailingWhitespace(n.Children), next); err != nil {
return err
}
indentLevel--
// }
if _, err = g.w.WriteIndent(indentLevel, `}`+"\n"); err != nil {
return err
}
return nil
}
func (g *generator) writeErrorHandler(indentLevel int) (err error) {
_, err = g.w.WriteIndent(indentLevel, "if templ_7745c5c3_Err != nil {\n")
if err != nil {
return err
}
indentLevel++
_, err = g.w.WriteIndent(indentLevel, "return templ_7745c5c3_Err\n")
if err != nil {
return err
}
indentLevel--
_, err = g.w.WriteIndent(indentLevel, "}\n")
if err != nil {
return err
}
return err
}
func (g *generator) writeElement(indentLevel int, n parser.Element) (err error) {
if n.IsVoidElement() {
return g.writeVoidElement(indentLevel, n)
}
return g.writeStandardElement(indentLevel, n)
}
func (g *generator) writeVoidElement(indentLevel int, n parser.Element) (err error) {
if len(n.Children) > 0 {
return fmt.Errorf("writeVoidElement: void element %q must not have child elements", n.Name)
}
if len(n.Attributes) == 0 {
// <br>
if _, err = g.w.WriteStringLiteral(indentLevel, fmt.Sprintf(`<%s>`, html.EscapeString(n.Name))); err != nil {
return err
}
} else {
// <style type="text/css"></style>
if err = g.writeElementCSS(indentLevel, n); err != nil {
return err
}
// <script type="text/javascript"></script>
if err = g.writeElementScript(indentLevel, n); err != nil {
return err
}
// <hr
if _, err = g.w.WriteStringLiteral(indentLevel, fmt.Sprintf(`<%s`, html.EscapeString(n.Name))); err != nil {
return err
}
if err = g.writeElementAttributes(indentLevel, n.Name, n.Attributes); err != nil {
return err
}
// >
if _, err = g.w.WriteStringLiteral(indentLevel, `>`); err != nil {
return err
}
}
return err
}
func (g *generator) writeStandardElement(indentLevel int, n parser.Element) (err error) {
if len(n.Attributes) == 0 {
// <div>
if _, err = g.w.WriteStringLiteral(indentLevel, fmt.Sprintf(`<%s>`, html.EscapeString(n.Name))); err != nil {
return err
}
} else {
// <style type="text/css"></style>
if err = g.writeElementCSS(indentLevel, n); err != nil {
return err
}
// <script type="text/javascript"></script>
if err = g.writeElementScript(indentLevel, n); err != nil {
return err
}
// <div
if _, err = g.w.WriteStringLiteral(indentLevel, fmt.Sprintf(`<%s`, html.EscapeString(n.Name))); err != nil {
return err
}
if err = g.writeElementAttributes(indentLevel, n.Name, n.Attributes); err != nil {
return err
}
// >
if _, err = g.w.WriteStringLiteral(indentLevel, `>`); err != nil {
return err
}
}
// Children.
if err = g.writeNodes(indentLevel, stripWhitespace(n.Children), nil); err != nil {
return err
}
// </div>
if _, err = g.w.WriteStringLiteral(indentLevel, fmt.Sprintf(`</%s>`, html.EscapeString(n.Name))); err != nil {
return err
}
return err
}
func (g *generator) writeAttributeCSS(indentLevel int, attr parser.ExpressionAttribute) (result parser.ExpressionAttribute, ok bool, err error) {
var r parser.Range
name := html.EscapeString(attr.Name)
if name != "class" {
ok = false
return
}
// Create a class name for the style.
// The expression can either be expecting a templ.Classes call, or an expression that returns
// var templ_7745c5c3_CSSClassess = []any{
classesName := g.createVariableName()
if _, err = g.w.WriteIndent(indentLevel, "var "+classesName+" = []any{"); err != nil {
return
}
// p.Name()
if r, err = g.w.Write(attr.Expression.Value); err != nil {
return
}
g.sourceMap.Add(attr.Expression, r)
// }\n
if _, err = g.w.Write("}\n"); err != nil {
return
}
// Render the CSS before the element if required.
// templ_7745c5c3_Err = templ.RenderCSSItems(ctx, templ_7745c5c3_Buffer, templ_7745c5c3_CSSClassess...)
if _, err = g.w.WriteIndent(indentLevel, "templ_7745c5c3_Err = templ.RenderCSSItems(ctx, templ_7745c5c3_Buffer, "+classesName+"...)\n"); err != nil {
return
}
if err = g.writeErrorHandler(indentLevel); err != nil {
return
}
// Rewrite the ExpressionAttribute to point at the new variable.
attr.Expression = parser.Expression{
Value: "templ.CSSClasses(" + classesName + ").String()",
}
return attr, true, nil
}
func (g *generator) writeAttributesCSS(indentLevel int, attrs []parser.Attribute) (err error) {
for i := 0; i < len(attrs); i++ {
if attr, ok := attrs[i].(parser.ExpressionAttribute); ok {
attr, ok, err = g.writeAttributeCSS(indentLevel, attr)
if err != nil {
return err
}
if ok {
attrs[i] = attr
}
}
if cattr, ok := attrs[i].(parser.ConditionalAttribute); ok {
err = g.writeAttributesCSS(indentLevel, cattr.Then)
if err != nil {
return err
}
err = g.writeAttributesCSS(indentLevel, cattr.Else)
if err != nil {
return err
}
attrs[i] = cattr
}
}
return nil
}
func (g *generator) writeElementCSS(indentLevel int, n parser.Element) (err error) {
return g.writeAttributesCSS(indentLevel, n.Attributes)
}
func isScriptAttribute(name string) bool {
for _, prefix := range []string{"on", "hx-on:"} {
if strings.HasPrefix(name, prefix) {
return true
}
}
return false
}