From 9e2b7620b101f9b0d7352ce313eb90714f5118c5 Mon Sep 17 00:00:00 2001 From: Matt Baer Date: Tue, 4 Apr 2023 12:09:49 -0400 Subject: [PATCH] Add funcs PostTitle, GetSlug, GetSlugFromPost --- go.mod | 2 +- posts/parse.go | 46 +++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/go.mod b/go.mod index 5170100..1955354 100644 --- a/go.mod +++ b/go.mod @@ -8,7 +8,7 @@ require ( github.com/microcosm-cc/bluemonday v1.0.5 github.com/rainycape/unidecode v0.0.0-20150907023854-cb7f23ec59be // indirect github.com/shurcooL/sanitized_anchor_name v1.0.0 // indirect - github.com/writeas/go-strip-markdown v2.0.1+incompatible + github.com/writeas/go-strip-markdown/v2 v2.1.1 github.com/writeas/impart v1.1.1 github.com/writeas/openssl-go v1.0.0 github.com/writeas/saturday v1.7.1 diff --git a/posts/parse.go b/posts/parse.go index 168289f..0d61bac 100644 --- a/posts/parse.go +++ b/posts/parse.go @@ -2,7 +2,8 @@ package posts import ( "fmt" - stripmd "github.com/writeas/go-strip-markdown" + stripmd "github.com/writeas/go-strip-markdown/v2" + "github.com/writeas/slug" "github.com/writeas/web-core/stringmanip" "regexp" "strings" @@ -37,6 +38,20 @@ func ExtractTitle(content string) (title string, body string) { return } +func PostTitle(content, friendlyId string) string { + content = StripHTMLWithoutEscaping(content) + + content = strings.TrimLeftFunc(stripmd.Strip(content), unicode.IsSpace) + eol := strings.IndexRune(content, '\n') + blankLine := strings.Index(content, "\n\n") + if blankLine != -1 && blankLine <= eol && blankLine <= assumedTitleLen { + return strings.TrimSpace(content[:blankLine]) + } else if utf8.RuneCountInString(content) <= maxTitleLen { + return content + } + return friendlyId +} + func FriendlyPostTitle(content, friendlyId string) string { content = StripHTMLWithoutEscaping(content) @@ -163,3 +178,32 @@ func PostLede(t string, includePunc bool) string { return t } + +func GetSlug(title, lang string) string { + return GetSlugFromPost("", title, lang) +} + +func GetSlugFromPost(title, body, lang string) string { + if title == "" { + // Remove Markdown, so e.g. link URLs and image alt text don't make it into the slug + body = strings.TrimSpace(stripmd.StripOptions(body, stripmd.Options{SkipImages: true})) + title = PostTitle(body, body) + } + title = PostLede(title, false) + // Truncate lede if needed + title, _ = TruncToWord(title, maxTitleLen) + var s string + if lang != "" && len(lang) == 2 { + s = slug.MakeLang(title, lang) + } else { + s = slug.Make(title) + } + + // Transliteration may cause the slug to expand past the limit, so truncate again + s, _ = TruncToWord(s, maxTitleLen) + return strings.TrimFunc(s, func(r rune) bool { + // TruncToWord doesn't respect words in a slug, since spaces are replaced + // with hyphens. So remove any trailing hyphens. + return r == '-' + }) +}