### Installation Source: https://context7.com/gka/chroma.js/llms.txt Instructions on how to install and import Chroma.js into your project. ```APIDOC ## Installation Install chroma-js via npm and import into your project. ```javascript // Install: npm install chroma-js // ES Module import import chroma from 'chroma-js'; // CommonJS require const chroma = require('chroma-js'); // Browser via CDN // ``` ``` -------------------------------- ### Install Chroma.js Source: https://github.com/gka/chroma.js/blob/main/readme.md Install the Chroma.js library using npm. This is the first step before importing it into your project. ```bash npm install chroma-js ``` -------------------------------- ### Clone Repository and Install Dev Dependencies Source: https://github.com/gka/chroma.js/blob/main/readme.md Clone the Chroma.js repository from GitHub and install the necessary development dependencies using npm. ```bash git clone git@github.com:gka/chroma.js.git cd chroma.js npm install ``` -------------------------------- ### Install chroma-js with npm Source: https://github.com/gka/chroma.js/blob/main/docs/src/index.md Installs the chroma-js npm module. Use with npm, pnpm, or yarn. ```shell npm install chroma-js # pnpm add chroma-js # yarn add chroma-js ``` -------------------------------- ### Install and Import Chroma.js Source: https://context7.com/gka/chroma.js/llms.txt Install chroma-js via npm and import it into your project using ES Module syntax or CommonJS. Browser usage via CDN is also supported. ```javascript // Install: npm install chroma-js // ES Module import import chroma from 'chroma-js'; // CommonJS require const chroma = require('chroma-js'); // Browser via CDN // ``` -------------------------------- ### Choropleth Map Color Scale Example Source: https://context7.com/gka/chroma.js/llms.txt An example of creating a classified color scale with a custom domain and class breaks, suitable for generating colors for choropleth maps based on population data. ```javascript import chroma from 'chroma-js'; // Choropleth map example const populationScale = chroma.scale('YlOrRd') .domain([0, 1000000]) .classes([0, 10000, 50000, 100000, 500000, 1000000]); const getColor = (population) => populationScale(population).hex(); console.log(getColor(5000)); // '#ffffb2' console.log(getColor(75000)); // '#fd8d3c' console.log(getColor(750000)); // '#bd0026' ``` -------------------------------- ### Get Oklab Components Source: https://github.com/gka/chroma.js/blob/main/docs/src/index.md Returns an array of L, a, and b components in the OKLab color space. ```javascript chroma('orange').oklab() ``` -------------------------------- ### TypeScript Greeter Class and Button Example Source: https://github.com/gka/chroma.js/blob/main/docs/libs/codemirror/mode/javascript/typescript.html Demonstrates a simple TypeScript class 'Greeter' and its usage to create a button that alerts a greeting when clicked. This code is intended to be run in a browser environment. ```typescript class Greeter { greeting: string; constructor (message: string) { this.greeting = message; } greet() { return "Hello, " + this.greeting; } } var greeter = new Greeter("world"); var button = document.createElement('button') button.innerText = "Say Hello" button.onclick = function() { alert(greeter.greet()) } document.body.appendChild(button) ``` -------------------------------- ### Get and Set Color Channel Values with get() / set() Source: https://context7.com/gka/chroma.js/llms.txt Access or modify individual color channel values in any supported color space using get() and set(). The set() method returns a new Color object and supports relative modifications using operators like '*', '+', and '-'. ```javascript import chroma from 'chroma-js'; // Get channel values const color = chroma('orangered'); console.log(color.get('lab.l')); // 57.58... (Lab lightness) console.log(color.get('hsl.h')); // 16.23... (HSL hue) console.log(color.get('rgb.r')); // 255 (red channel) console.log(color.get('lch.c')); // 108.95... (Lch chroma) // Set channel values (returns new Color) const blue = chroma('skyblue'); console.log(blue.set('hsl.h', 0).hex()); // '#b4878c' (change hue to red) console.log(blue.set('lch.c', 80).hex()); // '#00c9ff' (increase chroma) // Relative modifications with operators const orange = chroma('orangered'); console.log(orange.set('lab.l', '*0.5').hex()); // '#6f1500' (half lightness) console.log(orange.set('lch.c', '*2').hex()); // '#ff0000' (double chroma) console.log(orange.set('hsl.h', '+180').hex()); // '#0082ff' (rotate hue 180 deg) ``` -------------------------------- ### Example JSON-LD Object Source: https://github.com/gka/chroma.js/blob/main/docs/libs/codemirror/mode/javascript/json-ld.html A sample JSON-LD object representing the Empire State Building, demonstrating schema.org vocabulary. ```json { "@context": { "name": "http://schema.org/name", "description": "http://schema.org/description", "image": { "@id": "http://schema.org/image", "@type": "@id" }, "geo": "http://schema.org/geo", "latitude": { "@id": "http://schema.org/latitude", "@type": "xsd:float" }, "longitude": { "@id": "http://schema.org/longitude", "@type": "xsd:float" }, "xsd": "http://www.w3.org/2001/XMLSchema#" }, "name": "The Empire State Building", "description": "The Empire State Building is a 102-story landmark in New York City.", "image": "http://www.civil.usherbrooke.ca/cours/gci215a/empire-state-building.jpg", "geo": { "latitude": "40.75", "longitude": "73.98" } } ``` -------------------------------- ### Generate Color Blends with Chroma.js Source: https://github.com/gka/chroma.js/blob/main/test/html/blend.html This example demonstrates how to generate various color blending modes using Chroma.js. It iterates through different blend modes and creates visual swatches to display the results. Ensure Chroma.js is included in your project. ```javascript var names = Object.keys(chroma.colors), l = names.length; var cssMap = { dodge: 'color-dodge', burn: 'color-burn' }; Object.keys(chroma.blend).forEach(function (mode) { document.write('

