aboutsummaryrefslogtreecommitdiffstats
path: root/internal/web/summary.go
diff options
context:
space:
mode:
Diffstat (limited to 'internal/web/summary.go')
-rw-r--r--internal/web/summary.go62
1 files changed, 62 insertions, 0 deletions
diff --git a/internal/web/summary.go b/internal/web/summary.go
new file mode 100644
index 0000000..bc48e94
--- /dev/null
+++ b/internal/web/summary.go
@@ -0,0 +1,62 @@
+package web
+
+import (
+ "strings"
+
+ "github.com/gramanas/blogspace/internal/store"
+)
+
+// Listings can show a summary of each post instead of the whole thing
+// (theme.list_style). The blogger marks where the summary ends with
+// <!--more--> in the source; without the marker a Markdown post is cut after
+// its first summaryWords words, at a block boundary, and an HTML post is shown
+// whole (cutting hand-written markup blind would leave tags open).
+
+const (
+ moreMarker = "<!--more-->"
+ summaryWords = 70
+)
+
+// fillExcerpts sets what the list shows of each post: the summary when the
+// theme asks for one, the whole body otherwise.
+func fillExcerpts(theme Theme, posts []store.Post) {
+ for i := range posts {
+ p := &posts[i]
+ p.Excerpt, p.HasMore = p.BodyHTML, false
+ if theme.ListStyle == "summary" {
+ p.Excerpt, p.HasMore = postSummary(p)
+ }
+ }
+}
+
+// postSummary renders the part of the post a listing shows, and says whether
+// there is more to read.
+func postSummary(p *store.Post) (string, bool) {
+ if before, _, ok := strings.Cut(p.BodyMD, moreMarker); ok {
+ return renderBody(p.Format, before), true
+ }
+ if p.Format == store.FormatHTML {
+ return p.BodyHTML, false
+ }
+ head, cut := leadingBlocks(p.BodyMD, summaryWords)
+ if !cut {
+ return p.BodyHTML, false
+ }
+ return renderBody(p.Format, head), true
+}
+
+// leadingBlocks returns the blank-line separated blocks from the start of the
+// Markdown up to the first that brings the word count to n, and whether
+// anything was left out. A fenced code block is never cut in two.
+func leadingBlocks(md string, n int) (string, bool) {
+ blocks := strings.Split(md, "\n\n")
+ words, fences := 0, 0
+ for i, b := range blocks {
+ words += len(strings.Fields(b))
+ fences += strings.Count(b, "```")
+ if words >= n && fences%2 == 0 {
+ return strings.Join(blocks[:i+1], "\n\n"), i+1 < len(blocks)
+ }
+ }
+ return md, false
+}