feat(drive): UI: prepare right management

This commit is contained in:
Edouard Vanbelle
2026-06-23 20:26:08 +02:00
parent 6f1f44f962
commit 062bcb701b
5 changed files with 357 additions and 40 deletions
-33
View File
@@ -5277,21 +5277,6 @@
}
}
},
"node_modules/svelte-check/node_modules/picomatch": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
"dev": true,
"license": "MIT",
"optional": true,
"peer": true,
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/svelte-eslint-parser": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/svelte-eslint-parser/-/svelte-eslint-parser-1.8.0.tgz",
@@ -6546,24 +6531,6 @@
"dev": true,
"license": "ISC"
},
"node_modules/yaml": {
"version": "2.9.0",
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz",
"integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==",
"dev": true,
"license": "ISC",
"optional": true,
"peer": true,
"bin": {
"yaml": "bin.mjs"
},
"engines": {
"node": ">= 14.6"
},
"funding": {
"url": "https://github.com/sponsors/eemeli"
}
},
"node_modules/yocto-queue": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
+81 -4
View File
@@ -1,15 +1,92 @@
/**
* Drives endpoints. D0 ships read-only listing; mutations (create / rename /
* member changes) land in D2/D3 and will be added here under the same shape.
* Drives endpoints. D0 ships read-only listing; D2 adds the membership API.
* D3 will add the create-shared-drive flow under the same module.
*
* Consumers usually go through the `drives` store (`$lib/stores/drives.svelte`)
* which dedupes the request and caches the list — touch this module directly
* only when bypassing the cache is intentional (e.g. an explicit refresh).
*/
import { apiJson } from '$lib/api/client';
import type { Drive } from '$lib/api/types';
import { apiFetch, apiJson } from '$lib/api/client';
import { getCsrfHeaders } from '$lib/api/csrf';
import type { Drive, DriveMember, DriveMemberSubject, DriveRole } from '$lib/api/types';
const JSON_HEADERS = { 'Content-Type': 'application/json' };
/** `GET /api/drives` — every drive the caller can read, default first by convention. */
export function listDrives(): Promise<Drive[]> {
return apiJson<Drive[]>('/api/drives', { credentials: 'same-origin' });
}
/** `GET /api/drives/{id}/members` — every role grant on the drive. */
export function listDriveMembers(driveId: string): Promise<DriveMember[]> {
return apiJson<DriveMember[]>(`/api/drives/${encodeURIComponent(driveId)}/members`, {
credentials: 'same-origin'
});
}
/**
* `POST /api/drives/{id}/members` — add a member (or refresh an existing
* subject's role; the underlying `set_role` is idempotent via UNIQUE
* `(subject, resource)`).
*
* Refused with 405 on personal drives (immutable membership) and 400 if a
* last-owner demotion would orphan a shared drive.
*/
export async function addDriveMember(
driveId: string,
subject: DriveMemberSubject,
role: DriveRole,
expiresAt?: string | null
): Promise<DriveMember> {
const res = await apiFetch(`/api/drives/${encodeURIComponent(driveId)}/members`, {
method: 'POST',
headers: { ...JSON_HEADERS, ...getCsrfHeaders() },
credentials: 'same-origin',
body: JSON.stringify({ subject, role, expires_at: expiresAt ?? null })
});
if (!res.ok) throw new Error(`add member failed: ${res.status}`);
return (await res.json()) as DriveMember;
}
/**
* `PATCH /api/drives/{id}/members/{kind}/{sid}` — change a member's role.
* Same guards as `addDriveMember` apply.
*/
export async function updateDriveMember(
driveId: string,
subject: DriveMemberSubject,
role: DriveRole,
expiresAt?: string | null
): Promise<DriveMember> {
const url =
`/api/drives/${encodeURIComponent(driveId)}/members/` +
`${encodeURIComponent(subject.type)}/${encodeURIComponent(subject.id)}`;
const res = await apiFetch(url, {
method: 'PATCH',
headers: { ...JSON_HEADERS, ...getCsrfHeaders() },
credentials: 'same-origin',
body: JSON.stringify({ role, expires_at: expiresAt ?? null })
});
if (!res.ok) throw new Error(`update member failed: ${res.status}`);
return (await res.json()) as DriveMember;
}
/**
* `DELETE /api/drives/{id}/members/{kind}/{sid}` — remove a member.
* Idempotent (removing a non-member returns 204). Refused with 400 if it
* would leave a shared drive without an owner.
*/
export async function removeDriveMember(
driveId: string,
subject: DriveMemberSubject
): Promise<void> {
const url =
`/api/drives/${encodeURIComponent(driveId)}/members/` +
`${encodeURIComponent(subject.type)}/${encodeURIComponent(subject.id)}`;
const res = await apiFetch(url, {
method: 'DELETE',
headers: getCsrfHeaders(),
credentials: 'same-origin'
});
if (!res.ok) throw new Error(`remove member failed: ${res.status}`);
}
+33
View File
@@ -199,11 +199,27 @@ export interface SearchResults {
export type DriveKind = 'personal' | 'shared';
/** Role-keyed share strength. Matches `Role` in the backend authz model. */
export type DriveRole = 'owner' | 'editor' | 'contributor' | 'commenter' | 'viewer';
/** Subject of a grant. Mirrors `SubjectDto`. */
export type SubjectKind = 'user' | 'group' | 'token';
export interface DriveMemberSubject {
type: SubjectKind;
id: string;
}
/**
* One row from `GET /api/drives`. Mirrors `DriveDto` in
* `src/application/dtos/drive_dto.rs`. `default_for_user` is the caller's
* id when present, `null`/undefined otherwise — used to pick the default
* personal drive without hard-coding name conventions.
*
* `caller_role` is the strongest role the calling user holds on this drive
* (direct + group-mediated, collapsed). Drives the permission-aware UI
* gating on `/config/drive/<id>` and similar pages. `undefined` in
* contexts where the caller is the granter rather than a member (e.g.
* outgoing-grants listing).
*/
export interface Drive {
id: string;
@@ -216,4 +232,21 @@ export interface Drive {
policies: Record<string, unknown>;
created_at: string;
updated_at: string;
caller_role?: DriveRole | null;
}
/**
* One row from `GET /api/drives/{id}/members`. Mirrors `GrantDto` in
* `src/application/dtos/grant_dto.rs` — the shape is the same as any
* other role-grant; drive membership just constrains `resource.type` to
* `"drive"`.
*/
export interface DriveMember {
id: string;
subject: DriveMemberSubject;
resource: { type: 'drive'; id: string };
role: DriveRole;
granted_by: string;
granted_at: string;
expires_at?: string | null;
}
+12 -2
View File
@@ -62,13 +62,23 @@
onMount(() => {
void drivesStore.load();
});
// Dev/test override — set `localStorage.setItem('oxi-show-drive-picker', '1')`
// from DevTools to force the picker visible even with a single drive (useful
// for testing the UI before D3's shared-drive creation lands). Evaluated once
// at component mount; reload after toggling to apply.
const forceShowPicker = $derived(
typeof localStorage !== 'undefined' && localStorage.getItem('oxi-show-drive-picker') === '1'
);
</script>
<!-- Only show the drive switcher when there's an actual choice to make. With a
single drive (the default personal one) the picker just repeats "Personal"
under the Files nav row, so hide it; it reappears the moment a second drive
(e.g. a shared one) exists. -->
{#if drivesStore.loaded && drivesStore.drives.length > 1}
(e.g. a shared one) exists.
`forceShowPicker` is the localStorage-driven dev override (see script). -->
{#if drivesStore.loaded && (drivesStore.drives.length > 1 || forceShowPicker)}
<ul class="drive-picker" aria-label={t('drive.picker', 'Drives')}>
{#each sortedDrives as d (d.id)}
<li class="drive-picker__row" class:drive-picker__row--active={isActive(d)}>
@@ -3,16 +3,90 @@
import { page } from '$app/state';
import { onMount } from 'svelte';
import type { Drive } from '$lib/api/types';
import {
listDriveMembers,
removeDriveMember,
updateDriveMember
} from '$lib/api/endpoints/drives';
import type { Drive, DriveMember, DriveRole } from '$lib/api/types';
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';
const uuid = $derived(page.params.uuid ?? '');
const drive = $derived<Drive | null>(drivesStore.findById(uuid));
let members = $state<DriveMember[]>([]);
let membersLoaded = $state(false);
let membersError = $state<string | null>(null);
// Mutation controls are gated by *both* caller_role AND drive kind:
// even an Owner of a personal drive can't change membership (the
// backend guard refuses), so the UI hides the controls upfront for
// 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':
return t('drive.role.owner', 'Owner');
case 'editor':
return t('drive.role.editor', 'Editor');
case 'contributor':
return t('drive.role.contributor', 'Contributor');
case 'commenter':
return t('drive.role.commenter', 'Commenter');
case 'viewer':
return t('drive.role.viewer', 'Viewer');
}
}
async function loadMembers() {
if (!uuid) return;
try {
members = await listDriveMembers(uuid);
} catch (e) {
// 404 here means the caller lacks Read on the drive — which is
// also what the parent "Drive not found" card already conveys.
// Keep the listing area empty rather than surfacing a noisy toast.
membersError = e instanceof Error ? e.message : String(e);
members = [];
} finally {
membersLoaded = true;
}
}
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();
}
}
const kindLabel = $derived.by(() => {
if (!drive) return '';
return drive.kind === 'shared'
@@ -59,6 +133,7 @@
onMount(() => {
void drivesStore.load();
void loadMembers();
});
</script>
@@ -134,6 +209,73 @@
{/if}
</div>
<div class="card">
<h2><Icon name="users" /> {t('drive.members', 'Members')}</h2>
{#if !membersLoaded}
<p class="muted">{t('common.loading', 'Loading…')}</p>
{:else if members.length === 0}
<p class="muted">
{membersError ?? t('drive.members_empty', 'No members.')}
</p>
{:else}
<ul class="members">
{#each members as m (m.id)}
<li class="members__row">
{#if m.subject.type === 'user'}
<UserVignette userId={m.subject.id} />
{:else if m.subject.type === 'group'}
<span class="members__group">
<Icon name="users" />
<span class="mono">{m.subject.id}</span>
</span>
{:else}
<span class="members__token">
<Icon name="link" />
<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}
</li>
{/each}
</ul>
{#if !canManageMembers && drive.kind === 'personal'}
<p class="muted members__personal-note">
{t(
'drive.members.personal_immutable',
'Personal drives have a fixed single-owner membership.'
)}
</p>
{/if}
{/if}
</div>
{#if policyEntries.length > 0}
<div class="card">
<h2><Icon name="shield-alt" /> {t('drive.policies', 'Policies')}</h2>
@@ -248,4 +390,92 @@
.link:hover {
text-decoration: underline;
}
/* Members list */
.members {
list-style: none;
padding: 0;
margin: 0;
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.members__row {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.5rem 0.75rem;
border: 1px solid var(--color-border-faint);
border-radius: var(--radius-sm);
background: var(--color-bg-page);
}
.members__group,
.members__token {
display: inline-flex;
align-items: center;
gap: 0.4rem;
flex: 1;
min-width: 0;
color: var(--color-text-secondary);
}
.members__role {
display: inline-flex;
align-items: center;
padding: 0.2rem 0.65rem;
border-radius: var(--radius-pill, 999px);
font-size: 0.8rem;
background: var(--color-bg-muted);
color: var(--color-text-secondary);
flex: none;
}
.members__role--owner {
background: var(--color-accent-tint, var(--color-bg-muted));
color: var(--color-accent-text, var(--color-text-secondary));
font-weight: var(--weight-semibold);
}
.members__role--editor,
.members__role--contributor {
background: var(--color-accent-ring, var(--color-bg-muted));
color: var(--color-accent-text, var(--color-text-secondary));
}
.members__role-select {
flex: none;
padding: 0.25rem 0.5rem;
border-radius: var(--radius-sm);
border: 1px solid var(--color-border);
background: var(--color-bg-input);
color: var(--color-text);
font: inherit;
font-size: 0.85rem;
cursor: pointer;
}
.members__remove {
display: inline-flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
border: none;
border-radius: var(--radius-sm);
background: transparent;
color: var(--color-text-faint);
cursor: pointer;
}
.members__remove:hover {
background: var(--color-bg-hover);
color: var(--color-danger-text, var(--color-text));
}
.members__personal-note {
margin-top: 0.75rem;
font-size: 0.85rem;
}
</style>