@blackbelt-technology/pi-dashboard-client-utils 0.7.0 → 0.9.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.
@@ -23,7 +23,22 @@ const FOCUSABLE_SELECTOR = [
23
23
  function getFocusable(container: HTMLElement): HTMLElement[] {
24
24
  return Array.from(
25
25
  container.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR),
26
- ).filter((el) => !el.hasAttribute("hidden") && el.getAttribute("aria-hidden") !== "true");
26
+ ).filter((el) => !isHiddenWithin(el, container));
27
+ }
28
+
29
+ /**
30
+ * `hidden` / `aria-hidden` on an ANCESTOR hides the element just as effectively
31
+ * as on the element itself, so checking only the candidate's own attributes
32
+ * would let focus land inside a subtree assistive technology cannot see. Walk
33
+ * up to (and excluding) the container, which is where this dialog's world ends.
34
+ */
35
+ function isHiddenWithin(el: HTMLElement, container: HTMLElement): boolean {
36
+ let node: HTMLElement | null = el;
37
+ while (node && node !== container) {
38
+ if (node.hasAttribute("hidden") || node.getAttribute("aria-hidden") === "true") return true;
39
+ node = node.parentElement;
40
+ }
41
+ return false;
27
42
  }
28
43
 
29
44
  export function useFocusTrap(
@@ -38,10 +53,48 @@ export function useFocusTrap(
38
53
  const previouslyFocused = document.activeElement as HTMLElement | null;
39
54
 
40
55
  const focusable = getFocusable(container);
56
+ // When a child renders NOTHING focusable on its first paint, the container
57
+ // fallback below fires and focus is stranded on a non-interactive box even
58
+ // though the surface fills with controls a tick later. That was masked while
59
+ // every dialog rendered a built-in ✕ (always focusable[0]); suppressing it
60
+ // for `flush` surfaces exposed it — measured on `/settings/general`, which
61
+ // reaches 51 focusables but has 0 at mount. Watch for the first one and
62
+ // hand focus over, at most once, and only while focus is still parked on
63
+ // the container (never steal it back from the user).
64
+ // See change: fix-flush-dialog-scroll-and-close-collision.
65
+ let observer: MutationObserver | undefined;
41
66
  if (focusable.length > 0) {
42
67
  focusable[0].focus();
43
68
  } else {
44
69
  container.focus();
70
+ if (typeof MutationObserver !== "undefined") {
71
+ observer = new MutationObserver(() => {
72
+ if (document.activeElement !== container) {
73
+ observer?.disconnect();
74
+ return;
75
+ }
76
+ const late = getFocusable(container);
77
+ if (late.length === 0) return;
78
+ observer?.disconnect();
79
+ late[0].focus();
80
+ });
81
+ // Attributes matter as much as insertion: `getFocusable` keys on
82
+ // `:not([disabled])`, `[hidden]` and `aria-hidden`, so a button that is
83
+ // rendered DISABLED at mount and enables when data lands is a focusable
84
+ // that appears without any node being inserted (`href` likewise, for
85
+ // an anchor that gains one). Watching childList alone would strand
86
+ // focus in exactly that case.
87
+ //
88
+ // Cost is bounded by construction: the observer only exists for a
89
+ // dialog that opened with ZERO focusables, and it disconnects on the
90
+ // first one it finds (or the moment focus leaves the container).
91
+ observer.observe(container, {
92
+ childList: true,
93
+ subtree: true,
94
+ attributes: true,
95
+ attributeFilter: ["disabled", "hidden", "aria-hidden", "tabindex", "href"],
96
+ });
97
+ }
45
98
  }
46
99
 
47
100
  function onKeyDown(e: KeyboardEvent) {
@@ -73,6 +126,7 @@ export function useFocusTrap(
73
126
  document.addEventListener("keydown", onKeyDown, true);
74
127
 
75
128
  return () => {
129
+ observer?.disconnect();
76
130
  document.removeEventListener("keydown", onKeyDown, true);
77
131
  if (previouslyFocused && document.contains(previouslyFocused)) {
78
132
  previouslyFocused.focus();
package/src/useZoomPan.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { useCallback, useRef, useState } from "react";
1
+ import type React from "react";
2
+ import { useCallback, useLayoutEffect, useRef, useState } from "react";
2
3
 
3
4
  export interface ZoomPanState {
4
5
  scale: number;
@@ -10,6 +11,13 @@ export interface UseZoomPanOptions {
10
11
  minScale?: number;
11
12
  maxScale?: number;
12
13
  zoomStep?: number;
14
+ /**
15
+ * Scale the surface starts at and that reset / double-click return to.
16
+ * Clamped into [minScale, maxScale]; defaults to 1. While the user has not
17
+ * interacted, a changed value re-seeds the view (fit may resolve async).
18
+ * See change: fix-markdown-remount-storm (D4).
19
+ */
20
+ initialScale?: number;
13
21
  }
14
22
 
15
23
  const DEFAULT_MIN = 0.5;
@@ -26,7 +34,23 @@ export function useZoomPan(options?: UseZoomPanOptions) {
26
34
  const maxScale = options?.maxScale ?? DEFAULT_MAX;
27
35
  const zoomStep = options?.zoomStep ?? DEFAULT_STEP;
28
36
 
29
- const [state, setState] = useState<ZoomPanState>({ scale: 1, translateX: 0, translateY: 0 });
37
+ const initialScale = Math.min(maxScale, Math.max(minScale, options?.initialScale ?? 1));
38
+
39
+ const [state, rawSetState] = useState<ZoomPanState>({ scale: initialScale, translateX: 0, translateY: 0 });
40
+ // True once the user zoomed/panned; a late initialScale change must not override that.
41
+ const touched = useRef(false);
42
+ const setState = useCallback((u: React.SetStateAction<ZoomPanState>) => {
43
+ touched.current = true;
44
+ rawSetState(u);
45
+ }, []);
46
+ const resetToInitial = useCallback(() => {
47
+ touched.current = false;
48
+ rawSetState({ scale: initialScale, translateX: 0, translateY: 0 });
49
+ }, [initialScale]);
50
+
51
+ useLayoutEffect(() => {
52
+ if (!touched.current) rawSetState({ scale: initialScale, translateX: 0, translateY: 0 });
53
+ }, [initialScale]);
30
54
 
31
55
  // Refs for drag tracking (avoid re-renders during drag)
32
56
  const dragging = useRef(false);
@@ -59,7 +83,7 @@ export function useZoomPan(options?: UseZoomPanOptions) {
59
83
  };
60
84
  });
61
85
  },
62
- [clampScale],
86
+ [clampScale, setState],
63
87
  );
64
88
 
65
89
  // ── Wheel handler ──────────────────────────────────────────────────
@@ -108,7 +132,7 @@ export function useZoomPan(options?: UseZoomPanOptions) {
108
132
  translateX: prev.translateX + dx,
109
133
  translateY: prev.translateY + dy,
110
134
  }));
111
- }, []);
135
+ }, [setState]);
112
136
 
