eleventy.config.mjs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. import { appFilters } from "../shared/e11ty/filters.mjs"
  2. import { appData, getCopyList } from "../shared/e11ty/data.mjs";
  3. import { readFileSync, existsSync } from 'node:fs';
  4. import { fileURLToPath } from 'node:url'
  5. import { join, dirname } from 'node:path';
  6. import beautify from 'js-beautify';
  7. import { EleventyRenderPlugin } from "@11ty/eleventy";
  8. const shiki = await import('shiki');
  9. import { createCssVariablesTheme } from 'shiki/core'
  10. const __dirname = dirname(fileURLToPath(import.meta.url))
  11. export default function (eleventyConfig) {
  12. const environment = process.env.NODE_ENV || "production";
  13. appFilters(eleventyConfig);
  14. appData(eleventyConfig);
  15. eleventyConfig.addPlugin(EleventyRenderPlugin, {
  16. accessGlobalData: true,
  17. });
  18. eleventyConfig.addPassthroughCopy({
  19. ...getCopyList(),
  20. "public": "/",
  21. "static": "static",
  22. });
  23. eleventyConfig.addCollection('docs', collection => {
  24. return [...collection.getFilteredByGlob('./content/**/*.md')].sort((a, b) => {
  25. return a.data.title - b.data.title;
  26. });
  27. });
  28. eleventyConfig.setInputDirectory("content");
  29. eleventyConfig.setOutputDirectory("dist");
  30. eleventyConfig.setLayoutsDirectory("../../shared/layouts");
  31. eleventyConfig.setIncludesDirectory("../../shared/includes");
  32. eleventyConfig.setDataDirectory("../../shared/data");
  33. eleventyConfig.amendLibrary('md', () => { });
  34. eleventyConfig.addShortcode('scss-docs', function (name, filename) {
  35. const file = join(__dirname, `../core/scss/${filename}`)
  36. if (existsSync(file)) {
  37. const content = readFileSync(file, 'utf8');
  38. const regex = new RegExp(`\/\/\\sscss-docs-start\\s${name}\\n(.+?)\/\/\\sscss-docs-end`, 'gs')
  39. const m = content.matchAll(regex)
  40. if (m) {
  41. const matches = [...m]
  42. if (matches[0] && matches[0][1]) {
  43. const lines = matches[0][1].split('\n');
  44. // Find minimum number of leading spaces in non-empty lines
  45. const minIndent = lines
  46. .filter(line => line.trim().length > 0)
  47. .reduce((min, line) => {
  48. const match = line.match(/^(\s*)/);
  49. const leadingSpaces = match ? match[1].length : 0;
  50. return Math.min(min, leadingSpaces);
  51. }, Infinity);
  52. // Remove that many spaces from the start of each line
  53. const result = lines.map(line => line.startsWith(' '.repeat(minIndent))
  54. ? line.slice(minIndent)
  55. : line).join('\n');
  56. return "\n```scss\n" + result.trimRight() + "\n```\n"
  57. }
  58. }
  59. }
  60. return ''
  61. })
  62. // Shiki
  63. eleventyConfig.on('eleventy.before', async () => {
  64. const myTheme = createCssVariablesTheme({
  65. name: 'css-variables',
  66. variablePrefix: '--shiki-',
  67. variableDefaults: {},
  68. fontStyle: true
  69. })
  70. const highlighter = await shiki.createHighlighter({
  71. themes: ['github-dark', myTheme],
  72. langs: [
  73. 'html',
  74. 'blade',
  75. 'php',
  76. 'yaml',
  77. 'js',
  78. 'jsx',
  79. 'ts',
  80. 'shell',
  81. 'diff',
  82. 'vue',
  83. 'scss',
  84. 'css'
  85. ],
  86. });
  87. eleventyConfig.amendLibrary('md', function (mdLib) {
  88. return mdLib.set({
  89. highlight: function (code, lang) {
  90. // prettify code
  91. if(lang === 'html') {
  92. code = beautify.html(code, {
  93. indent_size: 2,
  94. wrap_line_length: 80,
  95. });
  96. }
  97. let highlightedCode = highlighter.codeToHtml(code, {
  98. lang: lang,
  99. theme: 'github-dark'
  100. });
  101. return highlightedCode;
  102. },
  103. });
  104. }
  105. );
  106. });
  107. /**
  108. * Filters
  109. */
  110. function buildCollectionTree(flatData) {
  111. const tree = [];
  112. const lookup = {};
  113. flatData
  114. .filter(item => item.url !== '/')
  115. .forEach(item => {
  116. lookup[item.url] = { ...item, children: [] };
  117. });
  118. flatData.forEach(item => {
  119. const parts = item.url.split('/').filter(Boolean);
  120. if (parts.length === 1) {
  121. tree.push(lookup[item.url]);
  122. } else {
  123. const parentUrl = '/' + parts.slice(0, -1).join('/') + '/';
  124. if (lookup[parentUrl]) {
  125. lookup[parentUrl].children.push(lookup[item.url]);
  126. } else {
  127. tree.push(lookup[item.url]);
  128. }
  129. }
  130. });
  131. return tree;
  132. }
  133. eleventyConfig.addFilter("collection-tree", function (collection) {
  134. const a = collection.map(item => {
  135. return {
  136. data: item.data,
  137. page: item.page,
  138. url: item.url,
  139. children: []
  140. }
  141. }).sort((a, b) => {
  142. return (a.data.order || 999) - (b.data.order || 999);
  143. });
  144. return buildCollectionTree(a);
  145. });
  146. eleventyConfig.addFilter("collection-children", function (collection, page) {
  147. const url = page.url.split('/').filter(Boolean).join('/');
  148. const filteredCollection = collection.filter(item => {
  149. const parts = item.url.split('/').filter(Boolean);
  150. return parts.length > 1 && parts.slice(0, -1).join('/') === url;
  151. });
  152. return filteredCollection.sort((a, b) => {
  153. return (a.data?.order || 999) - (b.data?.order || 999);
  154. });
  155. });
  156. eleventyConfig.addFilter("next-prev", function (collection, page) {
  157. const items = collection
  158. .filter(item => {
  159. const parts = item.url.split('/').filter(Boolean);
  160. return parts.length > 1 && parts.slice(0, -1).join('/') === page.url.split('/').filter(Boolean).slice(0, -1).join('/');
  161. })
  162. .sort((a, b) => {
  163. return a.data.title.localeCompare(b.data.title);
  164. })
  165. .sort((a, b) => {
  166. return (a.data?.order || 999) - (b.data?.order || 999);
  167. });
  168. const index = items.findIndex(item => item.url === page.url);
  169. const prevPost = index > 0 ? items[index - 1] : null;
  170. const nextPost = index < items.length - 1 ? items[index + 1] : null;
  171. return {
  172. prev: prevPost ? prevPost : null,
  173. next: nextPost ? nextPost : null,
  174. };
  175. });
  176. const generateUniqueId = (text) => {
  177. return text
  178. .replace(/<[^>]+>/g, "")
  179. .replace(/\s/g, "-")
  180. .replace(/[^\w-]+/g, "")
  181. .replace(/--+/g, "-")
  182. .replace(/^-+|-+$/g, "")
  183. .toLowerCase();
  184. }
  185. eleventyConfig.addFilter("headings-id", function (content) {
  186. return content.replace(/<h([1-6])>([^<]+)<\/h\1>/g, (match, level, text) => {
  187. const headingId = generateUniqueId(text);
  188. return `<h${level} id="${headingId}">${text}</h${level}>`;
  189. });
  190. })
  191. eleventyConfig.addFilter("toc", function (name) {
  192. const toc = [];
  193. const contentWithoutExamples = name.replace(/<div[^>]*\bclass=["'][^"']*\bexample\b[^"']*".*?>.*?<\/div>/gs, '');
  194. const headings = contentWithoutExamples.match(/<h([23])>(.*?)<\/h\1>/g);
  195. if (headings) {
  196. headings.forEach(heading => {
  197. const level = parseInt(heading.match(/<h([1-6])>/)[1]);
  198. const text = heading.replace(/<[^>]+>/g, "");
  199. const id = generateUniqueId(text);
  200. toc.push({ level, text, id });
  201. });
  202. }
  203. return toc;
  204. })
  205. eleventyConfig.addFilter("remove-href", function (content) {
  206. return content.replace(/href="#"/g, 'href="javascript:void(0)"');
  207. })
  208. /**
  209. * Data
  210. */
  211. const pkg = JSON.parse(readFileSync(join("..", "core", "package.json"), "utf-8"))
  212. eleventyConfig.addGlobalData("environment", environment);
  213. eleventyConfig.addGlobalData("package", pkg);
  214. eleventyConfig.addGlobalData("cdnUrl", `https://cdn.jsdelivr.net/npm/@tabler/core@${pkg.version}`);
  215. const data = {
  216. iconsCount: () => 123,
  217. emailsCount: () => 123,
  218. illustrationsCount: () => 123
  219. };
  220. for (const [key, value] of Object.entries(data)) {
  221. eleventyConfig.addGlobalData(key, value);
  222. }
  223. eleventyConfig.addGlobalData("docs-links", [
  224. { title: 'Website', url: 'https://tabler.io', icon: 'world' },
  225. { title: 'Preview', url: 'https://preview.tabler.io', icon: 'layout-dashboard' },
  226. { title: 'Support', url: 'https://tabler.io/support', icon: 'headset' },
  227. ]);
  228. /**
  229. * Tags
  230. */
  231. eleventyConfig.addPairedShortcode("cards", function (content) {
  232. return `<div class="mt-6"><div class="row g-3">${content}</div></div>`;
  233. });
  234. eleventyConfig.addPairedShortcode("card", function (content, title, href) {
  235. return `<div class="col-6">
  236. <${href ? "a" : "div"} href="${href}" class="card ${href ? "" : " bg-surface-tertiary"}">
  237. <div class="card-body">
  238. <div class="position-relative">${href ? "" : `<span class="badge position-absolute top-0 end-0">Coming soon</span>`}
  239. <div class="row align-items-center">
  240. <div class="col">
  241. <h3 class="card-title mb-2">${title}</h3>
  242. <div class="text-secondary small">${content}</div>
  243. </div>
  244. <div class="col-auto">
  245. <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="icon icon-tabler icons-tabler-outline icon-tabler-chevron-right"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M9 6l6 6l-6 6" /></svg>
  246. </div>
  247. </div>
  248. </div>
  249. </div>
  250. </${href ? "a" : "div"}>
  251. </div>`;
  252. });
  253. };