@bevel-software/platform-core-frontend 0.13.1 → 0.13.3

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bevel-software/platform-core-frontend",
3
- "version": "0.13.1",
3
+ "version": "0.13.3",
4
4
  "description": "Open-source core UI of the Bevel platform (raw TS/TSX source): workspace explorer/viewer, branches & change requests, Library, secrets, tools, access control.",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -45,7 +45,7 @@
45
45
  "tailwind-merge": "^3.5.0",
46
46
  "xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz",
47
47
  "yaml": "^2.9.0",
48
- "@bevel-software/platform-shared": "0.13.1"
48
+ "@bevel-software/platform-shared": "0.13.3"
49
49
  },
50
50
  "devDependencies": {
51
51
  "@testing-library/jest-dom": "^6.9.1",
@@ -240,9 +240,50 @@ function renderPage(
240
240
  library?: Partial<LibraryContextValue>,
241
241
  /** Props the canonical /workspace mount passes; the legacy route passes none. */
242
242
  pageProps?: { provisional?: boolean },
243
+ /** Git state — overridden to test what the page does when there is no log. */
244
+ gitValue: GitContextValue = git,
243
245
  ) {
244
246
  libraryMock.value = { ...libraryValue(owned, crs, mine), ...library };
245
- return render(
247
+ return render(harness(bus, gitValue, routerState, pageProps));
248
+ }
249
+
250
+ /**
251
+ * Wait for the page to stop loading before driving it.
252
+ *
253
+ * The reading pane is the LAST thing to arrive: it needs the skill detail
254
+ * (which is also what puts the second tab on screen) and then the file's bytes
255
+ * off the default branch. Waiting on a TAB instead can resolve earlier —
256
+ * `findByRole('tab', …)` is satisfied by the SKILL.md tab, which renders
257
+ * before either of those lands.
258
+ *
259
+ * Why the keyboard tests use it: `jumps to the first and last file with Home
260
+ * and End` was seen failing in full-suite runs on a loaded machine, never in
261
+ * isolation (0 in 20 runs). The cause was NOT established — a deliberately
262
+ * delayed detail load does not reproduce it, and the same runs on the
263
+ * unmodified file were too few to tell the two versions apart. What is certain
264
+ * is that both keyboard tests were driving the tablist while several requests
265
+ * were still in flight, and they are about arrow keys, not about loading. So
266
+ * they start from a settled page. If the flake outlives this, the cause is
267
+ * somewhere else and this at least stops the tablist tests from being where it
268
+ * is hunted.
269
+ */
270
+ async function settled() {
271
+ await screen.findByTestId('md-view');
272
+ }
273
+
274
+ /**
275
+ * The provider tree `renderPage` mounts, as a value — so a test can hand the
276
+ * SAME tree back to `rerender` with a different git state and watch the page
277
+ * react WITHOUT remounting it. Remounting would reset the very state
278
+ * (`historyOpen`) those tests are about, and pass whatever the page did.
279
+ */
280
+ function harness(
281
+ bus: EventBusContextValue,
282
+ gitValue: GitContextValue,
283
+ routerState?: Record<string, unknown>,
284
+ pageProps?: { provisional?: boolean },
285
+ ) {
286
+ return (
246
287
  <MemoryRouter
247
288
  initialEntries={[
248
289
  { pathname: '/skills-and-tools/skills/newsletter', state: routerState ?? null },
@@ -250,7 +291,7 @@ function renderPage(
250
291
  >
251
292
  <AuthContext.Provider value={auth}>
252
293
  <WorkspaceContext.Provider value={workspace}>
253
- <GitContext.Provider value={git}>
294
+ <GitContext.Provider value={gitValue}>
254
295
  <EventBusContext.Provider value={bus}>
255
296
  {/* The real toast provider: the success message IS the page's
256
297
  report that the merge landed, so a stubbed-out toast would
@@ -267,7 +308,7 @@ function renderPage(
267
308
  </GitContext.Provider>
268
309
  </WorkspaceContext.Provider>
269
310
  </AuthContext.Provider>
270
- </MemoryRouter>,
311
+ </MemoryRouter>
271
312
  );
272
313
  }
273
314
 
@@ -371,7 +412,8 @@ describe('SkillPage', () => {
371
412
  */
372
413
  it('moves selection AND focus with the arrow keys', async () => {
373
414
  renderPage(false);
374
- const skillTab = await screen.findByRole('tab', { name: /SKILL\.md/ });
415
+ await settled();
416
+ const skillTab = screen.getByRole('tab', { name: /SKILL\.md/ });
375
417
  const sourcesTab = screen.getByRole('tab', { name: /sources\.yaml/ });
376
418
 
377
419
  skillTab.focus();
@@ -387,7 +429,8 @@ describe('SkillPage', () => {
387
429
 
388
430
  it('jumps to the first and last file with Home and End', async () => {
389
431
  renderPage(false);
390
- const skillTab = await screen.findByRole('tab', { name: /SKILL\.md/ });
432
+ await settled();
433
+ const skillTab = screen.getByRole('tab', { name: /SKILL\.md/ });
391
434
  const sourcesTab = screen.getByRole('tab', { name: /sources\.yaml/ });
392
435
 
393
436
  skillTab.focus();
@@ -1123,4 +1166,165 @@ describe('SkillPage: deciding on a change', () => {
1123
1166
  fireEvent.click(withdraw);
1124
1167
  await waitFor(() => expect(apiMock.cancelPullRequest).toHaveBeenCalledWith(7));
1125
1168
  });
1169
+
1170
+ /**
1171
+ * A skill is a file in the repository, and this page is the ONLY surface it
1172
+ * has: the shell routes every default-branch `Plugins/` URL here
1173
+ * (`isLibraryLocation`) and the Knowledge tree does not list `Plugins/` at
1174
+ * all, so a `⋯` missing here means the git log for every skill in the
1175
+ * deployment is unreachable — the audit trail the product is sold on,
1176
+ * available for Knowledge pages and for nothing else.
1177
+ */
1178
+ describe('version history', () => {
1179
+ it('opens the log for the file on screen, at its workspace path', async () => {
1180
+ renderPage(false);
1181
+
1182
+ fireEvent.click(await screen.findByRole('button', { name: 'More actions' }));
1183
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Version history' }));
1184
+
1185
+ // The path the panel asks git about is the workspace-relative one the
1186
+ // Knowledge viewer would hand it — kbDirName included. Getting this
1187
+ // wrong asks about a file that does not exist and reports an empty
1188
+ // history for one that does.
1189
+ expect(
1190
+ await screen.findByText('Timeline: knowledge-base/Skills/newsletter/SKILL.md'),
1191
+ ).toBeInTheDocument();
1192
+ expect(screen.getByText('Version history: SKILL.md')).toBeInTheDocument();
1193
+
1194
+ // And there is a way back, because history is not in the URL.
1195
+ fireEvent.click(screen.getByRole('button', { name: 'Back to the file' }));
1196
+ expect(await screen.findByTestId('md-view')).toBeInTheDocument();
1197
+ });
1198
+
1199
+ it('does not follow you to another file of the skill', async () => {
1200
+ renderPage(false);
1201
+
1202
+ fireEvent.click(await screen.findByRole('button', { name: 'More actions' }));
1203
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Version history' }));
1204
+ await screen.findByText('Timeline: knowledge-base/Skills/newsletter/SKILL.md');
1205
+
1206
+ // A tab switch is a switch of file, and history is a lens on ONE file.
1207
+ // Carrying it across would show the previous file's log under the new
1208
+ // file's heading.
1209
+ fireEvent.click(screen.getByRole('tab', { name: 'sources.yaml' }));
1210
+ expect(screen.queryByText(/^Timeline:/)).toBeNull();
1211
+
1212
+ // And it does not come BACK on the way home. Keying the open flag to
1213
+ // the file it was opened for is not enough on its own: returning to
1214
+ // that tab then reopens a log nobody asked for a second time, which is
1215
+ // how you land on history when you meant to read the file.
1216
+ fireEvent.click(screen.getByRole('tab', { name: 'SKILL.md' }));
1217
+ expect(screen.queryByText(/^Timeline:/)).toBeNull();
1218
+ expect(await screen.findByTestId('md-view')).toBeInTheDocument();
1219
+ });
1220
+
1221
+ /**
1222
+ * `SkillFileEditor` holds the draft in its own state, so swapping it out
1223
+ * for the history panel throws away whatever was typed, with no warning
1224
+ * and no way back. The menu is withdrawn for exactly as long as that is
1225
+ * true.
1226
+ */
1227
+ it('is withdrawn while the editor is open, so a draft cannot be discarded', async () => {
1228
+ accessMock.result = {
1229
+ canWrite: true,
1230
+ eligible: { roles: [], users: [] },
1231
+ owners: { roles: [], users: [] },
1232
+ };
1233
+ renderPage(true);
1234
+
1235
+ fireEvent.click(await screen.findByRole('button', { name: 'Edit' }));
1236
+ await screen.findByRole('textbox', { name: /Edit SKILL\.md/ });
1237
+ expect(screen.queryByRole('button', { name: 'More actions' })).toBeNull();
1238
+
1239
+ // It comes back the moment the draft is gone.
1240
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
1241
+ expect(await screen.findByRole('button', { name: 'More actions' })).toBeInTheDocument();
1242
+ });
1243
+
1244
+ /**
1245
+ * `availability` is re-derived from a POLLED status call, so one failed
1246
+ * poll flips it to `error` and the next good one flips it back. If the
1247
+ * open flag survived that, the log would reappear over the file minutes
1248
+ * after the reader had gone back to reading.
1249
+ */
1250
+ it('closes for good when git stops answering mid-read', async () => {
1251
+ const bus = makeFakeBus();
1252
+ const { rerender } = renderPage(false, [], [], bus);
1253
+ fireEvent.click(await screen.findByRole('button', { name: 'More actions' }));
1254
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Version history' }));
1255
+ await screen.findByText(/^Timeline:/);
1256
+
1257
+ // A poll fails: the log goes away, and so does its trigger.
1258
+ rerender(harness(bus, { ...git, availability: 'error' } as GitContextValue));
1259
+ expect(screen.queryByText(/^Timeline:/)).toBeNull();
1260
+
1261
+ // The next poll succeeds. The file is still what is on screen.
1262
+ rerender(harness(bus, git));
1263
+ expect(await screen.findByTestId('md-view')).toBeInTheDocument();
1264
+ expect(screen.queryByText(/^Timeline:/)).toBeNull();
1265
+ expect(screen.getByRole('button', { name: 'More actions' })).toBeInTheDocument();
1266
+ });
1267
+
1268
+ /**
1269
+ * The MENU flag needs the same treatment as the log's, and it is a
1270
+ * separate flag: the trigger and its panel both live behind
1271
+ * `historyAvailable`, so an open menu unmounts with them and leaves its
1272
+ * flag set behind an element nobody can see. Found by cubic on #103.
1273
+ */
1274
+ it('does not spring the menu back open when git recovers', async () => {
1275
+ const bus = makeFakeBus();
1276
+ const { rerender } = renderPage(false, [], [], bus);
1277
+ const trigger = await screen.findByRole('button', { name: 'More actions' });
1278
+ fireEvent.click(trigger);
1279
+ expect(screen.getByRole('menuitem', { name: 'Version history' })).toBeInTheDocument();
1280
+
1281
+ // A poll fails while the menu is OPEN — trigger and panel go together.
1282
+ rerender(harness(bus, { ...git, availability: 'error' } as GitContextValue));
1283
+ expect(screen.queryByRole('button', { name: 'More actions' })).toBeNull();
1284
+
1285
+ // The next poll succeeds. The trigger is back, and it is CLOSED.
1286
+ rerender(harness(bus, git));
1287
+ const back = await screen.findByRole('button', { name: 'More actions' });
1288
+ expect(back).toHaveAttribute('aria-expanded', 'false');
1289
+ expect(screen.queryByRole('menuitem', { name: 'Version history' })).toBeNull();
1290
+ });
1291
+
1292
+ /**
1293
+ * `editing` is the same state by a second door, and it is reachable
1294
+ * without a mouse: `useDismissableMenu` dismisses on outside POINTERDOWN,
1295
+ * so tabbing from the open menu to Edit and pressing Enter never dismisses
1296
+ * it. Cancel then used to hand the menu back open over the file.
1297
+ */
1298
+ it('does not spring the menu back open when the editor closes', async () => {
1299
+ accessMock.result = {
1300
+ canWrite: true,
1301
+ eligible: { roles: [], users: [] },
1302
+ owners: { roles: [], users: [] },
1303
+ };
1304
+ renderPage(true);
1305
+ fireEvent.click(await screen.findByRole('button', { name: 'More actions' }));
1306
+ expect(screen.getByRole('menuitem', { name: 'Version history' })).toBeInTheDocument();
1307
+
1308
+ // Reached by keyboard, so no outside pointerdown ever dismissed the menu.
1309
+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }));
1310
+ await screen.findByRole('textbox', { name: /Edit SKILL\.md/ });
1311
+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
1312
+
1313
+ const back = await screen.findByRole('button', { name: 'More actions' });
1314
+ expect(back).toHaveAttribute('aria-expanded', 'false');
1315
+ expect(screen.queryByRole('menuitem', { name: 'Version history' })).toBeNull();
1316
+ });
1317
+
1318
+ it('has no trigger at all when git cannot answer', async () => {
1319
+ renderPage(false, [], [], makeFakeBus(), undefined, undefined, undefined, {
1320
+ ...git,
1321
+ availability: 'loading',
1322
+ } as GitContextValue);
1323
+
1324
+ // Version history is the whole menu, so no log means no `⋯` — an
1325
+ // overflow opening onto an empty panel is worse than no overflow.
1326
+ expect(await screen.findByRole('heading', { name: 'newsletter' })).toBeInTheDocument();
1327
+ expect(screen.queryByRole('button', { name: 'More actions' })).toBeNull();
1328
+ });
1329
+ });
1126
1330
  });
@@ -1,14 +1,25 @@
1
- import { useCallback, useEffect, useId, useMemo, useState, type ReactNode } from 'react';
1
+ import { useCallback, useEffect, useId, useMemo, useRef, useState, type ReactNode } from 'react';
2
2
  import { useLocation, useNavigate, useParams } from 'react-router-dom';
3
+ import { ArrowLeft, History } from 'lucide-react';
3
4
  import {
4
5
  DEFAULT_BRANCH,
5
6
  pluginOfPath,
6
7
  type PullRequestSummary,
7
8
  } from '@bevel-software/platform-shared';
8
9
  import '../../library.css';
9
- import { Badge, Button } from '../../../../shared/components';
10
+ import {
11
+ Badge,
12
+ Button,
13
+ IconButton,
14
+ MenuItem,
15
+ MenuPanel,
16
+ Surface,
17
+ useDismissableMenu,
18
+ } from '../../../../shared/components';
10
19
  import { useAuth } from '../../../auth/state/auth.context';
11
20
  import { useWorkspace } from '../../../workspace/state/workspace.context';
21
+ import { useGit } from '../../../git/state/git.context';
22
+ import { FileHistoryPanel } from '../../../git/components/FileHistoryPanel';
12
23
  import { kbFileUrl, resolveRelativePath, useNodeIdNav } from '../../../workspace/routing/kb-routes';
13
24
  import { cancelPullRequest } from '../../../pr/services/pr-cancel.api';
14
25
  import { useFileAccess } from '../../../access/hooks/useFileAccess';
@@ -91,8 +102,27 @@ export function SkillPage({
91
102
  const [selectedState, setSelected] = useState('SKILL.md');
92
103
  const selected = activeFile ?? selectedState;
93
104
  const [compareCr, setCompareCr] = useState<PullRequestSummary | null>(null);
105
+ /**
106
+ * The `⋯` menu's one destination: the git log for the file on screen,
107
+ * rendered in place of the reading pane. Local state rather than a URL,
108
+ * matching the Knowledge viewer's `activeTab` — a skill's canonical address
109
+ * names the FILE, and history is a lens on it, not a different file.
110
+ *
111
+ * Cleared whenever the file changes; see `historyKey` for why that is not a
112
+ * matter of taste.
113
+ */
114
+ const [historyOpen, setHistoryOpen] = useState(false);
115
+ const [menuOpen, setMenuOpen] = useState(false);
116
+ const menuTriggerRef = useRef<HTMLButtonElement>(null);
117
+ const closeMenu = useCallback(() => setMenuOpen(false), []);
118
+ const menuRef = useDismissableMenu<HTMLDivElement>({
119
+ open: menuOpen,
120
+ onClose: closeMenu,
121
+ returnFocusTo: menuTriggerRef,
122
+ });
94
123
  /** Ties the tabs to the panel they control; unique per mounted page. */
95
124
  const tabsId = useId();
125
+ const git = useGit();
96
126
 
97
127
  // Ownership is a property of the CATALOG entry, not of the skill document —
98
128
  // it comes from the per-file ACL the provider already resolved, so the page
@@ -210,6 +240,64 @@ export function SkillPage({
210
240
  Boolean((location.state as { startEditing?: boolean } | null)?.startEditing),
211
241
  );
212
242
  const [busyCr, setBusyCr] = useState<number | null>(null);
243
+
244
+ /**
245
+ * The workspace-relative path `FileHistoryPanel` reads the git log for — the
246
+ * same string the Knowledge viewer hands it, so a skill file's history is
247
+ * the file's history, not a second implementation of it. Null until the
248
+ * workspace and the skill have both resolved: the panel takes a path and
249
+ * asks immediately, so handing it a half-built one would ask about
250
+ * `undefined/SKILL.md`.
251
+ */
252
+ const historyPath = kbDirName && skillPath ? `${kbDirName}/${fileRepoPath}` : null;
253
+ /**
254
+ * Whether `⋯` has anything behind it. Git not ready means there is no log to
255
+ * show, and an overflow that opens onto an empty panel is worse than no
256
+ * overflow at all — the same call `KbPageHeader` makes.
257
+ *
258
+ * `!editing` is the other half, and it is not cosmetic: `SkillFileEditor`
259
+ * holds the draft in its own state, so swapping it out for the history panel
260
+ * would throw away whatever the person had typed with no warning and no way
261
+ * back. The menu returns the moment they save or cancel.
262
+ */
263
+ const historyAvailable = git.availability === 'ready' && historyPath !== null && !editing;
264
+ /**
265
+ * History closes when the file changes. It is a lens on ONE file, so a tab
266
+ * switch must land on that file's CONTENT — and it must stay landed: keying
267
+ * the open flag to the file it was opened for is not enough, because coming
268
+ * back to that tab then re-opens the log nobody asked for a second time.
269
+ *
270
+ * Adjusted during render rather than in an effect, so the new file's content
271
+ * paints on the first frame. An effect would show the old file's log under
272
+ * the new file's heading for one commit, which is the flicker the `active`
273
+ * derivation a few lines up exists to avoid.
274
+ */
275
+ const [historyKey, setHistoryKey] = useState(fileRepoPath);
276
+ if (historyKey !== fileRepoPath) {
277
+ setHistoryKey(fileRepoPath);
278
+ if (historyOpen) setHistoryOpen(false);
279
+ }
280
+ // Losing the log CLOSES it, rather than parking it behind a flag. Git
281
+ // availability is re-derived from a polled status call, so a single failed
282
+ // poll flips it to `error` — which takes the panel off screen — and the next
283
+ // successful one flips it back. Left open, that second poll would put the
284
+ // log back over the file minutes after the reader returned to reading. Once
285
+ // it is gone they ask for it again, which is one click.
286
+ //
287
+ // BOTH flags, for one reason: the trigger and its panel live behind
288
+ // `historyAvailable` together, so an open menu unmounts with them and its
289
+ // flag is left set behind an element nobody can see. Closing only the log
290
+ // fixed the panel and left the menu to spring open by itself on the next
291
+ // good poll.
292
+ //
293
+ // `editing` is the second door into the same state, and it is reachable
294
+ // without a mouse: `useDismissableMenu` dismisses on outside POINTERDOWN, so
295
+ // tabbing from the open menu to Edit and pressing Enter never dismisses it.
296
+ // The editor then withdraws `historyAvailable`, and Cancel used to hand the
297
+ // menu back open.
298
+ if (historyOpen && !historyAvailable) setHistoryOpen(false);
299
+ if (menuOpen && !historyAvailable) setMenuOpen(false);
300
+ const viewingHistory = historyAvailable && historyOpen;
213
301
  /**
214
302
  * Change requests a merge attempt has REFUSED as unmergeable. Git is the only
215
303
  * thing that can answer "does this still apply?", and it answers when asked
@@ -440,12 +528,58 @@ export function SkillPage({
440
528
 
441
529
  <header className="mt-4">
442
530
  <div className="flex items-center gap-3">
443
- <h1 className="text-display font-semibold text-ink">{skill?.name ?? name}</h1>
531
+ <h1 className="min-w-0 text-display font-semibold text-ink">{skill?.name ?? name}</h1>
444
532
  {skill && owned && (
445
533
  <Badge tone="outline" size="xs" className="shrink-0 uppercase">
446
534
  Owner
447
535
  </Badge>
448
536
  )}
537
+
538
+ {/* The same overflow a Knowledge page carries, for the same reason:
539
+ a skill is a file in the repository, and "who changed this, when"
540
+ is answerable about it exactly as it is about any other file. It
541
+ was unanswerable HERE and nowhere else, because this page is the
542
+ only surface a `Plugins/` file has — the shell routes those URLs
543
+ to the Library (`isLibraryLocation`) and the Knowledge tree does
544
+ not list `Plugins/` at all, so there was no viewer to fall back
545
+ to and no row to right-click.
546
+
547
+ Version history is the whole menu, so the trigger goes where the
548
+ menu goes — see `historyAvailable`. */}
549
+ {historyAvailable && (
550
+ <div className="relative ml-auto flex-none">
551
+ <IconButton
552
+ ref={menuTriggerRef}
553
+ aria-label="More actions"
554
+ aria-haspopup="menu"
555
+ aria-expanded={menuOpen}
556
+ active={menuOpen}
557
+ onClick={() => setMenuOpen((v) => !v)}
558
+ >
559
+ <span aria-hidden className="text-strong leading-none">
560
+ ⋯
561
+ </span>
562
+ </IconButton>
563
+ {menuOpen && (
564
+ <div ref={menuRef} className="absolute right-0 top-[calc(100%+5px)] z-40">
565
+ <MenuPanel role="menu" aria-label="More actions" className="min-w-[212px]">
566
+ <MenuItem
567
+ role="menuitem"
568
+ onClick={() => {
569
+ closeMenu();
570
+ setHistoryOpen(true);
571
+ }}
572
+ >
573
+ <span className="flex items-center gap-2.5">
574
+ <History size={14} />
575
+ Version history
576
+ </span>
577
+ </MenuItem>
578
+ </MenuPanel>
579
+ </div>
580
+ )}
581
+ </div>
582
+ )}
449
583
  </div>
450
584
  {/* No description line here — the file pane renders the raw SKILL.md,
451
585
  and its frontmatter panel already says what the skill is for.
@@ -476,16 +610,47 @@ export function SkillPage({
476
610
  }}
477
611
  />
478
612
 
479
- {/* The panel the tabs control. It wraps BOTH the reading pane and the
480
- editor that replaces it, so `aria-controls` resolves in either state
481
- rather than pointing at an element that exists only half the time. */}
613
+ {/* The panel the tabs control. It wraps the reading pane, the editor
614
+ that replaces it and the history that replaces both, so
615
+ `aria-controls` resolves in every state rather than pointing at an
616
+ element that exists only some of the time. */}
482
617
  <div
483
618
  role="tabpanel"
484
619
  id={skillPanelId(tabsId)}
485
620
  aria-labelledby={skillTabId(tabsId, active)}
486
- aria-busy={detail.loading || raw === null || undefined}
621
+ aria-busy={(!viewingHistory && (detail.loading || raw === null)) || undefined}
487
622
  >
488
- {detail.loading ? (
623
+ {viewingHistory && historyPath !== null ? (
624
+ <>
625
+ {/* An explicit way back. Without it the only route to the file would
626
+ be reopening it, since history is not in the URL. */}
627
+ <div className="mb-3 mt-4 flex items-center gap-2">
628
+ <Button
629
+ variant="quiet"
630
+ size="sm"
631
+ leadingIcon={<ArrowLeft size={13} />}
632
+ onClick={() => setHistoryOpen(false)}
633
+ >
634
+ Back to the file
635
+ </Button>
636
+ <span className="text-detail text-ink-faint">{`Version history: ${active}`}</span>
637
+ </div>
638
+ {/* A DEFINITE height, and a flex column to hold it. The panel is
639
+ built for the Knowledge viewer's full-height pane: its list and
640
+ its diff both scroll inside themselves, which needs a parent
641
+ whose height does not come from them. Dropped straight into this
642
+ reading column it would size to its own content instead, so a
643
+ long diff would stretch the page rather than scroll in place and
644
+ the empty state would collapse to a line. The measure matches the
645
+ editor's textarea, which is the same trade in the same column. */}
646
+ <Surface
647
+ radius="lg"
648
+ className="flex h-[60vh] min-h-80 flex-col overflow-hidden"
649
+ >
650
+ <FileHistoryPanel filePath={historyPath} />
651
+ </Surface>
652
+ </>
653
+ ) : detail.loading ? (
489
654
  <SkillFilePane
490
655
  file={active}
491
656
  raw={null}
@@ -568,8 +733,12 @@ export function SkillPage({
568
733
  )}
569
734
 
570
735
  {/* Every open proposal on this file, under the file it is about. The
571
- owner decides here; the author can take theirs back. */}
736
+ owner decides here; the author can take theirs back. Not under the
737
+ history panel: a box asking "approve this?" needs the text it would
738
+ change above it, and the log is not that text. The dock below still
739
+ reaches every open request from either view. */}
572
740
  {!editing &&
741
+ !viewingHistory &&
573
742
  boxes.map((cr) => {
574
743
  const mine = data.myCrNumbers.has(cr.number);
575
744
  // `[]` is the hook's "overtaken" answer — the proposal and the file
@@ -1,8 +1,8 @@
1
- import { useEffect, useLayoutEffect, useRef, useState } from 'react';
1
+ import { useEffect, useRef, useState } from 'react';
2
2
  import { X } from 'lucide-react';
3
3
  import { cn } from '../../../lib/utils';
4
4
  import { MenuPanel, MenuItem } from '../../../shared/components';
5
- import { useDismissableMenu } from '../../../shared/components';
5
+ import { useDismissableMenu, usePointerMenuPosition } from '../../../shared/components';
6
6
  import { useOpenChangeRequests } from '../hooks/useOpenChangeRequests';
7
7
  import { useWorkspace } from '../state/workspace.context';
8
8
  import { useFileNav } from '../routing/kb-routes';
@@ -339,21 +339,13 @@ function ContextMenu({
339
339
  returnFocusTo,
340
340
  }: ContextMenuProps) {
341
341
  const ref = useDismissableMenu<HTMLDivElement>({ open: true, onClose, returnFocusTo });
342
- const [pos, setPos] = useState<{ left: number; top: number }>({ left: state.x, top: state.y });
343
-
344
- // After the menu mounts, measure it and clamp into the viewport so a click
345
- // near the right/bottom edge doesn't open a menu that's partially off-screen.
346
- useLayoutEffect(() => {
347
- const el = ref.current;
348
- if (!el) return;
349
- const w = el.offsetWidth;
350
- const h = el.offsetHeight;
351
- const left = Math.max(0, Math.min(state.x, window.innerWidth - w));
352
- const top = Math.max(0, Math.min(state.y, window.innerHeight - h));
353
- setPos({ left, top });
354
- // `ref` comes from `useDismissableMenu` now, so it has to be declared —
355
- // it is a stable `useRef` box, so listing it changes nothing at runtime.
356
- }, [state.x, state.y, ref]);
342
+ // This menu measured and clamped itself, which the file tree's did not, and
343
+ // the two drifting apart is what left a right-click low in the tree with a
344
+ // menu running off the bottom of the window. One hook now, so a pointer
345
+ // menu's placement cannot depend on which surface opened it. The tab strip
346
+ // sits at the top of the window, so what changes here is only the inset from
347
+ // the right edge: the flip has nothing to flip away from.
348
+ const pos = usePointerMenuPosition(ref, state.x, state.y);
357
349
 
358
350
  const targetIdx = openTabs.findIndex((t) => t.path === state.tab.path);
359
351
  // If the target tab is gone (closed under us between menu open and click),
@@ -34,7 +34,7 @@ import { useFileNav } from '../routing/kb-routes';
34
34
  import { downloadViaBlob } from './renderers/downloadFile';
35
35
  import { cn } from '../../../lib/utils';
36
36
  import { MenuPanel, MenuItem, TextField, IconButton } from '../../../shared/components';
37
- import { useDismissableMenu } from '../../../shared/components';
37
+ import { useDismissableMenu, usePointerMenuPosition } from '../../../shared/components';
38
38
  import { useOpenChangeRequests } from '../hooks/useOpenChangeRequests';
39
39
  import { PullRequestsForMe } from '../../git/components/PullRequestsForMe';
40
40
  import { ManageAccessDialog } from '../../access/components/ManageAccessDialog';
@@ -180,6 +180,12 @@ function ContextMenu({
180
180
  // Outside-click, Escape, and focus return — none of which `MenuPanel`
181
181
  // provides (it is presentation only, by design).
182
182
  const ref = useDismissableMenu<HTMLDivElement>({ open: true, onClose, returnFocusTo });
183
+ // Measured placement, because the pointer is not a safe place to paint from.
184
+ // A folder's menu is nine rows, and a right-click low in the sidebar used to
185
+ // draw it straight off the bottom of the window with no way to reach what
186
+ // fell below: `Manage access`, `Rename` and `Delete` among them, and for a
187
+ // folder that `Manage access` row is the product's only route to it.
188
+ const pos = usePointerMenuPosition(ref, x, y);
183
189
 
184
190
  // Only files whose name ends with `.zip` (case-insensitive) get the
185
191
  // extraction affordance — matches the OS shell-extension behavior users
@@ -245,12 +251,12 @@ function ContextMenu({
245
251
 
246
252
  return (
247
253
  // Positioning stays with the caller — `MenuPanel` is presentation only, so
248
- // the fixed-to-the-pointer wrapper is ours and the panel inside is the
249
- // shared one.
254
+ // the fixed wrapper and its measured placement are ours, and the panel
255
+ // inside is the shared one.
250
256
  <div
251
257
  ref={ref}
252
258
  className="fixed z-50"
253
- style={{ left: x, top: y }}
259
+ style={{ left: pos.left, top: pos.top }}
254
260
  onMouseDown={(e) => e.stopPropagation()}
255
261
  >
256
262
  <MenuPanel role="menu" aria-label={`Actions for ${entry.name}`} className="min-w-[180px]">
@@ -1,4 +1,4 @@
1
- import { describe, it, expect, vi, beforeEach } from 'vitest';
1
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
2
  import { render, screen, fireEvent, waitFor, act, cleanup } from '@testing-library/react';
3
3
  import userEvent from '@testing-library/user-event';
4
4
  import { MemoryRouter } from 'react-router-dom';
@@ -920,3 +920,172 @@ describe('FileExplorer rows: the prototype tree', () => {
920
920
  expect(screen.queryByRole('dialog')).toBeNull();
921
921
  });
922
922
  });
923
+
924
+ // ── The right-click menu has to land on screen ──
925
+ //
926
+ // The panel is `position: fixed`, so whatever falls past the bottom edge of
927
+ // the window is unreachable: the page will not scroll to a fixed box, and the
928
+ // wheel scrolls the tree out from under a menu that stays where it was. A
929
+ // folder's menu is nine rows, so pinning it to the raw pointer put `Manage
930
+ // access`, `Rename` and `Delete` below the fold for any right-click in the
931
+ // lower quarter of the sidebar.
932
+ /** jsdom's own viewport, read at import before any test has stubbed it. */
933
+ const REAL_VIEWPORT = { width: window.innerWidth, height: window.innerHeight };
934
+
935
+ describe('FileExplorer right-click: the menu stays inside the window', () => {
936
+ const TREE: FileTreeEntry = {
937
+ name: '.',
938
+ relativePath: '.',
939
+ type: 'directory',
940
+ children: [
941
+ { name: 'reports', relativePath: 'reports', type: 'directory', children: [] },
942
+ { name: 'brief.md', relativePath: 'brief.md', type: 'file' },
943
+ ],
944
+ };
945
+
946
+ const MENU_W = 200;
947
+ const MENU_H = 300;
948
+
949
+ // jsdom lays nothing out, so every `offsetWidth`/`offsetHeight` is 0 and the
950
+ // placement would have nothing to react to. Give a size to the one element
951
+ // the hook measures: the fixed wrapper, identified by the `role="menu"`
952
+ // panel it holds.
953
+ const isMenuBox = (el: HTMLElement) => el.firstElementChild?.getAttribute('role') === 'menu';
954
+ let restoreLayout: (() => void) | null = null;
955
+
956
+ function stubViewport(width: number, height: number) {
957
+ const w = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetWidth')!;
958
+ const h = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetHeight')!;
959
+ // jsdom defines these as own accessors on `window`, so the descriptor is
960
+ // real and putting it back restores the getter rather than freezing a
961
+ // number in its place.
962
+ const iw = Object.getOwnPropertyDescriptor(window, 'innerWidth')!;
963
+ const ih = Object.getOwnPropertyDescriptor(window, 'innerHeight')!;
964
+ Object.defineProperty(HTMLElement.prototype, 'offsetWidth', {
965
+ configurable: true,
966
+ get(this: HTMLElement) {
967
+ return isMenuBox(this) ? MENU_W : 0;
968
+ },
969
+ });
970
+ Object.defineProperty(HTMLElement.prototype, 'offsetHeight', {
971
+ configurable: true,
972
+ get(this: HTMLElement) {
973
+ return isMenuBox(this) ? MENU_H : 0;
974
+ },
975
+ });
976
+ Object.defineProperty(window, 'innerWidth', { configurable: true, writable: true, value: width });
977
+ Object.defineProperty(window, 'innerHeight', { configurable: true, writable: true, value: height });
978
+ restoreLayout = () => {
979
+ Object.defineProperty(HTMLElement.prototype, 'offsetWidth', w);
980
+ Object.defineProperty(HTMLElement.prototype, 'offsetHeight', h);
981
+ Object.defineProperty(window, 'innerWidth', iw);
982
+ Object.defineProperty(window, 'innerHeight', ih);
983
+ };
984
+ }
985
+
986
+ /** The fixed wrapper the placement writes to: the `role="menu"` panel's parent. */
987
+ const menuBox = () => screen.getByRole('menu').parentElement as HTMLElement;
988
+
989
+ beforeEach(() => {
990
+ cleanup();
991
+ mockAuthFetch.mockReset();
992
+ });
993
+
994
+ afterEach(() => {
995
+ restoreLayout?.();
996
+ restoreLayout = null;
997
+ });
998
+
999
+ it('flips a folder menu above the pointer when it would run off the bottom', () => {
1000
+ stubViewport(1280, 800);
1001
+ renderExplorer({ fileTree: TREE });
1002
+
1003
+ fireEvent.contextMenu(screen.getByText('reports'), { clientX: 120, clientY: 760 });
1004
+
1005
+ // Above the pointer, with the 4px gap that keeps the cursor off the last
1006
+ // row: 760 - 4 - 300. Without the gap the pointer would come to rest on
1007
+ // `Delete`, which is exactly the row it should not be resting on.
1008
+ const box = menuBox();
1009
+ expect(box.style.top).toBe('456px');
1010
+ expect(parseInt(box.style.top, 10) + MENU_H).toBeLessThanOrEqual(window.innerHeight);
1011
+ });
1012
+
1013
+ it('keeps every row of a folder menu reachable, Manage access included', () => {
1014
+ stubViewport(1280, 800);
1015
+ renderExplorer({ fileTree: TREE });
1016
+
1017
+ fireEvent.contextMenu(screen.getByText('reports'), { clientX: 120, clientY: 780 });
1018
+
1019
+ // The impact line, asserted: the row that is the only route to a folder's
1020
+ // access control has to be inside the window, not merely rendered.
1021
+ expect(screen.getByRole('menuitem', { name: /Manage access/i })).toBeInTheDocument();
1022
+ const top = parseInt(menuBox().style.top, 10);
1023
+ expect(top).toBeGreaterThanOrEqual(8);
1024
+ expect(top + MENU_H).toBeLessThanOrEqual(window.innerHeight - 8);
1025
+ });
1026
+
1027
+ it('leaves a menu that already fits where the pointer put it', () => {
1028
+ stubViewport(1280, 800);
1029
+ renderExplorer({ fileTree: TREE });
1030
+
1031
+ fireEvent.contextMenu(screen.getByText('brief.md'), { clientX: 120, clientY: 100 });
1032
+
1033
+ // Down and to the right of the pointer is what every desktop shell does,
1034
+ // and it leaves the cursor on the first row, which is never destructive.
1035
+ const box = menuBox();
1036
+ expect(box.style.top).toBe('100px');
1037
+ expect(box.style.left).toBe('120px');
1038
+ });
1039
+
1040
+ it('clamps to the top margin when the window is shorter than the menu', () => {
1041
+ stubViewport(1280, 250);
1042
+ renderExplorer({ fileTree: TREE });
1043
+
1044
+ fireEvent.contextMenu(screen.getByText('reports'), { clientX: 120, clientY: 200 });
1045
+
1046
+ // Neither side fits, so the panel keeps its top rows rather than losing
1047
+ // both ends.
1048
+ expect(menuBox().style.top).toBe('8px');
1049
+ });
1050
+
1051
+ it('re-places an open menu when the window is resized under it', () => {
1052
+ stubViewport(1280, 800);
1053
+ renderExplorer({ fileTree: TREE });
1054
+
1055
+ // Opens with room to spare, so the menu sits at the pointer.
1056
+ fireEvent.contextMenu(screen.getByText('reports'), { clientX: 120, clientY: 400 });
1057
+ expect(menuBox().style.top).toBe('400px');
1058
+
1059
+ // Shrink the window with the menu still open. Dragging a window edge would
1060
+ // have closed it, since that is a mousedown outside the panel, but zoom,
1061
+ // fullscreen and OS window snapping resize without one.
1062
+ act(() => {
1063
+ Object.defineProperty(window, 'innerHeight', { configurable: true, writable: true, value: 500 });
1064
+ window.dispatchEvent(new Event('resize'));
1065
+ });
1066
+
1067
+ // 400 + 300 no longer fits under 500, and 400 - 4 - 300 clears the margin,
1068
+ // so it flips rather than hanging off the bottom of the new viewport.
1069
+ expect(menuBox().style.top).toBe('96px');
1070
+ });
1071
+
1072
+ it('pulls the menu back from the right edge of the window', () => {
1073
+ stubViewport(300, 800);
1074
+ renderExplorer({ fileTree: TREE });
1075
+
1076
+ fireEvent.contextMenu(screen.getByText('brief.md'), { clientX: 250, clientY: 100 });
1077
+
1078
+ // 300 - 200 - 8: the whole panel, not just its left edge, is on screen.
1079
+ expect(menuBox().style.left).toBe('92px');
1080
+ });
1081
+ });
1082
+
1083
+ // The stub above is only safe if it puts the window back. A viewport left at
1084
+ // the last case's 300px would silently narrow whatever runs next, including a
1085
+ // block someone appends below this one.
1086
+ describe('FileExplorer right-click: the viewport stub cleans up after itself', () => {
1087
+ it('leaves window.innerWidth and innerHeight as it found them', () => {
1088
+ expect(window.innerWidth).toBe(REAL_VIEWPORT.width);
1089
+ expect(window.innerHeight).toBe(REAL_VIEWPORT.height);
1090
+ });
1091
+ });
@@ -0,0 +1,58 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import type { FileTreeEntry } from '@bevel-software/platform-shared';
3
+ import { suggestedPages } from '../fileTree';
4
+
5
+ /**
6
+ * The empty state's opening offer walks the tree the server already filtered
7
+ * (`.bevelignore`, the reader's access), so visibility is inherited. What the
8
+ * walk must decide for itself is what counts as a PAGE — and an `access.md`
9
+ * is a document by extension only.
10
+ */
11
+
12
+ const file = (relativePath: string): FileTreeEntry => ({
13
+ name: relativePath.split('/').pop()!,
14
+ relativePath,
15
+ type: 'file',
16
+ });
17
+ const dir = (relativePath: string, children: FileTreeEntry[]): FileTreeEntry => ({
18
+ name: relativePath.split('/').pop()!,
19
+ relativePath,
20
+ type: 'directory',
21
+ children,
22
+ });
23
+
24
+ const TREE: FileTreeEntry = dir('', [
25
+ dir('knowledge-base', [
26
+ file('knowledge-base/access.md'),
27
+ file('knowledge-base/roles.yaml'),
28
+ dir('knowledge-base/KnowledgeBase', [
29
+ file('knowledge-base/KnowledgeBase/access.md'),
30
+ file('knowledge-base/KnowledgeBase/Access.MD'),
31
+ file('knowledge-base/KnowledgeBase/Onboarding.md'),
32
+ dir('knowledge-base/KnowledgeBase/GTM', [
33
+ file('knowledge-base/KnowledgeBase/GTM/access.md'),
34
+ file('knowledge-base/KnowledgeBase/GTM/Pricing.md'),
35
+ file('knowledge-base/KnowledgeBase/GTM/deals.csv'),
36
+ ]),
37
+ ]),
38
+ dir('knowledge-base/Plugins', [
39
+ dir('knowledge-base/Plugins/GTM', [file('knowledge-base/Plugins/GTM/README.md')]),
40
+ ]),
41
+ ]),
42
+ ]);
43
+
44
+ describe('suggestedPages', () => {
45
+ it('offers documents, never a folder\'s access rules — at any depth, in any case', () => {
46
+ const offered = suggestedPages(TREE, 10).map((e) => e.relativePath);
47
+ expect(offered).toEqual([
48
+ 'knowledge-base/KnowledgeBase/Onboarding.md',
49
+ 'knowledge-base/KnowledgeBase/GTM/Pricing.md',
50
+ ]);
51
+ });
52
+
53
+ it('honours the limit breadth-first and reports an empty knowledge base as such', () => {
54
+ expect(suggestedPages(TREE, 1).map((e) => e.name)).toEqual(['Onboarding.md']);
55
+ expect(suggestedPages(dir('', [dir('knowledge-base', [dir('knowledge-base/KnowledgeBase', [])])]), 3)).toEqual([]);
56
+ expect(suggestedPages(null, 3)).toEqual([]);
57
+ });
58
+ });
@@ -45,6 +45,15 @@ export function findKbRoot(node: FileTreeEntry | null): FileTreeEntry | null {
45
45
  /** Documents, as opposed to the data, config and archives beside them. */
46
46
  const READABLE_PAGE = /\.(md|markdown)$/i;
47
47
 
48
+ /**
49
+ * An `access.md` is a document by extension only: it is a folder's
50
+ * access-control rules, and it sits INSIDE the knowledge tree (every plugin
51
+ * and any governed folder carries one), so the root-file exclusion below
52
+ * never reaches it. Nobody opens a knowledge base to read who may edit it.
53
+ */
54
+ const ACCESS_RULES_FILE = 'access.md';
55
+ const isAccessRulesFile = (entry: FileTreeEntry): boolean => entry.name.toLowerCase() === ACCESS_RULES_FILE;
56
+
48
57
  /**
49
58
  * Pages worth offering to someone who has nothing open: the documents nearest
50
59
  * the top of the knowledge tree, breadth-first, so the opening suggestion is a
@@ -83,7 +92,7 @@ export function suggestedPages(tree: FileTreeEntry | null, limit: number): FileT
83
92
  // Dot-prefixed entries are the repository's own bookkeeping.
84
93
  if (entry.name.startsWith('.')) continue;
85
94
  if (entry.type === 'file') {
86
- if (READABLE_PAGE.test(entry.name)) pages.push(entry);
95
+ if (READABLE_PAGE.test(entry.name) && !isAccessRulesFile(entry)) pages.push(entry);
87
96
  } else if (entry.name !== PLUGINS_DIR) {
88
97
  next.push(...(entry.children ?? []));
89
98
  }
@@ -0,0 +1,50 @@
1
+ import { describe, it, expect, beforeEach } from 'vitest';
2
+ import { renderHook } from '@testing-library/react';
3
+ import { usePointerMenuPosition } from '../usePointerMenuPosition';
4
+
5
+ /**
6
+ * The hook measures the panel and places it relative to the pointer, keeping
7
+ * an 8px margin from every window edge. jsdom lays nothing out, so the panel
8
+ * is a stub with a fixed size.
9
+ */
10
+ function panel(w: number, h: number) {
11
+ const el = document.createElement('div');
12
+ Object.defineProperty(el, 'offsetWidth', { value: w });
13
+ Object.defineProperty(el, 'offsetHeight', { value: h });
14
+ return { current: el };
15
+ }
16
+
17
+ describe('usePointerMenuPosition', () => {
18
+ beforeEach(() => {
19
+ Object.defineProperty(window, 'innerWidth', { value: 1000, configurable: true });
20
+ Object.defineProperty(window, 'innerHeight', { value: 600, configurable: true });
21
+ });
22
+
23
+ it('opens at the pointer when the menu fits below it', () => {
24
+ const { result } = renderHook(() => usePointerMenuPosition(panel(200, 100), 300, 200));
25
+ expect(result.current).toEqual({ left: 300, top: 200 });
26
+ });
27
+
28
+ it('keeps the top margin when the pointer is in the first pixels of the window', () => {
29
+ // Fits below, so the downward branch places it — but never above the
30
+ // margin every other placement keeps from the window edge.
31
+ const { result } = renderHook(() => usePointerMenuPosition(panel(200, 100), 300, 2));
32
+ expect(result.current.top).toBe(8);
33
+ });
34
+
35
+ it('flips above the pointer when it does not fit below', () => {
36
+ const { result } = renderHook(() => usePointerMenuPosition(panel(200, 100), 300, 560));
37
+ expect(result.current.top).toBe(560 - 4 - 100);
38
+ });
39
+
40
+ it('pins to the bottom margin when it fits neither below nor above', () => {
41
+ const { result } = renderHook(() => usePointerMenuPosition(panel(200, 700), 300, 100));
42
+ expect(result.current.top).toBe(8);
43
+ expect(result.current.left).toBe(300);
44
+ });
45
+
46
+ it('keeps the right margin', () => {
47
+ const { result } = renderHook(() => usePointerMenuPosition(panel(200, 100), 950, 200));
48
+ expect(result.current.left).toBe(1000 - 200 - 8);
49
+ });
50
+ });
@@ -46,3 +46,5 @@ export type { PageShellWidth } from './PageShell';
46
46
  export { useModalLayer } from './useModalLayer';
47
47
  export { useDismissableMenu } from './useDismissableMenu';
48
48
  export type { DismissableMenuOptions } from './useDismissableMenu';
49
+ export { usePointerMenuPosition } from './usePointerMenuPosition';
50
+ export type { PointerMenuPosition } from './usePointerMenuPosition';
@@ -0,0 +1,92 @@
1
+ import { useLayoutEffect, useState, type RefObject } from 'react';
2
+
3
+ /** Minimum inset from a viewport edge, and the gap left when a menu flips above the pointer. */
4
+ const MENU_MARGIN = 8;
5
+ const MENU_GAP = 4;
6
+
7
+ /** Where a pointer-anchored panel should paint, in viewport coordinates. */
8
+ export interface PointerMenuPosition {
9
+ left: number;
10
+ top: number;
11
+ }
12
+
13
+ /**
14
+ * Places a pointer-anchored menu so the whole panel stays on screen.
15
+ *
16
+ * `MenuPanel` is presentation only and leaves positioning to its caller, which
17
+ * is the right call for a primitive but leaves every pointer-anchored menu to
18
+ * solve the same geometry. Three of them solved it three ways:
19
+ * `ManageAccessDialog`'s `AnchoredMenu` measures and flips, `EditorTabs`
20
+ * clamped, and the file tree pinned its panel straight to `clientX/clientY`.
21
+ *
22
+ * The tree is the one that hurt. A folder's menu is nine rows and about 300px
23
+ * tall, so a right-click anywhere in the lower quarter of the sidebar drew it
24
+ * downward off the bottom of the window, and being `position: fixed` there was
25
+ * no way back to the rows below the fold: the page will not scroll to a fixed
26
+ * box, and the wheel scrolls the tree out from under a menu that stays put.
27
+ * `Manage access` is one of those rows, and for a folder it is the only route
28
+ * to access control in the product.
29
+ *
30
+ * Down and to the right of the pointer stays the default, because that is what
31
+ * every desktop shell does and it leaves the pointer on the first row, which is
32
+ * never destructive. A panel that will not fit below flips above the pointer
33
+ * instead, keeping a small gap: the gap is not cosmetic, since a flip that put
34
+ * the panel's bottom edge exactly on the pointer would park the cursor on the
35
+ * last row, and in the tree's menu that row is `Delete`. Fitting neither way
36
+ * means the window is shorter than the menu, and the panel then sits against
37
+ * the bottom margin, which keeps its top rows reachable and loses only the
38
+ * bottom ones it could not have shown anyway.
39
+ *
40
+ * Pass the ref the panel already carries, the one from `useDismissableMenu`, so
41
+ * both hooks share a single box. Measuring in a layout effect means the browser
42
+ * paints the placed position once instead of flashing the unplaced one.
43
+ */
44
+ export function usePointerMenuPosition<T extends HTMLElement>(
45
+ ref: RefObject<T | null>,
46
+ x: number,
47
+ y: number,
48
+ ): PointerMenuPosition {
49
+ // The pre-measurement value is the pointer itself, so the first render is
50
+ // exactly where these menus used to open and the layout effect corrects it
51
+ // before paint.
52
+ const [pos, setPos] = useState<PointerMenuPosition>({ left: x, top: y });
53
+
54
+ useLayoutEffect(() => {
55
+ const place = () => {
56
+ const el = ref.current;
57
+ if (!el) return;
58
+ const w = el.offsetWidth;
59
+ const h = el.offsetHeight;
60
+ const left = Math.max(MENU_MARGIN, Math.min(x, window.innerWidth - w - MENU_MARGIN));
61
+ let top: number;
62
+ // Downward from the pointer, but never above the top margin: a pointer
63
+ // in the first few pixels of the window would otherwise put the menu's
64
+ // edge flush against the chrome, the one placement every other branch
65
+ // here keeps a margin from.
66
+ const below = Math.max(MENU_MARGIN, y);
67
+ if (below + h <= window.innerHeight - MENU_MARGIN) {
68
+ top = below;
69
+ } else if (y - MENU_GAP - h >= MENU_MARGIN) {
70
+ top = y - MENU_GAP - h;
71
+ } else {
72
+ top = Math.max(MENU_MARGIN, window.innerHeight - MENU_MARGIN - h);
73
+ }
74
+ // Keep the previous object when nothing moved. `place` runs again on
75
+ // every resize, and a fresh object each time would re-render for nothing.
76
+ setPos((prev) => (prev.left === left && prev.top === top ? prev : { left, top }));
77
+ };
78
+ place();
79
+ // A menu still open across a resize would otherwise keep a placement
80
+ // measured against a window that no longer exists. Dragging a window edge
81
+ // closes it first, because that is a mousedown outside the panel, but
82
+ // zooming, entering fullscreen and OS window snapping all resize without
83
+ // one, and the panel would be left hanging off the new viewport.
84
+ //
85
+ // `ref` is in the deps because it is read here. It is a stable `useRef`
86
+ // box, so listing it changes nothing at runtime.
87
+ window.addEventListener('resize', place);
88
+ return () => window.removeEventListener('resize', place);
89
+ }, [x, y, ref]);
90
+
91
+ return pos;
92
+ }