-
Notifications
You must be signed in to change notification settings - Fork 1
/
eleventy.config.js
217 lines (197 loc) · 6.94 KB
/
eleventy.config.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
const pluginRss = require('@11ty/eleventy-plugin-rss');
const yaml = require('js-yaml');
const md = require('./_lib/markdown-engine');
const queryString = require('query-string');
const embedTwitter = require('eleventy-plugin-embed-twitter');
const _ = require('lodash');
const localImages = require('eleventy-plugin-local-images');
const getOpenGraphData = require('./_lib/get-open-graph-data');
const dayjs = require('./_lib/dayjs');
const updatesCollection = require('./_lib/updates-collection');
const fs = require('fs');
const getUnsplashImageColor = require('./_lib/get-unsplash-image-color');
const webmentionsForUrl = require('./_lib/webmentions-for-url');
const htmlmin = require('html-minifier');
const posthtml = require('posthtml');
const uglify = require('posthtml-minify-classnames');
const syntaxHighlight = require('@11ty/eleventy-plugin-syntaxhighlight');
const now = new Date();
const IS_PRODUCTION = process.env.ELEVENTY_PRODUCTION === 'true';
module.exports = function (cfg) {
// Plugins
cfg.addPlugin(pluginRss);
cfg.addPlugin(embedTwitter, {
cacheText: IS_PRODUCTION,
});
cfg.addPlugin(syntaxHighlight);
if (IS_PRODUCTION) {
cfg.addPlugin(localImages, {
distPath: '_site',
assetPath: '/images',
selector: 'img',
verbose: true,
});
}
// Copy
cfg.addPassthroughCopy('fonts');
cfg.addPassthroughCopy('images');
cfg.addPassthroughCopy('stylesheets/*.css*');
cfg.addPassthroughCopy('notes/**/*.{gif,jpg,jpeg,png,m4a}');
// Collections
cfg.addCollection('notes', (collection) =>
collection.getFilteredByGlob(['notes/**/*.md']).filter((item) => item.data.draft !== true && item.date <= now)
);
cfg.addCollection('updates', updatesCollection);
cfg.addCollection('indexable', (collection) => collection.getAll().filter((item) => !item.data.noindex));
cfg.addCollection('tagList', (collection) => {
const tagsSet = new Set();
collection.getAll().forEach((item) => {
if (!item.data.tags) return;
item.data.tags.filter((tag) => !['post', 'all'].includes(tag)).forEach((tag) => tagsSet.add(tag));
});
return Array.from(tagsSet).sort();
});
cfg.addCollection('featured', (collection) =>
collection
.getAllSorted()
.filter((item) => item.data.featured)
.reverse()
);
cfg.addCollection('noindex', (collection) => collection.getAll().filter((item) => item.data.noindex));
cfg.addShortcode('query', (data) => {
return (
'?' +
queryString.stringify(
Object.keys(data).reduce((obj, key) => (key.startsWith('_') ? obj : { ...obj, [key]: data[key] }), {})
)
);
});
cfg.addNunjucksAsyncShortcode('HeroImage', async (unsplashImageId, alt = '', heroStyle, heroCaption) => {
if (!unsplashImageId) return '';
let style = '';
let imageDimentions = [1400, 900];
if (heroStyle === 'ribbon') {
imageDimentions = [1400, 450];
} else if (heroStyle === 'notes-thumbnail') {
imageDimentions = [700, 500];
}
const url = `https://source.unsplash.com/${unsplashImageId}/${imageDimentions.join('x')}?fm=jpg`;
const imageColor = await getUnsplashImageColor(url, 'muted');
if (imageColor) {
style = ` style="background-color: ${imageColor}"`;
}
return `<figure class="hero-image u-photo ${heroStyle ? `hero-${heroStyle}` : ''}">
<img src="${url}" alt="${alt.trim()}" width="${imageDimentions[0]}" height="${imageDimentions[1]}"${style}/>
${heroCaption ? `<figcaption class="hero-image__caption">${md.render(heroCaption)}</figcaption>` : ''}
</figure>`;
});
// Extentions / Libraries
cfg.setLibrary('md', md);
cfg.addDataExtension('yaml', yaml.safeLoad);
// Filters
cfg.addFilter('markdown', (contents) => md.render(contents));
cfg.addFilter('prettyUrl', prettyUrl);
cfg.addFilter('date', (date, format) => dayjs(date).format(format));
cfg.addFilter('dateRelative', (date) => dayjs(date).fromNow());
cfg.addFilter('debug', (obj) => `<pre style="overflow-x: auto;"><code>${JSON.stringify(obj, null, 2)}</code></pre>`);
cfg.addFilter('encodeURIComponent', (str) => encodeURIComponent(str));
cfg.addFilter('getTwitterUserFromURL', (tweetURL) => {
const url = new URL(tweetURL);
return `@${url.pathname.split('/')[1]}`;
});
cfg.addFilter('getHost', (url) => prettyUrl(new URL(url).host));
cfg.addFilter('cacheBust', (url) => (IS_PRODUCTION ? `${url}?${Date.now()}` : url));
cfg.addFilter('webmentionsForUrl', webmentionsForUrl);
cfg.addFilter('parseLinks', (content) =>
_.compact(
_.uniq((content || '').match(/href="(https?:\/\/\S+)"/) || []).filter(
(s) => !s.includes('twitter') && !s.startsWith('href')
)
)
);
cfg.addNunjucksAsyncFilter('getOpenGraphData', getOpenGraphData);
cfg.addFilter('isFeatured', (collection) => collection.filter((page) => page.data.featured));
cfg.addTransform('lazyImages', (content, outputPath) => {
if (!outputPath.endsWith('.html')) return content;
return content.replace(/<img /g, '<img loading="lazy" ');
});
cfg.addTransform('htmlmin', async function (content, outputPath) {
// Eleventy 1.0+: use this.inputPath and this.outputPath instead
if (outputPath && outputPath.endsWith('.html')) {
let html = content;
if (IS_PRODUCTION) {
const filteredClasses = [
'u-photo',
'p-note',
'h-card',
'p-name',
'u-url',
'h-entry',
'p-name',
'e-content',
'dt-published',
'dt-updated',
'u-syndication',
'p-category',
'p-author',
'asciicast-tvFG35UnF0pISTpgn247JyqaP',
];
html = (
await posthtml()
.use(
uglify({
filter: new RegExp(filteredClasses.join('|')),
})
)
.process(content)
)?.html;
}
let minified = htmlmin.minify(html, {
useShortDoctype: true,
removeComments: true,
collapseWhitespace: true,
});
return minified;
}
return content;
});
cfg.setFrontMatterParsingOptions({
excerpt: (file) => {
file.excerpt = file.data.excerpt || file.content.split('\n').slice(0, 3).join(' ');
},
excerpt_separator: '<!-- excerpt -->',
excerpt_alias: 'excerpt',
});
// Browsersync Overrides
cfg.setBrowserSyncConfig({
callbacks: {
ready: function (err, browserSync) {
if (err) {
console.error(err);
process.exit(1);
}
const content_404 = fs.readFileSync('_site/404.html');
browserSync.addMiddleware('*', (_, res) => {
res.write(content_404);
res.end();
});
},
},
ui: false,
ghostMode: false,
});
return {
dir: {
layouts: '_layouts',
},
};
};
function prettyUrl(input) {
const url = input.trim();
if (!/^http|^www\./.test(url)) return input;
return url
.trim()
.replace(/^https?:\/\//, '')
.replace(/^www\./, '')
.replace(/\/$/, '');
}