frontend: one dismiss rule for menus and popovers, menu keys, and dialog and side panel focus
useDismiss (shared) closes a floating box on a press outside or Escape: the press is seen in the capture phase, a press in an open modal dialog is not outside, Escape yields to a modal dialog the box is not in, and a box in a dialog closes alone. Popover, Dropdown, SettingsMenu, LinksMenu and UserMenu use it in place of five copies with different rules; Escape returns the focus to the button. Dropdown takes the focus on open and moves with the arrow keys, Home and End. The link, account and settings popovers drop role=menu (they had no menu keys) for a labelled group. Dialog no longer reports a close the caller asked for, ignores a drag that started inside and ended on the backdrop, and has a 2.75em close button. Popover uses the shared clampLeft. The dashboard's side panel is inert while closed, takes the focus on open and gives it back, and no longer claims aria-modal; hive-dialog gives the focus back on close.
This commit is contained in:
parent
a19745d30d
commit
844fb0a219
12 changed files with 299 additions and 121 deletions
|
|
@ -24,6 +24,7 @@
|
|||
"./pill.css": "./src/pill.css",
|
||||
"./forms.js": "./src/forms.js",
|
||||
"./prefs.js": "./src/prefs.ts",
|
||||
"./use-dismiss.js": "./src/use-dismiss.ts",
|
||||
"./dom.js": "./src/dom.js",
|
||||
"./modal.js": "./src/modal.js",
|
||||
"./shadow-css.js": "./src/shadow-css.js",
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@
|
|||
// that mode for the agents table, and dropped it with the table.
|
||||
import { useEffect, useRef } from "preact/hooks";
|
||||
import type { ComponentChildren, RefObject } from "preact";
|
||||
import { useDismiss } from "../use-dismiss.js";
|
||||
import "./Dropdown.css";
|
||||
|
||||
export interface DropdownOption {
|
||||
|
|
@ -64,32 +65,61 @@ export function Dropdown({
|
|||
anchorRef,
|
||||
}: DropdownProps) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
// A press outside, or Escape, closes it; the trigger (`anchorRef`) is inside,
|
||||
// so its own toggle stays in charge of closing.
|
||||
useDismiss({
|
||||
open,
|
||||
onDismiss: onClose,
|
||||
inside: anchorRef ? [ref, anchorRef] : [ref],
|
||||
focusOnEscape: () => {
|
||||
const anchor = anchorRef?.current;
|
||||
if (!anchor) return null;
|
||||
return anchor.matches("button") ? anchor : anchor.querySelector("button");
|
||||
},
|
||||
});
|
||||
|
||||
// A menu takes the focus when it opens, on the chosen item or the first, and
|
||||
// the arrow keys, Home and End move between the items.
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
function handlePointerDown(e: PointerEvent) {
|
||||
if (!(e.target instanceof Node)) return;
|
||||
if (ref.current?.contains(e.target)) return;
|
||||
if (anchorRef?.current?.contains(e.target)) return;
|
||||
onClose();
|
||||
}
|
||||
function handleKeyDown(e: KeyboardEvent) {
|
||||
if (e.key === "Escape") onClose();
|
||||
}
|
||||
// `pointerdown` (not `click`) so a drag-to-select that ends outside
|
||||
// still closes; capture phase so this sees the event before a
|
||||
// stopPropagation() elsewhere in the tree could swallow it.
|
||||
document.addEventListener("pointerdown", handlePointerDown, true);
|
||||
document.addEventListener("keydown", handleKeyDown);
|
||||
return () => {
|
||||
document.removeEventListener("pointerdown", handlePointerDown, true);
|
||||
document.removeEventListener("keydown", handleKeyDown);
|
||||
};
|
||||
}, [open, onClose]);
|
||||
const items =
|
||||
ref.current?.querySelectorAll<HTMLElement>(".ui-dropdown-item");
|
||||
if (!items || items.length === 0) return;
|
||||
const chosen = ref.current?.querySelector<HTMLElement>(
|
||||
".ui-dropdown-item-active",
|
||||
);
|
||||
(chosen ?? items[0]).focus();
|
||||
}, [open]);
|
||||
function onKeyDown(e: KeyboardEvent) {
|
||||
const items = Array.from(
|
||||
ref.current?.querySelectorAll<HTMLElement>(".ui-dropdown-item") ?? [],
|
||||
);
|
||||
const at = items.indexOf(document.activeElement as HTMLElement);
|
||||
const next =
|
||||
e.key === "ArrowDown"
|
||||
? (at + 1) % items.length
|
||||
: e.key === "ArrowUp"
|
||||
? (at - 1 + items.length) % items.length
|
||||
: e.key === "Home"
|
||||
? 0
|
||||
: e.key === "End"
|
||||
? items.length - 1
|
||||
: null;
|
||||
if (next === null || items.length === 0) return;
|
||||
e.preventDefault();
|
||||
items[next].focus();
|
||||
}
|
||||
|
||||
if (!open) return null;
|
||||
|
||||
return (
|
||||
<div class="ui-dropdown" role="menu" aria-label={label} ref={ref}>
|
||||
<div
|
||||
class="ui-dropdown"
|
||||
role="menu"
|
||||
aria-label={label}
|
||||
ref={ref}
|
||||
onKeyDown={onKeyDown}
|
||||
>
|
||||
{options.map((opt) => (
|
||||
<button
|
||||
type="button"
|
||||
|
|
|
|||
|
|
@ -31,6 +31,8 @@ class HiveDialog extends HTMLElement {
|
|||
} = this._opts || {};
|
||||
|
||||
const root = attachShadowCss(this, dialogCss);
|
||||
// The control that had the focus, so it gets it back when this closes.
|
||||
const opener = document.activeElement;
|
||||
|
||||
let settled = false;
|
||||
const done = (value) => {
|
||||
|
|
@ -41,6 +43,7 @@ class HiveDialog extends HTMLElement {
|
|||
new CustomEvent("hive-dialog-close", { detail: value }),
|
||||
);
|
||||
this.remove();
|
||||
if (opener instanceof HTMLElement && opener.isConnected) opener.focus();
|
||||
};
|
||||
const onKey = (e) => {
|
||||
if (dismissable && e.key === "Escape") {
|
||||
|
|
|
|||
|
|
@ -10,9 +10,10 @@
|
|||
// imports or `@import`s itself: the dashboard's JS bundle loads `.css`
|
||||
// imports as text, so a component that imported it would not style there
|
||||
// (the same split as `UserMenu`).
|
||||
import { useEffect, useRef, useState } from "preact/hooks";
|
||||
import { useRef, useState } from "preact/hooks";
|
||||
import { IconButton } from "../icon-button/IconButton.js";
|
||||
import { LinkIcon } from "../icons.js";
|
||||
import { useDismiss } from "../use-dismiss.js";
|
||||
import { linkAttrs, type MenuLink } from "./links.js";
|
||||
|
||||
export type { MenuLink };
|
||||
|
|
@ -28,22 +29,13 @@ export function LinksMenu({
|
|||
const [open, setOpen] = useState(false);
|
||||
const rootRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
function onPointerDown(e: MouseEvent) {
|
||||
if (rootRef.current && !rootRef.current.contains(e.target as Node))
|
||||
setOpen(false);
|
||||
}
|
||||
function onKeyDown(e: KeyboardEvent) {
|
||||
if (e.key === "Escape") setOpen(false);
|
||||
}
|
||||
document.addEventListener("pointerdown", onPointerDown);
|
||||
document.addEventListener("keydown", onKeyDown);
|
||||
return () => {
|
||||
document.removeEventListener("pointerdown", onPointerDown);
|
||||
document.removeEventListener("keydown", onKeyDown);
|
||||
};
|
||||
}, [open]);
|
||||
// A press outside or Escape closes it; Escape puts the focus back on the button.
|
||||
useDismiss({
|
||||
open,
|
||||
onDismiss: () => setOpen(false),
|
||||
inside: [rootRef],
|
||||
focusOnEscape: () => rootRef.current?.querySelector("button") ?? null,
|
||||
});
|
||||
|
||||
if (links.length === 0) return null;
|
||||
|
||||
|
|
@ -57,14 +49,13 @@ export function LinksMenu({
|
|||
<LinkIcon />
|
||||
</IconButton>
|
||||
{open ? (
|
||||
<div class="links-menu-popover" role="menu">
|
||||
<div class="links-menu-popover" role="group" aria-label={label}>
|
||||
{links.map((link) => (
|
||||
<a
|
||||
key={link.url}
|
||||
class="links-menu-item"
|
||||
href={link.url}
|
||||
{...linkAttrs(link)}
|
||||
role="menuitem"
|
||||
onClick={() => setOpen(false)}
|
||||
>
|
||||
{link.icon ? <span aria-hidden="true">{link.icon}</span> : null}
|
||||
|
|
|
|||
|
|
@ -23,10 +23,11 @@
|
|||
// once, high in its tree, with the SAME key strings passed to this
|
||||
// component, so the two stay in sync without this component owning any
|
||||
// page-specific naming decision.
|
||||
import { useEffect, useRef, useState } from "preact/hooks";
|
||||
import { useRef, useState } from "preact/hooks";
|
||||
import type { ComponentChildren } from "preact";
|
||||
import { IconButton } from "../icon-button/IconButton.js";
|
||||
import { GearIcon } from "../icons.js";
|
||||
import { useDismiss } from "../use-dismiss.js";
|
||||
import { useThemeOverride, type ThemeOverride } from "./theme-apply.js";
|
||||
import { useMotionOverride, type MotionOverride } from "./motion-apply.js";
|
||||
import "./SettingsMenu.css";
|
||||
|
|
@ -61,27 +62,13 @@ export function SettingsMenu({
|
|||
const [theme, setTheme] = useThemeOverride(themeKey);
|
||||
const [motion, setMotion] = useMotionOverride(motionKey);
|
||||
|
||||
// Close on an outside click or Escape — only listens while open.
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
function onPointerDown(e: PointerEvent) {
|
||||
if (
|
||||
rootRef.current &&
|
||||
e.target instanceof Node &&
|
||||
!rootRef.current.contains(e.target)
|
||||
)
|
||||
setOpen(false);
|
||||
}
|
||||
function onKeyDown(e: KeyboardEvent) {
|
||||
if (e.key === "Escape") setOpen(false);
|
||||
}
|
||||
document.addEventListener("pointerdown", onPointerDown, true);
|
||||
document.addEventListener("keydown", onKeyDown);
|
||||
return () => {
|
||||
document.removeEventListener("pointerdown", onPointerDown, true);
|
||||
document.removeEventListener("keydown", onKeyDown);
|
||||
};
|
||||
}, [open]);
|
||||
// A press outside or Escape closes it; Escape puts the focus back on the button.
|
||||
useDismiss({
|
||||
open,
|
||||
onDismiss: () => setOpen(false),
|
||||
inside: [rootRef],
|
||||
focusOnEscape: () => rootRef.current?.querySelector("button") ?? null,
|
||||
});
|
||||
|
||||
return (
|
||||
<div class="settings-menu-anchor" ref={rootRef}>
|
||||
|
|
@ -93,7 +80,7 @@ export function SettingsMenu({
|
|||
<GearIcon />
|
||||
</IconButton>
|
||||
{open ? (
|
||||
<div class="settings-menu-popover" role="menu" aria-label="settings">
|
||||
<div class="settings-menu-popover" role="group" aria-label="settings">
|
||||
<label class="settings-menu-row">
|
||||
<span>theme</span>
|
||||
<select
|
||||
|
|
|
|||
|
|
@ -42,7 +42,11 @@ class HiveSidePanel extends HTMLElement {
|
|||
connectedCallback() {
|
||||
const root = attachShadowCss(this, sidePanelCss);
|
||||
this.setAttribute("aria-hidden", "true");
|
||||
// Closed, the drawer is only slid off screen; `inert` keeps its controls out
|
||||
// of the Tab order and away from assistive tech until it opens.
|
||||
this.inert = true;
|
||||
this._owner = null;
|
||||
this._opener = null;
|
||||
|
||||
this._titleEl = el("span", {
|
||||
class: "side-panel-title",
|
||||
|
|
@ -79,7 +83,6 @@ class HiveSidePanel extends HTMLElement {
|
|||
{
|
||||
class: "side-panel-drawer",
|
||||
role: "dialog",
|
||||
"aria-modal": "true",
|
||||
"aria-labelledby": "side-panel-title",
|
||||
},
|
||||
this._resizeHandle,
|
||||
|
|
@ -94,7 +97,12 @@ class HiveSidePanel extends HTMLElement {
|
|||
this._closeBtn.addEventListener("click", () => this.close());
|
||||
this._backdrop.addEventListener("click", () => this.close());
|
||||
document.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Escape" && this.classList.contains("open")) this.close();
|
||||
if (
|
||||
e.key === "Escape" &&
|
||||
!e.defaultPrevented &&
|
||||
this.classList.contains("open")
|
||||
)
|
||||
this.close();
|
||||
});
|
||||
|
||||
this._applyStoredWidth();
|
||||
|
|
@ -109,8 +117,13 @@ class HiveSidePanel extends HTMLElement {
|
|||
this._owner = name;
|
||||
this._titleEl.textContent = title;
|
||||
this.replaceChildren(...(content ? [content] : []));
|
||||
// Remembered only on the first open: a replace while open keeps the
|
||||
// original opener.
|
||||
if (!this.classList.contains("open")) this._opener = document.activeElement;
|
||||
this.classList.add("open");
|
||||
this.setAttribute("aria-hidden", "false");
|
||||
this.inert = false;
|
||||
this._closeBtn.focus();
|
||||
}
|
||||
|
||||
refresh(name, title, content) {
|
||||
|
|
@ -123,6 +136,12 @@ class HiveSidePanel extends HTMLElement {
|
|||
this._owner = null;
|
||||
this.classList.remove("open");
|
||||
this.setAttribute("aria-hidden", "true");
|
||||
this.inert = true;
|
||||
// Back to the control that opened it, if that is still on the page.
|
||||
if (this._opener instanceof HTMLElement && this._opener.isConnected) {
|
||||
this._opener.focus();
|
||||
}
|
||||
this._opener = null;
|
||||
}
|
||||
|
||||
currentOwner() {
|
||||
|
|
|
|||
108
frontend/packages/shared/src/use-dismiss.ts
Normal file
108
frontend/packages/shared/src/use-dismiss.ts
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
// useDismiss — close a floating box (a menu, a popover) on a press outside it or
|
||||
// on Escape. One rule for every such box, in place of a copy in each: the press
|
||||
// is seen in the capture phase, so a handler that stops it further down cannot
|
||||
// hide it, and an open modal `<dialog>` is respected.
|
||||
//
|
||||
// - A press inside the box, or on its trigger (`inside`), is not outside.
|
||||
// - A press inside an open modal dialog that the box is not in is not outside
|
||||
// either: that dialog sits over the box (it opened from a menu item, say),
|
||||
// took the press, and the box stays. A press elsewhere in the dialog the box
|
||||
// is in is an outside press.
|
||||
// - Escape closes the box, unless a modal dialog is open that the box is not
|
||||
// in: then the dialog's own Escape is the one that counts. When the box is in
|
||||
// a dialog, only the box closes, not the dialog behind it.
|
||||
import { useEffect, useRef } from "preact/hooks";
|
||||
import type { RefObject } from "preact";
|
||||
|
||||
/**
|
||||
* The open dialogs that do not hold the box: `holdsBox` says whether a dialog
|
||||
* has the box or its trigger in it. A press in one of these, or an Escape while
|
||||
* one is open, belongs to that dialog and not to the box.
|
||||
*/
|
||||
export function dialogsOverBox<D>(
|
||||
dialogs: D[],
|
||||
holdsBox: (dialog: D) => boolean,
|
||||
): D[] {
|
||||
return dialogs.filter((d) => !holdsBox(d));
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a press at a place outside every `inside` element closes the box,
|
||||
* given whether the press is inside a dialog that sits over the box.
|
||||
*/
|
||||
export function pointerDismisses(
|
||||
inside: boolean,
|
||||
insideDialogOverBox: boolean,
|
||||
): boolean {
|
||||
return !inside && !insideDialogOverBox;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether Escape closes the box, given whether a modal dialog is open that the
|
||||
* box is not in.
|
||||
*/
|
||||
export function escapeDismisses(openDialogOutsideBox: boolean): boolean {
|
||||
return !openDialogOutsideBox;
|
||||
}
|
||||
|
||||
function contains(el: Element | null | undefined, target: EventTarget | null) {
|
||||
return target instanceof Node && el != null && el.contains(target);
|
||||
}
|
||||
|
||||
export function useDismiss({
|
||||
open,
|
||||
onDismiss,
|
||||
inside,
|
||||
focusOnEscape,
|
||||
}: {
|
||||
open: boolean;
|
||||
onDismiss: () => void;
|
||||
/** The box and its trigger: a press on either is not an outside press. */
|
||||
inside: Array<RefObject<Element | null>>;
|
||||
/** Where the focus goes when Escape closes the box, usually its trigger. */
|
||||
focusOnEscape?: () => HTMLElement | null;
|
||||
}) {
|
||||
// The latest callbacks, so the listeners are not re-added on every render.
|
||||
const latest = useRef({ onDismiss, inside, focusOnEscape });
|
||||
latest.current = { onDismiss, inside, focusOnEscape };
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
function onPointerDown(e: PointerEvent) {
|
||||
const { onDismiss, inside } = latest.current;
|
||||
const members = inside.map((ref) => ref.current);
|
||||
const over = dialogsOverBox(
|
||||
Array.from(document.querySelectorAll("dialog[open]")),
|
||||
(d) => members.some((m) => d.contains(m)),
|
||||
);
|
||||
if (
|
||||
pointerDismisses(
|
||||
members.some((m) => contains(m, e.target)),
|
||||
over.some((d) => contains(d, e.target)),
|
||||
)
|
||||
) {
|
||||
onDismiss();
|
||||
}
|
||||
}
|
||||
function onKeyDown(e: KeyboardEvent) {
|
||||
if (e.key !== "Escape") return;
|
||||
const { onDismiss, inside, focusOnEscape } = latest.current;
|
||||
const members = inside.map((ref) => ref.current);
|
||||
const dialogs = Array.from(document.querySelectorAll("dialog[open]"));
|
||||
const over = dialogsOverBox(dialogs, (d) =>
|
||||
members.some((m) => d.contains(m)),
|
||||
);
|
||||
if (!escapeDismisses(over.length > 0)) return;
|
||||
// In a dialog, the box closes alone: the dialog would close on this Escape too.
|
||||
if (dialogs.length > 0) e.preventDefault();
|
||||
onDismiss();
|
||||
focusOnEscape?.()?.focus();
|
||||
}
|
||||
document.addEventListener("pointerdown", onPointerDown, true);
|
||||
document.addEventListener("keydown", onKeyDown);
|
||||
return () => {
|
||||
document.removeEventListener("pointerdown", onPointerDown, true);
|
||||
document.removeEventListener("keydown", onKeyDown);
|
||||
};
|
||||
}, [open]);
|
||||
}
|
||||
|
|
@ -15,6 +15,7 @@
|
|||
// Styles live in `@hive/shared/user-menu.css`, which the mounting page
|
||||
// imports or `@import`s itself: the dashboard's JS bundle loads `.css`
|
||||
// imports as text, so a component that imported it would not style there.
|
||||
import { useDismiss } from "../use-dismiss.js";
|
||||
import { useEffect, useRef, useState } from "preact/hooks";
|
||||
import { IconButton } from "../icon-button/IconButton.js";
|
||||
import {
|
||||
|
|
@ -61,23 +62,13 @@ export function UserMenu({
|
|||
};
|
||||
}, [whoamiUrl]);
|
||||
|
||||
// Close on an outside click or Escape, as `SettingsMenu` does.
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
function onPointerDown(e: MouseEvent) {
|
||||
if (rootRef.current && !rootRef.current.contains(e.target as Node))
|
||||
setOpen(false);
|
||||
}
|
||||
function onKeyDown(e: KeyboardEvent) {
|
||||
if (e.key === "Escape") setOpen(false);
|
||||
}
|
||||
document.addEventListener("pointerdown", onPointerDown);
|
||||
document.addEventListener("keydown", onKeyDown);
|
||||
return () => {
|
||||
document.removeEventListener("pointerdown", onPointerDown);
|
||||
document.removeEventListener("keydown", onKeyDown);
|
||||
};
|
||||
}, [open]);
|
||||
// A press outside or Escape closes it; Escape puts the focus back on the button.
|
||||
useDismiss({
|
||||
open,
|
||||
onDismiss: () => setOpen(false),
|
||||
inside: [rootRef],
|
||||
focusOnEscape: () => rootRef.current?.querySelector("button") ?? null,
|
||||
});
|
||||
|
||||
const label = labelOf(who);
|
||||
const links = accountLinks(autheliaUrl);
|
||||
|
|
@ -94,7 +85,7 @@ export function UserMenu({
|
|||
{initialOf(label)}
|
||||
</IconButton>
|
||||
{open ? (
|
||||
<div class="user-menu-popover" role="menu">
|
||||
<div class="user-menu-popover" role="group" aria-label="account">
|
||||
{label ? <div class="user-menu-name">{label}</div> : null}
|
||||
{links ? (
|
||||
<>
|
||||
|
|
@ -103,7 +94,6 @@ export function UserMenu({
|
|||
href={links.settings}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
role="menuitem"
|
||||
onClick={() => setOpen(false)}
|
||||
>
|
||||
authelia settings
|
||||
|
|
@ -111,7 +101,6 @@ export function UserMenu({
|
|||
<a
|
||||
class="user-menu-item"
|
||||
href={links.logout}
|
||||
role="menuitem"
|
||||
onClick={() => {
|
||||
onLogout?.();
|
||||
setOpen(false);
|
||||
|
|
|
|||
|
|
@ -51,8 +51,8 @@
|
|||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 2.2em;
|
||||
height: 2.2em;
|
||||
width: 2.75em;
|
||||
height: 2.75em;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 0.4em;
|
||||
background: none;
|
||||
|
|
@ -66,11 +66,11 @@
|
|||
background: var(--bg);
|
||||
}
|
||||
.ui-dialog-body {
|
||||
/* Clears the close button's own box (0.75em inset + 2.2em size) with
|
||||
/* Clears the close button's own box (0.75em inset + 2.75em size) with
|
||||
room to spare — verified against a real screenshot; a smaller value
|
||||
let wide content (e.g. the create-agent form's two-panel layout)
|
||||
render directly under the button instead of beside it. */
|
||||
padding-right: 3.25em;
|
||||
padding-right: 3.75em;
|
||||
}
|
||||
/* `plain` has no floating close button of its own to clear — the
|
||||
content's own `Panel` header carries one instead (see `.ui-panel-close`
|
||||
|
|
|
|||
|
|
@ -45,6 +45,12 @@ export function Dialog({
|
|||
plain?: boolean;
|
||||
}) {
|
||||
const ref = useRef<HTMLDialogElement>(null);
|
||||
// The `close` event comes after a close the `open` prop asked for, too; only a
|
||||
// close the caller did not ask for (Escape) is reported back.
|
||||
const closedByProp = useRef(false);
|
||||
// Where the press began: a drag that starts inside and ends over the backdrop
|
||||
// is not a click on it.
|
||||
const pressedOnBackdrop = useRef(false);
|
||||
|
||||
// Drives the native open/closed state from the `open` prop rather
|
||||
// than mounting/unmounting the element — `showModal()`/`close()` are
|
||||
|
|
@ -53,8 +59,13 @@ export function Dialog({
|
|||
useEffect(() => {
|
||||
const el = ref.current;
|
||||
if (!el) return;
|
||||
if (open && !el.open) el.showModal();
|
||||
else if (!open && el.open) el.close();
|
||||
if (open && !el.open) {
|
||||
closedByProp.current = false;
|
||||
el.showModal();
|
||||
} else if (!open && el.open) {
|
||||
closedByProp.current = true;
|
||||
el.close();
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
// The dialog's own `close` event fires on Escape (and would fire on
|
||||
|
|
@ -65,6 +76,10 @@ export function Dialog({
|
|||
const el = ref.current;
|
||||
if (!el) return;
|
||||
function handleClose() {
|
||||
if (closedByProp.current) {
|
||||
closedByProp.current = false;
|
||||
return;
|
||||
}
|
||||
onClose();
|
||||
}
|
||||
el.addEventListener("close", handleClose);
|
||||
|
|
@ -80,8 +95,11 @@ export function Dialog({
|
|||
// exactly when it's outside the rendered content box — inside
|
||||
// the box, the click target is always some descendant. Standard
|
||||
// "click the backdrop to close" trick for native `<dialog>`.
|
||||
onPointerDown={(e) => {
|
||||
pressedOnBackdrop.current = e.target === ref.current;
|
||||
}}
|
||||
onClick={(e) => {
|
||||
if (e.target === ref.current) onClose();
|
||||
if (e.target === ref.current && pressedOnBackdrop.current) onClose();
|
||||
}}
|
||||
>
|
||||
{plain ? null : (
|
||||
|
|
|
|||
|
|
@ -27,11 +27,12 @@ import {
|
|||
} from "preact/hooks";
|
||||
import { createPortal } from "preact/compat";
|
||||
import type { ComponentChildren, RefObject } from "preact";
|
||||
import { useDismiss } from "@hive/shared/use-dismiss.js";
|
||||
import { clampLeft } from "../table/popover-position.js";
|
||||
import { focusInto, restoreFocus, triggerOf } from "./focus.js";
|
||||
import "./Popover.css";
|
||||
|
||||
// Space kept between the popover and the viewport's edges.
|
||||
const EDGE_PX = 8;
|
||||
// Space between the popover and its anchor.
|
||||
const GAP_PX = 4;
|
||||
|
||||
export function Popover({
|
||||
|
|
@ -96,9 +97,8 @@ export function Popover({
|
|||
if (!anchor) return;
|
||||
const r = anchor.getBoundingClientRect();
|
||||
const width = ref.current?.offsetWidth ?? 0;
|
||||
const maxLeft = window.innerWidth - width - EDGE_PX;
|
||||
const top = r.bottom + GAP_PX;
|
||||
const left = Math.max(EDGE_PX, Math.min(r.left, maxLeft));
|
||||
const left = clampLeft(r.left, width, window.innerWidth);
|
||||
// Scrolling anywhere (the streaming terminal included) calls this; keep
|
||||
// the old object when nothing moved so the subtree does not re-render.
|
||||
setPos((prev) =>
|
||||
|
|
@ -114,32 +114,9 @@ export function Popover({
|
|||
};
|
||||
}, [open, anchorRef]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
function inside(target: EventTarget | null, el: Element | null) {
|
||||
return target instanceof Node && el !== null && el.contains(target);
|
||||
}
|
||||
function onPointerDown(e: PointerEvent) {
|
||||
if (
|
||||
inside(e.target, ref.current) ||
|
||||
inside(e.target, anchorRef.current) ||
|
||||
inside(e.target, document.querySelector("dialog[open]"))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
onClose();
|
||||
}
|
||||
function onKeyDown(e: KeyboardEvent) {
|
||||
if (e.key !== "Escape" || document.querySelector("dialog[open]")) return;
|
||||
onClose();
|
||||
}
|
||||
document.addEventListener("pointerdown", onPointerDown);
|
||||
document.addEventListener("keydown", onKeyDown);
|
||||
return () => {
|
||||
document.removeEventListener("pointerdown", onPointerDown);
|
||||
document.removeEventListener("keydown", onKeyDown);
|
||||
};
|
||||
}, [open, onClose, anchorRef]);
|
||||
// A press outside or Escape closes it. A modal dialog opened from inside it
|
||||
// takes both, and leaves it alone.
|
||||
useDismiss({ open, onDismiss: onClose, inside: [ref, anchorRef] });
|
||||
|
||||
if (!open) return null;
|
||||
return createPortal(
|
||||
|
|
|
|||
43
frontend/packages/swarm-ui/test/use-dismiss.test.mjs
Normal file
43
frontend/packages/swarm-ui/test/use-dismiss.test.mjs
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
// When a press or Escape closes a floating box: the rule `useDismiss` applies.
|
||||
// Run by `npm test`.
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import {
|
||||
dialogsOverBox,
|
||||
escapeDismisses,
|
||||
pointerDismisses,
|
||||
} from "../../shared/src/use-dismiss.ts";
|
||||
|
||||
test("a press outside the box and every dialog closes it", () => {
|
||||
assert.equal(pointerDismisses(false, false), true);
|
||||
});
|
||||
|
||||
test("a press inside the box, or in a dialog over it, does not", () => {
|
||||
assert.equal(pointerDismisses(true, false), false);
|
||||
assert.equal(pointerDismisses(false, true), false);
|
||||
assert.equal(pointerDismisses(true, true), false);
|
||||
});
|
||||
|
||||
test("Escape closes the box unless a dialog it is not in is open", () => {
|
||||
assert.equal(escapeDismisses(false), true);
|
||||
assert.equal(escapeDismisses(true), false);
|
||||
});
|
||||
|
||||
test("a dialog the box is in is not over it", () => {
|
||||
const holding = { holdsBox: true };
|
||||
const over = { holdsBox: false };
|
||||
assert.deepEqual(
|
||||
dialogsOverBox([holding, over], (d) => d.holdsBox),
|
||||
[over],
|
||||
);
|
||||
assert.deepEqual(
|
||||
dialogsOverBox([holding], (d) => d.holdsBox),
|
||||
[],
|
||||
);
|
||||
});
|
||||
|
||||
test("a press in the dialog the box is in dismisses it", () => {
|
||||
const holding = { holdsBox: true };
|
||||
const over = dialogsOverBox([holding], (d) => d.holdsBox);
|
||||
assert.equal(pointerDismisses(false, over.includes(holding)), true);
|
||||
});
|
||||
Loading…
Reference in a new issue