feat(drive): improve drive edition from owners

This commit is contained in:
Edouard Vanbelle
2026-06-24 01:51:05 +02:00
parent d77846119f
commit 6034dd47d9
8 changed files with 214 additions and 116 deletions
+15 -6
View File
@@ -4,6 +4,15 @@ import { getCsrfHeaders } from '$lib/api/csrf';
import type { ItemType } from '$lib/api/types';
import type { ResourceBody, ResourcePage } from './resources';
/**
* Resource kinds the `/api/grants` family addresses. File/folder grants flow
* through the cascade engine; drive grants flow through
* `DriveManagementService` server-side, which layers personal-drive guard +
* last-owner protection on top of the same role-grant write. Either way the
* wire shape is identical, so the FE helpers below accept all three.
*/
export type GrantResourceType = ItemType | 'drive';
const JSON_HEADERS = { 'Content-Type': 'application/json' };
export type SubjectType = 'user' | 'group' | 'email' | 'token';
@@ -38,7 +47,7 @@ export interface Grant {
granted_by?: string;
subject: GrantSubject;
role: string;
resource: { type: ItemType; id: string };
resource: { type: GrantResourceType; id: string };
expires_at?: string | null;
}
@@ -80,14 +89,14 @@ export function expiryToIso(date: string | null | undefined): string | null {
return date ? new Date(`${date}T00:00:00Z`).toISOString() : null;
}
export function fetchGrantsForResource(type: ItemType, id: string): Promise<Grant[]> {
export function fetchGrantsForResource(type: GrantResourceType, id: string): Promise<Grant[]> {
const params = new URLSearchParams({ resource_type: type, resource_id: id });
return apiJson<Grant[]>(`/api/grants?${params}`, { credentials: 'same-origin' });
}
export async function createGrant(
subject: GrantSubjectInput,
resource: { type: ItemType; id: string },
resource: { type: GrantResourceType; id: string },
role: ShareRole,
expiresAt?: string | null
): Promise<CreateGrantResponse> {
@@ -106,7 +115,7 @@ export async function createGrant(
export async function updateGrantRole(
subject: GrantSubject,
resource: { type: ItemType; id: string },
resource: { type: GrantResourceType; id: string },
role: ShareRole,
expiresAt?: string | null
): Promise<void> {
@@ -148,7 +157,7 @@ export async function notifyGrantRecipient(grantId: string): Promise<NotifyOutco
}
export interface IncomingGrantItem {
resource_type: ItemType;
resource_type: GrantResourceType;
resource: ResourceBody;
granted_by?: string;
granted_at?: string;
@@ -169,7 +178,7 @@ export interface OutgoingResourceGrant {
}
export interface OutgoingGrantItem {
resource_type: ItemType;
resource_type: GrantResourceType;
resource: ResourceBody;
first_shared_at?: string;
/** One entry per (subject, permissions) pair. */
+4 -1
View File
@@ -52,8 +52,11 @@ async function systemContacts(includeSelf = false): Promise<Contact[]> {
const cached = includeSelf ? contactCacheWithSelf : contactCache;
if (cached) return cached;
try {
// `?include_self=true` (not `=1`) — Axum's `Query` extractor uses
// `serde_urlencoded`, which only deserialises `"true"`/`"false"`
// for `bool`. Sending `=1` would 400 before the handler runs.
const url = includeSelf
? '/api/address-books/system/contacts?include_self=1'
? '/api/address-books/system/contacts?include_self=true'
: '/api/address-books/system/contacts';
const res = await apiFetch(url, { credentials: 'same-origin' });
if (!res.ok) {
+62 -23
View File
@@ -28,7 +28,8 @@
searchRecipients,
type Recipient
} from '$lib/api/endpoints/recipients';
import type { ItemType, ShareItem } from '$lib/api/types';
import type { ShareItem } from '$lib/api/types';
import type { GrantResourceType } from '$lib/api/endpoints/grants';
import Icon from '$lib/icons/Icon.svelte';
import Modal from '$lib/components/Modal.svelte';
import UserVignette from '$lib/components/UserVignette.svelte';
@@ -38,7 +39,7 @@
interface Target {
id: string;
name: string;
kind: ItemType;
kind: GrantResourceType;
}
interface Props {
@@ -46,11 +47,32 @@
item: Target | null;
/** Fired with the item id when an outgoing share (grant or link) is created. */
onshared?: (id: string) => void;
/**
* Fired with the item id on **any** membership mutation — create,
* role change, expiry change, removal, or public-link creation.
* Distinct from `onshared` because some callers (file/folder list
* views that toggle a "shared" badge) only care about creation;
* the drive-config view needs to refresh on every change.
*/
onchange?: (id: string) => void;
/**
* Whether the "Public link" (token-grant) tab is exposed. Defaults to
* `true` for file/folder sharing. Drives set this to `false`: a drive
* grant is per-member only, never via a shareable URL — exposing the
* tab would suggest a capability that doesn't exist.
*/
allowLinks?: boolean;
}
let { open = $bindable(false), item, onshared }: Props = $props();
let { open = $bindable(false), item, onshared, onchange, allowLinks = true }: Props = $props();
// When the public-link tab is hidden, force the People view — otherwise a
// caller toggling `allowLinks` between renders could land on the now-hidden
// tab with no UI.
let tab = $state<'people' | 'link'>('people');
$effect(() => {
if (!allowLinks) tab = 'people';
});
let directoryAvailable = $state(true);
const ROLES: { v: ShareRole; l: string; icon: string }[] = [
@@ -163,6 +185,7 @@
results = [];
summarizeNotifications(res.notification.outcomes);
onshared?.(item.id);
onchange?.(item.id);
await loadGrants();
} catch (e) {
errorToast(e);
@@ -178,6 +201,7 @@
role,
expiryToIso(m.expiry)
);
onchange?.(item.id);
await loadGrants();
} catch (e) {
errorToast(e);
@@ -193,6 +217,7 @@
m.role,
expiryToIso(expiry)
);
onchange?.(item.id);
await loadGrants();
} catch (e) {
errorToast(e);
@@ -202,6 +227,7 @@
async function removeMember(m: Member) {
try {
for (const id of m.grantIds) await revokeGrant(id);
if (item) onchange?.(item.id);
await loadGrants();
} catch (e) {
errorToast(e);
@@ -259,7 +285,11 @@
let expiresAt = $state<string | null>(null);
async function loadShares() {
if (!item) return;
// The share-link API only supports file/folder items; the Link tab
// is hidden for drives (`allowLinks=false`) so this path is
// unreachable, but narrow the type here so TypeScript doesn't
// surface the widened `GrantResourceType` from `item.kind`.
if (!item || item.kind === 'drive') return;
linkLoading = true;
try {
shares = await listSharesForItem(item.id, item.kind);
@@ -271,7 +301,7 @@
}
async function createLink() {
if (!item) return;
if (!item || item.kind === 'drive') return;
creating = true;
try {
await createShare({
@@ -285,6 +315,7 @@
password = '';
expiresAt = null;
onshared?.(item.id);
onchange?.(item.id);
await loadShares();
ui.notify(t('share.created', 'Public link created'), 'success');
} catch (e) {
@@ -297,6 +328,7 @@
async function editLinkExpiry(share: ShareItem, expiry: string | null) {
try {
await updateShare(share.id, { expiresAt: expiry });
if (item) onchange?.(item.id);
await loadShares();
} catch (e) {
errorToast(e);
@@ -306,6 +338,7 @@
async function editLinkPassword(share: ShareItem, pw: string | null) {
try {
await updateShare(share.id, { password: pw });
if (item) onchange?.(item.id);
await loadShares();
ui.notify(
pw
@@ -321,6 +354,7 @@
async function removeLink(share: ShareItem) {
try {
await deleteShare(share.id);
if (item) onchange?.(item.id);
shares = shares.filter((s) => s.id !== share.id);
} catch (e) {
errorToast(e);
@@ -378,24 +412,29 @@
<Modal bind:open title={t('share.dialog_title', { name: item?.name ?? '' }, 'Share “{{name}}”')}>
<div data-testid="share-dialog">
<div class="tabs" role="tablist">
<button
role="tab"
data-testid="share-dialog-people-tab"
aria-selected={tab === 'people'}
onclick={() => (tab = 'people')}
>
{t('share.people', 'People')}
</button>
<button
role="tab"
data-testid="share-dialog-link-tab"
aria-selected={tab === 'link'}
onclick={() => (tab = 'link')}
>
{t('share.public_link', 'Public link')}
</button>
</div>
<!-- People/Link tab switcher. Hidden entirely when `allowLinks=false`
(the drive-members surface) — with only one tab visible the
switcher would be visual noise. -->
{#if allowLinks}
<div class="tabs" role="tablist">
<button
role="tab"
data-testid="share-dialog-people-tab"
aria-selected={tab === 'people'}
onclick={() => (tab = 'people')}
>
{t('share.people', 'People')}
</button>
<button
role="tab"
data-testid="share-dialog-link-tab"
aria-selected={tab === 'link'}
onclick={() => (tab = 'link')}
>
{t('share.public_link', 'Public link')}
</button>
</div>
{/if}
{#if tab === 'people'}
{#if !directoryAvailable && !grantsLoading}
@@ -3,17 +3,13 @@
import { page } from '$app/state';
import { onMount } from 'svelte';
import {
listDriveMembers,
removeDriveMember,
updateDriveMember
} from '$lib/api/endpoints/drives';
import { listDriveMembers } from '$lib/api/endpoints/drives';
import type { Drive, DriveMember, DriveRole } from '$lib/api/types';
import ShareDialog from '$lib/components/ShareDialog.svelte';
import UserVignette from '$lib/components/UserVignette.svelte';
import Icon from '$lib/icons/Icon.svelte';
import { t } from '$lib/i18n/index.svelte';
import { drives as drivesStore, driveIcon } from '$lib/stores/drives.svelte';
import { errorToast } from '$lib/utils/errors';
import { formatDate } from '$lib/utils/display';
import { formatBytes } from '$lib/utils/format';
@@ -30,10 +26,6 @@
// honest UX. Shared drives + Owner role → full controls.
const canManageMembers = $derived(drive?.kind === 'shared' && drive?.caller_role === 'owner');
// Roles offered in the dropdown. Owner sets the bundle; other roles
// match the backend `Role` enum order (owner → viewer = strongest → weakest).
const ASSIGNABLE_ROLES: DriveRole[] = ['owner', 'editor', 'viewer'];
function roleLabel(role: DriveRole): string {
switch (role) {
case 'owner':
@@ -49,6 +41,19 @@
}
}
// `shareDialogOpen` drives the ShareDialog modal — the same dialog
// used for file/folder sharing, parameterised with `kind: 'drive'`
// + `allowLinks: false`. Add/change-role/remove flow through the
// dialog's existing grants plumbing (server-side those routes
// dispatch to `DriveManagementService`).
let shareDialogOpen = $state(false);
// `dialogItem` is recomputed from the drive so the dialog title
// reflects renames.
const dialogItem = $derived(
drive ? { id: drive.id, name: drive.name, kind: 'drive' as const } : null
);
async function loadMembers() {
if (!uuid) return;
try {
@@ -64,27 +69,12 @@
}
}
async function changeRole(member: DriveMember, role: DriveRole) {
if (member.role === role) return;
try {
const updated = await updateDriveMember(uuid, member.subject, role);
members = members.map((m) => (m.id === member.id ? updated : m));
} catch (e) {
errorToast(e);
// Re-fetch so the dropdown reflects the server-side state, not the
// optimistic-but-rejected change.
await loadMembers();
}
}
async function removeMember(member: DriveMember) {
try {
await removeDriveMember(uuid, member.subject);
members = members.filter((m) => m.id !== member.id);
} catch (e) {
errorToast(e);
await loadMembers();
}
// Refresh the on-page member list on every dialog mutation (add,
// role change, remove). ShareDialog fires `onchange` for the full
// set of grant mutations — `onshared` only covers creation, which
// would leave role-change and removal stale here.
function onShareDialogChange() {
void loadMembers();
}
const kindLabel = $derived.by(() => {
@@ -133,7 +123,21 @@
onMount(() => {
void drivesStore.load();
void loadMembers();
});
// SvelteKit reuses this component when navigating between
// `/config/drive/<A>` and `/config/drive/<B>` (same route, different
// dynamic param), so `onMount` only fires once. Re-run the members
// fetch whenever `uuid` changes — without this, the previous drive's
// rows linger until a hard refresh. Resetting `members` + the loaded
// flag first prevents the brief flash of stale data before the new
// fetch returns.
$effect(() => {
const id = uuid;
members = [];
membersLoaded = false;
membersError = null;
if (id) void loadMembers();
});
</script>
@@ -210,7 +214,21 @@
</div>
<div class="card">
<h2><Icon name="users" /> {t('drive.members', 'Members')}</h2>
<div class="members__header">
<h2><Icon name="users" /> {t('drive.members', 'Members')}</h2>
{#if canManageMembers}
<button
type="button"
class="btn btn-primary"
data-testid="drive-manage-members-btn"
onclick={() => (shareDialogOpen = true)}
>
<Icon name="user-plus" />
{t('drive.manage_members', 'Manage members')}
</button>
{/if}
</div>
{#if !membersLoaded}
<p class="muted">{t('common.loading', 'Loading…')}</p>
{:else if members.length === 0}
@@ -218,6 +236,10 @@
{membersError ?? t('drive.members_empty', 'No members.')}
</p>
{:else}
<!-- Read-only summary. Add/change/remove happens inside the
ShareDialog modal opened by the button above; the inline
row controls used to live here have moved into the dialog
so the same flow handles file/folder + drive grants. -->
<ul class="members">
{#each members as m (m.id)}
<li class="members__row">
@@ -234,33 +256,9 @@
<span class="mono">{m.subject.id}</span>
</span>
{/if}
{#if canManageMembers}
<select
class="members__role-select"
value={m.role}
onchange={(e) =>
void changeRole(m, (e.currentTarget as HTMLSelectElement).value as DriveRole)}
aria-label={t('drive.member.change_role_aria', 'Change role')}
>
{#each ASSIGNABLE_ROLES as r (r)}
<option value={r}>{roleLabel(r)}</option>
{/each}
</select>
<button
type="button"
class="members__remove"
title={t('drive.member.remove', 'Remove member')}
aria-label={t('drive.member.remove', 'Remove member')}
onclick={() => void removeMember(m)}
>
<Icon name="times" />
</button>
{:else}
<span class="members__role members__role--{m.role}">
{roleLabel(m.role)}
</span>
{/if}
<span class="members__role members__role--{m.role}">
{roleLabel(m.role)}
</span>
</li>
{/each}
</ul>
@@ -290,6 +288,19 @@
{/if}
</div>
<!-- Drive members modal — reuses the same ShareDialog as file/folder
sharing. `allowLinks={false}` hides the public-link tab because
drives don't support shareable URLs (the backend service refuses
token subjects on drive resources). -->
{#if dialogItem}
<ShareDialog
bind:open={shareDialogOpen}
item={dialogItem}
allowLinks={false}
onchange={onShareDialogChange}
/>
{/if}
<style>
.config-drive {
max-width: 800px;
@@ -391,6 +402,20 @@
text-decoration: underline;
}
/* Members card header: title on the left, "Manage members" button on
the right when the caller can mutate membership. */
.members__header {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-3, 0.75rem);
margin-bottom: var(--space-3, 0.75rem);
}
.members__header h2 {
margin: 0;
}
/* Members list */
.members {
list-style: none;
+27 -20
View File
@@ -26,26 +26,33 @@
const byId = $derived(new Map(raw.map((it) => [it.resource.id, it])));
const entries = $derived(
raw.map((it): ResourceEntry => {
const isFile = it.resource_type === 'file';
return {
id: it.resource.id,
name: it.resource.name,
kind: it.resource_type,
iconClass: it.resource.icon_class,
// The sharer becomes the "owner" surface — ResourceList renders
// `<UserVignette userId>` (avatar / name / external badge),
// resolved lazily via `/api/users/{id}`. `path` keeps the
// resource's real location so the row still shows where it
// lives, not a translated string.
ownerId: it.granted_by ?? null,
ownerName: sharers.name(it.granted_by),
path: it.resource.path,
size: isFile ? (it.resource as FileItem).size : null,
date: it.granted_at,
category: isFile ? it.resource.category : 'Folder'
};
})
// Drive resources also surface in `/api/grants/incoming/resources`
// since the role_grants rewrite, but they don't belong in the
// file/folder ResourceList — they're reached through the drive
// picker / breadcrumb. Filter them out here so the row UI keeps
// its file|folder type contract.
raw
.filter((it) => it.resource_type !== 'drive')
.map((it): ResourceEntry => {
const isFile = it.resource_type === 'file';
return {
id: it.resource.id,
name: it.resource.name,
kind: it.resource_type as 'file' | 'folder',
iconClass: it.resource.icon_class,
// The sharer becomes the "owner" surface — ResourceList renders
// `<UserVignette userId>` (avatar / name / external badge),
// resolved lazily via `/api/users/{id}`. `path` keeps the
// resource's real location so the row still shows where it
// lives, not a translated string.
ownerId: it.granted_by ?? null,
ownerName: sharers.name(it.granted_by),
path: it.resource.path,
size: isFile ? (it.resource as FileItem).size : null,
date: it.granted_at,
category: isFile ? it.resource.category : 'Folder'
};
})
);
// Server-supported sort_by values (see grant_handler.rs:615):
+19 -3
View File
@@ -19,7 +19,8 @@
import { copyShareLink, deleteShare, getShareById, updateShare } from '$lib/api/endpoints/shares';
import { ensureResolvers, resolveLabel } from '$lib/api/endpoints/recipients';
import { fileInlineUrl } from '$lib/api/endpoints/files';
import type { FileItem, FolderItem, ItemType } from '$lib/api/types';
import type { FileItem, FolderItem } from '$lib/api/types';
import type { GrantResourceType } from '$lib/api/endpoints/grants';
import Icon from '$lib/icons/Icon.svelte';
import ListToolbar from '$lib/components/ListToolbar.svelte';
import { lazyComponent } from '$lib/composables/lazyComponent.svelte';
@@ -53,7 +54,7 @@
// Edit-sharing dialog
let dialogOpen = $state(false);
let dialogItem = $state<{ id: string; name: string; kind: ItemType } | null>(null);
let dialogItem = $state<{ id: string; name: string; kind: GrantResourceType } | null>(null);
// ShareDialog is heavy and only opens on demand — keep it out of this route's
// initial chunk and load it the first time the dialog is opened.
@@ -189,6 +190,13 @@
}
function openResource(item: OutgoingGrantItem) {
// Drives don't have a Files-page deep-link the same way folders do
// (their id is the drive UUID, not a folder UUID); route to the
// per-drive settings page so the user lands somewhere meaningful.
if (item.resource_type === 'drive') {
goto(resolve(`/config/drive/${item.resource.id}`));
return;
}
if (item.resource_type === 'folder') goto(resolve(`/files/${item.resource.id}`));
else window.open(fileInlineUrl(item.resource.id), '_blank', 'noopener');
}
@@ -351,6 +359,11 @@
}
function resourceIcon(item: OutgoingGrantItem): string {
// Drives use the `hdd` glyph (shared with DrivePicker / breadcrumb)
// so a shared drive reads as a distinct kind at a glance — folder
// and drive both grant access to a tree, but the scope is very
// different.
if (item.resource_type === 'drive') return 'hdd';
return item.resource_type === 'folder'
? 'folder'
: iconNameFromClass((item.resource as FileItem | FolderItem).icon_class);
@@ -629,7 +642,10 @@
{#if shareDialog.component}
{@const ShareDialog = shareDialog.component}
<ShareDialog bind:open={dialogOpen} item={dialogItem} />
<!-- Drives don't support shareable URLs — hide the Public-link tab
when the dialog is opened for a drive resource. File/folder
resources keep the default tab set. -->
<ShareDialog bind:open={dialogOpen} item={dialogItem} allowLinks={dialogItem?.kind !== 'drive'} />
{/if}
<style>
-1
View File
@@ -100,4 +100,3 @@ impl From<DriveWithRootName> for DriveDto {
}
}
}
+2 -2
View File
@@ -9,6 +9,8 @@ use axum::{
routing::{delete, get, post, put},
};
use crate::application::dtos::drive_dto::DriveDto;
use crate::application::dtos::grant_dto::{GrantDto, RoleDto, SubjectDto, SubjectTypeDto};
use crate::application::dtos::plugin_dto::{
PluginInfoDto, PluginLogEntryDto, PluginLogPageDto, PluginLogQueryDto, PluginRetentionDto,
SetEnabledDto,
@@ -19,8 +21,6 @@ use crate::application::dtos::settings_dto::{
SmtpTestResultDto, StartMigrationDto, TestOidcConnectionDto, TestStorageConnectionDto,
UpdateUserActiveDto, UpdateUserQuotaDto, UpdateUserRoleDto, VerifyMigrationDto,
};
use crate::application::dtos::drive_dto::DriveDto;
use crate::application::dtos::grant_dto::{GrantDto, RoleDto, SubjectDto, SubjectTypeDto};
use crate::application::ports::authorization_ports::AuthorizationEngine;
use crate::application::ports::plugin_ports::{LogQuery, PluginManagementPort, PluginMgmtError};
use crate::common::di::AppState;