]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/.eleventy.js
import 8.23.1 source
[pve-eslint.git] / eslint / docs / .eleventy.js
1 "use strict";
2
3 const eleventyNavigationPlugin = require("@11ty/eleventy-navigation");
4 const syntaxHighlight = require("@11ty/eleventy-plugin-syntaxhighlight");
5 const pluginRss = require("@11ty/eleventy-plugin-rss");
6 const pluginTOC = require("eleventy-plugin-nesting-toc");
7 const markdownItAnchor = require("markdown-it-anchor");
8 const markdownItContainer = require("markdown-it-container");
9 const Image = require("@11ty/eleventy-img");
10 const path = require("path");
11 const { slug } = require("github-slugger");
12 const yaml = require("js-yaml");
13
14 const {
15 DateTime
16 } = require("luxon");
17
18 module.exports = function(eleventyConfig) {
19
20 /*
21 * The docs stored in the eslint repo are loaded through eslint.org at
22 * at /docs/head to show the most recent version of the documentation
23 * based on the HEAD commit. This gives users a preview of what's coming
24 * in the next release. This is the way that the site works locally so
25 * it's easier to see if URLs are broken.
26 *
27 * When a release is published, HEAD is pushed to the "latest" branch.
28 * Netlify deploys that branch as well, and in that case, we want the
29 * docs to be loaded from /docs/latest on eslint.org.
30 *
31 * The path prefix is turned off for deploy previews so we can properly
32 * see changes before deployed.
33 */
34
35 let pathPrefix = "/docs/head/";
36
37 if (process.env.CONTEXT === "deploy-preview") {
38 pathPrefix = "/";
39 } else if (process.env.BRANCH === "latest") {
40 pathPrefix = "/docs/latest/";
41 }
42
43 //------------------------------------------------------------------------------
44 // Data
45 //------------------------------------------------------------------------------
46
47 // Load site-specific data
48 const siteName = process.env.ESLINT_SITE_NAME || "en";
49
50 eleventyConfig.addGlobalData("site_name", siteName);
51 eleventyConfig.addGlobalData("GIT_BRANCH", process.env.BRANCH);
52 eleventyConfig.addGlobalData("NOINDEX", process.env.BRANCH !== "latest");
53 eleventyConfig.addDataExtension("yml", contents => yaml.load(contents));
54
55 //------------------------------------------------------------------------------
56 // Filters
57 //------------------------------------------------------------------------------
58
59 eleventyConfig.addFilter("limitTo", (arr, limit) => arr.slice(0, limit));
60
61 eleventyConfig.addFilter("jsonify", variable => JSON.stringify(variable));
62
63 /**
64 * Takes in a string and converts to a slug
65 * @param {string} text text to be converted into slug
66 * @returns {string} slug to be used as anchors
67 */
68 function slugify(text) {
69 return slug(text.replace(/[<>()[\]{}]/gu, ""))
70 // eslint-disable-next-line no-control-regex -- used regex from https://github.com/eslint/archive-website/blob/master/_11ty/plugins/markdown-plugins.js#L37
71 .replace(/[^\u{00}-\u{FF}]/gu, "");
72 }
73
74 eleventyConfig.addFilter("slugify", str => {
75 if (!str) {
76 return "";
77 }
78
79 return slugify(str);
80 });
81
82 eleventyConfig.addFilter("URIencode", str => {
83 if (!str) {
84 return "";
85 }
86 return encodeURI(str);
87 });
88
89 /* order collection by the order specified in the front matter */
90 eleventyConfig.addFilter("sortByPageOrder", values => values.slice().sort((a, b) => a.data.order - b.data.order));
91
92 eleventyConfig.addFilter("readableDate", dateObj => {
93
94 // turn it into a JS Date string
95 const date = new Date(dateObj);
96
97 // pass it to luxon for formatting
98 return DateTime.fromJSDate(date).toFormat("dd MMM, yyyy");
99 });
100
101 eleventyConfig.addFilter("blogPermalinkDate", dateObj => {
102
103 // turn it into a JS Date string
104 const date = new Date(dateObj);
105
106 // pass it to luxon for formatting
107 return DateTime.fromJSDate(date).toFormat("yyyy/MM");
108 });
109
110 eleventyConfig.addFilter("readableDateFromISO", ISODate => DateTime.fromISO(ISODate).toUTC().toLocaleString(DateTime.DATE_FULL));
111
112 eleventyConfig.addFilter("dollars", value => new Intl.NumberFormat("en-US", {
113 style: "currency",
114 currency: "USD"
115 }).format(value));
116
117 /*
118 * parse markdown from includes, used for author bios
119 * Source: https://github.com/11ty/eleventy/issues/658
120 */
121 eleventyConfig.addFilter("markdown", value => {
122 const markdown = require("markdown-it")({
123 html: true
124 });
125
126 return markdown.render(value);
127 });
128
129 /*
130 * Removes `.html` suffix from the given url.
131 * `page.url` will include the `.html` suffix for all documents
132 * except for those written as `index.html` (their `page.url` ends with a `/`).
133 */
134 eleventyConfig.addFilter("prettyURL", url => {
135 if (url.endsWith(".html")) {
136 return url.slice(0, -".html".length);
137 }
138
139 return url;
140 });
141
142 //------------------------------------------------------------------------------
143 // Plugins
144 //------------------------------------------------------------------------------
145
146 eleventyConfig.addPlugin(eleventyNavigationPlugin);
147 eleventyConfig.addPlugin(syntaxHighlight, {
148 alwaysWrapLineHighlights: true
149 });
150 eleventyConfig.addPlugin(pluginRss);
151 eleventyConfig.addPlugin(pluginTOC, {
152 tags: ["h2", "h3", "h4"],
153 wrapper: "nav", // Element to put around the root `ol`
154 wrapperClass: "c-toc", // Class for the element around the root `ol`
155 headingText: "", // Optional text to show in heading above the wrapper element
156 headingTag: "h2" // Heading tag when showing heading above the wrapper element
157 });
158
159 /** @typedef {import("markdown-it/lib/token")} MarkdownItToken A MarkdownIt token. */
160
161 /**
162 * Generates HTML markup for an inline alert.
163 * @param {"warning"|"tip"|"important"} type The type of alert to create.
164 * @param {Array<MarkdownItToken>} tokens Array of MarkdownIt tokens to use.
165 * @param {number} index The index of the current token in the tokens array.
166 * @returns {string} The markup for the alert.
167 */
168 function generateAlertMarkup(type, tokens, index) {
169 if (tokens[index].nesting === 1) {
170 return `
171 <aside role="note" class="alert alert--${type}">
172 <svg class="alert__icon" aria-hidden="true" focusable="false" width="19" height="20" viewBox="0 0 19 20" fill="none">
173 <path d="M9.49999 6.66667V10M9.49999 13.3333H9.50832M17.8333 10C17.8333 14.6024 14.1024 18.3333 9.49999 18.3333C4.89762 18.3333 1.16666 14.6024 1.16666 10C1.16666 5.39763 4.89762 1.66667 9.49999 1.66667C14.1024 1.66667 17.8333 5.39763 17.8333 10Z" stroke="currentColor" stroke-width="1.66667" stroke-linecap="round" stroke-linejoin="round" />
174 </svg>
175 <div class="alert__content">
176 <span class="alert__type">${type[0].toUpperCase()}${type.slice(1)}</span>
177 <div class="alert__text">
178 `.trim();
179 }
180
181 return `
182 </div>
183 </div>
184 </aside>
185 `.trim();
186 }
187
188 const markdownIt = require("markdown-it");
189
190 eleventyConfig.setLibrary("md",
191 markdownIt({ html: true, linkify: true, typographer: true })
192 .use(markdownItAnchor, {
193 slugify
194 })
195 .use(markdownItContainer, "correct", {})
196 .use(markdownItContainer, "incorrect", {})
197 .use(markdownItContainer, "warning", {
198 render(tokens, idx) {
199 return generateAlertMarkup("warning", tokens, idx);
200 }
201 })
202 .use(markdownItContainer, "tip", {
203 render(tokens, idx) {
204 return generateAlertMarkup("tip", tokens, idx);
205 }
206 })
207 .use(markdownItContainer, "important", {
208 render(tokens, idx) {
209 return generateAlertMarkup("important", tokens, idx);
210 }
211 })
212 .disable("code"));
213
214 //------------------------------------------------------------------------------
215 // Shortcodes
216 //------------------------------------------------------------------------------
217
218 eleventyConfig.addNunjucksShortcode("link", function(url) {
219
220 // eslint-disable-next-line no-invalid-this -- Eleventy API
221 const urlData = this.ctx.further_reading_links[url];
222
223 if (!urlData) {
224 throw new Error(`Data missing for ${url}`);
225 }
226
227 const {
228 domain,
229 title,
230 logo
231 } = urlData;
232
233 return `
234 <article class="resource">
235 <div class="resource__image">
236 <img class="resource__img" width="75" height="75" src="${logo}" alt="Avatar image for ${domain}" onerror="this.onerror = null; this.src = '/icon.svg'" />
237 </div>
238 <div class="resource__content">
239 <a href="${url}" class="resource__title"> ${title} </a><br>
240 <span class="resource__domain"> ${domain}</span>
241 </div>
242 <svg class="c-icon resource__icon" width="13" height="12" viewBox="0 0 13 12" fill="none">
243 <path d="M1.5 11L11.5 1M11.5 1H1.5M11.5 1V11" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
244 </svg>
245 </article>`;
246 });
247
248 eleventyConfig.addShortcode("fixable", () => `
249 <div class="rule-category">
250 <span class="rule-category__icon">🛠 <span class="visually-hidden">Fixable</span></span>
251 <p class="rule-category__description">
252 if some problems reported by the rule are automatically fixable by the <code>--fix</code> command line option
253 </p>
254 </div>`);
255
256 eleventyConfig.addShortcode("recommended", () => `
257 <div class="rule-category">
258 <span class="rule-category__icon">✅ <span class="visually-hidden">Recommended</span></span>
259 <p class="rule-category__description">
260 if the <code>"extends": "eslint:recommended"</code> property in a configuration file enables the rule.
261 </p>
262 </div>`);
263
264 eleventyConfig.addShortcode("hasSuggestions", () => `
265 <div class="rule-category">
266 <span class="rule-category__icon">💡 <span class="visually-hidden">hasSuggestions</span></span>
267 <p class="rule-category__description">
268 if some problems reported by the rule are manually fixable by editor suggestions
269 </p>
270 </div>`);
271
272 eleventyConfig.addShortcode("related_rules", arr => {
273 const rules = arr;
274 let items = "";
275
276 rules.forEach(rule => {
277 const listItem = `<li class="related-rules__list__item">
278 <a href="${pathPrefix}rules/${rule}">
279 <span>${rule}</span>
280 <svg width="24" height="24" viewBox="0 0 24 24" fill="none" aria-hidden="true" focusable="false">
281 <path d="M5 12H19M19 12L12 5M19 12L12 19" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
282 </svg>
283 </a>
284 </li>`;
285
286 items += listItem;
287 });
288
289 return `
290 <ul class="related-rules__list" role="list">
291 ${items}
292 </ul>`;
293 });
294
295 eleventyConfig.addShortcode("important", (text, url) => `
296 <div role="note" class="alert alert--important">
297 <svg class="alert__icon" aria-hidden="true" focusable="false" width="21" height="18" viewBox="0 0 21 18" fill="none">
298 <path d="M10.4998 6.66666V9.99999M10.4998 13.3333H10.5081M9.0748 2.38333L2.01647 14.1667C1.87094 14.4187 1.79394 14.7044 1.79313 14.9954C1.79231 15.2864 1.86771 15.5726 2.01183 15.8254C2.15594 16.0783 2.36374 16.2889 2.61456 16.4365C2.86538 16.5841 3.15047 16.6635 3.44147 16.6667H17.5581C17.8491 16.6635 18.1342 16.5841 18.385 16.4365C18.6359 16.2889 18.8437 16.0783 18.9878 15.8254C19.1319 15.5726 19.2073 15.2864 19.2065 14.9954C19.2057 14.7044 19.1287 14.4187 18.9831 14.1667L11.9248 2.38333C11.7762 2.13841 11.5671 1.93593 11.3175 1.7954C11.0679 1.65487 10.7862 1.58104 10.4998 1.58104C10.2134 1.58104 9.93175 1.65487 9.68214 1.7954C9.43254 1.93593 9.22336 2.13841 9.0748 2.38333Z" stroke="currentColor" stroke-width="1.66667" stroke-linecap="round" stroke-linejoin="round" />
299 </svg>
300 <div class="alert__content">
301 <span class="alert__type">Important</span>
302 <div class="alert__text">${text}</div>
303 <a href="${url}" class="alert__learn-more">Learn more</a>
304 </div>
305 </div>`);
306
307 eleventyConfig.addShortcode("warning", (text, url) => `
308 <div role="note" class="alert alert--warning">
309 <svg class="alert__icon" aria-hidden="true" focusable="false" width="19" height="20" viewBox="0 0 19 20" fill="none">
310 <path d="M9.49999 6.66667V10M9.49999 13.3333H9.50832M17.8333 10C17.8333 14.6024 14.1024 18.3333 9.49999 18.3333C4.89762 18.3333 1.16666 14.6024 1.16666 10C1.16666 5.39763 4.89762 1.66667 9.49999 1.66667C14.1024 1.66667 17.8333 5.39763 17.8333 10Z" stroke="currentColor" stroke-width="1.66667" stroke-linecap="round" stroke-linejoin="round" />
311 </svg>
312 <div class="alert__content">
313 <span class="alert__type">Warning</span>
314 <div class="alert__text">${text}</div>
315 <a href="${url}" class="alert__learn-more">Learn more</a>
316 </div>
317 </div>`);
318
319 eleventyConfig.addShortcode("tip", (text, url) => `
320 <div role="note" class="alert alert--tip">
321 <svg class="alert__icon" aria-hidden="true" focusable="false" width="19" height="20" viewBox="0 0 19 20" fill="none">
322 <path d="M17.8333 9.23333V10C17.8323 11.797 17.2504 13.5456 16.1744 14.9849C15.0985 16.4241 13.5861 17.4771 11.8628 17.9866C10.1395 18.4961 8.29771 18.4349 6.61205 17.8122C4.92639 17.1894 3.4872 16.0384 2.50912 14.5309C1.53105 13.0234 1.06648 11.2401 1.18472 9.44693C1.30296 7.6538 1.99766 5.94694 3.16522 4.58089C4.33278 3.21485 5.91064 2.26282 7.66348 1.86679C9.41632 1.47076 11.2502 1.65195 12.8917 2.38333M17.8333 3.33333L9.49999 11.675L6.99999 9.175" stroke="currentColor" stroke-width="1.66667" stroke-linecap="round" stroke-linejoin="round" />
323 </svg>
324 <div class="alert__content">
325 <span class="alert__type">Tip</span>
326 <div class="alert__text">${text}</div>
327 <a href="${url}" class="alert__learn-more">Learn more</a>
328 </div>
329 </div>`);
330
331
332 eleventyConfig.addWatchTarget("./src/assets/");
333
334 //------------------------------------------------------------------------------
335 // File PassThroughs
336 //------------------------------------------------------------------------------
337
338 eleventyConfig.addPassthroughCopy({
339 "./src/static": "/"
340 });
341
342 eleventyConfig.addPassthroughCopy("./src/assets/");
343
344 eleventyConfig.addPassthroughCopy({
345 "./src/content/**/*.png": "/assets/images"
346 });
347
348 eleventyConfig.addPassthroughCopy({
349 "./src/content/**/*.jpg": "/assets/images"
350 });
351
352 eleventyConfig.addPassthroughCopy({
353 "./src/content/**/*.jpeg": "/assets/images"
354 });
355
356 eleventyConfig.addPassthroughCopy({
357 "./src/content/**/*.svg": "/assets/images"
358 });
359
360 eleventyConfig.addPassthroughCopy({
361 "./src/content/**/*.mp4": "/assets/videos"
362 });
363
364 eleventyConfig.addPassthroughCopy({
365 "./src/content/**/*.pdf": "/assets/documents"
366 });
367
368 eleventyConfig.addPassthroughCopy({
369 "./node_modules/algoliasearch/dist/algoliasearch-lite.esm.browser.js": "/assets/js/algoliasearch.js"
370 });
371
372 //------------------------------------------------------------------------------
373 // Collections
374 //------------------------------------------------------------------------------
375
376 eleventyConfig.addCollection("docs", collection => collection.getFilteredByGlob("./src/**/**/*.md"));
377
378 eleventyConfig.addCollection("library", collection => collection.getFilteredByGlob("./src/library/**/*.md"));
379
380
381 // START, eleventy-img (https://www.11ty.dev/docs/plugins/image/)
382 /* eslint-disable-next-line jsdoc/require-jsdoc
383 --
384 This shortcode is currently unused. If we are going to use it, add JSDoc
385 and describe what exactly is this doing.
386 */
387 function imageShortcode(source, alt, cls, sizes = "(max-width: 768px) 100vw, 50vw") {
388 const options = {
389 widths: [600, 900, 1500],
390 formats: ["webp", "jpeg"],
391 urlPath: "/assets/images/",
392 outputDir: "./_site/assets/images/",
393 filenameFormat(id, src, width, format) {
394 const extension = path.extname(src);
395 const name = path.basename(src, extension);
396
397 return `${name}-${width}w.${format}`;
398 }
399 };
400
401 /**
402 * Resolves source
403 * @returns {string} URL or a local file path
404 */
405 function getSRC() {
406 if (source.startsWith("http://") || source.startsWith("https://")) {
407 return source;
408 }
409
410 /*
411 * for convenience, you only need to use the image's name in the shortcode,
412 * and this will handle appending the full path to it
413 */
414 return path.join("./src/assets/images/", source);
415 }
416
417 const fullSrc = getSRC();
418
419
420 // generate images
421 Image(fullSrc, options); // eslint-disable-line new-cap -- `Image` is a function
422
423 const imageAttributes = {
424 alt,
425 class: cls,
426 sizes,
427 loading: "lazy",
428 decoding: "async"
429 };
430
431 // get metadata
432 const metadata = Image.statsSync(fullSrc, options);
433
434 return Image.generateHTML(metadata, imageAttributes);
435 }
436 eleventyConfig.addShortcode("image", imageShortcode);
437
438 // END, eleventy-img
439
440 //------------------------------------------------------------------------------
441 // Settings
442 //------------------------------------------------------------------------------
443
444 /*
445 * When we run `eleventy --serve`, Eleventy 1.x uses browser-sync to serve the content.
446 * By default, browser-sync (more precisely, underlying serve-static) will not serve
447 * `foo/bar.html` when we request `foo/bar`. Thus, we need to rewrite URLs to append `.html`
448 * so that pretty links without `.html` can work in a local development environment.
449 *
450 * There's no need to rewrite URLs that end with `/`, because that already works well
451 * (server will return the content of `index.html` in the directory).
452 * URLs with a file extension, like main.css, main.js, sitemap.xml, etc. should not be rewritten
453 */
454 eleventyConfig.setBrowserSyncConfig({
455 middleware: (req, res, next) => {
456 if (!/(?:\.[a-zA-Z][^/]*|\/)$/u.test(req.url)) {
457 req.url += ".html";
458 }
459 return next();
460 }
461 });
462
463 /*
464 * Generate the sitemap only in certain contexts to prevent unwanted discovery of sitemaps that
465 * contain URLs we'd prefer not to appear in search results (URLs in sitemaps are considered important).
466 * In particular, we don't want to deploy https://eslint.org/docs/head/sitemap.xml
467 * We want to generate the sitemap for:
468 * - Local previews
469 * - Netlify deploy previews
470 * - Netlify production deploy of the `latest` branch (https://eslint.org/docs/latest/sitemap.xml)
471 *
472 * Netlify always sets `CONTEXT` environment variable. If it isn't set, we assume this is a local build.
473 */
474 if (
475 process.env.CONTEXT && // if this is a build on Netlify ...
476 process.env.CONTEXT !== "deploy-preview" && // ... and not for a deploy preview ...
477 process.env.BRANCH !== "latest" // .. and not of the `latest` branch ...
478 ) {
479 eleventyConfig.ignores.add("src/static/sitemap.njk"); // ... then don't generate the sitemap.
480 }
481
482
483 return {
484 passthroughFileCopy: true,
485
486 pathPrefix,
487
488 markdownTemplateEngine: "njk",
489 dataTemplateEngine: "njk",
490 htmlTemplateEngine: "njk",
491
492 dir: {
493 input: "src",
494 includes: "_includes",
495 layouts: "_includes/layouts",
496 data: "_data",
497 output: "_site"
498 }
499 };
500 };