@bevel-software/platform-core-frontend 0.22.0 → 0.24.0

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 (45) hide show
  1. package/package.json +2 -2
  2. package/src/core/CoreAppShell.tsx +2 -0
  3. package/src/core/registry.ts +83 -0
  4. package/src/lib/api.ts +49 -0
  5. package/src/modules/access/api.ts +6 -4
  6. package/src/modules/admin/__tests__/UserAccountsPage.test.tsx +89 -1
  7. package/src/modules/admin/components/UserAccountsPage.tsx +93 -5
  8. package/src/modules/auth/components/LoginScreen.tsx +3 -0
  9. package/src/modules/auth/services/account.api.ts +26 -3
  10. package/src/modules/change-requests/components/BranchFilePreview.tsx +7 -1
  11. package/src/modules/git/__tests__/FileHistoryPanel.test.tsx +89 -10
  12. package/src/modules/git/__tests__/HistoryVersionPreview.test.tsx +479 -0
  13. package/src/modules/git/components/FileHistoryPanel.tsx +52 -65
  14. package/src/modules/git/components/HistoryVersionPreview.tsx +410 -0
  15. package/src/modules/layout/__tests__/ReadOnlyBanner.test.tsx +157 -0
  16. package/src/modules/layout/components/ReadOnlyBanner.tsx +96 -0
  17. package/src/modules/setup/__tests__/setup.repository-change.test.tsx +296 -0
  18. package/src/modules/setup/__tests__/setup.repository.test.tsx +114 -24
  19. package/src/modules/setup/__tests__/setup.test.tsx +5 -3
  20. package/src/modules/setup/components/SetupScreen.tsx +187 -46
  21. package/src/modules/setup/services/setup.api.ts +78 -3
  22. package/src/modules/workspace/components/FileExplorer.tsx +140 -12
  23. package/src/modules/workspace/components/FileViewer.tsx +11 -1
  24. package/src/modules/workspace/components/TreeActionConfirm.tsx +5 -7
  25. package/src/modules/workspace/components/__tests__/FileExplorer.test.tsx +603 -29
  26. package/src/modules/workspace/components/renderers/DocxRenderer.tsx +23 -6
  27. package/src/modules/workspace/components/renderers/DownloadFileButton.tsx +41 -8
  28. package/src/modules/workspace/components/renderers/EmailRenderer.tsx +20 -5
  29. package/src/modules/workspace/components/renderers/ImageRenderer.tsx +39 -16
  30. package/src/modules/workspace/components/renderers/PdfRenderer.tsx +27 -7
  31. package/src/modules/workspace/components/renderers/PptxRenderer.tsx +20 -5
  32. package/src/modules/workspace/components/renderers/RetryReadButton.tsx +37 -0
  33. package/src/modules/workspace/components/renderers/XlsxRenderer.tsx +20 -5
  34. package/src/modules/workspace/components/renderers/__tests__/htmlSandbox.test.ts +186 -7
  35. package/src/modules/workspace/components/renderers/__tests__/readPane.test.tsx +59 -0
  36. package/src/modules/workspace/components/renderers/htmlSandbox.ts +80 -20
  37. package/src/modules/workspace/components/renderers/index.ts +6 -1
  38. package/src/modules/workspace/components/renderers/readPane.ts +22 -0
  39. package/src/modules/workspace/components/renderers/rendererWorkspace.ts +50 -9
  40. package/src/modules/workspace/components/renderers/useReadRetry.ts +27 -0
  41. package/src/modules/workspace/routing/__tests__/kb-routes.test.tsx +79 -0
  42. package/src/modules/workspace/routing/kb-routes.ts +25 -10
  43. package/src/modules/workspace/services/workspace.api.ts +22 -1
  44. package/src/shared/markdown/__tests__/hrefs.test.ts +111 -0
  45. package/src/shared/markdown/hrefs.ts +80 -4
@@ -118,6 +118,50 @@ export interface SetupStatus {
118
118
  repository?: RepositoryStatus;
119
119
  }
120
120
 
