@coffre/ui 0.1.10 → 0.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/dist/client/_coffre/assets/account-BJAdDvZf.js +2 -0
  2. package/dist/client/_coffre/assets/account-D0jLpk5c.js +1 -0
  3. package/dist/client/_coffre/assets/affordances-Bq2-oUB5.js +1 -0
  4. package/dist/client/_coffre/assets/audit-C-pcBgKe.js +2 -0
  5. package/dist/client/_coffre/assets/audit-CHGlDeBB.js +1 -0
  6. package/dist/client/_coffre/assets/{auth.device-BP5FY0K1.js → auth.device-BndOUjse.js} +1 -1
  7. package/dist/client/_coffre/assets/auth.device-CWHNQn9W.js +2 -0
  8. package/dist/client/_coffre/assets/directory-nDExpkAz.js +1 -0
  9. package/dist/client/_coffre/assets/dist-QVHMLatb.js +1 -0
  10. package/dist/client/_coffre/assets/globals-CKBoTlyH.css +1 -0
  11. package/dist/client/_coffre/assets/grants-CjoOnxzz.js +1 -0
  12. package/dist/client/_coffre/assets/icons-BQ27Ds9u.js +1 -0
  13. package/dist/client/_coffre/assets/index-CUGytaO3.js +12 -0
  14. package/dist/client/_coffre/assets/link-DP8SVWon.js +1 -0
  15. package/dist/client/_coffre/assets/login-CeaxDMcr.js +2 -0
  16. package/dist/client/_coffre/assets/login-DrMgvqZn.js +1 -0
  17. package/dist/client/_coffre/assets/offboarding-CNr_1tnl.js +1 -0
  18. package/dist/client/_coffre/assets/page-CGmvjSy4.js +1 -0
  19. package/dist/client/_coffre/assets/preload-helper-ClBkJ19f.js +1 -0
  20. package/dist/client/_coffre/assets/principal-page-DNLb_q_e.js +1 -0
  21. package/dist/client/_coffre/assets/projects._project._environment-CHzbboGp.js +3 -0
  22. package/dist/client/_coffre/assets/projects._project._environment-DDxu_HHD.js +2 -0
  23. package/dist/client/_coffre/assets/projects._project.index-CIAsjvg6.js +2 -0
  24. package/dist/client/_coffre/assets/projects._project.index-DZ9l6d-1.js +1 -0
  25. package/dist/client/_coffre/assets/projects.index-4eUXreE_.js +1 -0
  26. package/dist/client/_coffre/assets/row-state-ByET1OKX.js +1 -0
  27. package/dist/client/_coffre/assets/settings-D2zp1Ssu.js +1 -0
  28. package/dist/client/_coffre/assets/suspense-C7KwSnTG.js +1 -0
  29. package/dist/client/_coffre/assets/tokens._token-DWmbqzNk.js +2 -0
  30. package/dist/client/_coffre/assets/tokens._token-Dui_4KfS.js +1 -0
  31. package/dist/client/_coffre/assets/tokens.index-CSi5Wxwf.js +1 -0
  32. package/dist/client/_coffre/assets/ui-BdipqGpP.js +46 -0
  33. package/dist/client/_coffre/assets/unregistered-CA7B4C1m.js +1 -0
  34. package/dist/client/_coffre/assets/use-action-DRm9yVhV.js +1 -0
  35. package/dist/client/_coffre/assets/use-change-BRRMJocl.js +1 -0
  36. package/dist/client/_coffre/assets/use-shell-BMGlJ25Q.js +1 -0
  37. package/dist/client/_coffre/assets/useQuery-D__2KBOs.js +1 -0
  38. package/dist/client/_coffre/assets/useSuspenseQuery-CSXyDALB.js +1 -0
  39. package/dist/client/_coffre/assets/users._user-BkNrX7Qf.js +1 -0
  40. package/dist/client/_coffre/assets/users._user-jbSvtdOg.js +2 -0
  41. package/dist/client/_coffre/assets/users.index-CKnQ1G76.js +1 -0
  42. package/dist/server/.vite/manifest.json +343 -246
  43. package/dist/server/_coffre/assets/_tanstack-start-manifest_v-Dx-c3XVk.js +162 -0
  44. package/dist/server/_coffre/assets/{account-CUQYGCYh.js → account-BocTPU1J.js} +150 -117
  45. package/dist/server/_coffre/assets/{account-DMlUoBxQ.js → account-CL8hOGhO.js} +10 -24
  46. package/dist/server/_coffre/assets/{affordances-BNaXjMOb.js → affordances-CKANXDTG.js} +2 -22
  47. package/dist/server/_coffre/assets/{async-local-storage-C0cwgkEr.js → async-local-storage-C10uQtMM.js} +3 -2
  48. package/dist/server/_coffre/assets/{audit-CCdSLmvK.js → audit-Bcka4vA6.js} +46 -16
  49. package/dist/server/_coffre/assets/audit-CSRQYIhu.js +31 -0
  50. package/dist/server/_coffre/assets/{auth.device-C05u5ROO.js → auth.device-CMcUISZY.js} +7 -5
  51. package/dist/server/_coffre/assets/{auth.device-BoFM1jcf.js → auth.device-DqO0T-rU.js} +5 -5
  52. package/dist/server/_coffre/assets/{directory-GsnYkse0.js → directory-CyYx6Jx1.js} +87 -112
  53. package/dist/server/_coffre/assets/{use-action-DwEmf58L.js → dist-CnnV3t2g.js} +3 -48
  54. package/dist/server/_coffre/assets/globals-CKBoTlyH.css +1 -0
  55. package/dist/server/_coffre/assets/grants-CRijabX0.js +158 -0
  56. package/dist/server/_coffre/assets/{page-BdnhpwvH.js → icons-Dy-5ccDF.js} +3 -196
  57. package/dist/server/_coffre/assets/lazyRouteComponent-CqBNCGuZ.js +480 -0
  58. package/dist/server/_coffre/assets/link-42ZWdjzZ.js +422 -0
  59. package/dist/server/_coffre/assets/{login-DUtCQju5.js → login-BI9tzJEy.js} +7 -5
  60. package/dist/server/_coffre/assets/{login-B2njIq_o.js → login-C-v88YwP.js} +2 -2
  61. package/dist/server/_coffre/assets/matchContext-qLfYbC6_.js +56 -0
  62. package/dist/server/_coffre/assets/{offboarding-8yMa7ViM.js → offboarding-1H0LavTd.js} +6 -4
  63. package/dist/server/_coffre/assets/page-D_mO0-sn.js +3592 -0
  64. package/dist/server/_coffre/assets/{principal-page-B8zPcS2b.js → principal-page-DQDoXute.js} +51 -42
  65. package/dist/server/_coffre/assets/{projects._project._environment-BZ5Z80V8.js → projects._project._environment-C-yVwC92.js} +168 -248
  66. package/dist/server/_coffre/assets/{projects._project._environment-DdIOc7wx.js → projects._project._environment-D_5R40of.js} +4 -11
  67. package/dist/server/_coffre/assets/{projects._project.index-CuEAUwGn.js → projects._project.index-A2BImFIT.js} +134 -96
  68. package/dist/server/_coffre/assets/{projects._project.index-DvbcU1kh.js → projects._project.index-BPPKxKrt.js} +5 -4
  69. package/dist/server/_coffre/assets/{projects.index-5HI0wOuG.js → projects.index-543IsPzY.js} +57 -55
  70. package/dist/server/_coffre/assets/{react-dom-qCTiwGGR.js → react-dom-bBoJXlK2.js} +417 -51
  71. package/dist/server/_coffre/assets/{router-CQDoql8s.js → router-CM3vK8QO.js} +376 -92
  72. package/dist/server/_coffre/assets/row-state-XBtDoIA4.js +117 -0
  73. package/dist/server/_coffre/assets/{settings-BVz78wjP.js → settings-BLVU74ym.js} +8 -6
  74. package/dist/server/_coffre/assets/suspense-CzYTwxOj.js +602 -0
  75. package/dist/server/_coffre/assets/tokens._token-B-hBgwBW.js +10 -0
  76. package/dist/server/_coffre/assets/{tokens._token-CWs3Mtki.js → tokens._token-aubAUonP.js} +97 -79
  77. package/dist/server/_coffre/assets/{tokens.index-Ck0LN7aC.js → tokens.index-4D3jwp5v.js} +9 -6
  78. package/dist/server/_coffre/assets/{ui-D_slKpSF.js → ui-BI3Bf72q.js} +7 -836
  79. package/dist/server/_coffre/assets/{unregistered-Z17da4Rc.js → unregistered-CagDxMyw.js} +5 -3
  80. package/dist/server/_coffre/assets/use-action-tzBZvjjQ.js +47 -0
  81. package/dist/server/_coffre/assets/use-change-Dggqxy5y.js +1212 -0
  82. package/dist/server/_coffre/assets/use-shell-CwStDfzX.js +462 -0
  83. package/dist/server/_coffre/assets/useQuery-C6_dBjem.js +8 -0
  84. package/dist/server/_coffre/assets/{useStore-DWGPqzXR.js → useRouter-CaUSUNsw.js} +1 -420
  85. package/dist/server/_coffre/assets/useSuspenseQuery-BuapQt_P.js +117 -0
  86. package/dist/server/_coffre/assets/{users._user-CMwj-VI9.js → users._user-137WNyxn.js} +4 -5
  87. package/dist/server/_coffre/assets/users._user-C252Iilj.js +10 -0
  88. package/dist/server/_coffre/assets/{users.index-fWHv6A30.js → users.index-DQHsfnal.js} +9 -6
  89. package/dist/server/index.js +6 -5
  90. package/package.json +5 -3
  91. package/src/components/directory.tsx +75 -104
  92. package/src/components/grants.tsx +60 -112
  93. package/src/components/principal-page.tsx +54 -67
  94. package/src/components/principal-picker.tsx +7 -16
  95. package/src/components/row-state.tsx +95 -0
  96. package/src/components/service-tokens.tsx +75 -64
  97. package/src/components/shell.tsx +1 -1
  98. package/src/components/syncs.tsx +42 -26
  99. package/src/lib/announce.ts +36 -0
  100. package/src/lib/changes.ts +498 -0
  101. package/src/lib/optimistic.ts +233 -0
  102. package/src/lib/queries.ts +393 -0
  103. package/src/lib/use-action.ts +20 -15
  104. package/src/lib/use-change.ts +42 -0
  105. package/src/lib/use-shell.ts +17 -0
  106. package/src/router.tsx +17 -9
  107. package/src/routes/__root.tsx +8 -38
  108. package/src/routes/account.tsx +163 -154
  109. package/src/routes/audit.tsx +51 -72
  110. package/src/routes/auth.device.tsx +4 -2
  111. package/src/routes/login.tsx +3 -2
  112. package/src/routes/projects.$project.$environment.tsx +226 -231
  113. package/src/routes/projects.$project.index.tsx +136 -118
  114. package/src/routes/projects.index.tsx +117 -145
  115. package/src/routes/settings.tsx +7 -7
  116. package/src/routes/tokens.$token.tsx +14 -17
  117. package/src/routes/tokens.index.tsx +8 -4
  118. package/src/routes/unregistered.tsx +3 -2
  119. package/src/routes/users.$user.tsx +4 -4
  120. package/src/routes/users.index.tsx +8 -4
  121. package/src/styles/globals.css +78 -1
  122. package/dist/client/_coffre/assets/account-B48wuSF8.js +0 -1
  123. package/dist/client/_coffre/assets/account-BkNyIDT7.js +0 -2
  124. package/dist/client/_coffre/assets/affordances-CmoY-8Xf.js +0 -1
  125. package/dist/client/_coffre/assets/audit-BvwKYb-5.js +0 -2
  126. package/dist/client/_coffre/assets/audit-D02H-zxS.js +0 -1
  127. package/dist/client/_coffre/assets/auth.device-DYOONgFF.js +0 -2
  128. package/dist/client/_coffre/assets/coffre-BBp7cKVa.js +0 -1
  129. package/dist/client/_coffre/assets/directory-Bu0EIxqI.js +0 -1
  130. package/dist/client/_coffre/assets/globals-Bh2x1gBM.css +0 -1
  131. package/dist/client/_coffre/assets/grants-DavcwofW.js +0 -1
  132. package/dist/client/_coffre/assets/index-CDPlq5rM.js +0 -12
  133. package/dist/client/_coffre/assets/login-C-wTm_t1.js +0 -2
  134. package/dist/client/_coffre/assets/login-CLLv1om9.js +0 -1
  135. package/dist/client/_coffre/assets/offboarding-DWsE2FSa.js +0 -1
  136. package/dist/client/_coffre/assets/page-DbSS7pYH.js +0 -1
  137. package/dist/client/_coffre/assets/preload-helper-DduCCcmc.js +0 -46
  138. package/dist/client/_coffre/assets/principal-page-Bp_iwuSd.js +0 -1
  139. package/dist/client/_coffre/assets/projects._project._environment-BMeX_B8l.js +0 -2
  140. package/dist/client/_coffre/assets/projects._project._environment-CT0A-hIU.js +0 -3
  141. package/dist/client/_coffre/assets/projects._project.index-C_xYOGLT.js +0 -2
  142. package/dist/client/_coffre/assets/projects._project.index-Chcf-cUd.js +0 -1
  143. package/dist/client/_coffre/assets/projects.index-CfOtb1X5.js +0 -2
  144. package/dist/client/_coffre/assets/projects.index-DSjOhLDh.js +0 -1
  145. package/dist/client/_coffre/assets/settings-BC9cUJNK.js +0 -1
  146. package/dist/client/_coffre/assets/settings-Bkj_E21y.js +0 -2
  147. package/dist/client/_coffre/assets/tokens._token-BA0KqvaW.js +0 -1
  148. package/dist/client/_coffre/assets/tokens._token-Dh9jLOkm.js +0 -2
  149. package/dist/client/_coffre/assets/tokens.index-BgAMWkHT.js +0 -2
  150. package/dist/client/_coffre/assets/tokens.index-CHueIAv1.js +0 -1
  151. package/dist/client/_coffre/assets/unregistered-D5go1AfR.js +0 -1
  152. package/dist/client/_coffre/assets/use-action-l__xZDYY.js +0 -1
  153. package/dist/client/_coffre/assets/users._user-Dwqa0gv5.js +0 -1
  154. package/dist/client/_coffre/assets/users._user-xJAb3T6Y.js +0 -2
  155. package/dist/client/_coffre/assets/users.index-BJoF-L37.js +0 -2
  156. package/dist/client/_coffre/assets/users.index-YUjtbTGy.js +0 -1
  157. package/dist/server/_coffre/assets/_tanstack-start-manifest_v-BKg2AlPu.js +0 -133
  158. package/dist/server/_coffre/assets/audit-CThXn2v7.js +0 -74
  159. package/dist/server/_coffre/assets/coffre-C2ANsTAz.js +0 -281
  160. package/dist/server/_coffre/assets/globals-Bh2x1gBM.css +0 -1
  161. package/dist/server/_coffre/assets/grants-B6k4Fu9z.js +0 -243
  162. package/dist/server/_coffre/assets/projects.index-uiomWX_l.js +0 -54
  163. package/dist/server/_coffre/assets/settings-4oRyDizv.js +0 -18
  164. package/dist/server/_coffre/assets/tokens._token-CF_deAwq.js +0 -18
  165. package/dist/server/_coffre/assets/tokens.index-DF_07KEe.js +0 -10
  166. package/dist/server/_coffre/assets/users._user-DUzwkSKT.js +0 -10
  167. package/dist/server/_coffre/assets/users.index-BbuweTwH.js +0 -10
