feat: migrate to vue 3 (#2689)

---------

Co-authored-by: Joep <jcbuhre@gmail.com>
Co-authored-by: Omar Hussein <omarmohammad1951@gmail.com>
Co-authored-by: Oleg Lobanov <oleg@lobanov.me>
This commit is contained in:
kloon15
2024-04-01 17:18:22 +02:00
committed by GitHub
parent 0e3b35b30e
commit 5100e587d7
164 changed files with 12202 additions and 8047 deletions

View File

@@ -1,156 +1,129 @@
<template>
<div
id="editor-container"
@touchmove.prevent.stop
@wheel.prevent.stop
>
<div id="editor-container" @touchmove.prevent.stop @wheel.prevent.stop>
<header-bar>
<action icon="close" :label="$t('buttons.close')" @action="close()" />
<title>{{ req.name }}</title>
<action icon="close" :label="t('buttons.close')" @action="close()" />
<title>{{ fileStore.req?.name ?? "" }}</title>
<action
v-if="user.perm.modify"
v-if="authStore.user?.perm.modify"
id="save-button"
icon="save"
:label="$t('buttons.save')"
:label="t('buttons.save')"
@action="save()"
/>
</header-bar>
<breadcrumbs base="/files" noLink />
<Breadcrumbs base="/files" noLink />
<form id="editor"></form>
</div>
</template>
<script>
import { mapState } from "vuex";
<script setup lang="ts">
import { files as api } from "@/api";
import { theme } from "@/utils/constants";
import buttons from "@/utils/buttons";
import url from "@/utils/url";
import { version as ace_version } from "ace-builds";
import ace from "ace-builds/src-min-noconflict/ace.js";
import modelist from "ace-builds/src-min-noconflict/ext-modelist.js";
import ace, { Ace, version as ace_version } from "ace-builds";
import modelist from "ace-builds/src-noconflict/ext-modelist";
import "ace-builds/src-noconflict/ext-language_tools";
import HeaderBar from "@/components/header/HeaderBar.vue";
import Action from "@/components/header/Action.vue";
import Breadcrumbs from "@/components/Breadcrumbs.vue";
import { useAuthStore } from "@/stores/auth";
import { useFileStore } from "@/stores/file";
import { useLayoutStore } from "@/stores/layout";
import { inject, onBeforeUnmount, onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import { getTheme } from "@/utils/theme";
export default {
name: "editor",
components: {
HeaderBar,
Action,
Breadcrumbs,
},
data: function () {
return {};
},
computed: {
...mapState(["req", "user"]),
breadcrumbs() {
let parts = this.$route.path.split("/");
const $showError = inject<IToastError>("$showError")!;
if (parts[0] === "") {
parts.shift();
}
const fileStore = useFileStore();
const authStore = useAuthStore();
const layoutStore = useLayoutStore();
if (parts[parts.length - 1] === "") {
parts.pop();
}
const { t } = useI18n();
let breadcrumbs = [];
const route = useRoute();
const router = useRouter();
for (let i = 0; i < parts.length; i++) {
breadcrumbs.push({ name: decodeURIComponent(parts[i]) });
}
const editor = ref<Ace.Editor | null>(null);
breadcrumbs.shift();
onMounted(() => {
window.addEventListener("keydown", keyEvent);
if (breadcrumbs.length > 3) {
while (breadcrumbs.length !== 4) {
breadcrumbs.shift();
}
const fileContent = fileStore.req?.content || "";
breadcrumbs[0].name = "...";
}
ace.config.set(
"basePath",
`https://cdn.jsdelivr.net/npm/ace-builds@${ace_version}/src-min-noconflict/`
);
return breadcrumbs;
},
},
created() {
window.addEventListener("keydown", this.keyEvent);
},
beforeDestroy() {
window.removeEventListener("keydown", this.keyEvent);
this.editor.destroy();
},
mounted: function () {
const fileContent = this.req.content || "";
editor.value = ace.edit("editor", {
value: fileContent,
showPrintMargin: false,
readOnly: fileStore.req?.type === "textImmutable",
theme: "ace/theme/chrome",
mode: modelist.getModeForPath(fileStore.req?.name).mode,
wrap: true,
enableBasicAutocompletion: true,
enableLiveAutocompletion: true,
enableSnippets: true,
});
ace.config.set(
"basePath",
`https://cdn.jsdelivr.net/npm/ace-builds@${ace_version}/src-min-noconflict/`
);
if (getTheme() === "dark") {
editor.value!.setTheme("ace/theme/twilight");
}
this.editor = ace.edit("editor", {
value: fileContent,
showPrintMargin: false,
readOnly: this.req.type === "textImmutable",
theme: "ace/theme/chrome",
mode: modelist.getModeForPath(this.req.name).mode,
wrap: true,
});
editor.value.focus();
});
if (theme == "dark") {
this.editor.setTheme("ace/theme/twilight");
}
onBeforeUnmount(() => {
window.removeEventListener("keydown", keyEvent);
editor.value?.destroy();
});
this.editor.focus();
},
methods: {
keyEvent(event) {
if (event.code === "Escape") {
this.close();
}
const keyEvent = (event: KeyboardEvent) => {
if (event.code === "Escape") {
close();
}
if (!event.ctrlKey && !event.metaKey) {
return;
}
if (!event.ctrlKey && !event.metaKey) {
return;
}
if (String.fromCharCode(event.which).toLowerCase() !== "s") {
return;
}
if (event.key !== "s") {
return;
}
event.preventDefault();
this.save();
},
async save() {
const button = "save";
buttons.loading("save");
event.preventDefault();
save();
};
try {
await api.put(this.$route.path, this.editor.getValue());
this.editor.session.getUndoManager().markClean();
buttons.success(button);
} catch (e) {
buttons.done(button);
this.$showError(e);
}
},
close() {
if (!this.editor.session.getUndoManager().isClean()) {
this.$store.commit("showHover", "discardEditorChanges");
return;
}
const save = async () => {
const button = "save";
buttons.loading("save");
this.$store.commit("updateRequest", {});
try {
await api.put(route.path, editor.value?.getValue());
editor.value?.session.getUndoManager().markClean();
buttons.success(button);
} catch (e: any) {
buttons.done(button);
$showError(e);
}
};
const close = () => {
if (!editor.value?.session.getUndoManager().isClean()) {
layoutStore.showHover("discardEditorChanges");
return;
}
let uri = url.removeLastDir(this.$route.path) + "/";
this.$router.push({ path: uri });
},
},
fileStore.updateRequest(null);
let uri = url.removeLastDir(route.path) + "/";
router.push({ path: uri });
};
</script>

View File

@@ -0,0 +1,960 @@
<template>
<div>
<header-bar showMenu showLogo>
<search />
<title />
<action
class="search-button"
icon="search"
:label="t('buttons.search')"
@action="openSearch()"
/>
<template #actions>
<template v-if="!isMobile">
<action
v-if="headerButtons.share"
icon="share"
:label="t('buttons.share')"
show="share"
/>
<action
v-if="headerButtons.rename"
icon="mode_edit"
:label="t('buttons.rename')"
show="rename"
/>
<action
v-if="headerButtons.copy"
id="copy-button"
icon="content_copy"
:label="t('buttons.copyFile')"
show="copy"
/>
<action
v-if="headerButtons.move"
id="move-button"
icon="forward"
:label="t('buttons.moveFile')"
show="move"
/>
<action
v-if="headerButtons.delete"
id="delete-button"
icon="delete"
:label="t('buttons.delete')"
show="delete"
/>
</template>
<action
v-if="headerButtons.shell"
icon="code"
:label="t('buttons.shell')"
@action="layoutStore.toggleShell"
/>
<action
:icon="viewIcon"
:label="t('buttons.switchView')"
@action="switchView"
/>
<action
v-if="headerButtons.download"
icon="file_download"
:label="t('buttons.download')"
@action="download"
:counter="fileStore.selectedCount"
/>
<action
v-if="headerButtons.upload"
icon="file_upload"
id="upload-button"
:label="t('buttons.upload')"
@action="uploadFunc"
/>
<action icon="info" :label="t('buttons.info')" show="info" />
<action
icon="check_circle"
:label="t('buttons.selectMultiple')"
@action="toggleMultipleSelection"
/>
</template>
</header-bar>
<div v-if="isMobile" id="file-selection">
<span v-if="fileStore.selectedCount > 0"
>{{ fileStore.selectedCount }} selected</span
>
<action
v-if="headerButtons.share"
icon="share"
:label="t('buttons.share')"
show="share"
/>
<action
v-if="headerButtons.rename"
icon="mode_edit"
:label="t('buttons.rename')"
show="rename"
/>
<action
v-if="headerButtons.copy"
icon="content_copy"
:label="t('buttons.copyFile')"
show="copy"
/>
<action
v-if="headerButtons.move"
icon="forward"
:label="t('buttons.moveFile')"
show="move"
/>
<action
v-if="headerButtons.delete"
icon="delete"
:label="t('buttons.delete')"
show="delete"
/>
</div>
<div v-if="layoutStore.loading">
<h2 class="message delayed">
<div class="spinner">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
<span>{{ t("files.loading") }}</span>
</h2>
</div>
<template v-else>
<div
v-if="
(fileStore.req?.numDirs ?? 0) + (fileStore.req?.numFiles ?? 0) == 0
"
>
<h2 class="message">
<i class="material-icons">sentiment_dissatisfied</i>
<span>{{ t("files.lonely") }}</span>
</h2>
<input
style="display: none"
type="file"
id="upload-input"
@change="uploadInput($event)"
multiple
/>
<input
style="display: none"
type="file"
id="upload-folder-input"
@change="uploadInput($event)"
webkitdirectory
multiple
/>
</div>
<div
v-else
id="listing"
ref="listing"
class="file-icons"
:class="authStore.user?.viewMode ?? ''"
>
<div>
<div class="item header">
<div></div>
<div>
<p
:class="{ active: nameSorted }"
class="name"
role="button"
tabindex="0"
@click="sort('name')"
:title="t('files.sortByName')"
:aria-label="t('files.sortByName')"
>
<span>{{ t("files.name") }}</span>
<i class="material-icons">{{ nameIcon }}</i>
</p>
<p
:class="{ active: sizeSorted }"
class="size"
role="button"
tabindex="0"
@click="sort('size')"
:title="t('files.sortBySize')"
:aria-label="t('files.sortBySize')"
>
<span>{{ t("files.size") }}</span>
<i class="material-icons">{{ sizeIcon }}</i>
</p>
<p
:class="{ active: modifiedSorted }"
class="modified"
role="button"
tabindex="0"
@click="sort('modified')"
:title="t('files.sortByLastModified')"
:aria-label="t('files.sortByLastModified')"
>
<span>{{ t("files.lastModified") }}</span>
<i class="material-icons">{{ modifiedIcon }}</i>
</p>
</div>
</div>
</div>
<h2 v-if="fileStore.req?.numDirs ?? false">
{{ t("files.folders") }}
</h2>
<div v-if="fileStore.req?.numDirs ?? false">
<item
v-for="item in dirs"
:key="base64(item.name)"
v-bind:index="item.index"
v-bind:name="item.name"
v-bind:isDir="item.isDir"
v-bind:url="item.url"
v-bind:modified="item.modified"
v-bind:type="item.type"
v-bind:size="item.size"
v-bind:path="item.path"
>
</item>
</div>
<h2 v-if="fileStore.req?.numFiles ?? false">{{ t("files.files") }}</h2>
<div v-if="fileStore.req?.numFiles ?? false">
<item
v-for="item in files"
:key="base64(item.name)"
v-bind:index="item.index"
v-bind:name="item.name"
v-bind:isDir="item.isDir"
v-bind:url="item.url"
v-bind:modified="item.modified"
v-bind:type="item.type"
v-bind:size="item.size"
v-bind:path="item.path"
>
</item>
</div>
<input
style="display: none"
type="file"
id="upload-input"
@change="uploadInput($event)"
multiple
/>
<input
style="display: none"
type="file"
id="upload-folder-input"
@change="uploadInput($event)"
webkitdirectory
multiple
/>
<div :class="{ active: fileStore.multiple }" id="multiple-selection">
<p>{{ t("files.multipleSelectionEnabled") }}</p>
<div
@click="() => (fileStore.multiple = false)"
tabindex="0"
role="button"
:title="t('buttons.clear')"
:aria-label="t('buttons.clear')"
class="action"
>
<i class="material-icons">clear</i>
</div>
</div>
</div>
</template>
</div>
</template>
<script setup lang="ts">
import { useAuthStore } from "@/stores/auth";
import { useClipboardStore } from "@/stores/clipboard";
import { useFileStore } from "@/stores/file";
import { useLayoutStore } from "@/stores/layout";
import { users, files as api } from "@/api";
import { enableExec } from "@/utils/constants";
import * as upload from "@/utils/upload";
import css from "@/utils/css";
import throttle from "lodash/throttle";
import { Base64 } from "js-base64";
import HeaderBar from "@/components/header/HeaderBar.vue";
import Action from "@/components/header/Action.vue";
import Search from "@/components/Search.vue";
import Item from "@/components/files/ListingItem.vue";
import {
computed,
inject,
nextTick,
onBeforeUnmount,
onMounted,
ref,
watch,
} from "vue";
import { useRoute } from "vue-router";
import { useI18n } from "vue-i18n";
import { storeToRefs } from "pinia";
const showLimit = ref<number>(50);
const columnWidth = ref<number>(280);
const dragCounter = ref<number>(0);
const width = ref<number>(window.innerWidth);
const itemWeight = ref<number>(0);
const $showError = inject<IToastError>("$showError")!;
const clipboardStore = useClipboardStore();
const authStore = useAuthStore();
const fileStore = useFileStore();
const layoutStore = useLayoutStore();
const { req } = storeToRefs(fileStore);
const route = useRoute();
const { t } = useI18n();
const listing = ref<HTMLElement | null>(null);
const nameSorted = computed(() =>
fileStore.req ? fileStore.req.sorting.by === "name" : false
);
const sizeSorted = computed(() =>
fileStore.req ? fileStore.req.sorting.by === "size" : false
);
const modifiedSorted = computed(() =>
fileStore.req ? fileStore.req.sorting.by === "modified" : false
);
const ascOrdered = computed(() =>
fileStore.req ? fileStore.req.sorting.asc : false
);
const dirs = computed(() => items.value.dirs.slice(0, showLimit.value));
const items = computed(() => {
const dirs: any[] = [];
const files: any[] = [];
fileStore.req?.items.forEach((item) => {
if (item.isDir) {
dirs.push(item);
} else {
files.push(item);
}
});
return { dirs, files };
});
const files = computed((): Resource[] => {
let _showLimit = showLimit.value - items.value.dirs.length;
if (_showLimit < 0) _showLimit = 0;
return items.value.files.slice(0, _showLimit);
});
const nameIcon = computed(() => {
if (nameSorted.value && !ascOrdered.value) {
return "arrow_upward";
}
return "arrow_downward";
});
const sizeIcon = computed(() => {
if (sizeSorted.value && ascOrdered.value) {
return "arrow_downward";
}
return "arrow_upward";
});
const modifiedIcon = computed(() => {
if (modifiedSorted.value && ascOrdered.value) {
return "arrow_downward";
}
return "arrow_upward";
});
const viewIcon = computed(() => {
const icons = {
list: "view_module",
mosaic: "grid_view",
"mosaic gallery": "view_list",
};
return authStore.user === null
? icons["list"]
: icons[authStore.user.viewMode];
});
const headerButtons = computed(() => {
return {
upload: authStore.user?.perm.create,
download: authStore.user?.perm.download,
shell: authStore.user?.perm.execute && enableExec,
delete: fileStore.selectedCount > 0 && authStore.user?.perm.delete,
rename: fileStore.selectedCount === 1 && authStore.user?.perm.rename,
share: fileStore.selectedCount === 1 && authStore.user?.perm.share,
move: fileStore.selectedCount > 0 && authStore.user?.perm.rename,
copy: fileStore.selectedCount > 0 && authStore.user?.perm.create,
};
});
const isMobile = computed(() => {
return width.value <= 736;
});
watch(req, () => {
// Reset the show value
if (
window.sessionStorage.getItem("listFrozen") !== "true" &&
window.sessionStorage.getItem("modified") !== "true"
) {
showLimit.value = 50;
nextTick(() => {
// Ensures that the listing is displayed
// How much every listing item affects the window height
setItemWeight();
// Fill and fit the window with listing items
fillWindow(true);
});
}
if (req.value?.isDir) {
window.sessionStorage.setItem("listFrozen", "false");
window.sessionStorage.setItem("modified", "false");
}
});
onMounted(() => {
// Check the columns size for the first time.
colunmsResize();
// How much every listing item affects the window height
setItemWeight();
// Fill and fit the window with listing items
fillWindow(true);
// Add the needed event listeners to the window and document.
window.addEventListener("keydown", keyEvent);
window.addEventListener("scroll", scrollEvent);
window.addEventListener("resize", windowsResize);
if (!authStore.user?.perm.create) return;
document.addEventListener("dragover", preventDefault);
document.addEventListener("dragenter", dragEnter);
document.addEventListener("dragleave", dragLeave);
document.addEventListener("drop", drop);
});
onBeforeUnmount(() => {
// Remove event listeners before destroying this page.
window.removeEventListener("keydown", keyEvent);
window.removeEventListener("scroll", scrollEvent);
window.removeEventListener("resize", windowsResize);
if (authStore.user && !authStore.user?.perm.create) return;
document.removeEventListener("dragover", preventDefault);
document.removeEventListener("dragenter", dragEnter);
document.removeEventListener("dragleave", dragLeave);
document.removeEventListener("drop", drop);
});
const base64 = (name: string) => Base64.encodeURI(name);
const keyEvent = (event: KeyboardEvent) => {
// No prompts are shown
if (layoutStore.currentPrompt !== null) {
return;
}
if (event.key === "Escape") {
// Reset files selection.
fileStore.selected = [];
}
if (event.key === "Delete") {
if (!authStore.user?.perm.delete || fileStore.selectedCount == 0) return;
// Show delete prompt.
layoutStore.showHover("delete");
}
if (event.key === "F2") {
if (!authStore.user?.perm.rename || fileStore.selectedCount !== 1) return;
// Show rename prompt.
layoutStore.showHover("rename");
}
// Ctrl is pressed
if (!event.ctrlKey && !event.metaKey) {
return;
}
switch (event.key) {
case "f":
event.preventDefault();
layoutStore.showHover("search");
break;
case "c":
case "x":
copyCut(event);
break;
case "v":
paste(event);
break;
case "a":
event.preventDefault();
for (let file of items.value.files) {
if (fileStore.selected.indexOf(file.index) === -1) {
fileStore.selected.push(file.index);
}
}
for (let dir of items.value.dirs) {
if (fileStore.selected.indexOf(dir.index) === -1) {
fileStore.selected.push(dir.index);
}
}
break;
case "s":
event.preventDefault();
document.getElementById("download-button")?.click();
break;
}
};
const preventDefault = (event: Event) => {
// Wrapper around prevent default.
event.preventDefault();
};
const copyCut = (event: Event | KeyboardEvent): void => {
if ((event.target as HTMLElement).tagName?.toLowerCase() === "input") return;
if (fileStore.req === null) return;
let items = [];
for (let i of fileStore.selected) {
items.push({
from: fileStore.req.items[i].url,
name: fileStore.req.items[i].name,
});
}
if (items.length === 0) {
return;
}
clipboardStore.$patch({
key: (event as KeyboardEvent).key,
items,
path: route.path,
});
};
const paste = (event: Event) => {
if ((event.target as HTMLElement).tagName?.toLowerCase() === "input") return;
// TODO router location should it be
let items: any[] = [];
for (let item of clipboardStore.items) {
const from = item.from.endsWith("/") ? item.from.slice(0, -1) : item.from;
const to = route.path + encodeURIComponent(item.name);
items.push({ from, to, name: item.name });
}
if (items.length === 0) {
return;
}
let action = (overwrite: boolean, rename: boolean) => {
api
.copy(items, overwrite, rename)
.then(() => {
fileStore.reload = true;
})
.catch($showError);
};
if (clipboardStore.key === "x") {
action = (overwrite, rename) => {
api
.move(items, overwrite, rename)
.then(() => {
clipboardStore.resetClipboard();
fileStore.reload = true;
})
.catch($showError);
};
}
if (clipboardStore.path == route.path) {
action(false, true);
return;
}
let conflict = upload.checkConflict(items, fileStore.req!.items);
let overwrite = false;
let rename = false;
if (conflict) {
layoutStore.showHover({
prompt: "replace-rename",
confirm: (event: Event, option: string) => {
overwrite = option == "overwrite";
rename = option == "rename";
event.preventDefault();
layoutStore.closeHovers();
action(overwrite, rename);
},
});
return;
}
action(overwrite, rename);
};
const colunmsResize = () => {
// Update the columns size based on the window width.
let items_ = css(["#listing.mosaic .item", ".mosaic#listing .item"]);
if (items_ === null) return;
let columns = Math.floor(
(document.querySelector("main")?.offsetWidth ?? 0) / columnWidth.value
);
if (columns === 0) columns = 1;
// @ts-ignore never type error
items_.style.width = `calc(${100 / columns}% - 1em)`;
};
const scrollEvent = throttle(() => {
const totalItems =
(fileStore.req?.numDirs ?? 0) + (fileStore.req?.numFiles ?? 0);
// All items are displayed
if (showLimit.value >= totalItems) return;
const currentPos = window.innerHeight + window.scrollY;
// Trigger at the 75% of the window height
const triggerPos = document.body.offsetHeight - window.innerHeight * 0.25;
if (currentPos > triggerPos) {
// Quantity of items needed to fill 2x of the window height
const showQuantity = Math.ceil((window.innerHeight * 2) / itemWeight.value);
// Increase the number of displayed items
showLimit.value += showQuantity;
}
}, 100);
const dragEnter = () => {
dragCounter.value++;
// When the user starts dragging an item, put every
// file on the listing with 50% opacity.
let items = document.getElementsByClassName("item");
// @ts-ignore
Array.from(items).forEach((file: HTMLElement) => {
file.style.opacity = "0.5";
});
};
const dragLeave = () => {
dragCounter.value--;
if (dragCounter.value == 0) {
resetOpacity();
}
};
const drop = async (event: DragEvent) => {
event.preventDefault();
dragCounter.value = 0;
resetOpacity();
let dt = event.dataTransfer;
let el: HTMLElement | null = event.target as HTMLElement;
if (fileStore.req === null || dt === null || dt.files.length <= 0) return;
for (let i = 0; i < 5; i++) {
if (el !== null && !el.classList.contains("item")) {
el = el.parentElement;
}
}
let files: UploadList = (await upload.scanFiles(dt)) as UploadList;
let items = fileStore.req.items;
let path = route.path.endsWith("/") ? route.path : route.path + "/";
if (
el !== null &&
el.classList.contains("item") &&
el.dataset.dir === "true"
) {
// Get url from ListingItem instance
// TODO: Don't know what is happening here
path = el.__vue__.url;
try {
items = (await api.fetch(path)).items;
} catch (error: any) {
$showError(error);
}
}
let conflict = upload.checkConflict(files, items);
if (conflict) {
layoutStore.showHover({
prompt: "replace",
action: (event: Event) => {
event.preventDefault();
layoutStore.closeHovers();
upload.handleFiles(files, path, false);
},
confirm: (event: Event) => {
event.preventDefault();
layoutStore.closeHovers();
upload.handleFiles(files, path, true);
},
});
return;
}
upload.handleFiles(files, path);
};
const uploadInput = (event: Event) => {
layoutStore.closeHovers();
let files = (event.currentTarget as HTMLInputElement)?.files;
if (files === null) return;
let folder_upload = !!files[0].webkitRelativePath;
const uploadFiles: UploadList = [];
for (let i = 0; i < files.length; i++) {
const file = files[i];
const fullPath = folder_upload ? file.webkitRelativePath : undefined;
uploadFiles.push({
file,
name: file.name,
size: file.size,
isDir: false,
fullPath,
});
}
let path = route.path.endsWith("/") ? route.path : route.path + "/";
let conflict = upload.checkConflict(uploadFiles, fileStore.req!.items);
if (conflict) {
layoutStore.showHover({
prompt: "replace",
action: (event: Event) => {
event.preventDefault();
layoutStore.closeHovers();
upload.handleFiles(uploadFiles, path, false);
},
confirm: (event: Event) => {
event.preventDefault();
layoutStore.closeHovers();
upload.handleFiles(uploadFiles, path, true);
},
});
return;
}
upload.handleFiles(uploadFiles, path);
};
const resetOpacity = () => {
let items = document.getElementsByClassName("item");
Array.from(items).forEach((file: Element) => {
(file as HTMLElement).style.opacity = "1";
});
};
const sort = async (by: string) => {
let asc = false;
if (by === "name") {
if (nameIcon.value === "arrow_upward") {
asc = true;
}
} else if (by === "size") {
if (sizeIcon.value === "arrow_upward") {
asc = true;
}
} else if (by === "modified") {
if (modifiedIcon.value === "arrow_upward") {
asc = true;
}
}
try {
if (authStore.user?.id) {
// @ts-ignore
await users.update({ id: authStore.user?.id, sorting: { by, asc } }, [
"sorting",
]);
}
} catch (e: any) {
$showError(e);
}
fileStore.reload = true;
};
const openSearch = () => {
layoutStore.showHover("search");
};
const toggleMultipleSelection = () => {
fileStore.toggleMultiple();
layoutStore.closeHovers();
};
const windowsResize = throttle(() => {
colunmsResize();
width.value = window.innerWidth;
// Listing element is not displayed
if (listing.value == null) return;
// How much every listing item affects the window height
setItemWeight();
// Fill but not fit the window
fillWindow();
}, 100);
const download = () => {
if (fileStore.req === null) return;
if (
fileStore.selectedCount === 1 &&
!fileStore.req.items[fileStore.selected[0]].isDir
) {
api.download(null, fileStore.req.items[fileStore.selected[0]].url);
return;
}
layoutStore.showHover({
prompt: "download",
confirm: (format: any) => {
layoutStore.closeHovers();
let files = [];
if (fileStore.selectedCount > 0 && fileStore.req !== null) {
for (let i of fileStore.selected) {
files.push(fileStore.req.items[i].url);
}
} else {
files.push(route.path);
}
api.download(format, ...files);
},
});
};
const switchView = async () => {
layoutStore.closeHovers();
const modes = {
list: "mosaic",
mosaic: "mosaic gallery",
"mosaic gallery": "list",
};
const data = {
id: authStore.user?.id,
viewMode: modes[authStore.user?.viewMode ?? "list"] || "list",
};
// @ts-ignore
users.update(data, ["viewMode"]).catch($showError);
// @ts-ignore
authStore.updateUser(data);
setItemWeight();
fillWindow();
};
const uploadFunc = () => {
if (
typeof window.DataTransferItem !== "undefined" &&
typeof DataTransferItem.prototype.webkitGetAsEntry !== "undefined"
) {
layoutStore.showHover("upload");
} else {
document.getElementById("upload-input")?.click();
}
};
const setItemWeight = () => {
// Listing element is not displayed
if (listing.value === null || fileStore.req === null) return;
let itemQuantity = fileStore.req.numDirs + fileStore.req.numFiles;
if (itemQuantity > showLimit.value) itemQuantity = showLimit.value;
// How much every listing item affects the window height
itemWeight.value = listing.value.offsetHeight / itemQuantity;
};
const fillWindow = (fit = false) => {
if (fileStore.req === null) return;
const totalItems = fileStore.req.numDirs + fileStore.req.numFiles;
// More items are displayed than the total
if (showLimit.value >= totalItems && !fit) return;
const windowHeight = window.innerHeight;
// Quantity of items needed to fill 2x of the window height
const showQuantity = Math.ceil(
(windowHeight + windowHeight * 2) / itemWeight.value
);
// Less items to display than current
if (showLimit.value > showQuantity && !fit) return;
// Set the number of displayed items
showLimit.value = showQuantity > totalItems ? totalItems : showQuantity;
};
</script>

View File

@@ -1,897 +0,0 @@
<template>
<div>
<header-bar showMenu showLogo>
<search />
<title />
<action
class="search-button"
icon="search"
:label="$t('buttons.search')"
@action="openSearch()"
/>
<template #actions>
<template v-if="!isMobile">
<action
v-if="headerButtons.share"
icon="share"
:label="$t('buttons.share')"
show="share"
/>
<action
v-if="headerButtons.rename"
icon="mode_edit"
:label="$t('buttons.rename')"
show="rename"
/>
<action
v-if="headerButtons.copy"
id="copy-button"
icon="content_copy"
:label="$t('buttons.copyFile')"
show="copy"
/>
<action
v-if="headerButtons.move"
id="move-button"
icon="forward"
:label="$t('buttons.moveFile')"
show="move"
/>
<action
v-if="headerButtons.delete"
id="delete-button"
icon="delete"
:label="$t('buttons.delete')"
show="delete"
/>
</template>
<action
v-if="headerButtons.shell"
icon="code"
:label="$t('buttons.shell')"
@action="$store.commit('toggleShell')"
/>
<action
:icon="viewIcon"
:label="$t('buttons.switchView')"
@action="switchView"
/>
<action
v-if="headerButtons.download"
icon="file_download"
:label="$t('buttons.download')"
@action="download"
:counter="selectedCount"
/>
<action
v-if="headerButtons.upload"
icon="file_upload"
id="upload-button"
:label="$t('buttons.upload')"
@action="upload"
/>
<action icon="info" :label="$t('buttons.info')" show="info" />
<action
icon="check_circle"
:label="$t('buttons.selectMultiple')"
@action="toggleMultipleSelection"
/>
</template>
</header-bar>
<div v-if="isMobile" id="file-selection">
<span v-if="selectedCount > 0">{{ selectedCount }} selected</span>
<action
v-if="headerButtons.share"
icon="share"
:label="$t('buttons.share')"
show="share"
/>
<action
v-if="headerButtons.rename"
icon="mode_edit"
:label="$t('buttons.rename')"
show="rename"
/>
<action
v-if="headerButtons.copy"
icon="content_copy"
:label="$t('buttons.copyFile')"
show="copy"
/>
<action
v-if="headerButtons.move"
icon="forward"
:label="$t('buttons.moveFile')"
show="move"
/>
<action
v-if="headerButtons.delete"
icon="delete"
:label="$t('buttons.delete')"
show="delete"
/>
</div>
<div v-if="loading">
<h2 class="message delayed">
<div class="spinner">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
<span>{{ $t("files.loading") }}</span>
</h2>
</div>
<template v-else>
<div v-if="req.numDirs + req.numFiles == 0">
<h2 class="message">
<i class="material-icons">sentiment_dissatisfied</i>
<span>{{ $t("files.lonely") }}</span>
</h2>
<input
style="display: none"
type="file"
id="upload-input"
@change="uploadInput($event)"
multiple
/>
<input
style="display: none"
type="file"
id="upload-folder-input"
@change="uploadInput($event)"
webkitdirectory
multiple
/>
</div>
<div
v-else
id="listing"
ref="listing"
:class="user.viewMode + ' file-icons'"
>
<div>
<div class="item header">
<div></div>
<div>
<p
:class="{ active: nameSorted }"
class="name"
role="button"
tabindex="0"
@click="sort('name')"
:title="$t('files.sortByName')"
:aria-label="$t('files.sortByName')"
>
<span>{{ $t("files.name") }}</span>
<i class="material-icons">{{ nameIcon }}</i>
</p>
<p
:class="{ active: sizeSorted }"
class="size"
role="button"
tabindex="0"
@click="sort('size')"
:title="$t('files.sortBySize')"
:aria-label="$t('files.sortBySize')"
>
<span>{{ $t("files.size") }}</span>
<i class="material-icons">{{ sizeIcon }}</i>
</p>
<p
:class="{ active: modifiedSorted }"
class="modified"
role="button"
tabindex="0"
@click="sort('modified')"
:title="$t('files.sortByLastModified')"
:aria-label="$t('files.sortByLastModified')"
>
<span>{{ $t("files.lastModified") }}</span>
<i class="material-icons">{{ modifiedIcon }}</i>
</p>
</div>
</div>
</div>
<h2 v-if="req.numDirs > 0">{{ $t("files.folders") }}</h2>
<div v-if="req.numDirs > 0">
<item
v-for="item in dirs"
:key="base64(item.name)"
v-bind:index="item.index"
v-bind:name="item.name"
v-bind:isDir="item.isDir"
v-bind:url="item.url"
v-bind:modified="item.modified"
v-bind:type="item.type"
v-bind:size="item.size"
v-bind:path="item.path"
>
</item>
</div>
<h2 v-if="req.numFiles > 0">{{ $t("files.files") }}</h2>
<div v-if="req.numFiles > 0">
<item
v-for="item in files"
:key="base64(item.name)"
v-bind:index="item.index"
v-bind:name="item.name"
v-bind:isDir="item.isDir"
v-bind:url="item.url"
v-bind:modified="item.modified"
v-bind:type="item.type"
v-bind:size="item.size"
v-bind:path="item.path"
>
</item>
</div>
<input
style="display: none"
type="file"
id="upload-input"
@change="uploadInput($event)"
multiple
/>
<input
style="display: none"
type="file"
id="upload-folder-input"
@change="uploadInput($event)"
webkitdirectory
multiple
/>
<div :class="{ active: $store.state.multiple }" id="multiple-selection">
<p>{{ $t("files.multipleSelectionEnabled") }}</p>
<div
@click="$store.commit('multiple', false)"
tabindex="0"
role="button"
:title="$t('files.clear')"
:aria-label="$t('files.clear')"
class="action"
>
<i class="material-icons">clear</i>
</div>
</div>
</div>
</template>
</div>
</template>
<script>
import Vue from "vue";
import { mapState, mapGetters, mapMutations } from "vuex";
import { users, files as api } from "@/api";
import { enableExec } from "@/utils/constants";
import * as upload from "@/utils/upload";
import css from "@/utils/css";
import throttle from "lodash.throttle";
import HeaderBar from "@/components/header/HeaderBar.vue";
import Action from "@/components/header/Action.vue";
import Search from "@/components/Search.vue";
import Item from "@/components/files/ListingItem.vue";
export default {
name: "listing",
components: {
HeaderBar,
Action,
Search,
Item,
},
data: function () {
return {
showLimit: 50,
columnWidth: 280,
dragCounter: 0,
width: window.innerWidth,
itemWeight: 0,
};
},
computed: {
...mapState(["req", "selected", "user", "multiple", "selected", "loading"]),
...mapGetters(["selectedCount", "currentPrompt"]),
nameSorted() {
return this.req.sorting.by === "name";
},
sizeSorted() {
return this.req.sorting.by === "size";
},
modifiedSorted() {
return this.req.sorting.by === "modified";
},
ascOrdered() {
return this.req.sorting.asc;
},
items() {
const dirs = [];
const files = [];
this.req.items.forEach((item) => {
if (item.isDir) {
dirs.push(item);
} else {
files.push(item);
}
});
return { dirs, files };
},
dirs() {
return this.items.dirs.slice(0, this.showLimit);
},
files() {
let showLimit = this.showLimit - this.items.dirs.length;
if (showLimit < 0) showLimit = 0;
return this.items.files.slice(0, showLimit);
},
nameIcon() {
if (this.nameSorted && !this.ascOrdered) {
return "arrow_upward";
}
return "arrow_downward";
},
sizeIcon() {
if (this.sizeSorted && this.ascOrdered) {
return "arrow_downward";
}
return "arrow_upward";
},
modifiedIcon() {
if (this.modifiedSorted && this.ascOrdered) {
return "arrow_downward";
}
return "arrow_upward";
},
viewIcon() {
const icons = {
list: "view_module",
mosaic: "grid_view",
"mosaic gallery": "view_list",
};
return icons[this.user.viewMode];
},
headerButtons() {
return {
upload: this.user.perm.create,
download: this.user.perm.download,
shell: this.user.perm.execute && enableExec,
delete: this.selectedCount > 0 && this.user.perm.delete,
rename: this.selectedCount === 1 && this.user.perm.rename,
share: this.selectedCount === 1 && this.user.perm.share,
move: this.selectedCount > 0 && this.user.perm.rename,
copy: this.selectedCount > 0 && this.user.perm.create,
};
},
isMobile() {
return this.width <= 736;
},
},
watch: {
req: function () {
if (window.sessionStorage.getItem("listFrozen") !=="true" && window.sessionStorage.getItem("modified") !=="true"){
// Reset the show value
this.showLimit = 50;
// Ensures that the listing is displayed
Vue.nextTick(() => {
// How much every listing item affects the window height
this.setItemWeight();
// Fill and fit the window with listing items
this.fillWindow(true);
});
}
if (this.req.isDir) {
window.sessionStorage.setItem("listFrozen", "false");
window.sessionStorage.setItem("modified", "false");
}
},
},
mounted: function () {
// Check the columns size for the first time.
this.colunmsResize();
// How much every listing item affects the window height
this.setItemWeight();
// Fill and fit the window with listing items
this.fillWindow(true);
// Add the needed event listeners to the window and document.
window.addEventListener("keydown", this.keyEvent);
window.addEventListener("scroll", this.scrollEvent);
window.addEventListener("resize", this.windowsResize);
if (!this.user.perm.create) return;
document.addEventListener("dragover", this.preventDefault);
document.addEventListener("dragenter", this.dragEnter);
document.addEventListener("dragleave", this.dragLeave);
document.addEventListener("drop", this.drop);
},
beforeDestroy() {
// Remove event listeners before destroying this page.
window.removeEventListener("keydown", this.keyEvent);
window.removeEventListener("scroll", this.scrollEvent);
window.removeEventListener("resize", this.windowsResize);
if (this.user && !this.user.perm.create) return;
document.removeEventListener("dragover", this.preventDefault);
document.removeEventListener("dragenter", this.dragEnter);
document.removeEventListener("dragleave", this.dragLeave);
document.removeEventListener("drop", this.drop);
},
methods: {
...mapMutations(["updateUser", "addSelected"]),
base64: function (name) {
return window.btoa(unescape(encodeURIComponent(name)));
},
keyEvent(event) {
// No prompts are shown
if (this.currentPrompt !== null) {
return;
}
// Esc!
if (event.keyCode === 27) {
// Reset files selection.
this.$store.commit("resetSelected");
}
// Del!
if (event.keyCode === 46) {
if (!this.user.perm.delete || this.selectedCount == 0) return;
// Show delete prompt.
this.$store.commit("showHover", "delete");
}
// F2!
if (event.keyCode === 113) {
if (!this.user.perm.rename || this.selectedCount !== 1) return;
// Show rename prompt.
this.$store.commit("showHover", "rename");
}
// Ctrl is pressed
if (!event.ctrlKey && !event.metaKey) {
return;
}
let key = String.fromCharCode(event.which).toLowerCase();
switch (key) {
case "f":
event.preventDefault();
this.$store.commit("showHover", "search");
break;
case "c":
case "x":
this.copyCut(event, key);
break;
case "v":
this.paste(event);
break;
case "a":
event.preventDefault();
for (let file of this.items.files) {
if (this.$store.state.selected.indexOf(file.index) === -1) {
this.addSelected(file.index);
}
}
for (let dir of this.items.dirs) {
if (this.$store.state.selected.indexOf(dir.index) === -1) {
this.addSelected(dir.index);
}
}
break;
case "s":
event.preventDefault();
document.getElementById("download-button").click();
break;
}
},
preventDefault(event) {
// Wrapper around prevent default.
event.preventDefault();
},
copyCut(event, key) {
if (event.target.tagName.toLowerCase() === "input") {
return;
}
let items = [];
for (let i of this.selected) {
items.push({
from: this.req.items[i].url,
name: this.req.items[i].name,
});
}
if (items.length == 0) {
return;
}
this.$store.commit("updateClipboard", {
key: key,
items: items,
path: this.$route.path,
});
},
paste(event) {
if (event.target.tagName.toLowerCase() === "input") {
return;
}
let items = [];
for (let item of this.$store.state.clipboard.items) {
const from = item.from.endsWith("/")
? item.from.slice(0, -1)
: item.from;
const to = this.$route.path + encodeURIComponent(item.name);
items.push({ from, to, name: item.name });
}
if (items.length === 0) {
return;
}
let action = (overwrite, rename) => {
api
.copy(items, overwrite, rename)
.then(() => {
this.$store.commit("setReload", true);
})
.catch(this.$showError);
};
if (this.$store.state.clipboard.key === "x") {
action = (overwrite, rename) => {
api
.move(items, overwrite, rename)
.then(() => {
this.$store.commit("resetClipboard");
this.$store.commit("setReload", true);
})
.catch(this.$showError);
};
}
if (this.$store.state.clipboard.path == this.$route.path) {
action(false, true);
return;
}
let conflict = upload.checkConflict(items, this.req.items);
let overwrite = false;
let rename = false;
if (conflict) {
this.$store.commit("showHover", {
prompt: "replace-rename",
confirm: (event, option) => {
overwrite = option == "overwrite";
rename = option == "rename";
event.preventDefault();
this.$store.commit("closeHovers");
action(overwrite, rename);
},
});
return;
}
action(overwrite, rename);
},
colunmsResize() {
// Update the columns size based on the window width.
let items = css(["#listing.mosaic .item", ".mosaic#listing .item"]);
if (!items) return;
let columns = Math.floor(
document.querySelector("main").offsetWidth / this.columnWidth
);
if (columns === 0) columns = 1;
items.style.width = `calc(${100 / columns}% - 1em)`;
},
scrollEvent: throttle(function () {
const totalItems = this.req.numDirs + this.req.numFiles;
// All items are displayed
if (this.showLimit >= totalItems) return;
const currentPos = window.innerHeight + window.scrollY;
// Trigger at the 75% of the window height
const triggerPos = document.body.offsetHeight - window.innerHeight * 0.25;
if (currentPos > triggerPos) {
// Quantity of items needed to fill 2x of the window height
const showQuantity = Math.ceil(
(window.innerHeight * 2) / this.itemWeight
);
// Increase the number of displayed items
this.showLimit += showQuantity;
}
}, 100),
dragEnter() {
this.dragCounter++;
// When the user starts dragging an item, put every
// file on the listing with 50% opacity.
let items = document.getElementsByClassName("item");
Array.from(items).forEach((file) => {
file.style.opacity = 0.5;
});
},
dragLeave() {
this.dragCounter--;
if (this.dragCounter == 0) {
this.resetOpacity();
}
},
drop: async function (event) {
event.preventDefault();
this.dragCounter = 0;
this.resetOpacity();
let dt = event.dataTransfer;
let el = event.target;
if (dt.files.length <= 0) return;
for (let i = 0; i < 5; i++) {
if (el !== null && !el.classList.contains("item")) {
el = el.parentElement;
}
}
let files = await upload.scanFiles(dt);
let items = this.req.items;
let path = this.$route.path.endsWith("/")
? this.$route.path
: this.$route.path + "/";
if (
el !== null &&
el.classList.contains("item") &&
el.dataset.dir === "true"
) {
// Get url from ListingItem instance
path = el.__vue__.url;
try {
items = (await api.fetch(path)).items;
} catch (error) {
this.$showError(error);
}
}
let conflict = upload.checkConflict(files, items);
if (conflict) {
this.$store.commit("showHover", {
prompt: "replace",
action: (event) => {
event.preventDefault();
this.$store.commit("closeHovers");
upload.handleFiles(files, path, false);
},
confirm: (event) => {
event.preventDefault();
this.$store.commit("closeHovers");
upload.handleFiles(files, path, true);
},
});
return;
}
upload.handleFiles(files, path);
},
uploadInput(event) {
this.$store.commit("closeHovers");
let files = event.currentTarget.files;
let folder_upload =
files[0].webkitRelativePath !== undefined &&
files[0].webkitRelativePath !== "";
if (folder_upload) {
for (let i = 0; i < files.length; i++) {
let file = files[i];
files[i].fullPath = file.webkitRelativePath;
}
}
let path = this.$route.path.endsWith("/")
? this.$route.path
: this.$route.path + "/";
let conflict = upload.checkConflict(files, this.req.items);
if (conflict) {
this.$store.commit("showHover", {
prompt: "replace",
action: (event) => {
event.preventDefault();
this.$store.commit("closeHovers");
upload.handleFiles(files, path, false);
},
confirm: (event) => {
event.preventDefault();
this.$store.commit("closeHovers");
upload.handleFiles(files, path, true);
},
});
return;
}
upload.handleFiles(files, path);
},
resetOpacity() {
let items = document.getElementsByClassName("item");
Array.from(items).forEach((file) => {
file.style.opacity = 1;
});
},
async sort(by) {
let asc = false;
if (by === "name") {
if (this.nameIcon === "arrow_upward") {
asc = true;
}
} else if (by === "size") {
if (this.sizeIcon === "arrow_upward") {
asc = true;
}
} else if (by === "modified") {
if (this.modifiedIcon === "arrow_upward") {
asc = true;
}
}
try {
await users.update({ id: this.user.id, sorting: { by, asc } }, [
"sorting",
]);
} catch (e) {
this.$showError(e);
}
this.$store.commit("setReload", true);
},
openSearch() {
this.$store.commit("showHover", "search");
},
toggleMultipleSelection() {
this.$store.commit("multiple", !this.multiple);
this.$store.commit("closeHovers");
},
windowsResize: throttle(function () {
this.colunmsResize();
this.width = window.innerWidth;
// Listing element is not displayed
if (this.$refs.listing == null) return;
// How much every listing item affects the window height
this.setItemWeight();
// Fill but not fit the window
this.fillWindow();
}, 100),
download() {
if (this.selectedCount === 1 && !this.req.items[this.selected[0]].isDir) {
api.download(null, this.req.items[this.selected[0]].url);
return;
}
this.$store.commit("showHover", {
prompt: "download",
confirm: (format) => {
this.$store.commit("closeHovers");
let files = [];
if (this.selectedCount > 0) {
for (let i of this.selected) {
files.push(this.req.items[i].url);
}
} else {
files.push(this.$route.path);
}
api.download(format, ...files);
},
});
},
switchView: async function () {
this.$store.commit("closeHovers");
const modes = {
list: "mosaic",
mosaic: "mosaic gallery",
"mosaic gallery": "list",
};
const data = {
id: this.user.id,
viewMode: modes[this.user.viewMode] || "list",
};
users.update(data, ["viewMode"]).catch(this.$showError);
// Await ensures correct value for setItemWeight()
await this.$store.commit("updateUser", data);
this.setItemWeight();
this.fillWindow();
},
upload: function () {
if (
typeof window.DataTransferItem !== "undefined" &&
typeof DataTransferItem.prototype.webkitGetAsEntry !== "undefined"
) {
this.$store.commit("showHover", "upload");
} else {
document.getElementById("upload-input").click();
}
},
setItemWeight() {
// Listing element is not displayed
if (this.$refs.listing == null) return;
let itemQuantity = this.req.numDirs + this.req.numFiles;
if (itemQuantity > this.showLimit) itemQuantity = this.showLimit;
// How much every listing item affects the window height
this.itemWeight = this.$refs.listing.offsetHeight / itemQuantity;
},
fillWindow(fit = false) {
const totalItems = this.req.numDirs + this.req.numFiles;
// More items are displayed than the total
if (this.showLimit >= totalItems && !fit) return;
const windowHeight = window.innerHeight;
// Quantity of items needed to fill 2x of the window height
const showQuantity = Math.ceil(
(windowHeight + windowHeight * 2) / this.itemWeight
);
// Less items to display than current
if (this.showLimit > showQuantity && !fit) return;
// Set the number of displayed items
this.showLimit = showQuantity > totalItems ? totalItems : showQuantity;
},
},
};
</script>

View File

@@ -1,46 +1,46 @@
<template>
<div
id="previewer"
@touchmove.prevent.stop
@touchmove.prevent.stop
@wheel.prevent.stop
@mousemove="toggleNavigation"
@touchstart="toggleNavigation"
>
<header-bar v-if="showNav">
<header-bar v-if="showNav">
<action icon="close" :label="$t('buttons.close')" @action="close()" />
<title>{{ name }}</title>
<action
:disabled="loading"
v-if="isResizeEnabled && req.type === 'image'"
:disabled="layoutStore.loading"
v-if="isResizeEnabled && fileStore.req?.type === 'image'"
:icon="fullSize ? 'photo_size_select_large' : 'hd'"
@action="toggleSize"
/>
<template #actions>
<action
:disabled="loading"
v-if="user.perm.rename"
:disabled="layoutStore.loading"
v-if="authStore.user?.perm.rename"
icon="mode_edit"
:label="$t('buttons.rename')"
show="rename"
/>
<action
:disabled="loading"
v-if="user.perm.delete"
:disabled="layoutStore.loading"
v-if="authStore.user?.perm.delete"
icon="delete"
:label="$t('buttons.delete')"
@action="deleteFile"
id="delete-button"
/>
<action
:disabled="loading"
v-if="user.perm.download"
:disabled="layoutStore.loading"
v-if="authStore.user?.perm.download"
icon="file_download"
:label="$t('buttons.download')"
@action="download"
/>
<action
:disabled="loading"
:disabled="layoutStore.loading"
icon="info"
:label="$t('buttons.info')"
show="info"
@@ -48,7 +48,7 @@
</template>
</header-bar>
<div class="loading delayed" v-if="loading">
<div class="loading delayed" v-if="layoutStore.loading">
<div class="spinner">
<div class="bounce1"></div>
<div class="bounce2"></div>
@@ -57,41 +57,29 @@
</div>
<template v-else>
<div class="preview">
<ExtendedImage v-if="req.type == 'image'" :src="raw"></ExtendedImage>
<ExtendedImage v-if="fileStore.req?.type == 'image'" :src="raw" />
<audio
v-else-if="req.type == 'audio'"
v-else-if="fileStore.req?.type == 'audio'"
ref="player"
:src="raw"
controls
:autoplay="autoPlay"
@play="autoPlay = true"
></audio>
<video
v-else-if="req.type == 'video'"
<VideoPlayer
v-else-if="fileStore.req?.type == 'video'"
ref="player"
:src="raw"
controls
:autoplay="autoPlay"
@play="autoPlay = true"
:source="raw"
:subtitles="subtitles"
:options="videoOptions"
>
<track
kind="captions"
v-for="(sub, index) in subtitles"
:key="index"
:src="sub"
:label="'Subtitle ' + index"
:default="index === 0"
/>
Sorry, your browser doesn't support embedded videos, but don't worry,
you can <a :href="downloadUrl">download it</a>
and watch it with your favorite video player!
</video>
</VideoPlayer>
<object
v-else-if="req.extension.toLowerCase() == '.pdf'"
v-else-if="fileStore.req?.extension.toLowerCase() == '.pdf'"
class="pdf"
:data="raw"
></object>
<div v-else-if="req.type == 'blob'" class="info">
<div v-else-if="fileStore.req?.type == 'blob'" class="info">
<div class="title">
<i class="material-icons">feedback</i>
{{ $t("files.noPreview") }}
@@ -107,7 +95,7 @@
target="_blank"
:href="raw"
class="button button--flat"
v-if="!req.isDir"
v-if="!fileStore.req?.isDir"
>
<div>
<i class="material-icons">open_in_new</i
@@ -144,214 +132,215 @@
</div>
</template>
<script>
import { mapGetters, mapState } from "vuex";
<script setup lang="ts">
import { useAuthStore } from "@/stores/auth";
import { useFileStore } from "@/stores/file";
import { useLayoutStore } from "@/stores/layout";
import { files as api } from "@/api";
import { resizePreview } from "@/utils/constants";
import url from "@/utils/url";
import throttle from "lodash.throttle";
import throttle from "lodash/throttle";
import HeaderBar from "@/components/header/HeaderBar.vue";
import Action from "@/components/header/Action.vue";
import ExtendedImage from "@/components/files/ExtendedImage.vue";
import { computed, inject, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import VideoPlayer from "@/components/files/VideoPlayer.vue";
const mediaTypes = ["image", "video", "audio", "blob"];
const mediaTypes: ResourceType[] = ["image", "video", "audio", "blob"];
export default {
name: "preview",
components: {
HeaderBar,
Action,
ExtendedImage,
},
data: function () {
return {
previousLink: "",
nextLink: "",
listing: null,
name: "",
fullSize: false,
showNav: true,
navTimeout: null,
hoverNav: false,
autoPlay: false,
previousRaw: "",
nextRaw: "",
};
},
computed: {
...mapState(["req", "user", "oldReq", "jwt", "loading"]),
...mapGetters(["currentPrompt"]),
hasPrevious() {
return this.previousLink !== "";
},
hasNext() {
return this.nextLink !== "";
},
downloadUrl() {
return api.getDownloadURL(this.req);
},
raw() {
if (this.req.type === "image" && !this.fullSize) {
return api.getPreviewURL(this.req, "big");
}
const previousLink = ref<string>("");
const nextLink = ref<string>("");
const listing = ref<ResourceItem[] | null>(null);
const name = ref<string>("");
const fullSize = ref<boolean>(false);
const showNav = ref<boolean>(true);
const navTimeout = ref<null | number>(null);
const hoverNav = ref<boolean>(false);
const autoPlay = ref<boolean>(false);
const previousRaw = ref<string>("");
const nextRaw = ref<string>("");
return api.getDownloadURL(this.req, true);
},
showMore() {
return this.currentPrompt?.prompt === "more";
},
isResizeEnabled() {
return resizePreview;
},
subtitles() {
if (this.req.subtitles) {
return api.getSubtitlesURL(this.req);
}
return [];
},
},
watch: {
$route: function () {
this.updatePreview();
this.toggleNavigation();
},
},
async mounted() {
window.addEventListener("keydown", this.key);
this.listing = this.oldReq.items;
this.updatePreview();
},
beforeDestroy() {
window.removeEventListener("keydown", this.key);
},
methods: {
deleteFile() {
this.$store.commit("showHover", {
prompt: "delete",
confirm: () => {
this.listing = this.listing.filter((item) => item.name !== this.name);
const player = ref<HTMLVideoElement | HTMLAudioElement | null>(null);
if (this.hasNext) {
this.next();
} else if (!this.hasPrevious && !this.hasNext) {
this.close();
} else {
this.prev();
}
},
});
},
prev() {
this.hoverNav = false;
this.$router.replace({ path: this.previousLink });
},
next() {
this.hoverNav = false;
this.$router.replace({ path: this.nextLink });
},
key(event) {
if (this.currentPrompt !== null) {
const $showError = inject<IToastError>("$showError")!;
const authStore = useAuthStore();
const fileStore = useFileStore();
const layoutStore = useLayoutStore();
const route = useRoute();
const router = useRouter();
const hasPrevious = computed(() => previousLink.value !== "");
const hasNext = computed(() => nextLink.value !== "");
const downloadUrl = computed(() =>
fileStore.req ? api.getDownloadURL(fileStore.req, true) : ""
);
const raw = computed(() => {
if (fileStore.req?.type === "image" && !fullSize.value) {
return api.getPreviewURL(fileStore.req, "big");
}
return downloadUrl.value;
});
const isResizeEnabled = computed(() => resizePreview);
const subtitles = computed(() => {
if (fileStore.req?.subtitles) {
return api.getSubtitlesURL(fileStore.req);
}
return [];
});
const videoOptions = computed(() => {
return { autoplay: autoPlay.value };
});
watch(route, () => {
updatePreview();
toggleNavigation();
});
// Specify hooks
onMounted(async () => {
window.addEventListener("keydown", key);
if (fileStore.oldReq) {
listing.value = fileStore.oldReq.items;
updatePreview();
}
});
onBeforeUnmount(() => window.removeEventListener("keydown", key));
// Specify methods
const deleteFile = () => {
layoutStore.showHover({
prompt: "delete",
confirm: () => {
if (listing.value === null) {
return;
}
listing.value = listing.value.filter((item) => item.name !== name.value);
if (event.which === 13 || event.which === 39) {
// right arrow
if (this.hasNext) this.next();
} else if (event.which === 37) {
// left arrow
if (this.hasPrevious) this.prev();
} else if (event.which === 27) {
// esc
this.close();
if (hasNext.value) {
next();
} else if (!hasPrevious.value && !hasNext.value) {
close();
} else {
prev();
}
},
async updatePreview() {
if (
this.$refs.player &&
this.$refs.player.paused &&
!this.$refs.player.ended
) {
this.autoPlay = false;
}
let dirs = this.$route.fullPath.split("/");
this.name = decodeURIComponent(dirs[dirs.length - 1]);
if (!this.listing) {
try {
const path = url.removeLastDir(this.$route.path);
const res = await api.fetch(path);
this.listing = res.items;
} catch (e) {
this.$showError(e);
}
}
this.previousLink = "";
this.nextLink = "";
for (let i = 0; i < this.listing.length; i++) {
if (this.listing[i].name !== this.name) {
continue;
}
for (let j = i - 1; j >= 0; j--) {
if (mediaTypes.includes(this.listing[j].type)) {
this.previousLink = this.listing[j].url;
this.previousRaw = this.prefetchUrl(this.listing[j]);
break;
}
}
for (let j = i + 1; j < this.listing.length; j++) {
if (mediaTypes.includes(this.listing[j].type)) {
this.nextLink = this.listing[j].url;
this.nextRaw = this.prefetchUrl(this.listing[j]);
break;
}
}
return;
}
},
prefetchUrl(item) {
if (item.type !== "image") {
return "";
}
return this.fullSize
? api.getDownloadURL(item, true)
: api.getPreviewURL(item, "big");
},
openMore() {
this.$store.commit("showHover", "more");
},
resetPrompts() {
this.$store.commit("closeHovers");
},
toggleSize() {
this.fullSize = !this.fullSize;
},
toggleNavigation: throttle(function () {
this.showNav = true;
if (this.navTimeout) {
clearTimeout(this.navTimeout);
}
this.navTimeout = setTimeout(() => {
this.showNav = false || this.hoverNav;
this.navTimeout = null;
}, 1500);
}, 500),
close() {
this.$store.commit("updateRequest", {});
let uri = url.removeLastDir(this.$route.path) + "/";
this.$router.push({ path: uri });
},
download() {
window.open(this.downloadUrl);
},
},
});
};
const prev = () => {
hoverNav.value = false;
router.replace({ path: previousLink.value });
};
const next = () => {
hoverNav.value = false;
router.replace({ path: nextLink.value });
};
const key = (event: KeyboardEvent) => {
if (layoutStore.currentPrompt !== null) {
return;
}
if (event.which === 13 || event.which === 39) {
// right arrow
if (hasNext.value) next();
} else if (event.which === 37) {
// left arrow
if (hasPrevious.value) prev();
} else if (event.which === 27) {
// esc
close();
}
};
const updatePreview = async () => {
if (player.value && player.value.paused && !player.value.ended) {
autoPlay.value = false;
}
let dirs = route.fullPath.split("/");
name.value = decodeURIComponent(dirs[dirs.length - 1]);
if (!listing.value) {
try {
const path = url.removeLastDir(route.path);
const res = await api.fetch(path);
listing.value = res.items;
} catch (e: any) {
$showError(e);
}
}
previousLink.value = "";
nextLink.value = "";
if (listing.value) {
for (let i = 0; i < listing.value.length; i++) {
if (listing.value[i].name !== name.value) {
continue;
}
for (let j = i - 1; j >= 0; j--) {
if (mediaTypes.includes(listing.value[j].type)) {
previousLink.value = listing.value[j].url;
previousRaw.value = prefetchUrl(listing.value[j]);
break;
}
}
for (let j = i + 1; j < listing.value.length; j++) {
if (mediaTypes.includes(listing.value[j].type)) {
nextLink.value = listing.value[j].url;
nextRaw.value = prefetchUrl(listing.value[j]);
break;
}
}
return;
}
}
};
const prefetchUrl = (item: ResourceItem) => {
if (item.type !== "image") {
return "";
}
return fullSize.value
? api.getDownloadURL(item, true)
: api.getPreviewURL(item, "big");
};
const toggleSize = () => (fullSize.value = !fullSize.value);
const toggleNavigation = throttle(function () {
showNav.value = true;
if (navTimeout.value) {
clearTimeout(navTimeout.value);
}
navTimeout.value = setTimeout(() => {
showNav.value = false || hoverNav.value;
navTimeout.value = null;
}, 1500);
}, 500);
const close = () => {
fileStore.updateRequest(null);
let uri = url.removeLastDir(route.path) + "/";
router.push({ path: uri });
};
const download = () => window.open(downloadUrl.value);
</script>