Converted views/settings/Global.vue to composition api

This commit is contained in:
Joep 2023-09-09 21:40:51 +02:00
parent 194668c391
commit d1b21c8089
6 changed files with 263 additions and 172 deletions

View File

@ -4,7 +4,7 @@ export function get() {
return fetchJSON(`/api/settings`, {}); return fetchJSON(`/api/settings`, {});
} }
export async function update(settings: settings) { export async function update(settings: ISettings) {
await fetchURL(`/api/settings`, { await fetchURL(`/api/settings`, {
method: "PUT", method: "PUT",
body: JSON.stringify(settings), body: JSON.stringify(settings),

View File

@ -18,6 +18,7 @@ interface ApiOpts {
interface tusSettings { interface tusSettings {
retryCount: number; retryCount: number;
chunkSize: number;
} }
type algo = any; type algo = any;

73
frontend/src/types/settings.d.ts vendored Normal file
View File

@ -0,0 +1,73 @@
interface ISettings {
signup: boolean;
createUserDir: boolean;
userHomeBasePath: string;
defaults: Defaults;
rules: any[];
branding: SettingsBranding;
tus: SettingsTus;
shell: string[];
commands: SettingsCommand;
}
interface SettingsDefaults {
scope: string;
locale: string;
viewMode: string;
singleClick: boolean;
sorting: SettingsSorting;
perm: SettingsPerm;
commands: any[];
hideDotfiles: boolean;
dateFormat: boolean;
}
interface SettingsSorting {
by: string;
asc: boolean;
}
interface SettingsPerm {
admin: boolean;
execute: boolean;
create: boolean;
rename: boolean;
modify: boolean;
delete: boolean;
share: boolean;
download: boolean;
}
interface SettingsBranding {
name: string;
disableExternal: boolean;
disableUsedPercentage: boolean;
files: string;
theme: string;
color: string;
}
interface SettingsTus {
chunkSize: number;
retryCount: number;
}
interface SettingsCommand {
after_copy?: string[];
after_delete?: string[];
after_rename?: string[];
after_save?: string[];
after_upload?: string[];
before_copy?: string[];
before_delete?: string[];
before_rename?: string[];
before_save?: string[];
before_upload?: string[];
}
interface SettingsUnit {
KB: number;
MB: number;
GB: number;
TB: number;
}

1
frontend/src/types/toast.d.ts vendored Normal file
View File

@ -0,0 +1 @@
type TToast = (message: string) => void;

View File

@ -1,25 +1,25 @@
<template> <template>
<errors v-if="error" :errorCode="error.status" /> <errors v-if="error" :errorCode="error.status" />
<div class="row" v-else-if="!loading"> <div class="row" v-else-if="!layoutStore.loading && settings !== null">
<div class="column"> <div class="column">
<form class="card" @submit.prevent="save"> <form class="card" @submit.prevent="save">
<div class="card-title"> <div class="card-title">
<h2>{{ $t("settings.globalSettings") }}</h2> <h2>{{ t("settings.globalSettings") }}</h2>
</div> </div>
<div class="card-content"> <div class="card-content">
<p> <p>
<input type="checkbox" v-model="settings.signup" /> <input type="checkbox" v-model="settings.signup" />
{{ $t("settings.allowSignup") }} {{ t("settings.allowSignup") }}
</p> </p>
<p> <p>
<input type="checkbox" v-model="settings.createUserDir" /> <input type="checkbox" v-model="settings.createUserDir" />
{{ $t("settings.createUserDir") }} {{ t("settings.createUserDir") }}
</p> </p>
<div> <div>
<p class="small">{{ $t("settings.userHomeBasePath") }}</p> <p class="small">{{ t("settings.userHomeBasePath") }}</p>
<input <input
class="input input--block" class="input input--block"
type="text" type="text"
@ -27,22 +27,22 @@
/> />
</div> </div>
<h3>{{ $t("settings.rules") }}</h3> <h3>{{ t("settings.rules") }}</h3>
<p class="small">{{ $t("settings.globalRules") }}</p> <p class="small">{{ t("settings.globalRules") }}</p>
<rules v-model:rules="settings.rules" /> <rules v-model:rules="settings.rules" />
<div v-if="isExecEnabled"> <div v-if="enableExec">
<h3>{{ $t("settings.executeOnShell") }}</h3> <h3>{{ t("settings.executeOnShell") }}</h3>
<p class="small">{{ $t("settings.executeOnShellDescription") }}</p> <p class="small">{{ t("settings.executeOnShellDescription") }}</p>
<input <input
class="input input--block" class="input input--block"
type="text" type="text"
placeholder="bash -c, cmd /c, ..." placeholder="bash -c, cmd /c, ..."
v-model="settings.shell" v-model="shellValue"
/> />
</div> </div>
<h3>{{ $t("settings.branding") }}</h3> <h3>{{ t("settings.branding") }}</h3>
<i18n-t <i18n-t
keypath="settings.brandingHelp" keypath="settings.brandingHelp"
@ -54,7 +54,7 @@
class="link" class="link"
target="_blank" target="_blank"
href="https://filebrowser.org/configuration/custom-branding" href="https://filebrowser.org/configuration/custom-branding"
>{{ $t("settings.documentation") }}</a >{{ t("settings.documentation") }}</a
> >
</i18n-t> </i18n-t>
@ -64,7 +64,7 @@
v-model="settings.branding.disableExternal" v-model="settings.branding.disableExternal"
id="branding-links" id="branding-links"
/> />
{{ $t("settings.disableExternalLinks") }} {{ t("settings.disableExternalLinks") }}
</p> </p>
<p> <p>
@ -73,11 +73,11 @@
v-model="settings.branding.disableUsedPercentage" v-model="settings.branding.disableUsedPercentage"
id="branding-links" id="branding-links"
/> />
{{ $t("settings.disableUsedDiskPercentage") }} {{ t("settings.disableUsedDiskPercentage") }}
</p> </p>
<p> <p>
<label for="theme">{{ $t("settings.themes.title") }}</label> <label for="theme">{{ t("settings.themes.title") }}</label>
<themes <themes
class="input input--block" class="input input--block"
v-model:theme="settings.branding.theme" v-model:theme="settings.branding.theme"
@ -86,7 +86,7 @@
</p> </p>
<p> <p>
<label for="branding-name">{{ $t("settings.instanceName") }}</label> <label for="branding-name">{{ t("settings.instanceName") }}</label>
<input <input
class="input input--block" class="input input--block"
type="text" type="text"
@ -97,7 +97,7 @@
<p> <p>
<label for="branding-files">{{ <label for="branding-files">{{
$t("settings.brandingDirectoryPath") t("settings.brandingDirectoryPath")
}}</label> }}</label>
<input <input
class="input input--block" class="input input--block"
@ -107,14 +107,14 @@
/> />
</p> </p>
<h3>{{ $t("settings.tusUploads") }}</h3> <h3>{{ t("settings.tusUploads") }}</h3>
<p class="small">{{ $t("settings.tusUploadsHelp") }}</p> <p class="small">{{ t("settings.tusUploadsHelp") }}</p>
<div class="tusConditionalSettings"> <div class="tusConditionalSettings">
<p> <p>
<label for="tus-chunkSize">{{ <label for="tus-chunkSize">{{
$t("settings.tusUploadsChunkSize") t("settings.tusUploadsChunkSize")
}}</label> }}</label>
<input <input
class="input input--block" class="input input--block"
@ -126,7 +126,7 @@
<p> <p>
<label for="tus-retryCount">{{ <label for="tus-retryCount">{{
$t("settings.tusUploadsRetryCount") t("settings.tusUploadsRetryCount")
}}</label> }}</label>
<input <input
class="input input--block" class="input input--block"
@ -143,7 +143,7 @@
<input <input
class="button button--flat" class="button button--flat"
type="submit" type="submit"
:value="$t('buttons.update')" :value="t('buttons.update')"
/> />
</div> </div>
</form> </form>
@ -152,11 +152,11 @@
<div class="column"> <div class="column">
<form class="card" @submit.prevent="save"> <form class="card" @submit.prevent="save">
<div class="card-title"> <div class="card-title">
<h2>{{ $t("settings.userDefaults") }}</h2> <h2>{{ t("settings.userDefaults") }}</h2>
</div> </div>
<div class="card-content"> <div class="card-content">
<p class="small">{{ $t("settings.defaultUserDescription") }}</p> <p class="small">{{ t("settings.defaultUserDescription") }}</p>
<user-form <user-form
:isNew="false" :isNew="false"
@ -169,16 +169,16 @@
<input <input
class="button button--flat" class="button button--flat"
type="submit" type="submit"
:value="$t('buttons.update')" :value="t('buttons.update')"
/> />
</div> </div>
</form> </form>
</div> </div>
<div class="column"> <div class="column">
<form v-if="isExecEnabled" class="card" @submit.prevent="save"> <form v-if="enableExec" class="card" @submit.prevent="save">
<div class="card-title"> <div class="card-title">
<h2>{{ $t("settings.commandRunner") }}</h2> <h2>{{ t("settings.commandRunner") }}</h2>
</div> </div>
<div class="card-content"> <div class="card-content">
@ -194,24 +194,24 @@
class="link" class="link"
target="_blank" target="_blank"
href="https://filebrowser.org/configuration/command-runner" href="https://filebrowser.org/configuration/command-runner"
>{{ $t("settings.documentation") }}</a >{{ t("settings.documentation") }}</a
> >
</i18n-t> </i18n-t>
<div <div
v-for="command in settings.commands" v-for="(command, key) in settings.commands"
:key="command.name" :key="key"
class="collapsible" class="collapsible"
> >
<input :id="command.name" type="checkbox" /> <input :id="key" type="checkbox" />
<label :for="command.name"> <label :for="key">
<p>{{ capitalize(command.name) }}</p> <p>{{ capitalize(key) }}</p>
<i class="material-icons">arrow_drop_down</i> <i class="material-icons">arrow_drop_down</i>
</label> </label>
<div class="collapse"> <div class="collapse">
<textarea <textarea
class="input input--block input--textarea" class="input input--block input--textarea"
v-model.trim="command.value" v-model.trim="commandObject[key]"
></textarea> ></textarea>
</div> </div>
</div> </div>
@ -221,7 +221,7 @@
<input <input
class="button button--flat" class="button button--flat"
type="submit" type="submit"
:value="$t('buttons.update')" :value="t('buttons.update')"
/> />
</div> </div>
</form> </form>
@ -229,9 +229,7 @@
</div> </div>
</template> </template>
<script> <script setup lang="ts">
import { mapState, mapWritableState } from "pinia";
import { useAuthStore } from "@/stores/auth";
import { useLayoutStore } from "@/stores/layout"; import { useLayoutStore } from "@/stores/layout";
import { settings as api } from "@/api"; import { settings as api } from "@/api";
import { enableExec } from "@/utils/constants"; import { enableExec } from "@/utils/constants";
@ -239,128 +237,121 @@ import UserForm from "@/components/settings/UserForm.vue";
import Rules from "@/components/settings/Rules.vue"; import Rules from "@/components/settings/Rules.vue";
import Themes from "@/components/settings/Themes.vue"; import Themes from "@/components/settings/Themes.vue";
import Errors from "@/views/Errors.vue"; import Errors from "@/views/Errors.vue";
import { computed, inject, onBeforeUnmount, onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";
export default { const error = ref<any>(null);
name: "settings", const originalSettings = ref<ISettings | null>(null);
components: { const settings = ref<ISettings | null>(null);
Themes, const debounceTimeout = ref<number | null>(null);
UserForm,
Rules, const commandObject = ref<{
Errors, [key in keyof SettingsCommand]: string;
}, }>({});
data: function () { const shellValue = ref<string>("")
return {
error: null, const $showError = inject<TToast>("$showError") as TToast;
originalSettings: null, const $showSuccess = inject<TToast>("$showSuccess") as TToast;
settings: null,
debounceTimeout: null, const { t } = useI18n();
};
}, const layoutStore = useLayoutStore();
inject: ["$showError", "$showSuccess"],
computed: { const formattedChunkSize = computed({
...mapState(useAuthStore, ["user"]),
...mapWritableState(useLayoutStore, ["loading"]),
isExecEnabled: () => enableExec,
formattedChunkSize: {
get() { get() {
return this.formatBytes(this.settings.tus.chunkSize); return settings?.value?.tus?.chunkSize
? formatBytes(settings?.value?.tus?.chunkSize)
: "";
}, },
set(value) { set(value: any) {
// Use debouncing to allow the user to type freely without // Use debouncing to allow the user to type freely without
// interruption by the formatter // interruption by the formatter
// Clear the previous timeout if it exists // Clear the previous timeout if it exists
if (this.debounceTimeout) { if (debounceTimeout.value) {
clearTimeout(this.debounceTimeout); clearTimeout(debounceTimeout.value);
} }
// Set a new timeout to apply the format after a short delay // Set a new timeout to apply the format after a short delay
this.debounceTimeout = setTimeout(() => { debounceTimeout.value = setTimeout(() => {
this.settings.tus.chunkSize = this.parseBytes(value); if (settings.value) settings.value.tus.chunkSize = parseBytes(value);
}, 1500); }, 1500);
}, },
},
},
async created() {
try {
this.loading = true;
const original = await api.get();
let settings = { ...original, commands: [] };
for (const key in original.commands) {
settings.commands.push({
name: key,
value: original.commands[key].join("\n"),
}); });
}
settings.shell = settings.shell.join(" "); // Define funcs
const capitalize = (name: string, where: string | RegExp = "_") => {
this.originalSettings = original;
this.settings = settings;
} catch (e) {
this.error = e;
} finally {
this.loading = false;
}
},
methods: {
capitalize(name, where = "_") {
if (where === "caps") where = /(?=[A-Z])/; if (where === "caps") where = /(?=[A-Z])/;
let splitted = name.split(where); let splitted = name.split(where);
name = ""; name = "";
for (let i = 0; i < splitted.length; i++) { for (let i = 0; i < splitted.length; i++) {
name += name += splitted[i].charAt(0).toUpperCase() + splitted[i].slice(1) + " ";
splitted[i].charAt(0).toUpperCase() + splitted[i].slice(1) + " ";
} }
return name.slice(0, -1); return name.slice(0, -1);
}, };
async save() {
let settings = { const save = async () => {
...this.settings, if (settings.value === null) return false;
shell: this.settings.shell let newSettings: ISettings = {
...settings.value,
shell:
settings.value?.shell
.join(" ")
.trim() .trim()
.split(" ") .split(" ")
.filter((s) => s !== ""), .filter((s: string) => s !== "") ?? [],
commands: {}, commands: {},
}; };
for (const { name, value } of this.settings.commands) { // @ts-ignore
settings.commands[name] = value.split("\n").filter((cmd) => cmd !== ""); for (const name of Object.keys(settings.value.commands)) {
// @ts-ignore
const newValue = commandObject.value[name]
// @ts-ignore
if(name in commandObject.value && !Array.isArray(newValue)) {
// @ts-ignore
newSettings.commands[name] = newValue
.split("\n")
.filter((cmd: string) => cmd !== "");
} else {
// @ts-ignore
newSettings.commands[name] = newValue
} }
}
newSettings.shell = shellValue.value.split("\n");
try { try {
await api.update(settings); await api.update(newSettings);
this.$showSuccess(this.$t("settings.settingsUpdated")); $showSuccess(t("settings.settingsUpdated"));
} catch (e) { } catch (e: any) {
this.$showError(e); $showError(e);
} }
}, };
// Parse the user-friendly input (e.g., "20M" or "1T") to bytes // Parse the user-friendly input (e.g., "20M" or "1T") to bytes
parseBytes(input) { const parseBytes = (input: string) => {
const regex = /^(\d+)(\.\d+)?(B|K|KB|M|MB|G|GB|T|TB)?$/i; const regex = /^(\d+)(\.\d+)?(B|K|KB|M|MB|G|GB|T|TB)?$/i;
const matches = input.match(regex); const matches = input.match(regex);
if (matches) { if (matches) {
const size = parseFloat(matches[1].concat(matches[2] || "")); const size = parseFloat(matches[1].concat(matches[2] || ""));
let unit = matches[3].toUpperCase(); let unit: keyof SettingsUnit =
matches[3].toUpperCase() as keyof SettingsUnit;
if (!unit.endsWith("B")) { if (!unit.endsWith("B")) {
unit += "B"; unit += "B";
} }
const units = { const units: SettingsUnit = {
KB: 1024, KB: 1024,
MB: 1024 ** 2, MB: 1024 ** 2,
GB: 1024 ** 3, GB: 1024 ** 3,
TB: 1024 ** 4, TB: 1024 ** 4,
}; };
return size * (units[unit] || 1); return size * (units[unit as keyof SettingsUnit] || 1);
} else { } else {
return 1024 ** 2; return 1024 ** 2;
} }
}, };
// Format the chunk size in bytes to user-friendly format // Format the chunk size in bytes to user-friendly format
formatBytes(bytes) { const formatBytes = (bytes: number) => {
const units = ["B", "KB", "MB", "GB", "TB"]; const units = ["B", "KB", "MB", "GB", "TB"];
let size = bytes; let size = bytes;
let unitIndex = 0; let unitIndex = 0;
@ -369,13 +360,39 @@ export default {
unitIndex++; unitIndex++;
} }
return `${size}${units[unitIndex]}`; return `${size}${units[unitIndex]}`;
},
// Clear the debounce timeout when the component is destroyed
beforeUnmount() {
if (this.debounceTimeout) {
clearTimeout(this.debounceTimeout);
}
},
},
}; };
// Define Hooks
onMounted(async () => {
try {
layoutStore.loading = true;
const original: ISettings = await api.get();
let newSettings: ISettings = { ...original, commands: {} };
for (const key in original.commands) {
// @ts-ignore
newSettings.commands[key] = original.commands[key];
// @ts-ignore
commandObject.value[key] = original.commands[key].join("\n");
}
originalSettings.value = original;
settings.value = newSettings;
// @ts-ignore
shellValue.value = newSettings.shell.join("\n")
} catch (e) {
error.value = e;
} finally {
layoutStore.loading = false;
}
});
// Clear the debounce timeout when the component is destroyed
onBeforeUnmount(() => {
if (debounceTimeout.value) {
clearTimeout(debounceTimeout.value);
}
});
</script> </script>

View File

@ -1,5 +1,4 @@
{ {
"devDependencies": { "devDependencies": {
"@typescript-eslint/eslint-plugin": "^6.6.0"
} }
} }