prism-custom-class.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. (function () {
  2. if (typeof Prism === 'undefined') {
  3. return;
  4. }
  5. /**
  6. * @callback ClassMapper
  7. * @param {string} className
  8. * @param {string} language
  9. * @returns {string}
  10. *
  11. * @callback ClassAdder
  12. * @param {ClassAdderEnvironment} env
  13. * @returns {undefined | string | string[]}
  14. *
  15. * @typedef ClassAdderEnvironment
  16. * @property {string} language
  17. * @property {string} type
  18. * @property {string} content
  19. */
  20. // options
  21. /** @type {ClassAdder | undefined} */
  22. var adder;
  23. /** @type {ClassMapper | undefined} */
  24. var mapper;
  25. /** @type {string} */
  26. var prefixString = '';
  27. /**
  28. * @param {string} className
  29. * @param {string} language
  30. */
  31. function apply(className, language) {
  32. return prefixString + (mapper ? mapper(className, language) : className);
  33. }
  34. Prism.plugins.customClass = {
  35. /**
  36. * Sets the function which can be used to add custom aliases to any token.
  37. *
  38. * @param {ClassAdder} classAdder
  39. */
  40. add: function (classAdder) {
  41. adder = classAdder;
  42. },
  43. /**
  44. * Maps all class names using the given object or map function.
  45. *
  46. * This does not affect the prefix.
  47. *
  48. * @param {Object<string, string> | ClassMapper} classMapper
  49. */
  50. map: function map(classMapper) {
  51. if (typeof classMapper === 'function') {
  52. mapper = classMapper;
  53. } else {
  54. mapper = function (className) {
  55. return classMapper[className] || className;
  56. };
  57. }
  58. },
  59. /**
  60. * Adds the given prefix to all class names.
  61. *
  62. * @param {string} string
  63. */
  64. prefix: function prefix(string) {
  65. prefixString = string || '';
  66. },
  67. /**
  68. * Applies the current mapping and prefix to the given class name.
  69. *
  70. * @param {string} className A single class name.
  71. * @param {string} language The language of the code that contains this class name.
  72. *
  73. * If the language is unknown, pass `"none"`.
  74. */
  75. apply: apply
  76. };
  77. Prism.hooks.add('wrap', function (env) {
  78. if (adder) {
  79. var result = adder({
  80. content: env.content,
  81. type: env.type,
  82. language: env.language
  83. });
  84. if (Array.isArray(result)) {
  85. env.classes.push.apply(env.classes, result);
  86. } else if (result) {
  87. env.classes.push(result);
  88. }
  89. }
  90. if (!mapper && !prefixString) {
  91. return;
  92. }
  93. env.classes = env.classes.map(function (c) {
  94. return apply(c, env.language);
  95. });
  96. });
  97. }());