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`, {});
}
export async function update(settings: settings) {
export async function update(settings: ISettings) {
await fetchURL(`/api/settings`, {
method: "PUT",
body: JSON.stringify(settings),

View File

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

View File

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