@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,14 +1,14 @@
1
1
  import { ageInDays, byFolder, CoffreError, foldersOf, olderThan, planImport, shownMember, type CoffreClient, type ListedReference } from '@coffre/client';
2
2
  import { parseDotenv } from '@coffre/core/dotenv';
3
- import { useEffect, useRef, useState, type ReactNode } from 'react';
4
- import { useQuery, useSuspenseQuery } from '@tanstack/react-query';
3
+ import { useEffect, useReducer, useRef, useState, type ReactNode } from 'react';
4
+ import { useQuery, useQueryClient, useSuspenseQuery } from '@tanstack/react-query';
5
5
  import { Link } from '@tanstack/react-router';
6
6
  import { useShell } from '../lib/use-shell';
7
7
  import { Menu } from '@base-ui/react/menu';
8
8
  import { toast } from 'sonner';
9
9
  import { failureMessage, useCoffre } from '../lib/coffre';
10
- import { archiveSecret, moveSecret, restoreSecret, saveSecrets, UnsavedEdits } from '../lib/changes';
11
- import type { ItemStatus } from '../lib/optimistic';
10
+ import { archiveSecret, moveSecret, restoreSecret, saveSecrets, UnsavedEdits, type SaveSecretsVars } from '../lib/changes';
11
+ import { changeKey, type ItemStatus } from '../lib/optimistic';
12
12
  import { affects, keys as queryKeys, queries } from '../lib/queries';
13
13
  import { useChange, useChangeStatus } from '../lib/use-change';
14
14
  import { RowFailure, RowPending, rowClass } from '../components/row-state';
@@ -29,10 +29,12 @@ import {
29
29
  type SecretChange,
30
30
  type SecretDraft,
31
31
  } from '../lib/secret-edit-batch';
32
+ import { createCopier } from '../lib/copy-attempts';
32
33
  import { revealIsCurrent, type Reveal } from '../lib/reveal';
34
+ import { noReads, revealToggleDisabled, rowReads } from '../lib/row-reads';
33
35
  import { sortKeys, type Sort } from '../lib/secret-order';
34
36
  import { inDialog } from '../lib/shortcuts';
