(function() {
var dropzone = document.getElementById('documents-dropzone');
var fileInput = document.getElementById('documents-file-input');
var listBody = document.getElementById('documents-list-body');
if (!dropzone || !listBody)
return;
function escapeHtml(s) {
var div = document.createElement('div');
div.textContent = s == null ? '' : String(s);
return div.innerHTML;
}
function post(path, params) {
return fetch(path, {
method: 'POST',
credentials: 'same-origin',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams(params || {}).toString()
}).then(function(r) { return r.json(); });
}
function loadList() {
post('/documents/api/list', {}).then(function(res) {
if (!res.ok || !res.documents.length) {
listBody.innerHTML = '
No documents yet - upload your first one above.
';
return;
}
var html = '| Name | Uploaded | | |
';
for (var i = 0; i < res.documents.length; i++) {
var doc = res.documents[i];
html += '' +
'| ' + escapeHtml(doc.name) + ' | ' +
'' + escapeHtml(doc.created) + ' | ' +
'Download | ' +
'Delete | ' +
'
';
}
html += '
';
listBody.innerHTML = html;
var actions = listBody.querySelectorAll('.documents-action');
for (var j = 0; j < actions.length; j++) {
actions[j].addEventListener('click', function() {
var id = this.getAttribute('data-id');
if (this.getAttribute('data-action') === 'download') {
window.fileManagerDownload && window.fileManagerDownload(id, this.getAttribute('data-name'));
} else {
post('/documents/api/delete', { id: id }).then(function(res) {
if (res.ok)
loadList();
});
}
});
}
}).catch(function() {
listBody.innerHTML = 'Could not load your documents.
';
});
}
function uploadFiles(files) {
if (!files || !files.length)
return;
if (window.fileManagerUpload)
window.fileManagerUpload(files);
}
dropzone.addEventListener('click', function() {
fileInput.click();
});
fileInput.addEventListener('change', function() {
uploadFiles(fileInput.files);
fileInput.value = '';
});
dropzone.addEventListener('dragover', function(e) {
e.preventDefault();
dropzone.classList.add('documents-dropzone-active');
});
dropzone.addEventListener('dragleave', function() {
dropzone.classList.remove('documents-dropzone-active');
});
dropzone.addEventListener('drop', function(e) {
e.preventDefault();
dropzone.classList.remove('documents-dropzone-active');
uploadFiles(e.dataTransfer.files);
});
// The site-wide file manager (documents.js, loaded once via
// mainpagetemplate.jet) dispatches this after a successful upload -
// listening here (rather than only refreshing right after our own
// uploadFiles() calls) also picks up uploads that were still running
// when this page was navigated to via spa.js.
document.addEventListener('documents:changed', loadList);
loadList();
})();