-
-
Notifications
You must be signed in to change notification settings - Fork 273
/
types.go
695 lines (622 loc) · 16.3 KB
/
types.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
package parser
import (
"fmt"
"html"
"io"
"strings"
"github.com/a-h/lexical/parse"
)
// {% package parser %}
//
// {% import "strings" %}
// {% import strs "strings" %}
//
// {% css AddressLineStyle() %}
// background-color: #ff0000;
// color: #ffffff;
// {% endcss %}
//
// {% templ RenderAddress(addr Address) %}
// <div style={%= AddressLineStyle() %}>{%= addr.Address1 %}</div>
// <div>{%= addr.Address2 %}</div>
// <div>{%= addr.Address3 %}</div>
// <div>{%= addr.Address4 %}</div>
// {% endtempl %}
//
// {% templ Render(p Person) %}
// <div>
// <div>{%= p.Name() %}</div>
// <a href={%= p.URL %}>{%= strings.ToUpper(p.Name()) %}</a>
// <div>
// {% if p.Type == "test" %}
// <span>{%= "Test user" %}</span>
// {% else %}
// <span>{%= "Not test user" %}</span>
// {% endif %}
// {% for _, v := range p.Addresses %}
// {% call RenderAddress(v) %}
// {% endfor %}
// </div>
// </div>
// {% endtempl %}
// Source mapping to map from the source code of the template to the
// in-memory representation.
type Position struct {
Index int64
Line int
Col int
}
func (p Position) String() string {
return fmt.Sprintf("line %d, col %d (index %d)", p.Line, p.Col, p.Index)
}
// NewPosition initialises a position.
func NewPosition() Position {
return Position{
Index: 0,
Line: 1,
Col: 0,
}
}
// NewPositionFromValues initialises a position.
func NewPositionFromValues(index int64, line, col int) Position {
return Position{
Index: index,
Line: line,
Col: col,
}
}
// NewPositionFromInput creates a position from a parse input.
func NewPositionFromInput(pi parse.Input) Position {
l, c := pi.Position()
return Position{
Index: pi.Index(),
Line: l,
Col: c,
}
}
// NewExpression creates a Go expression.
func NewExpression(value string, from, to Position) Expression {
return Expression{
Value: value,
Range: Range{
From: from,
To: to,
},
}
}
// NewRange creates a range.
func NewRange(from, to Position) Range {
return Range{
From: from,
To: to,
}
}
// Range of text within a file.
type Range struct {
From Position
To Position
}
// Expression containing Go code.
type Expression struct {
Value string
Range Range
}
type TemplateFile struct {
Package Package
Imports []Import
Nodes []TemplateFileNode
}
func (tf TemplateFile) Write(w io.Writer) error {
var indent int
if err := tf.Package.Write(w, indent); err != nil {
return err
}
if _, err := w.Write([]byte("\n\n")); err != nil {
return err
}
if len(tf.Imports) > 0 {
for i := 0; i < len(tf.Imports); i++ {
if err := tf.Imports[i].Write(w, indent); err != nil {
return err
}
if _, err := w.Write([]byte("\n")); err != nil {
return err
}
}
if _, err := w.Write([]byte("\n")); err != nil {
return err
}
}
for i := 0; i < len(tf.Nodes); i++ {
if err := tf.Nodes[i].Write(w, indent); err != nil {
return err
}
if _, err := w.Write([]byte("\n\n")); err != nil {
return err
}
}
return nil
}
// TemplateFileNode can be a Template or a CSS.
type TemplateFileNode interface {
IsTemplateFileNode() bool
Write(w io.Writer, indent int) error
}
// {% package parser %}
type Package struct {
Expression Expression
}
func (p Package) Write(w io.Writer, indent int) error {
return writeIndent(w, indent, "{% package "+p.Expression.Value+" %}")
}
func writeIndent(w io.Writer, level int, s string) (err error) {
if _, err = w.Write([]byte(strings.Repeat("\t", level))); err != nil {
return
}
_, err = w.Write([]byte(s))
return
}
// Whitespace.
type Whitespace struct {
Value string
}
func (ws Whitespace) IsNode() bool { return true }
func (ws Whitespace) Write(w io.Writer, indent int) error {
// Explicit whitespace nodes are removed from templates because they're auto-formatted.
return nil
}
// {% import "strings" %}
// {% import strs "strings" %}
type Import struct {
Expression Expression
}
func (imp Import) Write(w io.Writer, indent int) error {
return writeIndent(w, indent, "{% import "+imp.Expression.Value+" %}")
}
// CSS definition.
// {% css Name() %}
//
// color: #ffffff;
// background-color: {%= constants.BackgroundColor %};
// background-image: url('./somewhere.png');
//
// {% endcss %}
type CSSTemplate struct {
Name Expression
Properties []CSSProperty
}
func (css CSSTemplate) IsTemplateFileNode() bool { return true }
func (css CSSTemplate) Write(w io.Writer, indent int) error {
if err := writeIndent(w, indent, "{% css "+css.Name.Value+"() %}\n"); err != nil {
return err
}
for _, p := range css.Properties {
if err := p.Write(w, indent+1); err != nil {
return err
}
}
if err := writeIndent(w, indent, "{% endcss %}"); err != nil {
return err
}
return nil
}
// CSSProperty is a CSS property and value pair.
type CSSProperty interface {
IsCSSProperty() bool
Write(w io.Writer, indent int) error
}
// color: #ffffff;
type ConstantCSSProperty struct {
Name string
Value string
}
func (c ConstantCSSProperty) IsCSSProperty() bool { return true }
func (c ConstantCSSProperty) Write(w io.Writer, indent int) error {
if err := writeIndent(w, indent, c.Name+": "+c.Value+";\n"); err != nil {
return err
}
return nil
}
// background-color: {%= constants.BackgroundColor %};
type ExpressionCSSProperty struct {
Name string
Value StringExpression
}
func (c ExpressionCSSProperty) IsCSSProperty() bool { return true }
func (c ExpressionCSSProperty) Write(w io.Writer, indent int) error {
if err := writeIndent(w, indent, c.Name+": "); err != nil {
return err
}
if err := c.Value.Write(w, 0); err != nil {
return err
}
if _, err := w.Write([]byte(";\n")); err != nil {
return err
}
return nil
}
// <!DOCTYPE html>
type DocType struct {
Value string
}
func (dt DocType) IsNode() bool { return true }
func (dt DocType) Write(w io.Writer, indent int) error {
return writeIndent(w, indent, "<!DOCTYPE "+dt.Value+">")
}
// HTMLTemplate definition.
// {% templ Name(p Parameter) %}
//
// {% if ... %}
// <Element></Element>
//
// {% endtempl %}
type HTMLTemplate struct {
Name Expression
Parameters Expression
Children []Node
}
func (t HTMLTemplate) IsTemplateFileNode() bool { return true }
func (t HTMLTemplate) Write(w io.Writer, indent int) error {
if err := writeIndent(w, indent, "{% templ "+t.Name.Value+"("+t.Parameters.Value+") %}\n"); err != nil {
return err
}
if err := writeNodesBlock(w, indent+1, t.Children); err != nil {
return err
}
if err := writeIndent(w, indent, "{% endtempl %}"); err != nil {
return err
}
return nil
}
// A Node appears within a template, e.g. an StringExpression, Element, IfExpression etc.
type Node interface {
IsNode() bool
// Write out the string.
Write(w io.Writer, indent int) error
}
// Text node within the document.
type Text struct {
// Value is the raw HTML encoded value.
Value string
}
func (t Text) IsNode() bool { return true }
func (t Text) Write(w io.Writer, indent int) error {
return writeIndent(w, indent, t.Value)
}
// <a .../> or <div ...>...</div>
type Element struct {
Name string
Attributes []Attribute
Children []Node
}
var voidElements = map[string]struct{}{
"area": {}, "base": {}, "br": {}, "col": {}, "command": {}, "embed": {}, "hr": {}, "img": {}, "input": {}, "keygen": {}, "link": {}, "meta": {}, "param": {}, "source": {}, "track": {}, "wbr": {}}
// https://www.w3.org/TR/2011/WD-html-markup-20110113/syntax.html#void-element
func (e Element) IsVoidElement() bool {
_, ok := voidElements[e.Name]
return ok
}
var blockElements = map[string]struct{}{
"address": {}, "article": {}, "aside": {}, "body": {}, "blockquote": {}, "canvas": {}, "dd": {}, "div": {}, "dl": {}, "dt": {}, "fieldset": {}, "figcaption": {}, "figure": {}, "footer": {}, "form": {}, "h1": {}, "h2": {}, "h3": {}, "h4": {}, "h5": {}, "h6": {}, "head": {}, "header": {}, "hr": {}, "html": {}, "li": {}, "main": {}, "meta": {}, "nav": {}, "noscript": {}, "ol": {}, "p": {}, "pre": {}, "script": {}, "section": {}, "table": {}, "template": {}, "tfoot": {}, "turbo-stream": {}, "ul": {}, "video": {},
}
func (e Element) isBlockElement() bool {
_, ok := blockElements[e.Name]
return ok
}
func (e Element) hasNonWhitespaceChildren() bool {
for _, c := range e.Children {
if _, isWhitespace := c.(Whitespace); !isWhitespace {
return true
}
}
return false
}
func (e Element) containsBlockElement() bool {
for _, c := range e.Children {
switch n := c.(type) {
case Whitespace:
continue
case Element:
if n.isBlockElement() {
return true
}
continue
case StringExpression:
continue
case Text:
continue
}
// Any template elements should be considered block.
return true
}
return false
}
// Validate that no invalid expressions have been used.
func (e Element) Validate() (msgs []string, ok bool) {
// Validate that style attributes are constant.
for _, attr := range e.Attributes {
if exprAttr, isExprAttr := attr.(ExpressionAttribute); isExprAttr {
if strings.EqualFold(exprAttr.Name, "style") {
msgs = append(msgs, "invalid style attribute: style attributes cannot be a templ expression")
}
}
}
// Validate that script and style tags don't contain expressions.
if strings.EqualFold(e.Name, "script") || strings.EqualFold(e.Name, "style") {
if containsNonTextNodes(e.Children) {
msgs = append(msgs, "invalid node contents: script and style attributes must only contain text")
}
}
return msgs, len(msgs) == 0
}
func containsNonTextNodes(nodes []Node) bool {
for i := 0; i < len(nodes); i++ {
n := nodes[i]
switch n.(type) {
case Text:
continue
case Whitespace:
continue
default:
return true
}
}
return false
}
func (e Element) IsNode() bool { return true }
func (e Element) Write(w io.Writer, indent int) error {
if err := writeIndent(w, indent, "<"+e.Name); err != nil {
return err
}
for i := 0; i < len(e.Attributes); i++ {
if _, err := w.Write([]byte(" ")); err != nil {
return err
}
a := e.Attributes[i]
if _, err := w.Write([]byte(a.String())); err != nil {
return err
}
}
if e.hasNonWhitespaceChildren() {
if e.containsBlockElement() {
if _, err := w.Write([]byte(">\n")); err != nil {
return err
}
if err := writeNodesBlock(w, indent+1, e.Children); err != nil {
return err
}
if err := writeIndent(w, indent, "</"+e.Name+">"); err != nil {
return err
}
return nil
}
if _, err := w.Write([]byte(">")); err != nil {
return err
}
if err := writeNodesInline(w, e.Children); err != nil {
return err
}
if _, err := w.Write([]byte("</" + e.Name + ">")); err != nil {
return err
}
return nil
}
if e.IsVoidElement() {
if _, err := w.Write([]byte("/>")); err != nil {
return err
}
return nil
}
if _, err := w.Write([]byte("></" + e.Name + ">")); err != nil {
return err
}
return nil
}
func writeNodesInline(w io.Writer, nodes []Node) error {
return writeNodes(w, 0, nodes, false)
}
func writeNodesBlock(w io.Writer, indent int, nodes []Node) error {
return writeNodes(w, indent, nodes, true)
}
func writeNodes(w io.Writer, indent int, nodes []Node, block bool) error {
for i := 0; i < len(nodes); i++ {
if _, isWhitespace := nodes[i].(Whitespace); isWhitespace {
continue
}
if err := nodes[i].Write(w, indent); err != nil {
return err
}
if block {
if _, err := w.Write([]byte("\n")); err != nil {
return err
}
}
}
return nil
}
type Attribute interface {
IsAttribute() bool
String() string
}
// <hr noshade/>
type BoolConstantAttribute struct {
Name string
}
func (bca BoolConstantAttribute) IsAttribute() bool { return true }
func (bca BoolConstantAttribute) String() string {
return bca.Name
}
// href=""
type ConstantAttribute struct {
Name string
Value string
}
func (ca ConstantAttribute) IsAttribute() bool { return true }
func (ca ConstantAttribute) String() string {
return ca.Name + `="` + html.EscapeString(ca.Value) + `"`
}
// href={%= templ.Bool(...) }
type BoolExpressionAttribute struct {
Name string
Expression Expression
}
func (ea BoolExpressionAttribute) IsAttribute() bool { return true }
func (ea BoolExpressionAttribute) String() string {
return ea.Name + `?={%= ` + ea.Expression.Value + ` %}`
}
// href={%= ... }
type ExpressionAttribute struct {
Name string
Expression Expression
}
func (ea ExpressionAttribute) IsAttribute() bool { return true }
func (ea ExpressionAttribute) String() string {
return ea.Name + `={%= ` + ea.Expression.Value + ` %}`
}
// Nodes.
// CallTemplateExpression can be used to create and render a template using data.
// {%! Other(p.First, p.Last) %}
// or it can be used to render a template parameter.
// {%! v %}
type CallTemplateExpression struct {
// Expression returns a template to execute.
Expression Expression
}
func (cte CallTemplateExpression) IsNode() bool { return true }
func (cte CallTemplateExpression) Write(w io.Writer, indent int) error {
return writeIndent(w, indent, `{%! `+cte.Expression.Value+` %}`)
}
// {% if p.Type == "test" && p.thing %}
// {% endif %}
type IfExpression struct {
Expression Expression
Then []Node
Else []Node
}
func (n IfExpression) IsNode() bool { return true }
func (n IfExpression) Write(w io.Writer, indent int) error {
if err := writeIndent(w, indent, "{% if "+n.Expression.Value+" %}\n"); err != nil {
return err
}
indent++
if err := writeNodesBlock(w, indent, n.Then); err != nil {
return err
}
indent--
if len(n.Else) > 0 {
if err := writeIndent(w, indent, "{% else %}\n"); err != nil {
return err
}
if err := writeNodesBlock(w, indent+1, n.Else); err != nil {
return err
}
}
if err := writeIndent(w, indent, "{% endif %}"); err != nil {
return err
}
return nil
}
// {% switch p.Type %}
//
// {% case "Something" %}
// {% endcase %}
//
// {% endswitch %}
type SwitchExpression struct {
Expression Expression
Cases []CaseExpression
Default []Node
}
func (se SwitchExpression) IsNode() bool { return true }
func (se SwitchExpression) Write(w io.Writer, indent int) error {
if err := writeIndent(w, indent, "{% switch "+se.Expression.Value+" %}\n"); err != nil {
return err
}
indent++
for i := 0; i < len(se.Cases); i++ {
c := se.Cases[i]
if err := writeIndent(w, indent, "{% case "+c.Expression.Value+" %}\n"); err != nil {
return err
}
if err := writeNodesBlock(w, indent+1, c.Children); err != nil {
return err
}
if err := writeIndent(w, indent, "{% endcase %}\n"); err != nil {
return err
}
}
if len(se.Default) > 0 {
if err := writeIndent(w, indent, "{% default %}\n"); err != nil {
return err
}
if err := writeNodesBlock(w, indent+1, se.Default); err != nil {
return err
}
if err := writeIndent(w, indent, "{% enddefault %}\n"); err != nil {
return err
}
}
indent--
if err := writeIndent(w, indent, "{% endswitch %}"); err != nil {
return err
}
return nil
}
// {% case "Something" %}
// ...
// {% endcase %}
type CaseExpression struct {
Expression Expression
Children []Node
}
// {% for i, v := range p.Addresses %}
//
// {% call Address(v) %}
//
// {% endfor %}
type ForExpression struct {
Expression Expression
Children []Node
}
func (fe ForExpression) IsNode() bool { return true }
func (fe ForExpression) Write(w io.Writer, indent int) error {
if err := writeIndent(w, indent, "{% for "+fe.Expression.Value+" %}\n"); err != nil {
return err
}
if err := writeNodesBlock(w, indent+1, fe.Children); err != nil {
return err
}
if err := writeIndent(w, indent, "{% endfor %}"); err != nil {
return err
}
return nil
}
// StringExpression is used within HTML elements, and for style values.
// {%= ... %}
type StringExpression struct {
Expression Expression
}
func (se StringExpression) IsNode() bool { return true }
func (se StringExpression) IsStyleDeclarationValue() bool { return true }
func (se StringExpression) Write(w io.Writer, indent int) error {
return writeIndent(w, indent, `{%= `+se.Expression.Value+` %}`)
}
// ScriptTemplate is a script block.
type ScriptTemplate struct {
Name Expression
Parameters Expression
Value string
}
func (s ScriptTemplate) IsTemplateFileNode() bool { return true }
func (s ScriptTemplate) Write(w io.Writer, indent int) error {
if err := writeIndent(w, indent, "{% script "+s.Name.Value+"("+s.Parameters.Value+") %}\n"); err != nil {
return err
}
if _, err := io.WriteString(w, s.Value); err != nil {
return err
}
if err := writeIndent(w, indent, "{% endscript %}"); err != nil {
return err
}
return nil
}