@coffre/ui 0.6.0 → 0.6.2

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 (103) hide show
  1. package/dist/chunks/{affordances-D0GyCT-I.js → affordances-Dtyha68j.js} +10 -2
  2. package/dist/chunks/{affordances-D0GyCT-I.js.map → affordances-Dtyha68j.js.map} +1 -1
  3. package/dist/chunks/{audit-sentence-CUUMshIp.js → audit-sentence-BVv_9_nq.js} +2 -2
  4. package/dist/chunks/{audit-sentence-CUUMshIp.js.map → audit-sentence-BVv_9_nq.js.map} +1 -1
  5. package/dist/chunks/{connected-apps-IP0KfUjo.js → connected-apps-rBF9XUob.js} +4 -4
  6. package/dist/chunks/{connected-apps-IP0KfUjo.js.map → connected-apps-rBF9XUob.js.map} +1 -1
  7. package/dist/chunks/{delete-place-CVv6CN5y.js → delete-place-CkGezx5R.js} +4 -4
  8. package/dist/chunks/{delete-place-CVv6CN5y.js.map → delete-place-CkGezx5R.js.map} +1 -1
  9. package/dist/chunks/{directory-pMVS1m-c.js → directory-SRN01yP6.js} +38 -32
  10. package/dist/chunks/directory-SRN01yP6.js.map +1 -0
  11. package/dist/chunks/{folders-hR2Lnk0k.js → folders-Dw240WMJ.js} +2 -2
  12. package/dist/chunks/{folders-hR2Lnk0k.js.map → folders-Dw240WMJ.js.map} +1 -1
  13. package/dist/chunks/{grants-CgC8Ybhu.js → grants-1E1vqkM0.js} +5 -5
  14. package/dist/chunks/{grants-CgC8Ybhu.js.map → grants-1E1vqkM0.js.map} +1 -1
  15. package/dist/chunks/multi-combobox-CsIXihuc.js +99 -0
  16. package/dist/chunks/multi-combobox-CsIXihuc.js.map +1 -0
  17. package/dist/chunks/{offboarding-3fzRjKla.js → offboarding-Bt7KSixm.js} +3 -3
  18. package/dist/chunks/{offboarding-3fzRjKla.js.map → offboarding-Bt7KSixm.js.map} +1 -1
  19. package/dist/chunks/{principal-page-CYJIJAdp.js → principal-page-Cbx2l6XL.js} +21 -24
  20. package/dist/chunks/principal-page-Cbx2l6XL.js.map +1 -0
  21. package/dist/chunks/{project-page-lO5P6iCb.js → project-page-DKo2AFYg.js} +2 -2
  22. package/dist/chunks/{project-page-lO5P6iCb.js.map → project-page-DKo2AFYg.js.map} +1 -1
  23. package/dist/chunks/{queries-gigcQOO_.js → queries-BvSw1xBN.js} +87 -15
  24. package/dist/chunks/queries-BvSw1xBN.js.map +1 -0
  25. package/dist/chunks/{references-DZ179hTJ.js → references-DCoSPtvw.js} +4 -4
  26. package/dist/chunks/{references-DZ179hTJ.js.map → references-DCoSPtvw.js.map} +1 -1
  27. package/dist/chunks/{role-field-DiqiFwm_.js → role-field-D98CvNEg.js} +2 -2
  28. package/dist/chunks/{role-field-DiqiFwm_.js.map → role-field-D98CvNEg.js.map} +1 -1
  29. package/dist/chunks/{row-state-Zf3kZVhd.js → row-state-BsIHspy4.js} +2 -2
  30. package/dist/chunks/{row-state-Zf3kZVhd.js.map → row-state-BsIHspy4.js.map} +1 -1
  31. package/dist/chunks/{theme-B6-V9JvY.js → theme-3b4DnCow.js} +2 -2
  32. package/dist/chunks/{theme-B6-V9JvY.js.map → theme-3b4DnCow.js.map} +1 -1
  33. package/dist/chunks/{ui-Br-dNUTc.js → ui-2kwXXfrX.js} +95 -22
  34. package/dist/chunks/ui-2kwXXfrX.js.map +1 -0
  35. package/dist/chunks/{use-action-CQGGNqWb.js → use-action-Bv7yQ0DW.js} +2 -2
  36. package/dist/chunks/{use-action-CQGGNqWb.js.map → use-action-Bv7yQ0DW.js.map} +1 -1
  37. package/dist/chunks/{use-change-BdS1gzyo.js → use-change-DIQTGXER.js} +58 -17
  38. package/dist/chunks/use-change-DIQTGXER.js.map +1 -0
  39. package/dist/chunks/{use-shell-BCU505bx.js → use-shell-DhFoHjDS.js} +2 -2
  40. package/dist/chunks/{use-shell-BCU505bx.js.map → use-shell-DhFoHjDS.js.map} +1 -1
  41. package/dist/index.d.ts +13 -164
  42. package/dist/index.js +142 -129
  43. package/dist/index.js.map +1 -1
  44. package/dist/pages/account.js +8 -8
  45. package/dist/pages/approval.js +1 -1
  46. package/dist/pages/audit.js +46 -60
  47. package/dist/pages/audit.js.map +1 -1
  48. package/dist/pages/device-login.js +1 -1
  49. package/dist/pages/environment.js +458 -241
  50. package/dist/pages/environment.js.map +1 -1
  51. package/dist/pages/login.js +2 -2
  52. package/dist/pages/oauth-authorize.js +1 -1
  53. package/dist/pages/project-access.js +8 -8
  54. package/dist/pages/project-environments.js +19 -58
  55. package/dist/pages/project-environments.js.map +1 -1
  56. package/dist/pages/project-settings.d.ts +1 -1
  57. package/dist/pages/project-settings.js +54 -75
  58. package/dist/pages/project-settings.js.map +1 -1
  59. package/dist/pages/project.js +3 -7
  60. package/dist/pages/project.js.map +1 -1
  61. package/dist/pages/projects.js +51 -78
  62. package/dist/pages/projects.js.map +1 -1
  63. package/dist/pages/service-account.js +11 -136
  64. package/dist/pages/service-account.js.map +1 -1
  65. package/dist/pages/service-accounts.js +4 -4
  66. package/dist/pages/settings.js +5 -5
  67. package/dist/pages/unregistered.js +1 -1
  68. package/dist/pages/user.js +5 -5
  69. package/dist/pages/users.js +4 -4
  70. package/package.json +3 -3
  71. package/src/components/actions-log.tsx +1 -1
  72. package/src/components/affordances.ts +12 -0
  73. package/src/components/command-palette.tsx +4 -5
  74. package/src/components/directory.tsx +18 -18
  75. package/src/components/missing.tsx +63 -67
  76. package/src/components/principal-page.tsx +10 -14
  77. package/src/components/service-tokens.tsx +2 -11
  78. package/src/components/shell.tsx +79 -75
  79. package/src/components/trusted-workloads.tsx +2 -11
  80. package/src/components/ui.tsx +35 -25
  81. package/src/lib/changes.ts +63 -12
  82. package/src/lib/clipboard.ts +40 -0
  83. package/src/lib/copy-attempts.ts +103 -0
  84. package/src/lib/dismissal.ts +24 -0
  85. package/src/lib/optimistic.ts +3 -1
  86. package/src/lib/queries.ts +108 -14
  87. package/src/lib/row-reads.ts +64 -0
  88. package/src/options.ts +38 -50
  89. package/src/pages/audit.tsx +15 -24
  90. package/src/pages/environment.tsx +326 -97
  91. package/src/pages/project-environments.tsx +8 -34
  92. package/src/pages/project-settings.tsx +9 -20
  93. package/src/pages/project.tsx +1 -5
  94. package/src/pages/projects.tsx +13 -28
  95. package/src/parity.ts +3 -3
  96. package/src/styles/globals.css +87 -128
  97. package/dist/chunks/directory-pMVS1m-c.js.map +0 -1
  98. package/dist/chunks/principal-page-CYJIJAdp.js.map +0 -1
  99. package/dist/chunks/project-environments-lEzFHUt4.js +0 -11
  100. package/dist/chunks/project-environments-lEzFHUt4.js.map +0 -1
  101. package/dist/chunks/queries-gigcQOO_.js.map +0 -1
  102. package/dist/chunks/ui-Br-dNUTc.js.map +0 -1
  103. package/dist/chunks/use-change-BdS1gzyo.js.map +0 -1
