-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy path.eleventy.js
More file actions
881 lines (734 loc) · 35.9 KB
/
Copy path.eleventy.js
File metadata and controls
881 lines (734 loc) · 35.9 KB
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
const path = require("path");
const util = require("util");
const fs = require("fs");
const { EleventyRenderPlugin } = require("@11ty/eleventy");
const pluginRSS = require("@11ty/eleventy-plugin-rss");
const syntaxHighlight = require("@11ty/eleventy-plugin-syntaxhighlight");
const pluginMermaid = require("@kevingimbel/eleventy-plugin-mermaid");
const codeClipboard = require("eleventy-plugin-code-clipboard");
const htmlmin = require("html-minifier-terser");
const markdownIt = require("markdown-it");
const markdownItAnchor = require("markdown-it-anchor");
const markdownItFootnote = require("markdown-it-footnote");
const markdownItAttrs = require('markdown-it-attrs');
const spacetime = require("spacetime");
const { minify } = require("terser");
const codeowners = require('codeowners');
const pluginTOC = require('eleventy-plugin-toc');
const { decodeHTML } = require('entities');
const imageHandler = require('./lib/image-handler.js')
const site = require("./src/_data/site");
const { isSearchPage, isSearchUrl, extractHeadingRecords } = require("./lib/search-index.js");
const yaml = require("js-yaml");
const eleventyNavigationPlugin = require("@11ty/eleventy-navigation");
// Documentation alert boxes
const shortcodeMarkdown = new markdownIt()
const CALLOUT_ICONS = {
note: `<svg class="ff-callout__icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg>`,
warning: `<svg class="ff-callout__icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z"/><path d="M12 9v4"/><path d="M12 17h.01"/></svg>`,
caution: `<svg class="ff-callout__icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="10"/><line x1="12" x2="12" y1="8" y2="12"/><line x1="12" x2="12.01" y1="16" y2="16"/></svg>`,
}
function renderDocsAlertBox(content, tone = 'note') {
const normalizedTone = tone.toLowerCase();
const icon = CALLOUT_ICONS[normalizedTone] || CALLOUT_ICONS.note
const markdownContent = shortcodeMarkdown.render(content)
const contentWithIcon = markdownContent.replace(/^(<\w[^>]*>)/, `$1${icon}`)
return `<div class="ff-callout ff-callout--${normalizedTone}"><div class="ff-callout__content">${contentWithIcon}</div></div>`
}
// Skip slow optimizations when developing i.e. serve/watch or Netlify deploy preview
const DEV_MODE = process.env.ELEVENTY_RUN_MODE !== "build" || process.env.CONTEXT === "deploy-preview"
// Image processing is skipped in dev mode or when explicitly requested via SKIP_IMAGES.
// Kept separate from DEV_MODE so build-time image flags never affect analytics/consent script inclusion.
const SKIP_IMAGES = DEV_MODE || process.env.SKIP_IMAGES === 'true'
const DEPLOY_PREVIEW = process.env.CONTEXT === "deploy-preview";
const IMAGE_BUILD_PROFILE = process.env.IMAGE_BUILD_PROFILE || "full";
console.info(`[11ty] Image build profile: ${IMAGE_BUILD_PROFILE}`)
module.exports = function(eleventyConfig) {
eleventyConfig.addDataExtension("yaml", contents => yaml.load(contents)); // Add support for YAML data files
eleventyConfig.setUseGitIgnore(false); // Blueprints are generated into gitignored src/blueprints/, so they must not be ignored
eleventyConfig.setWatchThrottleWaitTime(500); // in milliseconds
eleventyConfig.setFrontMatterParsingOptions({
excerpt: true,
excerpt_separator: "<!--more-->",
excerpt_alias: "excerpt"
});
// Set DEV_MODE_POSTS to true if the context is not 'production'
const DEV_MODE_POSTS = process.env.CONTEXT !== "production";
// The filter excludes blog posts with a date in the future for the production website.
let processedPosts = {};
eleventyConfig.addFilter('isFuturePost', (post) => {
const isFuturePost = post.date && post.date > new Date();
if (isFuturePost && !processedPosts[post.title]) {
let text = DEV_MODE_POSTS ? 'Including' : 'Excluding';
let formattedDate = eleventyConfig.getFilter('shortDate')(post.date);
console.log(`[11ty/eleventy-base-blog] ${text} ${post.title} scheduled for ${formattedDate}`);
processedPosts[post.title] = true;
}
return isFuturePost && !DEV_MODE_POSTS;
});
// Define a filter named 'isFutureDate'
eleventyConfig.addFilter('isFutureDate', (dateString) => {
const date = new Date(dateString);
return date && date > new Date();
});
eleventyConfig.addFilter('extractH1Content', (content) => {
if (!content) return '';
const match = content.match(/<h1[^>]*>([\s\S]*?)<\/h1>/);
if (match) {
const textContent = match[1].replace(/<\/?[^>]+>/gi, '').trim();
return textContent;
}
return null;
});
eleventyConfig.addFilter("excludeCurrent", (items, currentUrl) => {
return items.filter(item => item.url !== currentUrl);
});
eleventyConfig.addFilter("shuffle", (array) => {
const shuffled = [...array];
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled;
});
// Add a global data variable for the current date
eleventyConfig.addGlobalData("currentDateISO", new Date().toISOString());
// Make filters globally accessible
global.isFuturePost = eleventyConfig.getFilter('isFuturePost');
global.isFutureDate = eleventyConfig.getFilter('isFutureDate');
global.extractH1Content = eleventyConfig.getFilter('extractH1Content');
// Layout aliases
eleventyConfig.addLayoutAlias('default', 'layouts/base.njk');
eleventyConfig.addLayoutAlias('page', 'layouts/page.njk');
eleventyConfig.addLayoutAlias('nohero', 'layouts/nohero.njk');
eleventyConfig.addLayoutAlias('solution', 'layouts/solution.njk');
eleventyConfig.addLayoutAlias('use-case', 'layouts/use-case.njk');
eleventyConfig.addLayoutAlias('catalog', 'layouts/catalog.njk');
eleventyConfig.addLayoutAlias('redirect', 'layouts/redirect.njk');
// Copy the contents of the `public` folder to the output folder
eleventyConfig.addPassthroughCopy({
"src/public/": "/",
});
// Naive copy of images for backwards compatibility of non short-code image handling (use of <img or in CSS)
eleventyConfig.addPassthroughCopy("src/**/images/**/*");
eleventyConfig.addPassthroughCopy("src/blueprints/**/flow.json");
eleventyConfig.addPassthroughCopy("src/events/hm25-invite.ics");
eleventyConfig.addPassthroughCopy("src/webinars/2025/simplifying-opc-ua/opc-ua-webinar-flows.zip");
eleventyConfig.addPassthroughCopy("src/js/ai-expert-modal.js");
eleventyConfig.addPassthroughCopy("src/js/hm-promo-banner.js");
eleventyConfig.addPassthroughCopy("src/js/nav-tracking.js");
eleventyConfig.addPassthroughCopy("src/js/signup-popup.js");
// Watch content images for the image pipeline
eleventyConfig.addWatchTarget("src/**/*.{svg,webp,png,jpeg,gif}");
eleventyConfig.setServerOptions({
// Additional files to watch that will trigger server updates
watch: ["_site/**/*.css", "_site/**/*.js"],
})
// CTA event/href/label data (single source of truth shared with the Nuxt
// Cta* components, which import the same src/_data/ctaDestinations.json)
// registered as a Nunjucks *global* rather than page data: the five
// ctaSignUp/ctaSignIn/ctaContactUs/ctaBookDemo/ctaPricing macros need to
// read it, and Nunjucks macros don't see page-context data
// (addGlobalData) unless it's explicitly passed in as an argument -
// addNunjucksGlobal makes it visible everywhere, macros included, with no
// per-call-site plumbing.
// Registered once with a stable object reference, then refreshed IN PLACE
// on every build (not re-registered via a second addNunjucksGlobal call,
// which only affected later builds - templates already held a reference
// to the first, now-stale value, so mid-watch edits rendered `undefined`
// until the whole process restarted). Mutating the same object's keys
// means every template holding a reference to it sees the update too.
const ctaDestinationsPath = require.resolve('./src/_data/ctaDestinations.json')
const ctaDestinations = require(ctaDestinationsPath)
eleventyConfig.addNunjucksGlobal('ctaDestinations', ctaDestinations)
eleventyConfig.addWatchTarget(ctaDestinationsPath)
eleventyConfig.on('eleventy.before', () => {
delete require.cache[ctaDestinationsPath]
const fresh = require(ctaDestinationsPath)
Object.keys(ctaDestinations).forEach(key => delete ctaDestinations[key])
Object.assign(ctaDestinations, fresh)
})
// make global accessible in src/_includes/layouts/base.njk for loading of PH scripts
eleventyConfig.addGlobalData('POSTHOG_APIKEY', () => process.env.POSTHOG_APIKEY || '' )
eleventyConfig.addGlobalData('DEV_MODE', () => DEV_MODE || DEV_MODE_POSTS)
eleventyConfig.addGlobalData('deployPreview', DEPLOY_PREVIEW)
// Custom Tooltip "Component"
eleventyConfig.addPairedShortcode("tooltip", function (content, text) {
return `<span class="ff-tooltip" data-tooltip="${text}">${content}</span><span></span>`
});
eleventyConfig.addPairedShortcode("blueCard", function(content) {
const md = new markdownIt();
let markdownContent = md.render(content);
return `<div class="ff-blue-card">${markdownContent}</div>`;
});
// Documentation alert boxes
eleventyConfig.addPairedLiquidShortcode('note', function (content) {
return renderDocsAlertBox(content, 'note')
})
eleventyConfig.addPairedLiquidShortcode('warning', function (content) {
return renderDocsAlertBox(content, 'warning')
})
eleventyConfig.addPairedLiquidShortcode('caution', function (content) {
return renderDocsAlertBox(content, 'caution')
})
let flowId = 0; // Keep a global counter to allow more than one
eleventyConfig.addPairedShortcode("renderFlow", function (flow, height = 200) {
flowId++; // Increment the flowId to allow multiple flows on the same page
return `<div id="nr-flow-${flowId}" style="height: ${height}px" data-grid-lines="true" data-zoom="true" data-images="true" data-link-lines="false" data-labels="true"></div>
<script type="module">const flow${flowId} = ${JSON.stringify(flow).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>')};
new FlowRenderer().renderFlows(JSON.parse(flow${flowId}.replace(/>/g,'>').replace(/</g,'<').replace(/&/g,'&')), { container: document.getElementById('nr-flow-${flowId}') })</script>`
});
eleventyConfig.addFilter("filterNodeCategory", function(nodes, category) {
if (category === "all") {
return nodes;
} else {
return nodes.filter(node => node.tags.includes(category));
}
});
// Custom filters
eleventyConfig.addFilter("json", (content) => {
return JSON.stringify(content)
});
// Resolves a chrome.json href of the form "site:<key>" against site.json,
// so single-sourced values (e.g. the job board URL) aren't duplicated as
// literal strings in the shared nav/footer data. Anything else passes through.
eleventyConfig.addFilter("resolveHref", (href, site) => {
if (typeof href === "string" && href.startsWith("site:")) {
return site[href.slice("site:".length)]
}
return href
});
eleventyConfig.addFilter("fromJson", (content) => {
try {
return JSON.parse(content);
} catch (e) {
console.error("Error parsing JSON:", e);
return content;
}
});
eleventyConfig.addFilter("head", (array, n) => {
if( n < 0 ) {
return array.slice(n);
}
return array.slice(0, n);
});
eleventyConfig.addFilter("limit", (arr, limit) => arr.slice(0, limit ));
// Marketing image for a nav highlight card: the linked page's image front matter
eleventyConfig.addFilter("pageImageForUrl", (collection, url) => {
const normalized = url && !url.endsWith("/") ? `${url}/` : url;
const match = (collection || []).find((p) => p.url === normalized);
return (match && match.data && match.data.image) || null;
});
eleventyConfig.addFilter('console', function (value) {
const str = util.inspect(value, { showHidden: false, depth: null });
return `<div style="white-space: pre-wrap;">${unescape(str)}</div>;`
});
eleventyConfig.addFilter('dictsortBy', function(val, reverse, attr) {
let array = [];
for (let k in val) {
// Preserve the key (slug) by adding it to the object
array.push({...val[k], _key: k});
}
array.sort((t1, t2) => {
var a = t1[attr];
var b = t2[attr];
return a > b ? 1 : (a === b ? 0 : -1); // eslint-disable-line no-nested-ternary
});
return array
});
eleventyConfig.addFilter('shortDate', dateObj => {
return spacetime(new Date(dateObj)).format('{date} {month-short}, {year}')
});
// Filter to safely convert values to Date objects
eleventyConfig.addFilter('toDate', value => {
if (!value) return new Date();
if (value instanceof Date) return value;
return new Date(value);
});
eleventyConfig.addFilter('formatNumber', num => {
if (num === undefined || num === null) return '0';
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
});
eleventyConfig.addFilter('md', (content) => {
if (!content) return '';
const md = new markdownIt({
html: true,
})
.use(markdownItAnchor, {
permalink: markdownItAnchor.permalink.headerLink()
});
return md.render(content);
});
eleventyConfig.addFilter('stripFirstH1', (str) => {
if (!str) return str;
// Remove the first h1 heading from the content to avoid duplicate h1 tags
// This is typically the package name which is already shown in the page header
return str.replace(/<h1[^>]*>.*?<\/h1>/, '');
});
eleventyConfig.addFilter('rewriteIntegrationLinks', (str, integration) => {
if (!str) return str;
// First pass: collect all actual anchor IDs from the HTML
const anchorIds = new Set();
const anchorIdRegex = /id="([^"]+)"/g;
let anchorMatch;
while ((anchorMatch = anchorIdRegex.exec(str)) !== null) {
anchorIds.add(anchorMatch[1]);
}
// Convert relative links in README to absolute links
const matcher = /((href|src)="([^"]*))"/g;
let match;
const result = str.replace(matcher, (fullMatch, group1, attr, url) => {
// Skip absolute URLs and mailto links
if (/^(http|https|mailto:)/.test(url)) {
return fullMatch;
}
// Handle same-page anchor links - try to fix broken anchors
if (url.startsWith('#')) {
const targetAnchor = url.substring(1);
// If the anchor doesn't exist, try to find a close match
if (!anchorIds.has(targetAnchor)) {
// Try to find anchors that match if we add periods back
// e.g., "migration-from-012-or-earlier" -> "migration-from-0.1.2-or-earlier"
for (const existingAnchor of anchorIds) {
// Remove all periods from existing anchor and compare
const normalizedExisting = existingAnchor.replace(/\./g, '');
if (normalizedExisting === targetAnchor) {
// Found a match! Use the correct anchor
return `${attr}="#${existingAnchor}"`;
}
}
}
return fullMatch;
}
// Convert relative links to repository links if available
if (integration.repository && integration.repository.url) {
const repoUrl = integration.repository.url
.replace('git+', '')
.replace('.git', '')
.replace('git://', 'https://');
// Handle different types of relative paths
if (url.startsWith('./') || url.startsWith('../')) {
const cleanUrl = url.replace(/^\.\.?\//, '');
return `${attr}="${repoUrl}/blob/master/${cleanUrl}"`;
} else if (url.startsWith('/')) {
// Repository-relative paths (e.g., /CHANGELOG.md)
const cleanUrl = url.replace(/^\//, '');
return `${attr}="${repoUrl}/blob/master/${cleanUrl}"`;
} else if (!url.startsWith('#')) {
// Simple relative paths without prefix
return `${attr}="${repoUrl}/blob/master/${url}"`;
}
}
return fullMatch;
});
return result;
});
eleventyConfig.addFilter('duration', mins => {
if (mins > 60) {
const hrs = Math.floor(mins/60)
return `${hrs}h ${mins%60}m`
}
else {
return `${mins} mins`
}
});
eleventyConfig.addFilter('inFuture', (posts) => {
// filter posts/webinars that only occurred in the past
if (posts) {
return posts.filter((post) => {
const postDate = spacetime(post.data.date)
return postDate.isAfter(spacetime.today()) || postDate.isSame(spacetime.today(), 'day')
})
} else {
return null
}
});
eleventyConfig.addFilter('inPast', (posts) => {
// filter posts/webinars that only occured in the past
return posts.filter((post) => {
const postDate = spacetime(post.data.date)
return postDate.isBefore(spacetime.today())
})
});
eleventyConfig.addFilter('dateInFuture', (date) => {
// return true is the provided date is in the past, otherwise, return false
const postDate = spacetime(date)
return postDate.isAfter(spacetime.today()) || postDate.isSame(spacetime.today(), 'day')
});
eleventyConfig.addFilter('countDays', (date) => {
// return true is the provided date is in the past, otherwise, return false
const postDate = spacetime(date)
const now = spacetime.now().startOf('day')
const days = now.diff(postDate, 'day') + 1
if (days === 0) {
return { value: 0, text: 'Today'}
} else if (days === 1) {
return { value: 1, text: 'Tomorrow'}
} else {
return { value: days, text: `${days} Days Away`}
}
});
eleventyConfig.addFilter("truncate", function(text, maxWordCount) {
if (text === undefined || text === null || text === "") {
return "";
}
text = String(text);
const split = text.split(" ");
if (split.length <= maxWordCount) {
return text;
}
return text.split(" ").splice(0, maxWordCount).join(" ") + "..."
});
eleventyConfig.addFilter("striptags", function(text) {
return decodeHTML(String(text).replace(/<[^>]+>/g, ""));
});
eleventyConfig.addFilter("readingTime", function(content) {
if (!content) {
return 1;
}
const words = String(content).replace(/<[^>]+>/g, " ").split(/\s+/).filter(Boolean).length;
return Math.max(1, Math.ceil(words / 200));
});
eleventyConfig.addFilter("restoreParagraphs", function(str) {
const content = new String(str);
return "<p>"+content.split(/\.\n/).join(".</p><p>")+"</p>"
});
eleventyConfig.addFilter("toAbsoluteUrl", function(url) {
return new URL(url, site.baseURL).href;
})
eleventyConfig.addFilter("stripLinks", function(text) {
return String(text).replace(/<a\s[^>]*>([\s\S]*?)<\/a>/gi, '$1');
});
eleventyConfig.addFilter("handbookBreadcrumbs", (url) => {
let parts = url.split("/").filter(e => e !== '');
if (parts[parts.length-1] === "index") {
parts.pop();
}
let path = "";
return "/"+parts.map(p => {
let url = `${path}/${p}`;
path = url;
return `<a class="mx-2" href="${url}/">${p}</a>`
}).join("/")
});
eleventyConfig.addFilter("rewriteHandbookLinks", (str, page) => {
const isIndexPage = /(README.md|index.md)$/i.test(page.inputPath)
return str.replace(/(href|src)="([^"]*)"/g, (full, attr, url) => {
if (/^(http|#|mailto:)/.test(url)) {
return full
}
url = url.replace(/.md(#.*)?$/, '$1')
url = url.replace(/README(#.*)?$/, '$1')
if (url[0] !== '/' && !isIndexPage) {
url = '../'+url
}
return `${attr}="${url}"`
})
})
eleventyConfig.addFilter("handbookEditLink", (page) => {
let baseUrl = 'https://github.com/FlowFuse/website/edit/main/'
let filePath = page.inputPath
if (/^\/docs/.test(page.url)) {
pathElements = page.inputPath.split(path.sep)
if (pathElements[pathElements.length - 1] === "index.md") {
pathElements[pathElements.length - 1] = "README.md"
}
filePath = path.join(...pathElements.slice(2))
baseUrl = 'https://github.com/FlowFuse/flowfuse/edit/main/'
}
return baseUrl+filePath.replace(/^.\//,'')
})
eleventyConfig.addFilter("pageOwners", (page) => {
// Eleventy's inputPath is relative, we need to drop the './' in front
return new codeowners().getOwner(page.inputPath.substring(2))
});
eleventyConfig.addFilter("ghUsersToTeamMembers", (ghUsers, team) => {
let teamMembers = [];
for (let i = 0; i < ghUsers.length; i++) {
const ghUser = ghUsers[i];
Object.keys(team).forEach(function (member) {
if (team[member].github === ghUser.substring(1)) {
teamMembers.push(team[member])
}
})
}
return teamMembers
});
eleventyConfig.addFilter("relatedPosts", function (collection = []) {
const { tags: requiredTags, page } = this.ctx;
return collection
.map(post => {
const commonTags = requiredTags?.reduce((count, tag) => count + (post.data.tags?.includes(tag) ? 1 : 0), 0);
return { ...post, commonTags };
})
.filter(post => post.url !== page.url && post.commonTags >= requiredTags.length - 1)
.sort((a, b) => b.commonTags - a.commonTags || b.date - a.date)
.slice(0, 5);
});
// Custom async filters
eleventyConfig.addNunjucksAsyncFilter("jsmin", async function (code, callback) {
try {
const minified = await minify(code);
callback(null, minified.code);
} catch (err) {
console.error("Terser error: ", err);
// Fail gracefully.
callback(null, code);
}
});
eleventyConfig.addShortcode("renderTeamMember", function (teamMember) {
// When the author is no longer at FlowFuse
if (typeof teamMember === "undefined" || teamMember === null) {
return `<div class="team-card--sm">
<div class="ff-headshot" style="background-image: url(/images/flowfuse-icon.png)"></div>
<div class="team-card-info my-auto">
<label>FlowFuse</label>
</div>
</div>`
}
return `<div class="team-card--sm">
<div class="ff-headshot" style="background-image: url(/images/team/headshot-${teamMember.headshot})"></div>
<div class="team-card-info">
<label>${teamMember.name}</label>
<span>${teamMember.title}</span>
</div>
</div>`
});
eleventyConfig.addShortcode("renderCompanyTile", function (company) {
return `<div class="company-tile">
<img class="company-tile-logo" src="${company.img}" />
<a href="${company.url}" class="no-underline text-gray-700">${company.name}</a>
</div>`
});
eleventyConfig.addShortcode("renderIntegration", function (integration) {
return `<div class="integration-tile">
<img class="integration-tile-icon" src="${integration.img}" />
<label>${integration.name}</label>
</div>`
});
eleventyConfig.addShortcode("year", () => `${new Date().getFullYear()}`);
function loadSVG (file) {
let relativeFilePath = `./src/_includes/components/icons/${file}.svg`;
let data = fs.readFileSync(relativeFilePath, function(err, contents) {
if (err) return err
return contents
});
return data.toString('utf8');
}
eleventyConfig.addFilter("templateExists", function(name){
return fs.existsSync(name)
})
eleventyConfig.addShortcode("ffIconLg", function(icon, isSolid) {
const svg = loadSVG(icon)
if (!isSolid) {
return `<svg class="ff-icon ff-icon-lg" fill="none" viewbox="0 0 24 24">${svg}</svg>`
} else {
return `<svg class="ff-icon ff-icon-lg ff-icon--solid" fill="none" viewbox="0 0 24 24">${svg}</svg>`
}
});
eleventyConfig.addPairedShortcode("navoption", function(content, label, link, depth, icon, iconSolid, addClasses) {
let svg, iconSvg = '', classes, chevron
if (icon) {
svg = loadSVG(icon)
if (!iconSolid) {
iconSvg = `<svg class="ff-icon ff-icon-sm" fill="none" viewbox="0 0 24 24">${svg}</svg>`
} else {
iconSvg = `<svg class="ff-icon ff-icon-sm ff-icon--solid" fill="none" viewbox="0 0 24 24">${svg}</svg>`
}
}
if (content) {
classes = "ff-nav-dropdown relative hover:cursor-pointer " + (addClasses || '')
} else {
classes= (addClasses || '')
}
if (content) {
const chevronDown = loadSVG('chevron-down')
// data-nav-section labels every link inside this panel for nav-click
// tracking (src/js/nav-tracking.js), independent of styling classes.
return `<li class="${classes}" data-nav-section="${label}"><span class="flex items-center gap-1">${iconSvg}<span class="ff-nav-label">${label}</span><span class="ff-nav-chevron">${chevronDown}</span></span>${content}</li>`
} else if (link) {
return `<li class="${classes}"><a class="flex items-center gap-2" href="${link}">${iconSvg}<span class="ff-nav-label">${label}</span></a></li>`
} else {
return `<li class="${classes}"><span class="flex items-center gap-2">${iconSvg}<span class="ff-nav-label">${label}</span></span></li>`
}
});
// Eleventy Image shortcode
// https://www.11ty.dev/docs/plugins/image/
if (SKIP_IMAGES) {
console.info(`[11ty] Image pipeline is enabled in dev mode, copying images without any conversion or resizing`)
} else {
console.info(`[11ty] Image pipeline is enabled in prod mode, expect a wait for first build while images are converted and resized`)
}
eleventyConfig.addAsyncShortcode("image", async function imageShortcode(src, alt, widths, sizes) {
const title = null
const currentWorkingFilePath = this.page.inputPath
return await imageHandler(src, alt, title, widths, sizes, currentWorkingFilePath, eleventyConfig, async=true, SKIP_IMAGES)
});
/*
Window chrome around a recording of a terminal session. Shared by the Device
Agent page and release posts so every frame looks the same; the frame's own
padding scales with the viewport, see .ff-terminal-frame in style.css.
The recording is deliberately not zoomable: the frame is the point, and a
zoom overlay on an animated GIF restarts it out of context.
*/
eleventyConfig.addAsyncShortcode("terminalFrame", async function terminalFrameShortcode(src, alt, width) {
const maxWidth = Number(width) || 1000
const currentWorkingFilePath = this.page.inputPath
const image = await imageHandler(src, alt, null, [maxWidth], null, currentWorkingFilePath, eleventyConfig, async=true, SKIP_IMAGES)
return `<div class="ff-terminal-frame" style="max-width: ${maxWidth}px">
<div class="ff-terminal-frame__bar">
<span class="ff-terminal-frame__dot ff-terminal-frame__dot--close"></span>
<span class="ff-terminal-frame__dot ff-terminal-frame__dot--minimise"></span>
<span class="ff-terminal-frame__dot ff-terminal-frame__dot--expand"></span>
</div>
<div class="ff-terminal-frame__screen">${image}</div>
</div>`
});
eleventyConfig.addAsyncShortcode("tileImage", async function(item, image, defaultImage, defaultDescription, imageSize, title = null, priority = false) {
let imageSrc, imageDescription;
if (item && item.data && item.data.image) {
// item.data.image exists
imageSrc = `./${item.data.image}`;
imageDescription = `Image representing ${item.data.title}`;
} else if (image) {
// image exists
imageSrc = `./${image}`;
imageDescription = `Image representing ${title}`;
} else {
// use default values
imageSrc = defaultImage;
imageDescription = defaultDescription;
}
const currentWorkingFilePath = this.page.inputPath;
return await imageHandler(imageSrc, imageDescription, title, [imageSize], null, currentWorkingFilePath, eleventyConfig, async=true, SKIP_IMAGES, priority);
});
// Placeholder: docs nav collection removed (docs served by Nuxt)
// Docs nav moved to Nuxt; this empty collection keeps left-nav.njk from erroring
eleventyConfig.addCollection('nav', function() { return {} });
eleventyConfig.addCollection("aiBlog", function(collectionApi) {
return collectionApi.getFilteredByTag("ai").filter(item => {
return !item.data.tags || !item.data.tags.includes("blueprints");
});
});
eleventyConfig.addCollection("homeLogos", function () {
const logosDir = path.join(__dirname, "src/images/home-logos");
const logos = fs.readdirSync(logosDir)
.filter(file => file.endsWith(".svg") || file.endsWith(".png"))
.map(file => path.join("images/home-logos", file));
return logos;
});
eleventyConfig.addCollection("publications", function(collectionApi) {
return collectionApi.getAll().filter(item => {
return item.data.tags && (item.data.tags.includes("whitepaper") || item.data.tags.includes("ebook"));
}).map(item => {
item.data.tags = item.data.tags.map(tag => {
if (tag.toLowerCase() === 'whitepaper') {
return 'Whitepaper';
} else if (tag.toLowerCase() === 'ebook') {
return 'eBook';
}
return tag;
});
return item;
});
});
// Plugins
eleventyConfig.addPlugin(EleventyRenderPlugin)
eleventyConfig.addPlugin(pluginRSS)
eleventyConfig.addPlugin(syntaxHighlight)
eleventyConfig.addPlugin(codeClipboard)
eleventyConfig.addPlugin(pluginMermaid)
eleventyConfig.addPlugin(eleventyNavigationPlugin);
eleventyConfig.addPlugin(pluginTOC, {
tags: ['h2', 'h3', 'h4'],
wrapper: 'div',
wrapperClass: 'toc',
ul: true,
});
const markdownItOptions = {
html: true,
}
const markdownItAnchorOptions = {
permalink: markdownItAnchor.permalink.headerLink()
}
const markdownLib = markdownIt(markdownItOptions)
.use(markdownItAnchor, markdownItAnchorOptions)
.use(markdownItFootnote)
.use(markdownItAttrs)
.use(codeClipboard.markdownItCopyButton, {
iconifyUrl: '',
additionalButtonClass: 'mdi mdi-content-copy',
iconStyle: 'background: initial',
})
markdownLib.renderer.rules.image = function (tokens, idx, options, env, self) {
const token = tokens[idx]
const imgSrc = token.attrGet('src')
const imgAlt = token.content
const imgTitle = token.attrGet('title')
// Get all the attributes of the image
const attributes = token.attrs.reduce((acc, attr) => {
acc[attr[0]] = attr[1];
return acc;
}, {});
const folderPath = env.page.inputPath
// Check if the image has the 'data-zoomable' attribute
const widths = 'data-zoomable' in attributes ? [1920] : [650]; // maximum width an image can be displayed at as part of blog prose
const htmlSizes = null
const async = false // cannot run async inside markdown
try {
let imageHtml = imageHandler(imgSrc, imgAlt, imgTitle, widths, htmlSizes, folderPath, eleventyConfig, async, SKIP_IMAGES)
// Add the additional attributes to the image
for (let attr in attributes) {
if (attr !== 'src' && attr !== 'alt' && attr !== 'title') {
imageHtml = imageHtml.replace('<img', `<img ${attr}="${attributes[attr]}"`);
}
}
return imageHtml;
} catch (error) {
console.error(`Image generation error while handling: ${imgSrc} in ${folderPath} - ${error}, consider using @skip`)
throw error
}
}
markdownLib.renderer.rules.link_open = (tokens, idx, options, env, self) => {
const hrefIndex = tokens[idx].attrIndex('href');
if (hrefIndex >= 0) {
let href = tokens[idx].attrs[hrefIndex][1];
const classIndex = tokens[idx].attrIndex('class');
// Exclude the link if it has the class 'header-anchor'
if (classIndex >= 0 && tokens[idx].attrs[classIndex][1] === 'header-anchor') {
return self.renderToken(tokens, idx, options);
}
// Ensure the URL has a trailing slash, but do not update if it contains a '#' or ends with '.md' or https
if (!href.endsWith('/') && !href.includes('#') && !href.endsWith('.md') && !href.endsWith('.zip') && !href.includes('https')) {
href += '/';
}
tokens[idx].attrs[hrefIndex][1] = href;
}
return self.renderToken(tokens, idx, options);
};
eleventyConfig.setLibrary("md", markdownLib)
if (!DEV_MODE) {
console.info(`[11ty] Output HTML will be minified, expect a short wait`)
eleventyConfig.addTransform("htmlmin", async function (content) {
if (this.page.outputPath && this.page.outputPath.endsWith(".html")) {
let minified = await htmlmin.minify(content, {
collapseBooleanAttributes: true,
collapseWhitespace: true,
conservativeCollapse: true,
preserveLineBreaks: true,
removeComments: true,
removeEmptyAttributes: true,
removeRedundantAttributes: true,
useShortDoctype: true,
})
return minified
}
return content
})
}
return {
dir: {
input: "src"
}
}
};