Debian Codegraph @

hugolib/page__per_output.go

raw
1 // Copyright 2019 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 hugolib
15
16 import (
17 "context"
18 "errors"
19 "fmt"
20 "html/template"
21 "sync"
22 "sync/atomic"
23
24 "github.com/gohugoio/hugo/common/hmaps"
25 "github.com/gohugoio/hugo/common/text"
26 "github.com/gohugoio/hugo/identity"
27 "github.com/gohugoio/hugo/tpl/tplimpl"
28 "github.com/spf13/cast"
29
30 "github.com/gohugoio/hugo/markup/converter/hooks"
31 gc "github.com/gohugoio/hugo/markup/goldmark/goldmark_config"
32 "github.com/gohugoio/hugo/markup/tableofcontents"
33
34 "github.com/gohugoio/hugo/markup/converter"
35
36 bp "github.com/gohugoio/hugo/bufferpool"
37
38 "github.com/gohugoio/hugo/output"
39 "github.com/gohugoio/hugo/resources/page"
40 "github.com/gohugoio/hugo/resources/resource"
41 )
42
43 var (
44 nopTargetPath = targetPathsHolder{}
45 nopPagePerOutput = struct {
46 resource.ResourceLinksProvider
47 page.ContentProvider
48 page.PageRenderProvider
49 page.PaginatorProvider
50 page.TableOfContentsProvider
51 page.AlternativeOutputFormatsProvider
52
53 targetPather
54 }{
55 page.NopPage,
56 page.NopPage,
57 page.NopPage,
58 page.NopPage,
59 page.NopPage,
60 page.NopPage,
61 nopTargetPath,
62 }
63 )
64
65 func newPageContentOutput(po *pageOutput) (*pageContentOutput, error) {
66 cp := &pageContentOutput{
67 po: po,
68 renderHooks: &renderHooks{},
69 otherOutputs: hmaps.NewCache[uint64, *pageContentOutput](),
70 }
71 return cp, nil
72 }
73
74 type renderHooks struct {
75 getRenderer hooks.GetRendererFunc
76 init sync.Once
77 }
78
79 // pageContentOutput represents the Page content for a given output format.
80 type pageContentOutput struct {
81 po *pageOutput
82
83 // Other pages involved in rendering of this page,
84 // typically included with .RenderShortcodes.
85 otherOutputs *hmaps.Cache[uint64, *pageContentOutput]
86
87 contentRenderedVersion uint32 // Incremented on reset.
88 contentRendered atomic.Bool // Set on content render.
89
90 // Renders Markdown hooks.
91 renderHooks *renderHooks
92 }
93
94 func (pco *pageContentOutput) trackDependency(idp identity.IdentityProvider) {
95 pco.po.p.dependencyManagerOutput.AddIdentity(idp.GetIdentity())
96 }
97
98 func (pco *pageContentOutput) Reset() {
99 if pco == nil {
100 return
101 }
102 pco.contentRenderedVersion++
103 pco.contentRendered.Store(false)
104 pco.renderHooks = &renderHooks{}
105 }
106
107 func (pco *pageContentOutput) Render(ctx context.Context, args ...any) (template.HTML, error) {
108 if len(args) == 0 {
109 return "", errors.New("no view given")
110 }
111 if len(args) > 2 {
112 return "", errors.New("too many arguments, expected VIEW [CONTEXT]")
113 }
114 view, err := cast.ToStringE(args[0])
115 if err != nil {
116 return "", fmt.Errorf("failed to convert view argument to string: %w", err)
117 }
118
119 // Make sure to send the *pageState and not the *pageContentOutput to the template.
120 var data any = pco.po.p
121 if len(args) == 2 {
122 data = args[1]
123 }
124
125 templ, found, err := pco.po.p.resolveTemplate(view)
126 if err != nil {
127 return "", pco.po.p.wrapError(err)
128 }
129
130 if !found {
131 return "", fmt.Errorf("template %q not found", view)
132 }
133
134 res, err := executeToString(ctx, pco.po.p.s.GetTemplateStore(), templ, data)
135 if err != nil {
136 return "", pco.po.p.wrapError(fmt.Errorf("failed to execute template %s: %w", templ.Name(), err))
137 }
138 return template.HTML(res), nil
139 }
140
141 func (pco *pageContentOutput) Fragments(ctx context.Context) *tableofcontents.Fragments {
142 return pco.c().Fragments(ctx)
143 }
144
145 func (pco *pageContentOutput) RenderShortcodes(ctx context.Context) (template.HTML, error) {
146 return pco.c().RenderShortcodes(ctx)
147 }
148
149 func (pco *pageContentOutput) Markup(opts ...any) page.Markup {
150 if len(opts) > 1 {
151 panic("too many arguments, expected 0 or 1")
152 }
153 var scope string
154 if len(opts) == 1 {
155 scope = cast.ToString(opts[0])
156 }
157 return pco.po.p.m.content.getOrCreateScope(scope, pco)
158 }
159
160 func (pco *pageContentOutput) c() page.Markup {
161 return pco.po.p.m.content.getOrCreateScope("", pco)
162 }
163
164 func (pco *pageContentOutput) Content(ctx context.Context) (any, error) {
165 r, err := pco.c().Render(ctx)
166 if err != nil {
167 return nil, err
168 }
169 return r.Content(ctx)
170 }
171
172 func (pco *pageContentOutput) ContentWithoutSummary(ctx context.Context) (template.HTML, error) {
173 r, err := pco.c().Render(ctx)
174 if err != nil {
175 return "", err
176 }
177 return r.ContentWithoutSummary(ctx)
178 }
179
180 func (pco *pageContentOutput) TableOfContents(ctx context.Context) template.HTML {
181 return pco.c().(*cachedContentScope).fragmentsHTML(ctx)
182 }
183
184 func (pco *pageContentOutput) Len(ctx context.Context) int {
185 return pco.mustRender(ctx).Len(ctx)
186 }
187
188 func (pco *pageContentOutput) mustRender(ctx context.Context) page.Content {
189 c, err := pco.c().Render(ctx)
190 if err != nil {
191 pco.fail(err)
192 }
193 return c
194 }
195
196 func (pco *pageContentOutput) fail(err error) {
197 pco.po.p.s.h.FatalError(pco.po.p.wrapError(err))
198 }
199
200 func (pco *pageContentOutput) Plain(ctx context.Context) string {
201 return pco.mustRender(ctx).Plain(ctx)
202 }
203
204 func (pco *pageContentOutput) PlainWords(ctx context.Context) []string {
205 return pco.mustRender(ctx).PlainWords(ctx)
206 }
207
208 func (pco *pageContentOutput) ReadingTime(ctx context.Context) int {
209 return pco.mustRender(ctx).ReadingTime(ctx)
210 }
211
212 func (pco *pageContentOutput) WordCount(ctx context.Context) int {
213 return pco.mustRender(ctx).WordCount(ctx)
214 }
215
216 func (pco *pageContentOutput) FuzzyWordCount(ctx context.Context) int {
217 return pco.mustRender(ctx).FuzzyWordCount(ctx)
218 }
219
220 func (pco *pageContentOutput) Summary(ctx context.Context) template.HTML {
221 summary, err := pco.mustRender(ctx).Summary(ctx)
222 if err != nil {
223 pco.fail(err)
224 }
225 return summary.Text
226 }
227
228 func (pco *pageContentOutput) Truncated(ctx context.Context) bool {
229 summary, err := pco.mustRender(ctx).Summary(ctx)
230 if err != nil {
231 pco.fail(err)
232 }
233 return summary.Truncated
234 }
235
236 func (pco *pageContentOutput) RenderString(ctx context.Context, args ...any) (template.HTML, error) {
237 return pco.c().RenderString(ctx, args...)
238 }
239
240 func (pco *pageContentOutput) initRenderHooks() error {
241 if pco == nil {
242 return nil
243 }
244
245 pco.renderHooks.init.Do(func() {
246 if pco.po.p.pageOutputTemplateVariationsState.Load() == 0 {
247 pco.po.p.pageOutputTemplateVariationsState.Store(1)
248 }
249
250 type cacheKey struct {
251 tp hooks.RendererType
252 id any
253 f output.Format
254 }
255
256 renderCache := make(map[cacheKey]any)
257 var renderCacheMu sync.Mutex
258
259 resolvePosition := func(renderContext any, pos int) text.Position {
260 rc, ok := renderContext.(converter.RenderContext)
261 var si sourceInfo
262 if ok {
263 si, ok = rc.SourceInfo.(sourceInfo)
264 }
265
266 if pos == -1 || !ok {
267 return text.Position{
268 Filename: pco.po.p.pathOrTitle(),
269 }
270 }
271 offset := resolveSourceOffset(si.sourceMap, pos)
272 filename := si.filename
273 if filename == "" {
274 filename = pco.po.p.pathOrTitle()
275 }
276
277 return posFromInput(filename, si.source, offset)
278 }
279
280 pco.renderHooks.getRenderer = func(tp hooks.RendererType, id any) any {
281 renderCacheMu.Lock()
282 defer renderCacheMu.Unlock()
283
284 key := cacheKey{tp: tp, id: id, f: pco.po.f}
285 if r, ok := renderCache[key]; ok {
286 return r
287 }
288
289 // Inherit the descriptor from the page/current output format.
290 // This allows for fine-grained control of the template used for
291 // rendering of e.g. links.
292 base, layoutDescriptor := pco.po.p.GetInternalTemplateBasePathAndDescriptor()
293
294 switch tp {
295 case hooks.LinkRendererType:
296 layoutDescriptor.Variant1 = "link"
297 case hooks.ImageRendererType:
298 layoutDescriptor.Variant1 = "image"
299 case hooks.HeadingRendererType:
300 layoutDescriptor.Variant1 = "heading"
301 case hooks.PassthroughRendererType:
302 layoutDescriptor.Variant1 = "passthrough"
303 if id != nil {
304 layoutDescriptor.Variant2 = id.(string)
305 }
306 case hooks.BlockquoteRendererType:
307 layoutDescriptor.Variant1 = "blockquote"
308 if id != nil {
309 layoutDescriptor.Variant2 = id.(string)
310 }
311 case hooks.TableRendererType:
312 layoutDescriptor.Variant1 = "table"
313 case hooks.CodeBlockRendererType:
314 layoutDescriptor.Variant1 = "codeblock"
315 if id != nil {
316 layoutDescriptor.Variant2 = id.(string)
317 }
318 }
319
320 renderHookConfig := pco.po.p.s.conf.Markup.Goldmark.RenderHooks
321 var ignoreEmbedded bool
322
323 // For multilingual single-host sites, "auto" becomes "fallback"
324 // earlier in the process.
325 switch layoutDescriptor.Variant1 {
326 case "link":
327 ignoreEmbedded = renderHookConfig.Link.UseEmbedded == gc.RenderHookUseEmbeddedNever ||
328 renderHookConfig.Link.UseEmbedded == gc.RenderHookUseEmbeddedAuto
329 case "image":
330 ignoreEmbedded = renderHookConfig.Image.UseEmbedded == gc.RenderHookUseEmbeddedNever ||
331 renderHookConfig.Image.UseEmbedded == gc.RenderHookUseEmbeddedAuto
332 }
333
334 candidates := pco.po.p.s.renderFormats
335 var numCandidatesFound int
336 consider := func(candidate *tplimpl.TemplInfo) bool {
337 if layoutDescriptor.Variant1 != candidate.D.Variant1 {
338 return false
339 }
340
341 if layoutDescriptor.Variant2 != "" && candidate.D.Variant2 != "" && layoutDescriptor.Variant2 != candidate.D.Variant2 {
342 return false
343 }
344
345 if ignoreEmbedded && candidate.SubCategory() == tplimpl.SubCategoryEmbedded {
346 // Don't consider the embedded hook templates.
347 return false
348 }
349
350 if pco.po.p.pageOutputTemplateVariationsState.Load() > 1 {
351 return true
352 }
353
354 if candidate.D.OutputFormat == "" {
355 numCandidatesFound++
356 } else if _, found := candidates.GetByName(candidate.D.OutputFormat); found {
357 numCandidatesFound++
358 }
359
360 return true
361 }
362
363 getHookTemplate := func() (*tplimpl.TemplInfo, bool) {
364 q := tplimpl.TemplateQuery{
365 Path: base,
366 Category: tplimpl.CategoryMarkup,
367 Desc: layoutDescriptor,
368 Sites: pco.po.p.s.siteVector,
369 Consider: consider,
370 }
371
372 v := pco.po.p.s.TemplateStore.LookupPagesLayout(q)
373
374 return v, v != nil
375 }
376
377 templ, found1 := getHookTemplate()
378 if found1 && templ == nil {
379 panic("found1 is true, but templ is nil")
380 }
381
382 if !found1 && layoutDescriptor.OutputFormat == pco.po.p.s.conf.DefaultOutputFormat {
383 numCandidatesFound++
384 }
385
386 if numCandidatesFound > 1 {
387 // More than one output format candidate found for this hook temoplate,
388 // so we cannot reuse the same rendered content.
389 pco.po.p.incrPageOutputTemplateVariation()
390 }
391
392 if !found1 {
393 if tp == hooks.CodeBlockRendererType {
394 // No user provided template for code blocks, so we use the native Go version -- which is also faster.
395 r := pco.po.p.s.ContentSpec.Converters.GetHighlighter()
396 renderCache[key] = r
397 return r
398 }
399 return nil
400 }
401
402 r := hookRendererTemplate{
403 templateHandler: pco.po.p.s.GetTemplateStore(),
404 templ: templ,
405 resolvePosition: resolvePosition,
406 }
407 renderCache[key] = r
408 return r
409 }
410 })
411
412 return nil
413 }
414
415 func (pco *pageContentOutput) getContentConverter() (converter.Converter, error) {
416 if err := pco.initRenderHooks(); err != nil {
417 return nil, err
418 }
419 return pco.po.p.getContentConverter(), nil
420 }
421
422 func (cp *pageContentOutput) ParseAndRenderContent(ctx context.Context, content []byte, renderTOC bool) (converter.ResultRender, error) {
423 c, err := cp.getContentConverter()
424 if err != nil {
425 return nil, err
426 }
427 si := sourceInfo{
428 source: content,
429 }
430 return cp.renderContentWithConverter(ctx, c, content, si, renderTOC)
431 }
432
433 func (pco *pageContentOutput) ParseContent(ctx context.Context, content []byte) (converter.ResultParse, bool, error) {
434 c, err := pco.getContentConverter()
435 if err != nil {
436 return nil, false, err
437 }
438 p, ok := c.(converter.ParseRenderer)
439 if !ok {
440 return nil, ok, nil
441 }
442 rctx := converter.RenderContext{
443 Ctx: ctx,
444 Src: content,
445 RenderTOC: true,
446 GetRenderer: pco.renderHooks.getRenderer,
447 }
448 r, err := p.Parse(rctx)
449 return r, ok, err
450 }
451
452 func (pco *pageContentOutput) RenderContent(ctx context.Context, content []byte, sourceInfo, doc any) (converter.ResultRender, bool, error) {
453 c, err := pco.getContentConverter()
454 if err != nil {
455 return nil, false, err
456 }
457 p, ok := c.(converter.ParseRenderer)
458 if !ok {
459 return nil, ok, nil
460 }
461 rctx := converter.RenderContext{
462 Ctx: ctx,
463 Src: content,
464 SourceInfo: sourceInfo,
465 RenderTOC: true,
466 GetRenderer: pco.renderHooks.getRenderer,
467 }
468 r, err := p.Render(rctx, doc)
469 return r, ok, err
470 }
471
472 func (pco *pageContentOutput) renderContentWithConverter(ctx context.Context, c converter.Converter, content []byte, sourceInfo any, renderTOC bool) (converter.ResultRender, error) {
473 r, err := c.Convert(
474 converter.RenderContext{
475 Ctx: ctx,
476 Src: content,
477 SourceInfo: sourceInfo,
478 RenderTOC: renderTOC,
479 GetRenderer: pco.renderHooks.getRenderer,
480 })
481 return r, err
482 }
483
484 // these will be shifted out when rendering a given output format.
485 type pagePerOutputProviders interface {
486 targetPather
487 page.PaginatorProvider
488 resource.ResourceLinksProvider
489 }
490
491 type targetPather interface {
492 targetPaths() page.TargetPaths
493 getRelURL() string
494 }
495
496 type targetPathsHolder struct {
497 // relURL is usually the same as OutputFormat.RelPermalink, but can be different
498 // for non-permalinkable output formats. These shares RelPermalink with the main (first) output format.
499 relURL string
500 paths page.TargetPaths
501 page.OutputFormat
502 }
503
504 func (t targetPathsHolder) getRelURL() string {
505 return t.relURL
506 }
507
508 func (t targetPathsHolder) targetPaths() page.TargetPaths {
509 return t.paths
510 }
511
512 func executeToString(ctx context.Context, h *tplimpl.TemplateStore, templ *tplimpl.TemplInfo, data any) (string, error) {
513 b := bp.GetBuffer()
514 defer bp.PutBuffer(b)
515 if err := h.ExecuteWithContext(ctx, templ, b, data); err != nil {
516 return "", err
517 }
518 return b.String(), nil
519 }