@bevel-software/platform-core-frontend 0.12.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.
@@ -31,7 +31,7 @@ export function ToolSecretsPanel({ tool, onChanged }: { tool: ToolSecrets; onCha
31
31
  if (tool.variables.length === 0) {
32
32
  return (
33
33
  <div className="flex flex-col gap-3">
34
- <SetupBanner setup={tool.setup} />
34
+ <SetupBanner setup={tool.setup} declared={tool.variables.some((v) => v.oauth)} />
35
35
  {tool.setup?.kind !== 'oauth-manual' && (
36
36
  <p className="text-detail text-ink-muted">
37
37
  {tool.setup?.kind === 'open' ? (
@@ -51,7 +51,7 @@ export function ToolSecretsPanel({ tool, onChanged }: { tool: ToolSecrets; onCha
51
51
 
52
52
  return (
53
53
  <div className="flex flex-col gap-3.5">
54
- <SetupBanner setup={tool.setup} />
54
+ <SetupBanner setup={tool.setup} declared={tool.variables.some((v) => v.oauth)} />
55
55
  {adminVars.length > 0 && (
56
56
  <VarPlugin
57
57
  title="Set by the tool owner"
@@ -95,21 +95,30 @@ function Chip({ children }: { children: React.ReactNode }) {
95
95
  }
96
96
 
97
97
  /**
98
- * When a `type: mcp` server needs sign-in that auto-discovery COULDN'T set up
99
- * (typically the provider has no dynamic client registration — e.g. Google),
100
- * the tool would otherwise look like it needs nothing. Make the required manual
101
- * setup explicit, and surface the discovery `reason` so the admin knows why.
98
+ * When a `type: mcp` server needs a sign-in with an owner-registered OAuth app
99
+ * (auto-discovery couldn't register one — Google, HubSpot — or the declaration
100
+ * already names a client id), the tool would otherwise look like it needs
101
+ * nothing until the owner finishes. Make the remaining step explicit, and
102
+ * surface the discovery `reason` so the admin knows what still blocks it.
102
103
  * The `open` / `oauth-auto` cases need no banner — they're either self-evident
103
104
  * (a sign-in variable appears below) or nothing-to-do.
104
105
  */
105
- function SetupBanner({ setup }: { setup: ToolSetup | null }) {
106
+ function SetupBanner({ setup, declared }: { setup: ToolSetup | null; declared: boolean }) {
106
107
  if (setup?.kind !== 'oauth-manual') return null;
107
108
  return (
108
109
  <Banner tone="wait" role="status">
109
- <span className="font-semibold">Sign-in setup needed.</span> This server needs users to sign
110
- in, but Bevel couldn&apos;t set that up automatically. A tool writer must register an OAuth
111
- client with the provider, declare it in the <Chip>.tool</Chip> file&apos;s{' '}
112
- <Chip>variables</Chip> block, then set its client secret here.
110
+ <span className="font-semibold">Sign-in setup needed.</span>{' '}
111
+ {declared ? (
112
+ <>The sign-in is declared — a tool writer sets its client secret here to finish.</>
113
+ ) : (
114
+ <>
115
+ This server needs users to sign in, but Bevel couldn&apos;t set that up automatically. A
116
+ tool writer must register an OAuth app with the provider and declare its client id on a
117
+ user-scoped sign-in variable — under <Chip>Edit server</Chip> on the tool&apos;s page for
118
+ an MCP server, or in the <Chip>.tool</Chip> file&apos;s <Chip>variables</Chip> block —
119
+ then set its client secret here.
120
+ </>
121
+ )}
113
122
  {setup.reason && <em className="mt-1 block text-detail">{setup.reason}</em>}
114
123
  </Banner>
115
124
  );
@@ -22,6 +22,8 @@ export interface OAuthProviderConfig {
22
22
  scopes?: string[];
23
23
  /** Extra static params appended to the authorization request (e.g. `audience`). */
24
24
  authParams?: Record<string, string>;
25
+ /** PKCE (S256) on the authorization-code flow — what MCP-spec providers require. */
26
+ pkce?: boolean;
25
27
  }
26
28
 
27
29
  async function unwrap(res: Response, fallback: string): Promise<never> {
@@ -33,9 +33,12 @@ export interface ToolVarStatus {
33
33
  * For a `type: mcp` tool, the setup requirement auto-discovery found:
34
34
  * - `open` — no auth; nothing to configure.
35
35
  * - `oauth-auto` — sign-in was set up automatically (appears as a user var).
36
- * - `oauth-manual` — the server needs sign-in but couldn't be set up
37
- * automatically; a tool writer must declare the provider in
38
- * the `.tool` file and set its client secret. `reason` says why.
36
+ * - `oauth-manual` — the sign-in needs an OAuth app the owner registers with
37
+ * the provider: a tool writer declares its client id on a
38
+ * user-scoped variable (the server editor for an mcp.json
39
+ * server; the `.tool` file otherwise) and sets its client
40
+ * secret. `reason` is present only while something still
41
+ * blocks the sign-in, and says what.
39
42
  */
40
43
  export interface ToolSetup {
41
44
  kind: 'open' | 'oauth-auto' | 'oauth-manual';
@@ -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
+ }