121
+ /**
122
+ * What the admin must decide before a save moves the deployment to another
123
+ * repository: `keep` — it only moved, so the open change requests still mean
124
+ * something — or `close` — it was replaced, so they are closed as "repository
125
+ * replaced". Nothing is deleted either way.
126
+ */
127
+ export type RepositoryChangeChoice = 'keep' | 'close';
128
+
129
+ /**
130
+ * The server refused the save until the move to another repository is
131
+ * confirmed (409). The one question every move is asked: another address,
132
+ * another repository on GitHub, another way of having one.
133
+ *
134
+ * Not an error to show as one: nothing was saved, nothing was destroyed, and
135
+ * the answer is a decision only the admin can make. `openChangeRequests` is
136
+ * the count the choice is about, read at the moment of the refusal. `from`
137
+ * and `to` are the way left and the way moved to: equal for a move within
138
+ * one way, absent from a server that knows one way only.
139
+ */
140
+ export class RepositoryChangeNeedsConfirmation extends Error {
141
+ readonly openChangeRequests: number;
142
+ readonly from?: GitMode;
143
+ readonly to?: GitMode;
144
+
145
+ constructor(openChangeRequests: number, from?: GitMode, to?: GitMode) {
146
+ super('This moves the deployment to another repository.');
147
+ this.name = 'RepositoryChangeNeedsConfirmation';
148
+ this.openChangeRequests = openChangeRequests;
149
+ this.from = from;
150
+ this.to = to;
151
+ }
152
+ }
153
+
154
+ /** What a save that changed the repository did about the open change requests. */
155
+ export interface RepositoryChangeResult {
156
+ choice: RepositoryChangeChoice | null;
157
+ /**
158
+ * How many were closed as "repository replaced". `keep` answers 0. A close
159
+ * that could not be done refuses the whole save, so this never reports on
160
+ * requests that are still open.
161
+ */
162
+ closedChangeRequests: number;
163
+ }
164
+
121
165
  export interface SaveResult {
122
166
  restartRequired: boolean;
123
167
  complete: boolean;
@@ -125,6 +169,8 @@ export interface SaveResult {
125
169
  settings: SettingStatus[];
126
170
  oidcVerification?: OidcVerification;
127
171
  repository?: RepositoryStatus;
172
+ /** Only on the save that changed the knowledge-base repository. */
173
+ repositoryChange?: RepositoryChangeResult;
128
174
  }
129
175
 
130
176
  /** Field-keyed messages, so the form can mark the input that was wrong. */
@@ -162,9 +208,21 @@ async function readError(res: Response): Promise<never> {
162
208
  } catch {
163
209
  throw new Error(`Request failed (${res.status})`);
164
210
  }
165
- const data = body as { error?: string; problems?: Record<string, string>; kbInit?: KbInitFailure };
211
+ const data = body as {
212
+ error?: string;
213
+ problems?: Record<string, string>;
214
+ kbInit?: KbInitFailure;
215
+ repositoryChange?: { openChangeRequests?: number; from?: GitMode; to?: GitMode };
216
+ };
166
217
  if (data.problems) throw new SettingsProblems(data.problems);
167
218
  if (data.kbInit) throw new KbInitFailed(data.kbInit);
219
+ // A save REFUSED until the repository change is confirmed. Checked before
220
+ // the generic throw so the form gets the decision to put to the admin, not
221
+ // a sentence in a red box that nothing can be done about.
222
+ if (res.status === 409 && data.repositoryChange) {
223
+ const { openChangeRequests, from, to } = data.repositoryChange;
224
+ throw new RepositoryChangeNeedsConfirmation(openChangeRequests ?? 0, from, to);
225
+ }
168
226
  throw new Error(data.error || `Request failed (${res.status})`);
169
227
  }
170
228
 
@@ -224,11 +282,28 @@ export async function fetchSetupStatus(): Promise<SetupStatus> {
224
282
  return (await res.json()) as SetupStatus;
225
283
  }
226
284
 
