-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy path.eleventy.js
307 lines (266 loc) · 9.05 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
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
const beautifyHTML = require("js-beautify").html;
const fs = require("fs");
const hljs = require("highlight.js");
const markdownIt = require("markdown-it");
const markdownItAnchor = require("markdown-it-anchor");
const matter = require("gray-matter");
const mojFilters = require("./src/moj/filters/all");
const nunjucks = require("nunjucks");
const path = require("path");
const { execSync } = require("child_process");
const releasePackage = require("./package/package.json");
const sass = require("sass");
const esbuild = require('esbuild');
const eleventyNavigationPlugin = require("@11ty/eleventy-navigation");
module.exports = function (eleventyConfig) {
eleventyConfig.addPlugin(eleventyNavigationPlugin);
/*
* If the node env is 'dev' then we include the src dir allowing components
* under development to be watched and loaded
*/
const templatePaths =
process.env.ENV === "dev"
? [
".",
"src",
"docs/_includes/",
"node_modules/govuk-frontend/dist/",
"node_modules/@ministryofjustice/frontend/",
]
: [
".",
"docs/_includes/",
"node_modules/govuk-frontend/dist/",
"node_modules/@ministryofjustice/frontend/",
];
const nunjucksEnv = nunjucks.configure(templatePaths);
Object.entries({
...eleventyConfig.nunjucksFilters,
...mojFilters(),
}).forEach(([name, callback]) => {
nunjucksEnv.addFilter(name, callback);
});
nunjucksEnv.addFilter("eleventyNavigation", eleventyNavigationPlugin.navigation.find);
eleventyConfig.setLibrary("njk", nunjucksEnv);
eleventyConfig.setLibrary(
"md",
markdownIt({
html: true,
typographer: true,
quotes: '“”‘’',
highlight: (str, language) =>
language ? hljs.highlight(str, { language }).value : str,
})
.disable("code")
.use(markdownItAnchor, {
level: [1, 2, 3, 4],
}),
);
eleventyConfig.addShortcode("example", function (exampleHref, height) {
let { data, content: nunjucksCode } = matter(
fs
.readFileSync(
path.join(__dirname, "docs", exampleHref, "index.njk"),
"utf8",
)
.trim(),
);
nunjucksCode = nunjucksCode.split("<!--no include-->")[0].trim();
const rawHtmlCode = nunjucksEnv.renderString(nunjucksCode);
const htmlCode = beautifyHTML(rawHtmlCode.trim(), {
indent_size: 2,
end_with_newline: true,
max_preserve_newlines: 1,
unformatted: ["code", "pre", "em", "strong"],
});
let jsCode = "";
try {
jsCode = fs
.readFileSync(
path.join(__dirname, "docs", exampleHref, "script.js"),
"utf8",
)
.trim();
} catch (e) {}
return nunjucksEnv.render("example.njk", {
href: exampleHref,
id: exampleHref.replace(/\//g, "-"),
arguments: data.arguments,
figmaLink: data.figma_link,
title: data.title,
height,
nunjucksCode,
htmlCode,
jsCode,
});
});
eleventyConfig.addShortcode(
"dateInCurrentMonth",
(day) => `${day}/${new Date().getMonth() + 1}/${new Date().getFullYear()}`,
);
eleventyConfig.addShortcode("lastUpdated", function (component) {
if (process.env.ENV == "staging") return "";
const dirPath = path.join(__dirname, "src/moj/components", component);
const [commit, lastUpdated] = execSync(
`LANG=en_GB git log -n1 --pretty=format:%H,%ad --date=format:'%e %B %Y' ${dirPath}`,
)
.toString()
.split(",");
return `<p>Last updated: <a href="https://github.com/ministryofjustice/moj-frontend/commit/${commit}">${lastUpdated}</a></p>`;
});
eleventyConfig.addShortcode("version", function () {
return releasePackage.version;
});
// Temp storage for tabs
let tabsStorage = [];
// Generate govuk tabs
eleventyConfig.addPairedShortcode("tabs", function (content, label = "Contents") {
const tabId = (tab) => {
return `${tab.label.toLowerCase().replace(/ /g, "-")}-tab`
}
const tabsList = tabsStorage.map((tab, index) => {
const isSelected = index === 0 ? '--selected' : '';
return `
<li class="govuk-tabs__list-item${isSelected} app-navigation__item" role="presentation">
<a class="govuk-tabs__tab app-navigation__link app-navigation__link" href="#${tabId(tab)}" role="tab" >
${tab.label}
</a>
</li>
`.trim();
}).join("\n").trim();
const tabPanels = tabsStorage.map((tab, index) => {
const isHidden = index === 0 ? '' : ' govuk-tabs__panel--hidden';
return `
<div class="govuk-tabs__panel${isHidden}" id="${tabId(tab)}" role="tabpanel">${tab.content}</div>
`.trim();
}).join("").trim();
tabsStorage = [];
return `
<div class="govuk-tabs app-navigation no-govuk-tabs-styles" data-module="govuk-tabs">
<h2 class="govuk-tabs__title">${label}</h2>
<ul class="govuk-tabs__list app-navigation__list" role="tabpanel">
${tabsList}
</ul>
${tabPanels}
</div>
`.trim();
});
// Find and store govuk tab for above tabs
eleventyConfig.addPairedShortcode("tab", function (content, label) {
tabsStorage.push({ label, content });
return "";
});
eleventyConfig.addPairedShortcode("banner", function (content, title) {
return `
<div class="govuk-notification-banner" role="region" aria-labelledby="govuk-notification-banner-title" data-module="govuk-notification-banner">
<div class="govuk-notification-banner__header">
<h2 class="govuk-notification-banner__title" id="govuk-notification-banner-title">
Important
</h2>
</div>
<div class="govuk-notification-banner__content">
<h3 class="govuk-notification-banner__heading">
${title}
</h3>
${content}</div>
</div>
`;
});
// Temp storage for tabs
let accordionSections = [];
// Generate govuk tabs
eleventyConfig.addPairedShortcode("accordion", function (content, accordionId) {
const sectionId = (section) => {
return `${section.label.toLowerCase().replace(/ /g, "-")}-section`
}
const contentId = (section,index) => {
return `${accordionId}-content-${index}`
}
const accordionContent = accordionSections.map((section,index) => {
return `
<div class="govuk-accordion__section">
<div class="govuk-accordion__section-header">
<h2 class="govuk-accordion__section-heading">
<span class="govuk-accordion__section-button" id="${sectionId(section)}">
${section.label}
</span>
</h2>
</div>
<div id="${contentId(section,index+1)}" class="govuk-accordion__section-content">${section.content}</div>
</div>
`.trim();
}).join("").trim();
accordionSections = [];
return `
<div class="govuk-accordion" data-module="govuk-accordion" id="${accordionId}">
${accordionContent}
</div>
`.trim();
});
// Find and store govuk tab for above tabs
eleventyConfig.addPairedShortcode("accordionSection", function (content, label) {
accordionSections.push({ label, content });
return "";
});
eleventyConfig.addFilter(
"addActiveAttribute",
function (config, filePathStem) {
if (config.items) {
return {
...config,
items: config.items.map((item) => ({
...item,
active: filePathStem.indexOf(item.href) > -1,
})),
};
} else if (config.sections) {
return {
...config,
sections: config.sections.map((section) => ({
...section,
items: section.items.map((item) => ({
...item,
active: filePathStem.indexOf(item.href) > -1,
})),
})),
};
}
},
);
eleventyConfig.addFilter("getScriptPath", function (inputPath) {
return inputPath.split("/").slice(1, -1).join("/") + "/script.js";
});
eleventyConfig.addFilter("getStylesPath", function (inputPath) {
return inputPath.split("/").slice(1, -1).join("/") + "/style.css";
});
eleventyConfig.addFilter(
"rev",
(filepath) => {
if (process.env.ENV == "production" || process.env.ENV == "staging") {
const manifest = JSON.parse(fs.readFileSync('public/assets/rev-manifest.json', 'utf8'));
const revision = manifest[filepath]
return `/${revision || filepath}`
} else {
return `/${filepath}`
}
}
)
// Rebuild when a change is made to a component template file
eleventyConfig.addWatchTarget("src/moj/components/**/*.njk");
// Give gulp a little time..
eleventyConfig.setWatchThrottleWaitTime(100);
eleventyConfig.setServerOptions({
liveReload: true,
domDiff: false,
port: 8080,
// Reload once assets have been rebuilt by gulp
watch: [
"public/assets/stylesheets/application.css",
"public/assets/javascript/all.js",
],
// Show local network IP addresses for device testing
showAllHosts: true,
// Show the dev server version number on the command line
showVersion: true,
});
};