@@ -1,10 +1,11 @@
1
- import { useEffect, useRef, useState, type ReactElement, type ReactNode } from 'react';
1
+ import { useEffect, useRef, useState, useSyncExternalStore, type ReactElement, type ReactNode } from 'react';
2
2
  import { AlertDialog } from '@base-ui/react/alert-dialog';
3
3
  import { Dialog } from '@base-ui/react/dialog';
4
4
  import { Menu } from '@base-ui/react/menu';
5
5
  import { Popover } from '@base-ui/react/popover';
6
6
  import { Tooltip } from '@base-ui/react/tooltip';
7
7
  import { AlertCircle, AlertTriangle, Check, Copy, Info, Loader, X } from './icons';
8
+ import { createCopier, type Copier } from '../lib/copy-attempts';
8
9
  import { usePreferences } from '../lib/preferences';
9
10
 
10
11
  /* -------------------------------------------------------------------------- */
@@ -240,47 +241,55 @@ export function breakAfterUnderscores(text: string): ReactNode {
240
241
  *
241
242
  * The glyph turns into a check, and screen readers hear "Copied", for 1.4s --
242
243
  * long enough to be noticed after the eye has moved on, short enough not to
243
- * look stuck.
244
+ * look stuck. A copy that fails says so the same way, in red, rather than
245
+ * leaving the click looking ignored.
246
+ *
247
+ * `value` is the text. A caller that must read it first (Copy on a hidden
248
+ * secret) passes the `copier` it owns instead, and `onCopy`, called inside the
249
+ * click so the clipboard write keeps its user gesture, which starts a copy on
250
+ * that copier. Copies do not lock the button: a click while one is out starts
251
+ * the next, and the latest one's ending is the one that shows. The copier's
252
+ * owner outlives the button, so a remount keeps the feedback of a copy in flight.
244
253
  */
245
254
  export function CopyButton({
246
- value,
247
255
  label = 'Copy',
248
256
  variant = 'icon',
257
+ ...source
249
258
  }: {
250
- value: string;
251
259
  label?: string;
252
260
  /** `act` sits among a table row's actions; `icon` anywhere else. */
253
261
  variant?: 'icon' | 'act';
254
- }) {
255
- const [copied, setCopied] = useState(false);
256
- const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
257
-
258
- useEffect(() => () => {
259
- if (timer.current !== null) clearTimeout(timer.current);
260
- }, []);
261
-
262
- async function copy() {
263
- try {
264
- await navigator.clipboard.writeText(value);
265
- } catch {
266
- return; // Clipboard denied; say nothing rather than claim success.
267
- }
268
- setCopied(true);
269
- if (timer.current !== null) clearTimeout(timer.current);
270
- timer.current = setTimeout(() => setCopied(false), 1400);
262
+ } & ({ value: string; copier?: undefined; onCopy?: undefined } | { value?: undefined; copier: Copier; onCopy: () => void })) {
263
+ const [own] = useState(() => createCopier());
264
+ const copier = source.copier ?? own;
265
+ const state = useSyncExternalStore(copier.subscribe, copier.feedback, copier.feedback);
266
+
267
+ function copy() {
268
+ if (source.copier !== undefined) source.onCopy();
269
+ else void own.run(source.value);
271
270
  }
272
271
 
272
+ const text = state === 'copied' ? 'Copied' : state === 'failed' ? 'Copy failed' : label;
273
273
  return (
274
- <Tip label={copied ? 'Copied' : label}>
274
+ <Tip label={text}>
275
275
  <button
276
276
  type="button"
277
277
  className={variant === 'act' ? 'act act-icon' : 'btn btn-quiet btn-sm btn-icon'}
278
278
  aria-label={label}
279
+ aria-busy={state === 'pending'}
279
280
  onClick={copy}
280
281
  >
281
- {copied ? <Check size={14} className="copied" /> : <Copy size={14} />}
282
+ {state === 'pending' ? (
283
+ <Spinner size={13} />
284
+ ) : state === 'copied' ? (
285
+ <Check size={14} className="copied" />
286
+ ) : state === 'failed' ? (
287
+ <AlertCircle size={14} className="copy-failed" />
288
+ ) : (
289
+ <Copy size={14} />
290
+ )}
282
291
  <span className="visually-hidden" aria-live="polite">
283
- {copied ? 'Copied' : ''}
292
+ {state === 'copied' ? 'Copied' : state === 'failed' ? 'Copy failed' : ''}
284
293
  </span>
285
294
  </button>
286
295
  </Tip>
@@ -430,7 +439,8 @@ function relative(iso: string, now: number, style: 'long' | 'narrow' = 'long'):
430
439
  return formatter.format(Math.round(delta / divisor), unit);
431
440
  }
432
441
 
433
- function absolute(iso: string, precise: boolean): string {
442
+ /** A UTC time as the log writes it: `2026-10-17 08:45:13`, to the millisecond when `precise`. */
443
+ export function absolute(iso: string, precise: boolean): string {
434
444
  return iso.replace('T', ' ').replace('Z', '').slice(0, precise ? 23 : 19);
435
445
  }
436
446
 
@@ -1,4 +1,4 @@
1
- import type { CoffreClient, ConnectedApp, IdentityRow, OffboardingReport, SecretKey, SessionRow } from '@coffre/client';
1
+ import type { CoffreClient, ConnectedApp, IdentityRow, MissingKey, OffboardingReport, SecretKey, SessionRow } from '@coffre/client';
2
2
  import { EVERYWHERE, unscoped, type InstanceRole, type Role, type Scope } from '@coffre/core/access';
3
3
  import type { QueryKey } from '@tanstack/react-query';
4
4
 
@@ -34,6 +34,7 @@ function listOf<TItem, TData extends { ok: boolean } | null>(
34
34
  const ARCHIVING: Words = { pending: 'Archiving…', done: 'archived', failed: 'Not archived.' };
35
35
  const REVOKING: Words = { pending: 'Revoking…', done: 'revoked', failed: 'Not revoked.' };
36
36
  const DISCONNECTING: Words = { pending: 'Disconnecting…', done: 'disconnected', failed: 'Not disconnected.' };
37
+ const MOVING: Words = { pending: 'Moving…', done: 'moved', failed: 'Not moved.' };
37
38
 
38
39
  const saving = (id: string): Target => ({ id, kind: 'saving' });
39
40
  const removing = (id: string): Target => ({ id, kind: 'removing' });
@@ -98,7 +99,7 @@ export function grantAccess(client: CoffreClient, project: string): Change<Grant
98
99
  },
99
100
  affects: (vars) => [
100
101
  ...affects.access(project, memberRef(vars.principalType, vars.principalId)),
101
- ...(vars.admit === true ? affects.admission() : []),
102
+ ...(vars.admit === true ? affects.admission(memberRef(vars.principalType, vars.principalId)) : []),
102
103
  ],
103
104
  run: async (vars) => {
104
105
  const place = grantPlace(project, vars.environmentSlug);
@@ -161,7 +162,7 @@ export function invite(client: CoffreClient): Change<Directory, DirectoryPrincip
161
162
  scope: vars.principalType === 'user' ? vars.scope : EVERYWHERE,
162
163
  },
163
164
  ],
164
- affects: () => affects.admission(),
165
+ affects: (vars) => affects.admission(principalId(vars)),
165
166
  run: async (vars) => {
166
167
  // Adding is an idempotent PUT that would also set the role of someone
167
168
  // already here; this is only for someone new.
@@ -296,7 +297,7 @@ type Projects = ({ ok: true; projects: ProjectSummary[] } | Failure);
296
297
 
297
298
  export const projectsList = listOf<ProjectSummary, Projects>(keys.projects, 'projects', (project) => project.slug);
298
299
 
299
- export function createProject(client: CoffreClient): Change<Projects, ProjectSummary, { slug: string; name: string }, void> {
300
+ export function createProject(client: CoffreClient): Change<Projects, ProjectSummary, { slug: string }, void> {
300
301
  return {
301
302
  list: projectsList,
302
303
  label: (vars) => `project ${vars.slug}`,
@@ -305,7 +306,7 @@ export function createProject(client: CoffreClient): Change<Projects, ProjectSum
305
306
  ...projects,
306
307
  {
307
308
  slug: vars.slug,
308
- name: vars.name,
309
+ name: vars.slug,
309
310
  archivedAt: null,
310
311
  folder: null,
311
312
  // Its maker manages it by their instance role, an Admin's or an Owner's.
@@ -317,7 +318,7 @@ export function createProject(client: CoffreClient): Change<Projects, ProjectSum
317
318
  affects: () => affects.places(),
318
319
  run: async (vars) => {
319
320
  // Creating is an idempotent PUT; a slug that is taken is refused here.
320
- const { created } = await client.projects.create(vars.slug, { name: vars.name });
321
+ const { created } = await client.projects.create(vars.slug);
321
322
  if (!created) throw new Refusal(`A project named "${vars.slug}" already exists.`);
322
323
  },
323
324
  };
@@ -358,19 +359,18 @@ export function environmentId(project: string, environment: string): string {
358
359
  }
359
360
 
360
361
  /** A new environment, empty or, `from` a sibling, forked: each of its keys copied. */
361
- export function createEnvironment(client: CoffreClient, project: string): Change<Projects, Environment, { slug: string; name: string; from?: string; references?: boolean }, void> {
362
+ export function createEnvironment(client: CoffreClient, project: string): Change<Projects, Environment, { slug: string; from?: string; references?: boolean }, void> {
362
363
  return {
363
364
  list: environmentsList(project),
364
365
  label: (vars) => `environment ${vars.slug}`,
365
366
  targets: (vars) => [saving(environmentId(project, vars.slug))],
366
367
  apply: (environments, vars) => [
367
368
  ...environments,
368
- { slug: vars.slug, name: vars.name, accessible: false, details: { archivedAt: null, secretCount: 0 } },
369
+ { slug: vars.slug, name: vars.slug, accessible: false, details: { archivedAt: null, secretCount: 0 } },
369
370
  ],
370
371
  affects: () => affects.places(),
371
372
  run: async (vars) => {
372
373
  const { created } = await client.environments.create(`${project}/${vars.slug}`, {
373
- name: vars.name,
374
374
  ...(vars.from === undefined ? {} : { from: vars.from }),
375
375
  ...(vars.references === true ? { references: true } : {}),
376
376
  });
@@ -379,7 +379,7 @@ export function createEnvironment(client: CoffreClient, project: string): Change
379
379
  };
380
380
  }
381
381
 
382
- export type RenameVars = { from: string; slug: string; name: string };
382
+ export type RenameVars = { from: string; slug: string };
383
383
 
384
384
  export function renameEnvironment(client: CoffreClient, project: string): Change<Projects, Environment, RenameVars, unknown> {
385
385
  return {
@@ -391,10 +391,10 @@ export function renameEnvironment(client: CoffreClient, project: string): Change
391
391
  : [saving(environmentId(project, vars.from)), saving(environmentId(project, vars.slug))],
392
392
  apply: (environments, vars) =>
393
393
  environments.map((environment) =>
394
- environment.slug === vars.from ? { ...environment, slug: vars.slug, name: vars.name } : environment,
394
+ environment.slug === vars.from ? { ...environment, slug: vars.slug } : environment,
395
395
  ),
396
396
  affects: () => affects.places(),
397
- run: (vars) => client.environments.update(`${project}/${vars.from}`, { slug: vars.slug, name: vars.name }),
397
+ run: (vars) => client.environments.update(`${project}/${vars.from}`, { slug: vars.slug }),
398
398
  };
399
399
  }
400
400
 
@@ -560,6 +560,7 @@ export function moveSecret(
560
560
  ): Change<Secrets, SecretKey, { key: string; folder: string | null }, unknown> {
561
561
  return {
562
562
  list: secretsList(place),
563
+ saving: MOVING,
563
564
  label: (vars) => vars.key,
564
565
  targets: (vars) => [saving(vars.key)],
565
566
  apply: (entries, vars) => entries.map((entry) => (entry.key === vars.key ? { ...entry, folder: vars.folder } : entry)),
@@ -599,3 +600,53 @@ export function archiveSecret(
599
600
  run: (vars) => client.secrets.update(`${place.project}/${place.environment}/${vars.key}`, { archived: true }),
600
601
  };
601
602
  }
603
+
604
+ // --- missing keys ----------------------------------------------------------------
605
+
606
+ type Missing = ({ ok: true; missing: MissingKey[] } | Failure);
607
+
608
+ export function missingList(place: { project: string; environment: string }) {
609
+ return listOf<MissingKey, Missing>(keys.missing(place), 'missing', (entry) => entry.key);
610
+ }
611
+
612
+ const DISMISSING: Words = { pending: 'Dismissing…', done: 'dismissed', failed: 'Not dismissed.' };
613
+ const RESTORING: Words = { pending: 'Restoring…', done: 'restored', failed: 'Not restored.' };
614
+
615
+ /**
616
+ * Dismiss missing keys for the whole team. It shows at once: a dismissal
617
+ * hides nothing anyone may read, so it need not wait for the server, and a
618
+ * refusal puts the keys back.
619
+ */
620
+ export function dismissMissing(client: CoffreClient, place: { project: string; environment: string }) {
621
+ return missingChange(client, place, true);
622
+ }
623
+
624
+ /** Bring dismissed keys back, as Undo after a dismissal does: listed again at once. */
625
+ export function restoreMissing(client: CoffreClient, place: { project: string; environment: string }) {
626
+ return missingChange(client, place, false);
627
+ }
628
+
629
+ function missingChange(
630
+ client: CoffreClient,
631
+ place: { project: string; environment: string },
632
+ dismissed: boolean,
633
+ ): Change<Missing, MissingKey, MissingKey[], unknown> {
634
+ return {
635
+ list: missingList(place),
636
+ saving: dismissed ? DISMISSING : RESTORING,
637
+ label: (entries) => (entries.length === 1 ? entries[0]!.key : `${entries.length} missing keys`),
638
+ targets: (entries) => entries.map((entry) => saving(entry.key)),
639
+ apply: (entries, named) => {
640
+ const names = new Set(named.map((entry) => entry.key));
641
+ const others = entries.filter((entry) => !names.has(entry.key));
642
+ // Listed by name, as the server lists them.
643
+ return dismissed ? others : [...others, ...named].sort((a, b) => (a.key < b.key ? -1 : 1));
644
+ },
645
+ affects: () => [],
646
+ run: (entries) =>
647
+ client.environments.dismiss(
648
+ `${place.project}/${place.environment}`,
649
+ Object.fromEntries(entries.map((entry) => [entry.key, dismissed ? true : null])),
650
+ ),
651
+ };
652
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Writing to the clipboard, from text that may still be on its way.
3
+ *
4
+ * A browser lets a page write to the clipboard only inside a click's user
5
+ * gesture, and Safari drops the gesture across an `await`. So a value that has
6
+ * to be fetched first (Copy on a hidden secret) is handed over as a promise:
7
+ * `clipboard.write` is called at once, with the promise inside a
8
+ * `ClipboardItem`, and the browser waits for it. Where that is not supported,
9
+ * the text is awaited, then written with `writeText`, which is what every
10
+ * browser but Safari allows.
11
+ *
12
+ * The text goes through byte for byte: no trimming, no newline changes.
13
+ */
14
+
15
+ /** What of the clipboard `copyText` uses; the browser's `navigator.clipboard` fits. */
16
+ export type ClipboardLike = {
17
+ writeText(text: string): Promise<void>;
18
+ write?(items: unknown[]): Promise<void>;
19
+ };
20
+
21
+ type ClipboardItemConstructor = new (items: Record<string, Promise<string>>) => unknown;
22
+
23
+ export async function copyText(
24
+ text: string | Promise<string>,
25
+ {
26
+ clipboard = globalThis.navigator?.clipboard as ClipboardLike | undefined,
27
+ item = (globalThis as { ClipboardItem?: ClipboardItemConstructor }).ClipboardItem,
28
+ }: { clipboard?: ClipboardLike; item?: ClipboardItemConstructor } = {},
29
+ ): Promise<void> {
30
+ // A read that fails after the copy has ended is nobody's to hear: not an unhandled rejection.
31
+ if (typeof text !== 'string') text.catch(() => {});
32
+ if (clipboard === undefined) throw new Error('The clipboard is not available here.');
33
+ if (typeof text !== 'string' && item !== undefined && clipboard.write !== undefined) {
34
+ // Called before anything is awaited: this is what keeps the user gesture.
35
+ // The text goes in as a string, not a Blob: decoding a Blob drops a leading U+FEFF.
36
+ await clipboard.write([new item({ 'text/plain': text })]);
37
+ return;
38
+ }
39
+ await clipboard.writeText(await text);
40
+ }
@@ -0,0 +1,103 @@
1
+ import { copyText } from './clipboard.ts';
2
+
3
+ /**
4
+ * How a copy ended, as far as anyone still cares.
5
+ *
6
+ * `superseded`: a newer copy began before this one ended, so this one reports
7
+ * nothing and writes nothing. Its result, good or bad, is not what the person
8
+ * asked for last.
9
+ */
10
+ export type CopyResult = { outcome: 'copied' } | { outcome: 'failed'; failure: unknown } | { outcome: 'superseded' };
11
+
12
+ /** What a copy button shows: a copy under way, or how the last one ended, for a moment. */
13
+ export type CopyFeedback = 'idle' | 'pending' | 'copied' | 'failed';
14
+
15
+ /**
16
+ * Copies where the latest one wins, and what they look like while they run.
17
+ *
18
+ * The clipboard is one resource per page, so "latest" is decided per page: every
19
+ * copy, from any row, takes a number from one counter before it awaits anything,
20
+ * and only the newest reports, shows feedback, or writes. A copy may start while
21
+ * an earlier one is still reading or waiting on the clipboard: a retry after a
22
+ * refusal, a click on another row, a row filtered out and back, a button replaced
23
+ * by a remount. When a copy from another copier takes over, the older one drops
24
+ * its pending or "Copied" feedback and goes back to idle. A copier belongs to
25
+ * whoever outlives the button (a row); the button only subscribes to it, so a
26
+ * remount picks up where it was.
27
+ */
28
+ export type Copier = {
29
+ run(text: string | Promise<string>): Promise<CopyResult>;
30
+ feedback(): CopyFeedback;
31
+ subscribe(listener: () => void): () => void;
32
+ };
33
+
34
+ const SUPERSEDED = new Error('A newer copy began.');
35
+
36
+ /** The page's newest copy, and the copier that made it. */
37
+ let latest = 0;
38
+ let owner: { drop(): void } | null = null;
39
+
40
+ export function createCopier({
41
+ copy = copyText,
42
+ copiedMs = 1400,
43
+ failedMs = 3000,
44
+ }: { copy?: typeof copyText; copiedMs?: number; failedMs?: number } = {}): Copier {
45
+ let feedback: CopyFeedback = 'idle';
46
+ let timer: ReturnType<typeof setTimeout> | null = null;
47
+ const listeners = new Set<() => void>();
48
+
49
+ function show(next: CopyFeedback) {
50
+ if (feedback === next) return;
51
+ feedback = next;
52
+ for (const listener of listeners) listener();
53
+ }
54
+
55
+ function stopTimer() {
56
+ if (timer !== null) clearTimeout(timer);
57
+ timer = null;
58
+ }
59
+
60
+ const self = {
61
+ /** Another copier's copy took over: nothing of this one's is left showing. */
62
+ drop() {
63
+ stopTimer();
64
+ show('idle');
65
+ },
66
+ };
67
+
68
+ return {
69
+ feedback: () => feedback,
70
+ subscribe(listener) {
71
+ listeners.add(listener);
72
+ return () => void listeners.delete(listener);
73
+ },
74
+ async run(text) {
75
+ const attempt = ++latest;
76
+ if (owner !== null && owner !== self) owner.drop();
77
+ owner = self;
78
+ stopTimer();
79
+ show('pending');
80
+ // A read that finishes after a newer copy began, anywhere on the page, is
81
+ // refused here, so it never reaches the clipboard: the fallback does not
82
+ // write it, and a ClipboardItem whose payload rejects writes nothing.
83
+ const gated =
84
+ typeof text === 'string'
85
+ ? text
86
+ : text.then((value) => {
87
+ if (attempt !== latest) throw SUPERSEDED;
88
+ return value;
89
+ });
90
+ let result: CopyResult = { outcome: 'copied' };
91
+ try {
92
+ // Called before anything is awaited: the click's gesture is still live.
93
+ await copy(gated);
94
+ } catch (failure) {
95
+ result = { outcome: 'failed', failure };
96
+ }
97
+ if (attempt !== latest) return { outcome: 'superseded' };
98
+ show(result.outcome === 'copied' ? 'copied' : 'failed');
99
+ timer = setTimeout(() => show('idle'), result.outcome === 'copied' ? copiedMs : failedMs);
100
+ return result;
101
+ },
102
+ };
103
+ }
@@ -0,0 +1,24 @@
1
+ import type { MissingKey } from '@coffre/client';
2
+ import { toast } from 'sonner';
3
+
4
+ import { failureMessage } from './coffre.ts';
5
+
6
+ /**
7
+ * Dismiss missing keys, and say so at once in a toast with Undo. A refused
8
+ * dismissal turns that toast into why it was refused, so the reason shows
9
+ * whatever the list does next: when reading it again fails too, the panel
10
+ * has no rows left to say it beneath.
11
+ */
12
+ export function dismissWithUndo(
13
+ entries: MissingKey[],
14
+ { dismiss, restore }: { dismiss: (entries: MissingKey[]) => Promise<unknown>; restore: (entries: MissingKey[]) => Promise<unknown> },
15
+ ): string | number {
16
+ const said = toast.success(entries.length === 1 ? `${entries[0]!.key} dismissed` : `${entries.length} keys dismissed`, {
17
+ action: {
18
+ label: 'Undo',
19
+ onClick: () => void restore(entries).catch((error: unknown) => toast.error(`Not restored. ${failureMessage(error)}`)),
20
+ },
21
+ });
22
+ dismiss(entries).catch((error: unknown) => toast.error(`Not dismissed. ${failureMessage(error)}`, { id: said, action: undefined }));
23
+ return said;
24
+ }
@@ -51,6 +51,8 @@ export type Change<TData, TItem, TVars, TResult> = {
51
51
  * removed ones as they are until confirmed. A rename touches both names.
52
52
  */
53
53
  targets: (vars: TVars) => Target[];
54
+ /** How saves are worded, when not as saves: dismissing. */
55
+ saving?: Words;
54
56
  /** How removals are worded, when not as removals: archiving, revoking. */
55
57
  removing?: Words;
56
58
  /** The items as they will be once the saves land; removals are left for the server. */
@@ -83,7 +85,7 @@ export function changeOptions<TData, TItem, TVars, TResult>(
83
85
  mutationFn: change.run,
84
86
  onMutate: async (vars) => {
85
87
  const targets = change.targets(vars);
86
- const words = { saving: WORDS.saving, removing: change.removing ?? WORDS.removing };
88
+ const words = { saving: change.saving ?? WORDS.saving, removing: change.removing ?? WORDS.removing };
87
89
  announce(`${change.label(vars)}: ${words[mainKind(targets)].pending}`);
88
90
  // A read already on its way would land over the change.
89
91
  await queryClient.cancelQueries({ queryKey: list.queryKey });
@@ -1,9 +1,10 @@
1
1
  import type { AuthInfo, CoffreClient, Member } from '@coffre/client';
2
2
  import { EVERYWHERE, INSTANCE_ROLES } from '@coffre/core/access';
3
- import { QueryClient, queryOptions, type QueryKey } from '@tanstack/react-query';
3
+ import { QueryClient, queryOptions, type FetchQueryOptions, type QueryKey } from '@tanstack/react-query';
4
4
 
5
5
  import { deriveUiCapabilities } from './capabilities.ts';
6
6
  import { memberRef, statusOf, uiResult } from './coffre.ts';
7
+ import { isActiveAccessibleEnvironment } from './project-environments.ts';
7
8
  import type { DirectoryPrincipal, GrantRow, Me, ProjectSummary } from '../shared/models';
8
9
 
9
10
  /**
@@ -98,13 +99,14 @@ function listDirectory(client: CoffreClient) {
98
99
  return uiResult(async () => {
99
100
  const { members, removed } = await client.members.list();
100
101
  const principals: DirectoryPrincipal[] = members.map(
101
- ({ principalType, principalId, instanceRole, scope, tampered, managed, grants }) => ({
102
+ ({ principalType, principalId, instanceRole, scope, tampered, managed, declared, grants }) => ({
102
103
  principalType,
103
104
  principalId,
104
105
  instanceRole,
105
106
  scope,
106
107
  tampered,
107
108
  managed,
109
+ declared,
108
110
  grants: grants.map(({ project, environment }) => ({ project, environment })),
109
111
  }),
110
112
  );
@@ -392,15 +394,37 @@ export function shellOf(
392
394
 
393
395
  export type Shell = ReturnType<typeof shellOf>;
394
396
 
397
+ /**
398
+ * How a loader reads. `fresh`, a page's own reads: the cached answer within
399
+ * `FRESH_MS`, else the network's, waited for. `cached`, a tab's: its page's
400
+ * layout has read the same, so it takes the cached answer at once, however
401
+ * old, and refetches behind it, and switching tabs never waits on the
402
+ * network. A read the cache lacks is waited for either way.
403
+ */
404
+ export type Freshness = 'fresh' | 'cached';
405
+
406
+ function read<T, TKey extends QueryKey>(queryClient: QueryClient, options: FetchQueryOptions<T, Error, T, TKey>, freshness: Freshness): Promise<T> {
407
+ return freshness === 'fresh' ? queryClient.fetchQuery(options) : queryClient.ensureQueryData({ ...options, revalidateIfStale: true });
408
+ }
409
+
410
+ /**
411
+ * Whether a tab may open: from the cache, and where the cache says no, from
412
+ * the network, which a no needs before the tab sends anyone away. A stale
413
+ * no could be an account since added back, or a role since given.
414
+ */
415
+ export async function tabOpens(opens: (freshness: Freshness) => Promise<boolean>): Promise<boolean> {
416
+ return (await opens('cached')) || opens('fresh');
417
+ }
418
+
395
419
  /**
396
420
  * The shell, as every loader reads it: from the cache while fresh, so a
397
421
  * child route never asks again for what the root has.
398
422
  */
399
- export async function loadShell(queryClient: QueryClient, client: CoffreClient): Promise<Shell> {
423
+ export async function loadShell(queryClient: QueryClient, client: CoffreClient, freshness: Freshness = 'fresh'): Promise<Shell> {
400
424
  const [auth, me, projects] = await Promise.all([
401
- queryClient.fetchQuery(queries.auth(client)),
402
- queryClient.fetchQuery(queries.me(client)),
403
- queryClient.fetchQuery(queries.projects(client)),
425
+ read(queryClient, queries.auth(client), freshness),
426
+ read(queryClient, queries.me(client), freshness),
427
+ read(queryClient, queries.projects(client), freshness),
404
428
  ]);
405
429
  return shellOf(auth, me, projects);
406
430
  }
@@ -422,6 +446,33 @@ export async function loadProject(queryClient: QueryClient, client: CoffreClient
422
446
  if (found.ok && found.managesAccess) await queryClient.fetchQuery(queries.grants(client, slug));
423
447
  }
424
448
 
449
+ /**
450
+ * What an environment's page reads: its secrets and, for whoever reads them,
451
+ * the references that read them from elsewhere and the keys it lacks,
452
+ * rendered with them. Where the project tree the shell holds says you read
453
+ * it, all three are asked at once, one round trip; elsewhere the others wait
454
+ * for the secrets, so a refused visit is one refusal in the log, not three.
455
+ */
456
+ export async function loadEnvironment(queryClient: QueryClient, client: CoffreClient, place: Place) {
457
+ const others = () =>
458
+ Promise.all([
459
+ queryClient.fetchQuery(queries.references(client, `${place.project}/${place.environment}`)),
460
+ queryClient.fetchQuery(queries.missing(client, place)),
461
+ ]);
462
+ const found = projectOf(await queryClient.ensureQueryData(queries.projects(client)), place.project);
463
+ // Neither in an archived project nor archived itself: the API serves neither.
464
+ const here = found.ok && found.project.archivedAt === null
465
+ ? found.project.environments.find((environment) => environment.slug === place.environment)
466
+ : undefined;
467
+ if (here !== undefined && isActiveAccessibleEnvironment(here)) {
468
+ const [secrets] = await Promise.all([queryClient.fetchQuery(queries.secrets(client, place)), others()]);
469
+ return secrets;
470
+ }
471
+ const secrets = await queryClient.fetchQuery(queries.secrets(client, place));
472
+ if (secrets.ok) await others();
473
+ return secrets;
474
+ }
475
+
425
476
  /** The directory pages' read: the directory, for owners. */
426
477
  export async function loadDirectory(queryClient: QueryClient, client: CoffreClient) {
427
478
  const shell = await loadShell(queryClient, client);
@@ -479,9 +530,9 @@ export async function loadServiceDirectory(queryClient: QueryClient, client: Cof
479
530
  }
480
531
 
481
532
  /** Who a user or service account is to the instance, its pages' header: null to anyone who does not run it. */
482
- export async function loadMember(queryClient: QueryClient, client: CoffreClient, member: string) {
483
- const shell = await loadShell(queryClient, client);
484
- return queryClient.fetchQuery(queries.report(client, member, shell.capabilities.runsInstance));
533
+ export async function loadMember(queryClient: QueryClient, client: CoffreClient, member: string, freshness: Freshness = 'fresh') {
534
+ const shell = await loadShell(queryClient, client, freshness);
535
+ return read(queryClient, queries.report(client, member, shell.capabilities.runsInstance), freshness);
485
536
  }
486
537
 
487
538
  export type MemberReport = Awaited<ReturnType<typeof loadMember>>;
@@ -491,9 +542,42 @@ export type MemberReport = Awaited<ReturnType<typeof loadMember>>;
491
542
  * and the grants you manage, in one request, which the server answers in
492
543
  * one query, however many projects they hold grants in.
493
544
  */
494
- export async function loadAccess(queryClient: QueryClient, client: CoffreClient, member: string) {
495
- const shell = await loadShell(queryClient, client);
496
- return queryClient.fetchQuery(queries.memberAccess(client, member, listsAccess(shell)));
545
+ export async function loadAccess(queryClient: QueryClient, client: CoffreClient, member: string, freshness: Freshness = 'fresh') {
546
+ const shell = await loadShell(queryClient, client, freshness);
547
+ return read(queryClient, queries.memberAccess(client, member, listsAccess(shell)), freshness);
548
+ }
549
+
550
+ /**
551
+ * A user's or service account's page: what every tab but Activity shows,
552
+ * read once by its layout, so its tabs open at once. Who they are, what they
553
+ * hold and, for a service account, how it signs in.
554
+ */
555
+ export async function loadPrincipal(queryClient: QueryClient, client: CoffreClient, principalType: 'user' | 'service', principalId: string) {
556
+ const member = memberRef(principalType, principalId);
557
+ await Promise.all([
558
+ loadMember(queryClient, client, member),
559
+ principalType === 'service' ? loadSignIn(queryClient, client, member) : loadAccess(queryClient, client, member),
560
+ ]);
561
+ }
562
+
563
+ /**
564
+ * A service account's Sign-in tab: its bearer tokens and trust bindings, as
565
+ * far as its page shows them (`signInWays`), which it returns: null where it
566
+ * shows neither.
567
+ */
568
+ export async function loadSignIn(queryClient: QueryClient, client: CoffreClient, member: string, freshness: Freshness = 'fresh') {
569
+ const [shell, access] = await Promise.all([
570
+ loadShell(queryClient, client, freshness),
571
+ loadAccess(queryClient, client, member, freshness),
572
+ ]);
573
+ const ways = signInWays(shell, access);
574
+ if (ways !== null) {
575
+ await Promise.all([
576
+ read(queryClient, queries.credentials(client, member, ways.tokens), freshness),
577
+ read(queryClient, queries.bindings(client, member, ways.workloads), freshness),
578
+ ]);
579
+ }
580
+ return ways;
497
581
  }
498
582
 
499
583
  /**
@@ -555,8 +639,18 @@ export const affects = {
555
639
  keys.projects,
556
640
  keys.me,
557
641
  ],
558
- /** Someone let in: the directory. */
559
- admission: (): QueryKey[] => [keys.directory],
642
+ /**
643
+ * Someone let in: the directory, and whatever was read of them before
644
+ * they were there, which said there was no such member: a new service
645
+ * account's row asks how it signs in as soon as it shows.
646
+ */
647
+ admission: (member: string): QueryKey[] => [
648
+ keys.directory,
649
+ keys.report(member),
650
+ keys.memberAccess(member),
651
+ keys.credentials(member),
652
+ keys.bindings(member),
653
+ ],
560
654
  /**
561
655
  * An instance role changed: the directory, their report, and, as it may be
562
656
  * your own, what you can see and do.