summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/syntax_highlight.js
blob: 96b6e78c668fa6052573af57379f2db56a4ec597 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/* eslint-disable consistent-return */

// 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>
//

export default function syntaxHighlight($els = null) {
  if (!$els) return;

  const els = $els.get ? $els.get() : $els;
  const handler = (el) => {
    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);
  }
}