Rainbow.js with own JSON Language definitions and theme (like Panda Syntax)

Rainbow.js with own JSON Language definitions and theme (like Panda Syntax)

by Alex

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/rainbow/1.2.0/js/rainbow.min.js"></script>
<pre><code data-language="json" id="code">Loading...</code></pre>

<!--
  Without generic and without js or json!

<script src="https://cdnjs.cloudflare.com/ajax/libs/rainbow/1.2.0/js/language/generic.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rainbow/1.2.0/js/language/javascript.min.js"></script>
-->

CSS

html,
body {
  margin: 0;
  padding: 0;
}
pre, code{
  width:100vw; height:100vh;
}

/**
 * Theme inspired by Panda Syntax
 */

pre {
  background: #272822;
  word-wrap: break-word;
  margin: 0px;
  padding: 10px;
  color: #fff;
  font-size: 14px;
  padding-left: 40px;
  counter-reset: line;
}

pre,
code {
  font-family: 'Fira Code', 'Monaco', courier, monospace;
}

/*...even faked line numbers are there...*/

pre .json.lines:before {
  counter-increment: line;
  content: counter(line);
  display: inline-block;
  padding: 0 .5em;
  color: #444;
  text-align: right;
  width: 20px;
  position: absolute;
  left: 0px;
}

pre .json.lines:last-of-type:after {
  color: #444;
  counter-increment: line;
  content: counter(line);
  display: inline-block;
  padding: 0 .5em;
  text-align: right;
  width: 20px;
  position: absolute;
  left: 0px;
}

pre .json.key {
  color: #66D9EF;
}

pre .json.string {
  color: #19F9D8;
}

pre .json.numeric {
  color: #FFB86C;
  font-weight: bold;
}

pre .json.keyword {
  color: #FF75B5;
  font-weight: bold;
}

JavaScript

Rainbow.defer = true;
Rainbow.extend("json", [{
    matches: [{
        name: 'json.key',
        pattern: /(".+?":)/g
      },
      {
        name: 'json.string',
        pattern: /(".*?"[,\n])/g
      }
    ],
    pattern: /(".*"[,:\n\r\s])/g
  },
  {
    'name': 'json.numeric',
    'pattern': /\b(\d+(\.\d+)?(e(\+|\-)?\d+)?(f|d)?|0x[\da-f]+)\b/gi
  },
  {
    'name': 'json.keyword',
    'pattern': /true|false|null/g
  },
  {
    'name': 'json.lines',
    'pattern': /\n/g
  }
]);
const url = 'https://jsonplaceholder.typicode.com/users/';
fetch(url)
  .then(resp => resp.json())
  .then(resp => {
    Rainbow.color(JSON.stringify(resp, null, '  '), 'json', function(highlightedCode) {
      console.log(highlightedCode)
      document.getElementById('code').innerHTML = highlightedCode;
    });
  });