-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path.eleventy.js
263 lines (238 loc) · 8.62 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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
const fs = require('fs');
const eleventyNavigationPlugin = require('@11ty/eleventy-navigation');
const syntaxHighlight = require('@11ty/eleventy-plugin-syntaxhighlight');
const pluginRss = require('@11ty/eleventy-plugin-rss');
const readingTime = require('eleventy-plugin-reading-time');
const format = require('date-fns/format');
const parseISO = require('date-fns/parseISO');
const Image = require('@11ty/eleventy-img');
const htmlMinTransform = require('./src/transforms/html-min-transform.js');
const createSocialImages = require('./ogImages');
module.exports = function(config) {
// Activate deep merge for data cascade
config.setDataDeepMerge(true);
// Plugins
config.addPlugin(eleventyNavigationPlugin);
config.addPlugin(syntaxHighlight);
config.addPlugin(pluginRss);
config.addPlugin(readingTime);
// Event listeners
config.on('afterBuild', async () => {
if (process.env.ELEVENTY_ENV === 'production') {
await createSocialImages();
}
});
// Custom collections
config.addCollection('allPages', function(collection) {
return collection
.getAll()
.filter(post =>
post.data.tags
? !post.data.tags.includes('project') || !post.data.tags.includes('talks')
: true,
);
});
config.addCollection('blogposts', function(collection) {
return collection.getFilteredByTag('posts').filter(post => post.data.published);
});
config.addCollection('featuredProjects', function(collection) {
return collection.getFilteredByTag('project').sort((a, b) => b.data.featured - a.data.featured);
});
config.addCollection('talks', function(collection) {
return collection.getFilteredByTag('talk').sort((a, b) => b.data.eventDate - a.data.eventDate);
});
// Custom filters
// First three are taken from taken from https://github.com/11ty/eleventy-base-blog/blob/master/.eleventy.js
config.addFilter('toDate', dateString => {
return parseISO(dateString);
});
config.addFilter('readableDate', dateObj => {
return format(dateObj, "MMMM d', 'yyyy");
});
config.addFilter('isoDate', dateObj => {
return format(dateObj, 'yyyy-MM-dd');
});
config.addFilter('isoDuration', readingTime => {
return `PT${readingTime.split(' ')[0]}M`;
});
config.addFilter('myRssDate', dateObj => {
// Fri, 24 Jul 2020 00:00:00 +0000
return format(dateObj, 'E, dd LLL yyyy HH:mm:ss xx');
});
config.addFilter('lastUpdated', collection => {
return new Date(
Math.max(
...collection.map(item => {
return item.date;
}),
),
);
});
// Get the first `n` elements of a collection.
config.addFilter('head', (array, n) => {
if (n < 0) {
return array.slice(n);
}
return array.slice(0, n);
});
// Return first segment of url path - used to highlight menu item for nested pages
config.addFilter('urlHead', path => {
return path !== '/' ? path.split('/').slice(0, 2).join('/') + `/` : path; // url paths in 11ty ends with trailing slash
});
// generate text param for Twitter share button
config.addFilter('twitterShare', (path, quote) => {
return `https://twitter.com/intent/tweet?text=${encodeURI(
`${quote} https://pustelto.com${path}`,
)}`;
});
// Add ` - Tomas Pustelnik` to head title
config.addFilter('withAuthor', title => {
return title ? `${title} - Tomas Pustelnik's personal website` : undefined;
});
// Custom shortcodes
config.addShortcode('codepen', function(penId, title, tabs = ['css', 'result']) {
return `<p class="codepen" data-height="324" data-theme-id="dark" data-default-tab="${tabs.join(
',',
)}" data-user="Pustelto" data-slug-hash="${penId}" data-preview="true" style="height: 324px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid; margin: 1em 0; padding: 1em;" data-pen-title="${title}">
<span>See the Pen <a href="https://codepen.io/Pustelto/pen/${penId}">
${title}</a> by Tomas Pustelnik (<a href="https://codepen.io/Pustelto">@Pustelto</a>)
on <a href="https://codepen.io">CodePen</a>.</span>
</p>
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>
`;
});
async function optimImg(src, opts) {
const finalOpts = {
widths: [320, 480, 640, 960, 1440],
formats: ['avif', 'webp', 'jpg'],
urlPath: './',
outputDir: '_site/images',
...opts,
};
let stats = await Image(src, finalOpts);
if (finalOpts.widths.length > 1) return stats;
else return stats['jpg'].pop();
}
config.addNunjucksAsyncShortcode('image', async function(src, alt, options) {
if (alt === undefined) {
throw new Error(`Missing \`alt\` on resImage from: ${src}`);
}
let stats = await optimImg(
'src' + this.page.url + src,
{
outputDir: '_site' + this.page.url,
},
options,
);
let lowestSrc = stats.jpeg[0];
let sizes = '(max-width: 39.4375rem) 100vw, 608px';
// Iterate over formats and widths
return `<picture>
${Object.values(stats)
.map(imageFormat => {
return ` <source type="image/${imageFormat[0].format}" srcset="${imageFormat
.map(entry => `${entry.url} ${entry.width}w`)
.join(', ')}" sizes="${sizes}">`;
})
.join('\n')}
<img
alt="${alt}"
src="${lowestSrc.url}"
width="${lowestSrc.width}"
height="${lowestSrc.height}"
loading="lazy"
decoding="async">
</picture>`;
});
config.addNunjucksAsyncShortcode('figure', async function(src, alt, caption, options) {
if (alt === undefined) {
throw new Error(`Missing \`alt\` on resImage from: ${src}`);
}
//TODO: extract to standalone function since it is shared with image short code
let stats = await optimImg('src' + this.page.url + src, {
outputDir: '_site' + this.page.url,
});
let lowestSrc = stats.jpeg[0];
let sizes = '(max-width: 39.4375rem) 100vw, 608px';
// Iterate over formats and widths
return `<figure><picture>
${Object.values(stats)
.map(imageFormat => {
return ` <source type="image/${imageFormat[0].format}" srcset="${imageFormat
.map(entry => `${entry.url} ${entry.width}w`)
.join(', ')}" sizes="${sizes}">`;
})
.join('\n')}
<img
alt="${alt}"
src="${lowestSrc.url}"
width="${lowestSrc.width}"
height="${lowestSrc.height}"
loading="lazy"
decoding="async">
</picture><figcaption>${caption}</figcaption></figure>`;
});
// Copy assets
config.addPassthroughCopy('src/fonts');
config.addPassthroughCopy('src/images');
config.addPassthroughCopy('src/blog/**/*.{gif}');
config.addPassthroughCopy('src/favicon*');
config.addPassthroughCopy('src/robots.txt');
config.addPassthroughCopy('src/_headers');
// Code transforms
config.addTransform('htmlmin', htmlMinTransform);
let markdownIt = require('markdown-it');
let mdAnchor = require('markdown-it-anchor');
let options = {
html: true,
xhtmlOut: true,
breaks: true,
linkify: false,
typographer: true,
};
const md = markdownIt(options)
.use(mdAnchor, {
permalink: mdAnchor.permalink.linkAfterHeader({
style: 'visually-hidden',
class: 'headingAnchor__link',
assistiveText: title => `Permalink to “${title}”`,
visuallyHiddenClass: 'visually-hidden',
wrapper: ['<div class="headingAnchor__wrapper">', '</div>'],
}),
})
.use(require('markdown-it-toc-done-right'), {
containerClass: 'toc',
})
.use(require('markdown-it-kbd'))
.use(require('markdown-it-abbr'))
.use(require('markdown-it-playground'))
.use(require('markdown-it-footnote'));
md.renderer.rules.footnote_block_open = () =>
'<section class="footnotes" aria-label="Footnotes">\n' + '<ol class="footnotes-list">\n';
// Markdown Parsing
config.setLibrary('md', md);
config.setBrowserSyncConfig({
callbacks: {
ready: function(err, bs) {
bs.addMiddleware('*', (req, res) => {
const content_404 = fs.readFileSync('_site/404.html');
// Add 404 http status code in request header.
res.writeHead(404, { 'Content-Type': 'text/html; charset=UTF-8' });
// Provides the 404 content without redirect.
res.write(content_404);
res.end();
});
},
},
});
// You can return your Config object (optional).
return {
dir: {
input: 'src',
},
templateFormats: ['njk', 'md', 'html', '11ty.js', 'css'],
htmlTemplateEngine: 'njk',
markdownTemplateEngine: 'njk',
passthroughFileCopy: true,
};
};