index.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. const hljs = require("highlight.js");
  2. const MAP = {
  3. py: "python",
  4. js: "javascript",
  5. json: "javascript",
  6. rb: "ruby",
  7. csharp: "cs"
  8. };
  9. function normalize(lang) {
  10. if (!lang) {
  11. return null;
  12. }
  13. const lower = lang.toLowerCase();
  14. return MAP[lower] || lower;
  15. }
  16. /**
  17. * @param {string} lang
  18. * @param {string} code
  19. * @returns {string|{html: boolean, body}}
  20. */
  21. function highlight(lang, code) {
  22. if (!lang)
  23. return {
  24. body: code,
  25. html: false
  26. };
  27. // Normalize lang
  28. lang = normalize(lang);
  29. try {
  30. return hljs.highlight(code, {
  31. language: lang
  32. }).value;
  33. } catch (e) {
  34. console.error(e);
  35. }
  36. return {
  37. body: code,
  38. html: false
  39. };
  40. }
  41. module.exports = {
  42. book: {
  43. assets: "./css",
  44. css: ["website.css"]
  45. },
  46. ebook: {
  47. assets: "./css",
  48. css: ["ebook.css"]
  49. },
  50. blocks: {
  51. code: function (block) {
  52. return highlight(block.kwargs.language, block.body);
  53. }
  54. }
  55. };