113
137
  const onPointerUp = useCallback(() => {
114
138
  dragging.current = false;
@@ -142,9 +166,7 @@ export function useZoomPan(options?: UseZoomPanOptions) {
142
166
  }, []);
143
167
 
144
168
  // ── Double-click reset ─────────────────────────────────────────────
145
- const onDoubleClick = useCallback(() => {
146
- setState({ scale: 1, translateX: 0, translateY: 0 });
147
- }, []);
169
+ const onDoubleClick = resetToInitial;
148
170
 
149
171
  // ── Button controls ────────────────────────────────────────────────
150
172
  const zoomIn = useCallback(() => {
@@ -152,18 +174,16 @@ export function useZoomPan(options?: UseZoomPanOptions) {
152
174
  const newScale = clampScale(prev.scale * zoomStep);
153
175
  return { ...prev, scale: newScale };
154
176
  });
155
- }, [clampScale, zoomStep]);
177
+ }, [clampScale, zoomStep, setState]);
156
178
 
157
179
  const zoomOut = useCallback(() => {
158
180
  setState((prev) => {
159
181
  const newScale = clampScale(prev.scale / zoomStep);
160
182
  return { ...prev, scale: newScale };
161
183
  });
162
- }, [clampScale, zoomStep]);
184
+ }, [clampScale, zoomStep, setState]);
163
185
 
164
- const reset = useCallback(() => {
165
- setState({ scale: 1, translateX: 0, translateY: 0 });
166
- }, []);
186
+ const reset = resetToInitial;
167
187
 
