Refactored addColor.js

This commit is contained in:
Leamsi Escribano 2021-07-04 13:55:49 -04:00
parent d35e768ce8
commit 4d4878c4fa
12 changed files with 218 additions and 277 deletions

207
js/ColorModule.js Normal file
View File

@ -0,0 +1,207 @@
/** Adds the given color to the palette
*
* @param {*} newColor the colour to add
* @return the list item containing the added colour
*/
const ColorModule = (() => {
const currentPalette = [];
const coloursList = document.getElementById("palette-list");
console.info("Initialized Color Module..");
document.getElementById('jscolor-hex-input').addEventListener('change',colorChanged, false);
document.getElementById('jscolor-hex-input').addEventListener('input', colorChanged, false);
document.getElementById('add-color-button').addEventListener('click', addColorButtonEvent, false);
new Sortable(document.getElementById("colors-menu"), {
animation:100,
filter: ".noshrink",
draggable: ".draggable-colour",
onEnd: makeIsDraggingFalse
});
// Changes all of one color to another after being changed from color picker
function colorChanged(colorHexElement) {
// Get old and new colors from the element
const hexElement = colorHexElement.target;
const hexElementValue = hexElement.value;
const newColor = hexToRgb(hexElementValue);
const oldColor = hexElement.oldColor;
//if the color is not a valid hex color, exit this function and do nothing
const newColorHex = hexElementValue.toLowerCase();
if (/^[0-9a-f]{6}$/i.test(newColorHex) == false) return
currentPalette.splice(currentPalette.indexOf("#" + newColor), 1);
newColor.a = 255;
//save undo state
new HistoryStateEditColor(hexElementValue.toLowerCase(), rgbToHex(oldColor));
//get the currently selected color
const currentlyEditedColor = document.getElementsByClassName('jscolor-active')[0];
const duplicateColorWarning = document.getElementById('duplicate-color-warning');
//check if selected color already matches another color
colors = document.getElementsByClassName('color-button');
//loop through all colors in palette
for (var i = 0; i < colors.length; i++) {
//if generated color matches this color
if (newColorHex == colors[i].jscolor.toString()) {
//if the color isnt the one that has the picker currently open
if (!colors[i].parentElement.classList.contains('jscolor-active')) {
//console.log('%cColor is duplicate', colorCheckingStyle);
//show the duplicate color warning
duplicateColorWarning.style.visibility = 'visible';
//shake warning icon
duplicateColorWarning.classList.remove('shake');
void duplicateColorWarning.offsetWidth;
duplicateColorWarning.classList.add('shake');
//exit function without updating color
return;
}
}
}
//if the color being edited has a duplicate color warning, remove it
duplicateColorWarning.style.visibility = 'hidden';
currentlyEditedColor.firstChild.jscolor.fromString(newColorHex);
replaceAllOfColor(oldColor, newColor);
//set new old color to changed color
hexElement.oldColor = newColor;
currentPalette.push('#' + newColorHex);
//if this is the current color, update the drawing color
if (hexElement.colorElement.parentElement.classList.contains('selected')) {
for (let i=1; i<layers.length - nAppLayers; i++) {
layers[i].context.fillStyle = '#'+ rgbToHex(newColor.r,newColor.g,newColor.b);
}
currentGlobalColor = newColor;
}
}
function addColorButtonEvent() {
//generate random color
const hue = Math.floor(Math.random()*255);
const sat = 130+Math.floor(Math.random()*100);
const lit = 70+Math.floor(Math.random()*100);
const newColorRgb = hslToRgb(hue,sat,lit);
const newColor = rgbToHex(newColorRgb.r,newColorRgb.g,newColorRgb.b);
//remove current color selection
document.querySelector('#colors-menu li.selected').classList.remove('selected');
//add new color and make it selected
var addedColor = addColor(newColor);
addedColor.classList.add('selected');
currentLayer.context.fillStyle = '#' + newColor;
//add history state
//saveHistoryState({type: 'addcolor', colorValue: addedColor.firstElementChild.jscolor.toString()});
new HistoryStateAddColor(addedColor.firstElementChild.jscolor.toString());
//show color picker
addedColor.firstElementChild.jscolor.show();
console.log('showing picker');
//hide edit button
addedColor.lastChild.classList.add('hidden');
}
function AddToSimplePalette() {
const simplePalette = document.getElementById("colors-menu");
const childCount = simplePalette.childElementCount;
// Removing all the colours
for (let i=0; i<childCount-1; i++) {
simplePalette.removeChild(simplePalette.children[0]);
}
// Adding the new ones
for (let i=0; i<coloursList.childElementCount; i++) {
const col = coloursList.children[i].style.backgroundColor;
if (col.includes("rgb")) {
addColor(cssToHex(col));
}
else {
addColor(col);
}
}
}
//formats a color button
function initColor (colorElement) {
//add jscolor picker for this color
colorElement.jscolor = new jscolor(colorElement.parentElement, {
valueElement: null,
styleElement: colorElement,
width:151,
position: 'left',
padding:0,
borderWidth:14,
borderColor: '#332f35',
backgroundColor: '#332f35',
insetColor: 'transparent',
value: colorElement.style.backgroundColor,
deleteButton: true,
});
}
function addColor (newColor) {
//add # at beginning if not present
if (newColor.charAt(0) != '#')
newColor = '#' + newColor;
currentPalette.push(newColor);
//create list item
var listItem = document.createElement('li');
//create button
var button = document.createElement('button');
button.classList.add('color-button');
button.style.backgroundColor = newColor;
button.addEventListener('mouseup', clickedColor);
listItem.appendChild(button);
listItem.classList.add("draggable-colour")
//insert new listItem element at the end of the colors menu (right before add button)
colorsMenu.insertBefore(listItem, colorsMenu.children[colorsMenu.children.length-1]);
//add jscolor functionality
initColor(button);
//add edit button
var editButtonTemplate = document.getElementsByClassName('color-edit-button')[0];
newEditButton = editButtonTemplate.cloneNode(true);
listItem.appendChild(newEditButton);
//when you click the edit button
on('click', newEditButton, function (event, button) {
//hide edit button
button.parentElement.lastChild.classList.add('hidden');
//show jscolor picker, if basic mode is enabled
if (pixelEditorMode == 'Basic')
button.parentElement.firstChild.jscolor.show();
else
showDialogue("palette-block", false);
});
return listItem;
}
return {
currentPalette,
addColor,
AddToSimplePalette
}
})();

