-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
imgtopicture.go
307 lines (255 loc) · 7.01 KB
/
imgtopicture.go
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
/**
* Copyright 2020 Google LLC
*
* 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 imgtopicture
import (
"fmt"
"sort"
"strings"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/gauntface/go-html-asset-manager/v4/assets/genimgs"
"github.com/gauntface/go-html-asset-manager/v4/manipulations"
"github.com/gauntface/go-html-asset-manager/v4/utils/config"
"github.com/gauntface/go-html-asset-manager/v4/utils/html/htmlparsing"
"golang.org/x/net/html"
)
var (
genimgsOpen = genimgs.Open
genimgsLookupSizes = genimgs.LookupSizes
)
func Manipulator(runtime manipulations.Runtime, doc *html.Node) error {
if !shouldRun(runtime.Config) {
return nil
}
for _, i := range runtime.Config.ImgToPicture {
err := manipulateWithConfig(runtime.S3, runtime.Debug, runtime.Config, i, doc)
if err != nil {
return err
}
}
return nil
}
func shouldRun(conf *config.Config) bool {
if conf == nil {
return false
}
if conf.Assets == nil || conf.Assets.StaticDir == "" {
return false
}
if len(conf.ImgToPicture) == 0 {
return false
}
return true
}
func manipulateWithConfig(s3Client *s3.Client, debug bool, conf *config.Config, imgtopic *config.ImgToPicConfig, doc *html.Node) error {
rawElements := htmlparsing.FindNodesByTag(imgtopic.ID, doc)
rawElements = append(rawElements, htmlparsing.FindNodesByClassname(imgtopic.ID, doc)...)
if debug {
fmt.Printf("Found %v raw elements for %q\n", len(rawElements), imgtopic.ID)
}
var imgs []*html.Node
for _, e := range rawElements {
imgs = append(imgs, htmlparsing.FindNodesByTag("img", e)...)
}
if debug {
fmt.Printf("Found %v img elements for %q\n", len(imgs), imgtopic.ID)
}
for _, ie := range imgs {
err := manipulateImg(s3Client, debug, conf, imgtopic, ie)
if err != nil {
return err
}
}
return nil
}
func manipulateImg(s3Client *s3.Client, debug bool, conf *config.Config, imgtopic *config.ImgToPicConfig, ie *html.Node) error {
attributes := htmlparsing.Attributes(ie)
srcAttr, ok := attributes["src"]
if !ok || srcAttr.Val == "" {
if debug {
fmt.Printf("Skipping img without src\n")
}
return nil
}
if strings.HasPrefix(srcAttr.Val, "http") || strings.HasPrefix(srcAttr.Val, "//") {
if debug {
fmt.Printf("Skipping img with abs URL %q\n", srcAttr.Val)
}
return nil
}
// Get the src image
i, err := genimgsOpen(conf, srcAttr.Val)
if err != nil {
return nil
}
// Get width and height from the image
origWidth, origHeight := i.Bounds().Size().X, i.Bounds().Size().Y
sizes, err := genimgsLookupSizes(s3Client, conf, srcAttr.Val)
if err != nil {
return err
}
if len(sizes) == 0 {
if debug {
fmt.Printf("No sizes found for %q\n", srcAttr.Val)
}
return nil
}
// Remove element from it's parent so it can be wrapped by picture
p := ie.Parent
s := ie.NextSibling
p.RemoveChild(ie)
pe := pictureElement(imgtopic, ie, sizes, origWidth, origHeight)
p.InsertBefore(pe, s)
return nil
}
func pictureElement(imgtopic *config.ImgToPicConfig, imgElement *html.Node, sizes []genimgs.GenImg, origWidth, origHeight int) *html.Node {
sourceSetByType := genimgs.GroupByType(sizes)
sourceSetsArray := orderedSourceSets(sourceSetByType)
picture := &html.Node{
Type: html.ElementNode,
Data: "picture",
Attr: []html.Attribute{},
}
for _, imgs := range sourceSetsArray {
picture.AppendChild(createSourceElement(imgtopic, imgs))
}
if imgtopic.Class != "" {
picture.Attr = append(picture.Attr, html.Attribute{
Key: "class",
Val: imgtopic.Class,
})
}
// Replace the img src="..." attribute to point to the largest generated asset
if len(sourceSetByType[""]) > 0 {
for i, a := range imgElement.Attr {
if a.Key != "src" {
continue
}
// Change the src of the img to the largest, generated, default URL
largest := sourceSetByType[""][len(sourceSetByType[""])-1]
imgElement.Attr[i].Val = largest.URL
}
}
picture.AppendChild(imgElement)
return picture
}
func createSourceElement(imgtopic *config.ImgToPicConfig, imgs []genimgs.GenImg) *html.Node {
source := &html.Node{
Type: html.ElementNode,
Data: "source",
Attr: []html.Attribute{},
}
if len(imgs) == 0 {
return source
}
// Add type attribute if appropriate
if imgs[0].Type != "" {
source.Attr = append(source.Attr, html.Attribute{
Key: "type",
Val: imgs[0].Type,
})
}
// Add sizes attribute
source.Attr = append(source.Attr, html.Attribute{
Key: "sizes",
Val: strings.Join(imgtopic.SourceSizes, ","),
})
// Sort and add srcset attribute
sort.Slice(imgs, func(i, j int) bool {
return imgs[i].Size < imgs[j].Size
})
srcsetValues := []string{}
for _, s := range imgs {
srcsetValues = append(srcsetValues, fmt.Sprintf("%v %vw", s.URL, s.Size))
}
source.Attr = append(source.Attr, html.Attribute{
Key: "srcset",
Val: strings.Join(srcsetValues, ","),
})
return source
}
func orderedSourceSets(sourceSetByType map[string][]genimgs.GenImg) [][]genimgs.GenImg {
// Order of src-set is important and we prefer avif, and then webp over other formats
desiredOrder := []string{
"image/avif",
"image/webp",
// Undefined is used for jpg and png
"",
}
sourceSets := [][]genimgs.GenImg{}
for _, dt := range desiredOrder {
v, ok := sourceSetByType[dt]
if !ok {
continue
}
sourceSets = append(sourceSets, v)
}
otherTypes := []string{}
for t := range sourceSetByType {
knownType := false
for _, o := range desiredOrder {
if o == t {
knownType = true
break
}
}
if !knownType {
otherTypes = append(otherTypes, t)
}
}
if len(otherTypes) > 0 {
fmt.Printf("⚠️ %v unexpected image format(s) in picture source set:\n", len(otherTypes))
for _, t := range otherTypes {
fmt.Printf(" - %v\n", t)
}
}
return sourceSets
}
// H/T to Jack Archibald for a simple and concise explainer of picture
// https://jakearchibald.com/2015/anatomy-of-responsive-images/
/*
<picture>
<!--
type: Type of asset
srcset: Img and the image width
sizes: Sizes the image will be displayed at
-->
<source
type="image/webp"
srcset="
/generated/example.1234abc/100.webp 100w,
/generated/example.1234abc/200.webp 200w,
/generated/example.1234abc/300.webp 300w
"
sizes="
(min-width: 800px) 800px,
100vw">
<source
srcset="
/generated/example.1234abc/100.jpg 100w,
/generated/example.1234abc/200.jpg 200w,
/generated/example.1234abc/300.jpg 300w,
"
sizes="
(min-width: 800px) 800px,
100vw">
<!--
src: Only used for browsers that don't support srcset
srcset:
-->
<img
alt="Example images"
src="/generated/example.1234abc/100.jpg">
</picture>
*/