rainbow.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. /**
  2. * Copyright 2012-2016 Craig Campbell
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *
  16. * Rainbow is a simple code syntax highlighter
  17. *
  18. * @see rainbowco.de
  19. */
  20. import Prism from './prism';
  21. import { isNode as utilIsNode, isWorker as utilIsWorker, createWorker, getLanguageForBlock } from './util';
  22. import rainbowWorker from './worker';
  23. /**
  24. * An array of the language patterns specified for each language
  25. *
  26. * @type {Object}
  27. */
  28. const patterns = {};
  29. /**
  30. * An object of languages mapping to what language they should inherit from
  31. *
  32. * @type {Object}
  33. */
  34. const inheritenceMap = {};
  35. /**
  36. * A mapping of language aliases
  37. *
  38. * @type {Object}
  39. */
  40. const aliases = {};
  41. /**
  42. * Representation of the actual rainbow object
  43. *
  44. * @type {Object}
  45. */
  46. let Rainbow = {};
  47. /**
  48. * Callback to fire after each block is highlighted
  49. *
  50. * @type {null|Function}
  51. */
  52. let onHighlightCallback;
  53. /**
  54. * Counter for block ids
  55. * @see https://github.com/ccampbell/rainbow/issues/207
  56. */
  57. let id = 0;
  58. const isNode = utilIsNode();
  59. const isWorker = utilIsWorker();
  60. let cachedWorker = null;
  61. function _getWorker() {
  62. if (isNode || cachedWorker === null) {
  63. cachedWorker = createWorker(rainbowWorker, Prism);
  64. }
  65. return cachedWorker;
  66. }
  67. /**
  68. * Helper for matching up callbacks directly with the
  69. * post message requests to a web worker.
  70. *
  71. * @param {object} message data to send to web worker
  72. * @param {Function} callback callback function for worker to reply to
  73. * @return {void}
  74. */
  75. function _messageWorker(message, callback) {
  76. const worker = _getWorker();
  77. function _listen(e) {
  78. if (e.data.id === message.id) {
  79. callback(e.data);
  80. worker.removeEventListener('message', _listen);
  81. }
  82. }
  83. worker.addEventListener('message', _listen);
  84. worker.postMessage(message);
  85. }
  86. /**
  87. * Browser Only - Handles response from web worker, updates DOM with
  88. * resulting code, and fires callback
  89. *
  90. * @param {Element} element
  91. * @param {object} waitingOn
  92. * @param {Function} callback
  93. * @return {void}
  94. */
  95. function _generateHandler(element, waitingOn, callback) {
  96. return function _handleResponseFromWorker(data) {
  97. element.innerHTML = data.result;
  98. element.classList.remove('loading');
  99. element.classList.add('rainbow-show');
  100. if (element.parentNode.tagName === 'PRE') {
  101. element.parentNode.classList.remove('loading');
  102. element.parentNode.classList.add('rainbow-show');
  103. }
  104. // element.addEventListener('animationend', (e) => {
  105. // if (e.animationName === 'fade-in') {
  106. // setTimeout(() => {
  107. // element.classList.remove('decrease-delay');
  108. // }, 1000);
  109. // }
  110. // });
  111. if (onHighlightCallback) {
  112. onHighlightCallback(element, data.lang);
  113. }
  114. if (--waitingOn.c === 0) {
  115. callback();
  116. }
  117. };
  118. }
  119. /**
  120. * Gets options needed to pass into Prism
  121. *
  122. * @param {object} options
  123. * @return {object}
  124. */
  125. function _getPrismOptions(options) {
  126. return {
  127. patterns,
  128. inheritenceMap,
  129. aliases,
  130. globalClass: options.globalClass,
  131. delay: !isNaN(options.delay) ? options.delay : 0
  132. };
  133. }
  134. /**
  135. * Gets data to send to webworker
  136. *
  137. * @param {string} code
  138. * @param {string} lang
  139. * @return {object}
  140. */
  141. function _getWorkerData(code, lang) {
  142. let options = {};
  143. if (typeof lang === 'object') {
  144. options = lang;
  145. lang = options.language;
  146. }
  147. lang = aliases[lang] || lang;
  148. const workerData = {
  149. id: id++,
  150. code,
  151. lang,
  152. options: _getPrismOptions(options),
  153. isNode
  154. };
  155. return workerData;
  156. }
  157. /**
  158. * Browser Only - Sends messages to web worker to highlight elements passed
  159. * in
  160. *
  161. * @param {Array} codeBlocks
  162. * @param {Function} callback
  163. * @return {void}
  164. */
  165. function _highlightCodeBlocks(codeBlocks, callback) {
  166. const waitingOn = { c: 0 };
  167. for (const block of codeBlocks) {
  168. const language = getLanguageForBlock(block);
  169. if (block.classList.contains('rainbow') || !language) {
  170. continue;
  171. }
  172. // This cancels the pending animation to fade the code in on load
  173. // since we want to delay doing this until it is actually
  174. // highlighted
  175. block.classList.add('loading');
  176. block.classList.add('rainbow');
  177. // We need to make sure to also add the loading class to the pre tag
  178. // because that is how we will know to show a preloader
  179. if (block.parentNode.tagName === 'PRE') {
  180. block.parentNode.classList.add('loading');
  181. }
  182. const globalClass = block.getAttribute('data-global-class');
  183. const delay = parseInt(block.getAttribute('data-delay'), 10);
  184. ++waitingOn.c;
  185. _messageWorker(_getWorkerData(block.innerHTML, { language, globalClass, delay }), _generateHandler(block, waitingOn, callback));
  186. }
  187. if (waitingOn.c === 0) {
  188. callback();
  189. }
  190. }
  191. function _addPreloader(preBlock) {
  192. const preloader = document.createElement('div');
  193. preloader.className = 'preloader';
  194. for (let i = 0; i < 7; i++) {
  195. preloader.appendChild(document.createElement('div'));
  196. }
  197. preBlock.appendChild(preloader);
  198. }
  199. /**
  200. * Browser Only - Start highlighting all the code blocks
  201. *
  202. * @param {Element} node HTMLElement to search within
  203. * @param {Function} callback
  204. * @return {void}
  205. */
  206. function _highlight(node, callback) {
  207. callback = callback || function() {};
  208. // The first argument can be an Event or a DOM Element.
  209. //
  210. // I was originally checking instanceof Event but that made it break
  211. // when using mootools.
  212. //
  213. // @see https://github.com/ccampbell/rainbow/issues/32
  214. node = node && typeof node.getElementsByTagName === 'function' ? node : document;
  215. const preBlocks = node.getElementsByTagName('pre');
  216. const codeBlocks = node.getElementsByTagName('code');
  217. const finalPreBlocks = [];
  218. const finalCodeBlocks = [];
  219. // First loop through all pre blocks to find which ones to highlight
  220. for (const preBlock of preBlocks) {
  221. _addPreloader(preBlock);
  222. // Strip whitespace around code tags when they are inside of a pre
  223. // tag. This makes the themes look better because you can't
  224. // accidentally add extra linebreaks at the start and end.
  225. //
  226. // When the pre tag contains a code tag then strip any extra
  227. // whitespace.
  228. //
  229. // For example:
  230. //
  231. // <pre>
  232. // <code>var foo = true;</code>
  233. // </pre>
  234. //
  235. // will become:
  236. //
  237. // <pre><code>var foo = true;</code></pre>
  238. //
  239. // If you want to preserve whitespace you can use a pre tag on
  240. // its own without a code tag inside of it.
  241. if (preBlock.getElementsByTagName('code').length) {
  242. // This fixes a race condition when Rainbow.color is called before
  243. // the previous color call has finished.
  244. if (!preBlock.getAttribute('data-trimmed')) {
  245. preBlock.setAttribute('data-trimmed', true);
  246. preBlock.innerHTML = preBlock.innerHTML.trim();
  247. }
  248. continue;
  249. }
  250. // If the pre block has no code blocks then we are going to want to
  251. // process it directly.
  252. finalPreBlocks.push(preBlock);
  253. }
  254. // @see http://stackoverflow.com/questions/2735067/how-to-convert-a-dom-node-list-to-an-array-in-javascript
  255. // We are going to process all <code> blocks
  256. for (const codeBlock of codeBlocks) {
  257. finalCodeBlocks.push(codeBlock);
  258. }
  259. _highlightCodeBlocks(finalCodeBlocks.concat(finalPreBlocks), callback);
  260. }
  261. /**
  262. * Callback to let you do stuff in your app after a piece of code has
  263. * been highlighted
  264. *
  265. * @param {Function} callback
  266. * @return {void}
  267. */
  268. function onHighlight(callback) {
  269. onHighlightCallback = callback;
  270. }
  271. /**
  272. * Extends the language pattern matches
  273. *
  274. * @param {string} language name of language
  275. * @param {object} languagePatterns object of patterns to add on
  276. * @param {string|undefined} inherits optional language that this language
  277. * should inherit rules from
  278. */
  279. function extend(language, languagePatterns, inherits) {
  280. // If we extend a language again we shouldn't need to specify the
  281. // inheritence for it. For example, if you are adding special highlighting
  282. // for a javascript function that is not in the base javascript rules, you
  283. // should be able to do
  284. //
  285. // Rainbow.extend('javascript', [ … ]);
  286. //
  287. // Without specifying a language it should inherit (generic in this case)
  288. if (!inheritenceMap[language]) {
  289. inheritenceMap[language] = inherits;
  290. }
  291. patterns[language] = languagePatterns.concat(patterns[language] || []);
  292. }
  293. function remove(language) {
  294. delete inheritenceMap[language];
  295. delete patterns[language];
  296. }
  297. /**
  298. * Starts the magic rainbow
  299. *
  300. * @return {void}
  301. */
  302. function color(...args) {
  303. // If you want to straight up highlight a string you can pass the
  304. // string of code, the language, and a callback function.
  305. //
  306. // Example:
  307. //
  308. // Rainbow.color(code, language, function(highlightedCode, language) {
  309. // // this code block is now highlighted
  310. // });
  311. if (typeof args[0] === 'string') {
  312. const workerData = _getWorkerData(args[0], args[1]);
  313. _messageWorker(workerData, (function(cb) {
  314. return function(data) {
  315. if (cb) {
  316. cb(data.result, data.lang);
  317. }
  318. };
  319. }(args[2])));
  320. return;
  321. }
  322. // If you pass a callback function then we rerun the color function
  323. // on all the code and call the callback function on complete.
  324. //
  325. // Example:
  326. //
  327. // Rainbow.color(function() {
  328. // console.log('All matching tags on the page are now highlighted');
  329. // });
  330. if (typeof args[0] === 'function') {
  331. _highlight(0, args[0]);
  332. return;
  333. }
  334. // Otherwise we use whatever node you passed in with an optional
  335. // callback function as the second parameter.
  336. //
  337. // Example:
  338. //
  339. // var preElement = document.createElement('pre');
  340. // var codeElement = document.createElement('code');
  341. // codeElement.setAttribute('data-language', 'javascript');
  342. // codeElement.innerHTML = '// Here is some JavaScript';
  343. // preElement.appendChild(codeElement);
  344. // Rainbow.color(preElement, function() {
  345. // // New element is now highlighted
  346. // });
  347. //
  348. // If you don't pass an element it will default to `document`
  349. _highlight(args[0], args[1]);
  350. }
  351. /**
  352. * Method to add an alias for an existing language.
  353. *
  354. * For example if you want to have "coffee" map to "coffeescript"
  355. *
  356. * @see https://github.com/ccampbell/rainbow/issues/154
  357. * @param {string} alias
  358. * @param {string} originalLanguage
  359. * @return {void}
  360. */
  361. function addAlias(alias, originalLanguage) {
  362. aliases[alias] = originalLanguage;
  363. }
  364. /**
  365. * public methods
  366. */
  367. Rainbow = {
  368. extend,
  369. remove,
  370. onHighlight,
  371. addAlias,
  372. color
  373. };
  374. if (isNode) {
  375. Rainbow.colorSync = function(code, lang) {
  376. const workerData = _getWorkerData(code, lang);
  377. const prism = new Prism(workerData.options);
  378. return prism.refract(workerData.code, workerData.lang);
  379. };
  380. }
  381. // In the browser hook it up to color on page load
  382. if (!isNode && !isWorker) {
  383. document.addEventListener('DOMContentLoaded', (event) => {
  384. if (!Rainbow.defer) {
  385. Rainbow.color(event);
  386. }
  387. }, false);
  388. }
  389. // From a node worker, handle the postMessage requests to it
  390. if (isWorker) {
  391. self.onmessage = rainbowWorker;
  392. }
  393. export default Rainbow;