summaryrefslogtreecommitdiff
path: root/layouts/_partials/utils/inject-footnotes.html
blob: 549ac75815a589f67da99ee9b3876cf90de6ad72 (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
{{ $content := . }}

{{ $footnotesPattern := `(?s)<div class="footnotes"[^>]*>.*?</div>` }}
{{ $footnotesMatch := findRE $footnotesPattern $content 1 }}

{{ if $footnotesMatch }}
  {{ $footnotesSection := index $footnotesMatch 0 }}

  {{ $liPattern := `(?s)<li id="fn:(\d+)">(.*?)</li>` }}
  {{ $footnoteItems := findRESubmatch $liPattern $footnotesSection }}

  {{ $footnoteMap := dict }}
  {{ range $footnoteItems }}
    {{ $id := index . 1 }}
    {{ $contentRaw := index . 2 }}
    {{ $cleanContent := replaceRE `(?s)\s*<a href="#fnref:\d+"[^>]*>.*?</a>\s*$` "" $contentRaw }}
    {{ $footnoteMap = merge $footnoteMap (dict $id $cleanContent) }}
  {{ end }}

  {{ $contentWithoutFootnotes := replaceRE $footnotesPattern "" $content }}

  {{ $refPattern := `<sup id="fnref:(\d+)".*?</sup>` }}
  {{ $refs := findRESubmatch $refPattern $contentWithoutFootnotes }}

  {{ $result := $contentWithoutFootnotes }}
  {{ $count := len $refs }}

  {{ range seq (sub $count 1) -1 0 }}
    {{ $ref := index $refs . }}
    {{ $refFull := index $ref 0 }}
    {{ $refId := index $ref 1 }}
    {{ $noteContent := index $footnoteMap $refId }}

    {{ if $noteContent }}
      {{ $inlineFootnote := printf `<div class="inline-footnote text-sm text-secondary flex gap-2 md:-ml-7 md:opacity-50 hover:opacity-100 transition-opacity" id="fn:%s"><span>[%s]</span><div>%s</div></div>` $refId $refId $noteContent }}

      {{ $blockTags := slice "p" "li" "td" "th" "blockquote" "h1" "h2" "h3" "h4" "h5" "h6" "figcaption" "dt" "dd" }}

      {{ $found := false }}

      {{ range $blockTags }}
        {{ if not $found }}
          {{ $tag := . }}
          {{ $pattern := printf `(?s)<%s[^>]*>.*?</%s>` $tag $tag }}
          {{ $matches := findRE $pattern $result }}

          {{ range $matches }}
            {{ if not $found }}
              {{ $block := . }}
              {{ if strings.Contains $block $refFull }}
                {{ $newBlock := printf `%s%s` $block $inlineFootnote }}
                {{ $result = replace $result $block $newBlock 1 }}
                {{ $found = true }}
              {{ end }}
            {{ end }}
          {{ end }}
        {{ end }}
      {{ end }}

      {{ if not $found }}
        {{ $replacement := printf `%s%s` $refFull $inlineFootnote }}
        {{ $result = replace $result $refFull $replacement 1 }}
      {{ end }}
    {{ end }}
  {{ end }}

  {{ $content = $result }}
{{ end }}

{{ $content | safeHTML }}