eleventy.config.mjs 8.3 KB

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