# Color Adjuster

[![styled with prettier](https://img.shields.io/badge/styled_with-prettier-ff69b4.svg)](https://github.com/prettier/prettier)
[![Greenkeeper badge](https://badges.greenkeeper.io/alexjoverm/typescript-library-starter.svg)](https://greenkeeper.io/)
[![Travis](https://img.shields.io/travis/alexjoverm/typescript-library-starter.svg)](https://travis-ci.org/alexjoverm/typescript-library-starter)
[![Coveralls](https://img.shields.io/coveralls/alexjoverm/typescript-library-starter.svg)](https://coveralls.io/github/alexjoverm/typescript-library-starter)
[![Donate](https://img.shields.io/badge/donate-paypal-blue.svg)]()

A web color adjuster.

### Features

 - **[TypeScript](https://www.typescriptlang.org/)** is a language for application-scale JavaScript.
 - Zero-setup. After running `npm install` things will setup for you.
 - **[RollupJS](https://rollupjs.org/)** for multiple optimized bundles following the [standard convention](http://2ality.com/2017/04/setting-up-multi-platform-packages.html) and [Tree-shaking](https://alexjoverm.github.io/2017/03/06/Tree-shaking-with-Webpack-2-TypeScript-and-Babel/)
 - Tests, coverage and interactive watch mode using **[Jest](http://facebook.github.io/jest/)**
 - **[Prettier](https://github.com/prettier/prettier)** and **[TSLint](https://palantir.github.io/tslint/)** for code formatting and consistency
 - **Docs automatic generation and deployment** to `gh-pages`, using **[TypeDoc](http://typedoc.org/)**
 - Automatic types `(*.d.ts)` file generation
 - **[Travis](https://travis-ci.org)** integration and **[Coveralls](https://coveralls.io/)** report
 - (Optional) **Automatic releases and changelog**, using [Semantic release](https://github.com/semantic-release/semantic-release), [Commitizen](https://github.com/commitizen/cz-cli), [Conventional changelog](https://github.com/conventional-changelog/conventional-changelog) and [Husky](https://github.com/typicode/husky) (for the git hooks)

### Quick start

html code
```
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <link rel="stylesheet" type="text/css" href="../dist/css/color-adjuster.css">
</head>
<body>
  <select id="colorMapSelector" style="position: absolute; left: 10px; top: 0px; width: 150px; height: 25px;"></select>
  <select id="alphaMapSelector" style="position: absolute; left: 10px; top: 30px; width: 150px; height: 25px;"></select>
  <button id="rgbCtrlButton" style="position: absolute; left: 10px; top: 60px; width: 150px; height: 25px;">添加rgb控制</button>
  <button id="alphaCtrlButton" style="position: absolute; left: 10px; top: 90px; width: 150px; height: 25px;">添加alpha控制</button>
  <button id="genButton" style="position: absolute; left: 10px; top: 120px; width: 150px; height: 25px;">生成序列</button>
  <button id="genColorMapButton" style="position: absolute; left: 10px; top: 150px; width: 150px; height: 25px;">生成颜色表</button>
  
  <div id="colorContainer"></div>
  <div id="colorMapContainer"></div>
  <script type="module" src="js/main.js"></script>
</body>
</html>
```

main.js code

You can import the generated bundle to use the whole library generated by this starter:

```
import {ColorMapAdjuster, ColorMapComponent} from "color-adjuster.module.js"
```
or
```html
<script src="color-adjuster.js"></script>
```
then
```
import {ColorMapAdjuster, ColorMapComponent} from "../../../dist/color-adjuster.module.js"
import "../../../node_modules/jquery/dist/jquery.js";

let colorMapSelector; // 颜色表选择器
let alphaMapSelector; // 透明度选择器

let colorContainer = document.getElementById("colorContainer"); // rgba编辑器容器
let colorContainerWidth = 600;
let colorContainerHeight = 260;
colorContainer.style.width = colorContainerWidth.toString() + "px";
colorContainer.style.height = colorContainerHeight.toString() + "px";
colorContainer.style.left = "300px";
colorContainer.style.top = "200px";
colorContainer.style.position = "absolute";


// rgbaMap编辑器
let colorMapType = "rgba"; // "rgb" or "rgba"
let colorMapAdjuster = new ColorMapAdjuster({
    container: colorContainer, // rgba编辑器容器
    width: colorContainerWidth, // 容器宽度
    height: colorContainerHeight, // 容器高度
    padding: { // 容器内边距
        top: 5,
        left: 5,
        right: 5,
        bottom: 5
    },
    edge: 10, // 控制点大小
    strokeWidth: 2, // 控制点边距
    type: colorMapType  // "rgb" or "rgba"
});

// rgbMap编辑器
// colorContainerWidth = 600;
// colorContainerHeight = 160;
// colorContainer.style.width = colorContainerWidth.toString() + "px";
// colorContainer.style.height = colorContainerHeight.toString() + "px";
// let colorMapType = "rgb"; // "rgb" or "rgba"
// let colorMapAdjuster = new ColorMapAdjuster({
//     container: colorContainer, // rgba编辑器容器
//     width: colorContainerWidth, // 容器宽度
//     height: colorContainerHeight, // 容器高度
//     padding: { // 容器内边距
//         top: 5,
//         left: 5,
//         right: 5,
//         bottom: 5
//     },
//     edge: 10, // 控制点大小
//     strokeWidth: 2, // 控制点边距
//     type: colorMapType  // "rgb" or "rgba"
// });


let colorMapContainer = document.getElementById("colorMapContainer"); // rgba编辑器容器
let colorMapContainerWidth = 400;
let colorMapContainerHeight = 50;
colorMapContainer.style.width = colorMapContainerWidth.toString() + "px";
colorMapContainer.style.height = colorMapContainerHeight.toString() + "px";
colorMapContainer.style.left = "400px";
colorMapContainer.style.top = "600px";
colorMapContainer.style.position = "absolute";
let colorMapComponent = new ColorMapComponent({
    colorMapAdjuster: colorMapAdjuster,
    container: colorMapContainer
});

/**
 * 初始化颜色选择器
 * @param colorMapSelector
 */
function initColorMapSelector(colorMapSelector) {
    // colorMap数组
    let colorCategories = ["jet", "hsv"];
    // 组装颜色表选择器下拉列表
    colorMapSelector = document.getElementById("colorMapSelector");
    for (let i = 0; i < colorCategories.length; i++) {
        let c = colorCategories[i];
        colorMapSelector.options.add(new Option(c, c));
    }
    // 绑定颜色表选择器更改事件
    $("#colorMapSelector").change(function () {
        colorMapSelectorChange($("#colorMapSelector").val());
        alphaMapSelectorChange($("#alphaMapSelector").val());
    });
}

/**
 * 初始化透明度选择器
 * @param alphaMapSelector
 */
function initAlphaMapSelector(alphaMapSelector) {
    // 透明度数组
    let alphaCategories = [
        "Opaque",
        "MiddleBasinS7"
    ]
    // 组装透明度选择器下拉列表
    alphaMapSelector = document.getElementById("alphaMapSelector");
    for (let i = 0; i < alphaCategories.length; i++) {
        let c = alphaCategories[i];
        alphaMapSelector.options.add(new Option(c, c));
    }
    // 绑定透明度选择器更改事件
    $("#alphaMapSelector").change(function () {
        colorMapSelectorChange($("#colorMapSelector").val());
        alphaMapSelectorChange($("#alphaMapSelector").val());
    });
}

/**
 * 初始化控制按钮
 */
function initCtrlButton() {
    $("#rgbCtrlButton").click(function () {
        colorMapAdjuster.colorMapAdjuster.rgbEditor.insertCtrlComponent(null);
    });
    $("#alphaCtrlButton").click(function () {
        if(colorMapType === "rgba") {
            colorMapAdjuster.colorMapAdjuster.alphaEditor.insertAlphaCtrlComponent(null);
        }
    });
    $("#genButton").click(function () {
        let rgbaMapList = colorMapAdjuster.colorMapAdjuster.genColorMapList();
        console.info(rgbaMapList);
    });
    $("#genColorMapButton").click(function () {
        colorMapComponent.updateColorMapCanvas();
    });

}

/**
 * 透明通道对应的nodes
 * @param opt
 * @returns {*[]}
 */
function loadPresetTrendAlphaMap(opt) {
    let nodes = [];
    switch (opt) {
        case "Opaque":
            nodes.push([0, 1.]); // 表示无参考线，值全为1
            nodes.push([1, 1.]);
            break;
        case "MiddleBasinS7":
            nodes.push([0, 1.]);
            nodes.push([2. / 7., 1.]);
            nodes.push([3. / 7., 0]);
            nodes.push([4. / 7., 0]);
            nodes.push([5. / 7., 1.]);
            nodes.push([1., 1.]);
            break;
    }
    return nodes;
}

/**
 * 颜色表选择器更改事件
 * @param colorMapSelectorOpt
 */
function colorMapSelectorChange(colorMapSelectorOpt){
  let colorMapArr = {
    "jet": ['#000083', '#0277c4', '#1effe5', '#e6ff1a', '#fc4c00', '#800000'],
    "hsv": ['#ff0000', '#ceff02', '#00fb62', '#026bfe', '#c400fb', '#ff0006']
  }
    // 颜色表
    let colorMapArrTemp = colorMapArr[colorMapSelectorOpt];
    let customColorMapTemp = [];
    let step = 1 / (colorMapArrTemp.length - 1);
    for (let i = 0; i < colorMapArrTemp.length; i++) {
        customColorMapTemp.push({
            x: i * step,
            color: colorMapArrTemp[i]
        });
    }
    colorMapAdjuster.colorMapAdjuster.rgbEditor.updateRgbCtrlEditor(customColorMapTemp);
    if(colorMapType === "rgba") {
        colorMapAdjuster.colorMapAdjuster.rgbaMapEditor.updateRgbaMapCanvas();
    } else if(colorMapType === "rgb") {
        colorMapAdjuster.colorMapAdjuster.rgbMapEditor.updateRgbMapCanvas();
    }

}


/**
 * 透明度表选择器更改事件
 * @param alphaMapSelectorOpt
 */
function alphaMapSelectorChange(alphaMapSelectorOpt) {
    let alphaMapArrTemp = loadPresetTrendAlphaMap(alphaMapSelectorOpt);
    let customAlphaMapTemp = [];
    for (let i = 0; i < alphaMapArrTemp.length; i++) {
        let fixedFlag = false;
        if(i === 0 || i === alphaMapArrTemp.length -1) {
            fixedFlag = true;
        }
        customAlphaMapTemp.push({
            x: alphaMapArrTemp[i][0],
            y: alphaMapArrTemp[i][1],
            index: i,
            fixedX: fixedFlag
        });
    }

    if(colorMapType === "rgba") {
        colorMapAdjuster.colorMapAdjuster.alphaEditor.updateAlphaCtrlEditor(customAlphaMapTemp);
        colorMapAdjuster.colorMapAdjuster.rgbaMapEditor.updateRgbaMapCanvas();
    } else if(colorMapType === "rgb") {
        colorMapAdjuster.colorMapAdjuster.rgbMapEditor.updateRgbMapCanvas();
    }

}

/**
 * 初始化
 */
function init(){
    // 初始化颜色选择器
    initColorMapSelector(colorMapSelector);
    // 初始化透明度选择器
    initAlphaMapSelector(alphaMapSelector);
    // 初始化控制按钮
    initCtrlButton();
}

init();

```

### NPM scripts

 - `npm start`: Run `npm run build` in watch mode
 - `npm test`: Run test suite
 - `npm run test:watch`: Run test suite in [interactive watch mode](http://facebook.github.io/jest/docs/cli.html#watch)
 - `npm run test:prod`: Run linting and generate coverage
 - `npm run build`: Generate bundles and typings, create docs
 - `npm run lint`: Lints code
 - `npm run commit`: Commit using conventional commit style ([husky](https://github.com/typicode/husky) will tell you to use it if you haven't :wink:)

### Excluding peerDependencies

On library development, one might want to set some peer dependencies, and thus remove those from the final bundle. You can see in [Rollup docs](https://rollupjs.org/#peer-dependencies) how to do that.

Good news: the setup is here for you, you must only include the dependency name in `external` property within `rollup.config.js`. For example, if you want to exclude `lodash`, just write there `external: ['lodash']`.

### Automatic releases

_**Prerequisites**: you need to create/login accounts and add your project to:_
 - [npm](https://www.npmjs.com/)
 - [Travis CI](https://travis-ci.org)
 - [Coveralls](https://coveralls.io)

_**Prerequisite for Windows**: Semantic-release uses
**[node-gyp](https://github.com/nodejs/node-gyp)** so you will need to
install
[Microsoft's windows-build-tools](https://github.com/felixrieseberg/windows-build-tools)
using this command:_

```bash
npm install --global --production windows-build-tools
```

#### Setup steps

Follow the console instructions to install semantic release and run it (answer NO to "Do you want a `.travis.yml` file with semantic-release setup?").

_Note: make sure you've setup `repository.url` in your `package.json` file_

```bash
npm install -g semantic-release-cli
semantic-release-cli setup
# IMPORTANT!! Answer NO to "Do you want a `.travis.yml` file with semantic-release setup?" question. It is already prepared for you :P
```

From now on, you'll need to use `npm run commit`, which is a convenient way to create conventional commits.

Automatic releases are possible thanks to [semantic release](https://github.com/semantic-release/semantic-release), which publishes your code automatically on [github](https://github.com/) and [npm](https://www.npmjs.com/), plus generates automatically a changelog. This setup is highly influenced by [Kent C. Dodds course on egghead.io](https://egghead.io/courses/how-to-write-an-open-source-javascript-library)

### Git Hooks

There is already set a `precommit` hook for formatting your code with Prettier :nail_care:

By default, there are two disabled git hooks. They're set up when you run the `npm run semantic-release-prepare` script. They make sure:
 - You follow a [conventional commit message](https://github.com/conventional-changelog/conventional-changelog)
 - Your build is not going to fail in [Travis](https://travis-ci.org) (or your CI server), since it's runned locally before `git push`

This makes more sense in combination with [automatic releases](#automatic-releases)

### FAQ

#### `Array.prototype.from`, `Promise`, `Map`... is undefined?

TypeScript or Babel only provides down-emits on syntactical features (`class`, `let`, `async/await`...), but not on functional features (`Array.prototype.find`, `Set`, `Promise`...), . For that, you need Polyfills, such as [`core-js`](https://github.com/zloirock/core-js) or [`babel-polyfill`](https://babeljs.io/docs/usage/polyfill/) (which extends `core-js`).

For a library, `core-js` plays very nicely, since you can import just the polyfills you need:

```javascript
import "core-js/fn/array/find"
import "core-js/fn/string/includes"
import "core-js/fn/promise"
...
```

#### What is `npm install` doing on first run?

It runs the script `tools/init` which sets up everything for you. In short, it:
 - Configures RollupJS for the build, which creates the bundles
 - Configures `package.json` (typings file, main file, etc)
 - Renames main src and test files

#### What if I don't want git-hooks, automatic releases or semantic-release??

Then you may want to:
 - Remove `commitmsg`, `postinstall` scripts from `package.json`. That will not use those git hooks to make sure you make a conventional commit
 - Remove `npm run semantic-release` from `.travis.yml`

#### What if I don't want to use coveralls or report my coverage?

Remove `npm run report-coverage` from `.travis.yml`

## Credits

Made with by [@rambo](https://gitee.com/xygg) and all these wonderful contributors ([emoji key](https://github.com/kentcdodds/all-contributors#emoji-key)):

<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore -->

[<img src="https://avatars.githubusercontent.com/u/7553206?s=400&u=5448cb379bde871163f2057612339e087be3572c&v=4" width="100px;"/><br /><sub><b>Rambo</b></sub>](https://github.com/Rambo2015)<br />[💻]("Code") [🔧]("Tools")[📖]( Documentation") 

This project follows the [all-contributors](https://github.com/kentcdodds/all-contributors) specification. Contributions of any kind are welcome!
