feat: show access as a folder tree with links to each item

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Guilhem Lemouel
2026-11-02 10:24:59 -08:00
co-authored by Claude Opus 5.5
parent a3e115516f
commit aa0ef48d90
4 changed files with 456 additions and 100 deletions
+255 -100
View File
@@ -1,20 +1,43 @@
<script lang="ts">
import { Alert, Badge, Drawer, DrawerContent, Section, Skeleton } from './common'
import { Alert, Badge, Button, Drawer, DrawerContent, Section, Skeleton } from './common'
import TextInput from './text_input/TextInput.svelte'
import Select from './select/Select.svelte'
import DataTable from './table/DataTable.svelte'
import Head from './table/Head.svelte'
import Cell from './table/Cell.svelte'
import Row from './table/Row.svelte'
import RowIcon from './common/table/RowIcon.svelte'
import { GranularAclService, type AccessReason, type PrincipalAccess } from '$lib/gen'
import { Tooltip } from './meltComponents'
import { GranularAclService, type PrincipalAccess } from '$lib/gen'
import { useOperatingWorkspace } from './operatingWorkspace.svelte'
import { logFeatureUsage } from '$lib/utils/featureUsage'
import { pluralize } from '$lib/utils'
import { itemHref } from './offboarding-utils'
import {
buildAccessTree,
flattenAccessTree,
type AccessItem,
type AccessOwnerNode
} from './access/accessTree'
import {
ChevronDown,
ChevronRight,
ChevronsDownUp,
ChevronsUpDown,
ExternalLink,
Folder,
FolderTree,
User,
Users
} from 'lucide-svelte'
const operatingWorkspace = useOperatingWorkspace()
type Target = 'self' | 'user' | 'service_account' | 'group'
const PAGE = 100
// A short list opens fully, so every item shows at once. A longer one starts at its folders.
const OPEN_UP_TO = 30
const KIND_LABELS: Record<string, string> = {
script: 'Script',
@@ -43,6 +66,9 @@
let search = $state('')
let kind: string | undefined = $state()
let nbDisplayed = $state(PAGE)
/** Rows opened or closed by hand, by path prefix. The rest follow `expandAll`. */
let openState: Record<string, boolean> = $state({})
let expandAll: boolean | undefined = $state()
// Responses are not ordered: a slow answer for the previous principal must not land on this one.
let requestId = 0
@@ -53,6 +79,8 @@
search = ''
kind = undefined
nbDisplayed = PAGE
openState = {}
expandAll = undefined
drawer?.openDrawer()
logFeatureUsage('access_view', 'opened', { key: target })
const id = ++requestId
@@ -69,6 +97,7 @@
const name = $derived(principal.slice(2))
const isGroup = $derived(principal.startsWith('g/'))
const who = $derived(isGroup ? `members of ${principal}` : principal)
const kindItems = $derived.by(() => {
const counts = new Map<string, number>()
@@ -79,39 +108,103 @@
}))
})
const filteredItems = $derived.by(() => {
const q = search.trim().toLowerCase()
return (access?.items ?? []).filter(
(item) => (!kind || item.kind === kind) && (!q || item.path.toLowerCase().includes(q))
)
})
const query = $derived(search.trim().toLowerCase())
const filtering = $derived(!!query || !!kind)
const allOpen = $derived(expandAll ?? (access?.items.length ?? 0) <= OPEN_UP_TO)
const tree = $derived(access && !access.is_admin ? buildAccessTree(access) : [])
const rows = $derived(
flattenAccessTree(tree, {
matches: (item) =>
(!kind || item.kind === kind) && (!query || item.path.toLowerCase().includes(query)),
isOpen: (key) => openState[key] ?? allOpen,
filtering
})
)
function reasonLabel(reason: AccessReason): string {
switch (reason.type) {
case 'own':
return 'Own path'
case 'group_path':
return `Path of g/${reason.group}`
case 'user':
return `Shared with ${principal}`
case 'group':
return `Shared with g/${reason.group}`
case 'folder':
return `Folder f/${reason.folder}`
}
function toggle(key: string, open: boolean): void {
openState[key] = !open
}
// `own` and `group_path` always grant write, so only grants that can be either say which.
function reasonAccess(reason: AccessReason): string | undefined {
if (reason.type === 'own' || reason.type === 'group_path') return undefined
return reason.write ? 'write' : 'read'
function toggleAll(): void {
expandAll = !allOpen
openState = {}
}
function folderVia(via: string): string {
function viaLabel(via: string): string {
return via === principal ? 'Shared directly' : `Through ${via}`
}
/** Where holding the whole folder or space comes from. Empty when only some items are shared. */
function ownerGrant(node: AccessOwnerNode): string {
if (!node.whole) return ''
if (node.key.startsWith('f/')) {
return [...(node.admin ? ['Folder admin'] : []), ...node.via.map(viaLabel)].join(', ')
}
return node.key === principal ? 'Own path' : `Through ${node.key}`
}
function ownerExplanation(node: AccessOwnerNode): string {
const verb = node.write ? 'write' : 'read'
if (!node.whole) {
return node.key.startsWith('f/')
? `${node.key} itself isn't shared with ${principal}. Only the items listed under it are, one by one, so items added to ${node.key} later stay out of reach.`
: `Only the items listed here are shared with ${principal}. Other items under ${node.key}/, and any added later, stay out of reach.`
}
if (node.key.startsWith('f/')) {
return node.via.length
? `${node.key} itself is shared with ${node.via.join(' and ')}, so ${who} can ${verb} every item in it, including items added later.`
: `${principal} administers ${node.key}, so ${who} can write every item in it, including items added later.`
}
if (node.key === principal) {
return isGroup
? `Items under ${principal}/ belong to the group, so its members can write every one of them, including items added later.`
: `Items under ${principal}/ belong to ${principal}, who can write every one of them, including items added later.`
}
return `${principal} is a member of ${node.key}, so ${principal} can write every item under ${node.key}/, including items added later.`
}
/** Grants on the item itself. What its folder or space gives is said once, on that row. */
function itemGrants(item: AccessItem): string[] {
return item.reasons.flatMap((r) =>
r.type === 'user' ? ['Shared directly'] : r.type === 'group' ? [viaLabel(`g/${r.group}`)] : []
)
}
function levelClass(item: AccessItem, grants: string[], owner: AccessOwnerNode): string {
if (!grants.length) return 'text-hint'
return item.write && owner.whole && !owner.write ? 'font-semibold text-emphasis' : ''
}
// The drawer can report on the workspace a session editor acts in, which is not
// necessarily the one the new tab would otherwise open.
function withWorkspace(href: string): string {
const [route, hash] = href.split(/#(.*)/s)
const query = `?workspace=${encodeURIComponent($operatingWorkspace ?? '')}`
return route + query + (hash !== undefined ? `#${hash}` : '')
}
function itemLink(kind: string, path: string): string | undefined {
const href = itemHref(kind, path)
return href ? withWorkspace(href) : undefined
}
</script>
{#snippet chevron(key: string, open: boolean)}
<!-- Keyboard access only: its click bubbles to the row, which does the toggling. -->
<button
type="button"
class="text-secondary shrink-0"
aria-expanded={open}
aria-label={`${open ? 'Collapse' : 'Expand'} ${key}`}
>
{#if open}
<ChevronDown size={14} />
{:else}
<ChevronRight size={14} />
{/if}
</button>
{/snippet}
<Drawer bind:this={drawer} size="1000px">
<DrawerContent title={`Access of ${principal}`} on:close={() => drawer?.closeDrawer()}>
<div class="flex flex-col gap-6">
@@ -134,55 +227,23 @@
{principal} is an admin of this workspace and can read and write every item in it.
</Alert>
{:else}
<Section label="Groups" small>
{#if access.groups.length}
<div class="flex flex-wrap gap-1">
{#each access.groups as group (group)}
<Badge color="gray">g/{group}</Badge>
{/each}
</div>
{:else}
<p class="text-xs text-secondary">Not in any group.</p>
{/if}
</Section>
<Section label="Folders" small>
{#if access.folders.length}
<DataTable size="xs">
<Head>
<tr>
<Cell head first>Folder</Cell>
<Cell head>Access</Cell>
<Cell head last>Why</Cell>
</tr>
</Head>
<tbody class="divide-y">
{#each access.folders as folder (folder.name)}
<tr>
<Cell first>f/{folder.name}</Cell>
<Cell>{folder.write ? 'Write' : 'Read'}</Cell>
<Cell last>
<div class="flex flex-wrap gap-1">
{#if folder.owner}
<Badge color="blue">Owner</Badge>
{/if}
{#each folder.via as via (via)}
<Badge color="gray">{folderVia(via)}</Badge>
{/each}
</div>
</Cell>
</tr>
{#if !isGroup}
<Section label="Groups" small>
{#if access.groups.length}
<div class="flex flex-wrap gap-1">
{#each access.groups as group (group)}
<Badge color="gray">g/{group}</Badge>
{/each}
</tbody>
</DataTable>
{:else}
<p class="text-xs text-secondary">No folder is shared with {principal}.</p>
{/if}
</Section>
</div>
{:else}
<p class="text-xs text-secondary">Not in any group.</p>
{/if}
</Section>
{/if}
<Section label={`Items (${access.items.length})`} small>
<div class="flex flex-col gap-2">
<div class="flex gap-2">
<div class="flex gap-2 items-center">
<TextInput
bind:value={search}
inputProps={{ placeholder: 'Search paths' }}
@@ -198,52 +259,146 @@
size="sm"
/>
</div>
<Button
variant="subtle"
unifiedSize="sm"
disabled={filtering}
startIcon={{ icon: allOpen ? ChevronsDownUp : ChevronsUpDown }}
on:click={toggleAll}
>
{allOpen ? 'Collapse all' : 'Expand all'}
</Button>
</div>
{#if filteredItems.length}
{#if rows.length}
<DataTable
size="xs"
shouldLoadMore={filteredItems.length > nbDisplayed}
shouldLoadMore={rows.length > nbDisplayed}
loadMore={PAGE}
on:loadMore={() => (nbDisplayed += PAGE)}
>
<Head>
<tr>
<Cell head first>Kind</Cell>
<Cell head>Path</Cell>
<Cell head first>Name</Cell>
<Cell head>Access</Cell>
<Cell head last>Why</Cell>
<Cell head last>Granted by</Cell>
</tr>
</Head>
<tbody class="divide-y">
{#each filteredItems.slice(0, nbDisplayed) as item (item.kind + ':' + item.path)}
<tr>
<Cell first>
<span class="flex items-center gap-1.5">
<RowIcon kind={item.kind as 'script'} size={14} />
{KIND_LABELS[item.kind] ?? item.kind}
</span>
</Cell>
<Cell><span class="font-mono text-2xs">{item.path}</span></Cell>
<Cell>{item.write ? 'Write' : 'Read'}</Cell>
<Cell last>
<div class="flex flex-wrap gap-1">
{#each item.reasons as reason, i (i)}
{@const level = reasonAccess(reason)}
<Badge color="gray">
{reasonLabel(reason)}{#if level}<span class="text-secondary"
>&nbsp;· {level}</span
>{/if}
<tbody>
{#each rows.slice(0, nbDisplayed) as row (row.type === 'item' ? `${row.item.kind}:${row.item.path}` : row.node.key)}
{#if row.type === 'owner'}
{@const node = row.node}
{@const OwnerIcon = node.key.startsWith('f/')
? Folder
: node.key.startsWith('g/')
? Users
: User}
<Row
hoverable={row.count > 0}
class="group"
on:click={() => row.count > 0 && toggle(node.key, row.open)}
>
<Cell first>
<div class="flex items-center gap-1.5">
{#if row.count > 0}
{@render chevron(node.key, row.open)}
{:else}
<span class="w-3.5 shrink-0"></span>
{/if}
<OwnerIcon size={14} class="text-secondary shrink-0" />
<span class="font-semibold text-emphasis">{node.key}</span>
<span class="text-secondary">{pluralize(row.count, 'item')}</span>
{#if node.key.startsWith('f/')}
<a
href={withWorkspace(`/folders#${node.key}`)}
target="_blank"
class="text-secondary hover:text-emphasis opacity-0 group-hover:opacity-100 focus-visible:opacity-100"
aria-label={`Open ${node.key} in a new tab`}
title={`Open ${node.key} in a new tab`}
onclick={(e) => e.stopPropagation()}
>
<ExternalLink size={12} />
</a>
{/if}
</div>
</Cell>
<Cell>
<!-- A badge is a level held on the folder or space itself; item rows show theirs as text. -->
<Tooltip class="-my-0.5">
<Badge
color="gray"
class={node.whole
? 'border border-transparent py-0'
: 'bg-transparent border border-dashed border-border-normal py-0'}
>
{node.whole ? (node.write ? 'Write' : 'Read') : 'Some items'}
</Badge>
{/each}
</div>
</Cell>
</tr>
{#snippet text()}{ownerExplanation(node)}{/snippet}
</Tooltip>
</Cell>
<Cell last>{ownerGrant(node)}</Cell>
</Row>
{:else if row.type === 'subfolder'}
<Row hoverable on:click={() => toggle(row.node.key, row.open)}>
<Cell first>
<div
class="flex items-center gap-1.5"
style="padding-left: {row.depth * 20}px"
>
{@render chevron(row.node.key, row.open)}
<FolderTree size={14} class="text-secondary shrink-0" />
<span class="font-medium text-emphasis">{row.node.name}</span>
<span class="text-secondary">{pluralize(row.count, 'item')}</span>
</div>
</Cell>
<Cell></Cell>
<Cell last></Cell>
</Row>
{:else}
{@const item = row.item}
{@const grants = itemGrants(item)}
{@const href = itemLink(item.kind, item.path)}
<tr>
<Cell first>
<div
class="flex items-center gap-1.5"
style="padding-left: {row.depth * 20}px"
>
<span class="w-3.5 shrink-0"></span>
<span class="flex shrink-0" title={KIND_LABELS[item.kind] ?? item.kind}>
<RowIcon kind={item.kind as 'script'} size={14} />
</span>
{#if href}
<a
{href}
target="_blank"
title={item.path}
class="group/link inline-flex items-center gap-1 text-primary hover:underline"
>{row.name}<ExternalLink
size={12}
class="opacity-0 group-hover/link:opacity-100 group-focus-visible/link:opacity-100 shrink-0"
/></a
>
{:else}
<span title={item.path}>{row.name}</span>
{/if}
</div>
</Cell>
<Cell>
<span class={levelClass(item, grants, row.owner)}
>{item.write ? 'Write' : 'Read'}</span
>
</Cell>
<Cell last>{grants.join(', ')}</Cell>
</tr>
{/if}
{/each}
</tbody>
</DataTable>
{:else}
<p class="text-xs text-secondary">
{access.items.length ? 'No item matches.' : `${principal} cannot read any item.`}
{access.items.length || access.folders.length
? 'No item matches.'
: `${principal} cannot read any item.`}
</p>
{/if}
</div>
@@ -0,0 +1,37 @@
import { describe, expect, it } from 'vitest'
import type { PrincipalAccess } from '$lib/gen'
import { buildAccessTree } from './accessTree'
const item = (path: string, reasons: PrincipalAccess['items'][number]['reasons']) => ({
kind: 'script',
path,
write: false,
reasons
})
describe('buildAccessTree', () => {
it('marks a folder or space whole only when it is held itself', () => {
const tree = buildAccessTree({
principal: 'u/alice',
is_admin: false,
groups: ['ops'],
folders: [{ name: 'reporting', write: false, owner: false, via: ['g/ops'] }],
items: [
item('u/bob/shared_note', [{ type: 'group', group: 'ops', write: true }]),
item('g/ops/oncall_page', [{ type: 'group_path', group: 'ops' }]),
item('f/reporting/archive/q3_rollup', [{ type: 'folder', folder: 'reporting' }]),
item('f/ledger/close_month', [{ type: 'group', group: 'ops', write: false }]),
item('u/alice/scratch', [{ type: 'own' }])
]
})
expect(tree.map((n) => [n.key, n.whole])).toEqual([
['u/alice', true],
['f/ledger', false],
['f/reporting', true],
['g/ops', true],
['u/bob', false]
])
expect(tree[2].subfolders.map((s) => s.key)).toEqual(['f/reporting/archive'])
})
})
@@ -0,0 +1,149 @@
import type { PrincipalAccess } from '$lib/gen'
export type AccessItem = PrincipalAccess['items'][number]
/** A path segment under a folder or a space, like `archive` in `f/reporting/archive/q3_rollup`. */
export interface AccessPathNode {
/** The full path prefix, e.g. `f/reporting/archive`. */
key: string
name: string
subfolders: AccessPathNode[]
items: { item: AccessItem; name: string }[]
}
/** A top-level row: a folder (`f/x`), a user's space (`u/x`) or a group's space (`g/x`). */
export interface AccessOwnerNode extends AccessPathNode {
/**
* The folder or space itself is held, so every item in it is reachable, items added later
* included. False when only some of its items are shared with the principal, one by one.
*/
whole: boolean
/** The level that holding the whole folder or space gives. */
write: boolean
/** The `u/` or `g/` grants on the folder that reach the principal. */
via: string[]
/** The principal, or one of its groups, is an admin of the folder. */
admin: boolean
}
export type AccessTreeRow =
| { type: 'owner'; node: AccessOwnerNode; depth: number; count: number; open: boolean }
| { type: 'subfolder'; node: AccessPathNode; depth: number; count: number; open: boolean }
| { type: 'item'; item: AccessItem; name: string; owner: AccessOwnerNode; depth: number }
/** Groups a principal's access by where each item lives, as the home page tree does. */
export function buildAccessTree(access: PrincipalAccess): AccessOwnerNode[] {
const owners = new Map<string, AccessOwnerNode>()
const ownerNode = (key: string): AccessOwnerNode => {
let node = owners.get(key)
if (!node) {
node = {
key,
name: key,
whole: false,
write: false,
via: [],
admin: false,
subfolders: [],
items: []
}
owners.set(key, node)
}
return node
}
// A folder is held whole only through a grant on the folder itself. One that only shows up in
// item paths has some of its items shared one by one, and nothing added to it later is reachable.
for (const folder of access.folders) {
Object.assign(ownerNode(`f/${folder.name}`), {
whole: true,
write: folder.write,
via: folder.via,
admin: folder.owner
})
}
for (const item of access.items) {
const segments = item.path.split('/')
const owner = ownerNode(segments.slice(0, 2).join('/'))
// The principal's own `u/` path, and the `g/` path of a group it is in, hold every item
// under them with write. Any other user's or group's space is reached item by item.
if (item.reasons.some((r) => r.type === 'own' || r.type === 'group_path')) {
owner.whole = true
owner.write = true
}
let parent: AccessPathNode = owner
for (const segment of segments.slice(2, -1)) {
let child = parent.subfolders.find((s) => s.name === segment)
if (!child) {
child = { key: `${parent.key}/${segment}`, name: segment, subfolders: [], items: [] }
parent.subfolders.push(child)
}
parent = child
}
parent.items.push({ item, name: segments[segments.length - 1] })
}
const rank = (node: AccessOwnerNode) =>
node.key === access.principal
? 0
: node.key.startsWith('f/')
? 1
: node.key.startsWith('g/')
? 2
: 3
const roots = [...owners.values()].sort((a, b) => rank(a) - rank(b) || a.key.localeCompare(b.key))
roots.forEach(sortNode)
return roots
}
function sortNode(node: AccessPathNode): void {
node.subfolders.sort((a, b) => a.name.localeCompare(b.name))
node.items.sort((a, b) => a.name.localeCompare(b.name))
node.subfolders.forEach(sortNode)
}
export function countItems(node: AccessPathNode, matches: (item: AccessItem) => boolean): number {
return (
node.items.filter(({ item }) => matches(item)).length +
node.subfolders.reduce((n, sub) => n + countItems(sub, matches), 0)
)
}
/**
* The rows to render, top to bottom. A filter opens every branch holding a match and drops the
* rest; without one, every folder and space shows, a folder held whole with no items included.
*/
export function flattenAccessTree(
roots: AccessOwnerNode[],
{
matches,
isOpen,
filtering
}: {
matches: (item: AccessItem) => boolean
isOpen: (key: string) => boolean
filtering: boolean
}
): AccessTreeRow[] {
const rows: AccessTreeRow[] = []
const walk = (node: AccessPathNode, owner: AccessOwnerNode, depth: number) => {
for (const sub of node.subfolders) {
const count = countItems(sub, matches)
if (count === 0) continue
const open = filtering || isOpen(sub.key)
rows.push({ type: 'subfolder', node: sub, depth, count, open })
if (open) walk(sub, owner, depth + 1)
}
for (const { item, name } of node.items) {
if (matches(item)) rows.push({ type: 'item', item, name, owner, depth })
}
}
for (const owner of roots) {
const count = countItems(owner, matches)
if (filtering && count === 0) continue
const open = count > 0 && (filtering || isOpen(owner.key))
rows.push({ type: 'owner', node: owner, depth: 0, count, open })
if (open) walk(owner, owner, 1)
}
return rows
}
@@ -20,6 +20,7 @@
import Row from '$lib/components/table/Row.svelte'
import Badge from '$lib/components/common/badge/Badge.svelte'
import { untrack } from 'svelte'
import { page } from '$app/stores'
import { DEMO_RESTRICTION_HINT, isDemoWorkspaceRestricted } from '$lib/cloud'
let restricted = $derived(
@@ -54,6 +55,20 @@
}
})
// Deep link: #f/<name> opens that folder's drawer. The `f/` prefix keeps it apart from
// global drawer hashes like #superadmin-settings, which a bare folder name could collide with.
let handledHash = ''
$effect(() => {
const hash = $page.url.hash
if (!hash.startsWith('#f/')) {
handledHash = ''
return
}
if (hash === handledHash || !folderEditorDrawer) return
handledHash = hash
folderEditorDrawer.initEdit(decodeURIComponent(hash.slice(3)))
})
function computeMembers(owners: string[], extra_perms: Record<string, any>) {
const members = new Set(owners)
for (const [user, _] of Object.entries(extra_perms)) {