35
- import { secretKeyProblem } from '../lib/validation';
37
+ import { folderProblem, secretKeyProblem } from '../lib/validation';
36
38
  import {
37
39
  breakAfterUnderscores,
38
40
  ConfirmButton,
@@ -53,6 +55,7 @@ import { GenerateValue, type GeneratedUse } from '../components/generate-value';
53
55
  import { MaskedInput, MaskedTextarea } from '../components/masked';
54
56
  import { FolderMenu, FolderRow, MoveToFolder } from '../components/folders';
55
57
  import { MissingKeys } from '../components/missing';
58
+ import { MultiCombobox } from '../components/multi-combobox';
56
59
  import { ArchiveBlocked, archiveBlockers, LentReferences, MakeReference, ReferenceValue } from '../components/references';
57
60
  import { isActiveAccessibleEnvironment } from '../lib/project-environments';
58
61
  import {
@@ -95,6 +98,13 @@ const Route = pageRoute<typeof environment>();
95
98
  */
96
99
  const REVEAL_TTL_SECONDS = 45;
97
100
 
101
+ /** Why a read of a secret's value failed, as the row says it. */
102
+ function readFailureMessage(failure: unknown): string {
103
+ return failure instanceof CoffreError
104
+ ? failureMessage(failure)
105
+ : 'The request could not be sent. Nothing was read.';
106
+ }
107
+
98
108
  export function EnvironmentPage() {
99
109
  const { project, environment } = Route.useParams();
100
110
  const { data: result } = useSuspenseQuery(queries.secrets(useCoffre(), { project, environment }));
@@ -152,6 +162,7 @@ function EnvironmentLedger({
152
162
  rotateAfterDays: number | null;
153
163
  }) {
154
164
  const coffre = useCoffre();
165
+ const queryClient = useQueryClient();
155
166
  const { principal } = useShell();
156
167
  const save = useChange(saveSecrets(coffre, { project, environment }, principal?.id ?? null));
157
168
  const restore = useChange(restoreSecret(coffre, { project, environment }));
@@ -179,6 +190,7 @@ function EnvironmentLedger({
179
190
  const [sort, setSort] = useState<Sort>({ by: 'key', descending: false });
180
191
  // A column's first click sorts it ascending: names A to Z, the oldest values first.
181
192
  const sortBy = (by: Sort['by']) => setSort((current) => ({ by, descending: current.by === by && !current.descending }));
193
+ const [addingFolder, setAddingFolder] = useState(false);
182
194
  const nextDraftId = useRef(0);
183
195
 
184
196
  const canWrite = permissions.includes('secret.write');
@@ -188,6 +200,10 @@ function EnvironmentLedger({
188
200
  // Listed by folder: those in none first, then each folder by name.
189
201
  const active = byFolder(keys.filter((entry) => !entry.archived)).flatMap(([, entries]) => entries);
190
202
  const folders = foldersOf(active);
203
+ // What can be filed now: not a secret whose save is on its way, which may
204
+ // not exist yet, nor one with an edit pending, as its menu offers no move
205
+ // while it is edited.
206
+ const settled = active.filter((entry) => status(entry.key).state !== 'pending' && secretChangeFor(changes, entry.key) === undefined);
191
207
  // Renaming or removing a folder: everything in it at once, the keys staying where they are.
192
208
  const refile = useAction();
193
209
  const place = `${project}/${environment}`;
@@ -285,6 +301,7 @@ function EnvironmentLedger({
285
301
  save(batch, {
286
302
  // What did not go comes back as it was, beside the other pending rows.
287
303
  onError: (error) => {
304
+ forgetRefusal(batch);
288
305
  const left = error instanceof UnsavedEdits ? error.outcome : batch;
289
306
  setDrafts((rows) => [...rows, ...left.drafts]);
290
307
  setChanges((current) => ({ ...current, ...left.changes }));
@@ -315,11 +332,16 @@ function EnvironmentLedger({
315
332
  setChanges({});
316
333
  setEditing(new Set());
317
334
  setSaveError(null);
318
- // A refused save, given up: its rows stop saying so.
319
- for (const entry of keys) {
320
- const state = status(entry.key);
321
- if (state.state === 'failed') dismiss(state.mutationId);
322
- }
335
+ }
336
+
337
+ /**
338
+ * A refused save leaves its rows no failure of their own: its edits come
339
+ * back on them, and the bar under the table says why. Every other refused
340
+ * change, a move for one, says why beneath its row.
341
+ */
342
+ function forgetRefusal(batch: SaveSecretsVars) {
343
+ const saves = queryClient.getMutationCache().findAll({ mutationKey: changeKey(queryKeys.secrets({ project, environment })) });
344
+ for (const each of saves) if (each.state.variables === batch) dismiss(each.mutationId);
323
345
  }
324
346
 
325
347
  /**
@@ -327,7 +349,7 @@ function EnvironmentLedger({
327
349
  * rest as one patch that lands whole or not at all. The edits show in the
328
350
  * list at once, each row marked as saving; whatever did not land comes
329
351
  * back as pending, so pressing save again retries exactly that, and the
330
- * save bar says why.
352
+ * bar under the table says why.
331
353
  */
332
354
  function saveChanges() {
333
355
  if (!ready) return;
@@ -338,6 +360,7 @@ function EnvironmentLedger({
338
360
  setSaveError(null);
339
361
  save(batch, {
340
362
  onError: (error) => {
363
+ forgetRefusal(batch);
341
364
  const left = error instanceof UnsavedEdits ? error.outcome : batch;
342
365
  setDrafts(left.drafts);
343
366
  setChanges(left.changes);
@@ -410,7 +433,7 @@ function EnvironmentLedger({
410
433
  : null;
411
434
 
412
435
  // Filtering narrows what is listed, never what is saved: a pending edit on
413
- // a row the filter hides still counts, and still shows in the save bar.
436
+ // a row the filter hides still counts, and still shows in the bar under the table.
414
437
  const needle = query.trim().toLowerCase();
415
438
  const listed = sortKeys(
416
439
  needle === '' ? active : active.filter((entry) => entry.key.toLowerCase().includes(needle)),
@@ -420,11 +443,7 @@ function EnvironmentLedger({
420
443
 
421
444
  return (
422
445
  <>
423
- <PageHeader
424
- tile={project}
425
- title={environment}
426
- aside={<EnvironmentName project={project} environment={environment} />}
427
- />
446
+ <PageHeader tile={project} title={environment} />
428
447
 
429
448
  {(active.length > 0 || drafts.length > 0) && (
430
449
  <div className="toolbar">
@@ -532,6 +551,7 @@ function EnvironmentLedger({
532
551
  status={state}
533
552
  // Not while its save is on its way.
534
553
  disabled={state.state === 'pending'}
554
+ onDismiss={dismiss}
535
555
  columns={columns}
536
556
  onEdit={() => setEditing((current) => new Set(current).add(entry.key))}
537
557
  onPatch={(patch) => patchChange(entry, patch)}
@@ -586,15 +606,33 @@ function EnvironmentLedger({
586
606
  </table>
587
607
  </div>
588
608
  )}
609
+ {pendingCount > 0 && (
610
+ <PendingBar
611
+ pending={pending}
612
+ ready={ready}
613
+ error={saveError ?? problem}
614
+ onDiscard={discardAll}
615
+ onSave={saveChanges}
616
+ />
617
+ )}
589
618
  </section>
590
619
 
591
620
  {canWrite && (
592
621
  <div className="table-actions">
593
- <button className="btn btn-primary" onClick={() => addDraft()}>
594
- <Plus size={14} />
595
- New secret
596
- </button>
622
+ <AddButton onAddSecret={() => addDraft()} onAddFolder={() => setAddingFolder(true)} canAddFolder={settled.length > 0} />
597
623
  {canReveal && <ImportEnv project={project} environment={environment} />}
624
+ <AddFolder
625
+ open={addingFolder}
626
+ onOpenChange={setAddingFolder}
627
+ keys={settled.map((entry) => entry.key)}
628
+ folders={folders}
629
+ onAdd={(folder, keys) => {
630
+ // As things stand on submit: a secret whose save started since the dialog opened is left out, not raced.
631
+ for (const entry of settled) {
632
+ if (keys.includes(entry.key) && entry.folder !== folder) move({ key: entry.key, folder });
633
+ }
634
+ }}
635
+ />
598
636
  </div>
599
637
  )}
600
638
 
@@ -654,56 +692,188 @@ function EnvironmentLedger({
654
692
  </Card>
655
693
  )}
656
694
 
657
- {pendingCount > 0 && (
658
- <div className="savebar" role="region" aria-label="Unsaved changes">
659
- <div className="savebar-inner">
660
- <span className="savebar-count">
661
- <span className="dot" aria-hidden />
662
- {pendingCount} unsaved change{pendingCount === 1 ? '' : 's'}
663
- </span>
664
- <span className="savebar-summary">
665
- {pending.slice(0, 3).map((item, index) => (
666
- <span key={`${item.key}:${index}`}>
667
- {index > 0 && ' · '}
668
- <span className="mono">{item.key}</span> {item.what}
669
- </span>
670
- ))}
671
- {pending.length > 3 && ` · and ${pending.length - 3} more`}
672
- </span>
673
- <div className="savebar-actions">
674
- <button className="btn btn-sm" onClick={discardAll}>
675
- Discard
676
- </button>
677
- <button
678
- className="btn btn-sm btn-primary"
679
- onClick={saveChanges}
680
- disabled={!ready}
681
- title="Save (⌘ Enter or Ctrl Enter)"
682
- aria-keyshortcuts="Meta+Enter Control+Enter"
683
- >
684
- Save {pendingCount === 1 ? 'change' : `${pendingCount} changes`}
685
- </button>
686
- </div>
687
- {(saveError ?? problem) !== null && (
688
- <p className="savebar-error" role="alert">
689
- <AlertCircle size={14} />
690
- <span>{saveError ?? problem}</span>
691
- </p>
692
- )}
693
- </div>
694
- </div>
695
- )}
696
695
  </>
697
696
  );
698
697
  }
699
698
 
700
- /** The display name sits beside the slug; it comes from the shell's project tree. */
701
- function EnvironmentName({ project, environment }: { project: string; environment: string }) {
702
- const { projects } = useShell();
703
- const name = projects
704
- .find((entry) => entry.slug === project)
705
- ?.environments.find((entry) => entry.slug === environment)?.name;
706
- return name === undefined ? null : <>{name}</>;
699
+ /**
700
+ * The pending edits, at the foot of the table they are made in: what they
701
+ * are, Discard and Save. It sticks to the bottom of the window while the
702
+ * table runs past it, so Save stays in reach of any row.
703
+ */
704
+ function PendingBar({
705
+ pending,
706
+ ready,
707
+ error,
708
+ onDiscard,
709
+ onSave,
710
+ }: {
711
+ pending: Pending[];
712
+ ready: boolean;
713
+ /** Why the last save failed, or why this one cannot go yet. */
714
+ error: string | null;
715
+ onDiscard: () => void;
716
+ onSave: () => void;
717
+ }) {
718
+ const count = pending.length;
719
+ return (
720
+ <div className="pending-bar" role="region" aria-label="Unsaved changes">
721
+ <span className="pending-count">
722
+ <span className="dot" aria-hidden />
723
+ {count} unsaved change{count === 1 ? '' : 's'}
724
+ </span>
725
+ <span className="pending-summary">
726
+ {pending.slice(0, 3).map((item, index) => (
727
+ <span key={`${item.key}:${index}`}>
728
+ {index > 0 && ' · '}
729
+ <span className="mono">{item.key}</span> {item.what}
730
+ </span>
731
+ ))}
732
+ {count > 3 && ` · and ${count - 3} more`}
733
+ </span>
734
+ <div className="pending-actions">
735
+ <button className="btn btn-sm" onClick={onDiscard}>
736
+ Discard
737
+ </button>
738
+ <button
739
+ className="btn btn-sm btn-primary"
740
+ onClick={onSave}
741
+ disabled={!ready}
742
+ title="Save (⌘ Enter or Ctrl Enter)"
743
+ aria-keyshortcuts="Meta+Enter Control+Enter"
744
+ >
745
+ Save {count === 1 ? 'change' : `${count} changes`}
746
+ </button>
747
+ </div>
748
+ {error !== null && (
749
+ <p className="pending-error" role="alert">
750
+ <AlertCircle size={14} />
751
+ <span>{error}</span>
752
+ </p>
753
+ )}
754
+ </div>
755
+ );
756
+ }
757
+
758
+ /**
759
+ * Add secret, and beside it a menu of the other things to add: a folder.
760
+ * One button in look, two to the keyboard and to a screen reader, the
761
+ * second a menu button.
762
+ */
763
+ function AddButton({
764
+ onAddSecret,
765
+ onAddFolder,
766
+ canAddFolder,
767
+ }: {
768
+ onAddSecret: () => void;
769
+ onAddFolder: () => void;
770
+ /** Whether there is a secret to file in a new folder. */
771
+ canAddFolder: boolean;
772
+ }) {
773
+ return (
774
+ <div className="split-button">
775
+ <button className="btn btn-primary" onClick={onAddSecret}>
776
+ <Plus size={14} />
777
+ Add secret
778
+ </button>
779
+ <Menu.Root>
780
+ <Menu.Trigger className="btn btn-primary btn-icon" aria-label="More to add">
781
+ <ChevronDown size={14} />
782
+ </Menu.Trigger>
783
+ <MenuPopup align="start">
784
+ <Menu.Item className="menu-item" onClick={onAddFolder} disabled={!canAddFolder}>
785
+ <Folder size={14} />
786
+ Add folder…
787
+ {!canAddFolder && <span className="menu-hint">after a secret</span>}
788
+ </Menu.Item>
789
+ </MenuPopup>
790
+ </Menu.Root>
791
+ </div>
792
+ );
793
+ }
794
+
795
+ /**
796
+ * A new folder, and the secrets filed in it. A folder is a name on what it
797
+ * holds (docs/design/environments.md), so it is made with its first
798
+ * secrets: one with nothing in it would not be there to see.
799
+ */
800
+ function AddFolder({
801
+ open,
802
+ onOpenChange,
803
+ keys,
804
+ folders,
805
+ onAdd,
806
+ }: {
807
+ open: boolean;
808
+ onOpenChange: (open: boolean) => void;
809
+ /** The secrets that can be filed, by name. */
810
+ keys: readonly string[];
811
+ /** The folders in use, which a name already in use joins. */
812
+ folders: readonly string[];
813
+ onAdd: (folder: string, keys: string[]) => void;
814
+ }) {
815
+ const [name, setName] = useState('');
816
+ const [chosen, setChosen] = useState<string[]>([]);
817
+ useEffect(() => {
818
+ if (!open) return;
819
+ setName('');
820
+ setChosen([]);
821
+ }, [open]);
822
+ const problem = folderProblem(name);
823
+ const joins = folders.includes(name);
824
+ const ready = name !== '' && problem === null && chosen.length > 0;
825
+
826
+ return (
827
+ <Modal
828
+ open={open}
829
+ onOpenChange={onOpenChange}
830
+ title="Add a folder"
831
+ description="Folders only arrange the list: names, values and access stay as they are."
832
+ >
833
+ <form
834
+ className="form"
835
+ onSubmit={(event) => {
836
+ event.preventDefault();
837
+ if (!ready) return;
838
+ onAdd(name, chosen);
839
+ onOpenChange(false);
840
+ }}
841
+ >
842
+ <label className="field">
843
+ <span className="label">Name</span>
844
+ <input
845
+ className="input"
846
+ autoFocus
847
+ spellCheck={false}
848
+ autoComplete="off"
849
+ value={name}
850
+ aria-invalid={problem !== null}
851
+ onChange={(event) => setName(event.target.value)}
852
+ />
853
+ <span className={`hint${problem !== null ? ' edit-note-error' : ''}`}>
854
+ {problem ?? (joins ? `${name} is in use: the secrets join it.` : 'One level: no slash.')}
855
+ </span>
856
+ </label>
857
+ <MultiCombobox
858
+ label="Secrets in it"
859
+ options={keys}
860
+ value={chosen}
861
+ onChange={setChosen}
862
+ placeholder="Pick one or more…"
863
+ hint="A folder holds at least one secret."
864
+ mono
865
+ />
866
+ <div className="dialog-actions">
867
+ <button className="btn" type="button" onClick={() => onOpenChange(false)}>
868
+ Cancel
869
+ </button>
870
+ <button className="btn btn-primary" type="submit" disabled={!ready}>
871
+ Add folder
872
+ </button>
873
+ </div>
874
+ </form>
875
+ </Modal>
876
+ );
707
877
  }
708
878
 
709
879
  /* -------------------------------------------------------------------------- */
@@ -747,8 +917,16 @@ function ValueField({
747
917
  // the end of the edit: taking its last line break out moves no focus.
748
918
  const [lines, setLines] = useState(() => start.includes('\n') || value.includes('\n'));
749
919
  if (!lines && value.includes('\n')) setLines(true);
750
- // Where the caret goes in the textarea a paste opened.
920
+ // Where the caret goes in the textarea a paste or a typed line break opened.
751
921
  const caret = useRef<number | null>(null);
922
+ // Text goes into the value of the single-line field in place of its
923
+ // selection, and the field turns into a textarea, focused, its caret after it.
924
+ const insert = (text: string, field: HTMLInputElement) => {
925
+ const from = field.selectionStart ?? value.length;
926
+ const to = field.selectionEnd ?? from;
927
+ caret.current = from + text.length;
928
+ onChange(value.slice(0, from) + text + value.slice(to));
929
+ };
752
930
  const field = {
753
931
  className: 'input input-mono',
754
932
  masked: !shown,
@@ -789,11 +967,16 @@ function ValueField({
789
967
  const pasted = event.clipboardData.getData('text/plain');
790
968
  if (!/[\r\n]/.test(pasted)) return;
791
969
  event.preventDefault();
792
- const text = pasted.replace(/\r\n?/g, '\n');
793
- const from = event.currentTarget.selectionStart ?? value.length;
794
- const to = event.currentTarget.selectionEnd ?? from;
795
- caret.current = from + text.length;
796
- onChange(value.slice(0, from) + text + value.slice(to));
970
+ insert(pasted.replace(/\r\n?/g, '\n'), event.currentTarget);
971
+ }}
972
+ // Shift+Enter types a line break, the way a textarea's Enter does.
973
+ // Enter alone stays as it was, and so does Cmd/Ctrl+Enter, which saves,
974
+ // and so does Shift+Enter that confirms text an input method is composing.
975
+ onKeyDown={(event) => {
976
+ if (event.key === 'Enter' && event.shiftKey && !event.metaKey && !event.ctrlKey && !event.nativeEvent.isComposing) {
977
+ event.preventDefault();
978
+ insert('\n', event.currentTarget);
979
+ } else field.onKeyDown(event);
797
980
  }}
798
981
  />
799
982
  )}
@@ -878,6 +1061,7 @@ function SecretRow({
878
1061
  environments,
879
1062
  status,
880
1063
  disabled,
1064
+ onDismiss,
881
1065
  columns,
882
1066
  onEdit,
883
1067
  onPatch,
@@ -907,6 +1091,8 @@ function SecretRow({
907
1091
  /** A save of this row on its way, or refused. */
908
1092
  status: ItemStatus;
909
1093
  disabled: boolean;
1094
+ /** Forget a refused change once its row has said so. */
1095
+ onDismiss: (mutationId: number) => void;
910
1096
  columns: number;
911
1097
  onEdit: () => void;
912
1098
  onPatch: (patch: Partial<SecretChange>) => void;
@@ -918,9 +1104,10 @@ function SecretRow({
918
1104
  saveReady: boolean;
919
1105
  onMarkArchive: () => void;
920
1106
  }) {
921
- const [reveal, setReveal] = useState<Reveal | null>(null);
1107
+ const [reads, dispatch] = useReducer(rowReads, noReads);
1108
+ const { reveal, revealing, error, copyError } = reads;
1109
+ const setReveal = (next: Reveal | null) => dispatch({ type: 'set-reveal', reveal: next });
922
1110
  const coffre = useCoffre();
923
- const [revealing, setRevealing] = useState(false);
924
1111
  const [historyOpen, setHistoryOpen] = useState(false);
925
1112
  const [moving, setMoving] = useState(false);
926
1113
  const [referring, setReferring] = useState(false);
@@ -935,7 +1122,6 @@ function SecretRow({
935
1122
  // What a reveal shows: its own version, or, as a reference, its source's.
936
1123
  const readVersion = reference === null ? entry.version : reference.version;
937
1124
  const holderPath = `${project}/${environment}/${entry.key}`;
938
- const [error, setError] = useState<string | null>(null);
939
1125
  // The current value, loaded on request as the starting point for an edit.
940
1126
  // It is not a change until it is edited: saving it untouched would append a
941
1127
  // version identical to the one it came from.
@@ -965,30 +1151,64 @@ function SecretRow({
965
1151
 
966
1152
  async function readValue({ show = true } = {}): Promise<string | null> {
967
1153
  if (shown !== null) return shown.value;
968
- setRevealing(true);
1154
+ dispatch({ type: 'read-started' });
969
1155
  try {
970
- const { values } = await coffre.secrets.reveal(`${project}/${environment}/${entry.key}`);
971
- const value = values[entry.key];
972
- setError(null);
973
- if (show) setReveal({ value, version: readVersion, at: Date.now() });
1156
+ const value = await fetchValue();
1157
+ dispatch({
1158
+ type: 'read-succeeded',
1159
+ reveal: show ? { value, version: readVersion, at: Date.now() } : null,
1160
+ });
974
1161
  return value;
975
1162
  } catch (failure) {
976
- setError(
977
- failure instanceof CoffreError
978
- ? failureMessage(failure)
979
- : 'The request could not be sent. Nothing was read.',
980
- );
1163
+ dispatch({ type: 'read-failed', message: readFailureMessage(failure) });
981
1164
  return null;
982
- } finally {
983
- setRevealing(false);
984
1165
  }
985
1166
  }
986
1167
 
1168
+ async function fetchValue(): Promise<string> {
1169
+ const { values } = await coffre.secrets.reveal(`${project}/${environment}/${entry.key}`);
1170
+ return values[entry.key];
1171
+ }
1172
+
987
1173
  function toggleReveal() {
988
1174
  if (shown !== null) setReveal(null);
989
1175
  else void readValue();
990
1176
  }
991
1177
 
1178
+ // Copy reads a hidden value the way Reveal does (the same audited read) and hands
1179
+ // it to the clipboard, never to the screen or to the row's reveal state: it shares
1180
+ // nothing with Reveal but the endpoint, so neither can change whether a value is
1181
+ // shown or Hide can be pressed. Copies do not lock each other out; the latest one
1182
+ // wins. The row holds the copier, which a remount of the button does not reset,
1183
+ // and only the latest copy may set `copyError` or the button's feedback.
1184
+ const [copier] = useState(() => createCopier());
1185
+ function copyValue() {
1186
+ dispatch({ type: 'copy-started' });
1187
+ // What a failed read said, if the read is what failed rather than the clipboard.
1188
+ const read: { failed: boolean; failure?: unknown } = { failed: false };
1189
+ const text =
1190
+ shown !== null
1191
+ ? shown.value
1192
+ : fetchValue().catch((failure: unknown) => {
1193
+ read.failed = true;
1194
+ read.failure = failure;
1195
+ throw failure;
1196
+ });
1197
+ void copier.run(text).then((result) => {
1198
+ if (result.outcome === 'superseded') return;
1199
+ dispatch(
1200
+ result.outcome === 'copied'
1201
+ ? { type: 'copy-succeeded' }
1202
+ : {
1203
+ type: 'copy-failed',
1204
+ message: read.failed
1205
+ ? readFailureMessage(read.failure)
1206
+ : 'The browser did not allow copying to the clipboard. Reveal the value and copy it by hand.',
1207
+ },
1208
+ );
1209
+ });
1210
+ }
1211
+
992
1212
  // An edit starts from the current value, read the way Reveal reads it, so
993
1213
  // the audit log shows who opened it. One that cannot be read starts empty.
994
1214
  const [opening, setOpening] = useState(false);
@@ -1149,16 +1369,17 @@ function SecretRow({
1149
1369
  </>
1150
1370
  ) : (
1151
1371
  <>
1152
- {/* Copy comes in to the left, so Hide stays where Reveal was clicked. */}
1153
- {shown !== null && (
1154
- <CopyButton variant="act" value={shown.value} label={`Copy ${entry.key}`} />
1155
- )}
1372
+ {/* Copy sits left of Reveal, hidden or shown, so Hide stays where
1373
+ Reveal was clicked. Hidden, it copies without showing the value;
1374
+ as for Reveal, it takes secret.read, and a reference copies the
1375
+ value it reads through. */}
1156
1376
  <SecretReadOnly canReveal={canReveal}>
1377
+ <CopyButton variant="act" copier={copier} onCopy={copyValue} label={`Copy ${entry.key}`} />
1157
1378
  <Tip label={shown === null ? 'Reveal' : 'Hide'}>
1158
1379
  <button
1159
1380
  className="act act-icon act-accent"
1160
1381
  onClick={toggleReveal}
1161
- disabled={revealing}
1382
+ disabled={revealToggleDisabled(reads, shown)}
1162
1383
  aria-label={`${shown === null ? 'Reveal' : 'Hide'} ${entry.key}`}
1163
1384
  >
1164
1385
  {revealing && !opening ? (
@@ -1358,13 +1579,21 @@ function SecretRow({
1358
1579
  </tr>
1359
1580
  )}
1360
1581
 
1361
- {(error ?? actError) !== null && (
1582
+ {(error ?? actError) !== null || copyError !== null ? (
1362
1583
  <tr className="row-error">
1363
1584
  <td colSpan={columns}>
1364
- <ErrorLine error={(error ?? actError)!} />
1585
+ {/* Reveal's refusal and Copy's are independent: neither hides the other. */}
1586
+ <ErrorLine error={error ?? actError} />
1587
+ <ErrorLine error={copyError} />
1365
1588
  </td>
1366
1589
  </tr>
1367
- )}
1590
+ ) : null}
1591
+
1592
+ <RowFailure
1593
+ status={status}
1594
+ columns={columns}
1595
+ onDismiss={() => status.state === 'failed' && onDismiss(status.mutationId)}
1596
+ />
1368
1597
  </>
1369
1598
  );
1370
1599
  }
@@ -1492,7 +1721,7 @@ function DraftRow({
1492
1721
  <input
1493
1722
  className="input input-mono"
1494
1723
  // Only the row that just mounted takes focus, which is the one the
1495
- // New secret button created.
1724
+ // Add secret button created.
1496
1725
  autoFocus
1497
1726
  aria-label="Name of the new secret"
1498
1727
  aria-invalid={keyProblem !== null}