[
  {
    "path": ".github/dependabot.yml",
    "content": "version: 2\nupdates:\n  - package-ecosystem: npm\n    directory: \"/\"\n    schedule:\n      interval: daily\n    assignees:\n      - mistic100\n    commit-message:\n      prefix: 'chore'\n      include: 'scope'\n  - package-ecosystem: github-actions\n    directory: '/'\n    schedule:\n      interval: weekly\n    assignees:\n      - mistic100\n    commit-message:\n      prefix: 'chore'\n      include: 'scope'\n  \n"
  },
  {
    "path": ".github/workflows/main.yml",
    "content": "name: CI\n\non: [push, pull_request]\n\njobs:\n  build:\n\n    runs-on: ubuntu-latest\n    \n    steps:\n    - uses: actions/checkout@v4\n    - name: build\n      run: |\n        npm install\n        npm run test\n"
  },
  {
    "path": ".gitignore",
    "content": ".idea\n*.iml\nnode_modules\nyarn.lock\nyarn-error.log\n"
  },
  {
    "path": "LICENSE",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2014-2025 Damien Sorel\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# tinygradient\n\n[![npm version](https://img.shields.io/npm/v/tinygradient.svg?style=flat-square)](https://www.npmjs.com/package/tinygradient)\n[![jsDelivr CDN](https://data.jsdelivr.com/v1/package/npm/tinygradient/badge)](https://www.jsdelivr.com/package/npm/tinygradient)\n[![GZIP size](https://img.shields.io/bundlephobia/minzip/tinygradient?label=gzip%20size)](https://bundlephobia.com/result?p=tinygradient)\n[![Build Status](https://github.com/mistic100/tinygradient/workflows/CI/badge.svg)](https://github.com/mistic100/tinygradient/actions)\n\nEasily generate color gradients with an unlimited number of color stops and steps. \n\n[Live demo](https://mistic100.github.io/tinygradient/)\n\n## Installation\n\n```\n$ npm install tinygradient\n```\n\n### Dependencies\n\n- [TinyColor](https://github.com/bgrins/TinyColor)\n\n## Usage\n\nThe gradient can be generated using RGB or HSV interpolation. HSV usually produces brighter colors.\n\n### Initialize gradient\n\nThe `tinygradient` constructor takes a list or an array of colors stops.\n\n```javascript\n// using varargs\nconst gradient = tinygradient('red', 'green', 'blue');\n\n// using array\nconst gradient = tinygradient([\n  '#ff0000',\n  '#00ff00',\n  '#0000ff'\n]);\n```\n\nThe colors are parsed with TinyColor, [multiple formats are accepted](https://github.com/bgrins/TinyColor/blob/master/README.md#accepted-string-input).\n\n```javascript\nconst gradient = tinygradient([\n  tinycolor('#ff0000'),       // tinycolor object\n  {r: 0, g: 255, b: 0},       // RGB object\n  {h: 240, s: 1, v: 1, a: 1}, // HSVa object\n  'rgb(120, 120, 0)',         // RGB CSS string\n  'gold'                      // named color\n]);\n```\n\nYou can also specify the position of each color stop (between `0` and `1`). If no position is specified, stops are distributed equidistantly.\n\n```javascript\nconst gradient = tinygradient([\n  {color: '#d8e0de', pos: 0},\n  {color: '#255B53', pos: 0.8},\n  {color: '#000000', pos: 1}\n]);\n```\n\n### Generate gradient\n\nEach method takes at least the number of desired steps.\n> The generated gradients might have one more step in certain conditions.\n\n```javascript\n// RGB interpolation\nconst colorsRgb = gradient.rgb(9);\n```\n![rgb](https://raw.githubusercontent.com/mistic100/tinygradient/master/images/rgb.png)\n\n```javascript\n// HSV clockwise interpolation\nconst colorsHsv = gradient.hsv(9);\n```\n![hsv](https://raw.githubusercontent.com/mistic100/tinygradient/master/images/hsv.png)\n\n```javascript\n// HSV counter-clockwise interpolation\nconst colorsHsv = gradient.hsv(9, true);\n```\n![hsv2](https://raw.githubusercontent.com/mistic100/tinygradient/master/images/hsv2.png)\n\nThere are also two methods which will automatically choose between clockwise and counter-clockwise.\n\n```javascript\n// HSV interpolation using shortest arc between colors\nconst colorsHsv = gradient.hsv(9, 'short');\n\n// HSV interpolation using longest arc between colors\nconst colorsHsv = gradient.hsv(9, 'long');\n```\n\nEach method returns an array of TinyColor objects, [see available methods](https://github.com/bgrins/TinyColor/blob/master/README.md#methods).\n\n### Get CSS gradient string\n\nThe `css` method will output a valid W3C string (without vendors prefix) to use with `background-image` CSS property.\n\n```javascript\n// linear gradient to right (default)\nconst gradientStr = gradient.css();\n\n// radial gradient ellipse at top left\nconst gradientStr = gradient.css('radial', 'farthest-corner ellipse at top left');\n```\n\n### Get color at a specific position\n\nReturns a single TinyColor object from a defined position in the gradient (from 0 to 1).\n\n```javascript\n// with RGB interpolation\ncolorAt55Percent = gradient.rgbAt(0.55);\n\n// with HSV interpolation\ncolorAt55Percent = gradient.hsvAt(0.55);\n```\n\n### Reversing gradient\n\nReturns a new instance of TinyGradient with reversed colors.\n\n```javascript\nconst reversedGradient = gradient.reverse();\n```\n\n### Loop the gradient\n\nReturns a new instance of TinyGradient with looped colors.\n\n```javascript\nconst loopedGradient = gradient.loop();\n```\n\n### Position-only stops\n\nI is possible to define stops with the `pos` property only and no `color`. This allows to define the position of the mid-point between the previous and the next stop.\n\n```js\nconst gradient = tinygradient([\n  {color: 'black', pos: 0},\n  {pos: 0.8}, // #808080 will be at 80% instead of 50%\n  {color: 'white', pos: 1}\n]);\n```\n\n\n## License\nThis library is available under the MIT license.\n"
  },
  {
    "path": "index.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n    <meta charset=\"utf-8\">\n\n    <title>tinygradient</title>\n\n    <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@4.1.3/dist/css/bootstrap.min.css\"/>\n    <link rel=\"stylesheet\"\n          href=\"https://cdn.jsdelivr.net/npm/bootstrap-colorpicker@3.0.3/dist/css/bootstrap-colorpicker.min.css\"/>\n\n    <style>\n        footer {\n            padding-top: 2rem;\n            padding-bottom: 2rem;\n            margin-top: 3rem;\n            background-color: #e9ecef;\n        }\n\n        .colorpicker.colorpicker-popup {\n            -moz-user-select: none;\n        }\n\n        .out-list .out {\n            width: 100%;\n            height: 20px;\n            margin-bottom: 20px;\n            display: flex;\n            justify-content: space-between;\n        }\n\n        .out-list .out.css {\n            margin-bottom: 0;\n        }\n\n        .out-list .out div {\n            flex-grow: 1;\n            position: relative;\n        }\n\n        .out-list .out div>span  {\n            content: attr(title);\n            position: absolute;\n            bottom: -15px;\n            font-family: monospace;\n            font-size: 12px;\n        }\n        .out-list .out div>span::selection {\n            color: white;\n            background: #444;\n        }\n    </style>\n</head>\n\n<body>\n\n<section class=\"jumbotron text-center\">\n    <div class=\"container\">\n        <h1 class=\"jumbotron-heading\">tinygradient</h1>\n        <p class=\"lead text-muted\">simple gradient generator</p>\n        <p>\n            <a href=\"https://github.com/mistic100/tinygradient\" class=\"btn btn-primary btn-lg\">\n                <img src=\"https://octodex.github.com/images/original.png\" height=\"32\" /> GitHub\n            </a>\n        </p>\n    </div>\n</section>\n\n<div class=\"container\">\n    <h2>Playground</h2>\n\n    <div class=\"row\">\n        <div class=\"col-4\">\n            <ul class=\"list-group mb-3\" id=\"colors-list\">\n                <li class=\"list-group-item list-group-item-secondary\" style=\"padding: 0.25rem 1.25rem;\">\n                    <div class=\"form-row\">\n                        <div class=\"col-7\">\n                            Color\n                        </div>\n                        <div class=\"col-5\">\n                            Position\n                        </div>\n                    </div>\n                </li>\n            </ul>\n\n            <button class=\"btn btn-primary mb-3\" type=\"button\" id=\"add-color\">new color</button>\n\n            <div class=\"form-group form-inline\">\n                <label for=\"steps\">Steps</label>\n                <input type=\"number\" class=\"ml-2 form-control\" min=\"2\" id=\"steps\" name=\"steps\">\n            </div>\n        </div>\n\n        <div class=\"col-8\">\n            <div class=\"card mb-4\">\n                <ul class=\"list-group list-group-flush out-list\" id=\"playground-output\">\n                </ul>\n            </div>\n        </div>\n    </div>\n</div>\n\n<div class=\"container\">\n    <h2>Colorbrewer</h2>\n\n    <div class=\"row\">\n        <div class=\"col-4\">\n            <div class=\"form-group form-inline\">\n                <label for=\"cb-scheme\">Scheme</label>\n                <select class=\"ml-2 form-control\" id=\"cb-scheme\" name=\"cb-scheme\"></select>\n            </div>\n\n            <div class=\"form-group form-inline\">\n                <label for=\"cb-steps\">Steps</label>\n                <input type=\"number\" class=\"ml-2 form-control\" min=\"3\" id=\"cb-steps\" name=\"cb-steps\">\n            </div>\n        </div>\n\n        <div class=\"col-8\">\n            <div class=\"card mb-4\">\n                <ul class=\"list-group list-group-flush out-list\" id=\"cb-playground-output\">\n                </ul>\n            </div>\n        </div>\n    </div>\n</div>\n\n<script type=\"text/template\" id=\"playground-item\">\n    <li class=\"list-group-item\">\n        <div class=\"form-row\">\n            <div class=\"col-7\">\n                <input class=\"form-control\" type=\"text\" name=\"color\">\n            </div>\n            <div class=\"col-3\">\n                <input class=\"form-control\" type=\"number\" min=\"0\" max=\"1\" step=\"0.1\" name=\"pos\">\n            </div>\n            <div class=\"col-2\">\n                <button class=\"btn btn-outline-danger\" data-dismiss=\"color\">del.</button>\n            </div>\n        </div>\n    </li>\n</script>\n\n<script src=\"https://cdn.jsdelivr.net/npm/jquery@3.3.1/dist/jquery.min.js\"></script>\n<script src=\"https://cdn.jsdelivr.net/npm/popper.js@1.14.6/dist/umd/popper.min.js\"></script>\n<script src=\"https://cdn.jsdelivr.net/npm/bootstrap@4.1.3/dist/js/bootstrap.min.js\"></script>\n<script src=\"https://cdn.jsdelivr.net/npm/bootstrap-colorpicker@3.0.3/dist/js/bootstrap-colorpicker.min.js\"></script>\n\n<script type=\"importmap\">\n    {\n        \"imports\": {\n            \"colorbrewer\": \"https://cdn.jsdelivr.net/npm/colorbrewer@1.5.9/+esm\",\n            \"randomcolor\": \"https://cdn.jsdelivr.net/npm/randomcolor/+esm\",\n            \"tinycolor2\": \"https://cdn.jsdelivr.net/npm/tinycolor2@1.6.0/esm/tinycolor.min.js\",\n            \"tinygradient\": \"./index.js\"\n        }\n    }\n</script>\n\n<script type=\"module\">\n    import colorbrewer from 'colorbrewer';\n    import randomColor from 'randomcolor';\n    import tinycolor from 'tinycolor2';\n    import tinygradient from 'tinygradient';\n\n    const tpl = document.querySelector('#playground-item').innerHTML;\n    const list = $('#colors-list');\n\n    let steps = 9;\n\n    function addColor(color) {\n        color = color || randomColor();\n\n        const item = $(tpl);\n        item.find('[name=color]').val(color).colorpicker();\n\n        list.append(item);\n\n        computePos();\n    }\n\n    function computePos() {\n        const pos = list.find('[name=pos]');\n\n        pos.each(function(i) {\n           this.value = i / (pos.length - 1);\n        });\n    }\n\n    function setOutputFromPlayground() {\n        const pos = list.find('[name=pos]')\n            .map(function () {\n                const val = parseFloat(this.value);\n                return isNaN(val) ? undefined : val;\n            })\n            .get();\n\n        const colors = list.find('[name=color]')\n            .map(function () {\n                return this.value;\n            })\n            .get()\n            .map(function(color, i) {\n                return {\n                    color: color,\n                    pos: pos[i]\n                };\n            });\n\n        setOutput(colors, steps);\n    }\n\n    function setOutput(colors, steps) {\n        let html = '';\n\n        if (colors.length < 2) {\n            html = 'Not enough colors';\n        } else {\n            try {\n                const grad = tinygradient(colors);\n\n                // CSS\n                html += '<li class=\"list-group-item\"><h4>CSS reference</h4>';\n                html += '<div class=\"out css\" style=\"background:' + grad.css() + ';\"></div>';\n                html += '</li>';\n\n                // RGB\n                html += '<li class=\"list-group-item\"><h4>RGB interpolation</h4>';\n                html += '<div class=\"out rgb\">';\n                grad.rgb(steps).forEach((color) => {\n                    html += '<div style=\"background:' + color.toRgbString() + ';\"><span>' + color.toHexString() + '</span></div>';\n                });\n                html += '</div></li>';\n\n                // RGB loop\n                html += '<li class=\"list-group-item\"><h4>RGB loop</h4>';\n                html += '<div class=\"out rgb\">';\n                grad.loop().rgb(Math.max(steps, colors.length * 2 - 1)).forEach((color) => {\n                    html += '<div style=\"background:' + color.toRgbString() + ';\"><span>' + color.toHexString() + '</span></div>';\n                });\n                html += '</div></li>';\n\n                // HSV\n                html += '<li class=\"list-group-item\"><h4>HSV short interpolation</h4>';\n                html += '<div class=\"out hsv\">';\n                grad.hsv(steps, 'short').forEach((color) => {\n                    html += '<div style=\"background:' + color.toRgbString() + ';\"><span>' + color.toHexString() + '</span></div>';\n                });\n                html += '</div></li>';\n\n                // HSV2\n                html += '<li class=\"list-group-item\"><h4>HSV long interpolation</h4>';\n                html += '<div class=\"out hsv2\">';\n                grad.hsv(steps, 'long').forEach((color) => {\n                    html += '<div style=\"background:' + color.toRgbString() + ';\"><span>' + color.toHexString() + '</span></div>';\n                });\n                html += '</div></li>';\n\n            } catch (error) {\n                html = error;\n            }\n        }\n\n        document.querySelector('#playground-output').innerHTML = html;\n    }\n\n    list\n        .on('colorpickerChange colorpickerCreate', function (e) {\n            e.colorpicker.element.css('background-color', e.color.toString());\n            e.colorpicker.element.css('color', tinycolor.mostReadable(e.color.toString(), ['white', 'black']).toHexString());\n            e.colorpicker.element[0].value = e.color.toString();\n            setOutputFromPlayground();\n        })\n        .on('change', '[name=pos]', function() {\n            setOutputFromPlayground();\n        })\n        .on('click', '[data-dismiss=\"color\"]', function () {\n            $(this).closest('li').remove();\n            computePos();\n            setOutputFromPlayground();\n        });\n\n    $('[name=steps]')\n        .on('change input', function () {\n            steps = this.value;\n            setOutputFromPlayground();\n        })\n        .val(steps);\n\n    addColor('#00E5BC');\n    addColor('#BF0022');\n\n    ////////////////////////////////////////\n\n    let cbScheme = 'BuGn';\n    let cbSteps = 9;\n\n    function setCbOutput() {\n        const colors = list.find('[name=color]')\n            .map(function () {\n                return this.value;\n            })\n            .get();\n\n        let html = '';\n\n        const cbVariant = Math.min(cbSteps, Math.max.apply(null, Object.keys(colorbrewer[cbScheme])));\n        const grad = tinygradient(colorbrewer[cbScheme][cbVariant]);\n\n        html += '<li class=\"list-group-item\">';\n        html += '<div class=\"out rgb\">';\n        grad.rgb(cbSteps).forEach((color) => {\n            html += '<div style=\"background:' + color.toRgbString() + ';\"><span>' + color.toHexString() + '</span></div>';\n        });\n        html += '</div></li>';\n\n        document.querySelector('#cb-playground-output').innerHTML = html;\n    }\n\n    (() => {\n        let html = '';\n\n        $.each(colorbrewer.schemeGroups, (group, schemes) => {\n           html+= '<optgroup label=\"' + group + '\">';\n           schemes.forEach((scheme) => {\n              html += '<option>' + scheme + '</option>';\n           });\n           html+= '</optgroup>';\n        });\n\n        $('[name=cb-scheme]').html(html);\n    })();\n\n    $('[name=cb-scheme]')\n        .on('change', function () {\n            cbScheme = this.value;\n            setCbOutput();\n        })\n        .val(cbScheme);\n\n    $('[name=cb-steps]')\n        .on('change', function () {\n            cbSteps = this.value;\n            setCbOutput();\n        })\n        .val(cbSteps);\n\n    $('#add-color').on('click', () => addColor());\n\n    setCbOutput();\n</script>\n\n</body>\n</html>\n"
  },
  {
    "path": "index.js",
    "content": "import tinycolor from 'tinycolor2';\n\n/**\n * @typedef {Object} TinyGradient.StopInput\n * @property {ColorInput} color\n * @property {number} pos\n */\n\n/**\n * @typedef {Object} TinyGradient.StepValue\n * @type {number} [r]\n * @type {number} [g]\n * @type {number} [b]\n * @type {number} [h]\n * @type {number} [s]\n * @type {number} [v]\n * @type {number} [a]\n */\n\n/**\n * @type {StepValue}\n */\nconst RGBA_MAX = { r: 256, g: 256, b: 256, a: 1 };\n\n/**\n * @type {StepValue}\n */\nconst HSVA_MAX = { h: 360, s: 1, v: 1, a: 1 };\n\n/**\n * Linearly compute the step size between start and end (not normalized)\n * @param {StepValue} start\n * @param {StepValue} end\n * @param {number} steps - number of desired steps\n * @return {StepValue}\n */\nfunction stepize(start, end, steps) {\n    let step = {};\n\n    for (let k in start) {\n        if (start.hasOwnProperty(k)) {\n            step[k] = steps === 0 ? 0 : (end[k] - start[k]) / steps;\n        }\n    }\n\n    return step;\n}\n\n/**\n * Compute the final step color\n * @param {StepValue} step - from `stepize`\n * @param {StepValue} start\n * @param {number} i - color index\n * @param {StepValue} max - rgba or hsva of maximum values for each channel\n * @return {StepValue}\n */\nfunction interpolate(step, start, i, max) {\n    let color = {};\n\n    for (let k in start) {\n        if (start.hasOwnProperty(k)) {\n            color[k] = step[k] * i + start[k];\n            color[k] = color[k] < 0 ? color[k] + max[k] : (max[k] !== 1 ? color[k] % max[k] : color[k]);\n        }\n    }\n\n    return color;\n}\n\n/**\n * Generate gradient with RGBa interpolation\n * @param {StopInput} stop1\n * @param {StopInput} stop2\n * @param {number} steps\n * @return {tinycolor[]} color1 included, color2 excluded\n */\nfunction interpolateRgb(stop1, stop2, steps) {\n    const start = stop1.color.toRgb();\n    const end = stop2.color.toRgb();\n    const step = stepize(start, end, steps);\n    let gradient = [stop1.color];\n\n    for (let i = 1; i < steps; i++) {\n        const color = interpolate(step, start, i, RGBA_MAX);\n        gradient.push(tinycolor(color));\n    }\n\n    return gradient;\n}\n\n/**\n * Generate gradient with HSVa interpolation\n * @param {StopInput} stop1\n * @param {StopInput} stop2\n * @param {number} steps\n * @param {boolean|'long'|'short'} mode\n * @return {tinycolor[]} color1 included, color2 excluded\n */\nfunction interpolateHsv(stop1, stop2, steps, mode) {\n    const start = stop1.color.toHsv();\n    const end = stop2.color.toHsv();\n\n    // rgb interpolation if one of the steps in grayscale\n    if (start.s === 0 || end.s === 0) {\n        return interpolateRgb(stop1, stop2, steps);\n    }\n\n    let trigonometric;\n    if (typeof mode === 'boolean') {\n        trigonometric = mode;\n    }\n    else {\n        const trigShortest = (start.h < end.h && end.h - start.h < 180) || (start.h > end.h && start.h - end.h > 180);\n        trigonometric = (mode === 'long' && trigShortest) || (mode === 'short' && !trigShortest);\n    }\n\n    const step = stepize(start, end, steps);\n    let gradient = [stop1.color];\n\n    // recompute hue\n    let diff;\n    if ((start.h <= end.h && !trigonometric) || (start.h >= end.h && trigonometric)) {\n        diff = end.h - start.h;\n    }\n    else if (trigonometric) {\n        diff = 360 - end.h + start.h;\n    }\n    else {\n        diff = 360 - start.h + end.h;\n    }\n    step.h = Math.pow(-1, trigonometric ? 1 : 0) * Math.abs(diff) / steps;\n\n    for (let i = 1; i < steps; i++) {\n        const color = interpolate(step, start, i, HSVA_MAX);\n        gradient.push(tinycolor(color));\n    }\n\n    return gradient;\n}\n\n/**\n * Compute substeps between each stops\n * @param {StopInput[]} stops\n * @param {number} steps\n * @return {number[]}\n */\nfunction computeSubsteps(stops, steps) {\n    const l = stops.length;\n\n    // validation\n    steps = parseInt(steps, 10);\n\n    if (isNaN(steps) || steps < 2) {\n        throw new Error('Invalid number of steps (< 2)');\n    }\n    if (steps < l) {\n        throw new Error('Number of steps cannot be inferior to number of stops');\n    }\n\n    // compute substeps from stop positions\n    let substeps = [];\n\n    for (let i = 1; i < l; i++) {\n        const step = (steps - 1) * (stops[i].pos - stops[i - 1].pos);\n        substeps.push(Math.max(1, Math.round(step)));\n    }\n\n    // adjust number of steps\n    let totalSubsteps = 1;\n    for (let n = l - 1; n--;) totalSubsteps += substeps[n];\n\n    while (totalSubsteps !== steps) {\n        if (totalSubsteps < steps) {\n            const min = Math.min.apply(null, substeps);\n            substeps[substeps.indexOf(min)]++;\n            totalSubsteps++;\n        }\n        else {\n            const max = Math.max.apply(null, substeps);\n            substeps[substeps.indexOf(max)]--;\n            totalSubsteps--;\n        }\n    }\n\n    return substeps;\n}\n\n/**\n * Compute the color at a specific position\n * @param {StopInput[]} stops\n * @param {number} pos\n * @param {string} method\n * @param {StepValue} max\n * @returns {tinycolor}\n */\nfunction computeAt(stops, pos, method, max) {\n    if (pos < 0 || pos > 1) {\n        throw new Error('Position must be between 0 and 1');\n    }\n\n    let start, end;\n    for (let i = 0, l = stops.length; i < l - 1; i++) {\n        if (pos >= stops[i].pos && pos < stops[i + 1].pos) {\n            start = stops[i];\n            end = stops[i + 1];\n            break;\n        }\n    }\n\n    if (!start) {\n        start = end = stops[stops.length - 1];\n    }\n\n    const step = stepize(start.color[method](), end.color[method](), (end.pos - start.pos) * 100);\n    const color = interpolate(step, start.color[method](), (pos - start.pos) * 100, max);\n    return tinycolor(color);\n}\n\nclass TinyGradient {\n    /**\n     * @param {StopInput[]|ColorInput[]} stops\n     * @returns {TinyGradient}\n     */\n    constructor(stops) {\n        // validation\n        if (stops.length < 2) {\n            throw new Error('Invalid number of stops (< 2)');\n        }\n\n        const havingPositions = stops[0].pos !== undefined;\n        let l = stops.length;\n        let p = -1;\n        let lastColorLess = false;\n        // create tinycolor objects and clean positions\n        this.stops = stops.map((stop, i) => {\n            const hasPosition = stop.pos !== undefined;\n            if (havingPositions ^ hasPosition) {\n                throw new Error('Cannot mix positionned and not posionned color stops');\n            }\n\n            if (hasPosition) {\n                const hasColor = stop.color !== undefined;\n                if (!hasColor && (lastColorLess || i === 0 || i === l - 1)) {\n                    throw new Error('Cannot define two consecutive position-only stops');\n                }\n                lastColorLess = !hasColor;\n\n                stop = {\n                    color    : hasColor ? tinycolor(stop.color) : null,\n                    colorLess: !hasColor,\n                    pos      : stop.pos\n                };\n\n                if (stop.pos < 0 || stop.pos > 1) {\n                    throw new Error('Color stops positions must be between 0 and 1');\n                }\n                else if (stop.pos < p) {\n                    throw new Error('Color stops positions are not ordered');\n                }\n                p = stop.pos;\n            }\n            else {\n                stop = {\n                    color: tinycolor(stop.color !== undefined ? stop.color : stop),\n                    pos  : i / (l - 1)\n                };\n            }\n\n            return stop;\n        });\n\n        if (this.stops[0].pos !== 0) {\n            this.stops.unshift({\n                color: this.stops[0].color,\n                pos  : 0\n            });\n            l++;\n        }\n        if (this.stops[l - 1].pos !== 1) {\n            this.stops.push({\n                color: this.stops[l - 1].color,\n                pos  : 1\n            });\n        }\n    }\n\n    /**\n     * Return new instance with reversed stops\n     * @return {TinyGradient}\n     */\n    reverse() {\n        let stops = [];\n\n        this.stops.forEach((stop) => {\n            stops.push({\n                color: stop.color,\n                pos  : 1 - stop.pos\n            });\n        });\n\n        return new TinyGradient(stops.reverse());\n    }\n\n    /**\n     * Return new instance with looped stops\n     * @return {TinyGradient}\n     */\n    loop() {\n        let stops1 = [];\n        let stops2 = [];\n\n        this.stops.forEach((stop) => {\n            stops1.push({\n                color: stop.color,\n                pos  : stop.pos / 2\n            });\n        });\n\n        this.stops.slice(0, -1).forEach((stop) => {\n            stops2.push({\n                color: stop.color,\n                pos  : 1 - stop.pos / 2\n            });\n        });\n\n        return new TinyGradient(stops1.concat(stops2.reverse()));\n    }\n\n    /**\n     * Generate gradient with RGBa interpolation\n     * @param {number} steps\n     * @return {tinycolor[]}\n     */\n    rgb(steps) {\n        const substeps = computeSubsteps(this.stops, steps);\n        let gradient = [];\n\n        this.stops.forEach((stop, i) => {\n            if (stop.colorLess) {\n                stop.color = interpolateRgb(this.stops[i - 1], this.stops[i + 1], 2)[1];\n            }\n        });\n\n        for (let i = 0, l = this.stops.length; i < l - 1; i++) {\n            const rgb = interpolateRgb(this.stops[i], this.stops[i + 1], substeps[i]);\n            gradient.splice(gradient.length, 0, ...rgb);\n        }\n\n        gradient.push(this.stops[this.stops.length - 1].color);\n\n        return gradient;\n    }\n\n    /**\n     * Generate gradient with HSVa interpolation\n     * @param {number} steps\n     * @param {boolean|'long'|'short'} [mode=false]\n     *    - false to step in clockwise\n     *    - true to step in trigonometric order\n     *    - 'short' to use the shortest way\n     *    - 'long' to use the longest way\n     * @return {tinycolor[]}\n     */\n    hsv(steps, mode) {\n        const substeps = computeSubsteps(this.stops, steps);\n        let gradient = [];\n\n        this.stops.forEach((stop, i) => {\n            if (stop.colorLess) {\n                stop.color = interpolateHsv(this.stops[i - 1], this.stops[i + 1], 2, mode)[1];\n            }\n        });\n\n        for (let i = 0, l = this.stops.length; i < l - 1; i++) {\n            const hsv = interpolateHsv(this.stops[i], this.stops[i + 1], substeps[i], mode);\n            gradient.splice(gradient.length, 0, ...hsv);\n        }\n\n        gradient.push(this.stops[this.stops.length - 1].color);\n\n        return gradient;\n    }\n\n    /**\n     * Generate CSS3 command (no prefix) for this gradient\n     * @param {String} [mode=linear] - 'linear' or 'radial'\n     * @param {String} [direction] - default is 'to right' or 'ellipse at center'\n     * @return {String}\n     */\n    css(mode, direction) {\n        mode = mode || 'linear';\n        direction = direction || (mode === 'linear' ? 'to right' : 'ellipse at center');\n\n        let css = mode + '-gradient(' + direction;\n        this.stops.forEach((stop) => {\n            css += ', ' + (stop.colorLess ? '' : stop.color.toRgbString() + ' ') + (stop.pos * 100) + '%';\n        });\n        css += ')';\n        return css;\n    }\n\n    /**\n     * Returns the color at specific position with RGBa interpolation\n     * @param {number} pos, between 0 and 1\n     * @return {tinycolor}\n     */\n    rgbAt(pos) {\n        return computeAt(this.stops, pos, 'toRgb', RGBA_MAX);\n    }\n\n    /**\n     * Returns the color at specific position with HSVa interpolation\n     * @param {number} pos, between 0 and 1\n     * @return {tinycolor}\n     */\n    hsvAt(pos) {\n        return computeAt(this.stops, pos, 'toHsv', HSVA_MAX);\n    }\n}\n\n/**\n * @param {StopInput[]|ColorInput[]|StopInput...|ColorInput...} stops\n * @returns {TinyGradient}\n */\nfunction tinygradient(stops) {\n    // varargs\n    if (arguments.length === 1) {\n        if (!Array.isArray(arguments[0])) {\n            throw new Error('\"stops\" is not an array');\n        }\n        stops = arguments[0];\n    }\n    else {\n        stops = Array.prototype.slice.call(arguments);\n    }\n\n    return new TinyGradient(stops);\n}\n\nexport {\n    tinygradient,\n    tinygradient as default,\n};\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"tinygradient\",\n  \"version\": \"2.0.1\",\n  \"author\": {\n    \"name\": \"Damien \\\"Mistic\\\" Sorel\",\n    \"email\": \"contact@git.strangeplanet.fr\",\n    \"url\": \"https://www.strangeplanet.fr\"\n  },\n  \"description\": \"Fast and small gradients manipulation, built on top of TinyColor\",\n  \"license\": \"MIT\",\n  \"homepage\": \"https://github.com/mistic100/tinygradient\",\n  \"type\": \"module\",\n  \"main\": \"index.js\",\n  \"types\": \"types.d.ts\",\n  \"files\": [\n    \"index.js\",\n    \"types.d.ts\"\n  ],\n  \"dependencies\": {\n    \"tinycolor2\": \"^1.6.0\"\n  },\n  \"devDependencies\": {\n    \"@types/tinycolor2\": \"^1.4.6\",\n    \"alive-server\": \"^1.3.0\",\n    \"mocha\": \"^11.1.0\"\n  },\n  \"keywords\": [\n    \"color\",\n    \"gradient\"\n  ],\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git://github.com/mistic100/tinygradient.git\"\n  },\n  \"bugs\": {\n    \"url\": \"https://github.com/mistic100/tinygradient/issues\"\n  },\n  \"scripts\": {\n    \"test\": \"mocha tests/*\",\n    \"serve\": \"alive-server\"\n  }\n}\n"
  },
  {
    "path": "tests/basics.js",
    "content": "import tinygradient from '../index.js';\nimport assert from 'assert';\n\ndescribe('TinyGradient', () => {\n    it('should throw an error on invalid steps/colors number', () => {\n        assert.throws(() => {\n            tinygradient('red');\n        });\n        assert.throws(() => {\n            tinygradient(['red']);\n        });\n        assert.throws(() => {\n            let grad = tinygradient('red', 'blue');\n            grad.rgb(1);\n        });\n        assert.throws(() => {\n            let grad = tinygradient('red', 'blue', 'green');\n            grad.rgb(2);\n        });\n    });\n\n    it('should accept varargs and array', () => {\n        let grad1 = tinygradient('red', 'green', 'blue', 'yellow', 'black');\n        let grad2 = tinygradient(['red', 'green', 'blue', 'yellow', 'black']);\n\n        assert.deepStrictEqual(\n            grad1.stops.map(c => c.color.toRgb()),\n            grad2.stops.map(c => c.color.toRgb())\n        );\n    });\n\n    it('should reverse gradient', () => {\n        let grad1 = tinygradient('red', 'green', 'blue', 'yellow', 'black');\n        let grad2 = grad1.reverse();\n\n        assert.deepStrictEqual(\n            grad1.stops.map(c => c.color.toRgb()),\n            grad2.stops.reverse().map(c => c.color.toRgb())\n        );\n    });\n\n    it('should generate 11 steps gradient from black to grey in RGB', () => {\n        let grad = tinygradient({ r: 0, g: 0, b: 0 }, { r: 100, g: 100, b: 100 });\n        let res = grad.rgb(11);\n\n        assert.strictEqual(11, res.length);\n        assert.deepStrictEqual({ r: 0, g: 0, b: 0, a: 1 }, res[0].toRgb(), 'black');\n        assert.deepStrictEqual({ r: 50, g: 50, b: 50, a: 1 }, res[5].toRgb(), 'dark gray');\n        assert.deepStrictEqual({ r: 100, g: 100, b: 100, a: 1 }, res[10].toRgb(), 'gray');\n    });\n\n    it('should generate 13 steps gradient from red to red in HSV', () => {\n        let grad = tinygradient([\n            { h: 0, s: 1, v: 1 },\n            { h: 120, s: 1, v: 1 },\n            { h: 240, s: 1, v: 1 },\n            { h: 0, s: 1, v: 1 }\n        ]);\n        let res = grad.hsv(13);\n\n        assert.strictEqual(13, res.length);\n        assert.deepStrictEqual({ h: 60, s: 1, v: 1, a: 1 }, res[2].toHsv(), 'yellow');\n        assert.deepStrictEqual({ h: 180, s: 1, v: 1, a: 1 }, res[6].toHsv(), 'cyan');\n        assert.deepStrictEqual({ h: 300, s: 1, v: 1, a: 1 }, res[10].toHsv(), 'magenta');\n    });\n\n    it('should generate CSS gradient command for 3 colors', () => {\n        let grad = tinygradient('#f00', '#0f0', '#00f');\n        let res = grad.css();\n        assert.strictEqual('linear-gradient(to right, rgb(255, 0, 0) 0%, rgb(0, 255, 0) 50%, rgb(0, 0, 255) 100%)', res, 'default');\n\n        grad = tinygradient('rgba(255,0,0,0.5)', 'rgba(0,255,0,0.5)', 'rgba(0,0,255,0.5)');\n        res = grad.css('radial', 'ellipse farthest-corner');\n        assert.strictEqual('radial-gradient(ellipse farthest-corner, rgba(255, 0, 0, 0.5) 0%, rgba(0, 255, 0, 0.5) 50%, rgba(0, 0, 255, 0.5) 100%)', res, 'radial with alpha');\n    });\n\n    it('should returns a single color at specific position', () => {\n        let grad = tinygradient('white', 'black');\n        let res = grad.rgbAt(0.5);\n        assert.deepStrictEqual({ r: 128, g: 128, b: 128, a: 1 }, res.toRgb(), 'rgb');\n\n        grad = tinygradient('red', 'blue');\n        res = grad.hsvAt(0.5);\n        assert.deepStrictEqual({ h: 120, s: 1, v: 1, a: 1 }, res.toHsv(), 'hsv');\n    });\n\n    it('should loop a gradient', () => {\n        let grad = tinygradient({ r: 0, g: 0, b: 0 }, { r: 255, g: 255, b: 255 });\n        let res = grad.loop().rgb(5);\n\n        assert.strictEqual(5, res.length);\n        assert.deepStrictEqual({ r: 0, g: 0, b: 0, a: 1 }, res[0].toRgb(), 'black');\n        assert.deepStrictEqual({ r: 255, g: 255, b: 255, a: 1 }, res[2].toRgb(), 'white');\n        assert.deepStrictEqual(res[0].toRgb(), res[4].toRgb(), 'black');\n        assert.deepStrictEqual(res[1].toRgb(), res[3].toRgb(), 'black');\n    });\n\n    it('should allow positionned stops', () => {\n        let grad = tinygradient([{ color: 'black', pos: 0 }, { color: 'white', pos: 0.5 }]);\n\n        assert.deepStrictEqual(\n            grad.rgb(5).map((c) => c.toHex()),\n            ['000000', '808080', 'ffffff', 'ffffff', 'ffffff']\n        );\n    });\n\n    it('should allow position only stops', () => {\n        // reference\n        let grad1 = tinygradient([{ color: 'black', pos: 0 }, { color: 'white', pos: 1 }]);\n\n        assert.deepStrictEqual(\n            grad1.rgb(5).map((c) => c.toHex()),\n            ['000000', '404040', '808080', 'bfbfbf', 'ffffff']\n        );\n\n        // with position stop\n        let grad2 = tinygradient([{ color: 'black', pos: 0 }, { pos: 0.2 }, { color: 'white', pos: 1 }]);\n\n        assert.deepStrictEqual(\n            grad2.rgb(5).map((c) => c.toHex()),\n            ['000000', '808080', 'aaaaaa', 'd5d5d5', 'ffffff']\n        );\n    });\n\n    it('should prevent consecutive position stops', () => {\n        assert.throws(() => {\n            tinygradient([{ color: 'black', pos: 0 }, { pos: 0.2 }, { pos: 0.4 }, { color: 'white', pos: 1 }]);\n        });\n        assert.throws(() => {\n            tinygradient([{ pos: 0.4 }, { color: 'white', pos: 1 }]);\n        });\n        assert.throws(() => {\n            tinygradient([{ color: 'black', pos: 0 }, { pos: 0.2 }]);\n        });\n    });\n\n    it('should prevent misordered stops', () => {\n        assert.throws(() => {\n            tinygradient([{ color: 'black', pos: 0.5 }, { color: 'white', pos: 0 }]);\n        });\n    });\n\n    it('should allow equal position stops', () => {\n        let grad = tinygradient([\n            { color: 'black', pos: 0 },\n            { color: 'white', pos: 0.5 },\n            { color: 'black', pos: 0.5 },\n            { color: 'white', pos: 1 },\n        ]);\n\n        assert.deepStrictEqual(\n            grad.rgb(8).map((c) => c.toHex()),\n            ['000000', '555555', 'aaaaaa', 'ffffff', '000000', '555555', 'aaaaaa', 'ffffff']\n        );\n    });\n\n    it('should force RGB interpolation when a color is grey', () => {\n        let grad = tinygradient('rgba(86, 86, 86)', 'rgb(45, 163, 185)');\n\n        assert.deepStrictEqual(\n            grad.hsv(5).map((c) => c.toHex()),\n            grad.rgb(5).map((c) => c.toHex()),\n        );\n    });\n});\n"
  },
  {
    "path": "types.d.ts",
    "content": "/*!\n * TinyGradient 1.1.2\n * Copyright 2014-2020 Damien \"Mistic\" Sorel (http://www.strangeplanet.fr)\n * Licensed under MIT (http://opensource.org/licenses/MIT)\n */\n\nimport * as tinycolor from 'tinycolor2';\n\ndeclare namespace tinygradient {\n\n    type ArcMode = boolean | 'short' | 'long';\n\n    type CssMode = 'linear' | 'radial';\n\n    type StopInput = {\n        color?: tinycolor.ColorInput\n        pos?: number\n    }\n\n    interface Instance {\n        stops: StopInput[]\n\n        /**\n         * Return new instance with reversed stops\n         * @return {Instance}\n         */\n        reverse(): Instance;\n\n        /**\n         * Return new instance with looped stops\n         * @return {Instance}\n         */\n        loop(): Instance;\n\n        /**\n         * Generate gradient with RGBa interpolation\n         * @param {int} steps\n         * @return {tinycolor.Instance[]}\n         */\n        rgb(steps: number): tinycolor.Instance[];\n\n        /**\n         * Generate gradient with HSVa interpolation\n         * @param {int} steps\n         * @param {ArcMode} [mode=false]\n         *    - false to step in clockwise\n         *    - true to step in trigonometric order\n         *    - 'short' to use the shortest way\n         *    - 'long' to use the longest way\n         * @return {tinycolor.Instance[]}\n         */\n        hsv(steps: number, mode: ArcMode): tinycolor.Instance[];\n\n        /**\n         * Generate CSS3 command (no prefix) for this gradient\n         * @param {CssMode} [mode=linear] - 'linear' or 'radial'\n         * @param {String} [direction] - default is 'to right' or 'ellipse at center'\n         * @return {String}\n         */\n        css(mode?: CssMode, direction?: string): string;\n\n        /**\n         * Returns the color at specific position with RGBa interpolation\n         * @param {float} pos, between 0 and 1\n         * @return {tinycolor.Instance}\n         */\n        rgbAt(pos: number): tinycolor.Instance;\n\n        /**\n         * Returns the color at specific position with HSVa interpolation\n         * @param {float} pos, between 0 and 1\n         * @return {tinycolor.Instance}\n         */\n        hsvAt(pos: number): tinycolor.Instance;\n\n    }\n\n    interface Constructor {\n        /**\n         * @class tinygradient\n         * @param {StopInput} stops\n         */\n        new (stops: StopInput[]): Instance;\n        new (...stops: StopInput[]): Instance;\n        (stops: StopInput[]): Instance;\n        (...stops: StopInput[]): Instance;\n\n        /**\n         * @class tinygradient\n         * @param {tinycolor.ColorInput[]} stops\n         */\n        new (stops: tinycolor.ColorInput[]): Instance;\n        new (...stops: tinycolor.ColorInput[]): Instance;\n        (stops: tinycolor.ColorInput[]): Instance;\n        (...stops: tinycolor.ColorInput[]): Instance;\n    }\n}\n\ndeclare const tinygradient: tinygradient.Constructor;\nexport default tinygradient;\nexport { tinygradient };\n"
  }
]