227
- export async function saveSettings(settings: Record<string, string>): Promise<SaveResult> {
285
+ /**
286
+ * Store the settings. `confirmRepositoryChange` carries the admin's decision
287
+ * about a change of the knowledge-base repository — without it the server
288
+ * refuses such a save (409), which arrives as
289
+ * {@link RepositoryChangeNeedsConfirmation} rather than as an error.
290
+ */
291
+ export async function saveSettings(
292
+ settings: Record<string, string>,
293
+ confirmRepositoryChange?: RepositoryChangeChoice,
294
+ /**
295
+ * How many open change requests the question showed when it was answered.
296
+ * The server asks again when the count has changed since, so a request
297
+ * opened while the question stood is not decided unasked.
298
+ */
299
+ seenOpenChangeRequests?: number,
300
+ ): Promise<SaveResult> {
228
301
  const res = await authFetch('/api/setup/settings', {
229
302
  method: 'POST',
230
303
  headers: { 'Content-Type': 'application/json' },
231
- body: JSON.stringify({ settings }),
304
+ body: JSON.stringify(
305
+ confirmRepositoryChange ? { settings, confirmRepositoryChange, seenOpenChangeRequests } : { settings },
306
+ ),
232
307
  });
233
308
  if (!res.ok) await readError(res);
234
309
  return (await res.json()) as SaveResult;
@@ -74,7 +74,12 @@ import { useOpenChangeRequests } from '../hooks/useOpenChangeRequests';
74
74
  import { AdminContext } from '../../admin/state/admin.context';
75
75
  import { ManageAccessDialog } from '../../access/components/ManageAccessDialog';
76
76
  import { offersManageAccess } from '../../access/manage-access-affordance';
77
- import { useAppRegistry } from '../../../core/registry';
77
+ import {
78
+ useAppRegistry,
79
+ type FolderMenuContext,
80
+ type FolderMenuItemDef,
81
+ type FolderMenuTools,
82
+ } from '../../../core/registry';
78
83
  import { fetchFileAccess, fetchProspectiveAccess } from '../../access/api';
79
84
  import {
80
85
  TreeActionConfirmDialog,
@@ -442,7 +447,16 @@ function ContextMenu({
442
447
  /** The row this menu was opened from — Escape hands focus back to it. */
443
448
  returnFocusTo?: React.RefObject<HTMLElement | null>;
444
449
  }) {
445
- const { deleteEntry, unzipHere, kbDirName, fileTree } = useWorkspace();
450
+ const {
451
+ deleteEntry,
452
+ unzipHere,
453
+ kbDirName,
454
+ fileTree,
455
+ createFile,
456
+ createDirectory,
457
+ refreshFileTree,
458
+ workspaceBranch,
459
+ } = useWorkspace();
446
460
  const suggestions = useSuggestions();
447
461
  const { isPinned, togglePin, available: pinning } = usePinned();
448
462
  const openManageAccess = useManageAccess();
@@ -463,6 +477,105 @@ function ContextMenu({
463
477
  // folder that `Manage access` row is the product's only route to it.
464
478
  const pos = usePointerMenuPosition(ref, x, y);
465
479
 
480
+ // ── The deployment's own folder entries ──
481
+ //
482
+ // Core registers none (see `FolderMenuItemDef`), so on a core deployment
483
+ // every line below collapses to nothing: no predicate runs, no write lookup
484
+ // is spent, no separator is drawn, and this menu is the menu it has always
485
+ // been. Only a folder's menu offers them, and only a folder that exists on
486
+ // this branch — a proposed row's folder is on a change request's branch,
487
+ // where nothing here could create anything.
488
+ const { folderMenuItems } = useAppRegistry();
489
+ const { open: openPath } = useTreeNav();
490
+ const offersRegistered = entry.type === 'directory' && !proposed && folderMenuItems.length > 0;
491
+ // Answered by the hook the tree's own write hints use, so an entry is told
492
+ // the same thing about this folder that the rest of the explorer believes.
493
+ // It short-circuits outside the repository and on an unprotected branch, so
494
+ // the lookup costs a request only where the answer can actually be "no".
495
+ const folderCanWrite = useCanWriteFolder(offersRegistered ? entry.relativePath : null);
496
+ // The branch the workspace IS, not the one a route may be navigating to —
497
+ // these rows are the workspace's, so an entry is told where they came from.
498
+ const branch = workspaceBranch ?? '';
499
+ const folder: FolderMenuContext = useMemo(
500
+ () => ({
501
+ path: entry.relativePath,
502
+ branch,
503
+ canWrite: folderCanWrite,
504
+ branchProtected: branch !== '' && isProtectedBranch(currentBranchModel(), branch),
505
+ }),
506
+ [entry.relativePath, branch, folderCanWrite],
507
+ );
508
+ const { registeredItems, predicateFailures } = useMemo(() => {
509
+ // One deployment entry's broken predicate must not cost the viewer the
510
+ // whole menu — Delete and Manage access included. It is left out here and
511
+ // said out loud below; the others are asked anyway.
512
+ const failures: { id: string; err: unknown }[] = [];
513
+ const items = offersRegistered
514
+ ? folderMenuItems.filter((item) => {
515
+ try {
516
+ return item.appliesTo(folder);
517
+ } catch (err) {
518
+ failures.push({ id: item.id, err });
519
+ return false;
520
+ }
521
+ })
522
+ : [];
523
+ return { registeredItems: items, predicateFailures: failures };
524
+ }, [offersRegistered, folderMenuItems, folder]);
525
+
526
+ // The failure is collected above and reported HERE, because a `console`
527
+ // line is a side effect and the memo above must stay a pure computation: it
528
+ // runs again on every render whose inputs moved — the `folderCanWrite`
529
+ // lookup resolving, a tree refresh arriving — and twice over in StrictMode,
530
+ // and none of those is a second thing going wrong. The ids already reported
531
+ // are remembered for the life of this menu, and this component mounts fresh
532
+ // on every open, so a broken entry costs exactly one line per menu opened.
533
+ const reportedFailures = useRef<Set<string>>(new Set());
534
+ useEffect(() => {
535
+ for (const { id, err } of predicateFailures) {
536
+ if (reportedFailures.current.has(id)) continue;
537
+ reportedFailures.current.add(id);
538
+ console.error(`Folder menu entry "${id}" failed appliesTo:`, err);
539
+ }
540
+ }, [predicateFailures]);
541
+
542
+ /**
543
+ * Run a registered entry. It creates nothing itself: the tools below are the
544
+ * workspace's own calls, the same ones "New file" and "New folder" make, so
545
+ * the access rules, the platform-file rules and the protected-branch rules
546
+ * reach it unchanged and a refusal arrives as a rejection from the route.
547
+ *
548
+ * Whatever it leaves unhandled — a throw, a rejection, or its own
549
+ * `showError` — is reported the way a refused "New folder" is reported, by
550
+ * the same `alert`.
551
+ */
552
+ const runRegistered = (item: FolderMenuItemDef) => {
553
+ // Closed BEFORE the action runs, for the reason the inline create input is
554
+ // unmounted before its create can fail: the alert steals focus, and
555
+ // dismissing it over a still-open menu would read as a click outside.
556
+ onClose();
557
+ const showError = (message: string) => {
558
+ alert(`${item.label} failed:\n${message}`);
559
+ };
560
+ const tools: FolderMenuTools = {
561
+ createFolder: (path) => createDirectory(path),
562
+ createFile: (path, content) => createFile(path, content),
563
+ refreshTree: async () => {
564
+ await refreshFileTree();
565
+ },
566
+ openPath,
567
+ showError,
568
+ };
569
+ void (async () => {
570
+ try {
571
+ await item.run(folder, tools);
572
+ } catch (err) {
573
+ console.error(`Folder menu entry "${item.id}" failed:`, err);
574
+ showError(err instanceof Error ? err.message : String(err));
575
+ }
576
+ })();
577
+ };
578
+
466
579
  // Only files whose name ends with `.zip` (case-insensitive) get the
467
580
  // extraction affordance — matches the OS shell-extension behavior users
468
581
  // already know from Windows Explorer / macOS Finder.
@@ -698,6 +811,26 @@ function ContextMenu({
698
811
  <span className="flex items-center gap-2"><Undo2 size={14} />Withdraw suggestion</span>
699
812
  </MenuItem>
700
813
  )}
814
+ {registeredItems.length > 0 && (
815
+ // The deployment's verbs, last and behind a separator: they are
816
+ // additions to this tree's vocabulary rather than part of it, and the
817
+ // rule holds in the other direction too — with none registered there
818
+ // is no separator to explain. Ordinary `MenuItem` buttons, so Tab
819
+ // reaches them and Enter runs them exactly as for `New folder`.
820
+ <>
821
+ <div className="my-1 border-t border-line" data-testid="folder-menu-registered-separator" />
822
+ {registeredItems.map((item) => (
823
+ <MenuItem
824
+ key={item.id}
825
+ role="menuitem"
826
+ data-folder-menu-item={item.id}
827
+ onClick={() => runRegistered(item)}
828
+ >
829
+ <span className="flex items-center gap-2">{item.icon}{item.label}</span>
830
+ </MenuItem>
831
+ ))}
832
+ </>
833
+ )}
701
834
  </MenuPanel>
702
835
  </div>
703
836
  );
@@ -888,12 +1021,6 @@ function RowNotice({
888
1021
  // ── Tree Node ──
889
1022
 
890
1023
  const DRAG_MIME = 'application/x-workspace-path';
891
- /**
892
- * What kind of row is being dragged — `directory` or `file`. The path alone
893
- * does not say (a folder may be named like a file), and the move dialog asks
894
- * a file-only access question, so the kind travels with the path.
895
- */
896
- const DRAG_KIND_MIME = 'application/x-workspace-kind';
897
1024
 
898
1025
  export function FileTreeNode({
899
1026
  entry,
@@ -1175,10 +1302,9 @@ export function FileTreeNode({
1175
1302
  const handleDragStart = useCallback((e: React.DragEvent) => {
1176
1303
  if (isRoot || reserved || dragRefusal) { e.preventDefault(); return; }
1177
1304
  e.dataTransfer.setData(DRAG_MIME, entry.relativePath);
1178
- e.dataTransfer.setData(DRAG_KIND_MIME, entry.type);
1179
1305
  e.dataTransfer.effectAllowed = 'move';
1180
1306
  setDragging(true);
1181
- }, [entry.relativePath, entry.type, isRoot, reserved, dragRefusal]);
1307
+ }, [entry.relativePath, isRoot, reserved, dragRefusal]);
1182
1308
 
1183
1309
  const handleDragEnd = useCallback(() => {
1184
1310
  setDragging(false);
@@ -1235,7 +1361,6 @@ export function FileTreeNode({
1235
1361
  confirm({
1236
1362
  kind: 'move',
1237
1363
  sourcePath,
1238
- sourceIsDirectory: e.dataTransfer.getData(DRAG_KIND_MIME) === 'directory',
1239
1364
  targetDir,
1240
1365
  // Named after the row that was dropped on, so a drop that resolved
1241
1366
  // to the clone's root still reads as "the top level".
@@ -1845,9 +1970,12 @@ export function TreeChrome({
1845
1970
  // nothing about access it cannot resolve. `kbDirName` alone is the KB root.
1846
1971
  const insideKb = (path: string) =>
1847
1972
  !!kbDirName && (path === kbDirName || path.startsWith(`${kbDirName}/`));
1973
+ // Folders are asked about as well as files. The rules a folder carries are
1974
+ // the `access.md` files inside it, and the resolver counts them at the
1975
+ // paths they land on — so a rename of a folder that grants its own access
1976
+ // answers "nothing changes", which is what happens.
1848
1977
  const accessLookup =
1849
1978
  moveRequest && workspaceId && kbDirName
1850
- && !moveRequest.sourceIsDirectory
1851
1979
  && moveRequest.sourcePath.startsWith(`${kbDirName}/`)
1852
1980
  && insideKb(moveRequest.targetDir)
1853
1981
  ? moveRequest
@@ -39,6 +39,7 @@ import { formatEligible } from '../../access/hooks/useFileAccess';
39
39
  import { PR_STALE_EVENT } from '../../../core/events';
40
40
  import { suggestedPages } from '../utils/fileTree';
41
41
  import { getFileRenderer, getRendererLayout, isViewOnlyFile } from './renderers';
42
+ import { READ_PANE } from './renderers/readPane';
42
43
  import { CanDownloadContext } from './renderers/DownloadFileButton';
43
44
  import type { RendererSaveState } from './renderers';
44
45
  import { KbDocumentShell } from './KbDocumentShell';
@@ -1427,7 +1428,16 @@ export function FileViewer() {
1427
1428
  around its files. One file-in-a-box drawing for the whole app;
1428
1429
  full-bleed renderers (pdf, csv, images…) are viewports, not
1429
1430
  documents, and keep their unframed definite-height contract. */}
1430
- <div className={shellVariant === 'full-bleed' ? 'flex min-h-0 flex-1 flex-col' : 'min-w-0'}>
1431
+ {/* `READ_PANE` — the file page's read region. A byte-reading viewer's
1432
+ "Try again" unmounts itself (the error block IS the renderer's whole
1433
+ output), so focus would fall to the body and the next Tab would
1434
+ restart at the top of the page. This wrapper stays mounted through
1435
+ every state the read goes through, prose and full-bleed alike, so
1436
+ it is what focus lands on. See `RetryReadButton`. */}
1437
+ <div
1438
+ {...READ_PANE}
1439
+ className={shellVariant === 'full-bleed' ? 'flex min-h-0 flex-1 flex-col' : 'min-w-0'}
1440
+ >
1431
1441
  {shellVariant === 'prose' ? (
1432
1442
  <>
1433
1443
  <FilePaneCard file={fileBaseName} actions={paneActions}>
@@ -62,15 +62,13 @@ export type TreeConfirmRequest =
62
62
  }
63
63
  | {
64
64
  kind: 'move';
65
- /** Workspace-relative path of the entry being moved. */
66
- sourcePath: string;
67
65
  /**
68
- * Is the thing being dragged a folder? A folder's access is its own
69
- * `access.md` plus every file under it — a different question from one
70
- * file's, and not one this dialog answers, so it asks nothing and says
71
- * only what it has always said.
66
+ * Workspace-relative path of the entry being moved. Its KIND is not
67
+ * part of the request any more: both kinds are asked the same question
68
+ * now, and the resolver — which reads the tree — is what knows whether
69
+ * the thing carries `access.md` files of its own.
72
70
  */
73
- sourceIsDirectory: boolean;
71
+ sourcePath: string;
74
72
  /** Workspace-relative folder it lands in; `''` is the workspace root. */
75
73
  targetDir: string;
76
74
  /** How the destination reads in the sentence — the drop target's row name. */