Added FileManager and TopMenuModule

The TopMenuModule binds the buttons so that they open the sub menus: at the moment it also binds those events that don't have a proper place yet. FileManager contains all the functions that have something to do with files, that is loading, opening, saving and exporting.
This commit is contained in:
unsettledgames 2021-07-15 22:21:19 +02:00
parent 9540002c6e
commit f76d05bffa
10 changed files with 303 additions and 299 deletions

197
js/FileManager.js Normal file
View File

@ -0,0 +1,197 @@
const FileManager = (() => {
// Binding the browse holder change event to file loading
const browseHolder = document.getElementById('open-image-browse-holder');
Input.on('change', browseHolder, loadFile);
function saveProject() {
//create name
let fileName;
let selectedPalette = Util.getText('palette-button');
if (selectedPalette != 'Choose a palette...'){
let paletteAbbreviation = palettes[selectedPalette].abbreviation;
fileName = 'pixel-'+paletteAbbreviation+'-'+canvasSize[0]+'x'+canvasSize[1]+'.lpe';
} else {
fileName = 'pixel-'+canvasSize[0]+'x'+canvasSize[1]+'.lpe';
selectedPalette = 'none';
}
//set download link
const linkHolder = document.getElementById('save-project-link-holder');
// create file content
const content = getProjectData();
linkHolder.href = 'data:text/plain;charset=utf-8,' + encodeURIComponent(content);
linkHolder.download = fileName;
linkHolder.click();
if (typeof ga !== 'undefined')
ga('send', 'event', 'Pixel Editor Save', selectedPalette, canvasSize[0]+'/'+canvasSize[1]); /*global ga*/
}
function exportProject() {
if (documentCreated) {
//create name
var selectedPalette = Util.getText('palette-button');
if (selectedPalette != 'Choose a palette...'){
var paletteAbbreviation = palettes[selectedPalette].abbreviation;
var fileName = 'pixel-'+paletteAbbreviation+'-'+canvasSize[0]+'x'+canvasSize[1]+'.png';
} else {
var fileName = 'pixel-'+canvasSize[0]+'x'+canvasSize[1]+'.png';
selectedPalette = 'none';
}
//set download link
var linkHolder = document.getElementById('save-image-link-holder');
// Creating a tmp canvas to flatten everything
var exportCanvas = document.createElement("canvas");
var emptyCanvas = document.createElement("canvas");
var layersCopy = layers.slice();
exportCanvas.width = canvasSize[0];
exportCanvas.height = canvasSize[1];
emptyCanvas.width = canvasSize[0];
emptyCanvas.height = canvasSize[1];
// Sorting the layers by z index
layersCopy.sort((a, b) => (a.canvas.style.zIndex > b.canvas.style.zIndex) ? 1 : -1);
// Merging every layer on the export canvas
for (let i=0; i<layersCopy.length; i++) {
if (layersCopy[i].menuEntry != null && layersCopy[i].isVisible) {
mergeLayers(exportCanvas.getContext('2d'), layersCopy[i].context);
}
// I'm not going to find out why the layer ordering screws up if you don't copy
// a blank canvas when layers[i] is not set as visible, but if you have time to
// spend, feel free to investigate (comment the else, create 3 layers: hide the
// middle one and export, the other 2 will be swapped in their order)
else {
mergeLayers(exportCanvas.getContext('2d'), emptyCanvas.getContext('2d'));
}
}
linkHolder.href = exportCanvas.toDataURL();
linkHolder.download = fileName;
linkHolder.click();
emptyCanvas.remove();
exportCanvas.remove();
//track google event
if (typeof ga !== 'undefined')
ga('send', 'event', 'Pixel Editor Export', selectedPalette, canvasSize[0]+'/'+canvasSize[1]); /*global ga*/
}
}
function open() {
//if a document exists
if (documentCreated) {
//check if the user wants to overwrite
if (confirm('Opening a pixel will discard your current one. Are you sure you want to do that?'))
//open file selection dialog
document.getElementById('open-image-browse-holder').click();
}
else
//open file selection dialog
document.getElementById('open-image-browse-holder').click();
}
function loadFile() {
let fileName = document.getElementById("open-image-browse-holder").value;
// Getting the extension
let extension = (fileName.substring(fileName.lastIndexOf('.')+1, fileName.length) || fileName).toLowerCase();
// I didn't write this check and I have no idea what it does
if (browseHolder.files && browseHolder.files[0]) {
// Btw, checking if the extension is supported
if (extension == 'png' || extension == 'gif' || extension == 'lpe') {
// If it's a Lospec Pixel Editor tm file, I load the project
if (extension == 'lpe') {
openProject();
}
else {
openFile();
}
}
else alert('Only .LPE project files, PNG and GIF files are allowed at this time.');
}
}
function openFile() {
//load file
var fileReader = new FileReader();
fileReader.onload = function(e) {
var img = new Image();
img.onload = function() {
//create a new pixel with the images dimentions
switchMode('Advanced');
Startup.newPixel(this.width, this.height);
//draw the image onto the canvas
currentLayer.context.drawImage(img, 0, 0);
createPaletteFromLayers();
//track google event
if (typeof ga !== 'undefined')
ga('send', 'event', 'Pixel Editor Load', colorPalette.length, this.width+'/'+this.height); /*global ga*/
};
img.src = e.target.result;
};
fileReader.readAsDataURL(browseHolder.files[0]);
}
function openProject() {
let file = browseHolder.files[0];
let reader = new FileReader();
// Getting all the data
reader.readAsText(file, "UTF-8");
// Converting the data to a json object and creating a new pixel (see _newPixel.js for more)
reader.onload = function (e) {
let dictionary = JSON.parse(e.target.result);
let mode = dictionary['editorMode'];
Startup.newPixel(dictionary['canvasWidth'], dictionary['canvasHeight'], dictionary);
}
}
function getProjectData() {
// use a dictionary
let dictionary = {};
// sorting layers by increasing z-index
let layersCopy = layers.slice();
layersCopy.sort((a, b) => (a.canvas.style.zIndex > b.canvas.style.zIndex) ? 1 : -1);
// save canvas size
dictionary['canvasWidth'] = currentLayer.canvasSize[0];
dictionary['canvasHeight'] = currentLayer.canvasSize[1];
// save editor mode
dictionary['editorMode'] = pixelEditorMode;
// save palette
for (let i=0; i<ColorModule.getCurrentPalette().length; i++) {
dictionary["color" + i] = ColorModule.getCurrentPalette()[i];
}
// save number of layers
dictionary["nLayers"] = layersCopy.length;
// save layers
for (let i=0; i<layersCopy.length; i++) {
// Only saving the layers the user has access to (no vfx, tmp or checkerboard layers)
if (layersCopy[i].menuEntry != null) {
dictionary["layer" + i] = layersCopy[i];
dictionary["layer" + i + "ImageData"] = layersCopy[i].canvas.toDataURL();
}
}
return JSON.stringify(dictionary);
}
return {
saveProject,
exportProject,
open
}
})();

