feat: grant and revoke from one row button in the grant navigator

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Guilhem Lemouel
2026-11-11 07:32:14 -08:00
co-authored by Claude Opus 5.5
parent 9b8eec16b7
commit b0f3b5bc3c
6 changed files with 587 additions and 162 deletions
@@ -224,13 +224,29 @@
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. */
/** Grants on the item itself, which decide whether its level reads as its own. */
function itemGrants(item: AccessItem): string[] {
return item.reasons.flatMap((r) =>
r.type === 'user' ? ['Shared directly'] : r.type === 'group' ? [viaLabel(`g/${r.group}`)] : []
)
}
/** Every reason the item is held: its own grants, then its folder or space. */
function itemReasons(item: AccessItem): string[] {
const labels = item.reasons.map((r) =>
r.type === 'user'
? 'Shared directly'
: r.type === 'group'
? viaLabel(`g/${r.group}`)
: r.type === 'folder'
? `Through f/${r.folder}`
: r.type === 'group_path'
? `Through g/${r.group}`
: 'Own path'
)
return [...new Set(labels)]
}
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' : ''
@@ -364,7 +380,7 @@
{/snippet}
{#snippet content()}
{#if access}
<GrantNavigator {principal} {access} onGranted={reload} />
<GrantNavigator {principal} {access} onChange={reload} />
{/if}
{/snippet}
</Popover>
@@ -526,7 +542,7 @@
>{item.write ? 'Write' : 'Read'}</span
>
</Cell>
<Cell>{grants.join(', ')}</Cell>
<Cell>{itemReasons(item).join(', ')}</Cell>
<Cell last actions>
{@const own = ownItemGrant(item)}
{#if own !== undefined}
+225 -85
View File
@@ -13,7 +13,8 @@ level *up*. Filter (internal or `externalFilter`) is global across all
leaves and ignores the current scope.
-->
<script lang="ts" generics="L">
import { ChevronLeft, ChevronRight, Loader2 } from 'lucide-svelte'
import { CheckCircle2, ChevronLeft, ChevronRight, Loader2 } from 'lucide-svelte'
import { fade, fly } from 'svelte/transition'
import TextInput from '$lib/components/text_input/TextInput.svelte'
import SearchItems from '$lib/components/SearchItems.svelte'
import Portal from '$lib/components/Portal.svelte'
@@ -30,6 +31,7 @@ leaves and ignores the current scope.
type DrillBranch,
type DrillIcon,
type DrillLeaf,
type DrillLeafAction,
type DrillNode
} from './drillPicker'
import Badge from '$lib/components/common/badge/Badge.svelte'
@@ -39,7 +41,10 @@ leaves and ignores the current scope.
interface Props {
tree: DrillNode<L>[]
onPick: (leaf: DrillLeaf<L>) => void
/** Picking a leaf: a click, or Enter on its highlighted row. Without it, a click on a leaf
* does nothing and Enter runs the highlighted row's selected `leafActions` button, for a
* picker whose rows act only through their buttons. */
onPick?: (leaf: DrillLeaf<L>) => void
/** Drill path to land on initially. Empty = root. */
initialScope?: string[]
/** Composite key of the row to highlight initially. */
@@ -87,13 +92,22 @@ leaves and ignores the current scope.
leaf: DrillLeaf<L>
) => { icon: DrillIcon; label: string; title: string; run: () => void } | undefined
/** Status badge on the right of a leaf row. Returns `undefined` for a leaf with
* nothing to report. The hover action, when there is one, covers it. */
* nothing to report. The hover action, when there is one, covers it. With `leafActions` it
* is plain text and `color` is unused. */
leafBadge?: (leaf: DrillLeaf<L>) => { label: string; color: BadgeColor } | undefined
/** Where picking a leaf navigates, for a host whose pick is a navigation. The row then
* renders as a link: a plain click still goes through `onPick`, while a middle or
* ⌘/Ctrl-click opens it in a new tab — taking ⌘/Ctrl-click from `leafAction`, which
* keeps ⌘/Ctrl-Enter. */
leafHref?: (leaf: DrillLeaf<L>) => string | undefined
/** What a leaf row offers, laid over its end while the row is highlighted (hovered or reached
* with the arrow keys), so the row does not reflow: the `preferred` one (else the first) as a
* button, which Enter runs when there is no `onPick`, and the others in its dropdown. In
* place of `leafAction`, not with it. */
leafActions?: (leaf: DrillLeaf<L>) => DrillLeafAction[] | undefined
/** What a `leafActions` button just did on a leaf ("Read granted"), shown over the row's
* end, highlighted or not, while it returns a text. */
leafDone?: (leaf: DrillLeaf<L>) => string | undefined
}
let {
@@ -113,7 +127,9 @@ leaves and ignores the current scope.
rowTooltip,
leafAction,
leafBadge,
leafHref
leafHref,
leafActions,
leafDone
}: Props = $props()
let searchInput: TextInput | undefined = $state()
@@ -302,7 +318,9 @@ leaves and ignores the current scope.
// Ignored until the user actually moves the mouse. Prevents the
// cursor (parked over a row) from clobbering keyboard-driven
// selection when the layout shifts beneath it.
if (mouseActive) highlightedKey = key
// A row's open menu sits over the rows below it, and the pointer crosses them to reach it:
// moving the highlight would take the menu's button away.
if (mouseActive && !actionMenuOpen) highlightedKey = key
}
/** `alt` picks the row's second action (see `leafAction`) rather than the row
@@ -310,6 +328,10 @@ leaves and ignores the current scope.
* that only appears on hover. A leaf with no second action ignores it. */
function pick(leaf: DrillLeaf<L>, alt = false) {
if (leaf.disabled) return
if (!onPick) {
if (leaf.key === highlightedKey) runMainAction()
return
}
// The second action is the row's other destination (its editor, for the deployed page
// this tab shows), so it stays available on the current row the plain pick skips.
if (alt) {
@@ -323,6 +345,25 @@ leaves and ignores the current scope.
onPick(leaf)
}
function runMainAction() {
const action = mainAction
if (action && !action.disabled && !action.loading) runAction(action)
}
/** The button area's width when each row's action ran: its success pill keeps it, since
* `actionsWidth` follows the highlighted row and would resize the pill on hover. */
let pillWidths: Record<string, number> = $state({})
function runAction(action: DrillLeafAction) {
if (highlightedKey) pillWidths[highlightedKey] = actionsWidth
action.run()
}
/** Fades out what lies under the highlighted row's buttons, which sit over its end. */
function fadeUnder(width: number): string {
const mask = `linear-gradient(to left, transparent ${width}px, #000 ${width + 16}px)`
return `mask-image: ${mask}; -webkit-mask-image: ${mask}`
}
// Single shared hover tooltip (opt-in via `rowTooltip`): one floating node
// re-anchored to the hovered row, instead of a popover per row — rows can
// number in the hundreds. Portaled to body because the picker often lives
@@ -385,6 +426,17 @@ leaves and ignores the current scope.
}
function handleSearchKeydown(e: KeyboardEvent) {
// A row's button has focus only after a click: it keeps its own keys, and Enter must not
// also reach the row. ↑/↓ and Escape return to the search field.
if ((e.target as HTMLElement | null)?.closest?.('[data-drill-action]')) {
if (e.key === 'ArrowDown' || e.key === 'ArrowUp' || e.key === 'Escape') {
e.preventDefault()
e.stopPropagation()
focus()
if (e.key !== 'Escape') moveHighlight(e.key === 'ArrowDown' ? 1 : -1)
}
return
}
if (e.key === 'ArrowDown') {
e.preventDefault()
e.stopPropagation()
@@ -400,6 +452,8 @@ leaves and ignores the current scope.
// highlighted row so an unrelated Tab in an empty picker still
// falls through to natural focus movement.
if (e.key === 'Tab' && !highlightedKey) return
// Without `onPick`, Enter on a leaf runs its selected button, which Tab must not do.
if (e.key === 'Tab' && !onPick && leafForKey(highlightedKey!)) return
e.preventDefault()
e.stopPropagation()
mouseActive = false
@@ -484,6 +538,22 @@ leaves and ignores the current scope.
})
const branchLoading = $derived(currentBranch ? (currentBranch.loading ?? false) : rootLoading)
const highlightedNode = $derived.by<DrillNode<L> | undefined>(() => {
if (!highlightedKey) return undefined
if (isSearching) return (searchedItems ?? []).find((r) => r.leaf.key === highlightedKey)?.leaf
return entryList.find((e) => e.key === highlightedKey)?.node
})
const highlightedActions = $derived(
highlightedNode?.type === 'leaf' && !highlightedNode.disabled
? (leafActions?.(highlightedNode) ?? [])
: []
)
const mainAction = $derived(highlightedActions.find((a) => a.preferred) ?? highlightedActions[0])
const otherActions = $derived(highlightedActions.filter((a) => a !== mainAction))
let actionMenuOpen = $state(false)
let actionsWidth = $state(0)
</script>
<SearchItems
@@ -525,6 +595,9 @@ leaves and ignores the current scope.
{@const action = leaf.disabled ? undefined : leafAction?.(leaf)}
{@const badge = leafBadge?.(leaf)}
{@const href = leaf.disabled ? undefined : leafHref?.(leaf)}
{@const inert = !onPick}
{@const actions = isHl ? highlightedActions : []}
{@const done = leafDone?.(leaf)}
<!-- The row's action sits BESIDE the option rather than inside it: a button nested in
a button is invalid markup. The wrapper carries the row's padding, highlight and
hover group so the two still read as one row. -->
@@ -534,99 +607,166 @@ leaves and ignores the current scope.
<!-- A disabled option dims through `disabled:opacity-50` and shows its cursor on this wrapper:
the base `button:disabled` rule in tailwind.config.cjs outranks a plain `opacity-50` and
turns pointer events off on the button itself. -->
<!-- `leafActions` show only on the highlighted row, so a pointer that comes back after the
arrow keys moved the highlight takes it on its first move, not on the next row it enters. -->
<div
class="group flex items-center transition-colors pr-3 {baseClass} {isHl
class="group relative flex items-center transition-colors pr-3 {baseClass} {isHl
? 'bg-surface-hover'
: ''} {leaf.disabled ? 'cursor-not-allowed' : ''}"
onmouseenter={(e) => {
setHoverHighlight(key)
tooltipEnter(e.currentTarget as HTMLElement, leaf)
}}
onmousemove={leafActions && !isHl ? () => setHoverHighlight(key) : undefined}
onmouseleave={tooltipLeave}
>
<svelte:element
this={href ? 'a' : 'button'}
type={href ? undefined : 'button'}
{href}
id={idFor(key)}
role="option"
aria-selected={isHl}
data-nav-key={key}
aria-current={isCur ? 'true' : undefined}
aria-label={tip ? `${leaf.label} — ${tip}` : undefined}
class="min-w-0 flex-1 text-left flex items-center gap-2 pl-3 {isCur
? 'cursor-default text-emphasis font-medium'
: 'text-[color:inherit]'} disabled:opacity-50"
disabled={href ? undefined : leaf.disabled}
tabindex={0}
onmousedown={(e: MouseEvent) => e.preventDefault()}
onclickcapture={(e: MouseEvent) => {
// Capture, not a delegated onclick: the picker is portalled outside the app root,
// where a delegated handler runs after SvelteKit's link handler has already
// followed the href, too late for preventDefault to keep a plain click on `pick`.
if (href && isNewTabClick(e)) return
e.preventDefault()
pick(leaf, e.metaKey || e.ctrlKey)
}}
<!-- With `leafActions`, what fades out under the row's buttons; `contents` otherwise. -->
<div
class={leafActions ? 'min-w-0 flex-1 flex items-center' : 'contents'}
style={actions.length ? fadeUnder(actionsWidth) : undefined}
>
{@render defaultLeafIcon(leaf)}
<!-- Centred in a two-line row's height so a one-line leaf sits where a two-line
one's pair does, rather than riding high against the top. A list with no
second line anywhere (a picker's pages) keeps its rows one line tall. -->
<div
class="min-w-0 flex-1 flex flex-col justify-center {twoLineHeight ? 'min-h-[2.25rem]' : ''}"
<svelte:element
this={href ? 'a' : inert ? 'div' : 'button'}
type={href || inert ? undefined : 'button'}
{href}
id={idFor(key)}
role="option"
aria-selected={isHl}
aria-disabled={inert && leaf.disabled ? 'true' : undefined}
data-nav-key={key}
aria-current={isCur ? 'true' : undefined}
aria-label={tip ? `${leaf.label} — ${tip}` : undefined}
class="min-w-0 flex-1 text-left flex items-center gap-2 pl-3 {isCur
? 'cursor-default text-emphasis font-medium'
: 'text-[color:inherit]'} {inert
? leaf.disabled
? 'opacity-50'
: 'cursor-default'
: 'disabled:opacity-50'}"
disabled={href || inert ? undefined : leaf.disabled}
tabindex={inert ? -1 : 0}
onmousedown={(e: MouseEvent) => e.preventDefault()}
onclickcapture={inert
? undefined
: (e: MouseEvent) => {
// Capture, not a delegated onclick: the picker is portalled outside the app root,
// where a delegated handler runs after SvelteKit's link handler has already
// followed the href, too late for preventDefault to keep a plain click on `pick`.
if (href && isNewTabClick(e)) return
e.preventDefault()
pick(leaf, e.metaKey || e.ctrlKey)
}}
>
{#if leaf.secondary}
<div class="text-xs text-primary font-normal truncate">{leaf.label}</div>
<div class="text-2xs text-hint font-normal font-mono truncate">
{secondary ?? leaf.secondary}
</div>
{:else}
<div class="text-xs text-primary font-normal font-mono truncate">
{secondary ?? leaf.label}
</div>
{@render defaultLeafIcon(leaf)}
<!-- Centred in a two-line row's height so a one-line leaf sits where a two-line
one's pair does, rather than riding high against the top. A list with no
second line anywhere (a picker's pages) keeps its rows one line tall. -->
<div
class="min-w-0 flex-1 flex flex-col justify-center {twoLineHeight
? 'min-h-[2.25rem]'
: ''}"
>
{#if leaf.secondary}
<div class="text-xs text-primary font-normal truncate">{leaf.label}</div>
<div class="text-2xs text-hint font-normal font-mono truncate">
{secondary ?? leaf.secondary}
</div>
{:else}
<div class="text-xs text-primary font-normal font-mono truncate">
{secondary ?? leaf.label}
</div>
{/if}
</div>
</svelte:element>
{#if leafActions}
<!-- Plain text beside the row's buttons, which sit over it while the row is
highlighted: a filled badge reads as one more button. -->
{#if badge}
<span class="shrink-0 pl-2 text-xs text-secondary">{badge.label}</span>
{/if}
<!-- Keyed on the props rather than on this leaf's own badge or action, so a picker
that has either holds the column open on every row: paths then truncate at one
column and the button lands in the same place down the list. -->
{:else if leafBadge || leafAction}
<!-- Both sit in one grid cell so they cross-fade in place rather than sitting
side by side or shifting the row as one replaces the other. -->
<div class="shrink-0 w-[4.5rem] grid justify-items-end items-center pl-2">
{#if action}
<!-- `invisible`, not `hidden`: display cannot be transitioned, while
visibility both fades with opacity and keeps the button out of the tab
order while it is out of sight — the picker's focus belongs to its
search field, and rows are reached with the arrow keys.
The classes sit on this wrapper, not on the Button: `wrapperClasses` is
twMerged with the button's own `flex`, which drops a conflicting
display and leaves it showing beside the badge. -->
<div
class="col-start-1 row-start-1 invisible opacity-0 transition-[opacity,visibility] duration-150 group-hover:visible group-hover:opacity-100"
>
<Button
unifiedSize="xs"
variant="default"
title={action.title}
startIcon={{ icon: action.icon }}
onClick={action.run}
wrapperClasses="shrink-0"
>
{action.label}
</Button>
</div>
{/if}
{#if badge}
<div
class="col-start-1 row-start-1 transition-[opacity,visibility] duration-150 {action
? 'group-hover:invisible group-hover:opacity-0'
: ''}"
>
<Badge small color={badge.color}>{badge.label}</Badge>
</div>
{/if}
</div>
{/if}
</div>
{#if actions.length}
<!-- Over the row's end, so a row keeps its layout whether or not it shows them. -->
<div
class="absolute inset-y-0 right-3 flex items-center gap-1"
bind:clientWidth={actionsWidth}
>
{#if mainAction && !done}
<!-- Local, so it waits for the pill to leave but not for a hover. -->
<span data-drill-action in:fade={{ delay: 150, duration: 100 }}>
<Button
unifiedSize="sm"
variant="default"
startIcon={mainAction.icon ? { icon: mainAction.icon } : undefined}
loading={mainAction.loading}
disabled={mainAction.disabled}
onClick={() => mainAction && runAction(mainAction)}
dropdownItems={otherActions.map((a) => ({
label: a.label,
description: a.hint,
icon: a.icon,
disabled: a.disabled || a.loading,
onClick: () => runAction(a)
}))}
bind:dropdownOpen={actionMenuOpen}
>
{mainAction.label}
</Button>
</span>
{/if}
</div>
</svelte:element>
<!-- Keyed on the props rather than on this leaf's own badge or action, so a picker
that has either holds the column open on every row: paths then truncate at one
column and the button lands in the same place down the list. -->
{#if leafBadge || leafAction}
<!-- Both sit in one grid cell so they cross-fade in place rather than sitting
side by side or shifting the row as one replaces the other. -->
<div class="shrink-0 w-[4.5rem] grid justify-items-end items-center pl-2">
{#if action}
<!-- `invisible`, not `hidden`: display cannot be transitioned, while
visibility both fades with opacity and keeps the button out of the tab
order while it is out of sight — the picker's focus belongs to its
search field, and rows are reached with the arrow keys.
The classes sit on this wrapper, not on the Button: `wrapperClasses` is
twMerged with the button's own `flex`, which drops a conflicting
display and leaves it showing beside the badge. -->
<div
class="col-start-1 row-start-1 invisible opacity-0 transition-[opacity,visibility] duration-150 group-hover:visible group-hover:opacity-100"
>
<Button
unifiedSize="xs"
variant="default"
title={action.title}
startIcon={{ icon: action.icon }}
onClick={action.run}
wrapperClasses="shrink-0"
>
{action.label}
</Button>
</div>
{/if}
{#if badge}
<div
class="col-start-1 row-start-1 transition-[opacity,visibility] duration-150 {action
? 'group-hover:invisible group-hover:opacity-0'
: ''}"
>
<Badge small color={badge.color}>{badge.label}</Badge>
</div>
{/if}
{/if}
{#if done}
<!-- SaveButton's success pill, over the row's button and its dropdown chevron. -->
<div
class="absolute inset-y-0 my-auto h-7 right-3 z-10 flex items-center justify-center gap-1.5 px-2 rounded-md text-xs font-medium whitespace-nowrap overflow-hidden bg-green-200 dark:bg-green-800 text-green-800 dark:text-green-200"
style={pillWidths[leaf.key] ? `width: ${pillWidths[leaf.key]}px` : undefined}
role="status"
transition:fly={{ y: -10, duration: 150 }}
>
<CheckCircle2 size={14} class="shrink-0" />
{done}
</div>
{/if}
</div>
@@ -1,18 +1,21 @@
<!--
@component
The access view's "+ Grant" list: the caller's own `u/` folder and every folder, with their items.
Picking a row grants the principal read on it; the "All of f/x" row grants the whole folder.
A row does nothing when clicked. The highlighted row offers each change to the principal's own
grant on it that changes what the principal can do (grant read or write, revoke write or read),
the most useful one as its button and the others in its dropdown. The "All of f/x" row
changes the grant on the whole folder.
-->
<script module lang="ts">
/** The navigator's tallest height, `max-h-[min(420px,60vh)]` below, for its host to place it. */
/** The navigator's tallest height, `max-h-[min(460px,60vh)]` below, for its host to place it. */
export function navigatorMaxHeight(): number {
return Math.min(420, window.innerHeight * 0.6)
return Math.min(460, window.innerHeight * 0.6)
}
</script>
<script lang="ts">
import DrillPicker from '$lib/components/DrillPicker.svelte'
import type { DrillLeaf, DrillNode } from '$lib/components/drillPicker'
import type { DrillLeaf, DrillLeafAction, DrillNode } from '$lib/components/drillPicker'
import RowIcon from '$lib/components/common/table/RowIcon.svelte'
import {
GranularAclService,
@@ -28,7 +31,9 @@ Picking a row grants the principal read on it; the "All of f/x" row grants the w
import { sendUserToast } from '$lib/toast'
import { debounce } from '$lib/utils'
import { Folder, User, Users } from 'lucide-svelte'
import { setGrant } from './access'
import ConfirmationModal from '$lib/components/common/confirmationModal/ConfirmationModal.svelte'
import { setOverlayHost } from '$lib/components/common/overlayHost.svelte'
import { setGrant, type GrantLevel, type GrantSource } from './access'
const operatingWorkspace = useOperatingWorkspace()
const operatingUser = useOperatingUser()
@@ -36,24 +41,51 @@ Picking a row grants the principal read on it; the "All of f/x" row grants the w
type Row = BrowseAccessItemsResponse['items'][number]
/** `kind` `folder` is the "All of f/x" row, its `path` the folder name. */
type Leaf = Row & { owner?: boolean }
/** What the principal holds on a row besides its own entry: the level, `undefined` where the
* access report cannot tell, and where it comes from, in the access table's words. */
type Inherited = { level: GrantLevel | undefined; hows: string[] }
let {
principal,
access,
onGranted
onChange,
source
}: {
principal: string
access: PrincipalAccess
onGranted: () => void
/** After each change to a grant, for the host to reload `access`. */
onChange: () => void
source?: GrantSource
} = $props()
const own = $derived(`u/${operatingUser.current?.username}`)
const api: GrantSource = {
get ownSpace() {
return `u/${operatingUser.current?.username}`
},
folders: () =>
GranularAclService.browseAccessFolders({ workspace: $operatingWorkspace!, principal }),
items: (query) =>
GranularAclService.browseAccessItems({
workspace: $operatingWorkspace!,
principal,
...query
}),
set: (kind, path, level) => setGrant($operatingWorkspace!, kind, path, principal, level)
}
const data = $derived(source ?? api)
const own = $derived(data.ownSpace)
let picker: { focus: () => void } | undefined = $state()
let folders: BrowseAccessFoldersResponse | undefined = $state()
/** Rows by top-level branch (`u/alice`, `f/billing`), then by `kind:path`. */
let rows: Record<string, Record<string, Row>> = $state({})
let loading: Record<string, boolean> = $state({})
const loaded = new Set<string>()
/** The change in flight, as `kind:path:label`. */
let pending: string | undefined = $state()
/** Runs before this time are ignored: the second press of a double click or Enter would
* otherwise run the button that took the first one's place. */
let settledUntil = 0
function branchOf(path: string): string {
return path.split('/', 2).join('/')
@@ -69,10 +101,7 @@ Picking a row grants the principal read on it; the "All of f/x" row grants the w
async function loadFolders() {
try {
folders = await GranularAclService.browseAccessFolders({
workspace: $operatingWorkspace!,
principal
})
folders = await data.folders()
} catch (e) {
sendUserToast(`Could not load folders: ${e?.body ?? e}`, true)
}
@@ -85,12 +114,7 @@ Picking a row grants the principal read on it; the "All of f/x" row grants the w
try {
let offset = 0
while (true) {
const page = await GranularAclService.browseAccessItems({
workspace: $operatingWorkspace!,
principal,
prefix: `${branch}/`,
offset
})
const page = await data.items({ prefix: `${branch}/`, offset })
merge(page.items)
// The branch shows from its first page; later pages fill it in as they arrive.
loading[branch] = false
@@ -108,12 +132,7 @@ Picking a row grants the principal read on it; the "All of f/x" row grants the w
// The picker searches only the rows it holds, so matches anywhere are fetched into the tree.
const searchSoon = debounce(async (search: string) => {
try {
const page = await GranularAclService.browseAccessItems({
workspace: $operatingWorkspace!,
principal,
search
})
merge(page.items)
merge((await data.items({ search })).items)
} catch (e) {
sendUserToast(`Could not search: ${e?.body ?? e}`, true)
}
@@ -139,6 +158,16 @@ Picking a row grants the principal read on it; the "All of f/x" row grants the w
.map(itemLeaf)
}
function folderData(folder: BrowseAccessFoldersResponse[number]): Leaf {
return {
kind: 'folder',
path: folder.name,
grant: folder.grant,
blocked: folder.blocked,
owner: folder.target_owner
}
}
const tree = $derived.by<DrillNode<Leaf>[]>(() => {
const folderNames = new Set((folders ?? []).map((f) => `f/${f.name}`))
const others = Object.keys(rows)
@@ -168,13 +197,7 @@ Picking a row grants the principal read on it; the "All of f/x" row grants the w
key: `folder:${folder.name}`,
label: `All of f/${folder.name}`,
searchableText: `f/${folder.name}`,
data: {
kind: 'folder',
path: folder.name,
grant: folder.grant,
blocked: folder.blocked,
owner: folder.target_owner
},
data: folderData(folder),
disabled: folder.target_owner || !!folder.blocked
},
...itemLeaves(`f/${folder.name}`)
@@ -195,49 +218,240 @@ Picking a row grants the principal read on it; the "All of f/x" row grants the w
]
})
const reaches = $derived(
new Map<string, boolean>([
...access.items.map((i) => [`${i.kind}:${i.path}`, i.write] as const),
...access.folders.map((f) => [`folder:${f.name}`, f.write] as const)
])
)
/** How the principal reaches each item it reaches, by `kind:path`. */
const reasons = $derived(
new Map<string, AccessReason[]>(
access.items.map((i) => [`${i.kind}:${i.path}`, i.reasons] as const)
)
)
const reachedFolders = $derived(new Map(access.folders.map((f) => [f.name, f])))
async function grant(leaf: DrillLeaf<Leaf>) {
const row = leaf.data
if (row.grant != undefined) return
try {
await setGrant($operatingWorkspace!, row.kind, row.path, principal, 'read')
row.grant = false
if (row.kind === 'folder') {
const folder = folders?.find((f) => f.name === row.path)
if (folder) folder.grant = false
}
onGranted()
} catch (e) {
const what = row.kind === 'folder' ? `f/${row.path}` : row.path
sendUserToast(`Could not grant ${what}: ${e?.body ?? e}`, true)
const isGroup = $derived(principal.startsWith('g/'))
const who = $derived(isGroup ? `members of ${principal}` : principal)
/** What read and write let the principal do, by kind. */
const GIVES: Record<string, { read: string; write: string }> = {
folder: { read: 'read all its items, new ones included', write: 'edit and add items' },
script: { read: 'see and run it', write: 'edit it' },
flow: { read: 'see and run it', write: 'edit it' },
app: { read: 'open and use it', write: 'edit it' },
raw_app: { read: 'open and use it', write: 'edit it' },
resource: { read: 'use it and see its value', write: 'change its value' },
variable: { read: 'use it and see its value', write: 'change its value' },
schedule: { read: 'see it', write: 'edit, enable and disable it' }
}
const GIVES_OTHER = { read: 'see it', write: 'edit it' }
const LEVELS: GrantLevel[] = ['none', 'read', 'write']
const LEVEL_LABELS: Record<GrantLevel, string> = {
none: 'No access',
read: 'Read',
write: 'Write'
}
function maxLevel(a: GrantLevel, b: GrantLevel): GrantLevel {
return LEVELS.indexOf(a) >= LEVELS.indexOf(b) ? a : b
}
function entryLevel(grant: boolean | null | undefined): GrantLevel {
return grant == undefined ? 'none' : grant ? 'write' : 'read'
}
/** The principal's own entry on an item, which `grant` on its row holds. */
function isOwnEntry(r: AccessReason): boolean {
return r.type === 'user' || (r.type === 'group' && `g/${r.group}` === principal)
}
function reasonLabel(r: AccessReason): string {
switch (r.type) {
case 'folder':
return `through f/${r.folder}`
case 'group':
return `through g/${r.group}`
case 'own':
return `under ${principal}/`
case 'group_path':
return `under g/${r.group}/`
default:
return 'shared directly'
}
}
function tooltip(leaf: DrillLeaf<Leaf>): string | undefined {
function inheritedOf(row: Leaf, key: string): Inherited {
if (row.kind === 'folder') {
if (row.owner) return { level: 'write', hows: ['folder admin'] }
const folder = reachedFolders.get(row.path)
const others = (folder?.via ?? []).filter((v) => v !== principal)
if (!folder || others.length === 0) return { level: 'none', hows: [] }
// `via` names the other entries without their levels, so next to the principal's own
// write the report cannot tell whether one of them gives write too.
const level = folder.grant === true ? undefined : folder.write ? 'write' : 'read'
return { level, hows: others.map((v) => `through ${v}`) }
}
const others = (reasons.get(key) ?? []).filter((r) => !isOwnEntry(r))
const level: GrantLevel =
others.length === 0
? 'none'
: others.some((r) => r.type === 'own' || r.type === 'group_path' || r.write)
? 'write'
: 'read'
return { level, hows: others.map(reasonLabel) }
}
/** The level held on a row. The own entry is read from the row, which a change made here
* updates before `access` reloads. */
function levelOf(row: Leaf, key: string): GrantLevel {
return maxLevel(inheritedOf(row, key).level ?? 'read', entryLevel(row.grant))
}
function pathOf(row: Leaf): string {
return row.kind === 'folder' ? `f/${row.path}` : row.path
}
/** Why a dimmed row can't be changed, for its tooltip. */
function lockedText(row: Leaf): string | undefined {
if (row.owner)
return `${principal} is an admin of f/${row.path}, so ${isGroup ? 'its members' : 'they'} can write every item in it.`
return row.blocked
}
/** Selected on a highlighted row, the first of these it offers. */
const PREFERRED = ['Grant read', 'Grant write', 'Revoke write', 'Revoke read']
function actionsFor(leaf: DrillLeaf<Leaf>): DrillLeafAction[] {
const row = leaf.data
if (row.owner) return `${principal} owns f/${row.path} and always keeps write`
if (row.blocked) return row.blocked
if (row.grant != undefined)
return `Already granted ${row.grant ? 'write' : 'read'}: change it from the table`
const write = reaches.get(leaf.key)
if (write === undefined) return undefined
const already = `Already ${write ? 'writes' : 'reads'} it`
const folder = reasons.get(leaf.key)?.find((r) => r.type === 'folder')?.folder
return folder
? `${already} through f/${folder}: picking it adds a direct grant, which stays even if f/${folder} is no longer shared`
: `${already}: picking it adds a direct grant, which stays even if that access is removed`
const ownLevel = entryLevel(row.grant)
const inherited = inheritedOf(row, leaf.key)
const level = maxLevel(inherited.level ?? 'read', ownLevel)
const gives = GIVES[row.kind] ?? GIVES_OTHER
// In the order of the level each one leaves, so the buttons read from less to more access.
const changes: { label: string; to: GrantLevel; hint: string }[] = []
if (ownLevel !== 'none' && inherited.level === 'none') {
changes.push({
label: 'Revoke read',
to: 'none',
hint: `${who} can no longer ${gives.read}.`
})
}
if (level === 'none') {
changes.push({ label: 'Grant read', to: 'read', hint: `${who} can ${gives.read}.` })
}
if (ownLevel === 'write' && inherited.level !== 'write') {
changes.push({
label: 'Revoke write',
to: 'read',
hint: inherited.level
? `${who} can no longer ${gives.write}, only ${gives.read}.`
: `the grant becomes read, but ${who} may still write ${inherited.hows.join(' or ')}.`
})
}
if (level !== 'write') {
const folder =
row.kind !== 'folder' && ownLevel === 'none'
? (reasons.get(leaf.key) ?? []).find((r) => r.type === 'folder')?.folder
: undefined
changes.push({
label: 'Grant write',
to: 'write',
hint:
level === 'none'
? `${who} can ${gives.read}, and ${gives.write}.`
: `${who} can also ${gives.write}.` +
(folder ? ` This grant stays if f/${folder} is no longer shared.` : '')
})
}
const preferred = PREFERRED.find((label) => changes.some((c) => c.label === label))
return changes.map((c) => ({
label: c.label,
hint: c.hint,
preferred: c.label === preferred,
loading: pending === `${leaf.key}:${c.label}`,
disabled: pending !== undefined,
run: () => change(leaf, c.label, c.to)
}))
}
/** A change to a whole folder, waiting for the dialog. */
let confirming:
| { leaf: DrillLeaf<Leaf>; label: string; level: GrantLevel; hint: string }
| undefined = $state()
function change(leaf: DrillLeaf<Leaf>, label: string, level: GrantLevel) {
if (pending !== undefined || Date.now() < settledUntil) return
if (leaf.data.kind !== 'folder') {
apply(leaf, label, level)
return
}
const hint = actionsFor(leaf).find((a) => a.label === label)?.hint ?? ''
confirming = { leaf, label, level, hint }
// Else the second press of a double click or Enter would confirm it at once.
settledUntil = Date.now() + 400
}
async function confirmFolder() {
if (!confirming || pending !== undefined || Date.now() < settledUntil) return
await apply(confirming.leaf, confirming.label, confirming.level)
confirming = undefined
}
function cancelFolder() {
if (pending !== undefined) return
confirming = undefined
picker?.focus()
}
/** Focus stays in the search field under the dialog, so its keys are answered here: the
* dialog's own window listener leaves alone keys that start inside a popover, which is where
* the access drawer shows this list. */
function dialogKeys(e: KeyboardEvent) {
if (!confirming || e.key === 'Tab') return
e.preventDefault()
e.stopPropagation()
if (e.key === 'Enter') confirmFolder()
else if (e.key === 'Escape') cancelFolder()
}
let root: HTMLElement | undefined = $state()
// The dialog covers this list rather than the page: a click on a dialog over the page lands
// outside the drawer's popover, which closes it and the dialog with it.
setOverlayHost({ el: () => root, drawers: { val: [] }, active: () => true })
const DONE: Record<string, string> = {
'Grant read': 'Read granted',
'Grant write': 'Write granted',
'Revoke write': 'Write revoked',
'Revoke read': 'Access revoked'
}
/** The row a change just landed on, and what it did ("Read granted"), for 1.5s. */
let done: { key: string; text: string } | undefined = $state()
let doneTimer: ReturnType<typeof setTimeout> | undefined
function showDone(key: string, text: string) {
clearTimeout(doneTimer)
done = { key, text }
doneTimer = setTimeout(() => (done = undefined), 1000)
}
async function apply(leaf: DrillLeaf<Leaf>, label: string, level: GrantLevel) {
const row = leaf.data
pending = `${leaf.key}:${label}`
try {
await data.set(row.kind, row.path, level)
row.grant = level === 'none' ? null : level === 'write'
if (row.kind === 'folder') {
const folder = folders?.find((f) => f.name === row.path)
if (folder) folder.grant = row.grant
}
onChange()
showDone(leaf.key, DONE[label] ?? 'Done')
} catch (e) {
sendUserToast(`Could not ${label.toLowerCase()} on ${pathOf(row)}: ${e?.body ?? e}`, true)
} finally {
pending = undefined
settledUntil = Date.now() + 400
// A click left focus on a button, which may be gone now.
picker?.focus()
}
}
</script>
@@ -245,20 +459,41 @@ Picking a row grants the principal read on it; the "All of f/x" row grants the w
<RowIcon kind={leaf.data.kind as 'folder'} size={12} />
{/snippet}
<div class="flex flex-col max-h-[min(420px,60vh)]">
<div
bind:this={root}
class="relative flex flex-col max-h-[min(460px,60vh)]"
onkeydowncapture={dialogKeys}
role="presentation"
>
{#if confirming}
{@const folder = pathOf(confirming.leaf.data)}
<ConfirmationModal
open
title="{confirming.label} on {folder}?"
confirmationText={confirming.label}
type={confirming.label.startsWith('Revoke') ? 'danger' : 'info'}
loading={pending !== undefined}
onConfirmed={confirmFolder}
onCanceled={cancelFolder}
>
<p>It applies to every item in {folder}: {confirming.hint}</p>
</ConfirmationModal>
{/if}
<DrillPicker
bind:this={picker}
{tree}
onPick={grant}
{leafIcon}
rowTooltip={(leaf) => lockedText(leaf.data)}
rootLoading={!folders}
onScopeChange={(scope) => scope.length === 1 && loadBranch(scope[0])}
onFilterChange={(filter) => filter.trim() && searchSoon(filter.trim())}
rowTooltip={tooltip}
leafActions={actionsFor}
leafDone={(leaf) => (done && done.key === leaf.key ? done.text : undefined)}
leafBadge={(leaf) => {
const write = reaches.get(leaf.key)
return write === undefined
const level = levelOf(leaf.data, leaf.key)
return level === 'none'
? undefined
: { label: write ? 'Writes' : 'Reads', color: write ? 'blue' : 'gray' }
: { label: LEVEL_LABELS[level], color: level === 'write' ? 'blue' : 'gray' }
}}
/>
</div>
+20 -1
View File
@@ -1,7 +1,26 @@
import { GranularAclService } from '$lib/gen'
import {
GranularAclService,
type BrowseAccessFoldersResponse,
type BrowseAccessItemsResponse
} from '$lib/gen'
export type GrantLevel = 'none' | 'read' | 'write'
/** Where the Grant navigator reads and changes grants. Without one it uses the API, in the
* operating workspace. */
export type GrantSource = {
/** The caller's own `u/` space, listed first. */
ownSpace: string
folders: () => Promise<BrowseAccessFoldersResponse>
items: (query: {
prefix?: string
search?: string
offset?: number
}) => Promise<BrowseAccessItemsResponse>
/** Sets the principal's own entry, as `setGrant` does. */
set: (kind: string, path: string, level: GrantLevel) => Promise<void>
}
type AclKind = Parameters<typeof GranularAclService.addGranularAcls>[0]['kind']
export const KIND_LABELS: Record<string, string> = {
@@ -516,9 +516,11 @@
'rounded-md m-0 p-0 center-center h-full',
variant === 'border' ? 'border-0 border-r border-y ' : 'border-0',
'rounded-r-md !rounded-l-none',
size === 'xs2' || size === 'xs' || unifiedSize === 'md' || unifiedSize === 'sm'
? '!w-8'
: '!w-10',
unifiedSize === 'xs' || unifiedSize === '2xs'
? '!w-6'
: size === 'xs2' || size === 'xs' || unifiedSize === 'md' || unifiedSize === 'sm'
? '!w-8'
: '!w-10',
dropdownBtnClasses
)}
>
@@ -32,6 +32,19 @@ export type DrillLeaf<L> = {
disabled?: boolean
}
/** Something a leaf row offers (see the picker's `leafActions`). */
export type DrillLeafAction = {
label: string
icon?: DrillIcon
/** What running it does, shown under its label in the row's dropdown. */
hint?: string
/** The row's button, with the others in its dropdown; the first one is otherwise. */
preferred?: boolean
loading?: boolean
disabled?: boolean
run: () => void
}
/** Branch node — interior entry the user drills into. */
export type DrillBranch<L> = {
type: 'branch'