Add Markdown parsing to the preview

main
Jack Punter 2024-05-06 19:35:53 +01:00
parent cb425edd8b
commit 6c42b31ae9
5 changed files with 94 additions and 54 deletions

2
go.mod
View File

@ -3,3 +3,5 @@ module send_email_site
go 1.21.6 go 1.21.6
require github.com/pelletier/go-toml/v2 v2.2.1 require github.com/pelletier/go-toml/v2 v2.2.1
require github.com/russross/blackfriday/v2 v2.1.0

2
go.sum
View File

@ -5,6 +5,8 @@ github.com/pelletier/go-toml/v2 v2.2.1 h1:9TA9+T8+8CUCO2+WYnDLCgrYi9+omqKXyjDtos
github.com/pelletier/go-toml/v2 v2.2.1/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= github.com/pelletier/go-toml/v2 v2.2.1/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=

97
main.go
View File

@ -16,6 +16,7 @@ import (
"time" "time"
"github.com/pelletier/go-toml/v2" "github.com/pelletier/go-toml/v2"
"github.com/russross/blackfriday/v2"
) )
// ------------- Api configs ------------- // ------------- Api configs -------------
@ -68,6 +69,48 @@ func ParseArguments(rawArgs string) map[string]string {
return result return result
} }
/*
* This is taken directly from the https://git.handmadecities.com/meetups/meetupinvite2000 repo
* Although I have added the blackfriday processing to it rather than doing it separately.
*/
func parseMailFile(contents string) (subject string, body string, valid bool) {
/* Remove leading and trailing newlines */
/* *** */
contents = strings.TrimSpace(contents)
lines := strings.Split(contents, "\n")
/* Check if there is at least one line */
/* *** */
if len(lines) == 0 {
return "", "", false
}
/* Check if the first line is a title with the '#' Markdown symbol */
/* *** */
if strings.HasPrefix(lines[0], "#") { // Extract subject without the '#' symbol and leading/trailing spaces
subject = strings.TrimSpace(strings.TrimPrefix(lines[0], "#"))
} else {
// If the first line is not a title, return an error
return "", "", false
}
/* Concatenate the remaining lines to form the body */
/* *** */
body = strings.Join(lines[1:], "\n")
/* Check if the body is not empty */
/* *** */
if body == "" {
return "", "", false
}
html := blackfriday.Run([]byte(body))
/* If all checks pass, set valid to true */
/* *** */
return subject, string(html), true
}
func GetMailingList(cfg ApiConfig) []string { func GetMailingList(cfg ApiConfig) []string {
type EmailsResonse struct { type EmailsResonse struct {
Emails []string `json:"emails"` Emails []string `json:"emails"`
@ -123,47 +166,34 @@ func main() {
} }
defer r.Body.Close() defer r.Body.Close()
arguments := ParseArguments(string(body)) arguments := ParseArguments(string(body))
// textarea_content := string(body)
email_content, err := url.QueryUnescape(arguments["email_input"]) decoded_markdown, err := url.QueryUnescape(arguments["email_input"])
if err != nil { if err != nil {
panic(err) panic(err)
} }
subject, html_body, valid := parseMailFile(decoded_markdown)
if !valid {
log.Print("Failed to parse the provided markdown")
return
}
// Return a response to HTMX // Return a response to HTMX
model := PostmarkTemplateModel{ model := PostmarkTemplateModel{
Name: apiConfig.Postmark.SenderName, Name: apiConfig.Postmark.SenderName,
Email: apiConfig.Postmark.SenderEmail, Email: apiConfig.Postmark.SenderEmail,
Body: email_content, Body: html_body,
Subject: "This is a test subject", // TODO(jack): Get from user input on page Subject: subject, // TODO(jack): Get from user input on page
} }
renderedEmail := renderPostmarkTemplate(apiConfig, postmarkTemplate, model) renderedEmail := renderPostmarkTemplate(apiConfig, postmarkTemplate, model)
w.Write([]byte(renderedEmail.Html))
})
mux.HandleFunc("/subject_preview", func(w http.ResponseWriter, r *http.Request) { // Render the priview to a file so that we can include it as an Iframe as the rendered HTML is a full document.
log.Printf("%v %v", r.Method, r.URL) err = os.WriteFile("./static/preview.html", []byte(renderedEmail.Html), 0666)
body, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError) log.Panicf("Failed to write file %v", err)
return
} }
defer r.Body.Close() templates.ExecuteTemplate(w, "mail_content", renderedEmail.Subject)
arguments := ParseArguments(string(body))
decoded_subject, err := url.QueryUnescape(arguments["subject"])
if err != nil {
panic(err)
}
model := PostmarkTemplateModel{
Name: apiConfig.Postmark.SenderName,
Email: apiConfig.Postmark.SenderEmail,
Body: "",
Subject: decoded_subject, // TODO(jack): Get from user input on page
}
renderedEmail := renderPostmarkTemplate(apiConfig, postmarkTemplate, model)
w.Write([]byte(renderedEmail.Subject))
}) })
// Endpoint called on load or button press by htmx to retrieve and populate the mailing list // Endpoint called on load or button press by htmx to retrieve and populate the mailing list
@ -186,6 +216,7 @@ func main() {
body_string := string(body) body_string := string(body)
arguments := ParseArguments(body_string) arguments := ParseArguments(body_string)
fmt.Printf("%v\n", arguments) fmt.Printf("%v\n", arguments)
var recipients []string var recipients []string
if arguments["destination"] == "test" { if arguments["destination"] == "test" {
recipients = []string{apiConfig.TestEmail} recipients = []string{apiConfig.TestEmail}
@ -195,17 +226,17 @@ func main() {
panic("unknown destination in arguments") panic("unknown destination in arguments")
} }
decoded_email, err := url.QueryUnescape(arguments["email_input"]) decoded_markdown, err := url.QueryUnescape(arguments["email_input"])
if err != nil { if err != nil {
panic(err) panic(err)
} }
decoded_subject, err := url.QueryUnescape(arguments["subject"]) subject, html_body, valid := parseMailFile(decoded_markdown)
if err != nil { if !valid {
panic(err) log.Print("Failed to parse the provided markdown")
return
} }
sendBatchWithTemplate(apiConfig, html_body, subject, recipients)
sendBatchWithTemplate(apiConfig, decoded_email, decoded_subject, recipients)
}) })
srv := &http.Server{ srv := &http.Server{

View File

@ -11,29 +11,27 @@
} }
} }
* {
box-sizing: border-box;
}
body { body {
overflow-y: scroll;
overflow-x: hidden;
width: 100%; width: 100%;
height: 100%; height: 100%;
background-color: #111; background-color: #111;
color: #CCC; color: #CCC;
tab-size: 4; tab-size: 4;
line-height: 1.2; line-height: 1.2;
/* text-align: justify; */
}
body {
overflow-y: scroll;
/* Show vertical scrollbar */
} }
.main-container { .main-container {
margin-left: auto; margin-left: auto;
margin-right: auto; margin-right: auto;
width: 95%; width: 95%;
max-width: 1080px; max-width: 1280px;
padding: 1em 0 1em 0; padding: 1em 0 1em 0;
/* padding-top:1em;
padding-bottom:1em; */
} }
.content { .content {
@ -97,4 +95,5 @@ ul {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
flex-wrap: nowrap; flex-wrap: nowrap;
width: 95%;
} }

View File

@ -20,21 +20,17 @@
<h1> This is an input </h1> <h1> This is an input </h1>
<div class="row"> <div class="row">
<div class="column" stye="align-items: center"> <div class="column" stye="align-items: center">
<div style="display: flex; justify-content: space-between;"> <textarea name="email_input" id="email_input"
<span class="input_label">Subject:</span> style="resize: none; width: 100%; height: 639px; padding: 6px 10px; border-radius: 4px; font-family: inter; font-size: 1em;"
<input name="subject" type="text" id="subject" hx-post="/subject_preview"
hx-trigger="keyup changed delay:1000ms" hx-target="#subject-preview">
</div><br>
<textarea name="email_input" id="email_input" rows="32" cols="64" style="resize: none;"
hx-trigger="keyup changed delay:1000ms" hx-post="/mail-content" hx-target="#email-preview" hx-trigger="keyup changed delay:1000ms" hx-post="/mail-content" hx-target="#email-preview"
placeholder="Type out your email here..."></textarea> placeholder="Type out your email here..."></textarea>
<br> <br>
<div class="row" style="justify-content: space-around;"> <div class="row" style="justify-content: space-around;">
<button hx-post="/send_email" hx-include="[id='email_input'], [id='subject']" <button hx-post="/send_email" hx-include="[id='email_input']" hx-vals='{"destination": "test"}'
hx-vals='{"destination": "test"}' hx-swap="none"> hx-swap="none">
Send Test Email Send Test Email
</button> </button>
<button hx-post="/send_email" hx-include="[id='email_input'], [id='subject']" <button hx-post="/send_email" hx-include="[id='email_input']"
hx-vals='{"destination": "mailing_list"}' hx-vals='{"destination": "mailing_list"}'
hx-confirm="You are about to send an email to your entire mailing list. Are you sure?" hx-confirm="You are about to send an email to your entire mailing list. Are you sure?"
hx-swap="none"> hx-swap="none">
@ -44,8 +40,7 @@
</div> </div>
<div class="column"> <div class="column">
<div id="subject-preview">&nbsp;</div><br> <div id="email-preview" style="display: flex; flex-direction: column; align-items: center;"></div>
<div id="email-preview"></div>
</div> </div>
</div> </div>
@ -71,4 +66,15 @@
<li><a href="mailto:{{ . }}"> {{ . }} </a></li> <li><a href="mailto:{{ . }}"> {{ . }} </a></li>
{{end}} {{end}}
</ul> </ul>
{{end}} {{end}}
{{ block "mail_content" . }}
<div style="display: flex; flex-direction: row; width: 100%; padding-left: 4px;">
<div>Subject: </div>
<div style="padding-left: 5%;">{{ . }}</div>
</div>
<br>
<iframe src="/static/preview.html" style="width: 600px; height: 600px; border-radius: 4px;"
title="Email Preivew"></iframe>
{{ end }}