@bevel-software/platform-core-frontend 0.27.0 → 0.28.1

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 (42) hide show
  1. package/package.json +2 -2
  2. package/src/core/ProductName.tsx +4 -4
  3. package/src/core/__tests__/ProductName.test.tsx +46 -0
  4. package/src/core/maker-url.ts +30 -0
  5. package/src/core/registry.ts +27 -0
  6. package/src/lib/__tests__/latest-request.test.ts +48 -0
  7. package/src/lib/latest-request.ts +45 -0
  8. package/src/modules/access/__tests__/ManageAccessDialog.no-sso-invite.test.tsx +222 -0
  9. package/src/modules/access/api.ts +19 -3
  10. package/src/modules/access/components/ManageAccessDialog.tsx +60 -7
  11. package/src/modules/admin/__tests__/AdminRolesPage.fixed-admin.test.tsx +16 -1
  12. package/src/modules/admin/__tests__/UserAccountsPage.test.tsx +284 -39
  13. package/src/modules/admin/components/AdminRolesPage.tsx +13 -14
  14. package/src/modules/admin/components/UserAccountsPage.tsx +91 -107
  15. package/src/modules/admin/services/roles.api.ts +14 -1
  16. package/src/modules/auth/__tests__/LoginScreen.test.tsx +80 -5
  17. package/src/modules/auth/__tests__/sso-strict-probe.test.ts +66 -0
  18. package/src/modules/auth/components/LoginScreen.tsx +100 -75
  19. package/src/modules/auth/services/account.api.ts +31 -2
  20. package/src/modules/auth/services/sso.ts +29 -8
  21. package/src/modules/auth/state/use-sign-in-methods.ts +41 -0
  22. package/src/modules/onboarding/__tests__/InviteButton.test.tsx +214 -0
  23. package/src/modules/onboarding/__tests__/first-page-prompt.test.ts +56 -1
  24. package/src/modules/onboarding/__tests__/get-started-column.test.tsx +538 -81
  25. package/src/modules/onboarding/__tests__/invite-dialog.test.tsx +543 -124
  26. package/src/modules/onboarding/__tests__/invite-emails.test.ts +247 -0
  27. package/src/modules/onboarding/components/GetStartedColumn.tsx +30 -11
  28. package/src/modules/onboarding/components/InviteButton.tsx +119 -15
  29. package/src/modules/onboarding/components/InviteDialog.tsx +392 -75
  30. package/src/modules/onboarding/first-page-prompt.ts +34 -0
  31. package/src/modules/onboarding/invite-emails.ts +171 -33
  32. package/src/modules/onboarding/state/invite-dialog.context.ts +7 -4
  33. package/src/modules/onboarding/state/invite-dialog.tsx +12 -4
  34. package/src/modules/toolbar/commands/actions.tsx +10 -4
  35. package/src/modules/toolbar/commands/useCommandActions.ts +5 -3
  36. package/src/modules/toolbar/components/AppSwitcher.tsx +19 -0
  37. package/src/modules/toolbar/components/__tests__/AppSwitcher.test.tsx +46 -1
  38. package/src/modules/toolbar/components/__tests__/SearchPalette.test.tsx +34 -2
  39. package/src/modules/workspace/hooks/__tests__/useCreatePage.test.ts +137 -0
  40. package/src/modules/workspace/hooks/__tests__/useKnowledgeWriteTarget.test.ts +302 -0
  41. package/src/modules/workspace/hooks/useCreatePage.ts +118 -28
  42. package/src/modules/workspace/hooks/useKnowledgeWriteTarget.ts +238 -0
