prism-line-highlight.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. (function () {
  2. if (typeof Prism === 'undefined' || typeof document === 'undefined' || !document.querySelector) {
  3. return;
  4. }
  5. var LINE_NUMBERS_CLASS = 'line-numbers';
  6. var LINKABLE_LINE_NUMBERS_CLASS = 'linkable-line-numbers';
  7. /**
  8. * @param {string} selector
  9. * @param {ParentNode} [container]
  10. * @returns {HTMLElement[]}
  11. */
  12. function $$(selector, container) {
  13. return Array.prototype.slice.call((container || document).querySelectorAll(selector));
  14. }
  15. /**
  16. * Returns whether the given element has the given class.
  17. *
  18. * @param {Element} element
  19. * @param {string} className
  20. * @returns {boolean}
  21. */
  22. function hasClass(element, className) {
  23. return element.classList.contains(className);
  24. }
  25. /**
  26. * Calls the given function.
  27. *
  28. * @param {() => any} func
  29. * @returns {void}
  30. */
  31. function callFunction(func) {
  32. func();
  33. }
  34. // Some browsers round the line-height, others don't.
  35. // We need to test for it to position the elements properly.
  36. var isLineHeightRounded = (function () {
  37. var res;
  38. return function () {
  39. if (typeof res === 'undefined') {
  40. var d = document.createElement('div');
  41. d.style.fontSize = '13px';
  42. d.style.lineHeight = '1.5';
  43. d.style.padding = '0';
  44. d.style.border = '0';
  45. d.innerHTML = '&nbsp;<br />&nbsp;';
  46. document.body.appendChild(d);
  47. // Browsers that round the line-height should have offsetHeight === 38
  48. // The others should have 39.
  49. res = d.offsetHeight === 38;
  50. document.body.removeChild(d);
  51. }
  52. return res;
  53. };
  54. }());
  55. /**
  56. * Returns the top offset of the content box of the given parent and the content box of one of its children.
  57. *
  58. * @param {HTMLElement} parent
  59. * @param {HTMLElement} child
  60. */
  61. function getContentBoxTopOffset(parent, child) {
  62. var parentStyle = getComputedStyle(parent);
  63. var childStyle = getComputedStyle(child);
  64. /**
  65. * Returns the numeric value of the given pixel value.
  66. *
  67. * @param {string} px
  68. */
  69. function pxToNumber(px) {
  70. return +px.substr(0, px.length - 2);
  71. }
  72. return child.offsetTop
  73. + pxToNumber(childStyle.borderTopWidth)
  74. + pxToNumber(childStyle.paddingTop)
  75. - pxToNumber(parentStyle.paddingTop);
  76. }
  77. /**
  78. * Returns whether the Line Highlight plugin is active for the given element.
  79. *
  80. * If this function returns `false`, do not call `highlightLines` for the given element.
  81. *
  82. * @param {HTMLElement | null | undefined} pre
  83. * @returns {boolean}
  84. */
  85. function isActiveFor(pre) {
  86. if (!pre || !/pre/i.test(pre.nodeName)) {
  87. return false;
  88. }
  89. if (pre.hasAttribute('data-line')) {
  90. return true;
  91. }
  92. if (pre.id && Prism.util.isActive(pre, LINKABLE_LINE_NUMBERS_CLASS)) {
  93. // Technically, the line numbers plugin is also necessary but this plugin doesn't control the classes of
  94. // the line numbers plugin, so we can't assume that they are present.
  95. return true;
  96. }
  97. return false;
  98. }
  99. var scrollIntoView = true;
  100. Prism.plugins.lineHighlight = {
  101. /**
  102. * Highlights the lines of the given pre.
  103. *
  104. * This function is split into a DOM measuring and mutate phase to improve performance.
  105. * The returned function mutates the DOM when called.
  106. *
  107. * @param {HTMLElement} pre
  108. * @param {string | null} [lines]
  109. * @param {string} [classes='']
  110. * @returns {() => void}
  111. */
  112. highlightLines: function highlightLines(pre, lines, classes) {
  113. lines = typeof lines === 'string' ? lines : (pre.getAttribute('data-line') || '');
  114. var ranges = lines.replace(/\s+/g, '').split(',').filter(Boolean);
  115. var offset = +pre.getAttribute('data-line-offset') || 0;
  116. var parseMethod = isLineHeightRounded() ? parseInt : parseFloat;
  117. var lineHeight = parseMethod(getComputedStyle(pre).lineHeight);
  118. var hasLineNumbers = Prism.util.isActive(pre, LINE_NUMBERS_CLASS);
  119. var codeElement = pre.querySelector('code');
  120. var parentElement = hasLineNumbers ? pre : codeElement || pre;
  121. var mutateActions = /** @type {(() => void)[]} */ ([]);
  122. /**
  123. * The top offset between the content box of the <code> element and the content box of the parent element of
  124. * the line highlight element (either `<pre>` or `<code>`).
  125. *
  126. * This offset might not be zero for some themes where the <code> element has a top margin. Some plugins
  127. * (or users) might also add element above the <code> element. Because the line highlight is aligned relative
  128. * to the <pre> element, we have to take this into account.
  129. *
  130. * This offset will be 0 if the parent element of the line highlight element is the `<code>` element.
  131. */
  132. var codePreOffset = !codeElement || parentElement == codeElement ? 0 : getContentBoxTopOffset(pre, codeElement);
  133. ranges.forEach(function (currentRange) {
  134. var range = currentRange.split('-');
  135. var start = +range[0];
  136. var end = +range[1] || start;
  137. /** @type {HTMLElement} */
  138. var line = pre.querySelector('.line-highlight[data-range="' + currentRange + '"]') || document.createElement('div');
  139. mutateActions.push(function () {
  140. line.setAttribute('aria-hidden', 'true');
  141. line.setAttribute('data-range', currentRange);
  142. line.className = (classes || '') + ' line-highlight';
  143. });
  144. // if the line-numbers plugin is enabled, then there is no reason for this plugin to display the line numbers
  145. if (hasLineNumbers && Prism.plugins.lineNumbers) {
  146. var startNode = Prism.plugins.lineNumbers.getLine(pre, start);
  147. var endNode = Prism.plugins.lineNumbers.getLine(pre, end);
  148. if (startNode) {
  149. var top = startNode.offsetTop + codePreOffset + 'px';
  150. mutateActions.push(function () {
  151. line.style.top = top;
  152. });
  153. }
  154. if (endNode) {
  155. var height = (endNode.offsetTop - startNode.offsetTop) + endNode.offsetHeight + 'px';
  156. mutateActions.push(function () {
  157. line.style.height = height;
  158. });
  159. }
  160. } else {
  161. mutateActions.push(function () {
  162. line.setAttribute('data-start', String(start));
  163. if (end > start) {
  164. line.setAttribute('data-end', String(end));
  165. }
  166. line.style.top = (start - offset - 1) * lineHeight + codePreOffset + 'px';
  167. line.textContent = new Array(end - start + 2).join(' \n');
  168. });
  169. }
  170. mutateActions.push(function () {
  171. line.style.width = pre.scrollWidth + 'px';
  172. });
  173. mutateActions.push(function () {
  174. // allow this to play nicely with the line-numbers plugin
  175. // need to attack to pre as when line-numbers is enabled, the code tag is relatively which screws up the positioning
  176. parentElement.appendChild(line);
  177. });
  178. });
  179. var id = pre.id;
  180. if (hasLineNumbers && Prism.util.isActive(pre, LINKABLE_LINE_NUMBERS_CLASS) && id) {
  181. // This implements linkable line numbers. Linkable line numbers use Line Highlight to create a link to a
  182. // specific line. For this to work, the pre element has to:
  183. // 1) have line numbers,
  184. // 2) have the `linkable-line-numbers` class or an ascendant that has that class, and
  185. // 3) have an id.
  186. if (!hasClass(pre, LINKABLE_LINE_NUMBERS_CLASS)) {
  187. // add class to pre
  188. mutateActions.push(function () {
  189. pre.classList.add(LINKABLE_LINE_NUMBERS_CLASS);
  190. });
  191. }
  192. var start = parseInt(pre.getAttribute('data-start') || '1');
  193. // iterate all line number spans
  194. $$('.line-numbers-rows > span', pre).forEach(function (lineSpan, i) {
  195. var lineNumber = i + start;
  196. lineSpan.onclick = function () {
  197. var hash = id + '.' + lineNumber;
  198. // this will prevent scrolling since the span is obviously in view
  199. scrollIntoView = false;
  200. location.hash = hash;
  201. setTimeout(function () {
  202. scrollIntoView = true;
  203. }, 1);
  204. };
  205. });
  206. }
  207. return function () {
  208. mutateActions.forEach(callFunction);
  209. };
  210. }
  211. };
  212. function applyHash() {
  213. var hash = location.hash.slice(1);
  214. // Remove pre-existing temporary lines
  215. $$('.temporary.line-highlight').forEach(function (line) {
  216. line.parentNode.removeChild(line);
  217. });
  218. var range = (hash.match(/\.([\d,-]+)$/) || [, ''])[1];
  219. if (!range || document.getElementById(hash)) {
  220. return;
  221. }
  222. var id = hash.slice(0, hash.lastIndexOf('.'));
  223. var pre = document.getElementById(id);
  224. if (!pre) {
  225. return;
  226. }
  227. if (!pre.hasAttribute('data-line')) {
  228. pre.setAttribute('data-line', '');
  229. }
  230. var mutateDom = Prism.plugins.lineHighlight.highlightLines(pre, range, 'temporary ');
  231. mutateDom();
  232. if (scrollIntoView) {
  233. document.querySelector('.temporary.line-highlight').scrollIntoView();
  234. }
  235. }
  236. var fakeTimer = 0; // Hack to limit the number of times applyHash() runs
  237. Prism.hooks.add('before-sanity-check', function (env) {
  238. var pre = env.element.parentElement;
  239. if (!isActiveFor(pre)) {
  240. return;
  241. }
  242. /*
  243. * Cleanup for other plugins (e.g. autoloader).
  244. *
  245. * Sometimes <code> blocks are highlighted multiple times. It is necessary
  246. * to cleanup any left-over tags, because the whitespace inside of the <div>
  247. * tags change the content of the <code> tag.
  248. */
  249. var num = 0;
  250. $$('.line-highlight', pre).forEach(function (line) {
  251. num += line.textContent.length;
  252. line.parentNode.removeChild(line);
  253. });
  254. // Remove extra whitespace
  255. if (num && /^(?: \n)+$/.test(env.code.slice(-num))) {
  256. env.code = env.code.slice(0, -num);
  257. }
  258. });
  259. Prism.hooks.add('complete', function completeHook(env) {
  260. var pre = env.element.parentElement;
  261. if (!isActiveFor(pre)) {
  262. return;
  263. }
  264. clearTimeout(fakeTimer);
  265. var hasLineNumbers = Prism.plugins.lineNumbers;
  266. var isLineNumbersLoaded = env.plugins && env.plugins.lineNumbers;
  267. if (hasClass(pre, LINE_NUMBERS_CLASS) && hasLineNumbers && !isLineNumbersLoaded) {
  268. Prism.hooks.add('line-numbers', completeHook);
  269. } else {
  270. var mutateDom = Prism.plugins.lineHighlight.highlightLines(pre);
  271. mutateDom();
  272. fakeTimer = setTimeout(applyHash, 1);
  273. }
  274. });
  275. window.addEventListener('hashchange', applyHash);
  276. window.addEventListener('resize', function () {
  277. var actions = $$('pre')
  278. .filter(isActiveFor)
  279. .map(function (pre) {
  280. return Prism.plugins.lineHighlight.highlightLines(pre);
  281. });
  282. actions.forEach(callFunction);
  283. });
  284. }());