debian-mirror-gitlab/app/assets/javascripts/syntax_highlight.js

43 lines
1.2 KiB
JavaScript
Raw Normal View History

2016-09-29 09:46:39 +05:30
// Syntax Highlighter
//
// Applies a syntax highlighting color scheme CSS class to any element with the
// `js-syntax-highlight` class
//
// ### Example Markup
//
// <div class="js-syntax-highlight"></div>
//
2017-08-17 22:00:37 +05:30
2021-10-27 15:23:28 +05:30
export default function syntaxHighlight($els = null) {
2023-03-17 16:20:25 +05:30
if (!$els || $els.length === 0) return;
2021-10-27 15:23:28 +05:30
const els = $els.get ? $els.get() : $els;
2023-06-20 00:43:36 +05:30
// eslint-disable-next-line consistent-return
2021-10-27 15:23:28 +05:30
const handler = (el) => {
2023-05-27 22:25:52 +05:30
if (el.classList === undefined) {
return el;
}
2021-10-27 15:23:28 +05:30
if (el.classList.contains('js-syntax-highlight')) {
// Given the element itself, apply highlighting
return el.classList.add(gon.user_color_scheme);
}
// Given a parent element, recurse to any of its applicable children
const children = el.querySelectorAll('.js-syntax-highlight');
if (children.length) {
return syntaxHighlight(children);
}
};
// In order to account for NodeList returned by document.querySelectorAll,
// we should rather check whether the els object is iterable
// instead of relying on Array.isArray()
const isIterable = typeof els[Symbol.iterator] === 'function';
if (isIterable) {
els.forEach((el) => handler(el));
} else {
handler(els);
2017-09-10 17:25:29 +05:30
}
2018-03-17 18:26:18 +05:30
}