@@ -0,0 +1,247 @@
1
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import { isInvited, sendInvites, wasEmailed } from '../invite-emails';
3
+
4
+ /** Every invite promotion is sent `ifActive`: the server refuses a switched-off account at the write. */
5
+ const ACTIVE = { ifActive: true };
6
+
7
+ /**
8
+ * `sendInvites` with and without a starting password: who gets it, who keeps
9
+ * their own, who is left alone, and that a send with a password never writes
10
+ * blind when the account list cannot be read (the server's account write
11
+ * replaces a stored password).
12
+ */
13
+
14
+ const PW = 'welcome-to-acme';
15
+ /** How a starting password is sent: the server never writes it over one of the account's own. */
16
+ const KEEP = { keepExistingPassword: true };
17
+
18
+ function makeApi(accounts: { email: string; hasPassword?: boolean; isEnvAdmin?: boolean; deactivatedAt?: string | null }[] | Error) {
19
+ return {
20
+ listAccounts: vi.fn(async () => {
21
+ if (accounts instanceof Error) throw accounts;
22
+ return accounts;
23
+ }),
24
+ createAccount: vi.fn<
25
+ (
26
+ email: string,
27
+ name: string,
28
+ password?: string,
29
+ options?: { keepExistingPassword?: boolean },
30
+ ) => Promise<{ passwordSet?: boolean; deactivated?: boolean; notified?: string[] } | void>
31
+ >(async () => ({ passwordSet: true })),
32
+ addMember: vi.fn(async () => []),
33
+ fetchRoles: vi.fn(async () => [{ canonical: 'admin', members: ['boss@acme.com'] }]),
34
+ };
35
+ }
36
+
37
+ let api: ReturnType<typeof makeApi>;
38
+ beforeEach(() => {
39
+ api = makeApi([
40
+ { email: 'nopw@acme.com', hasPassword: false },
41
+ { email: 'own@acme.com', hasPassword: true },
42
+ { email: 'env@acme.com', hasPassword: false, isEnvAdmin: true },
43
+ { email: 'off@acme.com', hasPassword: false, deactivatedAt: '2026-09-01T00:00:00Z' },
44
+ ]);
45
+ });
46
+
47
+ describe('sendInvites with a starting password', () => {
48
+ it('creates new accounts with it and completes an existing one that has none', async () => {
49
+ const result = await sendInvites(['new@acme.com', 'nopw@acme.com'], 'member', api, { password: PW });
50
+ expect(api.createAccount.mock.calls).toEqual([
51
+ ['new@acme.com', '', PW, KEEP],
52
+ ['nopw@acme.com', '', PW, KEEP],
53
+ ]);
54
+ expect(result).toEqual({
55
+ status: 'sent',
56
+ outcomes: [
57
+ { email: 'new@acme.com', status: 'created', role: 'member', passwordSet: true },
58
+ { email: 'nopw@acme.com', status: 'existing', passwordSet: true },
59
+ ],
60
+ });
61
+ });
62
+
63
+ it('never writes an account with its own password, the deployment admin, or a switched-off one', async () => {
64
+ const result = await sendInvites(['own@acme.com', 'env@acme.com', 'off@acme.com'], 'member', api, { password: PW });
65
+ expect(api.createAccount).not.toHaveBeenCalled();
66
+ expect(result).toEqual({
67
+ status: 'sent',
68
+ outcomes: [
69
+ { email: 'own@acme.com', status: 'existing', hasOwnPassword: true },
70
+ { email: 'env@acme.com', status: 'existing', hasOwnPassword: true },
71
+ { email: 'off@acme.com', status: 'existing', deactivated: true },
72
+ ],
73
+ });
74
+ });
75
+
76
+ it('still makes Admin invites admins, after the password', async () => {
77
+ await sendInvites(['new@acme.com', 'nopw@acme.com'], 'admin', api, { password: PW });
78
+ expect(api.createAccount.mock.calls.map((c) => c[2])).toEqual([PW, PW]);
79
+ expect(api.addMember.mock.calls).toEqual([
80
+ ['admin', 'new@acme.com', ACTIVE],
81
+ ['admin', 'nopw@acme.com', ACTIVE],
82
+ ]);
83
+ });
84
+
85
+ it('leaves an existing account as it was when setting the password fails, with the reason', async () => {
86
+ api.createAccount.mockRejectedValueOnce(new Error('Password too common'));
87
+ const result = await sendInvites(['nopw@acme.com'], 'admin', api, { password: PW });
88
+ expect(result).toEqual({
89
+ status: 'sent',
90
+ outcomes: [{ email: 'nopw@acme.com', status: 'existing', passwordError: 'Password too common' }],
91
+ });
92
+ expect(api.addMember).not.toHaveBeenCalled();
93
+ });
94
+
95
+ it('sends nothing at all when the account list cannot be read', async () => {
96
+ api = makeApi(new Error('down'));
97
+ const result = await sendInvites(['new@acme.com'], 'admin', api, { password: PW });
98
+ expect(result).toEqual({ status: 'accounts-unreadable' });
99
+ expect(api.createAccount).not.toHaveBeenCalled();
100
+ expect(api.addMember).not.toHaveBeenCalled();
101
+ expect(api.fetchRoles).not.toHaveBeenCalled();
102
+ });
103
+
104
+ it('keeps a password the account set after the list was read: the server refused the write', async () => {
105
+ api.createAccount.mockResolvedValue({ passwordSet: false });
106
+ const result = await sendInvites(['nopw@acme.com', 'new@acme.com'], 'member', api, { password: PW });
107
+ expect(api.createAccount.mock.calls).toEqual([
108
+ ['nopw@acme.com', '', PW, KEEP],
109
+ ['new@acme.com', '', PW, KEEP],
110
+ ]);
111
+ expect(result).toEqual({
112
+ status: 'sent',
113
+ outcomes: [
114
+ { email: 'nopw@acme.com', status: 'existing', hasOwnPassword: true },
115
+ // Not on the list, but there with a password of its own by the time of the write.
116
+ { email: 'new@acme.com', status: 'existing', hasOwnPassword: true },
117
+ ],
118
+ });
119
+ });
120
+
121
+ it('reports an account switched off after the list was read as switched off, not invited', async () => {
122
+ api.createAccount.mockResolvedValue({ passwordSet: false, deactivated: true });
123
+ const result = await sendInvites(['nopw@acme.com', 'new@acme.com'], 'member', api, { password: PW });
124
+ expect(result).toEqual({
125
+ status: 'sent',
126
+ outcomes: [
127
+ { email: 'nopw@acme.com', status: 'existing', deactivated: true },
128
+ { email: 'new@acme.com', status: 'existing', deactivated: true },
129
+ ],
130
+ });
131
+ if (result.status !== 'sent') throw new Error('not sent');
132
+ expect(result.outcomes.filter((o) => isInvited(o, true))).toEqual([]);
133
+ });
134
+
135
+ it('does not make a switched-off account an Admin, listed so or switched off since the read', async () => {
136
+ // Listed as switched off: no password write and no promotion.
137
+ const listed = await sendInvites(['off@acme.com'], 'admin', api, { password: PW });
138
+ expect(listed).toEqual({ status: 'sent', outcomes: [{ email: 'off@acme.com', status: 'existing', deactivated: true }] });
139
+ // Switched off between the read and the write: the server left it, and so does the promotion.
140
+ api.createAccount.mockResolvedValue({ passwordSet: false, deactivated: true });
141
+ const since = await sendInvites(['nopw@acme.com', 'new@acme.com'], 'admin', api, { password: PW });
142
+ expect(since).toEqual({
143
+ status: 'sent',
144
+ outcomes: [
145
+ { email: 'nopw@acme.com', status: 'existing', deactivated: true },
146
+ { email: 'new@acme.com', status: 'existing', deactivated: true },
147
+ ],
148
+ });
149
+ expect(api.addMember).not.toHaveBeenCalled();
150
+ });
151
+
152
+ it('still promotes an account that got its own password since the read', async () => {
153
+ api.createAccount.mockResolvedValue({ passwordSet: false });
154
+ await sendInvites(['new@acme.com'], 'admin', api, { password: PW });
155
+ expect(api.addMember.mock.calls).toEqual([['admin', 'new@acme.com', ACTIVE]]);
156
+ });
157
+
158
+ it('reports an account switched off between the read and the promotion as switched off, not an admin', async () => {
159
+ // The list says switched on and it has its own password, so nothing is
160
+ // written but the promotion — which the server refuses at the write.
161
+ api.addMember.mockRejectedValueOnce(Object.assign(new Error('This account is switched off'), { kind: 'deactivated' }));
162
+ const result = await sendInvites(['own@acme.com'], 'admin', api, { password: PW });
163
+ expect(api.addMember.mock.calls).toEqual([['admin', 'own@acme.com', ACTIVE]]);
164
+ expect(result).toEqual({
165
+ status: 'sent',
166
+ outcomes: [{ email: 'own@acme.com', status: 'existing', hasOwnPassword: true, deactivated: true }],
167
+ });
168
+ if (result.status !== 'sent') throw new Error('not sent');
169
+ expect(result.outcomes.filter((o) => isInvited(o, true))).toEqual([]);
170
+ });
171
+
172
+ it('carries the password in no outcome', async () => {
173
+ const result = await sendInvites(['new@acme.com', 'nopw@acme.com', 'own@acme.com'], 'member', api, {
174
+ password: PW,
175
+ });
176
+ expect(JSON.stringify(result)).not.toContain(PW);
177
+ });
178
+ });
179
+
180
+ describe('sendInvites without a password', () => {
181
+ it('gives no account one', async () => {
182
+ await sendInvites(['new@acme.com', 'nopw@acme.com'], 'member', api);
183
+ expect(api.createAccount.mock.calls).toEqual([['new@acme.com', '']]);
184
+ });
185
+
186
+ it('treats every address as new when the list cannot be read, as before', async () => {
187
+ api = makeApi(new Error('down'));
188
+ const result = await sendInvites(['new@acme.com'], 'member', api);
189
+ expect(api.createAccount).toHaveBeenCalledWith('new@acme.com', '');
190
+ expect(result).toEqual({ status: 'sent', outcomes: [{ email: 'new@acme.com', status: 'created', role: 'member' }] });
191
+ });
192
+ it('leaves a switched-off account unchanged on an Admin invite: no promotion', async () => {
193
+ const result = await sendInvites(['off@acme.com'], 'admin', api);
194
+ expect(api.addMember).not.toHaveBeenCalled();
195
+ expect(result).toEqual({ status: 'sent', outcomes: [{ email: 'off@acme.com', status: 'existing', deactivated: true }] });
196
+ });
197
+ });
198
+
199
+ describe('sendInvites carries how the deployment told the person', () => {
200
+ it('a new account the server says was emailed carries `notified`; one nobody told does not', async () => {
201
+ api.createAccount
202
+ .mockResolvedValueOnce({ passwordSet: true, notified: ['email'] })
203
+ .mockResolvedValueOnce({ passwordSet: true, notified: [] });
204
+ const result = await sendInvites(['one@acme.com', 'two@acme.com'], 'member', api, { password: PW });
205
+ expect(result).toEqual({
206
+ status: 'sent',
207
+ outcomes: [
208
+ { email: 'one@acme.com', status: 'created', role: 'member', passwordSet: true, notified: ['email'] },
209
+ { email: 'two@acme.com', status: 'created', role: 'member', passwordSet: true },
210
+ ],
211
+ });
212
+ expect(wasEmailed(result.status === 'sent' ? result.outcomes[0]! : failedOutcome)).toBe(true);
213
+ expect(wasEmailed(result.status === 'sent' ? result.outcomes[1]! : failedOutcome)).toBe(false);
214
+ });
215
+
216
+ it('without a password too, and only for a NEW account: an existing one that got a password was not invited', async () => {
217
+ api.createAccount.mockResolvedValue({ notified: ['email'] });
218
+ const result = await sendInvites(['new@acme.com'], 'member', api);
219
+ expect(result).toEqual({
220
+ status: 'sent',
221
+ outcomes: [{ email: 'new@acme.com', status: 'created', role: 'member', notified: ['email'] }],
222
+ });
223
+ // The server answers `notified` for a new account only; an existing
224
+ // account's password write never carries it onto the row.
225
+ api.createAccount.mockResolvedValue({ passwordSet: true, notified: ['email'] });
226
+ const existing = await sendInvites(['nopw@acme.com'], 'member', api, { password: PW });
227
+ expect(existing).toEqual({
228
+ status: 'sent',
229
+ outcomes: [{ email: 'nopw@acme.com', status: 'existing', passwordSet: true }],
230
+ });
231
+ });
232
+ });
233
+
234
+ const failedOutcome = { email: 'x@acme.com', status: 'error' as const, message: 'never' };
235
+
236
+ describe('isInvited', () => {
237
+ const failed = { email: 'nopw@acme.com', status: 'existing' as const, passwordError: 'Password too common' };
238
+ it('does not count an account whose password could not be set, without single sign-on', () => {
239
+ expect(isInvited(failed)).toBe(false);
240
+ });
241
+ it('counts it with single sign-on: it can still sign in that way', () => {
242
+ expect(isInvited(failed, true)).toBe(true);
243
+ });
244
+ it('never counts a switched-off account', () => {
245
+ expect(isInvited({ email: 'off@acme.com', status: 'existing', deactivated: true }, true)).toBe(false);
246
+ });
247
+ });
@@ -25,7 +25,13 @@ import { useCreatePage } from '../../workspace/hooks/useCreatePage';
25
25
  import { findEntryByPath, pathExistsInTree } from '../../workspace/utils/fileTree';
