Skip to content

Commit

Permalink
support comments
Browse files Browse the repository at this point in the history
  • Loading branch information
markuswustenberg committed Oct 18, 2024
1 parent 9fd4295 commit ee66285
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 14 deletions.
30 changes: 18 additions & 12 deletions cmd/html2gomponents/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,12 +69,11 @@ func start(r io.Reader, w2 io.Writer) error {
w.Write("package html\n")
w.Write("\n")
w.Write("import (\n")
w.Write("\t. \"maragu.dev/gomponents\"\n")
w.Write("\t. \"maragu.dev/gomponents/html\"\n")
w.Write(". \"maragu.dev/gomponents\"\n")
w.Write(". \"maragu.dev/gomponents/html\"\n")
w.Write(")\n")
w.Write("\n")
w.Write("func Component() Node {\n")
w.Write("\treturn ")

z := html.NewTokenizer(r)

Expand All @@ -89,26 +88,34 @@ loop:
if err := z.Err(); err != nil {
if errors.Is(err, io.EOF) {
if !hasContent {
w.Write("nil")
w.Write("return nil")
}
break loop
}
return err
}

case html.TextToken:
text := string(z.Text())
trimmed := strings.TrimSpace(text)
if trimmed == "" {
text := strings.TrimSpace(string(z.Text()))
if text == "" {
continue
}

if !hasContent {
w.Write("return ")
}

hasContent = true
w.Write(fmt.Sprintf("Text(%q)", trimmed))
w.Write(fmt.Sprintf("Text(%q)", text))
if depth > 0 {
w.Write(",")
}

case html.StartTagToken, html.SelfClosingTagToken:
if !hasContent {
w.Write("return ")
}

if hasContent {
w.Write("\n")
}
Expand All @@ -127,12 +134,11 @@ loop:
for {
key, val, moreAttr := z.TagAttr()

name := string(key)
if attr, ok := attrs[string(key)]; ok {
w.Write(attr)
} else {
w.Write(strings.ToTitle(string(name[0])))
w.Write(name[1:])
w.Write(strings.ToTitle(string(key[0])))
w.Write(string(key[1:]))
}
w.Write("(")

Expand Down Expand Up @@ -166,7 +172,7 @@ loop:
}

case html.CommentToken:
// TODO Ignore for now
w.Write("// " + string(z.Text()) + "\n")

case html.DoctypeToken:
// TODO Ignore for now
Expand Down
2 changes: 1 addition & 1 deletion cmd/html2gomponents/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func TestStart(t *testing.T) {
t.Fatal(err)
}
if out != w.String() {
t.Fatalf("expected %q, got %q", out, w.String())
t.Fatalf("expected %v, got %v", out, w.String())
}
})
}
Expand Down
3 changes: 2 additions & 1 deletion cmd/html2gomponents/testdata/_out/comment.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,6 @@ import (
)

func Component() Node {
return nil
// halløj
return Div()
}
1 change: 1 addition & 0 deletions cmd/html2gomponents/testdata/comment.html
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
<!--halløj-->
<div></div>

0 comments on commit ee66285

Please sign in to comment.