Debian Codegraph @

resources/page/page_markup.go

raw
1 // Copyright 2024 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package page
15
16 import (
17 "context"
18 "html/template"
19 "regexp"
20 "strings"
21 "unicode"
22 "unicode/utf8"
23
24 "github.com/gohugoio/hugo/common/types"
25 "github.com/gohugoio/hugo/markup/tableofcontents"
26 "github.com/gohugoio/hugo/media"
27 "github.com/gohugoio/hugo/tpl"
28 )
29
30 type Content interface {
31 Content(context.Context) (template.HTML, error)
32 ContentWithoutSummary(context.Context) (template.HTML, error)
33 Summary(context.Context) (Summary, error)
34 Plain(context.Context) string
35 PlainWords(context.Context) []string
36 WordCount(context.Context) int
37 FuzzyWordCount(context.Context) int
38 ReadingTime(context.Context) int
39 Len(context.Context) int
40 }
41
42 type Markup interface {
43 Render(context.Context) (Content, error)
44 RenderString(ctx context.Context, args ...any) (template.HTML, error)
45 RenderShortcodes(context.Context) (template.HTML, error)
46 Fragments(context.Context) *tableofcontents.Fragments
47 }
48
49 var _ types.PrintableValueProvider = Summary{}
50
51 const (
52 SummaryTypeAuto = "auto"
53 SummaryTypeManual = "manual"
54 SummaryTypeFrontMatter = "frontmatter"
55 )
56
57 type Summary struct {
58 Text template.HTML
59 Type string // "auto", "manual" or "frontmatter"
60 Truncated bool
61 }
62
63 func (s Summary) IsZero() bool {
64 return s.Text == ""
65 }
66
67 func (s Summary) PrintableValue() any {
68 return s.Text
69 }
70
71 var _ types.PrintableValueProvider = (*Summary)(nil)
72
73 type HtmlSummary struct {
74 source string
75 SummaryLowHigh types.LowHigh[string]
76 SummaryEndTag types.LowHigh[string]
77 WrapperStart types.LowHigh[string]
78 WrapperEnd types.LowHigh[string]
79 Divider types.LowHigh[string]
80 }
81
82 func (s HtmlSummary) wrap(ss string) string {
83 if s.WrapperStart.IsZero() {
84 return ss
85 }
86 return s.source[s.WrapperStart.Low:s.WrapperStart.High] + ss + s.source[s.WrapperEnd.Low:s.WrapperEnd.High]
87 }
88
89 func (s HtmlSummary) wrapLeft(ss string) string {
90 if s.WrapperStart.IsZero() {
91 return ss
92 }
93
94 return s.source[s.WrapperStart.Low:s.WrapperStart.High] + ss
95 }
96
97 func (s HtmlSummary) Value(l types.LowHigh[string]) string {
98 return s.source[l.Low:l.High]
99 }
100
101 func (s HtmlSummary) trimSpace(ss string) string {
102 return strings.TrimSpace(ss)
103 }
104
105 func (s HtmlSummary) Content() string {
106 if s.Divider.IsZero() {
107 return s.trimSpace(s.source)
108 }
109 ss := s.source[:s.Divider.Low]
110 ss += s.source[s.Divider.High:]
111 return s.trimSpace(ss)
112 }
113
114 func (s HtmlSummary) Summary() string {
115 if s.Divider.IsZero() {
116 return s.trimSpace(s.wrap(s.Value(s.SummaryLowHigh)))
117 }
118 ss := s.source[s.SummaryLowHigh.Low:s.Divider.Low]
119 if s.SummaryLowHigh.High > s.Divider.High {
120 ss += s.source[s.Divider.High:s.SummaryLowHigh.High]
121 }
122 if !s.SummaryEndTag.IsZero() {
123 ss += s.Value(s.SummaryEndTag)
124 }
125 return s.trimSpace(s.wrap(ss))
126 }
127
128 func (s HtmlSummary) ContentWithoutSummary() string {
129 if s.Divider.IsZero() {
130 if s.SummaryLowHigh.Low == s.WrapperStart.High && s.SummaryLowHigh.High == s.WrapperEnd.Low {
131 return ""
132 }
133 return s.trimSpace(s.wrapLeft(s.source[s.SummaryLowHigh.High:]))
134 }
135 if s.SummaryEndTag.IsZero() {
136 return s.trimSpace(s.wrapLeft(s.source[s.Divider.High:]))
137 }
138 return s.trimSpace(s.wrapLeft(s.source[s.SummaryEndTag.High:]))
139 }
140
141 func (s HtmlSummary) Truncated() bool {
142 return s.Summary() != s.Content()
143 }
144
145 func (s *HtmlSummary) resolveParagraphTagAndSetWrapper(mt media.Type) tagReStartEnd {
146 ptag := startEndP
147
148 switch mt.SubType {
149 case media.DefaultContentTypes.AsciiDoc.SubType:
150 ptag = startEndDiv
151 case media.DefaultContentTypes.ReStructuredText.SubType:
152 const markerStart = "<div class=\"document\">"
153 const markerEnd = "</div>"
154 i1 := strings.Index(s.source, markerStart)
155 i2 := strings.LastIndex(s.source, markerEnd)
156 if i1 > -1 && i2 > -1 {
157 s.WrapperStart = types.LowHigh[string]{Low: 0, High: i1 + len(markerStart)}
158 s.WrapperEnd = types.LowHigh[string]{Low: i2, High: len(s.source)}
159 }
160 }
161 return ptag
162 }
163
164 // Avoid counting words that are most likely HTML tokens.
165 var (
166 isProbablyHTMLTag = regexp.MustCompile(`^<\/?[A-Za-z]+>?$`)
167 isProablyHTMLAttribute = regexp.MustCompile(`^[A-Za-z]+=["']`)
168 )
169
170 func isProbablyHTMLToken(s string) bool {
171 return s == ">" || isProbablyHTMLTag.MatchString(s) || isProablyHTMLAttribute.MatchString(s)
172 }
173
174 // ExtractSummaryFromHTML extracts a summary from the given HTML content.
175 func ExtractSummaryFromHTML(mt media.Type, input string, numWords int, isCJK bool) (result HtmlSummary) {
176 result.source = input
177 ptag := result.resolveParagraphTagAndSetWrapper(mt)
178
179 if numWords <= 0 {
180 return result
181 }
182
183 var count int
184
185 countWord := func(word string) int {
186 word = strings.TrimSpace(word)
187 if len(word) == 0 {
188 return 0
189 }
190 if isProbablyHTMLToken(word) {
191 return 0
192 }
193
194 if isCJK {
195 word = tpl.StripHTML(word)
196 runeCount := utf8.RuneCountInString(word)
197 if len(word) == runeCount {
198 return 1
199 } else {
200 return runeCount
201 }
202 }
203
204 return 1
205 }
206
207 high := len(input)
208 if result.WrapperEnd.Low > 0 {
209 high = result.WrapperEnd.Low
210 }
211
212 for j := result.WrapperStart.High; j < high; {
213 s := input[j:]
214 closingIndex := strings.Index(s, "</"+ptag.tagName+">")
215
216 if closingIndex == -1 {
217 break
218 }
219
220 s = s[:closingIndex]
221
222 // Count the words in the current paragraph.
223 var wi int
224
225 for i, r := range s {
226 if unicode.IsSpace(r) || (i+utf8.RuneLen(r) == len(s)) {
227 word := s[wi:i]
228 count += countWord(word)
229 wi = i
230 if count >= numWords {
231 break
232 }
233 }
234 }
235
236 if count >= numWords {
237 summaryHigh := j + closingIndex + len(ptag.tagName) + 3
238 summaryHigh = expandSummaryHighToBalancedHTML(input, result.WrapperStart.High, summaryHigh, high)
239 result.SummaryLowHigh = types.LowHigh[string]{
240 Low: result.WrapperStart.High,
241 High: summaryHigh,
242 }
243 return
244 }
245
246 j += closingIndex + len(ptag.tagName) + 2
247
248 }
249
250 result.SummaryLowHigh = types.LowHigh[string]{
251 Low: result.WrapperStart.High,
252 High: high,
253 }
254
255 return
256 }
257
258 // expandSummaryHighToBalancedHTML moves high forward until every element
259 // opened in input[low:high] is closed, so the summary does not end inside
260 // e.g. a blockquote or list item.
261 func expandSummaryHighToBalancedHTML(input string, low, high, maxHigh int) int {
262 if low >= high || high >= maxHigh {
263 return high
264 }
265
266 var buf [16]string
267 stack := buf[:0]
268 sc := htmlTagScanner{s: input, pos: low}
269
270 for {
271 name, end, ok := sc.next(high)
272 if !ok {
273 break
274 }
275 stack = pushOrPopHTMLStack(stack, name, end)
276 }
277
278 if len(stack) == 0 {
279 return high
280 }
281
282 for {
283 name, end, ok := sc.next(maxHigh)
284 if !ok {
285 return high
286 }
287 stack = pushOrPopHTMLStack(stack, name, end)
288 if len(stack) == 0 {
289 return sc.pos
290 }
291 }
292 }
293
294 func pushOrPopHTMLStack(stack []string, name string, end bool) []string {
295 if end {
296 for i := len(stack) - 1; i >= 0; i-- {
297 if stack[i] == name {
298 return stack[:i]
299 }
300 }
301 return stack
302 }
303 if isVoidHTMLElement(name) {
304 return stack
305 }
306 return append(stack, name)
307 }
308
309 // htmlTagScanner is a minimal, allocation-free scanner for start and end tags.
310 // It skips comments, quoted attribute values and raw text elements.
311 type htmlTagScanner struct {
312 s string
313 pos int
314 }
315
316 // next returns the lowercased name of the next tag before limit and
317 // whether it is an end tag. ok is false when no more tags are found.
318 func (sc *htmlTagScanner) next(limit int) (name string, end, ok bool) {
319 for {
320 i := strings.IndexByte(sc.s[sc.pos:limit], '<')
321 if i == -1 {
322 sc.pos = limit
323 return "", false, false
324 }
325 sc.pos += i + 1
326 if sc.pos >= limit {
327 return "", false, false
328 }
329
330 end = false
331 switch c := sc.s[sc.pos]; c {
332 case '!', '?':
333 if strings.HasPrefix(sc.s[sc.pos:limit], "!--") {
334 sc.skipPast(limit, "-->")
335 } else {
336 sc.skipPast(limit, ">")
337 }
338 continue
339 case '/':
340 end = true
341 sc.pos++
342 }
343
344 start := sc.pos
345 for sc.pos < limit && isHTMLTagNameByte(sc.s[sc.pos]) {
346 sc.pos++
347 }
348 if sc.pos == start {
349 continue
350 }
351 name = strings.ToLower(sc.s[start:sc.pos])
352
353 selfClosing := false
354 for sc.pos < limit {
355 c := sc.s[sc.pos]
356 sc.pos++
357 switch c {
358 case '"', '\'':
359 sc.skipPast(limit, string(c))
360 case '/':
361 selfClosing = true
362 case '>':
363 if selfClosing {
364 continue
365 }
366 if !end && isRawTextHTMLElement(name) {
367 sc.skipPastEndTag(limit, name)
368 }
369 return name, end, true
370 default:
371 selfClosing = false
372 }
373 }
374 return name, end, true
375 }
376 }
377
378 func (sc *htmlTagScanner) skipPast(limit int, sep string) {
379 if i := strings.Index(sc.s[sc.pos:limit], sep); i == -1 {
380 sc.pos = limit
381 } else {
382 sc.pos += i + len(sep)
383 }
384 }
385
386 func (sc *htmlTagScanner) skipPastEndTag(limit int, name string) {
387 for {
388 sc.skipPast(limit, "</")
389 if sc.pos >= limit {
390 return
391 }
392 if rest := sc.s[sc.pos:limit]; len(rest) > len(name) && strings.EqualFold(rest[:len(name)], name) && !isHTMLTagNameByte(rest[len(name)]) {
393 sc.pos -= 2
394 return
395 }
396 }
397 }
398
399 func isHTMLTagNameByte(c byte) bool {
400 return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-'
401 }
402
403 func isRawTextHTMLElement(name string) bool {
404 switch name {
405 case "script", "style", "textarea", "title", "iframe", "xmp", "noembed", "noframes":
406 return true
407 }
408 return false
409 }
410
411 func isVoidHTMLElement(name string) bool {
412 switch name {
413 case "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr":
414 return true
415 }
416 return false
417 }
418
419 // ExtractSummaryFromHTMLWithDivider extracts a summary from the given HTML content with
420 // a manual summary divider.
421 func ExtractSummaryFromHTMLWithDivider(mt media.Type, input, divider string) (result HtmlSummary) {
422 result.source = input
423 result.Divider.Low = strings.Index(input, divider)
424 result.Divider.High = result.Divider.Low + len(divider)
425
426 if result.Divider.Low == -1 {
427 // No summary.
428 return
429 }
430
431 ptag := result.resolveParagraphTagAndSetWrapper(mt)
432
433 if !mt.IsHTML() {
434 result.Divider, result.SummaryEndTag = expandSummaryDivider(result.source, ptag, result.Divider)
435 }
436
437 result.SummaryLowHigh = types.LowHigh[string]{
438 Low: result.WrapperStart.High,
439 High: result.Divider.Low,
440 }
441
442 return
443 }
444
445 var (
446 pOrDiv = regexp.MustCompile(`<p[^>]?>|<div[^>]?>$`)
447
448 startEndDiv = tagReStartEnd{
449 startEndOfString: regexp.MustCompile(`<div[^>]*?>$`),
450 endEndOfString: regexp.MustCompile(`</div>$`),
451 tagName: "div",
452 }
453
454 startEndP = tagReStartEnd{
455 startEndOfString: regexp.MustCompile(`<p[^>]*?>$`),
456 endEndOfString: regexp.MustCompile(`</p>$`),
457 tagName: "p",
458 }
459 )
460
461 type tagReStartEnd struct {
462 startEndOfString *regexp.Regexp
463 endEndOfString *regexp.Regexp
464 tagName string
465 }
466
467 func expandSummaryDivider(s string, re tagReStartEnd, divider types.LowHigh[string]) (types.LowHigh[string], types.LowHigh[string]) {
468 var endMarkup types.LowHigh[string]
469
470 if divider.IsZero() {
471 return divider, endMarkup
472 }
473
474 lo, hi := divider.Low, divider.High
475
476 var preserveEndMarkup bool
477
478 // Find the start of the paragraph.
479
480 for i := lo - 1; i >= 0; i-- {
481 if s[i] == '>' {
482 if match := re.startEndOfString.FindString(s[:i+1]); match != "" {
483 lo = i - len(match) + 1
484 break
485 }
486 if match := pOrDiv.FindString(s[:i+1]); match != "" {
487 i -= len(match) - 1
488 continue
489 }
490 }
491
492 r, _ := utf8.DecodeRuneInString(s[i:])
493 if !unicode.IsSpace(r) {
494 preserveEndMarkup = true
495 break
496 }
497 }
498
499 divider.Low = lo
500
501 // Now walk forward to the end of the paragraph.
502 for ; hi < len(s); hi++ {
503 if s[hi] != '>' {
504 continue
505 }
506 if match := re.endEndOfString.FindString(s[:hi+1]); match != "" {
507 hi++
508 break
509 }
510 }
511
512 if preserveEndMarkup {
513 endMarkup.Low = divider.High
514 endMarkup.High = hi
515 } else {
516 divider.High = hi
517 }
518
519 // Consume trailing newline if any.
520 if divider.High < len(s) && s[divider.High] == '\n' {
521 divider.High++
522 }
523
524 return divider, endMarkup
525 }