26
26
  import { useOnboarding, useSetupChecklist } from '../state/onboarding';
27
27
  import { useAgentConnection } from '../state/agent-connection';
28
- import { chatGptPromptUrl, claudePromptUrl, firstPagePromptFor, firstPageRoute } from '../first-page-prompt';
28
+ import {
29
+ chatGptPromptUrl,
30
+ claudePromptUrl,
31
+ firstPagePromptFor,
32
+ firstPagePromptInFolder,
33
+ firstPageRoute,
34
+ } from '../first-page-prompt';
29
35
  import { useStarterPacks } from '../state/starter-packs';
30
36
  import { useInviteDialog } from '../state/invite-dialog.context';
31
37
  import { WELCOME_PATH } from '../paths';
@@ -182,7 +188,7 @@ export function GetStartedColumn() {
182
188
  const { kbDirName, openFilePath, workspaceBranch } = useWorkspace();
183
189
  const { tree } = useMergedWorkspaceTree();
184
190
  const { openWorkspacePath } = useFileNav();
185
- const { createPage } = useCreatePage();
191
+ const { createPage, pageFolder, pageFolderSettled } = useCreatePage();
186
192
  const invite = useInviteDialog();
187
193
 
188
194
  /**
@@ -224,6 +230,12 @@ export function GetStartedColumn() {
224
230
  const knowledgeRoot = kbDirName ? `${kbDirName}/${KNOWLEDGE_BASE_DIR}` : null;
225
231
  const guidePath = knowledgeRoot ? `${knowledgeRoot}/${GUIDE_FILE}` : null;
226
232
  const guideExists = guidePath !== null && pathExistsInTree(tree, guidePath);
233
+ // Where New page writes, below the top of Knowledge (`Sales`), or null at
234
+ // the top itself — what the agent's request has to name.
235
+ const pageSubfolder =
236
+ pageFolder && knowledgeRoot && pageFolder.startsWith(`${knowledgeRoot}/`)
237
+ ? pageFolder.slice(knowledgeRoot.length + 1)
238
+ : null;
227
239
 
228
240
  /**
229
241
  * The starter pack the team chose, if any: its first-page request replaces
@@ -248,11 +260,13 @@ export function GetStartedColumn() {
248
260
  }, [tree, waitingOnPlaceholders, reloadStarter]);
249
261
 
250
262
  /**
251
- * "New page": create a Markdown page in the Knowledge folder and open it
252
- * already in the editor (`useCreatePage`, shared with the command menu). The failure is kept here and shown on the step
253
- * because nothing else would say it — toasts only speak inside the
254
- * Library, and a refusal (a protected branch's write gate) is exactly what
255
- * the person needs to read.
263
+ * "New page": create a Markdown page in a Knowledge folder the person may
264
+ * write and open it already in the editor (`useCreatePage`, shared with the
265
+ * command menu). A refused write never reaches here: `useCreatePage`
266
+ * takes every 403 quietly, moving to the next folder the person may write
267
+ * or withdrawing New page, and resolves null. Any other failure is kept
268
+ * here and shown on the step, because nothing else would say it — toasts
269
+ * only speak inside the Library.
256
270
  */
257
271
  const [newPage, setNewPage] = useState<{ busy: boolean; error: string | null }>({ busy: false, error: null });
258
272
  const createFirstPage = async () => {
@@ -324,8 +338,11 @@ export function GetStartedColumn() {
324
338
  * the whole list — and let it be closed — on the strength of placeholders.
325
339
  * A failed request settles too, and the pages count as the app counted
326
340
  * them before there were packs.
341
+ *
342
+ * Only for someone who may write a Knowledge folder: nobody else is shown
343
+ * the step, and the list counts and completes without it.
327
344
  */
328
- items.push({
345
+ if (pageFolder) items.push({
329
346
  id: 'page',
330
347
  title: 'Write your first page',
331
348
  done:
@@ -340,7 +357,7 @@ export function GetStartedColumn() {
340
357
  <FirstPagePromptActions
341
358
  client={agent.client}
342
359
  kind={agent.kind}
343
- prompt={firstPagePromptFor(chosenPack)}
360
+ prompt={firstPagePromptInFolder(firstPagePromptFor(chosenPack), pageSubfolder)}
344
361
  newPage={newPageAction}
345
362
  />
346
363
  ),
@@ -385,8 +402,10 @@ export function GetStartedColumn() {
385
402
  const doneCount = items.filter((i) => i.done).length;
386
403
  // Until the admin verdict and its two questions are answered, the list is
387
404
  // not known — and showing a half-ticked list for a moment to an admin who
388
- // has done everything would be a column that flashes on every load.
389
- const settled = !isAdminLoading && (!isAdmin || (plugin.settled && teammate.settled));
405
+ // has done everything would be a column that flashes on every load. The
406
+ // same for where a page may be written: the step must not show and vanish.
407
+ const settled =
408
+ pageFolderSettled && !isAdminLoading && (!isAdmin || (plugin.settled && teammate.settled));
390
409
  const allDone = doneCount === items.length;
391
410
  // The completion line says whether the agent can reach the knowledge base,
392
411
  // so it waits for that answer rather than rewriting itself under the reader.
@@ -1,12 +1,30 @@
1
+ import { useEffect, useRef, useState } from 'react';
1
2
  import { Users } from 'lucide-react';
2
- import { Button, IconButton } from '../../../shared/components';
3
+ import { Button, IconButton, MenuPanel, buttonClasses, useDismissableMenu } from '../../../shared/components';
3
4
  import { useAdmin } from '../../admin/state/admin.context';
5
+ import { fetchAdmins, type AdminContact } from '../../access/api';
4
6
  import { useInviteDialog } from '../state/invite-dialog.context';
5
7
 
6
8
  /**
7
- * The toolbar's Invite button — admins only, because creating accounts is an
8
- * admin act and a button that answers "Admins only" is worse than none.
9
- * Opens the same dialog as the "Get set up" column's invite step.
9
+ * An email to one admin asking them to invite someone: the person only has
10
+ * to fill in who. The workspace's address is in it so the admin knows which
11
+ * workspace is meant.
12
+ */
13
+ function inviteRequestMailto(admin: AdminContact, origin: string): string {
14
+ const first = admin.name.split(/\s+/)[0] || admin.name;
15
+ const subject = 'Please invite someone to Hexis';
16
+ const body = `Hi ${first},\n\nCould you invite ... to our workspace at ${origin}?\n\nThanks`;
17
+ return `mailto:${admin.email}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
18
+ }
19
+
20
+ /**
21
+ * The toolbar's Invite button, shown to everyone signed in. An admin's click
22
+ * opens the Invite dialog — the same one as the "Get set up" column's invite
23
+ * step. Anyone else's opens a popover under the button saying only admins
24
+ * add people, and listing the admins, each with an Email button: a person
25
+ * who wants a colleague in learns how to get them in. The popover creates
26
+ * nothing, and closes like the profile menu (a click outside, or Escape,
27
+ * which hands focus back to the button).
10
28
  *
11
29
  * `compact` is the toolbar's narrow layout, where every control shares one
12
30
  * row with the essentials: the button sheds its word and keeps the icon, so
@@ -17,19 +35,105 @@ import { useInviteDialog } from '../state/invite-dialog.context';
17
35
  * tests and by hosts, and a button with nothing to open is a dead control.
18
36
  */
19
37
  export function InviteButton({ compact = false }: { compact?: boolean }) {
20
- const { isAdmin } = useAdmin();
38
+ const { isAdmin, isAdminLoading = false } = useAdmin();
21
39
  const invite = useInviteDialog();
22
- if (!isAdmin || !invite) return null;
23
- if (compact) {
24
- return (
25
- <IconButton aria-label="Invite" title="Invite" onClick={invite.open}>
26
- <Users size={16} aria-hidden />
27
- </IconButton>
28
- );
29
- }
30
- return (
31
- <Button size="sm" leadingIcon={<Users size={14} aria-hidden />} onClick={invite.open}>
40
+ const [asking, setAsking] = useState(false);
41
+ const triggerRef = useRef<HTMLButtonElement>(null);
42
+ const panelRef = useDismissableMenu<HTMLDivElement>({
43
+ open: asking,
44
+ onClose: () => setAsking(false),
45
+ returnFocusTo: triggerRef,
46
+ });
47
+ if (!invite) return null;
48
+
49
+ // While the admin check is still out the button is disabled, visibly,
50
+ // rather than showing an admin the ask-an-admin popover or answering a
51
+ // click with nothing.
52
+ const onClick = isAdmin ? () => invite.open() : () => setAsking((a) => !a);
53
+ const expanded = isAdmin || isAdminLoading ? undefined : asking;
54
+ const trigger = compact ? (
55
+ <IconButton
56
+ ref={triggerRef}
57
+ aria-label="Invite"
58
+ title="Invite"
59
+ aria-expanded={expanded}
60
+ disabled={isAdminLoading}
61
+ onClick={onClick}
62
+ >
63
+ <Users size={16} aria-hidden />
64
+ </IconButton>
65
+ ) : (
66
+ <Button
67
+ ref={triggerRef}
68
+ size="sm"
69
+ leadingIcon={<Users size={14} aria-hidden />}
70
+ aria-expanded={expanded}
71
+ disabled={isAdminLoading}
72
+ onClick={onClick}
73
+ >
32
74
  Invite
33
75
  </Button>
34
76
  );
77
+
78
+ return (
79
+ <div className="relative">
80
+ {trigger}
81
+ {asking && !isAdmin && (
82
+ <div ref={panelRef} className="absolute right-0 top-[calc(100%+5px)] z-40">
83
+ <AskAnAdmin />
84
+ </div>
85
+ )}
86
+ </div>
87
+ );
88
+ }
89
+
90
+ /**
91
+ * The popover's body. Reads the admins as it opens; when they cannot be
92
+ * read it keeps its two lines and lists nobody — the person still learns
93
+ * that only admins invite.
94
+ */
95
+ function AskAnAdmin() {
96
+ const [admins, setAdmins] = useState<AdminContact[] | null>(null);
97
+ useEffect(() => {
98
+ let cancelled = false;
99
+ fetchAdmins().then(
100
+ (list) => {
101
+ if (!cancelled) setAdmins(list);
102
+ },
103
+ () => {
104
+ if (!cancelled) setAdmins([]);
105
+ },
106
+ );
107
+ return () => {
108
+ cancelled = true;
109
+ };
110
+ }, []);
111
+ const origin = window.location.origin;
112
+ return (
113
+ // Never wider than the window: on a narrow toolbar the panel hangs off
114
+ // the button's right edge, and a fixed width would run off screen.
115
+ <MenuPanel role="group" aria-label="Ask an admin to invite people" className="w-80 max-w-[calc(100vw-1rem)] p-3">
116
+ <p className="text-strong font-semibold text-ink">Ask an admin to invite people</p>
117
+ <p className="mt-1 text-ui text-ink-muted">Only admins can add people to this workspace.</p>
118
+ {admins && admins.length > 0 && (
119
+ <ul aria-label="Admins" className="mt-3 max-h-64 overflow-y-auto border-t border-line pt-1.5">
120
+ {admins.map((admin) => (
121
+ <li key={admin.email} className="flex items-center gap-3 py-1.5">
122
+ <div className="min-w-0 flex-1">
123
+ <p className="truncate text-ui font-medium text-ink">{admin.name}</p>
124
+ <p className="truncate text-detail text-ink-muted">{admin.email}</p>
125
+ </div>
126
+ <a
127
+ href={inviteRequestMailto(admin, origin)}
128
+ aria-label={`Email ${admin.name}`}
129
+ className={buttonClasses({ variant: 'outline', size: 'sm' })}
130
+ >
131
+ Email
132
+ </a>
133
+ </li>
134
+ ))}
135
+ </ul>
136
+ )}
137
+ </MenuPanel>
138
+ );
35
139
  }