convert quota and access prompts to composition api + ts (#3421)

This commit is contained in:
Kevin B. authored and GitHub committed 2026-11-20 16:10:18 -05:00
1 parent 65c667e397
commit 7d4f014aca
5 files changed
+614 -536

No files matched your search

+346 -336
View File
@@ -6,19 +6,19 @@
<template v-else>
<div v-if="!pathExists && baseEntries.length > 0 && !isEditingPath" class="warning-banner">
<i class="material-symbols-outlined">warning</i>
<span>{{ $t("messages.pathNotFoundMessage") }}</span>
<span>{{ t("messages.pathNotFoundMessage") }}</span>
<button type="button" class="button button--flat button--blue" @click="startPathReassignment">
{{ $t("messages.reassignPath") }}
{{ t("messages.reassignPath") }}
</button>
</div>
<div v-if="isEditingPath" :class="{ 'embedded-list': embedded }">
<file-list
<FileList
@update:selected="updateTempPath"
:browseSource="sourceName"
:browsePath="embedded ? currentPath : null"
:hideDestinationSource="true"
:showFiles="true"
></file-list>
></FileList>
</div>
<div v-else>
<PathPickerButton
@@ -29,7 +29,7 @@
aria-label="access-path"
:show-files="true"
:show-folders="true"
:placeholder="$t('sidebar.chooseSource')"
:placeholder="t('sidebar.chooseSource')"
@navigate="onPathPickerNavigate"
/>
<div v-if="!embedded" class="settings-items">
@@ -39,9 +39,9 @@
<div class="card item">
<div class="card-content banner-content">
<i class="material-symbols-outlined">{{ sourceDenyDefault ? 'do_not_disturb_on' : 'check_circle' }}</i>
{{ $t("access.defaultBehavior", { suffix: ":" }) }} {{ sourceDenyDefault ? $t("access.deny") : $t("access.allow")
{{ t("access.defaultBehavior", { suffix: ":" }) }} {{ sourceDenyDefault ? t("access.deny") : t("access.allow")
}}
<HelpTooltipIcon :text="$t('access.defaultBehaviorDescription')" />
<HelpTooltipIcon :text="t('access.defaultBehaviorDescription')" />
</div>
</div>
<div class="form-flex-group">
@@ -49,14 +49,14 @@
v-model="addType"
class="flat-right form-compact access-type"
:options="addTypeOptions"
:aria-label="$t('access.userGroup')"
:aria-label="t('access.userGroup')"
/>
<ExpandDropdown
v-if="addType !== 'all'"
v-model="addListType"
class="flat-right flat-left form-compact form-grow access-list"
:options="addListTypeOptions"
:aria-label="$t('access.allowDeny')"
:aria-label="t('access.allowDeny')"
/>
<EntityPickerButton
v-if="addType !== 'all'"
@@ -75,51 +75,54 @@
<!-- Cascade Delete Toggle -->
<div v-if="entries.length > 0" class="cascade-toggle-section settings-items">
<ToggleSwitch class="item" v-model="cascadeDelete"
:name="$t('access.cascadeDelete')"
:description="$t('access.cascadeDeleteDescription')" />
:name="t('access.cascadeDelete')"
:description="t('access.cascadeDeleteDescription')" />
</div>
<settings-table
<SettingsTable
v-if="entries.length > 0"
:columns="columns"
:items="tableRows"
:aria-label="$t('general.access')"
:aria-label="t('general.access')"
>
<template #cell-edit="{ row }">
<button type="button" @click="deleteAccess(row.entry)" class="action" :aria-label="$t('general.delete')"
:title="$t('general.delete')">
<button type="button" @click="deleteAccess(row.entry)" class="action" :aria-label="t('general.delete')"
:title="t('general.delete')">
<i class="material-symbols">delete</i>
</button>
</template>
</settings-table>
</SettingsTable>
</div>
</template>
</div>
<div class="card-actions" :class="{ 'embedded-actions': embedded }">
<template v-if="isEditingPath">
<button type="button" class="button button--flat button--grey" @click="cancelPathChange" :aria-label="$t('general.cancel')" :title="$t('general.cancel')">
{{ $t("general.cancel") }}
<button type="button" class="button button--flat button--grey" @click="cancelPathChange" :aria-label="t('general.cancel')" :title="t('general.cancel')">
{{ t("general.cancel") }}
</button>
<button type="button" class="button button--flat" @click="confirmPathChange" :aria-label="$t('general.ok')" :title="$t('general.ok')">
{{ $t("general.ok") }}
<button type="button" class="button button--flat" @click="confirmPathChange" :aria-label="t('general.ok')" :title="t('general.ok')">
{{ t("general.ok") }}
</button>
</template>
<template v-else>
<button v-if="!embedded" type="button" class="button button--flat button--grey" @click="cancelChanges" :aria-label="$t('general.cancel')" :title="$t('general.cancel')">
{{ $t("general.cancel") }}
<button v-if="!embedded" type="button" class="button button--flat button--grey" @click="cancelChanges" :aria-label="t('general.cancel')" :title="t('general.cancel')">
{{ t("general.cancel") }}
</button>
<button type="button" class="button button--flat" :disabled="!dirty || saving" @click="saveChanges" :aria-label="$t('general.save')" :title="$t('general.save')">
{{ $t("general.save") }}
<button type="button" class="button button--flat" :disabled="!dirty || saving" @click="saveChanges" :aria-label="t('general.save')" :title="t('general.save')">
{{ t("general.save") }}
</button>
</template>
</div>
</template>
<script>
<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { useI18n } from "@/i18n/index.ts";
import { notify } from "@/notify/index.ts";
import { mutations } from "@/store/index.ts";
import { accessApi } from "@/api/index.js";
import HelpTooltipIcon from "@/components/HelpTooltipIcon.vue";
import FileList from "../files/FileList.vue";
import type { SelectionPayload } from "../files/FileList.vue";
import ToggleSwitch from "@/components/settings/ToggleSwitch.vue";
import LoadingSpinner from "@/components/LoadingSpinner.vue";
import PathPickerButton from "@/components/files/PathPickerButton.vue";
@@ -129,319 +132,326 @@ import SettingsTable from "@/components/settings/Table.vue";
import EntityPickerButton from "@/components/settings/EntityPickerButton.vue";
import { activityViewerPresets } from "@/utils/activityViewerLink.js";
import { eventBus } from "@/store/eventBus.ts";
import type { AccessRule, AccessRuleCategory } from "@/store/types.ts";
export default {
name: "access",
components: {
HelpTooltipIcon,
FileList,
ToggleSwitch,
LoadingSpinner,
PathPickerButton,
ExpandDropdown,
ActivityViewerButton,
SettingsTable,
EntityPickerButton,
},
props: {
promptId: { type: [String, Number], default: null },
sourceName: { type: String, required: true },
path: { type: String, default: "/" },
embedded: { type: Boolean, default: false }
},
data() {
return {
loading: false,
isEditingPath: false,
isReassigningPath: false,
tempPath: this.path,
currentPath: this.path,
currentSource: this.sourceName,
tempSource: this.sourceName,
originalPath: this.path,
rule: { denyAll: false, deny: { users: [], groups: [] }, allow: { users: [], groups: [] } },
sourceDenyDefault: false,
pathExists: true,
addType: "user",
addListType: "deny",
cascadeDelete: false,
/** Staged rule edits; nothing is applied until Save. */
pendingAdds: [],
pendingDeletes: [],
saving: false
};
},
computed: {
addTypeOptions() {
return [
{ value: "user", label: this.$t("general.user") },
{ value: "group", label: this.$t("general.group") },
{ value: "all", label: this.$t("access.all") },
];
},
addListTypeOptions() {
return [
{ value: "deny", label: this.$t("access.deny") },
{ value: "allow", label: this.$t("access.allow") },
];
},
/** Entries persisted on the server (before staged edits). */
baseEntries() {
/** @type {{allow: boolean, type: "user" | "group" | "all", name: string}[]} */
const entries = [];
if (this.rule.denyAll) {
entries.push({ allow: false, type: "all", name: this.$t("access.all") });
}
for (const name of this.rule.deny?.users || []) {
entries.push({ allow: false, type: "user", name });
}
for (const name of this.rule.deny?.groups || []) {
entries.push({ allow: false, type: "group", name });
}
for (const name of this.rule.allow?.users || []) {
entries.push({ allow: true, type: "user", name });
}
for (const name of this.rule.allow?.groups || []) {
entries.push({ allow: true, type: "group", name });
}
return entries;
},
/** What the rule will look like once Save applies the staged edits. */
entries() {
const deleted = new Set(this.pendingDeletes.map(this.opKey));
const base = this.baseEntries.filter(e => !deleted.has(this.opKey({
allow: e.allow,
ruleCategory: e.type,
value: e.type === "all" ? "" : e.name,
})));
const staged = this.pendingAdds.map(op => ({
allow: op.allow,
type: op.ruleCategory,
name: op.ruleCategory === "all" ? this.$t("access.all") : op.value,
}));
return [...base, ...staged];
},
dirty() {
return this.pendingAdds.length > 0 || this.pendingDeletes.length > 0;
},
columns() {
return [
{ key: "allowDeny", label: this.$t("access.allowDeny"), sortable: true },
{ key: "userGroup", label: this.$t("access.userGroup"), sortable: true },
{ key: "name", label: this.$t("general.name"), sortable: true },
{ key: "edit", label: this.$t("general.edit"), narrow: true, align: "right" },
];
},
/** Names already present on the selected allow/deny list for the category (excluded from the picker). */
existingNames() {
return this.entries
.filter((e) => e.type === this.addType && e.allow === (this.addListType === "allow"))
.map((e) => e.name);
},
tableRows() {
return this.entries.map((entry) => ({
id: `${entry.type}-${entry.name}-${entry.allow ? "allow" : "deny"}`,
allowDeny: entry.allow ? this.$t("access.allow") : this.$t("access.deny"),
userGroup: entry.type === "user"
? this.$t("general.user")
: (entry.type === "group" ? this.$t("general.group") : this.$t("access.all")),
name: entry.name,
entry,
}));
},
parentPath() {
const trimmed = this.currentPath.replace(/\/+$/, "");
return trimmed.slice(0, trimmed.lastIndexOf("/")) || "/";
},
activityViewerHref() {
return activityViewerPresets.access(this.currentSource, this.currentPath);
},
},
async mounted() {
await this.fetchRule();
},
watch: {
sourceName(newSourceName) {
this.currentSource = newSourceName;
this.tempSource = newSourceName;
this.resetPending();
this.fetchRule();
},
path(newPath) {
this.currentPath = newPath;
this.tempPath = newPath;
this.isEditingPath = false;
this.resetPending();
this.fetchRule();
}
},
methods: {
async onPathPickerNavigate() {
this.resetPending();
await this.fetchRule();
eventBus.emit("accessRulesChanged");
},
/**
* @param {{path: string, source: string}} pathOrData
*/
updateTempPath(pathOrData) {
if (pathOrData?.path) {
this.tempPath = pathOrData.path;
this.tempSource = pathOrData.source;
}
},
async confirmPathChange() {
if (this.isReassigningPath) {
// Reassigning path - call API to update
try {
await accessApi.updatePath(this.currentSource, this.originalPath, this.tempPath);
notify.showSuccessToast(this.$t("messages.pathReassigned"));
this.originalPath = this.tempPath;
this.currentPath = this.tempPath;
this.currentSource = this.tempSource;
this.pathExists = true;
this.isEditingPath = false;
this.isReassigningPath = false;
await this.fetchRule();
// Emit event to refresh access rules list
eventBus.emit('accessRulesChanged');
} catch (e) {
notify.showError(this.$t("messages.pathReassignFailed"));
console.error(e);
}
} else {
// Just viewing a different path
this.currentPath = this.tempPath;
this.currentSource = this.tempSource;
this.isEditingPath = false;
this.resetPending();
await this.fetchRule();
}
},
cancelPathChange() {
this.isEditingPath = false;
this.isReassigningPath = false;
},
startPathReassignment() {
this.isReassigningPath = true;
this.tempPath = this.currentPath;
this.isEditingPath = true;
},
async fetchRule() {
this.loading = true;
try {
const response = await accessApi.get(this.currentSource, this.currentPath);
// Handle new API response structure - now sourceDenyDefault is part of the rule
this.rule = response;
this.sourceDenyDefault = response.sourceDenyDefault || false;
this.pathExists = response.pathExists !== false;
} catch (_e) {
this.rule = { denyAll: false, deny: { users: [], groups: [] }, allow: { users: [], groups: [] } };
this.sourceDenyDefault = false;
this.pathExists = true;
} finally {
this.loading = false;
}
},
resetPending() {
this.pendingAdds = [];
this.pendingDeletes = [];
},
/** Stable key for matching entries to staged ops. */
opKey(op) {
return `${op.allow ? "allow" : "deny"}|${op.ruleCategory}|${op.value}`;
},
/**
* Stages a delete. Pending adds are simply un-staged; persisted
* entries get a delete op applied on Save.
* @param {{allow: boolean, type: string, name: string}} entry
*/
deleteAccess(entry) {
const op = {
allow: entry.allow,
ruleCategory: entry.type,
value: entry.type === 'all' ? '' : entry.name,
cascade: this.cascadeDelete && entry.type !== 'all'
};
const pendingIdx = this.pendingAdds.findIndex(a => this.opKey(a) === this.opKey(op));
if (pendingIdx !== -1) {
this.pendingAdds.splice(pendingIdx, 1);
return;
}
this.pendingDeletes.push(op);
},
/**
* Stages rule entries. `names` are picked users/groups; for the 'all'
* category an empty list stages the single deny-all entry.
* @param {string[]} names
*/
addEntries(names) {
const values = this.addType === 'all' ? [''] : names;
for (const value of values) {
const op = {
allow: this.addListType === 'allow' && this.addType !== 'all',
ruleCategory: this.addType,
value
};
// Re-adding a staged-for-delete entry just cancels the delete.
const delIdx = this.pendingDeletes.findIndex(d => this.opKey(d) === this.opKey(op));
if (delIdx !== -1) {
this.pendingDeletes.splice(delIdx, 1);
continue;
}
if (this.pendingAdds.some(a => this.opKey(a) === this.opKey(op))) {
continue;
}
// Same name on the opposite list (allow vs deny) is allowed by the backend.
this.pendingAdds.push(op);
}
},
/** Applies staged deletes then adds; keeps unapplied ops on failure. */
async saveChanges() {
if (this.saving) return;
this.saving = true;
let failed = false;
try {
for (const op of this.pendingDeletes.slice()) {
await accessApi.del(this.currentSource, this.currentPath, {
allow: op.allow,
ruleCategory: op.ruleCategory,
value: op.value,
cascade: op.cascade
});
this.pendingDeletes.splice(this.pendingDeletes.indexOf(op), 1);
}
for (const op of this.pendingAdds.slice()) {
await accessApi.add(this.currentSource, this.currentPath, {
allow: op.allow,
ruleCategory: op.ruleCategory,
value: op.value
});
this.pendingAdds.splice(this.pendingAdds.indexOf(op), 1);
}
} catch (e) {
failed = true;
notify.showError(e);
console.error(e);
}
await this.fetchRule();
// Emit event to refresh access rules list
eventBus.emit('accessRulesChanged');
this.saving = false;
if (!failed && this.embedded) {
notify.showSuccessToast(this.$t("settings.settingsUpdated"));
}
if (!this.dirty && !this.embedded) {
mutations.closeTopPrompt(this.promptId ?? undefined);
}
},
cancelChanges() {
this.pendingAdds = [];
this.pendingDeletes = [];
mutations.closeTopPrompt(this.promptId ?? undefined);
},
type AccessListType = "allow" | "deny";
interface AccessEntry {
allow: boolean;
type: AccessRuleCategory;
name: string;
}
interface AccessOp {
allow: boolean;
ruleCategory: AccessRuleCategory;
value: string;
cascade?: boolean;
}
interface TableColumn {
key: string;
label: string;
sortable?: boolean;
narrow?: boolean;
align?: "left" | "center" | "right";
}
const props = withDefaults(
defineProps<{
promptId?: number | null;
sourceName: string;
path?: string;
embedded?: boolean;
}>(),
{
promptId: null,
path: "/",
embedded: false,
}
};
);
const { t } = useI18n();
function emptyRule(): AccessRule {
return {
denyAll: false,
deny: { users: [], groups: [] },
allow: { users: [], groups: [] },
sourceDenyDefault: false,
pathExists: true,
};
}
const loading = ref(false);
const isEditingPath = ref(false);
const isReassigningPath = ref(false);
const tempPath = ref(props.path);
const currentPath = ref(props.path);
const currentSource = ref(props.sourceName);
const tempSource = ref(props.sourceName);
const originalPath = ref(props.path);
const rule = ref<AccessRule>(emptyRule());
const addType = ref<AccessRuleCategory>("user");
const addListType = ref<AccessListType>("deny");
const cascadeDelete = ref(false);
const pendingAdds = ref<AccessOp[]>([]);
const pendingDeletes = ref<AccessOp[]>([]);
const saving = ref(false);
const addTypeOptions = computed<{ value: AccessRuleCategory; label: string }[]>(() => [
{ value: "user", label: t("general.user") },
{ value: "group", label: t("general.group") },
{ value: "all", label: t("access.all") },
]);
const addListTypeOptions = computed<{ value: AccessListType; label: string }[]>(() => [
{ value: "deny", label: t("access.deny") },
{ value: "allow", label: t("access.allow") },
]);
/** Entries persisted on the server (before staged edits). */
const baseEntries = computed(() => {
const entries: AccessEntry[] = [];
if (rule.value.denyAll) {
entries.push({ allow: false, type: "all", name: t("access.all") });
}
for (const name of rule.value.deny.users) {
entries.push({ allow: false, type: "user", name });
}
for (const name of rule.value.deny.groups) {
entries.push({ allow: false, type: "group", name });
}
for (const name of rule.value.allow.users) {
entries.push({ allow: true, type: "user", name });
}
for (const name of rule.value.allow.groups) {
entries.push({ allow: true, type: "group", name });
}
return entries;
});
/** What the rule will look like once Save applies the staged edits. */
const entries = computed(() => {
const deleted = new Set(pendingDeletes.value.map(opKey));
const base = baseEntries.value.filter(e => !deleted.has(opKey({
allow: e.allow,
ruleCategory: e.type,
value: e.type === "all" ? "" : e.name,
})));
const staged = pendingAdds.value.map((op): AccessEntry => ({
allow: op.allow,
type: op.ruleCategory,
name: op.ruleCategory === "all" ? t("access.all") : op.value,
}));
return [...base, ...staged];
});
const sourceDenyDefault = computed(() => rule.value.sourceDenyDefault);
const pathExists = computed(() => rule.value.pathExists);
const dirty = computed(() => pendingAdds.value.length > 0 || pendingDeletes.value.length > 0);
const columns = computed<TableColumn[]>(() => [
{ key: "allowDeny", label: t("access.allowDeny"), sortable: true },
{ key: "userGroup", label: t("access.userGroup"), sortable: true },
{ key: "name", label: t("general.name"), sortable: true },
{ key: "edit", label: t("general.edit"), narrow: true, align: "right" },
]);
/** Names already present on the selected allow/deny list for the category (excluded from the picker). */
const existingNames = computed(() =>
entries.value
.filter((e) => e.type === addType.value && e.allow === (addListType.value === "allow"))
.map((e) => e.name)
);
const tableRows = computed(() =>
entries.value.map((entry) => ({
id: `${entry.type}-${entry.name}-${entry.allow ? "allow" : "deny"}`,
allowDeny: entry.allow ? t("access.allow") : t("access.deny"),
userGroup: entry.type === "user"
? t("general.user")
: (entry.type === "group" ? t("general.group") : t("access.all")),
name: entry.name,
entry,
}))
);
const activityViewerHref = computed(() => activityViewerPresets.access(currentSource.value, currentPath.value));
onMounted(fetchRule);
watch(() => props.sourceName, (newSourceName) => {
currentSource.value = newSourceName;
tempSource.value = newSourceName;
resetPending();
fetchRule();
});
watch(() => props.path, (newPath) => {
currentPath.value = newPath;
tempPath.value = newPath;
isEditingPath.value = false;
resetPending();
fetchRule();
});
async function onPathPickerNavigate() {
resetPending();
await fetchRule();
eventBus.emit("accessRulesChanged");
}
function updateTempPath(payload: SelectionPayload) {
if (payload.path) {
tempPath.value = payload.path;
tempSource.value = payload.source ?? tempSource.value;
}
}
async function confirmPathChange() {
if (isReassigningPath.value) {
// Reassigning path - call API to update
try {
await accessApi.updatePath(currentSource.value, originalPath.value, tempPath.value);
notify.showSuccessToast(t("messages.pathReassigned"));
originalPath.value = tempPath.value;
currentPath.value = tempPath.value;
currentSource.value = tempSource.value;
isEditingPath.value = false;
isReassigningPath.value = false;
await fetchRule();
// Emit event to refresh access rules list
eventBus.emit("accessRulesChanged");
} catch (e) {
notify.showError(t("messages.pathReassignFailed"));
console.error(e);
}
} else {
// Just viewing a different path
currentPath.value = tempPath.value;
currentSource.value = tempSource.value;
isEditingPath.value = false;
resetPending();
await fetchRule();
}
}
function cancelPathChange() {
isEditingPath.value = false;
isReassigningPath.value = false;
}
function startPathReassignment() {
isReassigningPath.value = true;
tempPath.value = currentPath.value;
isEditingPath.value = true;
}
async function fetchRule() {
loading.value = true;
try {
const response: AccessRule = await accessApi.get(currentSource.value, currentPath.value);
// Handle new API response structure - now sourceDenyDefault is part of the rule
rule.value = response;
} catch {
rule.value = emptyRule();
} finally {
loading.value = false;
}
}
function resetPending() {
pendingAdds.value = [];
pendingDeletes.value = [];
}
/** Stable key for matching entries to staged ops. */
function opKey(op: Pick<AccessOp, "allow" | "ruleCategory" | "value">) {
return `${op.allow ? "allow" : "deny"}|${op.ruleCategory}|${op.value}`;
}
/**
* Stages a delete. Pending adds are simply un-staged; persisted
* entries get a delete op applied on Save.
*/
function deleteAccess(entry: AccessEntry) {
const op: AccessOp = {
allow: entry.allow,
ruleCategory: entry.type,
value: entry.type === "all" ? "" : entry.name,
cascade: cascadeDelete.value && entry.type !== "all"
};
const pendingIdx = pendingAdds.value.findIndex(a => opKey(a) === opKey(op));
if (pendingIdx !== -1) {
pendingAdds.value.splice(pendingIdx, 1);
return;
}
pendingDeletes.value.push(op);
}
/**
* Stages rule entries. `names` are picked users/groups; for the 'all'
* category an empty list stages the single deny-all entry.
*/
function addEntries(names: string[]) {
const values = addType.value === "all" ? [""] : names;
for (const value of values) {
const op: AccessOp = {
allow: addListType.value === "allow" && addType.value !== "all",
ruleCategory: addType.value,
value
};
// Re-adding a staged-for-delete entry just cancels the delete.
const delIdx = pendingDeletes.value.findIndex(d => opKey(d) === opKey(op));
if (delIdx !== -1) {
pendingDeletes.value.splice(delIdx, 1);
continue;
}
if (pendingAdds.value.some(a => opKey(a) === opKey(op))) {
continue;
}
// Same name on the opposite list (allow vs deny) is allowed by the backend.
pendingAdds.value.push(op);
}
}
/** Applies staged deletes then adds; keeps unapplied ops on failure. */
async function saveChanges() {
if (saving.value) return;
saving.value = true;
let failed = false;
try {
for (const op of pendingDeletes.value.slice()) {
await accessApi.del(currentSource.value, currentPath.value, {
allow: op.allow,
ruleCategory: op.ruleCategory,
value: op.value,
cascade: op.cascade
});
pendingDeletes.value.splice(pendingDeletes.value.indexOf(op), 1);
}
for (const op of pendingAdds.value.slice()) {
await accessApi.add(currentSource.value, currentPath.value, {
allow: op.allow,
ruleCategory: op.ruleCategory,
value: op.value
});
pendingAdds.value.splice(pendingAdds.value.indexOf(op), 1);
}
} catch (e) {
failed = true;
notify.showError(e);
console.error(e);
}
await fetchRule();
// Emit event to refresh access rules list
eventBus.emit("accessRulesChanged");
saving.value = false;
if (!failed && props.embedded) {
notify.showSuccessToast(t("settings.settingsUpdated"));
}
if (!dirty.value && !props.embedded) {
mutations.closeTopPrompt(props.promptId ?? undefined);
}
}
function cancelChanges() {
resetPending();
mutations.closeTopPrompt(props.promptId ?? undefined);
}
</script>
<style scoped>
+1 -9
View File
@@ -91,7 +91,6 @@
</div>
<div v-if="quotaEnabled" class="info-quota-usage">
<QuotaFolderBar
class="info-quota-bar"
:source="source"
:path="filePath"
:enabled="true"
@@ -159,7 +158,7 @@ import { copyToClipboard } from "@/utils/clipboard.js";
import { formatDuration } from "@/utils/files.js";
import { resourcesApi, quotasApi, mediaApi } from "@/api/index.js";
import { getters, mutations, state } from "@/store/index.ts";
import type { InfoItem, SubtitleTrack } from "@/store/types.ts";
import type { InfoItem, QuotaSnapshot, SubtitleTrack } from "@/store/types.ts";
import { notify } from "@/notify/index.ts";
import { activityViewerPresets } from "@/utils/activityViewerLink.js";
import SlidingTabs from "@/components/settings/SlidingTabs.vue";
@@ -172,13 +171,6 @@ import Access from "@/components/prompts/Access.vue";
type InfoTab = "basic" | "media" | "quota" | "access" | "additional" | "checksums";
type HashAlgo = "md5" | "sha1" | "sha256" | "sha512";
interface QuotaSnapshot {
usedBytes?: number;
reservedBytes?: number;
measurementStatus?: string;
limitBytes?: number;
}
interface InfoRow {
key: string;
label: string;
+191 -154
View File
@@ -18,39 +18,65 @@
<ToggleSwitch
class="item"
v-model="enabled"
:name="$t('general.limit')"
:description="$t('quotas.folderDescription')"
:name="t('general.limit')"
:description="t('quotas.folderDescription')"
/>
</div>
<div v-if="enabled">
<ExpandDropdown
v-model="meter"
:options="meterOptions"
:aria-label="$t('quotas.usageCounting')"
:aria-label="t('quotas.usageCounting')"
/>
<p v-if="indexingDisabled" class="quota-help">{{ $t("quotas.indexingDisabledMeterHint") }}</p>
<p v-if="indexingDisabled" class="quota-help">{{ t("quotas.indexingDisabledMeterHint") }}</p>
<p v-else-if="measurementHelp" class="quota-help">{{ measurementHelp }}</p>
<p>{{ $t("general.limit") }}</p>
<p>{{ t("general.limit") }}</p>
<div class="quota-custom-row">
<QuotaCustomLimitInput
v-model:amount="customAmount"
v-model:unit="customUnit"
:aria-label="$t('general.limit')"
:aria-label="t('general.limit')"
/>
</div>
</div>
</div>
<div class="card-actions">
<button type="button" class="button button--flat button--grey" @click="close">{{ $t("general.cancel") }}</button>
<button v-if="quotaExists" type="button" class="button button--flat button--red" @click="removeQuota">
{{ $t("general.remove") }}
<button
type="button"
class="button button--flat button--grey"
:aria-label="t('general.cancel')"
:title="t('general.cancel')"
@click="close"
>
{{ t("general.cancel") }}
</button>
<button
v-if="quotaExists"
type="button"
class="button button--flat button--red"
:aria-label="t('general.remove')"
:title="t('general.remove')"
@click="removeQuota"
>
{{ t("general.remove") }}
</button>
<button
type="button"
class="button button--flat button--blue"
:disabled="!dirty"
:aria-label="t('general.save')"
:title="t('general.save')"
@click="save"
>
{{ t("general.save") }}
</button>
<button type="button" class="button button--flat button--blue" @click="save">{{ $t("general.save") }}</button>
</div>
</template>
<script>
<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { useI18n } from "@/i18n/index.ts";
import { mutations, state } from "@/store/index.ts";
import { quotasApi } from "@/api/index.js";
import ToggleSwitch from "@/components/settings/ToggleSwitch.vue";
@@ -60,153 +86,164 @@ import ActivityViewerButton from "@/components/settings/ActivityViewerButton.vue
import QuotaCustomLimitInput from "@/components/settings/QuotaCustomLimitInput.vue";
import { activityViewerPresets } from "@/utils/activityViewerLink.js";
import { notify } from "@/notify/index.ts";
import {
bytesFromCustomAmount,
customAmountFromBytes,
} from "@/utils/quotaUnits.js";
import { bytesFromCustomAmount, customAmountFromBytes } from "@/utils/quotaUnits.js";
import type { FileListItem, FolderQuota, QuotaMeter, QuotaSnapshot, QuotaUnit } from "@/store/types.ts";
export default {
name: "Quota",
components: { ToggleSwitch, ExpandDropdown, QuotaFolderBar, ActivityViewerButton, QuotaCustomLimitInput },
props: {
promptId: { type: [String, Number], default: null },
item: { type: Object, required: true },
source: { type: String, required: true },
path: { type: String, default: "" },
},
data() {
return {
enabled: false,
customAmount: 10,
customUnit: "gb",
meter: "index_size",
quotaExists: false,
snapshot: {},
};
},
computed: {
indexingDisabled() {
return Boolean(state.sources.info?.[this.source]?.indexingDisabled);
},
meterOptions() {
const opts = [
{ value: "index_size", label: this.$t("quotas.meterIndexScope") },
{ value: "accounted", label: this.$t("quotas.meterAccounted") },
];
if (this.indexingDisabled) {
return opts.filter((o) => o.value === "accounted");
type QuotaResponse = FolderQuota | FolderQuota[];
interface QuotaBody {
limitBytes: number;
meter: QuotaMeter;
}
const props = withDefaults(
defineProps<{
promptId?: number | null;
item: Pick<FileListItem, "path">;
source: string;
path?: string;
}>(),
{
promptId: null,
path: "",
}
);
const { t } = useI18n();
const enabled = ref(false);
const customAmount = ref(10);
const customUnit = ref<QuotaUnit>("gb");
const meter = ref<QuotaMeter>("index_size");
const quotaExists = ref(false);
const snapshot = ref<QuotaSnapshot>({});
// Limit and meter as loaded, to tell whether there is something to save
const saved = ref<QuotaBody | null>(null);
const indexingDisabled = computed(() => Boolean(state.sources.info?.[props.source]?.indexingDisabled));
const meterOptions = computed(() => {
const opts: { value: QuotaMeter; label: string }[] = [
{ value: "index_size", label: t("quotas.meterIndexScope") },
{ value: "accounted", label: t("quotas.meterAccounted") },
];
if (indexingDisabled.value) {
return opts.filter((o) => o.value === "accounted");
}
return opts;
});
const measurementHelp = computed(() =>
meter.value === "accounted" ? t("quotas.meterAccountedHint") : t("quotas.meterIndexHint")
);
const displayPath = computed(() => props.path || props.item.path || "/");
const limitBytes = computed(() => {
if (!enabled.value) return 0;
return bytesFromCustomAmount(customAmount.value, customUnit.value);
});
const dirty = computed(() => {
if (!enabled.value) return quotaExists.value;
if (!saved.value) return true;
return limitBytes.value !== saved.value.limitBytes || meter.value !== saved.value.meter;
});
const activityViewerHref = computed(() => activityViewerPresets.quotas(props.source, displayPath.value));
onMounted(async () => {
if (indexingDisabled.value) {
meter.value = "accounted";
}
await load();
});
function close() {
mutations.closeTopPrompt();
}
// The quotas endpoints answer with a list
function firstQuota(raw: QuotaResponse) {
return Array.isArray(raw) ? raw[0] : raw;
}
function errorMessage(err: unknown) {
return (err instanceof Error && err.message) || t("prompts.operationFailed");
}
function applySnapshot(data?: QuotaSnapshot) {
if (!data) return;
snapshot.value = {
usedBytes: data.usedBytes,
reservedBytes: data.reservedBytes,
measurementStatus: data.measurementStatus,
};
}
async function load() {
try {
const data = firstQuota((await quotasApi.get(props.source, displayPath.value)) as QuotaResponse);
if (!data) return;
applySnapshot(data);
if ((data.limitBytes || 0) > 0) {
quotaExists.value = true;
enabled.value = true;
meter.value = data.configuredMeter || data.meter || "index_size";
if (indexingDisabled.value) {
meter.value = "accounted";
}
return opts;
},
measurementHelp() {
if (this.meter === "accounted") {
return this.$t("quotas.meterAccountedHint");
}
return this.$t("quotas.meterIndexHint");
},
displayPath() {
return this.path || this.item?.path || "/";
},
limitBytes() {
if (!this.enabled) return 0;
return bytesFromCustomAmount(this.customAmount, this.customUnit);
},
activityViewerHref() {
return activityViewerPresets.quotas(this.source, this.displayPath);
},
},
async mounted() {
if (this.indexingDisabled) {
this.meter = "accounted";
syncLimitFromBytes(data.limitBytes);
saved.value = { limitBytes: bytesFromCustomAmount(customAmount.value, customUnit.value), meter: meter.value };
}
await this.load();
},
methods: {
close() {
mutations.closeTopPrompt();
},
applySnapshot(data) {
if (!data) return;
this.snapshot = {
...this.snapshot,
usedBytes: data.usedBytes,
reservedBytes: data.reservedBytes,
measurementStatus: data.measurementStatus,
meter: data.effectiveMeter || data.meter,
configuredMeter: data.configuredMeter,
effectiveMeter: data.effectiveMeter,
limitBytes: data.limitBytes,
};
},
async load() {
try {
const raw = await quotasApi.get(this.source, this.displayPath);
const data = Array.isArray(raw) ? raw[0] : raw;
if (!data) return;
this.applySnapshot(data);
if ((data.limitBytes || 0) > 0) {
this.quotaExists = true;
this.enabled = true;
this.meter = data.configuredMeter || data.meter || "index_size";
if (this.indexingDisabled) {
this.meter = "accounted";
}
this.syncLimitFromBytes(data.limitBytes);
}
} catch {
// no quota yet
} catch {
// no quota yet
}
}
function syncLimitFromBytes(bytes: number) {
const { amount, unit } = customAmountFromBytes(bytes);
customAmount.value = amount;
customUnit.value = unit;
}
async function save() {
try {
if (!enabled.value) {
if (quotaExists.value) {
await quotasApi.remove(props.source, displayPath.value);
}
},
syncLimitFromBytes(bytes) {
const { amount, unit } = customAmountFromBytes(bytes);
this.customAmount = amount;
this.customUnit = unit;
},
async save() {
try {
if (!this.enabled) {
if (this.quotaExists) {
await quotasApi.remove(this.source, this.displayPath);
}
notify.showSuccess(this.$t("general.saved"));
this.close();
return;
}
const meter = this.indexingDisabled ? "accounted" : this.meter;
const body = {
limitBytes: this.limitBytes,
meter,
};
if (this.quotaExists) {
const updated = await quotasApi.update(this.source, this.displayPath, body);
this.applySnapshot(updated);
} else {
const created = await quotasApi.create({
source: this.source,
path: this.displayPath,
...body,
});
this.quotaExists = true;
this.applySnapshot(created);
}
notify.showSuccess(this.$t("general.saved"));
this.close();
} catch (/** @type {any} */ err) {
notify.showError(err.message || this.$t("prompts.operationFailed"));
}
},
async removeQuota() {
if (!this.quotaExists) return;
try {
await quotasApi.remove(this.source, this.displayPath);
notify.showSuccess(this.$t("general.removed"));
this.close();
} catch (/** @type {any} */ err) {
notify.showError(err.message || this.$t("prompts.operationFailed"));
}
},
},
};
notify.showSuccess(t("general.saved"));
close();
return;
}
const body: QuotaBody = {
limitBytes: limitBytes.value,
meter: indexingDisabled.value ? "accounted" : meter.value,
};
if (quotaExists.value) {
const updated = await quotasApi.update(props.source, displayPath.value, body);
applySnapshot(firstQuota(updated as QuotaResponse));
} else {
const created = await quotasApi.create({
source: props.source,
path: displayPath.value,
...body,
});
quotaExists.value = true;
applySnapshot(firstQuota(created as QuotaResponse));
}
notify.showSuccess(t("general.saved"));
close();
} catch (err) {
notify.showError(errorMessage(err));
}
}
async function removeQuota() {
if (!quotaExists.value) return;
try {
await quotasApi.remove(props.source, displayPath.value);
notify.showSuccess(t("general.removed"));
close();
} catch (err) {
notify.showError(errorMessage(err));
}
}
</script>
<style scoped>
@@ -16,54 +16,56 @@
:bar-border-radius="12"
/>
<p v-if="enabled && snapshot.measurementStatus === 'accounted_fallback'" class="quota-folder-bar__help">
{{ $t("quotas.accountedFallback") }}
{{ t("quotas.accountedFallback") }}
</p>
<p
v-else-if="enabled && snapshot.measurementStatus && snapshot.measurementStatus !== 'ready'"
class="quota-folder-bar__help"
>
{{ $t("quotas.usageSyncPending") }}
{{ t("quotas.usageSyncPending") }}
</p>
</div>
</template>
<script>
<script setup lang="ts">
import { computed } from "vue";
import { useI18n } from "@/i18n/index.ts";
import ProgressBar from "@/components/ProgressBar.vue";
import type { QuotaSnapshot } from "@/store/types.ts";
export default {
name: "QuotaFolderBar",
components: { ProgressBar },
props: {
promptId: { type: [String, Number], default: null },
source: { type: String, required: true },
path: { type: String, required: true },
enabled: { type: Boolean, default: false },
limitBytes: { type: Number, default: 0 },
snapshot: { type: Object, default: () => ({}) },
},
computed: {
barVal() {
if (!this.enabled) return 0;
return this.snapshot.usedBytes || 0;
},
barMax() {
if (!this.enabled) return 1;
return this.limitBytes > 0 ? this.limitBytes : 1;
},
barValText() {
if (!this.enabled) return this.$t("general.disabled");
return null;
},
barStatus() {
if (!this.enabled) return "disk";
const used = (this.snapshot.usedBytes || 0) + (this.snapshot.reservedBytes || 0);
const max = this.barMax;
if (used / max >= 0.95) return "error";
if (used / max >= 0.8) return "warning";
return "normal";
},
},
};
type BarStatus = "disk" | "error" | "warning" | "normal";
const props = withDefaults(
defineProps<{
source: string;
path: string;
enabled?: boolean;
limitBytes?: number;
snapshot?: QuotaSnapshot;
}>(),
{
enabled: false,
limitBytes: 0,
snapshot: () => ({}),
}
);
const { t } = useI18n();
const barVal = computed(() => (props.enabled ? props.snapshot.usedBytes || 0 : 0));
const barMax = computed(() => {
if (!props.enabled) return 1;
return props.limitBytes > 0 ? props.limitBytes : 1;
});
const barValText = computed(() => (props.enabled ? undefined : t("general.disabled")));
const barStatus = computed<BarStatus>(() => {
if (!props.enabled) return "disk";
const used = (props.snapshot.usedBytes || 0) + (props.snapshot.reservedBytes || 0);
const max = barMax.value;
if (used / max >= 0.95) return "error";
if (used / max >= 0.8) return "warning";
return "normal";
});
</script>
<style scoped>
+37
View File
@@ -52,6 +52,43 @@ export interface MediaMetadata {
hasLyrics?: boolean;
}
export type QuotaMeter = "index_size" | "index_scope" | "accounted";
export type QuotaUnit = "mb" | "gb";
/** from backend web.folderQuotaResponse */
export interface QuotaSnapshot {
limitBytes?: number;
usedBytes?: number;
reservedBytes?: number;
meter?: QuotaMeter;
configuredMeter?: QuotaMeter;
effectiveMeter?: QuotaMeter;
measurementStatus?: "ready" | "accounted_fallback";
}
export interface FolderQuota extends QuotaSnapshot {
source: string;
path: string;
limitBytes: number;
}
export type AccessRuleCategory = "user" | "group" | "all";
/** from backend access.FrontendRuleSet */
export interface AccessRuleSet {
users: string[];
groups: string[];
}
/** from backend access.FrontendAccessRule */
export interface AccessRule {
denyAll?: boolean;
deny: AccessRuleSet;
allow: AccessRuleSet;
sourceDenyDefault: boolean;
pathExists: boolean;
}
/** List items have their position in `req.items` (by mutations.replaceRequest) */
export interface fileListItemIndex extends FileListItem {
index: number;