Skip to content

Commit

Permalink
Further merge the weekend changes
Browse files Browse the repository at this point in the history
1. Change naming
2. fix typo
3. Align coding style
  • Loading branch information
helamanl0424 authored Mar 28, 2024
1 parent cd8747c commit 65c126b
Showing 1 changed file with 86 additions and 62 deletions.
148 changes: 86 additions & 62 deletions samples/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
let pod = true;
let lastURL = [];
const podURL = 'http://localhost:3000/test/';

document.addEventListener("DOMContentLoaded", function() {

// Set default photo
setCurrentPath('');

// Show all items in the root storage URL
fetchAndDisplayItems();

Expand All @@ -30,7 +31,7 @@ document.addEventListener("DOMContentLoaded", function() {
};
let pico = getPicoURL();

fetch(`${pico}/1556/sample_app/attach_storage`, {
fetch(`${pico}1556/sample_app/attach_storage`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Expand Down Expand Up @@ -75,7 +76,7 @@ function toggleDetachAttachButtons() {
pod = false;
detachPodButton.style.display = 'none';
attachPodButton.style.display = 'inline-block';
fetch(`${pico}/1556/sample_app/detach_storage`)
fetch(`${pico}1556/sample_app/detach_storage`)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
Expand Down Expand Up @@ -111,6 +112,9 @@ async function toggleFolder(folderHeader) {
}

function setPicoURL(url) {
if (!url.endsWith('/')) {
url += '/';
}
localStorage.setItem('PicoURL', url);
}

Expand All @@ -119,17 +123,15 @@ function getPicoURL() {
}

function setCurrentPath(url) {
if (!url.endsWith('/')) {
url += '/';
}
localStorage.setItem('currentPath', url);
console.log(`setCurrentPath to ${url}`);
}

function getCurrentPath() {
return localStorage.getItem('currentPath');
}

async function fetchAndDisplayItems(folderPath = '', goBack = false) {
async function fetchAndDisplayItems(folderPath = podURL, goBack = false) {
const event = `${getPicoURL()}1556/sample_app/ls?fileURL=${folderPath}`;
try {
const response = await fetch(event);
Expand All @@ -140,7 +142,6 @@ async function fetchAndDisplayItems(folderPath = '', goBack = false) {
setCurrentPath(folderPath);
const json = await response.json();
let items = json.directives[0].name;

if (items != null) {
// Sort items by type: folders, photos, others
items.sort((a, b) => {
Expand All @@ -154,7 +155,7 @@ async function fetchAndDisplayItems(folderPath = '', goBack = false) {
return 0;
});

const urlMap = await prefetchFileURLs(items);
const urlMap = await prefetchDataURLs(items);
const folderDiv = document.querySelector('.folder');
folderDiv.innerHTML = ''; // Clear current contents

Expand All @@ -169,7 +170,7 @@ async function fetchAndDisplayItems(folderPath = '', goBack = false) {
displayCurrentPath(getCurrentPath());

} catch (error) {
console.error("Failed to fetch items:", error);
console.error("Failed to fetch and display items:", error);
}
}

Expand Down Expand Up @@ -229,7 +230,7 @@ function toggleControlPanel(showDefaultButtons) {
addButton('back', 'Back', backAction);
addButton('addPhoto', 'Add photo', addPhotoAction);
addButton('addFolder', 'Add folder', addFolderAction);
addButton('deleteFolder', 'Delete folder', deletFolderAction);
addButton('deleteFolder', 'Delete folder', deleteFolderAction);
addButton('sample', 'sample', sampleAction);
} else {
addButton('back', 'Back', backAction);
Expand Down Expand Up @@ -269,15 +270,17 @@ function addPhotoAction() {

const submitNewFile = () => {
const url = input.value.trim();
const filename = url.split('/').pop();
if (url) {
console.log(`Adding file from: ${url}`);
addFile(url).then(() => {
addFile(url, filename).then(() => {
fetchAndDisplayItems(getCurrentPath(), true);
alert('File added successfully!');
input.remove(); // Remove the input field
addPhotoBtn.style.display = ''; // Show the button again
}).catch(error => {
console.error('Error adding folder:', error);
alert('Failed to add file.');
console.error('Error adding file:', error);
alert('Failed to add the file.');
});
}
};
Expand Down Expand Up @@ -306,16 +309,20 @@ function addFolderAction() {
input.style.width = '150px';

const submitNewFolder = () => {
const folderName = input.value.trim();
let folderName = input.value.trim();
if (folderName) {
console.log(`Adding folder: ${folderName}`);
addFolder(folderName).then(() => {
if (!folderName.endsWith('/')) {
folderName += '/';
}
fetchAndDisplayItems(getCurrentPath() + folderName);
alert('Folder added successfully!');
input.remove(); // Remove the input field
addFolderBtn.style.display = ''; // Show the button again
}).catch(error => {
console.error('Error adding folder:', error);
alert('Failed to add folder.');
alert('Failed to add the folder.');
});
}
};
Expand All @@ -332,30 +339,33 @@ function addFolderAction() {
input.focus(); // Automatically focus the input field
}

async function deletFolderAction() {
const listEvent = `${getPicoURL()}1556/sample_app/ls?fileURL=${getCurrentPath()}`;
if (getCurrentPath() == '') {
alert('You cannot delete the root folder!');
return;
}
const listResponse = await fetch(listEvent);
if (!listResponse.ok) {
throw new Error(`List folder failed: ${response.status}`);
}
const json = await listResponse.json();
const items = json.directives[0].name;
if (items.length != 0) {
alert('You can only delete a empty folder!');
return;
}
const deleteEvent = `${getPicoURL()}/1556/sample_app/remove_folder?containerURL=${getCurrentPath}`;
const deleteResponse = await fetch(deleteEvent);
if (!deleteResponse.ok) {
throw new Error(`Delete folder failed: ${response.status}`);
async function deleteFolderAction() {
try {
const listEvent = `${getPicoURL()}1556/sample_app/ls?fileURL=${getCurrentPath()}`;
if (getCurrentPath() == '') {
alert('You cannot delete the root folder!');
return;
}
const listResponse = await fetch(listEvent);
if (!listResponse.ok) {
throw new Error(`List folder failed: ${response.status}`);
}
const json = await listResponse.json();
const items = json.directives[0].name;
if (items.length != 0) {
alert('You can only delete a empty folder!');
return;
}
const deleteEvent = `${getPicoURL()}1556/sample_app/remove_folder?containerURL=${getCurrentPath()}`;
const deleteResponse = await fetch(deleteEvent);
if (!deleteResponse.ok) {
throw new Error(`Delete folder failed: ${response.status}`);
}
alert('Folder deleted successfully!');
fetchAndDisplayItems(lastURL.pop(), true);
} catch (error) {
console.error('Error deleting the folder:', error);
}
// Success message
alert('Folder deleted successfully!');
fetchAndDisplayItems(lastURL.pop(), true);
}

function sampleAction() {
Expand Down Expand Up @@ -410,34 +420,39 @@ function removeAccessFromAction() {
}

async function addFolder(folderName) {
if (!folderName.endsWith('/')) {
folderName += '/';
}
const newPath = getCurrentPath() + folderName;
const event = `${getPicoURL()}/1556/create_folder?containerURL=${newPath}`;
const event = `${getPicoURL()}1556/sample_app/create_folder?containerURL=${newPath}`;
fetch(event)
.then(response => {
if (!response.ok) {
throw new Error(`Add folder failed: ${response.status}`);
}
fetchAndDisplayItems(newPath);
})
.catch(error => {
console.error('Error adding folder:', error);
alert('Failed to add the folder.');
});
}

async function getFileURL(item) {
const event = `${getPicoURL()}/1556/sample_app/fetch_file?fileURL=${getCurrentPath + item}`;
const response = await fetch(event);
if (!response.ok) {
throw new Error(`Fetch file failed: ${response.status}`);
async function getDataURL(item) {
try {
const event = `${getPicoURL()}1556/sample_app/fetch_file?fileURL=${getCurrentPath() + item}`;
const response = await fetch(event);
if (!response.ok) {
throw new Error(`Fetch file failed: ${response.status}`);
}
const json = await response.json();
return json.directives[0].name;
} catch (error) {
console.error("Failed to fetch the file:", error);
}
const json = await response.json();
return json.directives[0].name;

}

async function prefetchFileURLs(items) {
async function prefetchDataURLs(items) {
const urlPromises = items.map(item => {
if (getItemType(item) === 'photo') {
return getFileURL(item).then(url => ({ itemName: item, url }));
return getDataURL(item).then(url => ({ itemName: item, url }));
}
return Promise.resolve({ itemName: item, url: undefined });
});
Expand All @@ -451,20 +466,29 @@ async function prefetchFileURLs(items) {
return urlMap;
}

async function addFile(url) {
const destinationURL = getCurrentPath();
const queryParams = new URLSearchParams({
async function addFile(url, filename) {
const storeLocation = getCurrentPath();
const data = {
fileName: filename,
originURL: url,
destinationURL: destinationURL
}).toString();
const event = `${getPicoURL()}1556/sample_app/overwrite_file?${queryParams}`;
fetch(event)
destinationURL: storeLocation
};
fetch(`${getPicoURL()}1556/sample_app/overwrite_file`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => {
if (!response.ok) {
throw new Error(`Add file failed: ${response.status}`);
}
fetchAndDisplayItems(getCurrentPath(), true);
})
.catch(error => {
console.error('Error adding file:', error);
alert('Failed to add the file.');
});
}

function displayCurrentPath(path) {
Expand Down

0 comments on commit 65c126b

Please sign in to comment.