gradient-generator-ui
Version:
Library to create a gradient generator in vanilla-js with interactive user interface in html
74 lines • 2.81 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GeneratorManager = void 0;
const ColorUtils_1 = require("../ColorUtils");
class GeneratorManager {
constructor({ generator, keepChanges = true }) {
this.addMode = false;
this.cacheGradientColors = [];
if (!generator)
throw new Error('A Gradient Generator must be provided');
this.generator = generator;
this.keepChanges = keepChanges;
const mainElement = this.generator.getMainElement();
this.cacheGradientColors = this.generator.getGradientColors();
// Event to add new element
mainElement.addEventListener('click', (ev) => {
if (this.addMode) {
const gradientColors = [
{ colorHex: '#000000', position: 0 },
...this.generator.getGradientColors(),
{ colorHex: '#ffffff', position: 100 },
];
const newPosition = (ev.offsetX * 100) / mainElement.clientWidth;
const indx = gradientColors.findIndex(gc => gc.position > newPosition);
const color1 = gradientColors[indx - 1].colorHex;
const color2 = gradientColors[indx].colorHex;
generator.addColors({
colorHex: ColorUtils_1.getIntermediateColor(color1, color2),
position: newPosition,
});
this.cancelAddMode();
if (this.keepChanges) {
this.cacheGradientColors = this.generator.getGradientColors();
}
}
});
}
/**
* Activates the mode of adding new colors on click over the gradient generator main element
*/
activateAddMode() {
this.addMode = true;
const mainElement = this.generator.getMainElement();
mainElement.classList.add('gg-add');
}
/**
* Cancel the mode of adding new colors on the main element of the generator
*/
cancelAddMode() {
this.addMode = false;
const mainElement = this.generator.getMainElement();
mainElement.classList.remove('gg-add');
}
/**
* Save the changes and new colors when keepChanges option is false
*/
saveColors() {
this.cancelAddMode();
if (!this.keepChanges) {
this.cacheGradientColors = this.generator.getGradientColors();
}
}
/**
* Delete changes and new colors when keep changes option is false
*/
restoreColors() {
this.cancelAddMode();
if (!this.keepChanges) {
this.generator.setGradientColors(this.cacheGradientColors);
}
}
}
exports.GeneratorManager = GeneratorManager;
//# sourceMappingURL=Manager.js.map