Polish pass: identity forms, confirm dialogs, policy chips, merged grants, narrow screens
- Tokens: bigger show-once token with primary Copy; warn when no policies are selected (OpenBao then inherits the creator's policies). - Identity forms get headings, wider cards and two-column policy lists. - Replace window.confirm with an in-app confirm dialog (falls back to window.confirm without a provider). - Show policies, aliases and members as chips in the identity tables. - Access panel: one row per secret instead of separate data/metadata rules. - Stack graph details below 60rem; phone-width rules for tables, nav, toolbar. - New favicon and page title; label the root "*" path as "everything". Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d67a9c9b62
commit
0a2054eb41
19 files changed
+551
-67
No files matched your search
@@ -53,7 +53,7 @@ function setup() {
|
||||
|
||||
test('shows managed grants and read-only other policies', async () => {
|
||||
const user = setup()
|
||||
expect(await screen.findByText('secret/data/app/*')).toBeInTheDocument()
|
||||
expect(await screen.findByText('secret/app/*')).toBeInTheDocument()
|
||||
const other = screen.getByText('default').closest('li')!
|
||||
await user.click(within(other).getByRole('button', { name: 'View default' }))
|
||||
expect(await within(other).findByText(/capabilities/)).toBeInTheDocument()
|
||||
@@ -118,9 +118,9 @@ test('revoke asks for confirmation', async () => {
|
||||
vi.mocked(grants.revokeAccess).mockResolvedValue()
|
||||
const user = setup()
|
||||
const confirm = vi.spyOn(window, 'confirm').mockReturnValueOnce(false).mockReturnValueOnce(true)
|
||||
await user.click(await screen.findByRole('button', { name: 'Revoke secret/data/app/*' }))
|
||||
await user.click(await screen.findByRole('button', { name: 'Revoke secret/app/*' }))
|
||||
expect(grants.revokeAccess).not.toHaveBeenCalled()
|
||||
await user.click(screen.getByRole('button', { name: 'Revoke secret/data/app/*' }))
|
||||
await user.click(screen.getByRole('button', { name: 'Revoke secret/app/*' }))
|
||||
expect(grants.revokeAccess).toHaveBeenCalledWith(client, target, ['secret/data/app/*'])
|
||||
confirm.mockRestore()
|
||||
})
|
||||
|
||||
@@ -4,7 +4,10 @@ import type { BaoClient } from '../../api/bao'
|
||||
import { getGrantState, grantAccess, revokeAccess, type Target } from '../../api/grants'
|
||||
import { listKvMounts, readPolicyHcl } from '../../api/secrets'
|
||||
import { KV_CAPABILITIES, kvGrantRules, validateGrantPath, type KvCapability } from '../../model/managed'
|
||||
import { groupGrants } from '../../model/grantRows'
|
||||
import { CapabilityChips } from '../shared/CapabilityChips'
|
||||
import { PathPicker } from './PathPicker'
|
||||
import { useConfirm } from '../shared/useConfirm'
|
||||
|
||||
interface Props {
|
||||
client: BaoClient
|
||||
@@ -28,6 +31,7 @@ function PolicyView({ client, name }: { client: BaoClient; name: string }) {
|
||||
|
||||
export function AccessEditor({ client, target, onClose }: Props) {
|
||||
const qc = useQueryClient()
|
||||
const confirm = useConfirm()
|
||||
const stateKey = ['grant-state', target.kind, target.name]
|
||||
const state = useQuery({ queryKey: stateKey, queryFn: () => getGrantState(client, target) })
|
||||
const mounts = useQuery({ queryKey: ['kv-mounts'], queryFn: () => listKvMounts(client) })
|
||||
@@ -53,7 +57,7 @@ export function AccessEditor({ client, target, onClose }: Props) {
|
||||
return done()
|
||||
},
|
||||
})
|
||||
const revoke = useMutation({ mutationFn: (path: string) => revokeAccess(client, target, [path]), onSuccess: done })
|
||||
const revoke = useMutation({ mutationFn: (paths: string[]) => revokeAccess(client, target, paths), onSuccess: done })
|
||||
|
||||
function submit(e: FormEvent) {
|
||||
e.preventDefault()
|
||||
@@ -63,6 +67,7 @@ export function AccessEditor({ client, target, onClose }: Props) {
|
||||
}
|
||||
|
||||
const s = state.data
|
||||
const rows = groupGrants(s?.managed?.grants ?? [], mounts.data?.map((m) => m.path) ?? [])
|
||||
const editable = !s?.managed || s.managed.editable
|
||||
|
||||
return (
|
||||
@@ -93,28 +98,38 @@ export function AccessEditor({ client, target, onClose }: Props) {
|
||||
</p>
|
||||
)}
|
||||
{showRaw && <pre>{s.hcl}</pre>}
|
||||
{s.managed?.grants.length ? (
|
||||
{rows.length ? (
|
||||
<table aria-label="Granted by EnvBao">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Path</th>
|
||||
<th>Capabilities</th>
|
||||
<th>Secret</th>
|
||||
<th>Can</th>
|
||||
<th />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{s.managed.grants.map((g) => (
|
||||
<tr key={g.path}>
|
||||
{rows.map((row) => (
|
||||
<tr key={row.display}>
|
||||
<td>
|
||||
<code>{g.path}</code>
|
||||
<code>{row.display}</code>
|
||||
{row.wildcard && <span className="tag">everything inside</span>}
|
||||
</td>
|
||||
<td>
|
||||
<CapabilityChips capabilities={row.capabilities} />
|
||||
</td>
|
||||
<td>{g.capabilities.join(', ')}</td>
|
||||
<td>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Revoke ${g.path}`}
|
||||
aria-label={`Revoke ${row.display}`}
|
||||
disabled={!editable}
|
||||
onClick={() => window.confirm(`Revoke ${g.capabilities.join(', ')} on ${g.path}?`) && revoke.mutate(g.path)}
|
||||
onClick={async () => {
|
||||
const ok = await confirm({
|
||||
title: `Revoke access to ${row.display}?`,
|
||||
message: `Removes ${row.capabilities.join(', ')} from ${target.kind} “${target.name}”.`,
|
||||
confirmLabel: 'Revoke',
|
||||
})
|
||||
if (ok) revoke.mutate(row.paths)
|
||||
}}
|
||||
>
|
||||
Revoke
|
||||
</button>
|
||||
|
||||
@@ -4,6 +4,7 @@ import { revokeAccess } from '../../api/grants'
|
||||
import type { AccessGraph, GraphEdge, GraphNode, PolicyInput } from '../../model/graph'
|
||||
import { parseManagedPolicy, type GrantTarget } from '../../model/managed'
|
||||
import { CapabilityChips } from '../shared/CapabilityChips'
|
||||
import { useConfirm } from '../shared/useConfirm'
|
||||
|
||||
export type Selection = { kind: 'node'; id: string } | { kind: 'edge'; id: string }
|
||||
|
||||
@@ -147,6 +148,7 @@ function NodeDetails({ node, full, policies }: { node: GraphNode; full: AccessGr
|
||||
|
||||
function EdgeDetails({ client, edge, full, policies, onRevoked }: { client: BaoClient; edge: GraphEdge; full: AccessGraph } & Pick<Props, 'policies' | 'onRevoked'>) {
|
||||
const qc = useQueryClient()
|
||||
const confirm = useConfirm()
|
||||
const from = nodeById(full, edge.source)
|
||||
const to = nodeById(full, edge.target)
|
||||
const isGrant = from?.type === 'policy' && to?.type === 'path'
|
||||
@@ -186,10 +188,14 @@ function EdgeDetails({ client, edge, full, policies, onRevoked }: { client: BaoC
|
||||
<button
|
||||
type="button"
|
||||
className="danger"
|
||||
onClick={() =>
|
||||
window.confirm(`Revoke access to ${to!.label} from ${ownerMatch[1]} "${ownerMatch[2]}"? Other policies are unaffected.`) &&
|
||||
revoke.mutate()
|
||||
}
|
||||
onClick={async () => {
|
||||
const ok = await confirm({
|
||||
title: `Revoke access to ${to!.label}?`,
|
||||
message: `Removes it from ${ownerMatch[1]} “${ownerMatch[2]}”. Other policies are unaffected.`,
|
||||
confirmLabel: 'Revoke',
|
||||
})
|
||||
if (ok) revoke.mutate()
|
||||
}}
|
||||
disabled={revoke.isPending}
|
||||
>
|
||||
Revoke
|
||||
|
||||
@@ -7,7 +7,7 @@ export function GraphNodeCard({ data }: NodeProps) {
|
||||
<div className="gnode-card">
|
||||
<Handle type="target" position={Position.Left} isConnectable={false} />
|
||||
{kind && <span className="gnode-kind">{kind}</span>}
|
||||
<span className="gnode-label">{label}</span>
|
||||
<span className="gnode-label">{label === '*' ? 'everything (*)' : label}</span>
|
||||
<Handle type="source" position={Position.Right} isConnectable={false} />
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -5,6 +5,8 @@ import { addAlias, deleteAlias, deleteEntity, listEntities, saveEntity, userpass
|
||||
import { AccessEditor } from '../access/AccessEditor'
|
||||
import { ListState } from '../shared/ListState'
|
||||
import { PolicyPicker } from '../shared/PolicyPicker'
|
||||
import { useConfirm } from '../shared/useConfirm'
|
||||
import { NameChips, PolicyChips } from '../shared/PolicyChips'
|
||||
|
||||
interface Draft {
|
||||
name: string
|
||||
@@ -15,6 +17,7 @@ interface Draft {
|
||||
|
||||
export function EntitiesTab({ client }: { client: BaoClient }) {
|
||||
const qc = useQueryClient()
|
||||
const confirm = useConfirm()
|
||||
const entities = useQuery({ queryKey: ['entities'], queryFn: () => listEntities(client) })
|
||||
const [draft, setDraft] = useState<Draft | null>(null)
|
||||
const [accessFor, setAccessFor] = useState<string | null>(null)
|
||||
@@ -71,19 +74,26 @@ export function EntitiesTab({ client }: { client: BaoClient }) {
|
||||
{entities.data?.map((e) => (
|
||||
<tr key={e.id}>
|
||||
<td>{e.name}</td>
|
||||
<td>{e.aliases.map((a) => a.name).join(', ') || '—'}</td>
|
||||
<td>{e.policies.join(', ') || '—'}</td>
|
||||
<td>
|
||||
<NameChips names={e.aliases.map((a) => a.name)} />
|
||||
</td>
|
||||
<td>
|
||||
<PolicyChips policies={e.policies} />
|
||||
</td>
|
||||
<td>
|
||||
<button type="button" aria-label={`Access ${e.name}`} onClick={() => setAccessFor(e.name)}>
|
||||
Access
|
||||
</button>{' '}
|
||||
</button>
|
||||
<button type="button" aria-label={`Edit ${e.name}`} onClick={() => setDraft({ name: e.name, policies: e.policies, isNew: false, entity: e })}>
|
||||
Edit
|
||||
</button>{' '}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Delete ${e.name}`}
|
||||
onClick={() => window.confirm(`Delete entity "${e.name}" and its aliases?`) && remove.mutate(e.name)}
|
||||
onClick={async () => {
|
||||
if (await confirm({ title: `Delete entity “${e.name}”?`, message: 'Its aliases are deleted too. This cannot be undone.', confirmLabel: 'Delete' }))
|
||||
remove.mutate(e.name)
|
||||
}}
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
@@ -107,10 +117,10 @@ export function EntitiesTab({ client }: { client: BaoClient }) {
|
||||
</label>
|
||||
<PolicyPicker client={client} value={draft.policies} onChange={(policies) => setDraft({ ...draft, policies })} />
|
||||
{save.error && <p role="alert">{save.error.message}</p>}
|
||||
<div>
|
||||
<div className="form-actions">
|
||||
<button type="submit" disabled={save.isPending}>
|
||||
Save
|
||||
</button>{' '}
|
||||
</button>
|
||||
<button type="button" onClick={() => setDraft(null)}>
|
||||
Cancel
|
||||
</button>
|
||||
@@ -121,7 +131,13 @@ export function EntitiesTab({ client }: { client: BaoClient }) {
|
||||
{draft.entity.aliases.map((a) => (
|
||||
<div key={a.id}>
|
||||
{a.name}{' '}
|
||||
<button type="button" onClick={() => window.confirm(`Remove alias "${a.name}"?`) && detach.mutate(a.id)}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={async () => {
|
||||
if (await confirm({ title: `Remove alias “${a.name}”?`, message: 'The userpass user is no longer linked to this entity.', confirmLabel: 'Remove' }))
|
||||
detach.mutate(a.id)
|
||||
}}
|
||||
>
|
||||
Remove
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -5,6 +5,8 @@ import { deleteGroup, listEntities, listGroups, saveGroup } from '../../api/iden
|
||||
import { AccessEditor } from '../access/AccessEditor'
|
||||
import { ListState } from '../shared/ListState'
|
||||
import { PolicyPicker } from '../shared/PolicyPicker'
|
||||
import { useConfirm } from '../shared/useConfirm'
|
||||
import { NameChips, PolicyChips } from '../shared/PolicyChips'
|
||||
|
||||
interface Draft {
|
||||
name: string
|
||||
@@ -15,6 +17,7 @@ interface Draft {
|
||||
|
||||
export function GroupsTab({ client }: { client: BaoClient }) {
|
||||
const qc = useQueryClient()
|
||||
const confirm = useConfirm()
|
||||
const groups = useQuery({ queryKey: ['groups'], queryFn: () => listGroups(client) })
|
||||
const entities = useQuery({ queryKey: ['entities'], queryFn: () => listEntities(client) })
|
||||
const [draft, setDraft] = useState<Draft | null>(null)
|
||||
@@ -54,20 +57,26 @@ export function GroupsTab({ client }: { client: BaoClient }) {
|
||||
{groups.data?.map((g) => (
|
||||
<tr key={g.id}>
|
||||
<td>{g.name}</td>
|
||||
<td>{g.member_entity_ids.map(nameOf).join(', ') || '—'}</td>
|
||||
<td>{g.policies.join(', ') || '—'}</td>
|
||||
<td>
|
||||
<NameChips names={g.member_entity_ids.map(nameOf)} />
|
||||
</td>
|
||||
<td>
|
||||
<PolicyChips policies={g.policies} />
|
||||
</td>
|
||||
<td>
|
||||
<button type="button" aria-label={`Access ${g.name}`} onClick={() => setAccessFor(g.name)}>
|
||||
Access
|
||||
</button>{' '}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Edit ${g.name}`}
|
||||
onClick={() => setDraft({ name: g.name, policies: g.policies, members: g.member_entity_ids, isNew: false })}
|
||||
>
|
||||
Edit
|
||||
</button>{' '}
|
||||
<button type="button" aria-label={`Delete ${g.name}`} onClick={() => window.confirm(`Delete group "${g.name}"?`) && remove.mutate(g.name)}>
|
||||
</button>
|
||||
<button type="button" aria-label={`Delete ${g.name}`} onClick={async () => {
|
||||
if (await confirm({ title: `Delete group “${g.name}”?`, message: 'This cannot be undone.', confirmLabel: 'Delete' })) remove.mutate(g.name)
|
||||
}}>
|
||||
Delete
|
||||
</button>
|
||||
</td>
|
||||
@@ -88,7 +97,7 @@ export function GroupsTab({ client }: { client: BaoClient }) {
|
||||
Name
|
||||
<input value={draft.name} disabled={!draft.isNew} onChange={(e) => setDraft({ ...draft, name: e.target.value })} required />
|
||||
</label>
|
||||
<fieldset>
|
||||
<fieldset className="pick-grid">
|
||||
<legend>Member entities</legend>
|
||||
{entities.data?.map((e) => (
|
||||
<label key={e.id} className="check">
|
||||
@@ -106,10 +115,10 @@ export function GroupsTab({ client }: { client: BaoClient }) {
|
||||
</fieldset>
|
||||
<PolicyPicker client={client} value={draft.policies} onChange={(policies) => setDraft({ ...draft, policies })} />
|
||||
{save.error && <p role="alert">{save.error.message}</p>}
|
||||
<div>
|
||||
<div className="form-actions">
|
||||
<button type="submit" disabled={save.isPending}>
|
||||
Save
|
||||
</button>{' '}
|
||||
</button>
|
||||
<button type="button" onClick={() => setDraft(null)}>
|
||||
Cancel
|
||||
</button>
|
||||
|
||||
@@ -5,6 +5,8 @@ import { createToken, listTokens, revokeToken, type CreatedToken } from '../../a
|
||||
import { useSession } from '../../api/useSession'
|
||||
import { ListState } from '../shared/ListState'
|
||||
import { PolicyPicker } from '../shared/PolicyPicker'
|
||||
import { useConfirm } from '../shared/useConfirm'
|
||||
import { PolicyChips } from '../shared/PolicyChips'
|
||||
|
||||
interface Draft {
|
||||
displayName: string
|
||||
@@ -25,6 +27,7 @@ function formatTtl(seconds: number): string {
|
||||
|
||||
export function TokensTab({ client }: { client: BaoClient }) {
|
||||
const qc = useQueryClient()
|
||||
const confirm = useConfirm()
|
||||
const { tokenInfo } = useSession()
|
||||
const tokens = useQuery({ queryKey: ['tokens'], queryFn: () => listTokens(client) })
|
||||
const [draft, setDraft] = useState<Draft | null>(null)
|
||||
@@ -68,13 +71,15 @@ export function TokensTab({ client }: { client: BaoClient }) {
|
||||
<p>
|
||||
<strong>Copy this token now. It will not be shown again.</strong>
|
||||
</p>
|
||||
<code>{created.token}</code>{' '}
|
||||
<button type="button" onClick={copy}>
|
||||
{copied ? 'Copied' : 'Copy'}
|
||||
</button>{' '}
|
||||
<button type="button" onClick={() => setCreated(null)}>
|
||||
Done
|
||||
</button>
|
||||
<code className="token-value">{created.token}</code>
|
||||
<div className="form-actions">
|
||||
<button type="button" className="primary" onClick={copy}>
|
||||
{copied ? 'Copied' : 'Copy'}
|
||||
</button>
|
||||
<button type="button" onClick={() => setCreated(null)}>
|
||||
Done
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<ListState query={tokens} empty="No tokens." />
|
||||
@@ -98,7 +103,9 @@ export function TokensTab({ client }: { client: BaoClient }) {
|
||||
{t.display_name || '—'}
|
||||
{isSelf ? ' (you)' : ''}
|
||||
</td>
|
||||
<td>{t.policies.join(', ') || '—'}</td>
|
||||
<td>
|
||||
<PolicyChips policies={t.policies} />
|
||||
</td>
|
||||
<td>{formatTtl(t.ttl)}</td>
|
||||
<td>
|
||||
<code>{t.accessor.slice(0, 8)}…</code>
|
||||
@@ -109,10 +116,14 @@ export function TokensTab({ client }: { client: BaoClient }) {
|
||||
aria-label={`Revoke ${t.display_name || t.accessor}`}
|
||||
disabled={isSelf}
|
||||
title={isSelf ? 'This is the token you are signed in with' : undefined}
|
||||
onClick={() =>
|
||||
window.confirm(`Revoke token "${t.display_name || t.accessor}"? Tokens created from it are revoked too.`) &&
|
||||
revoke.mutate(t.accessor)
|
||||
}
|
||||
onClick={async () => {
|
||||
const ok = await confirm({
|
||||
title: `Revoke token “${t.display_name || t.accessor}”?`,
|
||||
message: 'Tokens created from it are revoked too.',
|
||||
confirmLabel: 'Revoke',
|
||||
})
|
||||
if (ok) revoke.mutate(t.accessor)
|
||||
}}
|
||||
>
|
||||
Revoke
|
||||
</button>
|
||||
@@ -130,7 +141,8 @@ export function TokensTab({ client }: { client: BaoClient }) {
|
||||
</button>
|
||||
)}
|
||||
{draft && (
|
||||
<form onSubmit={submit} aria-label="New token">
|
||||
<form onSubmit={submit} aria-label="New token" className="wide">
|
||||
<h3>New token</h3>
|
||||
<label>
|
||||
Display name
|
||||
<input value={draft.displayName} onChange={(e) => setDraft({ ...draft, displayName: e.target.value })} />
|
||||
@@ -143,15 +155,23 @@ export function TokensTab({ client }: { client: BaoClient }) {
|
||||
<input type="checkbox" checked={draft.renewable} onChange={(e) => setDraft({ ...draft, renewable: e.target.checked })} /> Renewable
|
||||
</label>
|
||||
<label className="check">
|
||||
<input type="checkbox" checked={draft.orphan} onChange={(e) => setDraft({ ...draft, orphan: e.target.checked })} /> Orphan
|
||||
(outlives the token you are signed in with; requires sudo)
|
||||
<input type="checkbox" checked={draft.orphan} onChange={(e) => setDraft({ ...draft, orphan: e.target.checked })} />
|
||||
<span>
|
||||
Orphan <span className="hint">(outlives the token you are signed in with; requires sudo)</span>
|
||||
</span>
|
||||
</label>
|
||||
<PolicyPicker client={client} value={draft.policies} onChange={(policies) => setDraft({ ...draft, policies })} />
|
||||
{draft.policies.length === 0 && (
|
||||
<p className="note-warn">
|
||||
No policies selected: OpenBao gives the new token the same policies as yours
|
||||
{tokenInfo?.policies.length ? ` (${tokenInfo.policies.join(', ')})` : ''}.
|
||||
</p>
|
||||
)}
|
||||
{create.error && <p role="alert">{create.error.message}</p>}
|
||||
<div>
|
||||
<div className="form-actions">
|
||||
<button type="submit" disabled={create.isPending}>
|
||||
Create
|
||||
</button>{' '}
|
||||
</button>
|
||||
<button type="button" onClick={() => setDraft(null)}>
|
||||
Cancel
|
||||
</button>
|
||||
|
||||
@@ -5,6 +5,8 @@ import { deleteUser, listUsers, saveUser } from '../../api/identities'
|
||||
import { AccessEditor } from '../access/AccessEditor'
|
||||
import { ListState } from '../shared/ListState'
|
||||
import { PolicyPicker } from '../shared/PolicyPicker'
|
||||
import { useConfirm } from '../shared/useConfirm'
|
||||
import { PolicyChips } from '../shared/PolicyChips'
|
||||
|
||||
interface Draft {
|
||||
name: string
|
||||
@@ -18,6 +20,7 @@ const empty: Draft = { name: '', password: '', policies: [], ttl: '', isNew: tru
|
||||
|
||||
export function UsersTab({ client }: { client: BaoClient }) {
|
||||
const qc = useQueryClient()
|
||||
const confirm = useConfirm()
|
||||
const users = useQuery({ queryKey: ['users'], queryFn: () => listUsers(client) })
|
||||
const [draft, setDraft] = useState<Draft | null>(null)
|
||||
const [accessFor, setAccessFor] = useState<string | null>(null)
|
||||
@@ -55,18 +58,22 @@ export function UsersTab({ client }: { client: BaoClient }) {
|
||||
{users.data?.map((u) => (
|
||||
<tr key={u.name}>
|
||||
<td>{u.name}</td>
|
||||
<td>{u.policies.join(', ') || '—'}</td>
|
||||
<td>
|
||||
<PolicyChips policies={u.policies} />
|
||||
</td>
|
||||
<td>
|
||||
<button type="button" aria-label={`Access ${u.name}`} onClick={() => setAccessFor(u.name)}>
|
||||
Access
|
||||
</button>{' '}
|
||||
</button>
|
||||
<button type="button" aria-label={`Edit ${u.name}`} onClick={() => setDraft({ ...u, password: '', ttl: u.ttl ? `${u.ttl}s` : '', isNew: false })}>
|
||||
Edit
|
||||
</button>{' '}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Delete ${u.name}`}
|
||||
onClick={() => window.confirm(`Delete user "${u.name}"? This cannot be undone.`) && remove.mutate(u.name)}
|
||||
onClick={async () => {
|
||||
if (await confirm({ title: `Delete user “${u.name}”?`, message: 'This cannot be undone.', confirmLabel: 'Delete' })) remove.mutate(u.name)
|
||||
}}
|
||||
>
|
||||
Delete
|
||||
</button>
|
||||
@@ -105,10 +112,10 @@ export function UsersTab({ client }: { client: BaoClient }) {
|
||||
</label>
|
||||
<PolicyPicker client={client} value={draft.policies} onChange={(policies) => setDraft({ ...draft, policies })} />
|
||||
{save.error && <p role="alert">{save.error.message}</p>}
|
||||
<div>
|
||||
<div className="form-actions">
|
||||
<button type="submit" disabled={save.isPending}>
|
||||
Save
|
||||
</button>{' '}
|
||||
</button>
|
||||
<button type="button" onClick={() => setDraft(null)}>
|
||||
Cancel
|
||||
</button>
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { fireEvent, render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { useState } from 'react'
|
||||
import { expect, test } from 'vitest'
|
||||
import { ConfirmProvider } from './ConfirmProvider'
|
||||
import { useConfirm } from './useConfirm'
|
||||
|
||||
function Trigger() {
|
||||
const confirm = useConfirm()
|
||||
const [answer, setAnswer] = useState('none')
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
onClick={async () =>
|
||||
setAnswer(
|
||||
(await confirm({ title: 'Delete user “alice”?', message: 'This cannot be undone.', confirmLabel: 'Delete' })) ? 'yes' : 'no',
|
||||
)
|
||||
}
|
||||
>
|
||||
ask
|
||||
</button>
|
||||
<output>{answer}</output>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function setup() {
|
||||
render(
|
||||
<ConfirmProvider>
|
||||
<Trigger />
|
||||
</ConfirmProvider>,
|
||||
)
|
||||
return userEvent.setup()
|
||||
}
|
||||
|
||||
test('shows the question and resolves true on confirm', async () => {
|
||||
const user = setup()
|
||||
await user.click(screen.getByRole('button', { name: 'ask' }))
|
||||
const dialog = await screen.findByRole('dialog', { name: 'Delete user “alice”?' })
|
||||
expect(dialog).toHaveTextContent('This cannot be undone.')
|
||||
await user.click(screen.getByRole('button', { name: 'Delete' }))
|
||||
expect(await screen.findByText('yes')).toBeInTheDocument()
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('resolves false on cancel, and Cancel has focus first', async () => {
|
||||
const user = setup()
|
||||
await user.click(screen.getByRole('button', { name: 'ask' }))
|
||||
expect(await screen.findByRole('button', { name: 'Cancel' })).toHaveFocus()
|
||||
await user.click(screen.getByRole('button', { name: 'Cancel' }))
|
||||
expect(await screen.findByText('no')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
test('resolves false when the dialog is cancelled', async () => {
|
||||
const user = setup()
|
||||
await user.click(screen.getByRole('button', { name: 'ask' }))
|
||||
// Browsers fire "cancel" on a modal dialog for Escape; jsdom does not, so send it directly.
|
||||
fireEvent(await screen.findByRole('dialog'), new Event('cancel', { cancelable: true }))
|
||||
expect(await screen.findByText('no')).toBeInTheDocument()
|
||||
})
|
||||
@@ -0,0 +1,59 @@
|
||||
import { useCallback, useEffect, useRef, useState, type MouseEvent, type ReactNode } from 'react'
|
||||
import { ConfirmContext, type Confirm, type ConfirmOptions } from './useConfirm'
|
||||
|
||||
interface Pending {
|
||||
options: ConfirmOptions
|
||||
resolve: (ok: boolean) => void
|
||||
}
|
||||
|
||||
/** Renders one modal confirmation dialog for the whole app; open it with useConfirm(). */
|
||||
export function ConfirmProvider({ children }: { children: ReactNode }) {
|
||||
const [pending, setPending] = useState<Pending | null>(null)
|
||||
const dialog = useRef<HTMLDialogElement>(null)
|
||||
|
||||
const confirm = useCallback<Confirm>((options) => new Promise((resolve) => setPending({ options, resolve })), [])
|
||||
|
||||
useEffect(() => {
|
||||
const el = dialog.current
|
||||
if (!pending || !el) return
|
||||
// showModal gives focus trapping, Escape and an inert page; fall back to a plain open dialog without it.
|
||||
if (typeof el.showModal === 'function') el.showModal()
|
||||
else el.setAttribute('open', '')
|
||||
}, [pending])
|
||||
|
||||
function settle(ok: boolean) {
|
||||
pending?.resolve(ok)
|
||||
setPending(null)
|
||||
}
|
||||
|
||||
return (
|
||||
<ConfirmContext value={confirm}>
|
||||
{children}
|
||||
{pending && (
|
||||
<dialog
|
||||
ref={dialog}
|
||||
className="confirm-dialog"
|
||||
aria-labelledby="confirm-title"
|
||||
aria-describedby={pending.options.message ? 'confirm-message' : undefined}
|
||||
onCancel={(e) => {
|
||||
e.preventDefault()
|
||||
settle(false)
|
||||
}}
|
||||
// A click on the backdrop lands on the dialog element itself, not on its content.
|
||||
onClick={(e: MouseEvent<HTMLDialogElement>) => e.target === e.currentTarget && settle(false)}
|
||||
>
|
||||
<h2 id="confirm-title">{pending.options.title}</h2>
|
||||
{pending.options.message && <p id="confirm-message">{pending.options.message}</p>}
|
||||
<div className="confirm-actions">
|
||||
<button type="button" autoFocus onClick={() => settle(false)}>
|
||||
Cancel
|
||||
</button>
|
||||
<button type="button" className="danger-solid" onClick={() => settle(true)}>
|
||||
{pending.options.confirmLabel}
|
||||
</button>
|
||||
</div>
|
||||
</dialog>
|
||||
)}
|
||||
</ConfirmContext>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { isManagedPolicy } from '../../model/graph'
|
||||
|
||||
function Empty() {
|
||||
return <span className="hint">None</span>
|
||||
}
|
||||
|
||||
/** Policy names as chips; the ones EnvBao manages are tinted. */
|
||||
export function PolicyChips({ policies }: { policies: readonly string[] }) {
|
||||
if (policies.length === 0) return <Empty />
|
||||
return (
|
||||
<ul className="chips plain">
|
||||
{policies.map((p) => (
|
||||
<li key={p} className={isManagedPolicy(p) ? 'managed' : undefined}>
|
||||
{p}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
|
||||
/** Plain names (aliases, members) as neutral chips. */
|
||||
export function NameChips({ names }: { names: readonly string[] }) {
|
||||
if (names.length === 0) return <Empty />
|
||||
return (
|
||||
<ul className="chips plain">
|
||||
{names.map((n) => (
|
||||
<li key={n}>{n}</li>
|
||||
))}
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
@@ -13,7 +13,7 @@ export function PolicyPicker({ client, value, onChange }: Props) {
|
||||
// Keep policies that are attached but no longer exist selectable, so editing doesn't drop them silently.
|
||||
const names = [...new Set([...(data ?? []), ...value])].filter((n) => n !== 'root').sort()
|
||||
return (
|
||||
<fieldset>
|
||||
<fieldset className="pick-grid">
|
||||
<legend>Policies</legend>
|
||||
{error && <p role="alert">Could not load policies: {error.message}</p>}
|
||||
{names.map((n) => (
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { createContext, useContext } from 'react'
|
||||
|
||||
export interface ConfirmOptions {
|
||||
title: string
|
||||
message?: string
|
||||
/** Label of the confirming button, e.g. "Delete". */
|
||||
confirmLabel: string
|
||||
}
|
||||
|
||||
export type Confirm = (options: ConfirmOptions) => Promise<boolean>
|
||||
|
||||
export const ConfirmContext = createContext<Confirm | null>(null)
|
||||
|
||||
/** Ask before a destructive action. Falls back to the browser's confirm() when no provider is mounted. */
|
||||
export function useConfirm(): Confirm {
|
||||
const confirm = useContext(ConfirmContext)
|
||||
return confirm ?? (async (o) => window.confirm(o.message ? `${o.title}\n${o.message}` : o.title))
|
||||
}
|
||||
Reference in new issue
Block a user