View File

@ -11,17 +11,17 @@
* - Each HistoryState must call saveHistoryState(this) so that it gets added to the stack
*
*/
const History = (() => {
const undoLogStyle = 'background: #87ff1c; color: black; padding: 5px;';
let undoStates = [];
let redoStates = [];
Input.on('click', 'undo-button', undo);
Input.on('click', 'redo-button', redo);
//rename to add undo state
function saveHistoryState (state) {
console.log("saved history");
console.log(state);
//get current canvas data and save to undoStates array
undoStates.push(state);

View File

@ -5,12 +5,7 @@ class Input {
element.addEventListener(event,
function (e) {
// e = event
//this = element clicked
functionCallback(e, ...args);
//if you need to access the event or this variable, you need to add them
//when you define the callback, but you cant use the word this, eg:
//on('click', menuButton, function (e, button) {});
functionCallback(...args, e);
});
}

View File

@ -90,8 +90,6 @@ const Startup = (() => {
currentLayer.canvas.style.zIndex = 2;
}
else {
// If it's not the first Pixel, I have to reset the app
// Deleting all the extra layers and canvases, leaving only one
let nLayers = layers.length;
for (let i=2; i < layers.length - nAppLayers; i++) {
@ -198,7 +196,7 @@ const Startup = (() => {
}
}
// OPTIMIZABLE: should probably moved to a FileManagement class or something
// REFACTOR: should probably moved to a FileManagement class or something
function loadLPE(fileContent) {
// I add every layer the file had in it
for (let i=0; i<fileContent['nLayers']; i++) {

97
js/TopMenuModule.js Normal file
View File

@ -0,0 +1,97 @@
const TopMenuModule = (() => {
const mainMenuItems = document.getElementById('main-menu').children;
initMenu();
function initMenu() {
//for each button in main menu (starting at 1 to avoid logo)
for (let i = 1; i < mainMenuItems.length; i++) {
//get the button that's in the list item
const menuItem = mainMenuItems[i];
const menuButton = menuItem.children[0];
//when you click a main menu items button
Input.on('click', menuButton, function (e) {
// Select the item
Util.select(e.target.parentElement);
});
const subMenu = menuItem.children[1];
const subMenuItems = subMenu.children;
//when you click an item within a menu button
for (var j = 0; j < subMenuItems.length; j++) {
const currSubmenuItem = subMenuItems[j];
const currSubmenuButton = currSubmenuItem.children[0];
switch (currSubmenuButton.textContent) {
case 'New':
Input.on('click', currSubmenuButton, Dialogue.showDialogue, 'new-pixel');
break;
case 'Save project':
Input.on('click', currSubmenuButton, FileManager.saveProject);
break;
case 'Open':
Input.on('click', currSubmenuButton, FileManager.open);
break;
case 'Export':
Input.on('click', currSubmenuButton, FileManager.exportProject);
break;
case 'Exit':
//if a document exists, make sure they want to delete it
if (documentCreated) {
//ask user if they want to leave
if (confirm('Exiting will discard your current pixel. Are you sure you want to do that?'))
//skip onbeforeunload prompt
window.onbeforeunload = null;
else
e.preventDefault();
}
break;
// REFACTOR: move the binding to the Selection IIFE or something like that once it's done
case 'Paste':
Input.on('click', currSubmenuButton, pasteSelection);
break;
case 'Copy':
Input.on('click', currSubmenuButton, copySelection);
break;
case 'Cut':
Input.on('click', currSubmenuButton, cutSelectionTool);
break;
case 'Cancel':
Input.on('click', currSubmenuButton, tool.pencil.switchTo);
break;
//Help Menu
case 'Settings':
//fill form with current settings values
//Util.setValue('setting-numberOfHistoryStates', settings.numberOfHistoryStates);
Input.on('click', currSubmenuButton, Dialogue.showDialogue, 'settings');
break;
case 'Help':
Input.on('click', currSubmenuButton, Dialogue.showDialogue, 'help');
break;
case 'About':
Input.on('click', currSubmenuButton, Dialogue.showDialogue, 'about');
break;
case 'Changelog':
Input.on('click', currSubmenuButton, Dialogue.showDialogue, 'changelog');
break;
}
}
}
}
function closeMenu () {
//remove .selected class from all menu buttons
for (var i = 0; i < mainMenuItems.length; i++) {
Util.deselect(mainMenuItems[i]);
}
}
return {
closeMenu
}
})();

View File

@ -1,229 +0,0 @@
var mainMenuItems = document.getElementById('main-menu').children;
//for each button in main menu (starting at 1 to avoid logo)
for (var i = 1; i < mainMenuItems.length; i++) {
//get the button that's in the list item
var menuItem = mainMenuItems[i];
var menuButton = menuItem.children[0];
//when you click a main menu items button
Input.on('click', menuButton, function (e) {
Util.select(e.target.parentElement);
});
var subMenu = menuItem.children[1];
var subMenuItems = subMenu.children;
//when you click an item within a menu button
for (var j = 0; j < subMenuItems.length; j++) {
var subMenuItem = subMenuItems[j];
var subMenuButton = subMenuItem.children[0];
subMenuButton.addEventListener('click', function (e) {
switch(this.textContent) {
//File Menu
case 'New':
Dialogue.showDialogue('new-pixel');
break;
case 'Save project':
//create name
var selectedPalette = Util.getText('palette-button');
if (selectedPalette != 'Choose a palette...'){
var paletteAbbreviation = palettes[selectedPalette].abbreviation;
var fileName = 'pixel-'+paletteAbbreviation+'-'+canvasSize[0]+'x'+canvasSize[1]+'.lpe';
} else {
var fileName = 'pixel-'+canvasSize[0]+'x'+canvasSize[1]+'.lpe';
selectedPalette = 'none';
}
//set download link
var linkHolder = document.getElementById('save-project-link-holder');
// create file content
var content = getProjectData();
linkHolder.href = 'data:text/plain;charset=utf-8,' + encodeURIComponent(content);
linkHolder.download = fileName;
linkHolder.click();
if (typeof ga !== 'undefined')
ga('send', 'event', 'Pixel Editor Save', selectedPalette, canvasSize[0]+'/'+canvasSize[1]); /*global ga*/
break;
case 'Open':
//if a document exists
if (documentCreated) {
//check if the user wants to overwrite
if (confirm('Opening a pixel will discard your current one. Are you sure you want to do that?'))
//open file selection dialog
document.getElementById('open-image-browse-holder').click();
}
else
//open file selection dialog
document.getElementById('open-image-browse-holder').click();
break;
case 'Export':
if (documentCreated) {
//create name
var selectedPalette = Util.getText('palette-button');
if (selectedPalette != 'Choose a palette...'){
var paletteAbbreviation = palettes[selectedPalette].abbreviation;
var fileName = 'pixel-'+paletteAbbreviation+'-'+canvasSize[0]+'x'+canvasSize[1]+'.png';
} else {
var fileName = 'pixel-'+canvasSize[0]+'x'+canvasSize[1]+'.png';
selectedPalette = 'none';
}
//set download link
var linkHolder = document.getElementById('save-image-link-holder');
// Creating a tmp canvas to flatten everything
var exportCanvas = document.createElement("canvas");
var emptyCanvas = document.createElement("canvas");
var layersCopy = layers.slice();
exportCanvas.width = canvasSize[0];
exportCanvas.height = canvasSize[1];
emptyCanvas.width = canvasSize[0];
emptyCanvas.height = canvasSize[1];
// Sorting the layers by z index
layersCopy.sort((a, b) => (a.canvas.style.zIndex > b.canvas.style.zIndex) ? 1 : -1);
// Merging every layer on the export canvas
for (let i=0; i<layersCopy.length; i++) {
if (layersCopy[i].menuEntry != null && layersCopy[i].isVisible) {
mergeLayers(exportCanvas.getContext('2d'), layersCopy[i].context);
}
// I'm not going to find out why the layer ordering screws up if you don't copy
// a blank canvas when layers[i] is not set as visible, but if you have time to
// spend, feel free to investigate (comment the else, create 3 layers: hide the
// middle one and export, the other 2 will be swapped in their order)
else {
mergeLayers(exportCanvas.getContext('2d'), emptyCanvas.getContext('2d'));
}
}
linkHolder.href = exportCanvas.toDataURL();
linkHolder.download = fileName;
linkHolder.click();
emptyCanvas.remove();
exportCanvas.remove();
//track google event
if (typeof ga !== 'undefined')
ga('send', 'event', 'Pixel Editor Export', selectedPalette, canvasSize[0]+'/'+canvasSize[1]); /*global ga*/
}
break;
case 'Exit':
console.log('exit');
//if a document exists, make sure they want to delete it
if (documentCreated) {
//ask user if they want to leave
if (confirm('Exiting will discard your current pixel. Are you sure you want to do that?'))
//skip onbeforeunload prompt
window.onbeforeunload = null;
else
e.preventDefault();
}
break;
//Edit Menu
case 'Undo':
History.undo();
break;
case 'Redo':
History.redo();
break;
//Palette Menu
case 'Add color':
ColorModule.addColor('#eeeeee');
break;
// SELECTION MENU
case 'Paste':
pasteSelection();
break;
case 'Copy':
copySelection();
tool.pencil.switchTo();
break;
case 'Cut':
cutSelectionTool();
tool.pencil.switchTo();
break;
case 'Cancel':
tool.pencil.switchTo();
break;
//Help Menu
case 'Settings':
//fill form with current settings values
Util.setValue('setting-numberOfHistoryStates', settings.numberOfHistoryStates);
Dialogue.showDialogue('settings');
break;
//Help Menu
case 'Help':
Dialogue.showDialogue('help');
break;
case 'About':
Dialogue.showDialogue('about');
break;
case 'Changelog':
Dialogue.showDialogue('changelog');
break;
}
closeMenu();
});
}
}
function closeMenu () {
//remove .selected class from all menu buttons
for (var i = 0; i < mainMenuItems.length; i++) {
Util.deselect(mainMenuItems[i]);
}
}
function getProjectData() {
// use a dictionary
let dictionary = {};
// sorting layers by increasing z-index
let layersCopy = layers.slice();
layersCopy.sort((a, b) => (a.canvas.style.zIndex > b.canvas.style.zIndex) ? 1 : -1);
// save canvas size
dictionary['canvasWidth'] = currentLayer.canvasSize[0];
dictionary['canvasHeight'] = currentLayer.canvasSize[1];
// save editor mode
dictionary['editorMode'] = pixelEditorMode;
// save palette
for (let i=0; i<ColorModule.currentPalette.length; i++) {
dictionary["color" + i] = ColorModule.currentPalette[i];
}
// save number of layers
dictionary["nLayers"] = layersCopy.length;
// save layers
for (let i=0; i<layersCopy.length; i++) {
// Only saving the layers the user has access to (no vfx, tmp or checkerboard layers)
if (layersCopy[i].menuEntry != null) {
dictionary["layer" + i] = layersCopy[i];
dictionary["layer" + i + "ImageData"] = layersCopy[i].canvas.toDataURL();
}
}
return JSON.stringify(dictionary);
}

View File

@ -390,7 +390,6 @@ function deleteLayer(saveHistory = true) {
let toDelete = layers[layerIndex];
let previousSibling = toDelete.menuEntry.previousElementSibling;
// Adding the ids to the unused ones
console.log("id cancellato: " + toDelete.id);
unusedIDs.push(toDelete.id);
// Selecting the next layer
@ -398,7 +397,7 @@ function deleteLayer(saveHistory = true) {
layers[layerIndex + 1].selectLayer();
}
// or the previous one if the next one doesn't exist
else {
else if (layerIndex != 1) {
layers[layerIndex - 1].selectLayer();
}

View File

@ -1,53 +0,0 @@
/** Loads a file (.png or .lpe)
*
*/
document.getElementById('open-image-browse-holder').addEventListener('change', function () {
let fileName = document.getElementById("open-image-browse-holder").value;
// Getting the extension
let extension = fileName.substring(fileName.lastIndexOf('.')+1, fileName.length) || fileName;
// I didn't write this check and I have no idea what it does
if (this.files && this.files[0]) {
// Btw, checking if the extension is supported
if (extension == 'png' || extension == 'gif' || extension == 'lpe') {
// If it's a Lospec Pixel Editor tm file, I load the project
if (extension == 'lpe') {
let file = this.files[0];
let reader = new FileReader();
// Getting all the data
reader.readAsText(file, "UTF-8");
// Converting the data to a json object and creating a new pixel (see _newPixel.js for more)
reader.onload = function (e) {
let dictionary = JSON.parse(e.target.result);
let mode = dictionary['editorMode'] == 'Advanced' ? 'Basic' : 'Advanced';
Startup.newPixel(dictionary['canvasWidth'], dictionary['canvasHeight'], mode, dictionary);
}
}
else {
//load file
var fileReader = new FileReader();
fileReader.onload = function(e) {
var img = new Image();
img.onload = function() {
//create a new pixel with the images dimentions
switchMode('Advanced');
Startup.newPixel(this.width, this.height);
//draw the image onto the canvas
currentLayer.context.drawImage(img, 0, 0);
createPaletteFromLayers();
//track google event
if (typeof ga !== 'undefined')
ga('send', 'event', 'Pixel Editor Load', colorPalette.length, this.width+'/'+this.height); /*global ga*/
};
img.src = e.target.result;
};
fileReader.readAsDataURL(this.files[0]);
}
}
else alert('Only .lpe project files, PNG and GIF files are allowed at this time.');
}
});

View File

@ -70,7 +70,7 @@ window.addEventListener("mouseup", function (mouseEvent) {
// Saving the event in case something else needs it
currentMouseEvent = mouseEvent;
closeMenu();
TopMenuModule.closeMenu();
if (currentLayer != null && !isChildOfByClass(mouseEvent.target, "layers-menu-entry")) {
currentLayer.closeOptionsMenu();

View File

@ -40,7 +40,6 @@
//=include _editorMode.js
/**load file**/
//=include _loadImage.js
//=include _loadPalette.js
/**event listeners**/
@ -49,7 +48,8 @@
/**buttons**/
//=include _toolButtons.js
//=include _fileMenu.js
//=include FileManager.js
//=include TopMenuModule.js
//=include _rectSelect.js
//=include _move.js
//=include _rectangle.js