aboutsummaryrefslogtreecommitdiffhomepage
path: root/resources/page/page_markup.go
blob: ef4a56e3a74807a7c9d306de1a543d8b1d33a116 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
// Copyright 2024 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package page

import (
	"context"
	"html/template"
	"regexp"
	"strings"
	"unicode"
	"unicode/utf8"

	"github.com/gohugoio/hugo/common/types"
	"github.com/gohugoio/hugo/markup/tableofcontents"
	"github.com/gohugoio/hugo/media"
	"github.com/gohugoio/hugo/tpl"
)

type Content interface {
	Content(context.Context) (template.HTML, error)
	ContentWithoutSummary(context.Context) (template.HTML, error)
	Summary(context.Context) (Summary, error)
	Plain(context.Context) string
	PlainWords(context.Context) []string
	WordCount(context.Context) int
	FuzzyWordCount(context.Context) int
	ReadingTime(context.Context) int
	Len(context.Context) int
}

type Markup interface {
	Render(context.Context) (Content, error)
	RenderString(ctx context.Context, args ...any) (template.HTML, error)
	RenderShortcodes(context.Context) (template.HTML, error)
	Fragments(context.Context) *tableofcontents.Fragments
}

var _ types.PrintableValueProvider = Summary{}

const (
	SummaryTypeAuto        = "auto"
	SummaryTypeManual      = "manual"
	SummaryTypeFrontMatter = "frontmatter"
)

type Summary struct {
	Text      template.HTML
	Type      string // "auto", "manual" or "frontmatter"
	Truncated bool
}

func (s Summary) IsZero() bool {
	return s.Text == ""
}

func (s Summary) PrintableValue() any {
	return s.Text
}

var _ types.PrintableValueProvider = (*Summary)(nil)

type HtmlSummary struct {
	source         string
	SummaryLowHigh types.LowHigh[string]
	SummaryEndTag  types.LowHigh[string]
	WrapperStart   types.LowHigh[string]
	WrapperEnd     types.LowHigh[string]
	Divider        types.LowHigh[string]
}

func (s HtmlSummary) wrap(ss string) string {
	if s.WrapperStart.IsZero() {
		return ss
	}
	return s.source[s.WrapperStart.Low:s.WrapperStart.High] + ss + s.source[s.WrapperEnd.Low:s.WrapperEnd.High]
}

func (s HtmlSummary) wrapLeft(ss string) string {
	if s.WrapperStart.IsZero() {
		return ss
	}

	return s.source[s.WrapperStart.Low:s.WrapperStart.High] + ss
}

func (s HtmlSummary) Value(l types.LowHigh[string]) string {
	return s.source[l.Low:l.High]
}

func (s HtmlSummary) trimSpace(ss string) string {
	return strings.TrimSpace(ss)
}

func (s HtmlSummary) Content() string {
	if s.Divider.IsZero() {
		return s.source
	}
	ss := s.source[:s.Divider.Low]
	ss += s.source[s.Divider.High:]
	return s.trimSpace(ss)
}

func (s HtmlSummary) Summary() string {
	if s.Divider.IsZero() {
		return s.trimSpace(s.wrap(s.Value(s.SummaryLowHigh)))
	}
	ss := s.source[s.SummaryLowHigh.Low:s.Divider.Low]
	if s.SummaryLowHigh.High > s.Divider.High {
		ss += s.source[s.Divider.High:s.SummaryLowHigh.High]
	}
	if !s.SummaryEndTag.IsZero() {
		ss += s.Value(s.SummaryEndTag)
	}
	return s.trimSpace(s.wrap(ss))
}

func (s HtmlSummary) ContentWithoutSummary() string {
	if s.Divider.IsZero() {
		if s.SummaryLowHigh.Low == s.WrapperStart.High && s.SummaryLowHigh.High == s.WrapperEnd.Low {
			return ""
		}
		return s.trimSpace(s.wrapLeft(s.source[s.SummaryLowHigh.High:]))
	}
	if s.SummaryEndTag.IsZero() {
		return s.trimSpace(s.wrapLeft(s.source[s.Divider.High:]))
	}
	return s.trimSpace(s.wrapLeft(s.source[s.SummaryEndTag.High:]))
}

func (s HtmlSummary) Truncated() bool {
	return s.SummaryLowHigh.High < len(s.source)
}

func (s *HtmlSummary) resolveParagraphTagAndSetWrapper(mt media.Type) tagReStartEnd {
	ptag := startEndP

	switch mt.SubType {
	case media.DefaultContentTypes.AsciiDoc.SubType:
		ptag = startEndDiv
	case media.DefaultContentTypes.ReStructuredText.SubType:
		const markerStart = "<div class=\"document\">"
		const markerEnd = "</div>"
		i1 := strings.Index(s.source, markerStart)
		i2 := strings.LastIndex(s.source, markerEnd)
		if i1 > -1 && i2 > -1 {
			s.WrapperStart = types.LowHigh[string]{Low: 0, High: i1 + len(markerStart)}
			s.WrapperEnd = types.LowHigh[string]{Low: i2, High: len(s.source)}
		}
	}
	return ptag
}