@@ -1,11 +1,11 @@
1
- import type { CoffreClient } from '@coffre/client';
2
- import { useEffect, useState } from 'react';
1
+ import { Fragment, useState } from 'react';
3
2
  import { DropdownMenu } from 'radix-ui';
4
- import { toast } from 'sonner';
5
- import { memberRef, Refusal, uiResult, useCoffre } from '../lib/coffre';
6
- import { useAction } from '../lib/use-action';
3
+ import { changeRole, directoryList, invite, removeMember, type InviteVars } from '../lib/changes';
4
+ import { memberRef, useCoffre } from '../lib/coffre';
5
+ import { useChange, useChangeStatus } from '../lib/use-change';
7
6
  import type { DirectoryPrincipal } from '../shared/models';
8
- import { ConfirmDialog, EmptyState, ErrorLine, Modal, Spinner, Toggletip } from './ui';
7
+ import { RowFailure, RowPending, rowClass } from './row-state';
8
+ import { ConfirmDialog, EmptyState, Modal, Spinner, Toggletip } from './ui';
9
9
  import { PrincipalLink } from './principal';
10
10
  import { Key, Lock, MoreHorizontal, Pencil, Plus, ShieldCheck, User, X } from './icons';
11
11
 
@@ -19,21 +19,9 @@ import { Key, Lock, MoreHorizontal, Pencil, Plus, ShieldCheck, User, X } from '.
19
19
 
