generated from distantcam/windty
-
Notifications
You must be signed in to change notification settings - Fork 0
/
.eleventy.js
243 lines (210 loc) · 7.44 KB
/
.eleventy.js
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
const fs = require("fs");
const path = require("path");
const htmlmin = require("html-minifier-terser");
const tailwind = require('tailwindcss');
const postCss = require('postcss');
const autoprefixer = require('autoprefixer');
const cssnano = require('cssnano');
const mdit = require('markdown-it')
const mditAttrs = require('markdown-it-attrs');
const mditHighlight = require('markdown-it-highlightjs');
const Image = require('@11ty/eleventy-img');
// sizes and formats of resized images to make them responsive
// it can be overwriten when using the "Picture" short code
const Images = {
WIDTHS: [426, 460, 580, 768, 1200], // sizes of generated images
FORMATS: ['webp', 'jpeg'], // formats of generated images
SIZES: '(max-width: 1200px) 70vw, 1200px' // size of image rendered
}
module.exports = async function(eleventyConfig) {
const { EleventyHtmlBasePlugin } = await import("@11ty/eleventy");
eleventyConfig.addPlugin(EleventyHtmlBasePlugin);
if (process.env.ELEVENTY_PRODUCTION) {
eleventyConfig.addTransform("htmlmin", htmlminTransform);
}
// markdown
const mditOptions = {
html: true,
breaks: true,
linkify: true,
typographer: true,
}
const mdLib = mdit(mditOptions).use(mditAttrs).use(mditHighlight, { inline: true }).disable('code')
// generate responsive images from Markdown
mdLib.renderer.rules.image = (tokens, idx, options, env, self) => {
const token = tokens[idx]
const imgPath = token.attrGet('src')
const isGlobal = imgPath.slice(0, env.meta.public_folder.length) === env.meta.public_folder
const imgSrc = isGlobal
? "./" + env.meta.media_folder + imgPath.slice(env.meta.public_folder.length)
: imgPath.slice(0,1) === "/"
? env.eleventy.directories.input.slice(0, -1) + imgPath
: env.page.inputPath.substring(0, env.page.inputPath.lastIndexOf('/')) + "/" + imgPath
const imgAlt = token.content
const imgTitle = token.attrGet('title') ?? ''
const className = token.attrGet('class')
const ImgOptions = getImgOptions(env.page, imgSrc, imgAlt, className, Images.WIDTHS, Images.FORMATS, Images.SIZES);
const htmlOptions = {
alt: imgAlt,
class: className,
sizes: Images.SIZES,
loading: className?.includes('lazy') ? 'lazy' : undefined,
decoding: 'async',
title: imgTitle
}
Image(imgSrc, ImgOptions)
const metadata = Image.statsSync(imgSrc, ImgOptions)
const picture = Image.generateHTML(metadata, htmlOptions)
return picture
}
eleventyConfig.setLibrary('md', mdLib)
// Passthrough
eleventyConfig.addPassthroughCopy({ "src/assets": "." });
eleventyConfig.addPassthroughCopy({ 'src/_assets/public': '/' });
eleventyConfig.addPassthroughCopy({ 'src/_assets/img': '/img' });
eleventyConfig.addPassthroughCopy({ 'src/_assets/fonts': '/fonts' });
// Watch targets
eleventyConfig.addWatchTarget("./src/_assets/css/");
// process css
eleventyConfig.addNunjucksAsyncFilter('postcss', postcssFilter);
// Image shortcode with <picture>
eleventyConfig.addShortcode("Picture", async (
page,
src,
alt,
className = undefined,
widths = Images.WIDTHS,
formats = Images.FORMATS,
sizes = Images.SIZES
) => {
if (!alt) {
throw new Error(`Missing \`alt\` on myImage from: ${src}`);
}
const srcImage = getSrcImage(page, src);
const options = getImgOptions(page, src, alt, className, widths, formats, sizes);
const imageMetadata = await Image(srcImage, options);
const sourceHtmlString = Object.values(imageMetadata)
// Map each format to the source HTML markup
.map((images) => {
// The first entry is representative of all the others
// since they each have the same shape
const { sourceType } = images[0];
// Use our util from earlier to make our lives easier
const sourceAttributes = stringifyAttributes({
type: sourceType,
// srcset needs to be a comma-separated attribute
srcset: images.map((image) => image.srcset).join(', '),
sizes,
});
// Return one <source> per format
return `<source ${sourceAttributes}>`;
})
.join('\n');
const getLargestImage = (format) => {
const images = imageMetadata[format];
return images[images.length - 1];
}
const largestUnoptimizedImg = getLargestImage(formats[0]);
const imgAttributes = stringifyAttributes({
src: largestUnoptimizedImg.url,
width: largestUnoptimizedImg.width,
height: largestUnoptimizedImg.height,
alt,
loading: className?.includes('lazy') ? 'lazy' : undefined,
decoding: 'async',
});
const imgHtmlString = `<img ${imgAttributes}>`;
const pictureAttributes = stringifyAttributes({
class: className,
});
const picture = `<picture ${pictureAttributes}>
${sourceHtmlString}
${imgHtmlString}
</picture>`;
return `${picture}`;
});
// Collections
eleventyConfig.addCollection("documentation", function (collection) {
return collection.getFilteredByGlob("./src/pages/documentation/**/*.md");
});
return {
dir: {
input: "src/pages",
media: "src/static/img",
layouts: '../_layouts',
includes: '../_layouts/includes',
data: '../_data',
output: '_site',
},
templateFormats: ['md', 'njk', 'jpg', 'gif', 'png', 'html', 'jpeg', 'webp'],
pathPrefix: process.env.BASE_HREF ? `/${process.env.BASE_HREF}/` : "/" // used with github pages
}
}; // end config
function htmlminTransform(content, outputPath) {
if( outputPath.endsWith(".html") ) {
let minified = htmlmin.minify(content, {
useShortDoctype: true,
removeComments: true,
collapseWhitespace: true
});
return minified;
}
return content;
}
const postcssFilter = (cssCode, done) => {
postCss([
require('postcss-import'),
tailwind(require('./tailwind.config')),
autoprefixer(),
// TODO use purgecss for each layout
// cssnano({ preset: 'default' })
])
.process(cssCode, {
// path to our CSS file
from: './src/_assets/css/styles.css'
})
.then(
(r) => done(null, r.css),
(e) => done(e, null)
);
}
/** Maps a config of attribute-value pairs to an HTML string
* representing those same attribute-value pairs.
*/
const stringifyAttributes = (attributeMap) => {
return Object.entries(attributeMap)
.map(([attribute, value]) => {
if (typeof value === 'undefined') return '';
return `${attribute}="${value}"`;
})
.join(' ');
};
const getSrcImage = (page, src) => {
let inputFolder = page.inputPath.split("/")
inputFolder.pop()
inputFolder = inputFolder.join("/");
return inputFolder+"/"+src;
}
const getImgOptions = (page, src, alt, className, widths, formats, sizes) => {
let outputFolder = page.outputPath.split("/")
outputFolder.pop() // remove index.html
outputFolder = outputFolder.join("/");
let urlPath = outputFolder.split("/")
urlPath.shift() // remove ./
urlPath.shift() // remove _site
urlPath = "/" + urlPath.join("/");
const options = {
widths: widths
.concat(widths.map((w) => w * 2)) // generate 2x sizes
.filter((v, i, s) => s.indexOf(v) === i), // dedupe
formats: [...formats, null],
outputDir: outputFolder,
urlPath: urlPath,
filenameFormat: function (id, src, width, format, options) {
const extension = path.extname(src);
const name = path.basename(src, extension);
return `${name}-${width}w.${format}`;
}
}
return options;
}