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
|
package glightbox
import (
"bytes"
"fmt"
"math/rand"
"regexp"
"strings"
"time"
"github.com/SayaAndy/saya-today-web/internal/tailwind"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/ast"
"github.com/yuin/goldmark/parser"
"github.com/yuin/goldmark/renderer"
"github.com/yuin/goldmark/renderer/html"
"github.com/yuin/goldmark/util"
)
type GLightboxHTMLRenderer struct {
html.Config
md goldmark.Markdown
anchorMatchRe *regexp.Regexp
}
func NewGLightboxHTMLRenderer(opts ...html.Option) renderer.NodeRenderer {
r := &GLightboxHTMLRenderer{
Config: html.NewConfig(),
md: goldmark.New(
goldmark.WithParserOptions(
parser.WithAutoHeadingID(),
parser.WithAttribute(),
),
goldmark.WithRenderer(
renderer.NewRenderer(
renderer.WithNodeRenderers(
util.Prioritized(tailwind.NewCustomLinkRenderer(
html.WithUnsafe(), html.WithHardWraps(), html.WithXHTML(),
), 50),
util.Prioritized(html.NewRenderer(
html.WithUnsafe(), html.WithHardWraps(), html.WithXHTML(),
), 100),
),
),
),
),
}
for _, opt := range opts {
opt.SetHTMLOption(&r.Config)
}
r.anchorMatchRe = regexp.MustCompile(`(?s)<\s*a(\s+[^<]*)(href\s*=\s*["'].*?["'])\s*([^<]*)>(.*?)<\s*\/\s*a\s*>`)
return r
}
func (r *GLightboxHTMLRenderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer) {
reg.Register(KindGLightboxBlock, r.renderGLightbox)
}
func (r *GLightboxHTMLRenderer) renderGLightbox(w util.BufWriter, source []byte, n ast.Node, entering bool) (ast.WalkStatus, error) {
if entering {
gallery := n.(*GLightboxBlock)
if len(gallery.Images) == 0 {
return ast.WalkContinue, nil
}
galleryID := generateDivId(8)
var elements []string
for i, img := range gallery.Images {
fullImageUrl := gallery.Namespace + img.URL
imageUrlSegments := strings.Split(fullImageUrl, ".")
imageUrlWithoutExt := strings.Join(imageUrlSegments[:len(imageUrlSegments)-1], ".")
imageUrlParts := strings.Split(imageUrlWithoutExt, "/")
imageNameParts := strings.Split(imageUrlParts[len(imageUrlParts)-1], "-")
var captionBuf bytes.Buffer
captionHTML := img.Caption
if err := r.md.Convert(img.Caption, &captionBuf); err == nil {
captionHTML = captionBuf.Bytes()
captionHTML = bytes.TrimPrefix(captionHTML, []byte("<p>"))
captionHTML = bytes.TrimSuffix(captionHTML, []byte("</p>\n"))
captionHTML = bytes.TrimSuffix(captionHTML, []byte("</p>"))
}
dayDate, _ := time.Parse("20060102 150405", imageNameParts[len(imageNameParts)-2]+" "+imageNameParts[len(imageNameParts)-1])
dayDate = dayDate.In(gallery.Location)
glightboxDescId := ""
if len(captionHTML) != 0 {
glightboxDescId = fmt.Sprintf("glightbox-desc-%s-%d", galleryID, i)
}
dataDescriptionAttribute := ""
if glightboxDescId != "" {
dataDescriptionAttribute = fmt.Sprintf("data-description=\".%s\"", glightboxDescId)
}
tagClassList := make([]string, 0, len(img.Tags))
for _, tag := range img.Tags {
switch tag {
case "2x":
tagClassList = append(tagClassList, "grid-item-2x")
}
}
if len(img.Caption) > 0 {
tagClassList = append(tagClassList, "grid-tooltip")
}
anchorlessCaptionHTML := r.anchorMatchRe.ReplaceAll(captionHTML, []byte("<span class=\"linklike\" $1 $3>$4</span>"))
elements = append(elements, fmt.Sprintf(`
<a href="https://f003.backblazeb2.com/file/sayana-photos/full/%s" class="glightbox grid-item %s grid-item-%s p-1"
data-gallery="gallery" data-title="%s" %s>
<picture>
<source media="(width < 800px)" srcset="https://f003.backblazeb2.com/file/sayana-photos/webp-320p/%s.webp" />
<source media="(width < 2400px)" srcset="https://f003.backblazeb2.com/file/sayana-photos/webp-560p/%s.webp" />
<source media="(width < 3200px)" srcset="https://f003.backblazeb2.com/file/sayana-photos/webp-800p/%s.webp" />
<source media="(width < 4000px)" srcset="https://f003.backblazeb2.com/file/sayana-photos/webp-1200p/%s.webp" />
<source media="(width >= 4000px)" srcset="https://f003.backblazeb2.com/file/sayana-photos/webp-1600p/%s.webp" />
<img src="https://f003.backblazeb2.com/file/sayana-photos/webp-560p/%s.webp" />
</picture>
<span class="grid-tooltip-text"><p>%s</p></span>
<span class="grid-item-index">%d</span>
</a>`, fullImageUrl, strings.Join(tagClassList, " "), galleryID, dayDate.Format("2006-01-02 15:04:05 -07:00"), dataDescriptionAttribute, imageUrlWithoutExt, imageUrlWithoutExt, imageUrlWithoutExt, imageUrlWithoutExt, imageUrlWithoutExt, imageUrlWithoutExt, anchorlessCaptionHTML, i+1))
if glightboxDescId != "" {
elements = append(elements, fmt.Sprintf(`
<div class="glightbox-desc rounded-4 %s">
<p>%s</p>
</div>`, glightboxDescId, captionHTML))
}
}
w.WriteString(strings.ReplaceAll(`
<div class="items-center flex flex-col">
<hr class="border-t-3 border-dotted border-main-hard mt-1 mb-2 w-[80%%] ml-auto mr-auto">
<div class="grid masonry-grid-{id}">
<div class="grid-sizer grid-sizer-{id}"></div>
`+strings.Join(elements, "\n")+`
</div>
<hr class="border-t-3 border-dotted border-main-hard mt-1 mb-2 w-[80%%] ml-auto mr-auto">
</div>
<script>
var pckry_{id} = new Packery('.masonry-grid-{id}', {
itemSelector: '.grid-item-{id}',
columnWidth: '.grid-sizer-{id}',
percentPosition: false
});
var imgLoad_{id}_timer;
var imgLoad_{id} = imagesLoaded('.masonry-grid-{id}');
function initMasonryLayout_{id}(tm) {
clearTimeout(imgLoad_{id}_timer);
imgLoad_{id}_timer = setTimeout(() => pckry_{id}.layout(), 100);
}
imgLoad_{id}.on('progress', initMasonryLayout_{id});
window.addEventListener('resize', initMasonryLayout_{id});
document.addEventListener('popout', (e) => {
window.removeEventListener('resize', initMasonryLayout_{id});
imgLoad_{id}.off('progress', initMasonryLayout_{id});
initMasonryLayout_{id} = null;
imgLoad_{id} = null;
}, {once: true});
</script>
`, "{id}", galleryID))
}
return ast.WalkContinue, nil
}
func generateDivId(length int) string {
const charset = "abcdefghijklmnopqrstuvwxyz"
seededRand := rand.New(rand.NewSource(time.Now().UnixNano())) // Seed with current time
b := make([]byte, length)
for i := range b {
b[i] = charset[seededRand.Intn(len(charset))]
}
return string(b)
}
|