20
20
  type PrincipalType = DirectoryPrincipal['principalType'];
21
21
 
22
- /**
23
- * Everyone in the directory, and who was removed. The API shows grant
24
- * managers the members of their projects; the directory pages stay the
25
- * owners' own, and asking for anyone else would only log a refusal.
26
- */
27
- export async function loadDirectory(client: CoffreClient, canManage: boolean) {
28
- if (!canManage) return { ok: false as const, error: 'Only owners can manage users and service accounts.' };
29
- return uiResult(async () => {
30
- const { members, removed } = await client.members.list();
31
- const principals: DirectoryPrincipal[] = members.map(
32
- ({ principalType, principalId, instanceRole, isRootAdmin, tampered }) => ({ principalType, principalId, instanceRole, isRootAdmin, tampered }),
33
- );
34
- return { principals, removed };
35
- });
36
- }
22
+ /** How the directory, and its changes, name someone: `user:…`, `token:…`. */
23
+ export const memberOf = (principal: Pick<DirectoryPrincipal, 'principalType' | 'principalId'>) =>
24
+ memberRef(principal.principalType, principal.principalId);
37
25
 
38
26
  export const ROLE_LABEL: Record<DirectoryPrincipal['instanceRole'], string> = {
39
27
  'root-admin': 'Root admin',
@@ -58,9 +46,14 @@ export function DirectoryTable({
58
46
  hasRemoved?: boolean;
59
47
  }) {
60
48
  const users = principalType === 'user';
49
+ const columns = users ? 4 : 3;
50
+ const { status, failedAdds, dismiss } = useChangeStatus(directoryList.queryKey);
51
+ const refused = failedAdds<InviteVars>(principals.map(memberOf)).filter(
52
+ ({ vars }) => vars.principalType === principalType,
53
+ );
61
54
  return (
62
55
  <section className="card" aria-label={users ? 'Users' : 'Tokens'}>
63
- {principals.length === 0 ? (
56
+ {principals.length === 0 && refused.length === 0 ? (
64
57
  <EmptyState
65
58
  title={
66
59
  hasRemoved
@@ -99,28 +92,52 @@ export function DirectoryTable({
99
92
  </tr>
100
93
  </thead>
101
94
  <tbody>
102
- {principals.map((principal, index) => (
103
- <tr key={principal.principalId} className="row-link">
104
- <td className="n">{index + 1}</td>
105
- <td
106
- className="col-lead"
107
- data-label={principal.principalType === 'user' ? 'Email' : 'Name'}
108
- >
109
- <PrincipalLink
110
- type={principal.principalType}
111
- id={principal.principalId}
112
- stretch
95
+ {principals.map((principal, index) => {
96
+ const state = status(memberOf(principal));
97
+ return (
98
+ <Fragment key={principal.principalId}>
99
+ <tr className={`row-link ${rowClass(state)}`}>
100
+ <td className="n">{index + 1}</td>
101
+ <td
102
+ className="col-lead"
103
+ data-label={principal.principalType === 'user' ? 'Email' : 'Name'}
104
+ >
105
+ <PrincipalLink
106
+ type={principal.principalType}
107
+ id={principal.principalId}
108
+ stretch
109
+ />
110
+ </td>
111
+ {users && (
112
+ <td className="col-role" data-label="Instance role">
113
+ <InstanceRole principal={principal} />
114
+ </td>
115
+ )}
116
+ <td className="col-actions">
117
+ {state.state === 'pending' ? (
118
+ <RowPending status={state} />
119
+ ) : (
120
+ <PrincipalActions principal={principal} />
121
+ )}
122
+ </td>
123
+ </tr>
124
+ <RowFailure
125
+ status={state}
126
+ columns={columns}
127
+ onDismiss={() => state.state === 'failed' && dismiss(state.mutationId)}
113
128
  />
114
- </td>
115
- {users && (
116
- <td className="col-role" data-label="Instance role">
117
- <InstanceRole principal={principal} />
118
- </td>
119
- )}
120
- <td className="col-actions">
121
- <PrincipalActions principal={principal} />
122
- </td>
123
- </tr>
129
+ </Fragment>
130
+ );
131
+ })}
132
+ {refused.map(({ mutationId, vars, status: failed }) => (
133
+ <RowFailure
134
+ key={mutationId}
135
+ status={failed}
136
+ columns={columns}
137
+ onDismiss={() => dismiss(mutationId)}
138
+ >
139
+ {vars.principalId} was not added.
140
+ </RowFailure>
124
141
  ))}
125
142
  </tbody>
126
143
  </table>
@@ -184,12 +201,10 @@ export function InstanceRole({ principal }: { principal: DirectoryPrincipal }) {
184
201
  export function PrincipalActions({
185
202
  principal,
186
203
  trigger = 'act act-quiet act-menu',
187
- onRemoved,
188
204
  }: {
189
205
  principal: DirectoryPrincipal;
190
206
  /** The menu button's classes: a row action in tables, a button in a page head. */
191
207
  trigger?: string;
192
- onRemoved?: () => unknown;
193
208
  }) {
194
209
  const [editing, setEditing] = useState(false);
195
210
  const [confirming, setConfirming] = useState(false);
@@ -197,13 +212,12 @@ export function PrincipalActions({
197
212
  principal.instanceRole === 'owner' ? 'owner' : 'user',
198
213
  );
199
214
  const coffre = useCoffre();
200
- const { pending, error, setError, run } = useAction();
215
+ const setRole = useChange(changeRole(coffre));
216
+ const remove = useChange(removeMember(coffre));
217
+ const { status } = useChangeStatus(directoryList.queryKey);
218
+ const pending = status(memberOf(principal)).state === 'pending';
201
219
  const kind = KIND[principal.principalType];
202
220
 
203
- useEffect(() => {
204
- if (error !== null && !editing) toast.error(error);
205
- }, [editing, error]);
206
-
207
221
  if (principal.isRootAdmin) return null;
208
222
 
209
223
  return (
@@ -249,10 +263,7 @@ export function PrincipalActions({
249
263
  {principal.principalType === 'user' && (
250
264
  <Modal
251
265
  open={editing}
252
- onOpenChange={(open) => {
253
- setEditing(open);
254
- if (!open) setError(null);
255
- }}
266
+ onOpenChange={setEditing}
256
267
  title={
257
268
  <>
258
269
  Role of <span className="mono">{principal.principalId}</span>
@@ -263,28 +274,17 @@ export function PrincipalActions({
263
274
  className="form"
264
275
  onSubmit={(event) => {
265
276
  event.preventDefault();
266
- void run(
267
- () =>
268
- coffre.members.add(memberRef('user', principal.principalId), {
269
- owner: instanceRole === 'owner',
270
- }),
271
- () => {
272
- toast.success(
273
- `${principal.principalId} is now ${ROLE_LABEL[instanceRole].toLowerCase()}`,
274
- );
275
- setEditing(false);
276
- },
277
- );
277
+ // Shown in the list at once; the row says if the server refuses.
278
+ setRole({ principalId: principal.principalId, owner: instanceRole === 'owner' });
279
+ setEditing(false);
278
280
  }}
279
281
  >
280
282
  <RoleField value={instanceRole} onChange={setInstanceRole} />
281
- <ErrorLine error={error} />
282
283
  <div className="dialog-actions">
283
284
  <button className="btn" type="button" onClick={() => setEditing(false)}>
284
285
  Cancel
285
286
  </button>
286
- <button className="btn btn-primary" type="submit" disabled={pending}>
287
- {pending && <Spinner />}
287
+ <button className="btn btn-primary" type="submit">
288
288
  Save
289
289
  </button>
290
290
  </div>
@@ -316,15 +316,7 @@ export function PrincipalActions({
316
316
  )
317
317
  }
318
318
  confirmLabel={`Remove ${kind}`}
319
- onConfirm={() =>
320
- void run(
321
- () => coffre.members.remove(memberRef(principal.principalType, principal.principalId)),
322
- async () => {
323
- toast.success(`${principal.principalId} removed`);
324
- await onRemoved?.();
325
- },
326
- )
327
- }
319
+ onConfirm={() => remove(principal)}
328
320
  />
329
321
  </>
330
322
  );
@@ -334,15 +326,13 @@ export function AddPrincipal({ principalType }: { principalType: PrincipalType }
334
326
  const [open, setOpen] = useState(false);
335
327
  const [principalId, setPrincipalId] = useState('');
336
328
  const [instanceRole, setInstanceRole] = useState<'user' | 'owner'>('user');
337
- const coffre = useCoffre();
338
- const { pending, error, setError, run } = useAction();
329
+ const add = useChange(invite(useCoffre()));
339
330
  const kind = KIND[principalType];
340
331
 
341
332
  function close() {
342
333
  setOpen(false);
343
334
  setPrincipalId('');
344
335
  setInstanceRole('user');
345
- setError(null);
346
336
  }
347
337
 
348
338
  return (
@@ -362,22 +352,9 @@ export function AddPrincipal({ principalType }: { principalType: PrincipalType }
362
352
  className="form"
363
353
  onSubmit={(event) => {
364
354
  event.preventDefault();
365
- void run(
366
- async () => {
367
- // Adding is an idempotent PUT that would also set the role of
368
- // someone already here; this form is only for someone new.
369
- const member = memberRef(principalType, principalId.trim());
370
- const { members } = await coffre.members.list();
371
- if (members.some((entry) => entry.member === member)) {
372
- throw new Refusal('That principal already exists.');
373
- }
374
- await coffre.members.add(member, { owner: principalType === 'user' && instanceRole === 'owner' });
375
- },
376
- () => {
377
- toast.success(`${principalId.trim()} added`);
378
- close();
379
- },
380
- );
355
+ // Shown in the list at once; the list says if the server refuses.
356
+ add({ principalType, principalId: principalId.trim(), owner: instanceRole === 'owner' });
357
+ close();
381
358
  }}
382
359
  >
383
360
  <label className="field">
@@ -401,17 +378,11 @@ export function AddPrincipal({ principalType }: { principalType: PrincipalType }
401
378
  <RoleField value={instanceRole} onChange={setInstanceRole} />
402
379
  )}
403
380
 
404
- <ErrorLine error={error} />
405
381
  <div className="dialog-actions">
406
382
  <button className="btn" type="button" onClick={close}>
407
383
  Cancel
408
384
  </button>
409
- <button
410
- className="btn btn-primary"
411
- type="submit"
412
- disabled={pending || principalId.trim() === ''}
413
- >
414
- {pending && <Spinner />}
385
+ <button className="btn btn-primary" type="submit" disabled={principalId.trim() === ''}>
415
386
  Add {kind}
416
387
  </button>
417
388
  </div>
@@ -1,79 +1,15 @@
1
- import type { CoffreClient } from '@coffre/client';
2
- import type { Role } from '@coffre/core/access';
3
1
  import type { ReactNode } from 'react';
4
- import { toast } from 'sonner';
5
- import { failureMessage, memberRef, uiFailure, useCoffre } from '../lib/coffre';
6
- import { useAction } from '../lib/use-action';
2
+ import { grantId, revokeGrant, type GrantVars } from '../lib/changes';
3
+ import type { FailedAdd } from '../lib/optimistic';
4
+ import { useCoffre } from '../lib/coffre';
7
5
  import { projectAccessLabel } from '../lib/project-access';
8
- import type { GrantRow, ProjectSummary } from '../shared/models';
9
- import { ConfirmButton, ErrorLine, Spinner } from './ui';
6
+ import { keys } from '../lib/queries';
7
+ import { useChange, useChangeStatus } from '../lib/use-change';
8
+ import type { GrantRow } from '../shared/models';
9
+ import { RowFailure, RowPending, rowClass } from './row-state';
10
+ import { ConfirmButton } from './ui';
10
11
  import { Clock, ShieldCheck } from './icons';
11
12
 
12
- /**
13
- * One project and, when you manage its access, its grants. A project that is
14
- * not there for you fails with no message: the page words that itself.
15
- */
16
- export async function loadProject(client: CoffreClient, slug: string) {
17
- let project: ProjectSummary | undefined;
18
- try {
19
- project = (await client.projects.list()).projects.find((entry) => entry.slug === slug);
20
- } catch (error) {
21
- return uiFailure(error);
22
- }
23
- if (project === undefined) return { ok: false as const, error: null };
24
- if (!project.permissions.includes('grant.manage')) {
25
- return { ok: true as const, project, grants: [] as GrantRow[], grantsError: null };
26
- }
27
-
28
- try {
29
- const { members } = await client.members.list(slug);
30
- const grants: GrantRow[] = members.flatMap((member) =>
31
- member.grants.map((grant) => ({
32
- id: grant.id,
33
- principalType: member.principalType,
34
- principalId: member.principalId,
35
- role: grant.role,
36
- roleName: grant.roleName,
37
- permissions: grant.permissions,
38
- scope: grant.environment === null ? ('project' as const) : ('environment' as const),
39
- environmentSlug: grant.environment,
40
- expiresAt: grant.expiresAt,
41
- })),
42
- );
43
- return { ok: true as const, project, grants, grantsError: null };
44
- } catch (error) {
45
- return { ok: true as const, project, grants: [] as GrantRow[], grantsError: failureMessage(error) };
46
- }
47
- }
48
-
49
- /** Where a grant applies, as the API names it: `market`, or `market/prod`. */
50
- export function grantPlace(project: string, environmentSlug: string | null): string {
51
- return environmentSlug === null ? project : `${project}/${environmentSlug}`;
52
- }
53
-
54
- /**
55
- * Give someone a role at one place. Access is declarative, so asking for what
56
- * they already hold is not an error, whoever asked first: `existed` says so.
57
- */
58
- export async function ensureGrant(
59
- coffre: CoffreClient,
60
- data: {
61
- project: string;
62
- principalType: GrantRow['principalType'];
63
- principalId: string;
64
- role: string;
65
- environmentSlug: string | null;
66
- expiresAt: string | null;
67
- },
68
- ): Promise<{ existed: boolean }> {
69
- const place = grantPlace(data.project, data.environmentSlug);
70
- const role = data.role as Role;
71
- const { changes } = await coffre.access.set(memberRef(data.principalType, data.principalId), {
72
- [place]: data.expiresAt === null ? role : { role, until: data.expiresAt },
73
- });
74
- return { existed: changes[place] === 'unchanged' };
75
- }
76
-
77
13
  /**
78
14
  * Grants as a table: who or where in the first column, then the access, when
79
15
  * it lapses, and a revoke.
@@ -125,14 +61,15 @@ export function GrantRowView({
125
61
  lead: ReactNode;
126
62
  leadLabel: string;
127
63
  }) {
128
- const coffre = useCoffre();
129
- const { pending, error, run } = useAction();
64
+ const revoke = useChange(revokeGrant(useCoffre(), project));
65
+ const { status, dismiss } = useChangeStatus(keys.grants(project));
66
+ const state = status(grantId(grant));
130
67
  const label = projectAccessLabel(grant);
131
68
  const expired = grant.expiresAt !== null && new Date(grant.expiresAt).getTime() < Date.now();
132
69
 
133
70
  return (
134
71
  <>
135
- <tr>
72
+ <tr className={rowClass(state)}>
136
73
  <td className="n">{number}</td>
137
74
  <td className="col-lead" data-label={leadLabel}>
138
75
  {lead}
@@ -160,45 +97,56 @@ export function GrantRowView({
160
97
  )}
161
98
  </td>
162
99
  <td className="col-actions">
163
- <ConfirmButton
164
- trigger={
165
- <button className="act act-danger" disabled={pending}>
166
- {pending && <Spinner size={13} />}
167
- Revoke
168
- </button>
169
- }
170
- title={
171
- <>
172
- Revoke {label} from <span className="mono">{grant.principalId}</span>?
173
- </>
174
- }
175
- body={
176
- <>
177
- They lose <strong>{label}</strong> on <span className="mono">{project}</span>{' '}
178
- immediately, including any process using it right now. Other grants they hold
179
- still apply.
180
- </>
181
- }
182
- confirmLabel="Revoke access"
183
- onConfirm={() =>
184
- run(
185
- () =>
186
- coffre.access.set(memberRef(grant.principalType, grant.principalId), {
187
- [grantPlace(project, grant.environmentSlug)]: null,
188
- }),
189
- () => toast.success(`Revoked ${label} on ${project} from ${grant.principalId}`),
190
- )
191
- }
192
- />
100
+ {state.state === 'pending' ? (
101
+ <RowPending status={state} />
102
+ ) : (
103
+ <ConfirmButton
104
+ trigger={<button className="act act-danger">Revoke</button>}
105
+ title={
106
+ <>
107
+ Revoke {label} from <span className="mono">{grant.principalId}</span>?
108
+ </>
109
+ }
110
+ body={
111
+ <>
112
+ They lose <strong>{label}</strong> on <span className="mono">{project}</span>{' '}
113
+ immediately, including any process using it right now. Other grants they hold
114
+ still apply.
115
+ </>
116
+ }
117
+ confirmLabel="Revoke access"
118
+ onConfirm={() => revoke(grant)}
119
+ />
120
+ )}
193
121
  </td>
194
122
  </tr>
195
- {error !== null && (
196
- <tr className="row-error">
197
- <td colSpan={5}>
198
- <ErrorLine error={error} />
199
- </td>
200
- </tr>
201
- )}
123
+ <RowFailure
124
+ status={state}
125
+ columns={5}
126
+ onDismiss={() => state.state === 'failed' && dismiss(state.mutationId)}
127
+ />
202
128
  </>
203
129
  );
204
130
  }
131
+
132
+ /**
133
+ * Grants the server refused to give: rolled back, so no row of theirs is
134
+ * left, and listed here, after the table's rows, saying why.
135
+ */
136
+ export function RefusedGrants({ refused }: { refused: RefusedGrant[] }) {
137
+ return refused.map(({ mutationId, vars, status, dismiss }) => (
138
+ <RowFailure key={mutationId} status={status} columns={5} onDismiss={dismiss}>
139
+ {vars.principalId} was not given {vars.roleName.toLowerCase()}.
140
+ </RowFailure>
141
+ ));
142
+ }
143
+
144
+ type RefusedGrant = FailedAdd<GrantVars> & { dismiss: () => void };
145
+
146
+ /** The grants of one kind the server refused to give in a project, still to be said. */
147
+ export function useRefusedGrants(project: string, grants: GrantRow[], principalType?: GrantRow['principalType']): RefusedGrant[] {
148
+ const { failedAdds, dismiss } = useChangeStatus(keys.grants(project));
149
+ return failedAdds<GrantVars>(grants.map(grantId))
150
+ .filter(({ vars }) => principalType === undefined || vars.principalType === principalType)
151
+ .map((refused) => ({ ...refused, dismiss: () => dismiss(refused.mutationId) }));
152
+ }
@@ -1,10 +1,14 @@
1
- import type { CoffreClient } from '@coffre/client';
2
1
  import { useState } from 'react';
3
- import { Link, useLoaderData, useRouter } from '@tanstack/react-router';
2
+ import { useSuspenseQueries, useSuspenseQuery } from '@tanstack/react-query';
3
+ import { Link } from '@tanstack/react-router';
4
+ import { useShell } from '../lib/use-shell';
4
5
  import { toast } from 'sonner';
5
- import { memberRef, statusOf, uiResult, useCoffre } from '../lib/coffre';
6
+ import { memberRef, useCoffre } from '../lib/coffre';
7
+ import { directoryList } from '../lib/changes';
8
+ import { affects, managedProjects, queries } from '../lib/queries';
9
+ import { useChangeStatus } from '../lib/use-change';
10
+ import { ItemFailure } from './row-state';
6
11
  import { useAction } from '../lib/use-action';
7
- import type { UiCapabilities } from '../lib/capabilities';
8
12
  import { projectAccessLabel } from '../lib/project-access';
9
13
  import {
10
14
  accessChanges,
@@ -21,7 +25,7 @@ import {
21
25
  import type { DirectoryPrincipal, GrantRow, ProjectSummary } from '../shared/models';
22
26
  import { ClosedDoor, PageHeader } from './page';
23
27
  import { EmptyState, ErrorLine, Modal, Notice, Spinner } from './ui';
24
- import { GrantRowView, GrantsTable, loadProject } from './grants';
28
+ import { GrantRowView, GrantsTable } from './grants';
25
29
  import { InstanceRole, KIND, PrincipalActions } from './directory';
26
30
  import { PrincipalReportCards, RemovedNotice } from './offboarding';
27
31
  import { PrincipalAvatar } from './principal';
@@ -33,70 +37,47 @@ type PrincipalType = DirectoryPrincipal['principalType'];
33
37
  type ProjectAccess = { project: ProjectSummary; grants: GrantRow[]; grantsError: string | null };
34
38
 
35
39
  /**
36
- * Everything one user's or token's page shows: who it is to the instance and
37
- * what it has seen (owners only), and its grants on every project where you
38
- * manage access.
39
- *
40
- * There is no "grants of this principal" call, so this asks each project you
41
- * manage for its grants and keeps this principal's. Projects where you do not
42
- * hold grant.manage are skipped rather than asked: the refusal would land in
43
- * the audit log as a denial in your name. The report is only asked for
44
- * instance owners, for the same reason.
40
+ * Everything one user's or token's page shows, from what `loadPrincipal`
41
+ * read: who it is to the instance and what it has seen (owners only), and its
42
+ * grants on every project where you manage access.
45
43
  */
46
- export async function loadPrincipalPage(
47
- client: CoffreClient,
48
- principalType: PrincipalType,
49
- principalId: string,
50
- root: { projects: ProjectSummary[]; capabilities: UiCapabilities } | undefined,
51
- ) {
52
- const managed = (root?.projects ?? []).filter((project) =>
53
- project.permissions.includes('grant.manage'),
54
- );
55
- const [report, details] = await Promise.all([
56
- root?.capabilities.canManageGrants
57
- ? uiResult(async () => {
58
- try {
59
- return { report: await client.members.get(memberRef(principalType, principalId)) };
60
- } catch (error) {
61
- // No such principal is an answer, not a failure.
62
- if (statusOf(error) === 404) return { report: null };
63
- throw error;
64
- }
65
- })
66
- : Promise.resolve(null),
67
- Promise.all(managed.map((project) => loadProject(client, project.slug))),
68
- ]);
69
-
70
- const access: ProjectAccess[] = details.flatMap((result) =>
71
- result.ok
72
- ? [
73
- {
74
- project: result.project,
75
- grants: result.grants.filter(
76
- (grant) =>
77
- grant.principalType === principalType && grant.principalId === principalId,
78
- ),
79
- grantsError: result.grantsError,
80
- },
81
- ]
82
- : [],
44
+ function usePrincipalPage(principalType: PrincipalType, principalId: string) {
45
+ const client = useCoffre();
46
+ const { projects, capabilities } = useShell();
47
+ const managed = managedProjects(projects);
48
+ const { data: report } = useSuspenseQuery(
49
+ queries.report(client, memberRef(principalType, principalId), capabilities.canManageGrants),
83
50
  );
84
-
51
+ const grants = useSuspenseQueries({
52
+ queries: managed.map((project) => queries.grants(client, project.slug)),
53
+ });
54
+ const access: ProjectAccess[] = managed.map((project, index) => {
55
+ const result = grants[index]!.data;
56
+ return {
57
+ project,
58
+ grants: result.ok
59
+ ? result.grants.filter(
60
+ (grant) => grant.principalType === principalType && grant.principalId === principalId,
61
+ )
62
+ : [],
63
+ grantsError: result.ok ? null : result.error,
64
+ };
65
+ });
85
66
  return { report, access };
86
67
  }
87
68
 
88
69
  export function PrincipalPage({
89
70
  principalType,
90
71
  principalId,
91
- data,
92
72
  }: {
93
73
  principalType: PrincipalType;
94
74
  principalId: string;
95
- data: Awaited<ReturnType<typeof loadPrincipalPage>>;
96
75
  }) {
97
- const router = useRouter();
98
- const { instanceRole } = useLoaderData({ from: '__root__' });
99
- const { report, access } = data;
76
+ const { instanceRole } = useShell();
77
+ const { report, access } = usePrincipalPage(principalType, principalId);
78
+ // A role change or removal made from this page's menu, refused.
79
+ const { status, dismiss } = useChangeStatus(directoryList.queryKey);
80
+ const change = status(memberRef(principalType, principalId));
100
81
  const kind = KIND[principalType];
101
82
  const people = principalType === 'user';
102
83
  const list = people ? '/users' : '/tokens';
@@ -170,17 +151,18 @@ export function PrincipalPage({
170
151
  />
171
152
  )}
172
153
  {entry !== undefined && (
173
- <PrincipalActions
174
- principal={entry}
175
- trigger="btn btn-icon"
176
- onRemoved={() => router.invalidate()}
177
- />
154
+ <PrincipalActions principal={entry} trigger="btn btn-icon" />
178
155
  )}
179
156
  </>
180
157
  )
181
158
  }
182
159
  />
183
160
 
161
+ {change.state === 'failed' && (
162
+ <div className="report-notice">
163
+ <ItemFailure status={change} onDismiss={() => dismiss(change.mutationId)} />
164
+ </div>
165
+ )}
184
166
  {report?.ok === false && (
185
167
  <div className="report-notice">
186
168
  <Notice tone="bad">{report.error}</Notice>
@@ -327,11 +309,16 @@ function EditAccess({
327
309
  memberRef(principalType, principalId),
328
310
  Object.assign({}, ...changed.map(({ project, changes }) => accessPatch(project.slug, changes))),
329
311
  ),
330
- () => {
331
- toast.success(
332
- `Updated ${principalId}’s access on ${changed.length} project${changed.length === 1 ? '' : 's'}`,
333
- );
334
- close();
312
+ {
313
+ affects: changed.flatMap(({ project }) =>
314
+ affects.access(project.slug, memberRef(principalType, principalId)),
315
+ ),
316
+ onSuccess: () => {
317
+ toast.success(
318
+ `Updated ${principalId}’s access on ${changed.length} project${changed.length === 1 ? '' : 's'}`,
319
+ );
320
+ close();
321
+ },
335
322
  },
336
323
  );
337
324
  }}