Rewrite file manager in svelte

This commit is contained in:
2021-05-18 23:47:38 +02:00
parent 5875d187b6
commit 9f8d5cc8a2
9 changed files with 689 additions and 170 deletions

View File

@@ -64,12 +64,12 @@ function DirectoryElement(directoryArea, footer) {
this.lastScrollTop = 0
}
DirectoryElement.prototype.reset = function() {
DirectoryElement.prototype.reset = function () {
this.allFiles = []
this.visibleFiles = []
}
DirectoryElement.prototype.addFile = function(icon, name, href, type, size, sizeLabel, dateCreated) {
DirectoryElement.prototype.addFile = function (icon, name, href, type, size, sizeLabel, dateCreated) {
this.allFiles.push({
icon: icon,
name: name,
@@ -82,14 +82,14 @@ DirectoryElement.prototype.addFile = function(icon, name, href, type, size, size
})
}
DirectoryElement.prototype.renderFiles = function() {
DirectoryElement.prototype.renderFiles = function () {
this.search(this.lastSearchTerm)
}
// search filters the allFiles array on a search term. All files which match the
// search term will be put into visibleFiles. The visibleFiles array will then
// be rendered by renderVisibleFiles
DirectoryElement.prototype.search = function(term) {
DirectoryElement.prototype.search = function (term) {
term = term.toLowerCase()
this.lastSearchTerm = term
this.visibleFiles = []
@@ -124,7 +124,7 @@ DirectoryElement.prototype.search = function(term) {
}
// searchSubmit opens the first file in the search results
DirectoryElement.prototype.searchSubmit = function() {
DirectoryElement.prototype.searchSubmit = function () {
if (this.visibleFiles.length === 0) {
return // There are no files visible
}
@@ -132,7 +132,7 @@ DirectoryElement.prototype.searchSubmit = function() {
window.location = this.getVisibleFile(0).href
}
DirectoryElement.prototype.sortBy = function(field) {
DirectoryElement.prototype.sortBy = function (field) {
if (field === "") {
// If no sort field is provided we use the last used sort field
field = this.currentSortField
@@ -158,9 +158,9 @@ DirectoryElement.prototype.sortBy = function(field) {
// Then prepend the arrow to the current sort label
if (this.currentSortAscending) {
this.sortButtons[field].innerText = "▼ "+this.sortButtons[field].innerText
this.sortButtons[field].innerText = "▼ " + this.sortButtons[field].innerText
} else {
this.sortButtons[field].innerText = "▲ "+this.sortButtons[field].innerText
this.sortButtons[field].innerText = "▲ " + this.sortButtons[field].innerText
}
let fieldA, fieldB
@@ -168,7 +168,7 @@ DirectoryElement.prototype.sortBy = function(field) {
fieldA = this.allFiles[a][this.currentSortField]
fieldB = this.allFiles[b][this.currentSortField]
if (typeof(fieldA) === "number") {
if (typeof (fieldA) === "number") {
if (this.currentSortAscending) {
return fieldA - fieldB
} else {
@@ -185,7 +185,7 @@ DirectoryElement.prototype.sortBy = function(field) {
this.renderVisibleFiles(true)
}
DirectoryElement.prototype.createFileButton = function(file, index) {
DirectoryElement.prototype.createFileButton = function (file, index) {
let el = document.createElement("a")
el.classList = "node"
el.href = file.href
@@ -235,11 +235,11 @@ DirectoryElement.prototype.createFileButton = function(file, index) {
// This function dereferences an index in the visibleFiles array to a real file
// in the allFiles array. The notation is a bit confusing so the separate
// function is just for clarity
DirectoryElement.prototype.getVisibleFile = function(index) {
DirectoryElement.prototype.getVisibleFile = function (index) {
return this.allFiles[this.visibleFiles[index]]
}
DirectoryElement.prototype.renderVisibleFiles = function(freshStart) {
DirectoryElement.prototype.renderVisibleFiles = function (freshStart) {
let scrollDown = this.lastScrollTop <= this.directoryArea.scrollTop
this.lastScrollTop = this.directoryArea.scrollTop
@@ -249,24 +249,24 @@ DirectoryElement.prototype.renderVisibleFiles = function(freshStart) {
if (freshStart) {
this.dirContainer.innerHTML = ""
this.dirContainer.style.height = totalHeight+"px"
this.dirContainer.style.height = totalHeight + "px"
scrollDown = true
let totalSize = 0
for (let i in this.visibleFiles) {
totalSize += this.getVisibleFile(i).size
}
this.footer.innerText = this.visibleFiles.length+" items. Total size: "+formatDataVolume(totalSize, 4)
this.footer.innerText = this.visibleFiles.length + " items. Total size: " + formatDataVolume(totalSize, 4)
}
let paddingTop = this.lastScrollTop - this.lastScrollTop%fileHeight
let start = Math.floor(paddingTop/fileHeight) - 5
let paddingTop = this.lastScrollTop - this.lastScrollTop % fileHeight
let start = Math.floor(paddingTop / fileHeight) - 5
if (start < 0) { start = 0 }
let end = Math.ceil((paddingTop+viewportHeight)/fileHeight) + 5
if (end > this.visibleFiles.length) { end = this.visibleFiles.length-1 }
let end = Math.ceil((paddingTop + viewportHeight) / fileHeight) + 5
if (end > this.visibleFiles.length) { end = this.visibleFiles.length - 1 }
this.dirContainer.style.paddingTop = (start*fileHeight)+"px"
this.dirContainer.style.paddingTop = (start * fileHeight) + "px"
// Remove the elements which are out of bounds
let firstEl
@@ -282,23 +282,23 @@ DirectoryElement.prototype.renderVisibleFiles = function(freshStart) {
if (firstIdx < start) {
this.dirContainer.removeChild(firstEl)
console.debug("Remove start "+firstIdx)
console.debug("Remove start " + firstIdx)
} else if (lastIdx > end) {
this.dirContainer.removeChild(lastEl)
console.debug("Remove end "+lastIdx)
console.debug("Remove end " + lastIdx)
} else {
break
}
}
console.debug(
"start "+start+
" end "+end+
" firstIdx "+firstIdx+
" lastIdx "+lastIdx+
" freshStart "+freshStart+
" scrollDown "+scrollDown+
" children "+this.dirContainer.childElementCount
"start " + start +
" end " + end +
" firstIdx " + firstIdx +
" lastIdx " + lastIdx +
" freshStart " + freshStart +
" scrollDown " + scrollDown +
" children " + this.dirContainer.childElementCount
)
// Then add the elements which have become visible. When the user scrolls
@@ -311,7 +311,7 @@ DirectoryElement.prototype.renderVisibleFiles = function(freshStart) {
continue
}
this.dirContainer.append(this.createFileButton(this.getVisibleFile(i), i))
console.debug("Append "+i);
console.debug("Append " + i);
}
} else {
for (let i = end; i >= start; i--) {
@@ -319,7 +319,7 @@ DirectoryElement.prototype.renderVisibleFiles = function(freshStart) {
continue
}
this.dirContainer.prepend(this.createFileButton(this.getVisibleFile(i), i))
console.debug("Prepend "+i);
console.debug("Prepend " + i);
}
}
}

View File

@@ -1,99 +0,0 @@
function DirectoryNode(file, index) {
this.el = document.createElement("div")
this.el.classList = "node"
if (file.selected) {
this.el.classList += " node_selected"
}
this.el.href = file.href
this.el.target = "_blank"
this.el.title = file.name
this.el.setAttribute("fileindex", index)
this.el.addEventListener("click", e => {
if (e.detail > 1) {
return // Prevent dblclick from triggering click
}
if (e.which == 2) {
// Middle mouse button opens the file in a new window
this.open(true)
return
}
this.select()
})
this.el.addEventListener("tap")
this.el.addEventListener("dblclick", e => {
this.open(false)
})
{
let cell = document.createElement("div")
let thumb = document.createElement("img")
thumb.src = file.icon
cell.appendChild(thumb)
let label = document.createElement("span")
label.innerText = file.name
cell.appendChild(label)
cell.appendChild(label)
this.el.appendChild(cell)
}
{
let cell = document.createElement("div")
cell.style.width = this.fieldDateWidth
let label = document.createElement("span")
label.innerText = printDate(new Date(file.dateCreated), true, true, false)
cell.appendChild(label)
this.el.appendChild(cell)
}
{
let cell = document.createElement("div")
cell.style.width = this.fieldSizeWidth
let label = document.createElement("span")
label.innerText = file.sizeLabel
cell.appendChild(label)
this.el.appendChild(cell)
}
{
let cell = document.createElement("div")
cell.style.width = this.fieldTypeWidth
let label = document.createElement("span")
label.innerText = file.type
cell.appendChild(label)
this.el.appendChild(cell)
}
return this.el
}
DirectoryNode.prototype.select = function() {
if (this.el.classList.contains("node_selected")) {
this.el.classList = "node"
file.selected = false
} else {
this.el.classList = "node node_selected"
file.selected = true
}
}
DirectoryNode.prototype.open = function(newTab) {
if (newTab) {
window.open(file.href, "_blank")
} else {
window.open(file.href)
}
}
DirectoryNode.prototype.click = function(e) {
if (e.detail > 1) {
return // Prevent dblclick from triggering click
}
if (e.which == 2) {
// Middle mouse button opens the file in a new window
e.preventDefault()
window.open(file.href, "_blank")
return
}
}
DirectoryNode.prototype.doubleClick = function() {
window.open(file.href)
}

View File

@@ -34,13 +34,13 @@ function FileManager(windowElement) {
)
}
FileManager.prototype.setSpinner = function() {
FileManager.prototype.setSpinner = function () {
this.window.appendChild(document.getElementById("tpl_spinner").content.cloneNode(true))
}
FileManager.prototype.delSpinner = function() {
FileManager.prototype.delSpinner = function () {
for (let i in this.window.children) {
if (
typeof(this.window.children[i].classList) === "object" &&
typeof (this.window.children[i].classList) === "object" &&
this.window.children[i].classList.contains("spinner")
) {
this.window.children[i].remove()
@@ -48,24 +48,20 @@ FileManager.prototype.delSpinner = function() {
}
}
FileManager.prototype.getDirectory = function(path) {
console.log("ayy!")
}
FileManager.prototype.getUserFiles = function() {
FileManager.prototype.getUserFiles = function () {
this.setSpinner()
let getAll = (page) => {
let numFiles = 1000
fetch(apiEndpoint+"/user/files?page="+page+"&limit="+numFiles).then(resp => {
fetch(apiEndpoint + "/user/files?page=" + page + "&limit=" + numFiles).then(resp => {
if (!resp.ok) { Promise.reject("yo") }
return resp.json()
}).then(resp => {
for (let i in resp.files) {
this.directoryElement.addFile(
apiEndpoint+"/file/"+resp.files[i].id+"/thumbnail?width=32&height=32",
apiEndpoint + "/file/" + resp.files[i].id + "/thumbnail?width=32&height=32",
resp.files[i].name,
"/u/"+resp.files[i].id,
"/u/" + resp.files[i].id,
resp.files[i].mime_type,
resp.files[i].size,
formatDataVolume(resp.files[i].size, 4),
@@ -76,7 +72,7 @@ FileManager.prototype.getUserFiles = function() {
this.directoryElement.renderFiles()
if (resp.files.length === numFiles) {
getAll(page+1)
getAll(page + 1)
} else {
// Less than the maximum number of results means we're done
// loading, we can remove the loading spinner
@@ -84,7 +80,7 @@ FileManager.prototype.getUserFiles = function() {
}
}).catch((err) => {
this.delSpinner()
throw(err)
throw (err)
})
}
@@ -92,22 +88,22 @@ FileManager.prototype.getUserFiles = function() {
getAll(0)
}
FileManager.prototype.getUserLists = function() {
FileManager.prototype.getUserLists = function () {
this.setSpinner()
this.directoryElement.reset()
fetch(apiEndpoint+"/user/lists").then(resp => {
fetch(apiEndpoint + "/user/lists").then(resp => {
if (!resp.ok) { Promise.reject("yo") }
return resp.json()
}).then(resp => {
for (let i in resp.lists) {
this.directoryElement.addFile(
apiEndpoint+"/list/"+resp.lists[i].id+"/thumbnail?width=32&height=32",
apiEndpoint + "/list/" + resp.lists[i].id + "/thumbnail?width=32&height=32",
resp.lists[i].title,
"/l/"+resp.lists[i].id,
"/l/" + resp.lists[i].id,
"list",
resp.lists[i].file_count,
resp.lists[i].file_count+" files",
resp.lists[i].file_count + " files",
resp.lists[i].date_created,
)
}
@@ -116,12 +112,12 @@ FileManager.prototype.getUserLists = function() {
this.delSpinner()
}).catch((err) => {
this.delSpinner()
throw(err)
throw (err)
})
}
FileManager.prototype.keyboardEvent = function(e) {
console.log("Pressed: "+e.keyCode)
FileManager.prototype.keyboardEvent = function (e) {
console.log("Pressed: " + e.keyCode)
// CTRL + F or "/" opens the search bar
if (e.ctrlKey && e.keyCode === 70 || !e.ctrlKey && e.keyCode === 191) {

View File

@@ -0,0 +1,21 @@
{{define "file_manager_svelte"}}<!DOCTYPE html>
<html lang="en">
<head>
{{template "meta_tags" "File Manager"}}
{{template "user_style" .}}
<script>
window.api_endpoint = '{{.APIEndpoint}}';
</script>
<link rel='stylesheet' href='/res/svelte/user_file_manager.css'>
<script defer src='/res/svelte/user_file_manager.js'></script>
</head>
<body>
{{template "page_menu" .}}
<div id="page_body" class="page_body"></div>
{{template "analytics"}}
</body>
</html>
{{end}}

View File

@@ -0,0 +1,35 @@
{{define "file_viewer_svelte"}}
<!DOCTYPE html>
<html lang="en">
<head>
<title>{{.Title}}</title>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
{{ template "opengraph" .OGData }}
{{ template "user_style" . }}
<link rel="icon" sizes="32x32" href="/res/img/pixeldrain_32.png" />
<link rel="icon" sizes="128x128" href="/res/img/pixeldrain_128.png" />
<link rel="icon" sizes="152x152" href="/res/img/pixeldrain_152.png" />
<link rel="icon" sizes="180x180" href="/res/img/pixeldrain_180.png" />
<link rel="icon" sizes="192x192" href="/res/img/pixeldrain_192.png" />
<link rel="icon" sizes="196x196" href="/res/img/pixeldrain_196.png" />
<link rel="icon" sizes="256x256" href="/res/img/pixeldrain_256.png" />
<link rel="apple-touch-icon" sizes="152x152" href="/res/img/pixeldrain_152.png" />
<link rel="apple-touch-icon" sizes="180x180" href="/res/img/pixeldrain_180.png" />
<link rel="shortcut icon" sizes="196x196" href="/res/img/pixeldrain_196.png" />
<meta name="theme-color" content="#75AD38"/>
<script>
window.api_endpoint = '{{.APIEndpoint}}';
const initialNode = {{.Other}};
</script>
<link rel='stylesheet' href='/res/svelte/file_viewer.css'>
<script defer src='/res/svelte/file_viewer.js'></script>
</head>
<body id="body"></body>
</html>
{{end}}

View File

@@ -29,9 +29,11 @@ function serve() {
const builddir = "../res/static/svelte"
export default [
"file_viewer",
"filesystem",
"modal",
"user_buckets",
"user_file_manager",
"admin_abuse_reporters",
"admin_abuse_reports",
].map((name, index) => ({

View File

@@ -0,0 +1,8 @@
import App from './user_file_manager/FileManager.svelte';
const app = new App({
target: document.getElementById("page_body"),
props: {}
});
export default app;

View File

@@ -0,0 +1,360 @@
<script>
import { formatDataVolume, formatDate } from "../util/Formatting.svelte";
// Main elements
let directoryArea
let directorySorters
let nodeContainer
let statusBar = "Loading..."
// Create sort buttons
// Sorting internal state. By default we sort by dateCreated in descending
// order (new to old)
let currentSortField = "dateCreated"
let currentSortAscending = false
let tableColumns = [
{ name: "Name", field: "name", width: "" },
{ name: "Creation date", field: "dateCreated", width: "160px" },
{ name: "Size", field: "size", width: "90px" },
{ name: "Type", field: "type", width: "200px" },
]
// Scroll event for rendering new file nodes when they become visible
let frameRequested = false;
const onScroll = (e) => {
if (frameRequested) { return }
frameRequested = true
requestAnimationFrame(() => {
renderVisibleFiles()
frameRequested = false
})
}
// Internal state, contains a list of all files in the directory, visible
// files in the directory and the last scroll position. These are used for
// rendering the file list correctly
// type: {icon, name, href, type, size, sizeLabel, dateCreated, selected}
let allFiles = []
export const reset = () => {
allFiles = []
}
export const addFile = (icon, name, href, type, size, sizeLabel, dateCreated) => {
allFiles.push({
icon: icon,
name: name,
href: href,
type: type,
size: size,
sizeLabel: sizeLabel,
dateCreated: dateCreated,
selected: false,
filtered: false,
visible: false,
})
}
export const renderFiles = () => {
search(lastSearchTerm)
}
// search filters the allFiles array on a search term. All files which match the
// search term will be put into visibleFiles. The visibleFiles array will then
// be rendered by renderVisibleFiles
let lastSearchTerm = ""
export const search = (term) => {
term = term.toLowerCase()
lastSearchTerm = term
if (term === "") {
for (let i in allFiles) {
allFiles[i].filtered = false
}
sortBy("")
renderVisibleFiles()
return
}
let fileName = ""
for (let i in allFiles) {
fileName = allFiles[i].name.toLowerCase()
// If there's an exact match we'll show it as the only result
// if (fileName === term) {
// allFiles[i].filtered = false
// break
// }
if (fileName.includes(term)) {
// If a file name contains the search term we include it in the results
allFiles[i].filtered = false
} else {
allFiles[i].filtered = true
}
}
sortBy("")
renderVisibleFiles()
}
// searchSubmit opens the first file in the search results
export const searchSubmit = () => {
for (let i in allFiles) {
if (allFiles[i].visible && !allFiles[i].filtered) {
window.location = allFiles[i].href
break
}
}
}
const sortBy = (field) => {
if (field === "") {
// If no sort field is provided we use the last used sort field
field = currentSortField
} else {
// If a sort field is provided we check in which direction we have to
// sort
if (currentSortField !== field) {
// If this field is a different field than before we sort it in
// ascending order
currentSortAscending = true
currentSortField = field
} else if (currentSortField === field) {
// If it is the same field as before we reverse the sort order
currentSortAscending = !currentSortAscending
}
}
// Add the arrow to the sort label. First remove the arrow from all sort
// labels
let colIdx = 0
for (let i in tableColumns) {
if (tableColumns[i].field == field) {
colIdx = i
}
tableColumns[i].name = tableColumns[i].name.replace("▲ ", "").replace("▼ ", "")
}
// Then prepend the arrow to the current sort label
if (currentSortAscending) {
tableColumns[colIdx].name = "▼ " + tableColumns[colIdx].name
} else {
tableColumns[colIdx].name = "▲ " + tableColumns[colIdx].name
}
tableColumns = tableColumns
let fieldA, fieldB
allFiles.sort((a, b) => {
fieldA = a[currentSortField]
fieldB = b[currentSortField]
if (typeof (fieldA) === "number") {
if (currentSortAscending) {
return fieldA - fieldB
} else {
return fieldB - fieldA
}
} else {
if (currentSortAscending) {
return fieldA.localeCompare(fieldB)
} else {
return fieldB.localeCompare(fieldA)
}
}
})
renderVisibleFiles()
}
const renderVisibleFiles = () => {
const fileHeight = 40
let paddingTop = directoryArea.scrollTop - directoryArea.scrollTop % fileHeight
let start = Math.floor(paddingTop / fileHeight) - 3
if (start < 0) { start = 0 }
let end = Math.ceil((paddingTop + directoryArea.clientHeight) / fileHeight) + 3
if (end > allFiles.length) { end = allFiles.length - 1 }
nodeContainer.style.paddingTop = (start * fileHeight) + "px"
// All files which have not been filtered out by the search function. We
// pretend that files with filtered == true do not exist
let totalFiles = 0
let totalSize = 0
for (let i in allFiles) {
if (totalFiles >= start && totalFiles <= end && !allFiles[i].filtered) {
allFiles[i].visible = true
} else {
allFiles[i].visible = false
}
if (!allFiles[i].filtered) {
totalFiles++
totalSize += allFiles[i].size
}
}
nodeContainer.style.height = (totalFiles * fileHeight) + "px"
statusBar = totalFiles + " items. Total size: " + formatDataVolume(totalSize, 4)
// Update the view
allFiles = allFiles
console.debug(
"start " + start +
" end " + end +
" children " + nodeContainer.childElementCount
)
}
</script>
<div id="directory_element">
<div bind:this={directoryArea} on:scroll={onScroll} id="directory_area" class="directory_area">
<div bind:this={directorySorters} id="sorters" class="directory_sorters">
{#each tableColumns as col}
<div on:click={sortBy(col.field)} style="min-width: {col.width}">{col.name}</div>
{/each}
</div>
<div bind:this={nodeContainer} id="node_container" class="directory_node_container">
{#each allFiles as file}
{#if file.visible && !file.filtered}
<a class="node" href={file.href} target="_blank" title="{file.name}" class:node_selected={file.selected}>
<div>
<img src={file.icon} alt="file thumbnail" />
<span>{file.name}</span>
</div>
<div style="width: {tableColumns[1].width}">
<span>{formatDate(new Date(file.dateCreated), true, true, false)}</span>
</div>
<div style="width: {tableColumns[2].width}">
<span>{file.sizeLabel}</span>
</div>
<div style="width: {tableColumns[3].width}">
<span>{file.type}</span>
</div>
</a>
{/if}
{/each}
</div>
</div>
<div id="footer" class="status_bar highlight_1">
{statusBar}
</div>
</div>
<style>
#directory_element {
flex: 1 1 auto;
display: flex;
flex-direction: column;
overflow: auto;
}
#sorters {
display: flex;
flex-direction: row;
position: sticky;
overflow: hidden;
top: 0;
z-index: 1;
background-color: var(--layer_2_color);
min-width: 850px;
}
#sorters > div {
display: inline-block;
margin: 4px 10px;
padding: 4px;
box-sizing: border-box;
border-bottom: 1px solid var(--input_color);
cursor: pointer;
}
#sorters > :first-child,
.node > :first-child {
flex-shrink: 1;
flex-grow: 1;
}
#sorters > :not(:first-child),
.node > :not(:first-child) {
flex-shrink: 0;
flex-grow: 0;
}
#directory_area {
flex: 1 1 auto;
margin: 0;
padding: 0;
overflow-x: auto;
text-align: left;
box-sizing: border-box;
}
#node_container {
/* Required because we use padding for moving the nodes down when items
above are out of view*/
box-sizing: border-box;
display: block;
min-width: 850px;
}
#footer {
flex-shrink: 0;
text-align: left;
}
.node {
display: flex;
flex-direction: row;
position: static;
height: 40px;
overflow: hidden;
/* I use padding instead of margin here because it goves me more precise
control over the size.
Check out https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing*/
margin: 0;
box-sizing: border-box;
color: var(--text_color);
text-decoration: none;
}
.node:hover:not(.node_selected) {
background-color: var(--input_color_dark);
color: var(--input_text_color);
text-decoration: none;
}
.node_selected {
background-color: var(--highlight_color);
color: var(--highlight_text_color);
}
.node > div {
height: 100%;
overflow: hidden;
margin: auto 10px;
padding: 4px;
box-sizing: border-box;
display: inline-block;
text-overflow: ellipsis;
white-space: nowrap;
}
.node > div > span {
margin: auto;
box-sizing: border-box;
display: block;
text-overflow: ellipsis;
white-space: nowrap;
}
.node > div > img {
max-height: 100%;
margin-right: 6px;
width: auto;
min-width: auto;
float: left;
display: block;
}
</style>

View File

@@ -0,0 +1,196 @@
<script>
import { onMount } from "svelte";
import { formatDataVolume } from "../util/Formatting.svelte";
import Spinner from "../util/Spinner.svelte";
import DirectoryElement from "./DirectoryElement.svelte"
let loading = true
let navBar
let breadcrumbs = ""
let btnReload
let inputSearch
let directoryElement
let getUserFiles = () => {
loading = true
directoryElement.reset()
fetch(window.api_endpoint + "/user/files").then(resp => {
if (!resp.ok) { Promise.reject("yo") }
return resp.json()
}).then(resp => {
for (let i in resp.files) {
directoryElement.addFile(
window.api_endpoint + "/file/" + resp.files[i].id + "/thumbnail?width=32&height=32",
resp.files[i].name,
"/u/" + resp.files[i].id,
resp.files[i].mime_type,
resp.files[i].size,
formatDataVolume(resp.files[i].size, 4),
resp.files[i].date_upload,
)
}
directoryElement.renderFiles()
}).catch((err) => {
throw (err)
}).finally(() => {
loading = false
})
}
let getUserLists = () => {
loading = true
directoryElement.reset()
fetch(window.api_endpoint + "/user/lists").then(resp => {
if (!resp.ok) { Promise.reject("yo") }
return resp.json()
}).then(resp => {
for (let i in resp.lists) {
directoryElement.addFile(
window.api_endpoint + "/list/" + resp.lists[i].id + "/thumbnail?width=32&height=32",
resp.lists[i].title,
"/l/" + resp.lists[i].id,
"list",
resp.lists[i].file_count,
resp.lists[i].file_count + " files",
resp.lists[i].date_created,
)
}
directoryElement.renderFiles()
}).catch((err) => {
throw (err)
}).finally(() => {
loading = false
})
}
const searchHandler = (e) => {
if (e.keyCode === 27) { // Escape
e.preventDefault()
inputSearch.blur()
return
} else if (e.keyCode === 13) { // Enter
e.preventDefault()
directoryElement.searchSubmit()
return
}
requestAnimationFrame(() => {
directoryElement.search(inputSearch.value)
})
}
let keyboardEvent = (e) => {
console.log("Pressed: " + e.keyCode)
// CTRL + F or "/" opens the search bar
if (e.ctrlKey && e.keyCode === 70 || !e.ctrlKey && e.keyCode === 191) {
e.preventDefault()
inputSearch.focus()
}
}
let initialized = false
let hashChange = () => {
if (!initialized) {
return
}
if (window.location.hash === "#files") {
breadcrumbs = "My Files"
getUserFiles()
} else if (window.location.hash === "#lists") {
breadcrumbs = "My Lists"
getUserLists()
} else {
alert("invalid file manager type")
}
}
onMount(() => {
initialized = true
hashChange()
})
</script>
<svelte:window on:keydown={keyboardEvent} on:hashchange={hashChange} />
<div id="file_manager" class="file_manager">
<div bind:this={navBar} id="nav_bar" class="nav_bar highlight_1">
<button id="btn_menu" onclick="toggleMenu()"><i class="icon">menu</i></button>
<div class="spacer"></div>
<input class="breadcrumbs" type="text" value="{breadcrumbs}"/>
<div class="spacer"></div>
<input bind:this={inputSearch} on:keyup={searchHandler} id="input_search" class="input_search" type="text" placeholder="press / to search"/>
<div class="spacer"></div>
<button bind:this={btnReload} on:click={hashChange()} id="btn_reload"><i class="icon">refresh</i></button>
</div>
{#if loading}
<div class="spinner">
<Spinner></Spinner>
</div>
{/if}
<DirectoryElement bind:this={directoryElement}></DirectoryElement>
</div>
<style>
:global(#page_body) {
height: 100%;
padding: 0;
}
/* Override the menu button so it doesn't overlap the file manager when the menu
is collapsed */
:global(#button_toggle_navigation) {
display: none;
}
#file_manager {
position: absolute;
padding: 0;
background-color: var(--layer_2_color);
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
}
#nav_bar {
flex-shrink: 0;
display: flex;
flex-direction: row;
}
#nav_bar > button {
flex-shrink: 0;
}
.spacer {
width: 8px;
}
.breadcrumbs {
flex-grow: .7;
flex-shrink: 1;
min-width: 0;
}
.input_search {
flex-grow: .3;
flex-shrink: 1;
min-width: 100px;
}
.spinner {
position: absolute;
display: block;
margin: auto;
max-width: 100%;
max-height: 100%;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 100px;
height: 100px;
}
</style>