' + mode + '

'); for (var i = 0; i < 10; i++) { var row = el('div.row'), left = el('div.left'), right = el('div.right'); var bottom = names[Math.floor(Math.random() * l)], top = names[Math.floor(Math.random() * l)]; swatch(bottom, left); swatch(chroma.blend(bottom, top, mode).hex(), left); swatch(top, left); swatch(bottom, right); swatch(bottom, right); var s = swatch(top, right); s.className = 'swatch overlay'; s.style.mixBlendMode = cssMap[mode] || mode; swatch(top, right); } }); function swatch(color, parent) { var s = el('div.swatch', parent); s.setAttribute('title', color); s.style.background = color; return s; } function el(t, parent) { var p = t.split('.'); var e = document.createElement(p[0]); if (p[1]) e.className = p[1]; (parent || document.body).appendChild(e); return e; } ``` -------------------------------- ### Get Oklch Components Source: https://github.com/gka/chroma.js/blob/main/docs/src/index.md Returns an array of Lightness, chroma, and hue components in the OKLch color space. ```javascript chroma('skyblue').oklch() ``` -------------------------------- ### color.alpha Source: https://github.com/gka/chroma.js/blob/main/docs/index.html Get and set the color opacity. ```APIDOC ## color.alpha(a) ### Description Get and set the color opacity using `color.alpha`. ### Parameters #### Path Parameters - **a** (Number) - The alpha value (0 to 1) to set. If omitted, the current alpha value is returned. ### Request Example ```javascript // Set alpha chroma('red').alpha(0.5); // Get alpha chroma('rgba(255,0,0,0.35)').alpha(); ``` ### Response #### Success Response (200) - **alphaValue** (Number) - The alpha value of the color, or the chroma object itself if alpha was set. ``` -------------------------------- ### Get LAB Components Source: https://github.com/gka/chroma.js/blob/main/docs/src/index.md Returns an array of L, a, and b components in the CIELAB color space. ```javascript chroma('orange').lab() ``` -------------------------------- ### Initialize CodeMirror Editor Source: https://github.com/gka/chroma.js/blob/main/docs/libs/codemirror/mode/javascript/index.html Initializes a CodeMirror editor instance from a textarea element. This setup includes line numbers, bracket matching, and comment toggling functionality. ```javascript var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers: true, matchBrackets: true, continueComments: "Enter", extraKeys: {"Ctrl-Q": "toggleComment"} }); ``` -------------------------------- ### Get Oklab/Oklch Color Components Source: https://context7.com/gka/chroma.js/llms.txt Returns color components in the modern Oklab or Oklch color spaces, which provide improved perceptual uniformity over CIE Lab. Oklab: [Lightness (0-1), a, b]. Oklch: [Lightness (0-1), Chroma, Hue (0-360)]. ```javascript import chroma from 'chroma-js'; const color = chroma('hotpink'); // Oklab: [Lightness (0-1), a, b] console.log(color.oklab()); // [0.7..., 0.15..., -0.05...] // Oklch: [Lightness (0-1), Chroma, Hue (0-360)] console.log(color.oklch()); // [0.7..., 0.16..., 342...] // Create from Oklab const oklabColor = chroma.oklab(0.5, -0.1, 0.1); console.log(oklabColor.hex()); // '#3d7e42' // Create from Oklch const oklchColor = chroma.oklch(0.7, 0.15, 60); console.log(oklchColor.hex()); // '#e49a44' ``` -------------------------------- ### Generating Cubehelix Color Schemes with chroma.cubehelix() Source: https://context7.com/gka/chroma.js/llms.txt Create Dave Green's cubehelix color schemes, designed for perceptually uniform rainbow gradients. Customize parameters like start hue, rotations, gamma, and lightness range. Can be converted to a scale. ```javascript import chroma from 'chroma-js'; // Default cubehelix const defaultHelix = chroma.cubehelix(); console.log(defaultHelix(0).hex()); // '#000000' console.log(defaultHelix(0.5).hex()); // '#a17c66' console.log(defaultHelix(1).hex()); // '#ffffff' ``` ```javascript // Customized cubehelix const custom = chroma.cubehelix () .start(200) // Start hue angle .rotations(-0.5) // Number of rotations .gamma(0.8) // Gamma correction .lightness([0.3, 0.8]); // Lightness range console.log(custom(0).hex()); // '#355069' console.log(custom(0.5).hex()); // '#6c9963' console.log(custom(1).hex()); // '#c5bfa0' ``` ```javascript // Convert to scale const cubehelixScale = chroma.cubehelix () .start(200) .rotations(-0.35) .gamma(0.7) .lightness([0.3, 0.8]) .scale() .correctLightness() .colors(5); console.log(cubehelixScale); ``` ```javascript // Parameters explained: // start: Initial hue (0-360) // rotations: Hue rotations (negative = reverse direction) // hue: Saturation control (0-1 or [start, end]) // gamma: Lightness curve // lightness: [dark, light] bounds (0-1) ``` -------------------------------- ### Create Colors from Temperature (Kelvin) Source: https://context7.com/gka/chroma.js/llms.txt Use chroma.temperature() to create colors based on light source temperatures in Kelvin. Common light temperatures are provided as examples. You can also estimate temperature from a color or create scales. ```javascript import chroma from 'chroma-js'; // Common light temperatures console.log(chroma.temperature(1000).hex()); // '#ff3800' (candle flame) console.log(chroma.temperature(2000).hex()); // '#ff8912' (warm incandescent) console.log(chroma.temperature(3500).hex()); // '#ffc38a' (sunset) console.log(chroma.temperature(5500).hex()); // '#fff4e5' (daylight) console.log(chroma.temperature(6500).hex()); // '#fffafe' (overcast) console.log(chroma.temperature(10000).hex()); // '#ccdcff' (blue sky) console.log(chroma.temperature(20000).hex()); // '#a9c1ff' (clear blue sky) ``` ```javascript // Temperature scale visualization const tempScale = (i) => chroma.temperature(i * 30000); const temps = [0.1, 0.2, 0.3, 0.5, 0.7, 1.0]; console.log(temps.map(t => tempScale(t).hex())); ``` ```javascript // Estimate temperature from color console.log(chroma('#ff3300').temperature()); // ~1000K console.log(chroma('#ff8a13').temperature()); // ~2000K console.log(chroma('#cbdbff').temperature()); // ~10000K ``` ```javascript // Create warm-to-cool scale const warmCool = chroma.scale([ chroma.temperature(2000), chroma.temperature(6500), chroma.temperature(15000) ]).mode('lab'); ``` -------------------------------- ### Preview Documentation Locally Source: https://github.com/gka/chroma.js/blob/main/readme.md Preview the documentation locally by running the npm run docs-preview script. ```bash npm run docs-preview ``` -------------------------------- ### Set Cubehelix Start Hue Source: https://github.com/gka/chroma.js/blob/main/docs/src/index.md Adjust the starting hue of the cubehelix color scheme. The default value is 300. ```javascript chroma.cubehelix().start(300); chroma.cubehelix().start(200); ``` -------------------------------- ### Get Color Channels with Chroma.js Source: https://github.com/gka/chroma.js/blob/main/docs/index.html Use the get() method to retrieve the value of a specific color channel (e.g., 'lab.l', 'hsl.l', 'rgb.g'). ```javascript chroma('orangered').get('lab.l'); ``` ```javascript chroma('orangered').get('hsl.l'); ``` ```javascript chroma('orangered').get('rgb.g'); ``` -------------------------------- ### Color Scale with Custom Domain and Quantiles Source: https://github.com/gka/chroma.js/blob/main/readme.md Create a color scale using a predefined color scheme ('RdYlBu') with a custom domain, specifying 7 steps and using 'quantiles' for distribution. ```javascript chroma.scale('RdYlBu').domain(myValues, 7, 'quantiles'); ``` -------------------------------- ### chroma.lab() Constructor Source: https://github.com/gka/chroma.js/blob/main/docs/src/index.md Constructs a color object using the CIELAB color space. ```APIDOC ## chroma.lab() ### Description Constructs a color object using the CIELAB color space. This is one of the dedicated constructor functions for specific color spaces available under the `chroma` namespace. ### Method `chroma.lab(l, a, b)` ### Endpoint N/A (JavaScript function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript chroma.lab(50, -20, 30); ``` ### Response #### Success Response (200) Returns a chroma.js color object representing the CIELAB color. #### Response Example (A chroma.js color object, not directly representable as JSON) ``` -------------------------------- ### Create and Use Color Scales Source: https://github.com/gka/chroma.js/blob/main/readme.md Create a color scale between two colors and get a color at a specific position (0.5 in this case). Use .hex() to get the color in hexadecimal format. ```javascript scale = chroma.scale(['white', 'red']); scale(0.5).hex(); // #FF7F7F ``` -------------------------------- ### color.oklab() Source: https://github.com/gka/chroma.js/blob/main/docs/src/index.md Returns an array of OKLAB components. ```APIDOC ## color.oklab() ### Description Returns an array with the L, a, and b components in the OKLab color space. ### Method `oklab()` ### Request Example ```js chroma('orange').oklab() ``` ### Response - **oklabArray** (Array) - An array containing the L, a, b components in OKLab. ``` -------------------------------- ### Get and Set Color Luminance with Chroma.js Source: https://github.com/gka/chroma.js/blob/main/docs/index.html Use the luminance() method to get the relative brightness of a color (0-1) or to set a target luminance by interpolating with black or white. The color space for interpolation can be specified. ```javascript chroma('white').luminance(); ``` ```javascript chroma('aquamarine').luminance(); ``` ```javascript chroma('hotpink').luminance(); ``` ```javascript chroma('darkslateblue').luminance(); ``` ```javascript chroma('black').luminance(); ``` ```javascript // set lumincance to 50% for all colors chroma('white').luminance(0.5); ``` ```javascript chroma('aquamarine').luminance(0.5); ``` ```javascript chroma('hotpink').luminance(0.5); ``` ```javascript chroma('darkslateblue').luminance(0.5); ``` ```javascript chroma('aquamarine').luminance(0.5); // rgb ``` ```javascript chroma('aquamarine').luminance(0.5, 'lab'); ``` ```javascript chroma('aquamarine').luminance(0.5, 'hsl'); ``` -------------------------------- ### color.oklab() / color.oklch() Source: https://context7.com/gka/chroma.js/llms.txt Returns color components in the modern Oklab or Oklch color spaces, which provide improved perceptual uniformity over CIE Lab. ```APIDOC ## color.oklab() / color.oklch() ### Description Returns color components in the modern Oklab or Oklch color spaces, which provide improved perceptual uniformity over CIE Lab. ### Method GET (implicit) ### Endpoint color.oklab() color.oklch() ### Parameters None ### Request Example ```javascript import chroma from 'chroma-js'; const color = chroma('hotpink'); // Oklab: [Lightness (0-1), a, b] console.log(color.oklab()); // [0.7..., 0.15..., -0.05...] // Oklch: [Lightness (0-1), Chroma, Hue (0-360)] console.log(color.oklch()); // [0.7..., 0.16..., 342...] // Create from Oklab const oklabColor = chroma.oklab(0.5, -0.1, 0.1); console.log(oklabColor.hex()); // '#3d7e42' // Create from Oklch const oklchColor = chroma.oklch(0.7, 0.15, 60); console.log(oklchColor.hex()); // '#e49a44' ``` ### Response #### Success Response (200) - **Array** (Array) - An array containing [lightness, a, b] for Oklab, or [lightness, chroma, hue] for Oklch. #### Response Example ```json [0.7, 0.15, -0.05] // For .oklab() ``` ```json [0.7, 0.16, 342] // For .oklch() ``` ``` -------------------------------- ### Get or Set Alpha Channel Source: https://context7.com/gka/chroma.js/llms.txt Gets or sets the alpha (opacity) channel of a color. Values range from 0 (fully transparent) to 1 (fully opaque). Setting alpha returns a new Color instance. ```javascript import chroma from 'chroma-js'; // Get alpha const color = chroma('rgba(255, 0, 0, 0.5)'); console.log(color.alpha()); // 0.5 // Set alpha (returns new Color) const red = chroma('red'); const semiRed = red.alpha(0.5); console.log(semiRed.rgba()); // [255, 0, 0, 0.5] console.log(red.alpha()); // 1 (original unchanged) // Chain with other operations const result = chroma('blue') .alpha(0.7) .darken() .hex(); console.log(result); // '#0000b3b3' (hex with alpha) ``` -------------------------------- ### Update Documentation Source: https://github.com/gka/chroma.js/blob/main/readme.md Update the project's documentation by running the npm run docs script. ```bash npm run docs ``` -------------------------------- ### Get or Set Color Luminance with luminance() Source: https://context7.com/gka/chroma.js/llms.txt The luminance() method gets or sets the relative luminance of a color according to WCAG standards (0=black, 1=white). It can also be used to interpolate luminance in different color spaces like 'lab' or 'hsl'. ```javascript import chroma from 'chroma-js'; // Get luminance console.log(chroma('white').luminance()); // 1 console.log(chroma('black').luminance()); // 0 console.log(chroma('red').luminance()); // 0.2126 console.log(chroma('aquamarine').luminance()); // 0.808... console.log(chroma('hotpink').luminance()); // 0.346... // Set luminance (adjusts color to match target) const colors = ['white', 'aquamarine', 'hotpink', 'darkslateblue']; const normalized = colors.map(c => chroma(c).luminance(0.5).hex()); console.log(normalized); // All colors adjusted to 50% luminance // Interpolate in different color spaces const color = chroma('aquamarine'); console.log(color.luminance(0.5).hex()); // '#6fddb1' (rgb) console.log(color.luminance(0.5, 'lab').hex()); // '#6ed6ab' (lab) console.log(color.luminance(0.5, 'hsl').hex()); // '#68d6ab' (hsl) ``` -------------------------------- ### Chroma.js Color Brewer and Bezier Interpolation Source: https://github.com/gka/chroma.js/blob/main/docs/src/index.md Explains how to use ColorBrewer scales and perform bezier interpolation between colors in chroma.js. ```APIDOC ### chroma.brewer chroma.js includes the definitions from [ColorBrewer2.org](http://colorbrewer2.org/). Read more about these colors [in the corresponding paper](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.361.6082&rep=rep1&type=pdf) by Mark Harrower and Cynthia A. Brewer. ```js chroma.scale('YlGnBu'); chroma.scale('Spectral'); ``` To reverse the colors you could simply reverse the domain: ```js chroma.scale('Spectral').domain([1,0]); ``` You can access the colors directly using `chroma.brewer`. ```js chroma.brewer.OrRd ``` ### chroma.bezier #### (colors) `chroma.bezier` returns a function that [bezier-interpolates between colors](https://www.vis4.net/blog/mastering-multi-hued-color-scales/) in `Lab` space. The input range of the function is `[0..1]`. ```js // linear interpolation chroma.scale(['yellow', 'red', 'black']); // bezier interpolation chroma.bezier(['yellow', 'red', 'black']); ``` You can convert an bezier interpolator into a chroma.scale instance ```js chroma.bezier(['yellow', 'red', 'black']) .scale() .colors(5); ``` ``` -------------------------------- ### Initialize CodeMirror with JSON-LD Mode Source: https://github.com/gka/chroma.js/blob/main/docs/libs/codemirror/mode/javascript/json-ld.html Use this to set up a CodeMirror editor instance for JSON-LD content. Ensure the target textarea has the ID 'code'. ```javascript var editor = CodeMirror.fromTextArea(document.getElementById("code"), { matchBrackets: true, autoCloseBrackets: true, mode: "application/ld+json", lineWrapping: true }); ``` -------------------------------- ### Get Colors from a Scale Source: https://github.com/gka/chroma.js/blob/main/docs/src/index.md Extract a specified number of equi-distant colors from a scale using `scale.colors(n)`. If `n` is omitted, it returns the original array of colors used to create the scale. Pass `null` for `format` to get `chroma` instances. ```javascript chroma.scale('OrRd').colors(5); chroma.scale(['white', 'black']).colors(12); ``` -------------------------------- ### Run Tests Source: https://github.com/gka/chroma.js/blob/main/readme.md Execute the test suite for Chroma.js using the npm test script. It's recommended to add new tests for any added features. ```bash npm test ``` -------------------------------- ### color.luminance Source: https://github.com/gka/chroma.js/blob/main/docs/index.html Gets or sets the relative brightness of a color. ```APIDOC ## color.luminance([lum, mode='rgb']) ### Description If called without arguments, returns the relative brightness of the color. If called with arguments, it adjusts the luminance of the color by interpolating with black or white. ### Parameters #### Path Parameters - **lum** (Number) - Optional. The target luminance value (0 to 1). If provided, the color's luminance will be adjusted to this value. - **mode** (String) - Optional. The color space to use for interpolation ('rgb', 'lab', 'hsl'). Defaults to 'rgb'. ### Request Example ```javascript // Get luminance chroma('white').luminance(); chroma('aquamarine').luminance(); // Set luminance to 50% chroma('white').luminance(0.5); chroma('aquamarine').luminance(0.5); // Set luminance in different color spaces chroma('aquamarine').luminance(0.5, 'lab'); chroma('aquamarine').luminance(0.5, 'hsl'); ``` ### Response #### Success Response (200) - **luminanceValue** (Number) - The luminance value of the color (when getting) or the chroma object itself (when setting). ``` -------------------------------- ### Build Chroma.js Source: https://github.com/gka/chroma.js/blob/main/readme.md Compile the CoffeeScript source files into build files using the npm build script. ```bash npm run build ``` -------------------------------- ### Color Manipulation - Luminance Source: https://github.com/gka/chroma.js/blob/main/docs/src/index.md Get and adjust the luminance of a color. ```APIDOC ## color.luminance([lum, mode='rgb']) ### Description If called without arguments, returns the relative brightness of the color (normalized to 0 for black and 1 for white). If called with arguments, it adjusts the luminance of the color by interpolating with black or white. ### Parameters #### Path Parameters - **lum** (Number) - Optional. The target luminance value (0 to 1). If provided, the color's luminance will be adjusted to this value. - **mode** (String) - Optional. The color space used for interpolation ('rgb', 'lab', 'hsl'). Defaults to 'rgb'. ### Request Example ```js // Get luminance chroma('white').luminance(); chroma('aquamarine').luminance(); // Adjust luminance chroma('white').luminance(0.5); chroma('aquamarine').luminance(0.5); chroma('aquamarine').luminance(0.5, 'lab'); ``` ``` -------------------------------- ### Get Numeric Representation Source: https://github.com/gka/chroma.js/blob/main/docs/src/index.md Returns the numeric representation of the hexadecimal RGB color. ```javascript chroma('#000000').num() ``` ```javascript chroma('#0000ff').num() ``` ```javascript chroma('#00ff00').num() ``` ```javascript chroma('#ff0000').num() ``` -------------------------------- ### Initialize CodeMirror for Shell and JavaScript Source: https://github.com/gka/chroma.js/blob/main/docs/index.html Initializes CodeMirror instances for shell and JavaScript code blocks, enabling syntax highlighting and interactive features. Includes functionality to display color previews and evaluate JavaScript code. ```javascript $('code.lang-shell').each(function () { var code = this; var cm = CodeMirror( function (elt) { code.parentNode.replaceChild(elt, code); }, { value: code.innerHTML.trim(), indentUnit: 4, mode: 'shell', readOnly: true, lineWrapping: true, scrollbarStyle: 'null', } ); }); $('code.lang-js').each(function () { var code = this; var cm = CodeMirror( function (elt) { code.parentNode.replaceChild(elt, code); }, { value: code.innerHTML.trim(), indentUnit: 4, mode: 'javascript', lineWrapping: true, scrollbarStyle: 'null' } ); cm.on('update', function ( _cm, change ) { showColors(_cm); }); var resDisplay = $( '
' ).appendTo(cm.display.wrapper.parentNode); if (!cm.getDoc().getValue().includes('import')) showColors(cm); function showColors(cm) { $('.cm-string', cm.display.wrapper).each(styleSpan); $('.cm-number', cm.display.wrapper).each(enableSlider); // evaluate script var src = cm.getDoc().getValue(); //resDisplay.html(''); chroma.setLabWhitePoint('D65'); try { var s = src.split(';').filter(d => d).map(eval); resDisplay.html( '
  1. ' + s .map(resRec) .map(d => d || ' ') // .filter(function (d) { // return d !== undefined; // }) .join('
  2. ') + '