// ExtractSummaryFromHTML extracts a summary from the given HTML content.
func ExtractSummaryFromHTML(mt media.Type, input string, numWords int, isCJK bool) (result HtmlSummary) {
	result.source = input
	ptag := result.resolveParagraphTagAndSetWrapper(mt)

	if numWords <= 0 {
		return result
	}

	var count int

	countWord := func(word string) int {
		if isCJK {
			word = tpl.StripHTML(word)
			runeCount := utf8.RuneCountInString(word)
			if len(word) == runeCount {
				return 1
			} else {
				return runeCount
			}
		}

		return 1
	}

	high := len(input)
	if result.WrapperEnd.Low > 0 {
		high = result.WrapperEnd.Low
	}

	for j := result.WrapperStart.High; j < high; {
		s := input[j:]
		closingIndex := strings.Index(s, "</"+ptag.tagName)

		if closingIndex == -1 {
			break
		}

		s = s[:closingIndex]

		// Count the words in the current paragraph.
		var wi int

		for i, r := range s {
			if unicode.IsSpace(r) || (i+utf8.RuneLen(r) == len(s)) {
				word := s[wi:i]
				count += countWord(word)
				wi = i
				if count >= numWords {
					break
				}
			}
		}

		if count >= numWords {
			result.SummaryLowHigh = types.LowHigh[string]{
				Low:  result.WrapperStart.High,
				High: j + closingIndex + len(ptag.tagName) + 3,
			}
			return
		}

		j += closingIndex + len(ptag.tagName) + 2

	}

	result.SummaryLowHigh = types.LowHigh[string]{
		Low:  result.WrapperStart.High,
		High: high,
	}

	return
}

// ExtractSummaryFromHTMLWithDivider extracts a summary from the given HTML content with
// a manual summary divider.
func ExtractSummaryFromHTMLWithDivider(mt media.Type, input, divider string) (result HtmlSummary) {
	result.source = input
	result.Divider.Low = strings.Index(input, divider)
	result.Divider.High = result.Divider.Low + len(divider)

	if result.Divider.Low == -1 {
		// No summary.
		return
	}

	ptag := result.resolveParagraphTagAndSetWrapper(mt)

	if !mt.IsHTML() {
		result.Divider, result.SummaryEndTag = expandSummaryDivider(result.source, ptag, result.Divider)
	}

	result.SummaryLowHigh = types.LowHigh[string]{
		Low:  result.WrapperStart.High,
		High: result.Divider.Low,
	}

	return
}

var (
	pOrDiv = regexp.MustCompile(`<p[^>]?>|<div[^>]?>$`)

	startEndDiv = tagReStartEnd{
		startEndOfString: regexp.MustCompile(`<div[^>]*?>$`),
		endEndOfString:   regexp.MustCompile(`</div>$`),
		tagName:          "div",
	}

	startEndP = tagReStartEnd{
		startEndOfString: regexp.MustCompile(`<p[^>]*?>$`),
		endEndOfString:   regexp.MustCompile(`</p>$`),
		tagName:          "p",
	}
)

type tagReStartEnd struct {
	startEndOfString *regexp.Regexp
	endEndOfString   *regexp.Regexp
	tagName          string
}

func expandSummaryDivider(s string, re tagReStartEnd, divider types.LowHigh[string]) (types.LowHigh[string], types.LowHigh[string]) {
	var endMarkup types.LowHigh[string]

	if divider.IsZero() {
		return divider, endMarkup
	}

	lo, hi := divider.Low, divider.High

	var preserveEndMarkup bool

	// Find the start of the paragraph.

	for i := lo - 1; i >= 0; i-- {
		if s[i] == '>' {
			if match := re.startEndOfString.FindString(s[:i+1]); match != "" {
				lo = i - len(match) + 1
				break
			}
			if match := pOrDiv.FindString(s[:i+1]); match != "" {
				i -= len(match) - 1
				continue
			}
		}

		r, _ := utf8.DecodeRuneInString(s[i:])
		if !unicode.IsSpace(r) {
			preserveEndMarkup = true
			break
		}
	}

	divider.Low = lo

	// Now walk forward to the end of the paragraph.
	for ; hi < len(s); hi++ {
		if s[hi] != '>' {
			continue
		}
		if match := re.endEndOfString.FindString(s[:hi+1]); match != "" {
			hi++
			break
		}
	}

	if preserveEndMarkup {
		endMarkup.Low = divider.High
		endMarkup.High = hi
	} else {
		divider.High = hi
	}

	// Consume trailing newline if any.
	if divider.High < len(s) && s[divider.High] == '\n' {
		divider.High++
	}

	return divider, endMarkup
}