View File

@ -1,56 +0,0 @@
let currentPalette = [];
/** Adds the given color to the palette
*
* @param {*} newColor the colour to add
* @return the list item containing the added colour
*/
function addColor (newColor) {
//add # at beginning if not present
if (newColor.charAt(0) != '#')
newColor = '#' + newColor;
currentPalette.push(newColor);
//create list item
var listItem = document.createElement('li');
//create button
var button = document.createElement('button');
button.classList.add('color-button');
button.style.backgroundColor = newColor;
button.addEventListener('mouseup', clickedColor);
listItem.appendChild(button);
listItem.classList.add("draggable-colour")
//insert new listItem element at the end of the colors menu (right before add button)
colorsMenu.insertBefore(listItem, colorsMenu.children[colorsMenu.children.length-1]);
//add jscolor functionality
initColor(button);
//add edit button
var editButtonTemplate = document.getElementsByClassName('color-edit-button')[0];
newEditButton = editButtonTemplate.cloneNode(true);
listItem.appendChild(newEditButton);
//when you click the edit button
on('click', newEditButton, function (event, button) {
//hide edit button
button.parentElement.lastChild.classList.add('hidden');
//show jscolor picker, if basic mode is enabled
if (pixelEditorMode == 'Basic')
button.parentElement.firstChild.jscolor.show();
else
showDialogue("palette-block", false);
});
return listItem;
}
new Sortable(document.getElementById("colors-menu"), {
animation:100,
filter: ".noshrink",
draggable: ".draggable-colour",
onEnd: makeIsDraggingFalse
});

View File