' ); $('.cm-string', resDisplay).each(styleSpan); } catch (e) { // console.warn(e); } function resRec(d) { if ($.isArray(d)) { return '\[' + d.map(d.length > 2 ? resShort : resLong).join(',') + '\]'; } return resLong(d); function resLong(d) { if (typeof d == 'boolean') { return '' + (d ? 'true' : 'false') + ''; } else if (typeof d == 'string') { // string color, e.g. hex value return '"' + d + '"'; } else if (typeof d == 'object' && d._rgb) { // chroma.js object return ( '' + d.hex() + '' ); } else if ($.isNumeric(d)) { return '' + round(d, 3) + ''; } else if ($.isFunction(d)) { var s = ''; var dom = d.domain ? d.domain() : [0, 1], dmin = Math.min(dom[0], dom[dom.length - 1]), dmax = Math.max(dom[dom.length - 1], dom[0]); for (var i = 0; i <= 100; i++) { s += ''; } s += '' + dmin + ''; s += '' + (dmin + dmax) * 0.5 + ''; s += '' + dmax + ''; return '
' + s + '
'; } } function resShort(d) { if (typeof d == 'string') { // string color, e.g. hex value return ( '\'' + chroma(d).hex() + '"' ); } else if (typeof d == 'object' && d._rgb) { // chroma.js object return ( '\'' + d.hex() + '"' ); } else if ($.isNumeric(d)) { return '' + round(d, 2) + ''; } else if (isNaN(d)) { return 'NaN'; } } function round(d, p) { var n = Math.pow(10, p); return Math.round(d * n) / n; } } } function styleSpan() { var span = $(this); //setTimeout(function() { val = span.data('color') || span.html().replace(/['"]/g, '').trim(); if (chroma[val]) { span.attr('style', ''); return; } try { if (chroma.valid(val)) { const col = chroma(val); const l = col.oklch()[0]; const isCSS = /[a-z]+\([^\)]+\)/.test(val); span.attr( 'style', [ 'background-color:' + (isCSS ? val : col.hex()), 'color:' + (l < 0.7 ? 'white' : 'black'), ...(isCSS ? [] : ['opacity:' + col.alpha()]) ].join(';') ); } } catch (e) { //console.log(e); span.attr('style', ''); // not a color, so ignore } //}, 50); } function enableSlider() { return; var span = $(this), slider = $('
').addClass('slider'), input = $('').appendTo(slider); span.off('mouseenter').on('mouseenter', function () { var v = +span.text(), d = Math.pow(10, Math.max(1, Math.log10(v))), min = v - d, max = v + d; input.attr({ min: min, max: max }).prop('value', v); console.log('span', v); span.append(slider); }); span.off('mouseleave').on('mouseleave', function () { //slider.remove(); }); } }); var toc = $( '
    ' ) .addClass('toc') .appendTo($('
    ').addClass('toc-container').appendTo('.wrap')); var hue = Math.random() * 360; $('h2,h3').each(function () { var h = $(this), l = h.attr('id'), t = h.is('h2'); toc.append( '