UNPKG

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