168
188
  const handlers = {
169
189
  onWheel,
@@ -175,5 +195,5 @@ export function useZoomPan(options?: UseZoomPanOptions) {
175
195
  onDoubleClick,
176
196
  };
177
197
 
178
- return { state, handlers, zoomIn, zoomOut, reset };
198
+ return { state, handlers, zoomIn, zoomOut, reset, initialScale };
179
199
  }
package/src/AGENTS.md DELETED
@@ -1,25 +0,0 @@
1
- # DOX — packages/client-utils/src
2
-
3
- Files in this directory. One row per source file.
4
-
5
- | File | Purpose |
6
- |------|---------|
7
- | `ActionList.tsx` | `ui:action-list` primitive. Exports `ActionList({ actions })` — horizontal row of MDI-icon + label buttons. `ExtendedActionItem` carries `dataAction` (pluginId/sessionId/action/payload) dispatched via `sendPluginAction`, or classical `onClick`. `IconByKey` reads `@mdi/js` eagerly (statically imported across the shell — synchronous flat property lookup, no dynamic import) and looks up path by export-name key. See change: shrink-client-index-chunk. |
8
- | `agent-card-utils.ts` | Shared helpers for agent card rendering. Exports `formatTokens`, `formatDuration`, `AgentCardStatus` type, `StatusIconDef`, `statusIconDefs` (pending/running/complete/error/blocked/stopped/background → MDI icon + color), `getStatusIcon`. Used by `FlowAgentCard` and `AgentToolRenderer`. |
9
- | `AgentCardShell.tsx` | Exports `AgentCardShell` — reusable card container with status-colored border, header row (status icon + name + optional `headerRight`), optional `stats` line, clickable/selected states. `getStatusIcon` drives icon + border color. Consumers pass tool-specific content as children. |
10
- | `Confirm.tsx` | Confirm preset over Dialog (size sm). Props `{open,onClose,title,message,body?,intent?,confirmLabel?,cancelLabel?,onConfirm,testId?}`. Action → onConfirm only (no auto-close); cancel/Esc/overlay → onClose. Replaces legacy ConfirmDialog. See change: unify-dialog-system. |
11
- | `Dialog.tsx` | Unified modal shell. Props `{open,onClose,title?,icon?,size?,testId?,ariaLabel?,children}`. Owns DialogPortal, overlay `bg-black/60`, Esc via shared escape-stack (`useEscapeDismiss(open,onClose)` — onClose fires on Escape only when topmost registered layer; overlay opened above consumes it first), click-outside, focus trap (useFocusTrap), `role="dialog"`/`aria-modal`/`aria-labelledby`, `z-[60]`, size sm/md/lg → max-w-sm/md/lg, `max-h-[80vh]`. Renders standard ✕ close button (absolute top-right, testId `<testId>-close`) on every dialog incl. flush/headerless. Static subcomponents `Dialog.Footer`/`Dialog.Cancel`/`Dialog.Action` (intent primary\|danger\|neutral). See change: unify-dialog-system. |
12
- | `DialogPortal.tsx` | Exports `DialogPortal` — `createPortal` to `document.body`. Hides body scroll (`overflow: hidden`) on mount, restores prior value on unmount. |
13
- | `EmptyState.tsx` | EmptyState primitive. Props `{title, body?, icon?, action?, secondaryAction?}`. Single `action` prop enforces one-primary-CTA. Renders NN/g empty-state pattern: value-framed heading, optional body, ≤1 primary CTA, ≤1 secondary escape-hatch. data-empty-state markers. See change: extend-client-utils-state-feedback-primitives. |
14
- | `escape-stack.ts` | Shared escape-dismiss stack. Single module-stable `document`-bubble `keydown` listener + LIFO registry; Escape invokes `onEscape` of topmost registered layer only, then `preventDefault`+`stopImmediatePropagation`; guards `e.repeat`+`e.defaultPrevented`. Attach-once/never-detach (early-returns on empty). Exports `useEscapeDismiss(active,onEscape)` (`useId`-stable id, ref-backed onEscape, remove-by-id), `registerEscapeLayer`/`unregisterEscapeLayer`, `__resetEscapeStack` (test-only, prod no-op). See change: fix-stacked-escape-closes-layers. |
15
- | `focusRing.ts` | Exports `focusRing` = "focus-ring" className string. Points at `.focus-ring` utility in packages/client/src/index.css (:focus-visible, 2px outline, 2px offset, var(--focus-ring) color). Replaces ad-hoc focus:outline-none + 1px border. WCAG 2.2 §2.4.7/§2.4.11. See change: extend-client-utils-state-feedback-primitives. |
16
- | `Popover.tsx` | `ui:popover` primitive. Exports `Popover`, `PopoverProps`, `computePopoverPosition` (pure). Anchors floating panel to `anchorEl`'s rect; flips above on bottom overflow, shifts left on right overflow; recomputes on resize/scroll. Dismisses on outside mousedown or Escape. Body portal, not modal/scroll-lock/tooltip. |
17
- | `SearchableSelectDialog.tsx` | Exports `SearchableSelectDialog`, `SelectOption`. Filterable list inside `Dialog` (size `sm`). Arrow/Enter/Esc keyboard nav, scrolls selected into view, optional badge. Used for single-select choices. |
18
- | `Skeleton.tsx` | Skeleton primitive for content-layout loads. Props `{variant=text\|card\|bubble\|row, count?}`. Honors prefers-reduced-motion via useMediaQuery (static, no animate-pulse). aria-hidden. data-skeleton / data-skeleton-item / data-static markers. See change: extend-client-utils-state-feedback-primitives. |
19
- | `StatusPill.tsx` | `ui:status-pill` primitive. Exports `StatusPill({ state, text, icon?, tooltip? })` — state-tinted pill. `STATE_STYLE_DARK`/`STATE_STYLE_LIGHT` palettes keyed by `UiStatusPillState` (running/success/info/warn/error/muted). `useIsLightTheme` observes `data-theme` attr. `IconByKey` reads `@mdi/js` eagerly (statically imported across the shell — synchronous flat lookup, no dynamic import). See change: shrink-client-index-chunk. |
20
- | `statusPresentation.ts` | `statusPresentation(kind)` maps StatusKind (done\|current\|todo\|error) to `{glyph, tokenVar, label}`. Glyph = mandatory non-hue channel (✓ done, ▸ current, ○ todo, ✕ error). tokenVar references semantic --status-* / --text-muted token. `statusAriaLabel(name, kind)` returns "Name, label". WCAG 2.2 §1.4.1. Consumed by composer ArtifactChip + board BoardStatePill. See change: extend-client-utils-state-feedback-primitives. |
21
- | `useFocusTrap.ts` | `useFocusTrap(ref,open)` hook. Stores prev activeElement, focuses first focusable child on open, traps Tab/Shift+Tab, restores focus on close. See change: unify-dialog-system. |
22
- | `useMediaQuery.ts` | Reactive CSS media-query hook. Returns match boolean. Guards missing window.matchMedia (returns false). See change: extend-client-utils-state-feedback-primitives. |
23
- | `useMobile.tsx` | Exports `MobileProvider` + `useMobile`. `MobileContext` provides boolean: viewport `max-width: 767px` OR `max-height: 599px` (catches landscape phones). Backed by `useMediaQuery`. |
24
- | `useZoomPan.ts` | Exports `useZoomPan`, `ZoomPanState`, `UseZoomPanOptions`. State `{ scale, translateX, translateY }`. Wheel zoom centered on cursor, pointer drag pan (deferred capture past `DRAG_THRESHOLD` so clicks reach children), pinch zoom, double-click reset, `zoomIn`/`zoomOut`/`reset` controls. Clamp `minScale`/`maxScale`. Used by `MermaidBlock`, `FlowGraph`. |
25
- | `ZoomControls.tsx` | Exports `ZoomControls({ onZoomIn, onZoomOut, onReset, scale })` — top-right overlay buttons (zoom in/out/reset) using MDI icons, percent readout when `scale !== 1`. Shared by `MermaidBlock` and `FlowGraph`. Stops pointer propagation. |
@@ -1,72 +0,0 @@
1
- import React from "react";
2
- import { describe, it, expect, vi, afterEach } from "vitest";
3
- import { render, fireEvent, cleanup } from "@testing-library/react";
4
- import { ActionList } from "../ActionList.js";
5
-
6
- afterEach(() => cleanup());
7
-
8
- describe("ActionList", () => {
9
- it("renders nothing for empty actions", () => {
10
- const { container } = render(<ActionList actions={[]} />);
11
- expect(container.firstChild).toBeNull();
12
- });
13
-
14
- it("renders each action as a button", () => {
15
- const { getAllByRole } = render(
16
- <ActionList
17
- actions={[
18
- { label: "Run A" },
19
- { label: "Run B" },
20
- ]}
21
- />,
22
- );
23
- const buttons = getAllByRole("button");
24
- expect(buttons).toHaveLength(2);
25
- expect(buttons[0].textContent).toContain("Run A");
26
- expect(buttons[1].textContent).toContain("Run B");
27
- });
28
-
29
- it("clicking calls onClick", () => {
30
- const onClick = vi.fn();
31
- const { getByRole } = render(
32
- <ActionList actions={[{ label: "Run", onClick }]} />,
33
- );
34
- fireEvent.click(getByRole("button"));
35
- expect(onClick).toHaveBeenCalledTimes(1);
36
- });
37
-
38
- it("disabled buttons do not trigger onClick", () => {
39
- const onClick = vi.fn();
40
- const { getByRole } = render(
41
- <ActionList actions={[{ label: "Run", onClick, disabled: true }]} />,
42
- );
43
- fireEvent.click(getByRole("button"));
44
- expect(onClick).not.toHaveBeenCalled();
45
- });
46
-
47
- it("tooltip is set from `tooltip` prop", () => {
48
- const { getByRole } = render(
49
- <ActionList actions={[{ label: "Run", tooltip: "Run flow X" }]} />,
50
- );
51
- expect(getByRole("button").getAttribute("title")).toBe("Run flow X");
52
- });
53
-
54
- // Post static-conversion (change: shrink-client-index-chunk): mdi[key] is a
55
- // synchronous lookup, so the icon path renders immediately with no useEffect.
56
- it("renders the icon <path> synchronously for a valid mdi key (test-plan #S3)", () => {
57
- const { container } = render(
58
- <ActionList actions={[{ label: "Refresh", icon: "mdiRefresh" }]} />,
59
- );
60
- const p = container.querySelector("svg path");
61
- expect(p).toBeTruthy();
62
- expect(p?.getAttribute("d") ?? "").not.toBe("");
63
- });
64
-
65
- it("renders no icon and does not throw for an unknown mdi key (test-plan #S3)", () => {
66
- const { container } = render(
67
- <ActionList actions={[{ label: "Nope", icon: "mdiNotAReal" }]} />,
68
- );
69
- expect(container.querySelector("svg path")).toBeNull();
70
- expect(container.querySelector("button")?.textContent).toContain("Nope");
71
- });
72
- });
@@ -1,105 +0,0 @@
1
- import { describe, it, expect, afterEach, vi } from "vitest";
2
- import { render, cleanup, fireEvent } from "@testing-library/react";
3
- import React from "react";
4
- import { Confirm } from "../Confirm.js";
5
-
6
- afterEach(() => cleanup());
7
-
8
- describe("Confirm", () => {
9
- it("renders title and message", () => {
10
- const { getByText, baseElement } = render(
11
- <Confirm
12
- open
13
- onClose={() => {}}
14
- onConfirm={() => {}}
15
- title="Forget workspace?"
16
- message="This cannot be undone."
17
- testId="c"
18
- />,
19
- );
20
- expect(getByText("Forget workspace?")).toBeTruthy();
21
- expect(getByText("This cannot be undone.")).toBeTruthy();
22
- const container = baseElement.querySelector("[data-testid='c']")!;
23
- expect(container.getAttribute("aria-labelledby")).toBeTruthy();
24
- });
25
-
26
- it("renders optional body node", () => {
27
- const { getByTestId } = render(
28
- <Confirm
29
- open
30
- onClose={() => {}}
31
- onConfirm={() => {}}
32
- title="t"
33
- message="m"
34
- body={<ul data-testid="files" />}
35
- />,
36
- );
37
- expect(getByTestId("files")).toBeTruthy();
38
- });
39
-
40
- it("uses default labels", () => {
41
- const { getByText } = render(
42
- <Confirm open onClose={() => {}} onConfirm={() => {}} title="t" message="m" />,
43
- );
44
- expect(getByText("Confirm")).toBeTruthy();
45
- expect(getByText("Cancel")).toBeTruthy();
46
- });
47
-
48
- it("uses custom labels", () => {
49
- const { getByText } = render(
50
- <Confirm
51
- open
52
- onClose={() => {}}
53
- onConfirm={() => {}}
54
- title="t"
55
- message="m"
56
- confirmLabel="Forget"
57
- cancelLabel="Keep"
58
- />,
59
- );
60
- expect(getByText("Forget")).toBeTruthy();
61
- expect(getByText("Keep")).toBeTruthy();
62
- });
63
-
64
- it("maps danger intent to action button class", () => {
65
- const { baseElement } = render(
66
- <Confirm
67
- open
68
- onClose={() => {}}
69
- onConfirm={() => {}}
70
- title="t"
71
- message="m"
72
- intent="danger"
73
- testId="c"
74
- />,
75
- );
76
- expect(
77
- baseElement.querySelector("[data-testid='c-action']")!.className,
78
- ).toContain("bg-red-600");
79
- });
80
-
81
- it("action calls onConfirm only; cancel/Esc call onClose only", () => {
82
- const onConfirm = vi.fn();
83
- const onClose = vi.fn();
84
- const { baseElement } = render(
85
- <Confirm
86
- open
87
- onClose={onClose}
88
- onConfirm={onConfirm}
89
- title="t"
90
- message="m"
91
- testId="c"
92
- />,
93
- );
94
- fireEvent.click(baseElement.querySelector("[data-testid='c-action']")!);
95
- expect(onConfirm).toHaveBeenCalledTimes(1);
96
- expect(onClose).not.toHaveBeenCalled();
97
-
98
- fireEvent.click(baseElement.querySelector("[data-testid='c-cancel']")!);
99
- expect(onClose).toHaveBeenCalledTimes(1);
100
-
101
- fireEvent.keyDown(document, { key: "Escape" });
102
- expect(onClose).toHaveBeenCalledTimes(2);
103
- expect(onConfirm).toHaveBeenCalledTimes(1);
104
- });
105
- });
@@ -1,215 +0,0 @@
1
- import { describe, it, expect, afterEach, vi } from "vitest";
2
- import { render, cleanup, fireEvent } from "@testing-library/react";
3
- import React from "react";
4
- import { mdiAlert } from "@mdi/js";
5
- import { Dialog } from "../Dialog.js";
6
-
7
- afterEach(() => cleanup());
8
-
9
- describe("Dialog", () => {
10
- it("renders nothing when closed", () => {
11
- const { baseElement } = render(
12
- <Dialog open={false} onClose={() => {}} testId="d">
13
- <p>hi</p>
14
- </Dialog>,
15
- );
16
- expect(baseElement.querySelector("[data-testid='d']")).toBeNull();
17
- });
18
-
19
- it("renders at document.body via portal when open", () => {
20
- const { baseElement } = render(
21
- <Dialog open onClose={() => {}} testId="d">
22
- <p>body</p>
23
- </Dialog>,
24
- );
25
- const container = baseElement.querySelector("[data-testid='d']");
26
- expect(container).toBeTruthy();
27
- expect(container!.getAttribute("role")).toBe("dialog");
28
- expect(container!.getAttribute("aria-modal")).toBe("true");
29
- });
30
-
31
- it("calls onClose on Esc", () => {
32
- const onClose = vi.fn();
33
- render(
34
- <Dialog open onClose={onClose} testId="d">
35
- <p>x</p>
36
- </Dialog>,
37
- );
38
- // Escape now routes through the shared escape-stack (document-bubble listener).
39
- fireEvent.keyDown(document, { key: "Escape" });
40
- expect(onClose).toHaveBeenCalledTimes(1);
41
- });
42
-
43
- it("calls onClose on overlay click", () => {
44
- const onClose = vi.fn();
45
- const { baseElement } = render(
46
- <Dialog open onClose={onClose} testId="d">
47
- <p>x</p>
48
- </Dialog>,
49
- );
50
- fireEvent.click(baseElement.querySelector("[data-testid='d-overlay']")!);
51
- expect(onClose).toHaveBeenCalledTimes(1);
52
- });
53
-
54
- it("does not call onClose when clicking inside the container", () => {
55
- const onClose = vi.fn();
56
- const { getByText } = render(
57
- <Dialog open onClose={onClose} testId="d">
58
- <p>inside</p>
59
- </Dialog>,
60
- );
61
- fireEvent.click(getByText("inside"));
62
- expect(onClose).not.toHaveBeenCalled();
63
- });
64
-
65
- it("sets aria-labelledby when title is given", () => {
66
- const { baseElement } = render(
67
- <Dialog open onClose={() => {}} title="Hello" testId="d">
68
- <p>x</p>
69
- </Dialog>,
70
- );
71
- const container = baseElement.querySelector("[data-testid='d']")!;
72
- const labelledBy = container.getAttribute("aria-labelledby");
73
- expect(labelledBy).toBeTruthy();
74
- expect(document.getElementById(labelledBy!)!.textContent).toBe("Hello");
75
- });
76
-
77
- it("omits aria-labelledby and header without title/icon", () => {
78
- const { baseElement } = render(
79
- <Dialog open onClose={() => {}} testId="d">
80
- <p>x</p>
81
- </Dialog>,
82
- );
83
- const container = baseElement.querySelector("[data-testid='d']")!;
84
- expect(container.getAttribute("aria-labelledby")).toBeNull();
85
- expect(container.querySelector("h3")).toBeNull();
86
- });
87
-
88
- it("renders header icon + title", () => {
89
- const { baseElement } = render(
90
- <Dialog open onClose={() => {}} title="T" icon={mdiAlert} testId="d">
91
- <p>x</p>
92
- </Dialog>,
93
- );
94
- const container = baseElement.querySelector("[data-testid='d']")!;
95
- expect(container.querySelector("h3")!.textContent).toBe("T");
96
- expect(container.querySelector("svg")).toBeTruthy();
97
- });
98
-
99
- it("applies overlay tint and z-index chrome", () => {
100
- const { baseElement } = render(
101
- <Dialog open onClose={() => {}} testId="d">
102
- <p>x</p>
103
- </Dialog>,
104
- );
105
- const overlay = baseElement.querySelector("[data-testid='d-overlay']")!;
106
- expect(overlay.className).toContain("bg-black/60");
107
- const root = overlay.parentElement!;
108
- expect(root.className).toContain("z-[60]");
109
- const container = baseElement.querySelector("[data-testid='d']")!;
110
- expect(container.className).toContain("bg-[var(--bg-primary)]");
111
- expect(container.className).toContain("border-[var(--border-primary)]");
112
- });
113
-
114
- it.each([
115
- ["sm", "max-w-sm"],
116
- ["md", "max-w-md"],
117
- ["lg", "max-w-lg"],
118
- ["full", "max-w-[95vw]"],
119
- ] as const)("applies %s size class %s", (size, cls) => {
120
- const { baseElement } = render(
121
- <Dialog open onClose={() => {}} size={size} testId="d">
122
- <p>x</p>
123
- </Dialog>,
124
- );
125
- expect(baseElement.querySelector("[data-testid='d']")!.className).toContain(cls);
126
- });
127
-
128
- it.each([
129
- ["sm", "max-h-[80vh]"],
130
- ["md", "max-h-[80vh]"],
131
- ["lg", "max-h-[80vh]"],
132
- ["full", "max-h-[92vh]"],
133
- ] as const)("applies %s height cap %s", (size, cls) => {
134
- const { baseElement } = render(
135
- <Dialog open onClose={() => {}} size={size} testId="d">
136
- <p>x</p>
137
- </Dialog>,
138
- );
139
- expect(baseElement.querySelector("[data-testid='d']")!.className).toContain(cls);
140
- });
141
-
142
- it("flush drops padding and clips overflow (edge-to-edge body)", () => {
143
- const { baseElement } = render(
144
- <Dialog open onClose={() => {}} flush testId="d">
145
- <p>x</p>
146
- </Dialog>,
147
- );
148
- const cls = baseElement.querySelector("[data-testid='d']")!.className;
149
- expect(cls).toContain("overflow-hidden");
150
- expect(cls).not.toContain("p-5");
151
- });
152
-
153
- it("non-flush keeps padding + scroll", () => {
154
- const { baseElement } = render(
155
- <Dialog open onClose={() => {}} testId="d">
156
- <p>x</p>
157
- </Dialog>,
158
- );
159
- const cls = baseElement.querySelector("[data-testid='d']")!.className;
160
- expect(cls).toContain("p-5");
161
- expect(cls).toContain("overflow-y-auto");
162
- });
163
-
164
- it("defaults to max-w-md", () => {
165
- const { baseElement } = render(
166
- <Dialog open onClose={() => {}} testId="d">
167
- <p>x</p>
168
- </Dialog>,
169
- );
170
- expect(baseElement.querySelector("[data-testid='d']")!.className).toContain(
171
- "max-w-md",
172
- );
173
- });
174
-
175
- it("maps action intents to classes and derives testIds", () => {
176
- const onAction = vi.fn();
177
- const onCancel = vi.fn();
178
- const { baseElement } = render(
179
- <Dialog open onClose={() => {}} testId="d">
180
- <Dialog.Footer>
181
- <Dialog.Cancel onClick={onCancel} testId="d-cancel" />
182
- <Dialog.Action onClick={onAction} intent="danger" testId="d-action">
183
- Go
184
- </Dialog.Action>
185
- </Dialog.Footer>
186
- </Dialog>,
187
- );
188
- const action = baseElement.querySelector("[data-testid='d-action']")!;
189
- expect(action.className).toContain("bg-red-600");
190
- const cancel = baseElement.querySelector("[data-testid='d-cancel']")!;
191
- fireEvent.click(cancel);
192
- fireEvent.click(action);
193
- expect(onCancel).toHaveBeenCalledTimes(1);
194
- expect(onAction).toHaveBeenCalledTimes(1);
195
- });
196
-
197
- it("primary intent uses accent, neutral uses border", () => {
198
- const { baseElement } = render(
199
- <Dialog open onClose={() => {}} testId="d">
200
- <Dialog.Action onClick={() => {}} testId="p">
201
- P
202
- </Dialog.Action>
203
- <Dialog.Action onClick={() => {}} intent="neutral" testId="n">
204
- N
205
- </Dialog.Action>
206
- </Dialog>,
207
- );
208
- expect(baseElement.querySelector("[data-testid='p']")!.className).toContain(
209
- "bg-[var(--accent-primary)]",
210
- );
211
- expect(baseElement.querySelector("[data-testid='n']")!.className).toContain(
212
- "border-[var(--border-primary)]",
213
- );
214
- });
215
- });
@@ -1,58 +0,0 @@
1
- import { describe, it, expect, afterEach } from "vitest";
2
- import { render, cleanup } from "@testing-library/react";
3
- import React from "react";
4
- import { DialogPortal } from "../DialogPortal.js";
5
-
6
- afterEach(() => cleanup());
7
-
8
- describe("DialogPortal", () => {
9
- it("renders children at document.body", () => {
10
- const { baseElement } = render(
11
- <div id="app-root">
12
- <DialogPortal>
13
- <div data-testid="dialog-content">Hello</div>
14
- </DialogPortal>
15
- </div>
16
- );
17
- // Child should be in body, not inside #app-root
18
- const content = baseElement.querySelector("[data-testid='dialog-content']");
19
- expect(content).toBeTruthy();
20
- expect(content!.textContent).toBe("Hello");
21
- // Should NOT be inside #app-root
22
- const appRoot = baseElement.querySelector("#app-root");
23
- expect(appRoot!.querySelector("[data-testid='dialog-content']")).toBeNull();
24
- });
25
-
26
- it("sets document.body overflow to hidden on mount", () => {
27
- document.body.style.overflow = "";
28
- render(
29
- <DialogPortal>
30
- <div>Dialog</div>
31
- </DialogPortal>
32
- );
33
- expect(document.body.style.overflow).toBe("hidden");
34
- });
35
-
36
- it("restores document.body overflow on unmount", () => {
37
- document.body.style.overflow = "auto";
38
- const { unmount } = render(
39
- <DialogPortal>
40
- <div>Dialog</div>
41
- </DialogPortal>
42
- );
43
- expect(document.body.style.overflow).toBe("hidden");
44
- unmount();
45
- expect(document.body.style.overflow).toBe("auto");
46
- });
47
-
48
- it("restores empty overflow on unmount when originally empty", () => {
49
- document.body.style.overflow = "";
50
- const { unmount } = render(
51
- <DialogPortal>
52
- <div>Dialog</div>
53
- </DialogPortal>
54
- );
55
- unmount();
56
- expect(document.body.style.overflow).toBe("");
57
- });
58
- });