Skip to content

Commit

Permalink
Add funcs PostTitle, GetSlug, GetSlugFromPost
Browse files Browse the repository at this point in the history
  • Loading branch information
thebaer committed Apr 4, 2023
1 parent b5516d2 commit 9e2b762
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 2 deletions.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
46 changes: 45 additions & 1 deletion posts/parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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 == '-'
})
}

0 comments on commit 9e2b762

Please sign in to comment.