-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
add all files #1
base: main
Are you sure you want to change the base?
Conversation
@@ -0,0 +1,175 @@ | |||
//formatting bytes to MB/KB/GB for UI. | |||
function formatSizeUnits(fileSize) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Your function changes the given param
for example:
function name (x) { x = 1 }
bad practice
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Here is a code example from chatgpt that achieves the same result:
function formatBytes(bytes) {
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes === 0) return '0 Byte';
const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}
// Example usage:
console.log(formatBytes(1024)); // Output: 1 KB
console.log(formatBytes(1048576)); // Output: 1 MB
console.log(formatBytes(1099511627776)); // Output: 1 TB
|
||
} | ||
//shrinking the file name for UI. | ||
function shrinkFileName(fileName) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Awesome idea, but can be achieved using just css
(read about ellipsis with css)
} | ||
function updateLocalStorage() { | ||
|
||
const storedFiles = JSON.parse(window.localStorage.getItem("selectedFiles")) || []; //holding the selected file as JSON object |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You don't have to specify window
before reaching localStorage
.
You can just use localStorage
function updateLocalStorage() { | ||
|
||
const storedFiles = JSON.parse(window.localStorage.getItem("selectedFiles")) || []; //holding the selected file as JSON object | ||
console.log(storedFiles); //self-checking |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
redundant console.log
please remove
const storedFiles = JSON.parse(window.localStorage.getItem("selectedFiles")) || []; //holding the selected file as JSON object | ||
console.log(storedFiles); //self-checking | ||
// As I was struggling with the CSS I tried to dynamically resize my container (lines 28-32) | ||
const fileCount = storedFiles.length; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
filesCount?
window.localStorage.setItem("selectedFiles", JSON.stringify(updatedFiles)); //updating the local storage with the new set of items | ||
} | ||
//function that sums the size in bytes for each selected file | ||
function calcTotalSize(files) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
rename to getTotalSize (the name should suggest that there is a returned value)
const text = document.getElementById("mb-left-num"); | ||
const usage = document.getElementById("storage-used"); | ||
|
||
const maxStorage = 100 * 1024 * 1024; //setting the max storage to 100MB. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Awesome that you are using bytes.
But this kind of property should be stored in a more global place.
Because if in the future, you will need to change it to 200MB, you won't have to search for this line
alert("Not enough memory, please remove file/s and try again"); | ||
} | ||
//validations | ||
let percentage; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
const percentage = totalSize > 0 ? (totalSize / maxStorage) * 100 : 0
console.log("Percentage:", percentage); | ||
progressBar.style.width = percentage + "%"; //changing the width of the progress bar according to variant. | ||
//validations | ||
let formattedSize; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
const formattedSize = totalSize > 0 ? formatSizeUnits(totalSize) : "100 MB"
if (files.length > 0) { | ||
const selectedFiles = JSON.parse(window.localStorage.getItem("selectedFiles")) || []; //wether there are already files or not | ||
|
||
const newFiles = Array.from(files).map(file => ({ |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Syntactic sugar:
const newFiles = Array.from(files).map(({name, size}) => ({
name,
size
}));
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@ Tal levi
Good job in general, please take a look at the comments
} | ||
|
||
function updateStorageOnUpload (fileSize) { | ||
var totalStorage = parseInt(localStorage.getItem('totalStorage')); //this makes char to int |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Use let
let totalStorage = parseInt(localStorage.getItem('totalStorage'))
https://www.geeksforgeeks.org/difference-between-var-and-let-in-javascript/
document.getElementById('usedStorage').textContent = usedStorage; | ||
|
||
var remainingStorage = totalStorage - usedStorage; | ||
var percentageUsed = (usedStorage) ; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
redundant variable
document.getElementById('upload').addEventListener('click', uploadFile); | ||
|
||
function initializeStorage() { | ||
// Check if the storage is already initialized |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Reduce the amount of comments.
Clear and readable code should speak for itself
var usedStorage = parseInt(localStorage.getItem('usedStorage')); | ||
|
||
totalStorage -= fileSize; | ||
usedStorage += Math.ceil(fileSize); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
usedStorage += (fileSize).toFixed(2);
Might be more appropriate
for (var i=0; i<selectedFiles.length; i++) { | ||
var currentFile = selectedFiles[i]; | ||
var allowedFormats = ["image/jpeg", "image/jpg", "image/png", "image.gif"]; //this array includes the acceptable formats | ||
var fileSize = (currentFile.size) / (1024) / (1024); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
redundant ()
|
||
function CheckSpace (fileSize) { | ||
var totalStorage = parseInt(localStorage.getItem('totalStorage')); | ||
if (fileSize>totalStorage) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Indentations and spaces
fileInput.value = ''; | ||
return; | ||
} | ||
CheckSpace(fileSize); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The function checkFileFormat
should only have one responsibility.
CheckSpace
should not be called here
} | ||
|
||
function updateStorageOnUpload (fileSize) { | ||
var totalStorage = parseInt(localStorage.getItem('totalStorage')); //this makes char to int |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
In general, the usage of totalStorage
in local storage can be removed.
let totalStorage = 100
in the start of the file would have the same effect, with less calls to the localStorage
function uploadFile() { | ||
|
||
checkFileFormat(); | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Here would be the appropriate place to call CheckSpace()
:)
@@ -0,0 +1,86 @@ | |||
var files=[]; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
use let instead var
let files = [];
https://www.geeksforgeeks.org/difference-between-var-and-let-in-javascript/
@@ -0,0 +1,86 @@ | |||
var files=[]; | |||
let maxSize=100; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
the variable never change, use const.
const maxSize = 100;
https://www.w3schools.com/js/js_const.asp
var files=[]; | ||
let maxSize=100; | ||
|
||
<!-- This function displays a list of the uploaded images and can delete them from the list--> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There is no need to add comments before the functions, clean code is comprehensible code without comments.
|
||
if (!allowedExt.some(ext => file.name.toLowerCase().endsWith(ext))) { | ||
alert("Error: File format is not supported."); | ||
console.error('Error: File format is not supported.'); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You should remove all the console.log before you commit.
if (!allowedExt.some(ext => file.name.toLowerCase().endsWith(ext))) { | ||
alert("Error: File format is not supported."); | ||
console.error('Error: File format is not supported.'); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Shouldn't you stop the function when user try to upload unsupported file?
if (!allowedExt.some(ext => file.name.toLowerCase().endsWith(ext))) {
alert("Error: File format is not supported.");
return;
}
In your case the user can still upload every file.
StorageLeft.innerHTML = MbLeft; | ||
return MbLeft; | ||
} | ||
else { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This code is unreachable.
You already check the image size (in handleUserImages
) before entering calcFileSize
.
Meaning you can remove the if/else condition.
} | ||
} | ||
|
||
<!-- This function opens the file explorer --> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You should create the input in the html instead here.
more clean.
in the html: <input type="file" onchange="handleUserImages()">
const MbLeft = maxSize - totalUsedSpaceMb; | ||
console.log('MbLeft:', MbLeft); | ||
const StorageUsed = document.getElementById('StorageUsed'); | ||
const StorageUsed1 = document.getElementById('StorageUsed1'); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You should give variable names meaningful names.
const StorageUsed = document.getElementById('StorageUsed'); | ||
const StorageUsed1 = document.getElementById('StorageUsed1'); | ||
StorageUsed.innerHTML = maxSize - MbLeft; | ||
StorageUsed1.innerHTML = maxSize - MbLeft; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You can save the calculate in a separate variable instead of doing it twice.
let remainingSize = maxSize - MbLeft
StorageUsed.innerHTML = remainingSize
StorageUsed1.innerHTML = remainingSize
function calcFileSize(file) { | ||
if (checkImageSize(file)) { | ||
var totalUsedSpaceMb = Math.ceil(files.reduce((acc, curr) => acc + curr.size / (1024 ** 2), 0)); | ||
const MbLeft = maxSize - totalUsedSpaceMb; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The convention of variable names in JavaScript is camelCase.
you can read about it:
https://developer.mozilla.org/en-US/docs/Glossary/Camel_case
|
||
<!-- This function checks the size of the image that the user uploads--> | ||
function checkImageSize(file) { | ||
const imageSizeMB = ((file.size) / (1024 ** 2)); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You should rename the variable from file
to image
.
You called it a file but treat it as an image.
const imageSizeMb
= ((file.size
) / (1024 ** 2));
let gradientElement; | ||
let storedSize | ||
let remainingSize | ||
let storedFiles=[]; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You don't use this variable, you should remove.
storedSize+=sizeInMB; | ||
// for(const file of FormatedFiles){ | ||
// storedFiles.push({name:file.name,size:file.size/1024/1024}); | ||
// } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Remove unnecessary comments.
} | ||
for(const name of fileNames){ | ||
if(!(name.toLowerCase().endsWith('.jpg')||name.toLowerCase().endsWith('.jpeg')||name.toLowerCase().endsWith('.png')||name.toLowerCase().endsWith('.gif'))){ | ||
error="one or more of the files isn't supported"; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There is a lot ways to solve it in the right way.
for example:
- In your way, you repeat
name.toLowerCase()
4times.
You should save it in separate variable.
const lowerCaseName = name.toLowerCase()
if(lowerCaseName.endsWith('.jpg') || lowerCaseName.endsWith('.jpeg') || lowerCaseName.endsWith('.png') || lowerCaseName.endsWith('.gif'))
- You can make it more clean.
...
if(isValidImageFileName(lowerCaseName))
...
function isValidImageFileName(fileName) {
const regex = /\.(jpg|jpeg|png|gif)$/i;
return regex.test(fileName);
}
read about regex
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions
|
||
function validateFiles(fileNames,sizeOfFiles){ // checking if the files are supported and if there is enough space to upload them | ||
let error=''; | ||
if(sizeOfFiles+storedSize>150){ |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You should make a global variable instead of 150.
you repeat 150 few times.
const maxSize = 150
@@ -0,0 +1,86 @@ | |||
const TotalSizeMb = 100; | |||
var files = []; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nice job
Generally, use "let" and "const" instead of "var".
Check out my comments.
|
||
function initializeStorage() { | ||
// Check if the storage is already initialized | ||
if (!localStorage.getItem('totalStorage')) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Consider defining totalStorage
as a constant
} | ||
} | ||
|
||
function CheckSpace (fileSize) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Functions names should start with a lower case letter while classes will start with an upper case letter.
Rename to checkSpace
function updateStorageUI() { | ||
var totalStorage = parseInt(localStorage.getItem('totalStorage')); //this makes char to int | ||
var usedStorage = parseInt(localStorage.getItem('usedStorage')); | ||
|
||
document.getElementById('remainingStorage').textContent = totalStorage; | ||
document.getElementById('usedStorage').textContent = usedStorage; | ||
|
||
var remainingStorage = totalStorage - usedStorage; | ||
var percentageUsed = (usedStorage) ; | ||
var progressBar = document.getElementById('progressBar'); | ||
progressBar.style.width = percentageUsed + '%'; | ||
|
||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
updateStorageUI
has two responsibilities: calculate the percentages and update in the UI.
Functions should have one responsibility only .
Consider to create a new function to calculate the percentages.
function uploadFile() { | ||
|
||
checkFileFormat(); | ||
|
||
|
||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
uploadFile
should contain all steps to upload a file:
function uploadFile() {
checkFileFormat();
checkSpace();
updateStorageUI()
}
|
||
if (!allowedExtensions.some(ext => file.name.toLowerCase().endsWith(ext))) { | ||
alert("Error: File format is not supported."); | ||
console.error('Error: File format is not supported.'); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Remove console logs
|
||
function chooseFile() { | ||
console.log('chooseFile'); | ||
const fileInput = document.createElement('input'); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why creating the HTML element here?
} | ||
|
||
function fileSizeCalculator(file) { | ||
if(checkFileSize(file)){ |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Redundant call to checkFileSize()
In addition, functions should only have one porpuse.
fileSizeCalculator
should get a file, and output it size
let state = loadState(); | ||
state.sizeNum = Math.round((state.sizeNum - fileSize) * 100) / 100; | ||
|
||
state.files = state.files.filter(file => file.name !== button.textContent); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I Would give an id to the button.
Searching base on the textContent is bad practice
|
||
|
||
function handleRemove(button, fileSize) { | ||
let state = loadState(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
const here aswell
var currentSize = 0; | ||
|
||
if (localStorage.getItem('current_size') !== null) { | ||
currentSize = Number(localStorage.getItem('current_size')); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You can save localStorage.getItem('current_size')
into a variable to prevent code duplication
|
||
|
||
document.addEventListener('DOMContentLoaded', function () { | ||
let state = loadState(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
const
|
||
function updateUI() { | ||
var left_mb = 800 - currentSize; | ||
document.getElementById('current_mb_text').textContent = currentSize + ' MB'; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Please dont use magic numbers, save 800
into a variable for example const MAX_SIZE = 800
and use the variable.
It will be more readable.
Also be consistent with teh naming of your variables (picke one style for example variable_name
or variableName
and stick to it)
}); | ||
|
||
|
||
function clearState() { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
unused function
document.getElementById('current_mb_text').textContent = currentSize + ' MB'; | ||
document.getElementById('current_mb_title').textContent = currentSize + ' MB'; | ||
document.getElementById('left_mb').textContent = left_mb + ' MB'; | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Also you can save the MB
into a variable as well
var fileSize = e.target.files[i].size; | ||
var fileType = e.target.files[i].type; | ||
var fileSizeinMb = Math.floor(fileSize / 1000); | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If you choose to use camle case use caps on every word - fileSizeInMb
This calculation is not correct, I uploaded a file with a size of 811KB
and the variable fileSizeinMb
was 800
.
updateLeft(state.sizeNum); | ||
|
||
const filesDiv = document.getElementById("files"); | ||
const button = document.createElement('button'); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can seperate to another function.
createFileButton()
@@ -0,0 +1,112 @@ | |||
function saveState(sizeNum, files) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Very well done overall!
|
||
async function uploadFiles(){ | ||
let size = 0; | ||
const filesSystemFileHandler = await showOpenFilePicker({multiple: true}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It can be done with the html: <input type="file" multiple>
const files = await extractFileFromHandler(filesSystemFileHandler); | ||
|
||
files.forEach(element => { | ||
size+= element.size/1024/1024; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Consider saving the size of MB as a constant.
async function uploadFiles(){ | ||
let size = 0; | ||
const filesSystemFileHandler = await showOpenFilePicker({multiple: true}); | ||
const files = await extractFileFromHandler(filesSystemFileHandler); | ||
|
||
files.forEach(element => { | ||
size+= element.size/1024/1024; | ||
}); | ||
|
||
const error = validateFiles(files, size); | ||
if(error !== "") { | ||
alert(error); | ||
return; | ||
} | ||
|
||
storedSize += size; | ||
files.forEach(file => {storedFiles.push({fileName: file.name, fileSize: file.size/1024/1024});}); | ||
|
||
updateView(); | ||
localStorage.setItem('storedSize', storedSize); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nice, but the function should be attached to an input element.
It is a bad practice to get input from an element that doesn't have input functionality.
See the example here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file
|
||
const FillTheBar = document.getElementById('FillTheBarId'); | ||
|
||
document.getElementById('fileInput').onchange = function() { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nice, but this may cause errors on a large scale.
By defining onchange = function() {...}
you override the existing/default function.
The best practice is to use element.addEventListener("change", function(e){...})
See: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
|
||
for (let i = 0; i < files.length; i++) { | ||
const file = files[i]; | ||
totalFileSize += file.size / 1048576; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Consider saving the size of MB in a constant
const MB = 1048576
totalFileSize += file.size / MB;
usedSpaceId.textContent = usedSpace.toFixed(2); | ||
availableDiskSpaceId.textContent = availableDiskSpace.toFixed(2)+ ' MB ' ; | ||
FillTheBar.style.width = '0%'; | ||
}לא |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why not?
if (usedSpace + totalFileSize <= totalDiskSpace) { | ||
usedSpace += totalFileSize; | ||
availableDiskSpace = totalDiskSpace - usedSpace; | ||
|
||
usedSpaceId.textContent = usedSpace.toFixed(2); | ||
availableDiskSpaceId.textContent = availableDiskSpace.toFixed(2)+ ' MB ' ; | ||
|
||
FillTheBar.style.width = (usedSpace * 100) / totalDiskSpace + '%'; | ||
|
||
} else { | ||
|
||
alert('There is not enough space on the disk, please try again'); | ||
document.getElementById('fileInput').value = ''; | ||
usedSpace = 0; | ||
availableDiskSpace = totalDiskSpace; | ||
usedSpaceId.textContent = usedSpace.toFixed(2); | ||
availableDiskSpaceId.textContent = availableDiskSpace.toFixed(2)+ ' MB ' ; | ||
FillTheBar.style.width = '0%'; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There is repetition.
Do all calculations inside the if-else statement. Then, apply the results to the elements.
let barWidth = 0
if (usedSpace + totalFileSize <= totalDiskSpace) {
usedSpace += totalFileSize;
availableDiskSpace = totalDiskSpace - usedSpace;
barWidth = (usedSpace * 100) / totalDiskSpace
} else {
alert('There is not enough space on the disk, please try again');
document.getElementById('fileInput').value = '';
usedSpace = 0;
availableDiskSpace = totalDiskSpace;
}
usedSpaceId.textContent = usedSpace.toFixed(2);
availableDiskSpaceId.textContent = availableDiskSpace.toFixed(2)+ ' MB ' ;
FillTheBar.style.width = `${barWidth}%`;
</div> | ||
<div class="icon-img"> | ||
<img src="images/icon-upload.svg" alt="" aria-hidden="true" /> | ||
</div>> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
remove the '>' char
<script src="index.js"></script> | ||
</head> | ||
|
||
<body onload="Initialize()"> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nice using of onload
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
left you some comments
Great work! keep going 🚀
<div class="icon-img" id="uploadIcon" onclick="openUploadFileDialog()"> | ||
<img src="images/icon-upload.svg" alt="" aria-hidden="true" /> | ||
<input type="file" id="fileUpload" style="display: none;" /> | ||
</div> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
using <label>
element with for
attribute, could prevent us for create unnecessary event handler and connect the label element to your input element
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label
function openUploadFileDialog() { | ||
var fileUpload = document.getElementById('fileUpload'); | ||
fileUpload.click(); | ||
fileUpload.addEventListener('change', handleNewFile); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
it's great to create event listeners, it's much greater to remove the kill event listener when you finish with them
please read about removeEventListener
method and understand how much it important to clean events!
function changeStats() { | ||
document.getElementById('storage-span').innerHTML = storageUsed + ' GB'; | ||
document.getElementById('gb-left-span').innerHTML = maxStorage + ' ' + '<span>GB left</span>'; | ||
document.getElementById('gradient-bar').style.width = (storageUsed / 999) * 100 + '%'; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
document.getElementById('gradient-bar').style.width = (storageUsed / 999) * 100 + '%'; | |
document.getElementById('gradient-bar').style.width = (storageUsed / maxStorage) * 100 + '%'; |
great practice to create and assign constants variable like maxStorage
, but why not using them? :)
var storageUsed = 0; | ||
var maxStorage = 999; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
var
keyword not used anymore and can make trouble
for that es6 bring with him let
and const
keywords.
please read about block scopes VS funtcional scopes
https://blog.coolhead.in/difference-between-function-scope-and-block-scope-in-javascript
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
left you some comments
Great work! keep going 🚀
var totalDiskSpace = 10; // in MB | ||
var currentSpace = 0; | ||
var files = {}; // Store file names and their sizes | ||
var allowedFormats = ['.jpg', '.jpeg', '.gif', '.png']; // Allowed file formats |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
var keyword not used anymore and not relevant
also it can make us a lots of trouble when we thinking about scopes
es6 brought to us the let
/const
keywords for replacement
please read Block Scope VS Functional Scopes -
https://blog.coolhead.in/difference-between-function-scope-and-block-scope-in-javascript
|
||
input.addEventListener('change', function(event) { | ||
var newFiles = event.target.files; | ||
for (var i = 0; i < newFiles.length; i++) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
the var inside the for loop very bed practice
for (var i = 0; i < newFiles.length; i++) { | |
for (let i = 0; i < newFiles.length; i++) { |
} else { | ||
alert('File "' + fileName + '" is already uploaded.'); | ||
} | ||
} | ||
|
||
// Save files localStorage after processing all files | ||
saveStateToLocalStorage(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
by trigger this alerts above, do you prevent the save? please check it
it seems you still add the file
function loadStateFromLocalStorage() { | ||
var savedFiles = localStorage.getItem('files'); | ||
if (savedFiles !== null) { | ||
files = JSON.parse(savedFiles); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
files should be variable?
removeText.addEventListener('click', function() { | ||
listItem.remove(); | ||
var fileSizeMB = files[fileName]; | ||
delete files[fileName]; | ||
updateAvailableSpace(-fileSizeMB); | ||
saveStateToLocalStorage(); // Update localStorage after removing file | ||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
please create for this function and call it instead of write it as anonymous function
removeText.addEventListener('click', function() { | |
listItem.remove(); | |
var fileSizeMB = files[fileName]; | |
delete files[fileName]; | |
updateAvailableSpace(-fileSizeMB); | |
saveStateToLocalStorage(); // Update localStorage after removing file | |
}); | |
removeText.addEventListener('click', onRemoveFile); |
another thing, we must clean after our events then not listening anymore!!
please read about removeEventListener
method
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
left you some comments
Great work! keep going 🚀
<div class="icon-img"> | ||
<img src="images/icon-document.svg" alt="" aria-hidden="true" /> | ||
</div> | ||
<div class="icon-img" id="imageUploader" alt="Upload Files" style="cursor: pointer;" onclick="document.getElementById('fileInput').click();"> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
it very bad practice expose your ids and your events, it can bring a lots of hackers to scan your websites and business.
<div class="icon-img" id="imageUploader" alt="Upload Files" style="cursor: pointer;" onclick="document.getElementById('fileInput').click();"> | |
<div class="icon-img" id="imageUploader" alt="Upload Files" style="cursor: pointer;" onclick="onUploadFiles()"> |
<div class="icon-img" id="imageUploader" alt="Upload Files" style="cursor: pointer;" onclick="document.getElementById('fileInput').click();"> | ||
<img src="images/icon-folder.svg" alt="" aria-hidden="true" /> | ||
<!-- Hidden file input --> | ||
<input type="file" id="fileInput" multiple accept=".jpg, .jpeg, .gif, .png" style="display: none;" onchange="handleFiles(this.files)"> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
also here
var minMemory = "0"; | ||
var maxMemory = "10 MB" | ||
var currentDiskSpace = 0; | ||
var diskSize = 10 * 1024 * 1024; // 10 MB for testing | ||
var currentPercent = 0; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
var keyword not used anymore and not relevant
also it can make us a lots of trouble when we thinking about scopes
es6 brought to us the let
/const
keywords for replacement
please read Block Scope VS Functional Scopes -
https://blog.coolhead.in/difference-between-function-scope-and-block-scope-in-javascript
function createFilePreview(file, fileId) { | ||
|
||
var fileName = file.name; | ||
var fileExtension = fileName.slice(((fileName.lastIndexOf(".") - 1) >>> 0) + 2); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
can you explain what the >>>
operator do?
if (currentDiskSpace + totalSize > diskSize) { | ||
alert('There is not enough space on the disk.'); | ||
} else { | ||
Array.from(files).forEach(function(file, index) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
great implantation using Array.from for converting ArrayLike to Array!
I love it! 🚀
function updateHTML(elementName, value){ | ||
document.getElementById(elementName).innerHTML = value; | ||
} | ||
var i = 0; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
where this i
variable used?
can be problem when it lives in global
filePreviewContainer.appendChild(filePreview); | ||
|
||
|
||
deleteIndicator.addEventListener('click', function() { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
creating event listener and remove them when we don't need them can make our application preform very bad and it ca lead to stackoverflow problem and crash the browser
please read about removeEventListener
method
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
left you some comments
Great work! keep going 🚀
<label for="choose-file" > | ||
<img src="images/icon-folder.svg" alt="" aria-hidden="true" /> | ||
</label> | ||
<input type="file" id="choose-file" onchange="onFileInputChange(this)" style="display: none;" /> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this keyword are not used anymore and bed practice in this point of time
event function will bring you out of the box the event data as first argument
please read about createEventListener
method
progressElement.style.width = percent.toString(10) + '%'; | ||
}; | ||
|
||
const addCurrentFileSize = (s) => { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
what s
means?
naming conversion is very critical in our world!
removeButton.addEventListener('click',()=>{ | ||
span.remove(); | ||
addCurrentFileSize(-size); | ||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
for that you can create new function called onRemoveFile
removeButton.addEventListener('click',()=>{ | |
span.remove(); | |
addCurrentFileSize(-size); | |
}); | |
removeButton.addEventListener('click', onRemoveFile); |
another thing
creating event listener and remove them when we don't need them can make our application preform very bad and it can lead to stackoverflow problem and crash the browser
please read about removeEventListener
method
if (usedSize + s < totalSize) { | ||
usedSize += s; | ||
sizeLeft = totalSize - usedSize; | ||
percent = 100 * (usedSize / totalSize) - 4; | ||
usedSizeElement.innerText = shortenSizeNumber(usedSize) + ' MB'; | ||
sizeLeftElement.innerText = shortenSizeNumber(sizeLeft); | ||
progressElement.style.width = percent.toString(10) + '%'; | ||
progressElement.style.transition = 'width 0.5s ease 0.1s'; | ||
} else { | ||
alert('There is not enough space on the disk'); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
very good approach using the if / else statement and prevent uplaod file!
love it 🚀
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
index2.js
as file name can be not so good
try renaming as main.js
<label for="choose-file" > | ||
<img src="images/icon-folder.svg" alt="" aria-hidden="true" /> | ||
</label> | ||
<input type="file" id="choose-file" onchange="onFileInputChange(this)" style="display: none;" /> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I see you use the power of the label element sticking with input element
I love it! 🚀
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
left you some comments
Great work! keep going 🚀
<img class="logo" src="images/logo.svg" alt="Fylo logo" /> | ||
<section class="icons"> | ||
<div class="icon-img"> | ||
<button id = "documentButton" class="imageDocumentButton"> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
try to prevent spaces in elements attributes
<button id = "documentButton" class="imageDocumentButton"> | |
<button id="documentButton" class="imageDocumentButton"> |
</div> | ||
<div class="icon-img"> | ||
<button onclick="importData()" class="imageUpladFile"> | ||
<img src="images/icon-folder.svg" alt="" aria-hidden="true" /> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
always put value for alt
attribute!
document.addEventListener('DOMContentLoaded', function() { | ||
const documantButton = document.getElementById('documentButton'); | ||
const gradientBar = document.getElementById('gradientBar'); | ||
const sizeText = document.getElementById('sizeText'); | ||
const remaningSize = document.getElementById('remaningSize'); | ||
const fileNamesContainer = document.getElementById('fileNamesContainer'); | ||
const restMem = document.getElementById('restMem'); | ||
getLocalStorage(); | ||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
you sure it work for you?
please read the compare between block scope VS functional scope
let totalSizeInMB = 0; | ||
|
||
function getLocalStorage() { // the function get the file how save in the local storage | ||
var tmpdata = JSON.parse(localStorage.getItem('fileStorage')); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
var keyword not used anymore, instead use const
also it can make you some trouble when it inside function decleration
.
remaningSize.textContent = (10 - totalSizeInMB).toFixed(2) + ' MB'; | ||
restMem.textContent = totalSizeInMB.toFixed(2) + ' MB'; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
remaningSize.textContent = (10 - totalSizeInMB).toFixed(2) + ' MB'; | |
restMem.textContent = totalSizeInMB.toFixed(2) + ' MB'; | |
remaningSize.innerText = (10 - totalSizeInMB).toFixed(2) + ' MB'; | |
restMem.innerText = totalSizeInMB.toFixed(2) + ' MB'; |
let files = Array.from(input.files); | ||
files.forEach(function(file) { | ||
let fileSizeInMB = file.size / (1024 * 1024); | ||
if (fileSizeInMB > 10) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
consider create constant for the TOTAL_MAX_SIZE
instead of change this parameter hard coded
for example if I ask to increase the max size of your hardware, you will start scan all you project and changing the 10
parameter, but if you create constant variable you will just changing it and that all
fileNameElement.addEventListener('click', function() { | ||
fileNamesContainer.removeChild(fileNameElement); | ||
removeFile(fileSizeInMB); | ||
localStorage.removeItem('fileStorage'); | ||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
creating event listeners and not remove them when we don't need them can make our application preform very bad and it can lead to stackoverflow problem and crash the browser
please read about removeEventListener
method
let fileNameElement = document.createElement('button'); | ||
fileNameElement.classList.add('file-button'); | ||
fileNameElement.textContent = fileName; | ||
fileNameElement.addEventListener('click', function() { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
consider create function and pass it in the event listener instead of creating anonymos functon
fileNameElement.addEventListener('click', function() { | |
fileNameElement.addEventListener('click', onRemoveFile) |
function moveBar(size) { | ||
const element = document.getElementById("gradient-bar-id"); | ||
let currentWidth = parseFloat(element.style.width) || 3; | ||
let targetWidth = size * 10; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
can be const
} | ||
|
||
//Get total size from local storage | ||
function getTotalFileSize() { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
const getTotalFileSize = () => parseFloat(localStorage.getItem('totalFileSize')) || 0;
|
||
const fileInput = document.getElementById('fileInput'); | ||
const fileSizeDisplay = document.getElementById('fileSizeDisplay'); | ||
const MBLeftElement = document.getElementById('MBLeft'); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
camelCase
@@ -0,0 +1,178 @@ | |||
/*NOTE: the size of the files extracted from the <input type="file"> element |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The storage number in the front dont work.
You've used NaN Bytes of your storage
</section> | ||
<!-- Storage Container --> | ||
<section class="storage-container"> | ||
<h1>You've used <span id="used-space">815 GB</span> of your storage</h1> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If JavaScript updates this number, don't display a number here; instead, display "loading..." for example.
if(key.split(size_suffix).length == 1 && key !== AVAIL_SPACE ){ | ||
append_file_name(key); | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There is no need for comments within a function, clean and readable code speaks for itself.
if(key.split(size_suffix).length == 1 && key !== AVAIL_SPACE ){ | ||
append_file_name(key); | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
In this case, it's preferable to use (!localStorage.getItem(AVAIL_SPACE))
instead.
const openUploadMenu = e => document.getElementById("upload-input").click(); | ||
|
||
const supported_extensions = ["jpg","jpeg","png","gif","JPG","JPEG","PNG","GIF"]; | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Where does this const belong? If it's for use throughout the entire file, place it at the top of the file. If it's only relevant to a specific function, put it at the top of that function.
@@ -0,0 +1,82 @@ | |||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
the number in the left side of the proggress bar dont change
} | ||
} | ||
|
||
//Get total size from local storage |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There is no need for comments within a function, clean and readable code speaks for itself.
//Update progress bar based on total file size | ||
function updateProgressBar(totalSize, previousSize) { | ||
moveBar(totalSize, previousSize); | ||
fileSizeDisplay.textContent = totalSize === 0 ? totalSize.toFixed(0) : totalSize.toFixed(2); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
name values to make the code more readable, and reuse this const:
moveBar(totalSize, previousSize);
const totalSizeValue = totalSize === 0 ? totalSize.toFixed(0) : totalSize.toFixed(2);
fileSizeDisplay.textContent = totalSizeValue;
MBLeftElement.firstChild.textContent = 10 - totalSizeValue;
return; | ||
} | ||
|
||
const fileSize = (selectedFile.size / (1024 * 1024)); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
if u are gonna use a lot in files size make a consts in the top of the code
const GB = 1024 * 1024 * 1024;
const MB = 1024 * 1024;
const KB = 1024;
const fileInput = document.getElementById('fileInput'); | ||
const fileSizeDisplay = document.getElementById('fileSizeDisplay'); | ||
const MBLeftElement = document.getElementById('MBLeft'); | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There is no limit to the types of files that can be uploaded
No description provided.