@ -1,59 +0,0 @@
// add-color-button management
on('click', 'add-color-button', function(){
if (!documentCreated) return;
var colorCheckingStyle = `
color: white;
background: #3c4cc2;
`;
var colorIsUnique = true;
do {
//console.log('%cchecking for unique colors', colorCheckingStyle)
//generate random color
var hue = Math.floor(Math.random()*255);
var sat = 130+Math.floor(Math.random()*100);
var lit = 70+Math.floor(Math.random()*100);
var newColorRgb = hslToRgb(hue,sat,lit);
var newColor = rgbToHex(newColorRgb.r,newColorRgb.g,newColorRgb.b);
var newColorHex = newColor;
//check if color has been used before
colors = document.getElementsByClassName('color-button');
colorCheckingLoop: for (var i = 0; i < colors.length; i++) {
//console.log('%c'+newColorHex +' '+ colors[i].jscolor.toString(), colorCheckingStyle)
//if generated color matches this color
if (newColorHex == colors[i].jscolor.toString()) {
//console.log('%ccolor already exists', colorCheckingStyle)
//start loop again
colorIsUnique = false;
//exit
break colorCheckingLoop;
}
}
}
while (colorIsUnique == false);
//remove current color selection
document.querySelector('#colors-menu li.selected').classList.remove('selected');
//add new color and make it selected
var addedColor = addColor(newColor);
addedColor.classList.add('selected');
currentLayer.context.fillStyle = '#' + newColor;
//add history state
//saveHistoryState({type: 'addcolor', colorValue: addedColor.firstElementChild.jscolor.toString()});
new HistoryStateAddColor(addedColor.firstElementChild.jscolor.toString());
//show color picker
addedColor.firstElementChild.jscolor.show();
console.log('showing picker');
//hide edit button
addedColor.lastChild.classList.add('hidden');
}, false);

View File

@ -1,101 +0,0 @@
document.getElementById('jscolor-hex-input').addEventListener('change', colorChanged, false);
on('input', 'jscolor-hex-input', function (e) {
//get hex value
var newColorHex = e.target.value.toLowerCase();
//if the color is not (yet) a valid hex color, exit this function and do nothing
if (/^[0-9a-f]{6}$/i.test(newColorHex) == false)
return;
//get currently editing color
var currentlyEditedColor = document.getElementsByClassName('jscolor-active')[0];
//update the actual color picker to the inputted color
currentlyEditedColor.firstChild.jscolor.fromString(newColorHex);
colorChanged(e);
});
//changes all of one color to another after being changed from color picker
function colorChanged(e) {
//console.log('colorChanged() to ' + e.target.value);
//get colors
var newColor = hexToRgb(e.target.value);
var oldColor = e.target.oldColor;
currentPalette.splice(currentPalette.indexOf("#" + newColor), 1);
newColor.a = 255;
//save undo state
new HistoryStateEditColor(e.target.value.toLowerCase(), rgbToHex(oldColor));
//get the currently selected color
var currentlyEditedColor = document.getElementsByClassName('jscolor-active')[0];
var duplicateColorWarning = document.getElementById('duplicate-color-warning');
//check if selected color already matches another color
colors = document.getElementsByClassName('color-button');
//console.log(colors);
var colorCheckingStyle = 'background: #bc60c4; color: white';
var newColorHex = e.target.value.toLowerCase();
//if the color is not a valid hex color, exit this function and do nothing
if (/^[0-9a-f]{6}$/i.test(newColorHex) == false)
return;
//loop through all colors in palette
for (var i = 0; i < colors.length; i++) {
//if generated color matches this color
if (newColorHex == colors[i].jscolor.toString()) {
//console.log('%ccolor already exists'+(colors[i].parentElement.classList.contains('jscolor-active')?' (but is the current color)':''), colorCheckingStyle);
//if the color isnt the one that has the picker currently open
if (!colors[i].parentElement.classList.contains('jscolor-active')) {
//console.log('%cColor is duplicate', colorCheckingStyle);
//show the duplicate color warning
duplicateColorWarning.style.visibility = 'visible';
//shake warning icon
duplicateColorWarning.classList.remove('shake');
void duplicateColorWarning.offsetWidth;
duplicateColorWarning.classList.add('shake');
//exit function without updating color
return;
}
}
}
//if the color being edited has a duplicate color warning, remove it
duplicateColorWarning.style.visibility = 'hidden';
currentlyEditedColor.firstChild.jscolor.fromString(newColorHex);
replaceAllOfColor(oldColor, newColor);
//set new old color to changed color
e.target.oldColor = newColor;
currentPalette.push('#' + newColorHex);
//if this is the current color, update the drawing color
if (e.target.colorElement.parentElement.classList.contains('selected')) {
for (let i=1; i<layers.length - nAppLayers; i++) {
layers[i].context.fillStyle = '#'+ rgbToHex(newColor.r,newColor.g,newColor.b);
}
currentGlobalColor = newColor;
}
/* this is wrong and bad
if (settings.switchToChangedColor) {
}*/
}

View File

