mirror of
https://github.com/home-assistant/frontend.git
synced 2026-12-02 01:30:11 +00:00
Compare commits
4
Commits
dev
...
hac-popover
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8d4e6af0ff | ||
|
|
5c8571eeff | ||
|
|
0b3ca64355 | ||
|
|
731badc2c0 |
No files matched your search
@@ -102,6 +102,12 @@ import type { HacCard } from "@home-assistant/components/card/scoped";
|
||||
The package has no root entry point: each element and the scoped helpers
|
||||
(`@home-assistant/components/scoped`) have their own.
|
||||
|
||||
## Events
|
||||
|
||||
Events are named after the element that fires them, like
|
||||
`hac-popover-show`, and bubble out of shadow roots. A listener further out
|
||||
can therefore tell a popover closing from a dialog closing around it.
|
||||
|
||||
## Theming
|
||||
|
||||
Each component exposes its own `--hac-*` custom properties, documented in its
|
||||
@@ -131,8 +137,10 @@ src/components/card/ <hac-card> -> @home-assistant/components/card
|
||||
```
|
||||
|
||||
Shared code lives in `src/utils/`: `registration/` for defining elements
|
||||
(global and scoped) and `element/` for helpers that components use
|
||||
themselves, like slot checks.
|
||||
(global and scoped), `element/` for helpers that components use
|
||||
themselves, like slot checks, and `popup/` for the base of floating elements
|
||||
like `hac-popover`, positioned with
|
||||
[Floating UI](https://floating-ui.com).
|
||||
|
||||
Every element has its own version in `info.ts`.
|
||||
|
||||
|
||||
@@ -41,6 +41,9 @@ const publicApiOnly = () => ({
|
||||
declaration.members = declaration.members?.filter(
|
||||
(member) => !member.privacy || member.privacy === "public"
|
||||
);
|
||||
// Events dispatched with a computed name, like the popup base's, have no
|
||||
// name here; the element documents them with @fires instead
|
||||
declaration.events = declaration.events?.filter((event) => event.name);
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -72,7 +75,8 @@ const distPaths = () => {
|
||||
};
|
||||
|
||||
export default {
|
||||
globs: ["src/components/**/hac-*.ts"],
|
||||
// Base classes are analyzed too, so elements list the members they inherit
|
||||
globs: ["src/components/**/hac-*.ts", "src/utils/popup/*.ts"],
|
||||
outdir: "dist",
|
||||
litelement: true,
|
||||
plugins: [
|
||||
|
||||
@@ -48,6 +48,9 @@
|
||||
"dev": "rslib build --watch",
|
||||
"prepublishOnly": "pnpm run build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@floating-ui/dom": "^1.8.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"lit": "^3.3.0"
|
||||
},
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { define } from "../../utils/registration/define";
|
||||
import { HacPopover } from "./hac-popover";
|
||||
import { TAG_NAME } from "./info";
|
||||
|
||||
// Registers <hac-popover> in the global registry, as used by Home Assistant
|
||||
define(TAG_NAME, HacPopover);
|
||||
|
||||
export { HacPopover };
|
||||
@@ -0,0 +1,237 @@
|
||||
import type { Placement } from "@floating-ui/dom";
|
||||
import { css, type PropertyValues } from "lit";
|
||||
import { property } from "lit/decorators.js";
|
||||
import { containsComposed, deepActiveElement } from "../../utils/element/focus";
|
||||
import { listen } from "../../utils/element/listen";
|
||||
import { PopupBase, type PopupHideDetail } from "../../utils/popup/popup-base";
|
||||
import { TAG_NAME } from "./info";
|
||||
|
||||
/**
|
||||
* @element hac-popover
|
||||
*
|
||||
* @summary
|
||||
* Panel opened from an anchor for content people read or interact with, like
|
||||
* help text with links. Place it right after its anchor, so Tab moves from the
|
||||
* anchor into the content and Escape returns focus to the anchor.
|
||||
*
|
||||
* @slot - The popover's content.
|
||||
*
|
||||
* @csspart body - The popover's container.
|
||||
*
|
||||
* @cssprop --hac-popover-background-color - Background of the popover.
|
||||
* @cssprop --hac-popover-max-width - Maximum width. Defaults to `280px`.
|
||||
* @cssprop --hac-popover-max-height - Maximum height. Defaults to `360px`.
|
||||
* @cssprop --hac-popover-box-shadow - Shadow of the popover.
|
||||
* @cssprop --hac-popover-border - Border shorthand. Set to `none` to remove it.
|
||||
* @cssprop --hac-popover-border-radius - Corner radius. Defaults to `24px`.
|
||||
* @cssprop --hac-popover-padding - Padding around the content. Defaults to `16px`.
|
||||
*
|
||||
* @fires hac-popover-show - The popover is about to open. Cancelable.
|
||||
* @fires hac-popover-after-show - The popover opened.
|
||||
* @fires hac-popover-hide - The popover is about to close. Cancelable. `detail.reason` says why.
|
||||
* @fires hac-popover-after-hide - The popover closed. `detail.reason` says why.
|
||||
*/
|
||||
export class HacPopover extends PopupBase {
|
||||
/**
|
||||
* What opens the popover. `hover` also opens it while a mouse rests on the
|
||||
* anchor; a click still works, for touch and keyboard. `manual` leaves it to
|
||||
* `show()`, `hide()` and `open`.
|
||||
*/
|
||||
@property() public trigger: "click" | "hover" | "manual" = "click";
|
||||
|
||||
/**
|
||||
* Preferred placement relative to the anchor: `top`, `right`, `bottom` or
|
||||
* `left`, optionally followed by `-start` or `-end`. Flips to the other
|
||||
* side when there is no room.
|
||||
*/
|
||||
@property({ reflect: true }) public placement: Placement = "bottom-start";
|
||||
|
||||
protected readonly eventPrefix = TAG_NAME;
|
||||
|
||||
private _pinned = false;
|
||||
|
||||
private _timer?: number;
|
||||
|
||||
public disconnectedCallback(): void {
|
||||
super.disconnectedCallback();
|
||||
clearTimeout(this._timer);
|
||||
}
|
||||
|
||||
protected willUpdate(changedProps: PropertyValues<this>): void {
|
||||
super.willUpdate(changedProps);
|
||||
if (changedProps.has("open")) {
|
||||
this.anchor?.setAttribute("aria-expanded", String(this.open));
|
||||
if (!this.open) {
|
||||
this._pinned = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected anchorChanged(
|
||||
anchor: HTMLElement | null,
|
||||
oldAnchor: HTMLElement | null
|
||||
): void {
|
||||
if (oldAnchor && oldAnchor !== anchor) {
|
||||
oldAnchor.removeAttribute("aria-expanded");
|
||||
oldAnchor.removeAttribute("aria-controls");
|
||||
}
|
||||
if (anchor) {
|
||||
anchor.setAttribute("aria-expanded", String(this.open));
|
||||
anchor.setAttribute("aria-controls", this.id);
|
||||
}
|
||||
}
|
||||
|
||||
protected attachAnchor(anchor: HTMLElement): (() => void)[] {
|
||||
return [
|
||||
listen(anchor, "click", this._handleClick),
|
||||
listen(anchor, "pointerenter", this._handleEnter),
|
||||
listen(anchor, "pointerleave", this._handleLeave),
|
||||
listen(anchor, "focusout", this._handleFocusOut),
|
||||
listen(this, "pointerenter", this._handleEnter),
|
||||
listen(this, "pointerleave", this._handleLeave),
|
||||
listen(this, "focusout", this._handleFocusOut),
|
||||
];
|
||||
}
|
||||
|
||||
protected handleEscape(): void {
|
||||
const focusInside = this._focusInside();
|
||||
this.close("escape-key");
|
||||
if (focusInside) {
|
||||
this.anchor?.focus();
|
||||
}
|
||||
}
|
||||
|
||||
private _focusInside(): boolean {
|
||||
const active = deepActiveElement();
|
||||
return (
|
||||
containsComposed(this, active) ||
|
||||
(this.anchor ? containsComposed(this.anchor, active) : false)
|
||||
);
|
||||
}
|
||||
|
||||
private _opensOnClick(): boolean {
|
||||
return this.trigger !== "manual";
|
||||
}
|
||||
|
||||
private _handleClick = (): void => {
|
||||
if (!this._opensOnClick()) {
|
||||
return;
|
||||
}
|
||||
clearTimeout(this._timer);
|
||||
if (this.open && this._pinned) {
|
||||
this.close("anchor-click");
|
||||
return;
|
||||
}
|
||||
this._pinned = true;
|
||||
this.open = true;
|
||||
};
|
||||
|
||||
private _handleEnter = (ev: PointerEvent): void => {
|
||||
if (ev.pointerType !== "mouse" || this.trigger !== "hover") {
|
||||
return;
|
||||
}
|
||||
clearTimeout(this._timer);
|
||||
if (!this.open) {
|
||||
this._timer = window.setTimeout(() => {
|
||||
this.open = true;
|
||||
}, 150);
|
||||
}
|
||||
};
|
||||
|
||||
private _handleLeave = (ev: PointerEvent): void => {
|
||||
if (
|
||||
ev.pointerType !== "mouse" ||
|
||||
this.trigger !== "hover" ||
|
||||
this._pinned
|
||||
) {
|
||||
return;
|
||||
}
|
||||
clearTimeout(this._timer);
|
||||
this._timer = window.setTimeout(() => {
|
||||
// Keyboard users may have moved into the content; focusout closes it
|
||||
if (!this._focusInside()) {
|
||||
this.close("mouse-leave");
|
||||
}
|
||||
}, 150);
|
||||
};
|
||||
|
||||
private _handleFocusOut = (ev: FocusEvent): void => {
|
||||
const next = ev.relatedTarget as Node | null;
|
||||
if (!this.open || !next) {
|
||||
return;
|
||||
}
|
||||
const insideAnchor = this.anchor
|
||||
? containsComposed(this.anchor, next)
|
||||
: false;
|
||||
const insidePopover = containsComposed(this, next);
|
||||
if (!insideAnchor && !insidePopover) {
|
||||
this.close("focus-out");
|
||||
}
|
||||
};
|
||||
|
||||
static styles = [
|
||||
PopupBase.styles,
|
||||
css`
|
||||
.body {
|
||||
max-width: min(
|
||||
var(--hac-popover-max-width, 280px),
|
||||
var(--available-width, 100vw)
|
||||
);
|
||||
max-height: min(
|
||||
var(--hac-popover-max-height, 360px),
|
||||
var(--available-height, 100vh)
|
||||
);
|
||||
overflow: auto;
|
||||
padding: var(--hac-popover-padding, var(--ha-space-4, 16px));
|
||||
border: var(
|
||||
--hac-popover-border,
|
||||
1px solid var(--ha-color-border-neutral-quiet, rgba(0, 0, 0, 0.12))
|
||||
);
|
||||
border-radius: var(
|
||||
--hac-popover-border-radius,
|
||||
var(--ha-border-radius-3xl, 24px)
|
||||
);
|
||||
background-color: var(
|
||||
--hac-popover-background-color,
|
||||
var(--ha-color-surface-default, #fff)
|
||||
);
|
||||
color: var(--primary-text-color, var(--ha-color-text-primary, #141414));
|
||||
box-shadow: var(
|
||||
--hac-popover-box-shadow,
|
||||
0 8px 28px rgba(0, 0, 0, 0.18)
|
||||
);
|
||||
font-family: var(--ha-font-family-body, inherit);
|
||||
font-size: var(--ha-font-size-m, 14px);
|
||||
line-height: 1.45;
|
||||
overflow-wrap: anywhere;
|
||||
animation: hac-popover-in 160ms ease;
|
||||
}
|
||||
|
||||
@keyframes hac-popover-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(4px);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.body {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
`,
|
||||
];
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
"hac-popover": HacPopover;
|
||||
}
|
||||
|
||||
interface HTMLElementEventMap {
|
||||
"hac-popover-show": CustomEvent<null>;
|
||||
"hac-popover-after-show": CustomEvent<null>;
|
||||
"hac-popover-hide": CustomEvent<PopupHideDetail>;
|
||||
"hac-popover-after-hide": CustomEvent<PopupHideDetail>;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
/** Tag name of the element. */
|
||||
export const TAG_NAME = "hac-popover";
|
||||
|
||||
/** Version of <hac-popover>. */
|
||||
export const VERSION = "0.1.0";
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { ElementDefinition } from "../../utils/registration/definition";
|
||||
import { HacPopover } from "./hac-popover";
|
||||
import { TAG_NAME } from "./info";
|
||||
|
||||
export { HacPopover };
|
||||
|
||||
/**
|
||||
* The bundled <hac-popover> for a scoped registry:
|
||||
* `ScopedElementsMixin(LitElement, [hacPopover])` or
|
||||
* `createScopedElementRegistry([hacPopover])`.
|
||||
*/
|
||||
export const hacPopover: ElementDefinition<typeof HacPopover> = {
|
||||
tagName: TAG_NAME,
|
||||
element: HacPopover,
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Like `Node.contains`, but follows slots and shadow hosts, so slotted content
|
||||
* counts as inside the element it is slotted into.
|
||||
*/
|
||||
export const containsComposed = (
|
||||
container: Node,
|
||||
node: Node | null
|
||||
): boolean => {
|
||||
let current: Node | null = node;
|
||||
while (current) {
|
||||
if (current === container) {
|
||||
return true;
|
||||
}
|
||||
current =
|
||||
(current as Element).assignedSlot ??
|
||||
current.parentNode ??
|
||||
(current as ShadowRoot).host ??
|
||||
null;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
/** The focused element, looking into open shadow roots. */
|
||||
export const deepActiveElement = (): Element | null => {
|
||||
let active = document.activeElement;
|
||||
while (active?.shadowRoot?.activeElement) {
|
||||
active = active.shadowRoot.activeElement;
|
||||
}
|
||||
return active;
|
||||
};
|
||||
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* Adds an event listener and returns a function that removes it. Unlike the
|
||||
* `signal` option, this also works before Chrome 90 and Safari 15.
|
||||
*/
|
||||
export const listen = <K extends keyof HTMLElementEventMap>(
|
||||
target: EventTarget,
|
||||
type: K,
|
||||
listener: (ev: HTMLElementEventMap[K]) => void,
|
||||
options?: boolean | AddEventListenerOptions
|
||||
): (() => void) => {
|
||||
target.addEventListener(type, listener as EventListener, options);
|
||||
return () =>
|
||||
target.removeEventListener(type, listener as EventListener, options);
|
||||
};
|
||||
@@ -0,0 +1,7 @@
|
||||
let counter = 0;
|
||||
|
||||
/** An id that is unique within the page, for linking elements with ARIA. */
|
||||
export const uniqueId = (prefix: string): string => {
|
||||
counter += 1;
|
||||
return `${prefix}-${counter}`;
|
||||
};
|
||||
@@ -0,0 +1,414 @@
|
||||
import {
|
||||
autoUpdate,
|
||||
computePosition,
|
||||
flip,
|
||||
offset,
|
||||
type Placement,
|
||||
shift,
|
||||
type SideObject,
|
||||
size,
|
||||
} from "@floating-ui/dom";
|
||||
import {
|
||||
css,
|
||||
type CSSResultGroup,
|
||||
html,
|
||||
LitElement,
|
||||
nothing,
|
||||
type PropertyValues,
|
||||
type TemplateResult,
|
||||
} from "lit";
|
||||
import { property, query } from "lit/decorators.js";
|
||||
import { listen } from "../element/listen";
|
||||
import { uniqueId } from "../element/unique-id";
|
||||
|
||||
const supportsPopover =
|
||||
typeof HTMLElement !== "undefined" &&
|
||||
Object.prototype.hasOwnProperty.call(HTMLElement.prototype, "popover");
|
||||
|
||||
// Open popups, newest last, so Escape closes only the topmost one
|
||||
const openPopups: PopupBase[] = [];
|
||||
|
||||
const VIEWPORT_PADDING = 8;
|
||||
|
||||
/**
|
||||
* Why a popup closed. `programmatic` covers `hide()`, setting `open`,
|
||||
* `disabled` and the anchor going away.
|
||||
*/
|
||||
export type PopupHideReason =
|
||||
| "anchor-click"
|
||||
| "click-outside"
|
||||
| "escape-key"
|
||||
| "focus-out"
|
||||
| "mouse-leave"
|
||||
| "programmatic";
|
||||
|
||||
export interface PopupHideDetail {
|
||||
reason: PopupHideReason;
|
||||
}
|
||||
|
||||
const SIDES = ["top", "right", "bottom", "left"] as const;
|
||||
|
||||
// Distance to keep from each viewport edge: the padding plus the safe area,
|
||||
// like a notch or the Android navigation bar, which flip, shift and size
|
||||
// otherwise ignore
|
||||
const edgePadding = (body: HTMLElement): SideObject => {
|
||||
const styles = getComputedStyle(body);
|
||||
const padding = {} as SideObject;
|
||||
for (const side of SIDES) {
|
||||
padding[side] =
|
||||
VIEWPORT_PADDING +
|
||||
(parseFloat(styles.getPropertyValue(`--_safe-area-${side}`)) || 0);
|
||||
}
|
||||
return padding;
|
||||
};
|
||||
|
||||
/**
|
||||
* Base of floating elements like hac-popover: finds the anchor by id, shows
|
||||
* the body in the top layer where the Popover API exists (fixed positioning
|
||||
* otherwise), positions it with floating-ui and closes it with Escape or a
|
||||
* press outside. Events are named after the element, like
|
||||
* `hac-popover-show`, so a listener further out can tell them apart from
|
||||
* those of a dialog or menu around it.
|
||||
*/
|
||||
export abstract class PopupBase extends LitElement {
|
||||
/** The id of the anchor element, in the same root as the popup. */
|
||||
@property() public for?: string;
|
||||
|
||||
/** Whether the popup is shown. */
|
||||
@property({ type: Boolean, reflect: true }) public open = false;
|
||||
|
||||
/**
|
||||
* Preferred placement relative to the anchor: `top`, `right`, `bottom` or
|
||||
* `left`, optionally followed by `-start` or `-end`. Flips to the other
|
||||
* side when there is no room.
|
||||
*/
|
||||
@property({ reflect: true }) public placement: Placement = "top";
|
||||
|
||||
/** Distance from the anchor in pixels. */
|
||||
@property({ type: Number }) public distance = 8;
|
||||
|
||||
/** Offset along the anchor in pixels. */
|
||||
@property({ type: Number }) public skidding = 0;
|
||||
|
||||
/** Prevents the popup from opening. */
|
||||
@property({ type: Boolean, reflect: true }) public disabled = false;
|
||||
|
||||
@query(".body", true) protected body?: HTMLElement;
|
||||
|
||||
protected anchor: HTMLElement | null = null;
|
||||
|
||||
/** Prefix of the events, usually the tag name. */
|
||||
protected abstract readonly eventPrefix: string;
|
||||
|
||||
// Whether the body is shown. `open` can briefly differ while a show or hide
|
||||
// event is being cancelled.
|
||||
private _shown = false;
|
||||
|
||||
private _hideReason?: PopupHideReason;
|
||||
|
||||
private _detachAnchor: (() => void)[] = [];
|
||||
|
||||
private _detachDocument: (() => void)[] = [];
|
||||
|
||||
private _stopAutoUpdate?: () => void;
|
||||
|
||||
public show(): void {
|
||||
this.open = true;
|
||||
}
|
||||
|
||||
public hide(): void {
|
||||
this.open = false;
|
||||
}
|
||||
|
||||
public connectedCallback(): void {
|
||||
super.connectedCallback();
|
||||
if (!this.id) {
|
||||
this.id = uniqueId(this.localName);
|
||||
}
|
||||
if (this.hasUpdated) {
|
||||
this._resolveAnchor();
|
||||
}
|
||||
}
|
||||
|
||||
public disconnectedCallback(): void {
|
||||
super.disconnectedCallback();
|
||||
this._setAnchor(null);
|
||||
this._teardownOpen();
|
||||
}
|
||||
|
||||
protected updated(changedProps: PropertyValues<this>): void {
|
||||
super.updated(changedProps);
|
||||
// Also retry while the anchor is missing, as it may render after the popup
|
||||
if (changedProps.has("for") || (this.for && !this.anchor)) {
|
||||
this._resolveAnchor();
|
||||
}
|
||||
if (changedProps.has("disabled") && this.disabled && this.open) {
|
||||
this.open = false;
|
||||
}
|
||||
if (changedProps.has("open")) {
|
||||
this._syncOpen();
|
||||
}
|
||||
if (
|
||||
this._shown &&
|
||||
(changedProps.has("placement") ||
|
||||
changedProps.has("distance") ||
|
||||
changedProps.has("skidding"))
|
||||
) {
|
||||
this._reposition();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the listeners that open and close the popup to the anchor. Returns
|
||||
* the functions that remove them again.
|
||||
*/
|
||||
protected abstract attachAnchor(anchor: HTMLElement): (() => void)[];
|
||||
|
||||
/** Called after the anchor changed, to update its ARIA attributes. */
|
||||
protected anchorChanged(
|
||||
_anchor: HTMLElement | null,
|
||||
_oldAnchor: HTMLElement | null
|
||||
): void {
|
||||
// Implemented by subclasses
|
||||
}
|
||||
|
||||
/** Closes the popup and passes the reason to the hide events. */
|
||||
protected close(reason: PopupHideReason): void {
|
||||
if (this.open) {
|
||||
this._hideReason = reason;
|
||||
this.open = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Closes the popup on Escape. Subclasses may also move focus. */
|
||||
protected handleEscape(): void {
|
||||
this.close("escape-key");
|
||||
}
|
||||
|
||||
protected renderBody(): TemplateResult {
|
||||
return html`<slot></slot>`;
|
||||
}
|
||||
|
||||
protected render(): TemplateResult {
|
||||
return html`<div
|
||||
part="body base"
|
||||
class="body"
|
||||
popover=${supportsPopover ? "manual" : nothing}
|
||||
?hidden=${!this.open}
|
||||
>
|
||||
${this.renderBody()}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
private _resolveAnchor(): void {
|
||||
const root = this.getRootNode() as Document | ShadowRoot;
|
||||
const anchor =
|
||||
this.for && "getElementById" in root
|
||||
? root.getElementById(this.for)
|
||||
: null;
|
||||
if (anchor !== this.anchor) {
|
||||
this._setAnchor(anchor);
|
||||
}
|
||||
}
|
||||
|
||||
private _setAnchor(anchor: HTMLElement | null): void {
|
||||
const oldAnchor = this.anchor;
|
||||
this._detachAnchor.forEach((detach) => detach());
|
||||
this.anchor = anchor;
|
||||
this._detachAnchor = anchor ? this.attachAnchor(anchor) : [];
|
||||
this.anchorChanged(anchor, oldAnchor);
|
||||
if (!anchor && this.open) {
|
||||
this.open = false;
|
||||
}
|
||||
if (anchor && this._shown) {
|
||||
this._startAutoUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
// Runs a show or hide when `open` and the shown state differ. A cancelled
|
||||
// event resets `open`, which then matches again and runs nothing.
|
||||
private _syncOpen(): void {
|
||||
const reason = this._hideReason ?? "programmatic";
|
||||
this._hideReason = undefined;
|
||||
if (this.open === this._shown) {
|
||||
return;
|
||||
}
|
||||
if (this.open) {
|
||||
if (!this.anchor) {
|
||||
this._resolveAnchor();
|
||||
}
|
||||
if (this.disabled || !this.anchor || !this._fire("show", true)) {
|
||||
this.open = false;
|
||||
return;
|
||||
}
|
||||
this._showBody();
|
||||
this._fire("after-show");
|
||||
return;
|
||||
}
|
||||
const detail: PopupHideDetail = { reason };
|
||||
if (!this._fire("hide", true, detail)) {
|
||||
this.open = true;
|
||||
return;
|
||||
}
|
||||
this._teardownOpen();
|
||||
this._fire("after-hide", false, detail);
|
||||
}
|
||||
|
||||
private _showBody(): void {
|
||||
const body = this.body;
|
||||
if (!body) {
|
||||
return;
|
||||
}
|
||||
this._shown = true;
|
||||
if (supportsPopover && !body.matches(":popover-open")) {
|
||||
body.showPopover();
|
||||
}
|
||||
openPopups.push(this);
|
||||
this._detachDocument = [
|
||||
// Capture phase on window, so Escape closes the popup before a dialog
|
||||
// around it sees the key
|
||||
listen(window, "keydown", this._handleKeyDown, true),
|
||||
listen(document, "pointerdown", this._handlePointerDown, true),
|
||||
];
|
||||
this._startAutoUpdate();
|
||||
}
|
||||
|
||||
private _startAutoUpdate(): void {
|
||||
this._stopAutoUpdate?.();
|
||||
const body = this.body;
|
||||
this._stopAutoUpdate =
|
||||
this.anchor && body
|
||||
? autoUpdate(this.anchor, body, () => this._reposition())
|
||||
: undefined;
|
||||
}
|
||||
|
||||
private _teardownOpen(): void {
|
||||
if (!this._shown) {
|
||||
return;
|
||||
}
|
||||
this._shown = false;
|
||||
this._detachDocument.forEach((detach) => detach());
|
||||
this._detachDocument = [];
|
||||
this._stopAutoUpdate?.();
|
||||
this._stopAutoUpdate = undefined;
|
||||
const index = openPopups.indexOf(this);
|
||||
if (index !== -1) {
|
||||
openPopups.splice(index, 1);
|
||||
}
|
||||
const body = this.body;
|
||||
if (supportsPopover && body?.matches(":popover-open")) {
|
||||
body.hidePopover();
|
||||
}
|
||||
}
|
||||
|
||||
private async _reposition(): Promise<void> {
|
||||
const anchor = this.anchor;
|
||||
const body = this.body;
|
||||
if (!anchor || !body || !this._shown) {
|
||||
return;
|
||||
}
|
||||
const padding = edgePadding(body);
|
||||
const { x, y, placement } = await computePosition(anchor, body, {
|
||||
strategy: "fixed",
|
||||
placement: this.placement,
|
||||
middleware: [
|
||||
offset({ mainAxis: this.distance, crossAxis: this.skidding }),
|
||||
flip({ padding }),
|
||||
shift({ padding }),
|
||||
size({
|
||||
padding,
|
||||
apply: ({ availableWidth, availableHeight }) => {
|
||||
body.style.setProperty(
|
||||
"--available-width",
|
||||
`${Math.max(0, availableWidth)}px`
|
||||
);
|
||||
body.style.setProperty(
|
||||
"--available-height",
|
||||
`${Math.max(0, availableHeight)}px`
|
||||
);
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
body.style.left = `${x}px`;
|
||||
body.style.top = `${y}px`;
|
||||
body.dataset.placement = placement;
|
||||
}
|
||||
|
||||
private _handleKeyDown = (ev: KeyboardEvent): void => {
|
||||
if (
|
||||
ev.key !== "Escape" ||
|
||||
ev.isComposing ||
|
||||
openPopups[openPopups.length - 1] !== this
|
||||
) {
|
||||
return;
|
||||
}
|
||||
ev.preventDefault();
|
||||
ev.stopPropagation();
|
||||
this.handleEscape();
|
||||
};
|
||||
|
||||
private _handlePointerDown = (ev: PointerEvent): void => {
|
||||
const path = ev.composedPath();
|
||||
if (path.includes(this) || (this.anchor && path.includes(this.anchor))) {
|
||||
return;
|
||||
}
|
||||
this.close("click-outside");
|
||||
};
|
||||
|
||||
private _fire(
|
||||
type: string,
|
||||
cancelable = false,
|
||||
detail: PopupHideDetail | null = null
|
||||
): boolean {
|
||||
return this.dispatchEvent(
|
||||
new CustomEvent(`${this.eventPrefix}-${type}`, {
|
||||
bubbles: true,
|
||||
composed: true,
|
||||
cancelable,
|
||||
detail,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
static styles: CSSResultGroup = css`
|
||||
:host {
|
||||
display: contents;
|
||||
/* Home Assistant's insets include the companion app's */
|
||||
--_safe-area-top: var(
|
||||
--safe-area-inset-top,
|
||||
env(safe-area-inset-top, 0px)
|
||||
);
|
||||
--_safe-area-right: var(
|
||||
--safe-area-inset-right,
|
||||
env(safe-area-inset-right, 0px)
|
||||
);
|
||||
--_safe-area-bottom: var(
|
||||
--safe-area-inset-bottom,
|
||||
env(safe-area-inset-bottom, 0px)
|
||||
);
|
||||
--_safe-area-left: var(
|
||||
--safe-area-inset-left,
|
||||
env(safe-area-inset-left, 0px)
|
||||
);
|
||||
}
|
||||
|
||||
.body {
|
||||
position: fixed;
|
||||
inset: auto;
|
||||
left: 0;
|
||||
top: 0;
|
||||
z-index: 1000;
|
||||
box-sizing: border-box;
|
||||
width: max-content;
|
||||
max-width: var(--available-width, 100vw);
|
||||
margin: 0;
|
||||
border: 0;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.body[hidden] {
|
||||
display: none;
|
||||
}
|
||||
`;
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import "../src/components/popover/global";
|
||||
import type { HacPopover } from "../src/components/popover/hac-popover";
|
||||
|
||||
const mount = async () => {
|
||||
document.body.innerHTML = `
|
||||
<button id="anchor">More info</button>
|
||||
<hac-popover for="anchor"><a id="link" href="#">Learn more</a></hac-popover>
|
||||
<button id="outside">Next</button>
|
||||
`;
|
||||
const popover = document.querySelector("hac-popover") as HacPopover;
|
||||
await popover.updateComplete;
|
||||
const get = (id: string) => document.getElementById(id) as HTMLElement;
|
||||
return {
|
||||
popover,
|
||||
anchor: get("anchor"),
|
||||
link: get("link"),
|
||||
outside: get("outside"),
|
||||
};
|
||||
};
|
||||
|
||||
const pressEscape = () =>
|
||||
window.dispatchEvent(
|
||||
new KeyboardEvent("keydown", { key: "Escape", bubbles: true })
|
||||
);
|
||||
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
// Keyboard and screen reader users rely on the anchor's state and on focus
|
||||
// coming back to the anchor; nothing else shows them the popover closed.
|
||||
describe("hac-popover", () => {
|
||||
it("links the anchor and toggles on click", async () => {
|
||||
const { popover, anchor } = await mount();
|
||||
expect(anchor.getAttribute("aria-controls")).toBe(popover.id);
|
||||
expect(anchor.getAttribute("aria-expanded")).toBe("false");
|
||||
|
||||
anchor.click();
|
||||
await popover.updateComplete;
|
||||
expect(popover.open).toBe(true);
|
||||
expect(anchor.getAttribute("aria-expanded")).toBe("true");
|
||||
|
||||
anchor.click();
|
||||
await popover.updateComplete;
|
||||
expect(popover.open).toBe(false);
|
||||
expect(anchor.getAttribute("aria-expanded")).toBe("false");
|
||||
});
|
||||
|
||||
it("returns focus to the anchor on Escape from inside", async () => {
|
||||
const { popover, anchor, link } = await mount();
|
||||
anchor.click();
|
||||
await popover.updateComplete;
|
||||
link.focus();
|
||||
|
||||
pressEscape();
|
||||
await popover.updateComplete;
|
||||
expect(popover.open).toBe(false);
|
||||
expect(document.activeElement).toBe(anchor);
|
||||
});
|
||||
|
||||
it("closes when focus leaves the anchor and the content", async () => {
|
||||
const { popover, anchor, link, outside } = await mount();
|
||||
anchor.focus();
|
||||
anchor.click();
|
||||
await popover.updateComplete;
|
||||
|
||||
link.focus();
|
||||
await popover.updateComplete;
|
||||
expect(popover.open).toBe(true);
|
||||
|
||||
outside.focus();
|
||||
await popover.updateComplete;
|
||||
expect(popover.open).toBe(false);
|
||||
});
|
||||
|
||||
it("stays open while focus is inside when the mouse leaves", async () => {
|
||||
const { popover, anchor, link } = await mount();
|
||||
popover.trigger = "hover";
|
||||
const mouse = (type: string) =>
|
||||
anchor.dispatchEvent(new PointerEvent(type, { pointerType: "mouse" }));
|
||||
mouse("pointerenter");
|
||||
await new Promise((resolve) => {
|
||||
setTimeout(resolve, 200);
|
||||
});
|
||||
expect(popover.open).toBe(true);
|
||||
|
||||
link.focus();
|
||||
mouse("pointerleave");
|
||||
await new Promise((resolve) => {
|
||||
setTimeout(resolve, 200);
|
||||
});
|
||||
expect(popover.open).toBe(true);
|
||||
});
|
||||
|
||||
it("runs each transition once when one is cancelled", async () => {
|
||||
const { popover, anchor } = await mount();
|
||||
const fired: string[] = [];
|
||||
for (const type of ["show", "after-show", "hide", "after-hide"]) {
|
||||
popover.addEventListener(`hac-popover-${type}`, () => fired.push(type));
|
||||
}
|
||||
popover.addEventListener("hac-popover-hide", (ev) => ev.preventDefault(), {
|
||||
once: true,
|
||||
});
|
||||
|
||||
anchor.click();
|
||||
await popover.updateComplete;
|
||||
popover.hide();
|
||||
await popover.updateComplete;
|
||||
await popover.updateComplete;
|
||||
expect(popover.open).toBe(true);
|
||||
expect(fired).toEqual(["show", "after-show", "hide"]);
|
||||
});
|
||||
|
||||
// Parents like a picker react differently to Escape than to a press outside
|
||||
it("tells why it closed", async () => {
|
||||
const { popover, anchor, outside } = await mount();
|
||||
const reasons: string[] = [];
|
||||
popover.addEventListener("hac-popover-after-hide", (ev) =>
|
||||
reasons.push(ev.detail.reason)
|
||||
);
|
||||
const closeWith = async (close: () => void) => {
|
||||
anchor.click();
|
||||
await popover.updateComplete;
|
||||
close();
|
||||
await popover.updateComplete;
|
||||
};
|
||||
|
||||
await closeWith(() => anchor.click());
|
||||
await closeWith(pressEscape);
|
||||
await closeWith(() =>
|
||||
outside.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true }))
|
||||
);
|
||||
await closeWith(() => popover.hide());
|
||||
expect(reasons).toEqual([
|
||||
"anchor-click",
|
||||
"escape-key",
|
||||
"click-outside",
|
||||
"programmatic",
|
||||
]);
|
||||
});
|
||||
|
||||
it("finds an anchor rendered after the popover", async () => {
|
||||
document.body.innerHTML = `<hac-popover for="late">Text</hac-popover>`;
|
||||
const popover = document.querySelector("hac-popover") as HacPopover;
|
||||
await popover.updateComplete;
|
||||
const anchor = document.createElement("button");
|
||||
anchor.id = "late";
|
||||
popover.before(anchor);
|
||||
|
||||
popover.show();
|
||||
await popover.updateComplete;
|
||||
expect(popover.open).toBe(true);
|
||||
expect(anchor.getAttribute("aria-expanded")).toBe("true");
|
||||
});
|
||||
});
|
||||
Generated
+4
@@ -738,6 +738,10 @@ importers:
|
||||
version: 7.4.1(patch_hash=75e6346ad8d8af554c167f77ac7d9b9652f010398efdc6b399925a4795133099)([email protected])
|
||||
|
||||
packages/components:
|
||||
dependencies:
|
||||
'@floating-ui/dom':
|
||||
specifier: ^1.8.0
|
||||
version: 1.8.0
|
||||
devDependencies:
|
||||
'@custom-elements-manifest/analyzer':
|
||||
specifier: 0.11.0
|
||||
|
||||
@@ -94,6 +94,12 @@
|
||||
"matchDepTypes": ["peerDependencies"],
|
||||
"rangeStrategy": "widen"
|
||||
},
|
||||
{
|
||||
"description": "Keep semver ranges for dependencies of the published components package, so consumers can share one copy with other libraries",
|
||||
"matchFileNames": ["packages/components/package.json"],
|
||||
"matchDepTypes": ["dependencies"],
|
||||
"rangeStrategy": "bump"
|
||||
},
|
||||
{
|
||||
"description": "Group all Python version updates from home-assistant/core",
|
||||
"matchDepNames": ["python"],
|
||||
|
||||
Reference in new issue
Block a user