@blackbelt-technology/pi-dashboard-client-utils 0.10.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +3 -3
- package/src/ActionListMenuContext.ts +6 -1
- package/src/AgentCardShell.tsx +13 -3
- package/src/Confirm.tsx +7 -2
- package/src/Dialog.tsx +4 -1
- package/src/agent-card-utils.ts +7 -2
- package/src/identity/login-flow.ts +33 -0
- package/src/minimal-chat/MinimalChatView.tsx +13 -8
- package/src/minimal-chat/types.ts +4 -2
- package/src/useFocusTrap.ts +37 -4
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@blackbelt-technology/pi-dashboard-client-utils",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.0",
|
|
4
4
|
"description": "Small reusable React components, hooks, and helpers shared between the pi-dashboard shell and dashboard plugins. Per-subpath exports; no markdown stack.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"publishConfig": {
|
|
@@ -159,8 +159,8 @@
|
|
|
159
159
|
"react-dom": ">=18.0.0"
|
|
160
160
|
},
|
|
161
161
|
"dependencies": {
|
|
162
|
-
"@blackbelt-technology/dashboard-plugin-runtime": "^0.
|
|
163
|
-
"@blackbelt-technology/pi-dashboard-shared": "^0.
|
|
162
|
+
"@blackbelt-technology/dashboard-plugin-runtime": "^0.12.0",
|
|
163
|
+
"@blackbelt-technology/pi-dashboard-shared": "^0.12.0",
|
|
164
164
|
"@mdi/js": "^7.4.47",
|
|
165
165
|
"@mdi/react": "^1.6.1"
|
|
166
166
|
},
|
|
@@ -7,13 +7,18 @@
|
|
|
7
7
|
* hosting menu can close itself. `null` (the default) keeps the standalone
|
|
8
8
|
* horizontal-row rendering unchanged.
|
|
9
9
|
*
|
|
10
|
-
*
|
|
10
|
+
* `open` mirrors the hosting menu's open state, so a claim that stays mounted
|
|
11
|
+
* while the menu is closed can refresh its data when the menu opens.
|
|
12
|
+
*
|
|
13
|
+
* See change: add-session-actions-flyout; stop-flows-edit-mode-project-writes (D4).
|
|
11
14
|
*/
|
|
12
15
|
import { createContext } from "react";
|
|
13
16
|
|
|
14
17
|
export interface ActionListMenuContextValue {
|
|
15
18
|
/** Called after an enabled item was activated (handler already ran). */
|
|
16
19
|
onActivate?: () => void;
|
|
20
|
+
/** True while the hosting menu is open (undefined when the host does not report it). */
|
|
21
|
+
open?: boolean;
|
|
17
22
|
}
|
|
18
23
|
|
|
19
24
|
export const ActionListMenuContext = createContext<ActionListMenuContextValue | null>(null);
|
package/src/AgentCardShell.tsx
CHANGED
|
@@ -18,12 +18,22 @@ interface Props {
|
|
|
18
18
|
/** Whether the card is clickable/selected */
|
|
19
19
|
onClick?: () => void;
|
|
20
20
|
selected?: boolean;
|
|
21
|
+
/** Border accent replacing the status accent: `question` = purple (an open
|
|
22
|
+
* flow question). Selection still wins. See change: adopt-flow-parent-mailbox. */
|
|
23
|
+
accent?: "question";
|
|
21
24
|
/** Tool-specific content */
|
|
22
25
|
children?: ReactNode;
|
|
23
26
|
}
|
|
24
27
|
|
|
25
|
-
export function AgentCardShell({ name, status, headerRight, stats, onClick, selected, children }: Props) {
|
|
28
|
+
export function AgentCardShell({ name, status, headerRight, stats, onClick, selected, accent, children }: Props) {
|
|
26
29
|
const { icon, color } = getStatusIcon(status);
|
|
30
|
+
// The question accent replaces the status border; selection (blue) wins.
|
|
31
|
+
const statusBorder =
|
|
32
|
+
accent === "question"
|
|
33
|
+
? selected
|
|
34
|
+
? ""
|
|
35
|
+
: "border-[var(--accent-purple)]"
|
|
36
|
+
: `${status === "running" ? "border-yellow-500/30" : ""} ${status === "error" ? "border-red-500/30" : ""}`;
|
|
27
37
|
|
|
28
38
|
return (
|
|
29
39
|
<div
|
|
@@ -31,8 +41,8 @@ export function AgentCardShell({ name, status, headerRight, stats, onClick, sele
|
|
|
31
41
|
className={`rounded-lg border p-2.5 transition-all duration-150 flex flex-col
|
|
32
42
|
${onClick ? "cursor-pointer hover:shadow-md" : ""}
|
|
33
43
|
${selected ? "border-blue-500/60 bg-[var(--bg-surface)]" : "border-[var(--border-subtle)] bg-[color-mix(in_srgb,var(--bg-secondary),var(--bg-tertiary))]"}
|
|
34
|
-
${
|
|
35
|
-
${status === "
|
|
44
|
+
${statusBorder}
|
|
45
|
+
${status === "queued" ? "border-dashed !border-[var(--severity-neutral-border)]" : ""}
|
|
36
46
|
`}
|
|
37
47
|
>
|
|
38
48
|
{/* Header: icon + name + optional right content */}
|
package/src/Confirm.tsx
CHANGED
|
@@ -12,13 +12,16 @@ interface ConfirmProps {
|
|
|
12
12
|
confirmLabel?: string;
|
|
13
13
|
cancelLabel?: string;
|
|
14
14
|
onConfirm: () => void;
|
|
15
|
+
/** `"cancel"` puts initial focus on Cancel (use for destructive confirms). Unset = unchanged. */
|
|
16
|
+
defaultFocus?: "cancel";
|
|
15
17
|
testId?: string;
|
|
16
18
|
}
|
|
17
19
|
|
|
18
20
|
/**
|
|
19
21
|
* Thin preset over `Dialog` for the common title-message-confirm-cancel
|
|
20
22
|
* shape. Delegates all chrome (portal, overlay, focus, ARIA, dismissal) to
|
|
21
|
-
* `Dialog`.
|
|
23
|
+
* `Dialog`. An untitled confirm (title "") is named by its message (`aria-label`);
|
|
24
|
+
* `Dialog` ignores it when a title exists. `onConfirm` does NOT auto-close — the caller controls dismissal.
|
|
22
25
|
*
|
|
23
26
|
* See change: unify-dialog-system (design.md D7).
|
|
24
27
|
*/
|
|
@@ -32,15 +35,17 @@ export function Confirm({
|
|
|
32
35
|
confirmLabel = "Confirm",
|
|
33
36
|
cancelLabel = "Cancel",
|
|
34
37
|
onConfirm,
|
|
38
|
+
defaultFocus,
|
|
35
39
|
testId,
|
|
36
40
|
}: ConfirmProps) {
|
|
37
41
|
return (
|
|
38
|
-
<Dialog open={open} onClose={onClose} title={title} size="sm" testId={testId}>
|
|
42
|
+
<Dialog open={open} onClose={onClose} title={title} ariaLabel={message} size="sm" testId={testId}>
|
|
39
43
|
<p className="text-sm text-[var(--text-secondary)]">{message}</p>
|
|
40
44
|
{body}
|
|
41
45
|
<Dialog.Footer>
|
|
42
46
|
<Dialog.Cancel
|
|
43
47
|
onClick={onClose}
|
|
48
|
+
autoFocus={defaultFocus === "cancel"}
|
|
44
49
|
testId={testId ? `${testId}-cancel` : undefined}
|
|
45
50
|
>
|
|
46
51
|
{cancelLabel}
|
package/src/Dialog.tsx
CHANGED
|
@@ -179,14 +179,17 @@ interface DialogCancelProps {
|
|
|
179
179
|
onClick: () => void;
|
|
180
180
|
children?: ReactNode;
|
|
181
181
|
testId?: string;
|
|
182
|
+
/** Mark as the dialog's initial focus target (renders `data-autofocus`, read by `useFocusTrap`). */
|
|
183
|
+
autoFocus?: boolean;
|
|
182
184
|
}
|
|
183
185
|
|
|
184
|
-
function DialogCancel({ onClick, children = "Cancel", testId }: DialogCancelProps) {
|
|
186
|
+
function DialogCancel({ onClick, children = "Cancel", testId, autoFocus }: DialogCancelProps) {
|
|
185
187
|
return (
|
|
186
188
|
<button
|
|
187
189
|
type="button"
|
|
188
190
|
onClick={onClick}
|
|
189
191
|
data-testid={testId}
|
|
192
|
+
data-autofocus={autoFocus ? "" : undefined}
|
|
190
193
|
className={`${ACTION_BASE} border border-[var(--border-primary)] text-[var(--text-secondary)] hover:text-[var(--text-primary)]`}
|
|
191
194
|
>
|
|
192
195
|
{children}
|
package/src/agent-card-utils.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* Used by FlowAgentCard (flows) and AgentToolRenderer (subagents).
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
|
-
import { mdiAlertCircle, mdiCheckCircle, mdiCircleOutline, mdiCloseCircle, mdiLoading, mdiMinusCircleOutline, mdiPause, mdiStop } from "@mdi/js";
|
|
6
|
+
import { mdiAlertCircle, mdiCheckCircle, mdiCircleOutline, mdiClockOutline, mdiCloseCircle, mdiLoading, mdiMinusCircleOutline, mdiPause, mdiStop } from "@mdi/js";
|
|
7
7
|
import { Icon } from "@mdi/react";
|
|
8
8
|
import React, { type ReactNode } from "react";
|
|
9
9
|
|
|
@@ -19,7 +19,7 @@ export function formatDuration(ms: number): string {
|
|
|
19
19
|
return sec < 60 ? `${sec.toFixed(1)}s` : `${Math.floor(sec / 60)}m ${Math.floor(sec % 60)}s`;
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
-
export type AgentCardStatus = "pending" | "running" | "complete" | "error" | "blocked" | "stopped" | "background" | "elided";
|
|
22
|
+
export type AgentCardStatus = "pending" | "queued" | "running" | "complete" | "error" | "blocked" | "stopped" | "background" | "elided";
|
|
23
23
|
|
|
24
24
|
export interface StatusIconDef {
|
|
25
25
|
icon: ReactNode;
|
|
@@ -29,6 +29,11 @@ export interface StatusIconDef {
|
|
|
29
29
|
/** Status icon definitions for agent cards */
|
|
30
30
|
export const statusIconDefs: Record<string, StatusIconDef> = {
|
|
31
31
|
pending: { icon: React.createElement(Icon, { path: mdiCircleOutline, size: 0.55 }), color: "text-[var(--text-tertiary)]" },
|
|
32
|
+
/**
|
|
33
|
+
* Waiting for a concurrency slot: static clock, neutral token, never the
|
|
34
|
+
* running spinner. See change: subagent-queue-visibility (D7).
|
|
35
|
+
*/
|
|
36
|
+
queued: { icon: React.createElement(Icon, { path: mdiClockOutline, size: 0.55 }), color: "text-[var(--severity-neutral-fg)]" },
|
|
32
37
|
running: { icon: React.createElement(Icon, { path: mdiLoading, size: 0.55, className: "animate-spin" }), color: "text-yellow-400" },
|
|
33
38
|
complete: { icon: React.createElement(Icon, { path: mdiCheckCircle, size: 0.55 }), color: "text-green-400" },
|
|
34
39
|
error: { icon: React.createElement(Icon, { path: mdiCloseCircle, size: 0.55 }), color: "text-red-400" },
|
|
@@ -25,6 +25,7 @@
|
|
|
25
25
|
* (B4/LG-19): a plain bearer is stored, no key is persisted across the redirect.
|
|
26
26
|
*/
|
|
27
27
|
|
|
28
|
+
import { classifyUrl } from "@blackbelt-technology/pi-dashboard-shared/url-policy.js";
|
|
28
29
|
import { buildAuthorizeRequest, exchangeCode, type OidcClientConfig } from "./oidc-flow.js";
|
|
29
30
|
import { clearAccessToken, getIdToken, setAccessToken, setIdToken } from "./token-store.js";
|
|
30
31
|
|
|
@@ -74,6 +75,29 @@ export class LoginFlowError extends Error {
|
|
|
74
75
|
}
|
|
75
76
|
}
|
|
76
77
|
|
|
78
|
+
/**
|
|
79
|
+
* Discovery endpoints come from a fetched document, so they are untrusted
|
|
80
|
+
* navigation / fetch targets (harden-client-sinks D11): `https:` anywhere, or
|
|
81
|
+
* `http:` on a loopback host only. Classified with `origin = null` because the
|
|
82
|
+
* endpoints are absolute.
|
|
83
|
+
*/
|
|
84
|
+
function isAllowedOidcEndpoint(raw: unknown): boolean {
|
|
85
|
+
const cls = classifyUrl(raw, null);
|
|
86
|
+
if (cls === "loopback") return true;
|
|
87
|
+
if (cls !== "external") return false;
|
|
88
|
+
try {
|
|
89
|
+
return new URL((raw as string).trim()).protocol === "https:";
|
|
90
|
+
} catch {
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function assertDiscoveryEndpoints(disc: Discovery, keys: readonly (keyof Discovery)[]): void {
|
|
96
|
+
for (const k of keys) {
|
|
97
|
+
if (!isAllowedOidcEndpoint(disc[k])) throw new Error(`disallowed ${k}`);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
77
101
|
async function fetchJson<T>(url: string): Promise<T> {
|
|
78
102
|
const res = await fetch(url);
|
|
79
103
|
if (!res.ok) throw new Error(`fetch failed: ${res.status}`);
|
|
@@ -94,6 +118,12 @@ export async function beginLogin(returnTo: string): Promise<void> {
|
|
|
94
118
|
disc = await fetchJson<Discovery>(
|
|
95
119
|
`${cfg.issuer.replace(/\/+$/, "")}/.well-known/openid-configuration`,
|
|
96
120
|
);
|
|
121
|
+
assertDiscoveryEndpoints(
|
|
122
|
+
disc,
|
|
123
|
+
disc.end_session_endpoint === undefined
|
|
124
|
+
? ["authorization_endpoint", "token_endpoint"]
|
|
125
|
+
: ["authorization_endpoint", "token_endpoint", "end_session_endpoint"],
|
|
126
|
+
);
|
|
97
127
|
} catch (err) {
|
|
98
128
|
throw new LoginFlowError("discovery-failed", err);
|
|
99
129
|
}
|
|
@@ -122,6 +152,7 @@ export async function beginLogin(returnTo: string): Promise<void> {
|
|
|
122
152
|
redirectUri,
|
|
123
153
|
};
|
|
124
154
|
sessionStorage.setItem(STASH_KEY, JSON.stringify(stash));
|
|
155
|
+
// client-sinks: allow — authorization_endpoint passed isAllowedOidcEndpoint (classifyUrl) above
|
|
125
156
|
window.location.assign(req.url);
|
|
126
157
|
}
|
|
127
158
|
|
|
@@ -145,6 +176,7 @@ export async function beginLogout(): Promise<void> {
|
|
|
145
176
|
`${cfg.issuer.replace(/\/+$/, "")}/.well-known/openid-configuration`,
|
|
146
177
|
);
|
|
147
178
|
if (!disc.end_session_endpoint) throw new Error("no end_session_endpoint");
|
|
179
|
+
assertDiscoveryEndpoints(disc, ["end_session_endpoint"]);
|
|
148
180
|
} catch (err) {
|
|
149
181
|
throw new LoginFlowError("discovery-failed", err);
|
|
150
182
|
}
|
|
@@ -152,6 +184,7 @@ export async function beginLogout(): Promise<void> {
|
|
|
152
184
|
url.searchParams.set("client_id", cfg.clientId);
|
|
153
185
|
url.searchParams.set("post_logout_redirect_uri", `${window.location.origin}/`);
|
|
154
186
|
if (idToken) url.searchParams.set("id_token_hint", idToken);
|
|
187
|
+
// client-sinks: allow — end_session_endpoint passed isAllowedOidcEndpoint (classifyUrl) above
|
|
155
188
|
window.location.assign(url.toString());
|
|
156
189
|
}
|
|
157
190
|
|
|
@@ -29,6 +29,7 @@ import {
|
|
|
29
29
|
mdiCloseCircle,
|
|
30
30
|
mdiHeadLightbulb,
|
|
31
31
|
mdiPencil,
|
|
32
|
+
mdiStopCircleOutline,
|
|
32
33
|
} from "@mdi/js";
|
|
33
34
|
import { Icon } from "@mdi/react";
|
|
34
35
|
import React from "react";
|
|
@@ -62,6 +63,9 @@ export function statusVisualsFor(status: MinimalChatStatus): {
|
|
|
62
63
|
return { iconPath: mdiAlertCircle, colorClass: "text-orange-400" };
|
|
63
64
|
case "pending":
|
|
64
65
|
return { iconPath: mdiCircleOutline, colorClass: "text-[var(--text-tertiary)]" };
|
|
66
|
+
case "stopped":
|
|
67
|
+
// Neutral and final: never the success check, never error red.
|
|
68
|
+
return { iconPath: mdiStopCircleOutline, colorClass: "text-[var(--severity-neutral-fg)]" };
|
|
65
69
|
default: {
|
|
66
70
|
// Exhaustive check — TS will error if a new MinimalChatStatus branch
|
|
67
71
|
// is missed. The runtime fallback is the same as "pending".
|
|
@@ -398,7 +402,7 @@ export function MinimalChatView({
|
|
|
398
402
|
<span className="text-[11px] text-[var(--text-muted)] ml-auto whitespace-nowrap">
|
|
399
403
|
{meta?.tokens && (
|
|
400
404
|
<>
|
|
401
|
-
|
|
405
|
+
↓{formatTokens(meta.tokens.input ?? 0)} ↑{formatTokens(meta.tokens.output ?? 0)}
|
|
402
406
|
{(meta.cost !== undefined || meta.durationMs !== undefined) && " · "}
|
|
403
407
|
</>
|
|
404
408
|
)}
|
|
@@ -410,16 +414,17 @@ export function MinimalChatView({
|
|
|
410
414
|
</div>
|
|
411
415
|
);
|
|
412
416
|
|
|
413
|
-
// Inline mode
|
|
414
|
-
//
|
|
415
|
-
// `flex-1 min-h-0 overflow-y-auto` (below)
|
|
416
|
-
//
|
|
417
|
+
// Inline mode sizes to its content, capped at `max-h-[60vh]`: a fixed
|
|
418
|
+
// height left a large blank area under short content (#1083). The body's
|
|
419
|
+
// `flex-1 min-h-0 overflow-y-auto` (below) scrolls once the cap is reached.
|
|
420
|
+
// Streaming growth is monotone per entry; the live tail is clamped by
|
|
421
|
+
// `LiveEntry` (`max-h-36`), so no bounce.
|
|
417
422
|
//
|
|
418
|
-
// See change: fix-
|
|
423
|
+
// See change: fix-chat-transcript-layout (D3; was fix-flows-plugin-polish).
|
|
419
424
|
const containerClasses =
|
|
420
425
|
mode === "popout"
|
|
421
426
|
? "flex flex-col h-full overflow-hidden"
|
|
422
|
-
: "flex flex-col h-[60vh] overflow-hidden";
|
|
427
|
+
: "flex flex-col max-h-[60vh] overflow-hidden";
|
|
423
428
|
|
|
424
429
|
// Newest reasoning entry opens on mount while the producer is live, so a
|
|
425
430
|
// just-finished block stays readable (main-chat parity). Mount-time only.
|
|
@@ -473,7 +478,7 @@ export function MinimalChatView({
|
|
|
473
478
|
);
|
|
474
479
|
|
|
475
480
|
return (
|
|
476
|
-
<div className={containerClasses}>
|
|
481
|
+
<div className={containerClasses} data-testid="minimal-chat-view" data-mode={mode}>
|
|
477
482
|
{header}
|
|
478
483
|
{body}
|
|
479
484
|
</div>
|
|
@@ -17,7 +17,8 @@ export type MinimalChatMode = "inline" | "popout" | "row";
|
|
|
17
17
|
* status enum into this union; the view never sees producer-specific tokens.
|
|
18
18
|
*
|
|
19
19
|
* Mapping tables (see design §Decision 2):
|
|
20
|
-
* - SubagentState: created → pending, running → running, completed → complete, failed → error
|
|
20
|
+
* - SubagentState: created → pending, running → running, completed → complete, failed → error,
|
|
21
|
+
* stopped → stopped (neutral, final; see change: subagent-queue-visibility)
|
|
21
22
|
* - FlowAgentState: identity (already uses these tokens)
|
|
22
23
|
*/
|
|
23
24
|
export type MinimalChatStatus =
|
|
@@ -25,7 +26,8 @@ export type MinimalChatStatus =
|
|
|
25
26
|
| "running"
|
|
26
27
|
| "complete"
|
|
27
28
|
| "error"
|
|
28
|
-
| "blocked"
|
|
29
|
+
| "blocked"
|
|
30
|
+
| "stopped";
|
|
29
31
|
|
|
30
32
|
/**
|
|
31
33
|
* One timeline entry. The discriminated union is the structural intersection
|
package/src/useFocusTrap.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { type RefObject, useEffect } from "react";
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Focus management for modal dialogs.
|
|
5
5
|
*
|
|
6
6
|
* On `open` transition to true: stores the previously-focused element,
|
|
7
|
-
* moves focus to the first focusable child inside `ref`
|
|
7
|
+
* moves focus to the first focusable child inside `ref` — preferring one
|
|
8
|
+
* marked `data-autofocus` — (or the container
|
|
8
9
|
* itself if none), and traps `Tab` / `Shift+Tab` within the container.
|
|
9
10
|
* On close (or unmount): restores focus to the previously-focused element
|
|
10
11
|
* if it is still in the document.
|
|
@@ -41,6 +42,34 @@ function isHiddenWithin(el: HTMLElement, container: HTMLElement): boolean {
|
|
|
41
42
|
return false;
|
|
42
43
|
}
|
|
43
44
|
|
|
45
|
+
/**
|
|
46
|
+
* Initial focus target: the first visible `[data-autofocus]` control when one
|
|
47
|
+
* is present (an opt-in, e.g. `Dialog.Cancel autoFocus`), else the first
|
|
48
|
+
* focusable. Tab containment still walks the full focusable list.
|
|
49
|
+
* See change: sidebar-folder-ux.
|
|
50
|
+
*/
|
|
51
|
+
function pickInitialFocus(focusable: HTMLElement[], container: HTMLElement): HTMLElement | undefined {
|
|
52
|
+
return focusable.find((el) => el.hasAttribute("data-autofocus") && isRendered(el, container)) ?? focusable[0];
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** False when the element or an ancestor inside the container is CSS-hidden (`display: none`), so it cannot take focus. */
|
|
56
|
+
function isRendered(el: HTMLElement, container: HTMLElement): boolean {
|
|
57
|
+
let node: HTMLElement | null = el;
|
|
58
|
+
while (node && node !== container) {
|
|
59
|
+
if (getComputedStyle(node).display === "none") return false;
|
|
60
|
+
node = node.parentElement;
|
|
61
|
+
}
|
|
62
|
+
return true;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Open traps, oldest first. Every trap listens on `document`, so with two open (a plugin dialog above the
|
|
67
|
+
* Settings overlay) each would drag focus into ITS container on Tab and the last listener would win — Tab then
|
|
68
|
+
* pinned focus on the top dialog's first control. Only the topmost trap acts. See change: add-google-connect
|
|
69
|
+
* (test-plan #B52, keyboard reachability of the data-use link).
|
|
70
|
+
*/
|
|
71
|
+
const openTraps: HTMLElement[] = [];
|
|
72
|
+
|
|
44
73
|
export function useFocusTrap(
|
|
45
74
|
ref: RefObject<HTMLElement | null>,
|
|
46
75
|
open: boolean,
|
|
@@ -51,6 +80,7 @@ export function useFocusTrap(
|
|
|
51
80
|
if (!container) return;
|
|
52
81
|
|
|
53
82
|
const previouslyFocused = document.activeElement as HTMLElement | null;
|
|
83
|
+
openTraps.push(container);
|
|
54
84
|
|
|
55
85
|
const focusable = getFocusable(container);
|
|
56
86
|
// When a child renders NOTHING focusable on its first paint, the container
|
|
@@ -64,7 +94,7 @@ export function useFocusTrap(
|
|
|
64
94
|
// See change: fix-flush-dialog-scroll-and-close-collision.
|
|
65
95
|
let observer: MutationObserver | undefined;
|
|
66
96
|
if (focusable.length > 0) {
|
|
67
|
-
focusable
|
|
97
|
+
pickInitialFocus(focusable, container)?.focus();
|
|
68
98
|
} else {
|
|
69
99
|
container.focus();
|
|
70
100
|
if (typeof MutationObserver !== "undefined") {
|
|
@@ -76,7 +106,7 @@ export function useFocusTrap(
|
|
|
76
106
|
const late = getFocusable(container);
|
|
77
107
|
if (late.length === 0) return;
|
|
78
108
|
observer?.disconnect();
|
|
79
|
-
late
|
|
109
|
+
pickInitialFocus(late, container)?.focus();
|
|
80
110
|
});
|
|
81
111
|
// Attributes matter as much as insertion: `getFocusable` keys on
|
|
82
112
|
// `:not([disabled])`, `[hidden]` and `aria-hidden`, so a button that is
|
|
@@ -101,6 +131,7 @@ export function useFocusTrap(
|
|
|
101
131
|
if (e.key !== "Tab") return;
|
|
102
132
|
const node = ref.current;
|
|
103
133
|
if (!node) return;
|
|
134
|
+
if (openTraps[openTraps.length - 1] !== node) return;
|
|
104
135
|
const items = getFocusable(node);
|
|
105
136
|
if (items.length === 0) {
|
|
106
137
|
e.preventDefault();
|
|
@@ -128,6 +159,8 @@ export function useFocusTrap(
|
|
|
128
159
|
return () => {
|
|
129
160
|
observer?.disconnect();
|
|
130
161
|
document.removeEventListener("keydown", onKeyDown, true);
|
|
162
|
+
const at = openTraps.lastIndexOf(container);
|
|
163
|
+
if (at >= 0) openTraps.splice(at, 1);
|
|
131
164
|
if (previouslyFocused && document.contains(previouslyFocused)) {
|
|
132
165
|
previouslyFocused.focus();
|
|
133
166
|
}
|