@ -20,7 +20,7 @@ function createColorPalette(paletteColors, deletePreviousPalette = true) {
// Adding all the colours in the array
for (var i = 0; i < paletteColors.length; i++) {
var newColor = paletteColors[i];
var newColorElement = addColor(newColor);
var newColorElement = ColorModule.addColor(newColor);
var newColorHex = hexToRgb(newColor);

View File

@ -43,7 +43,7 @@ function closeDialogue () {
dialogueOpen = false;
if (currentOpenDialogue == "palette-block") {
pbAddToSimplePalette();
ColorModule.AddToSimplePalette();
}
}

View File

@ -147,7 +147,7 @@ for (var i = 1; i < mainMenuItems.length; i++) {
//Palette Menu
case 'Add color':
addColor('#eeeeee');
ColorModule.addColor('#eeeeee');
break;
// SELECTION MENU
case 'Paste':
@ -207,8 +207,8 @@ function getProjectData() {
// save editor mode
dictionary['editorMode'] = pixelEditorMode;
// save palette
for (let i=0; i<currentPalette.length; i++) {
dictionary["color" + i] = currentPalette[i];
for (let i=0; i<ColorModule.currentPalette.length; i++) {
dictionary["color" + i] = ColorModule.currentPalette[i];
}
// save number of layers

View File

@ -383,7 +383,7 @@ function HistoryStateAddColor (colorValue) {
};
this.redo = function () {
addColor(this.colorValue);
ColorModule.addColor(this.colorValue);
undoStates.push(this);
};
@ -400,7 +400,7 @@ function HistoryStateDeleteColor (colorValue) {
var currentCanvas = currentLayer.context.getImageData(0, 0, canvasSize[0], canvasSize[1]);
currentLayer.context.putImageData(this.canvas, 0, 0);
addColor(this.colorValue);
ColorModule.addColor(this.colorValue);
this.canvas = currentCanvas;
redoStates.push(this);

View File

@ -1,25 +0,0 @@
// NEXTPULL: to remove when the new palette system is added
//formats a color button
function initColor (colorElement) {
//console.log('initColor()');
//console.log(document.getElementById('jscolor-hex-input'))
//add jscolor picker for this color
colorElement.jscolor = new jscolor(colorElement.parentElement, {
valueElement: null, //if you dont set this to null, it turns the button (colorElement) into text, we set it when you open the picker
styleElement: colorElement,
width:151,
position: 'left',
padding:0,
borderWidth:14,
borderColor: '#332f35',
backgroundColor: '#332f35',
insetColor: 'transparent',
value: colorElement.style.backgroundColor,
deleteButton: true,
});
}

View File

@ -12,7 +12,7 @@ function newPixel (width, height, editorMode, fileContent = null) {
pixelEditorMode = editorMode;
// The palette is empty, at the beginning
currentPalette = [];
ColorModule.currentPalette.length = 0;
// If this is the first pixel I'm creating since the app has started
if (firstPixel) {
@ -125,8 +125,8 @@ function newPixel (width, height, editorMode, fileContent = null) {
var defaultBackgroundColor = rgbToHex(bg.r,bg.g,bg.b);
//add colors to palette
addColor(defaultForegroundColor).classList.add('selected');
addColor(defaultBackgroundColor);
ColorModule.addColor(defaultForegroundColor).classList.add('selected');
ColorModule.addColor(defaultBackgroundColor);
//set current drawing color as foreground color
currentLayer.context.fillStyle = '#'+defaultForegroundColor;

View File

@ -308,26 +308,4 @@ function cssToHex(rgb) {
return ("0" + parseInt(x).toString(16)).slice(-2);
}
return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
function pbAddToSimplePalette() {
let simplePalette = document.getElementById("colors-menu");
let childCount = simplePalette.childElementCount;
// Removing all the colours
for (let i=0; i<childCount-1; i++) {
simplePalette.removeChild(simplePalette.children[0]);
}
// Adding the new ones
for (let i=0; i<coloursList.childElementCount; i++) {
let col = coloursList.children[i].style.backgroundColor;
if (col.includes("rgb")) {
addColor(cssToHex(col));
}
else {
addColor(col);
}
}
}

View File

@ -32,9 +32,7 @@
//=include _newPixel.js
//=include _createColorPalette.js
//=include _changeZoom.js
//=include _addColor.js
//=include _colorChanged.js
//=include _initColor.js
//=include ColorModule.js
//=include _dialogue.js
//=include _featuresLog.js
//=include _drawLine.js
@ -65,7 +63,6 @@
/**buttons**/
//=include _toolButtons.js
//=include _addColorButton.js
//=include _clickedColor.js
//=include _fileMenu.js
//=include _createButton.js