Compare commits

..
Author SHA1 Message Date
renovate[bot] c682a9970c Update ghcr.io/element-hq/element-web:develop Docker digest to 01b0026 (#4536)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-12-01 01:26:19 +00:00
Robin 36b0e41269 Merge pull request #4481 from element-hq/robin/popover
Create generic popover component
2026-11-30 14:21:44 -05:00
Robin 51e6baea17 Add close button to Popover 2026-11-30 14:13:12 -05:00
Robin 3a9708020a Make Popover respect custom root element 2026-11-30 13:25:21 -05:00
Robin 6e6494fe38 Merge branch 'main' into robin/popover 2026-11-30 13:21:01 -05:00
Robin 0eff661159 Create generic popover component 2026-11-19 23:53:19 -05:00
16 changed files with 421 additions and 197 deletions
+6 -36
View File
@@ -22,24 +22,13 @@ const LabelledButton = (): ReactNode => (
</TooltipProvider>
);
/** The element that the button's tooltip label was floated into. */
const labelParent = (): HTMLElement | null => {
const button = screen.getByRole("button", { name: "Microphone" });
return document.getElementById(button.getAttribute("aria-labelledby")!)!
.parentElement;
};
/** The container of Element Call's own that the tooltip floated into. */
const portalOf = (element: HTMLElement | null): Element | null =>
element?.closest("[data-element-call-portal]") ?? null;
test("floats into the host document with no root", () => {
render(
<CallPortalRoot root={undefined}>
<LabelledButton />
</CallPortalRoot>,
);
expect(portalOf(labelParent())?.parentElement).toBe(document.body);
expect(screen.getByRole("button", { name: "Microphone" })).toBeTruthy();
});
test("floats into the root it is given", () => {
@@ -50,33 +39,14 @@ test("floats into the root it is given", () => {
<LabelledButton />
</CallPortalRoot>,
);
// Into a container of Element Call's own, for its stylesheets to find
expect(portalOf(labelParent())?.parentElement).toBe(root);
const button = screen.getByRole("button", { name: "Microphone" });
const label = document.getElementById(
button.getAttribute("aria-labelledby")!,
);
expect(root.contains(label)).toBe(true);
root.remove();
});
test("moves what floated along when the root changes", () => {
const first = document.createElement("div");
const second = document.createElement("div");
document.body.append(first, second);
const { rerender, unmount } = render(
<CallPortalRoot root={first}>
<LabelledButton />
</CallPortalRoot>,
);
rerender(
<CallPortalRoot root={second}>
<LabelledButton />
</CallPortalRoot>,
);
expect(first.querySelector("[data-element-call-portal]")).toBeNull();
expect(portalOf(labelParent())?.parentElement).toBe(second);
unmount();
expect(second.querySelector("[data-element-call-portal]")).toBeNull();
first.remove();
second.remove();
});
test("waits for a root that is not available yet", () => {
render(
<CallPortalRoot root={null}>
+9 -37
View File
@@ -5,50 +5,22 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { type FC, type ReactNode, useLayoutEffect, useState } from "react";
import { type FC, type ReactNode } from "react";
import { PortalRoot } from "@vector-im/compound-web";
import { PortalElementProvider } from "../src/RootElementContext";
interface Props {
root: HTMLElement | null | undefined;
children: ReactNode;
}
/**
* Where Compound floats the call's menus and tooltips: a container of Element
* Call's own inside `root`, or inside the host document's body with no `root`.
* With `null`, the root is not available yet and the container stays out of
* the document until it is, so nothing floated is shown before then.
*
* The container is marked `data-element-call-portal` and carries the call's
* theme and platform (see `useTheme`), so that Element Call's stylesheets reach
* what floats out of its root just as they reach what stays inside.
* Where Compound floats the call's menus and tooltips. With no `root` the call
* is not wrapped at all and they go into the host document's body; `null` is
* Compound's "not available yet", and the floating parts wait for it.
*/
export const CallPortalRoot: FC<Props> = ({ root, children }): ReactNode => {
// One container for the call's lifetime, moved to wherever the root is.
// What Compound has floated into it moves along, even into another
// document such as a Picture-in-Picture window's; Compound itself leaves
// what it floated where it was when its root changes.
const [container] = useState(() => {
const element = document.createElement("div");
element.setAttribute("data-element-call-portal", "");
return element;
});
useLayoutEffect(() => {
const parent = root === undefined ? document.body : root;
// Left out of the document until the root is available
if (parent === null) return;
parent.append(container);
return (): void => container.remove();
}, [root, container]);
return (
<PortalRoot root={container}>
<PortalElementProvider value={container}>
{children}
</PortalElementProvider>
</PortalRoot>
export const CallPortalRoot: FC<Props> = ({ root, children }): ReactNode =>
root === undefined ? (
children
) : (
<PortalRoot root={root}>{children}</PortalRoot>
);
};
+6 -24
View File
@@ -8,15 +8,10 @@ Please see LICENSE in the repository root for full details.
import { describe, expect, it } from "vitest";
import postcss from "postcss";
import {
PORTAL_SELECTOR,
ROOT_SELECTOR,
scopeStylesToRoot,
} from "./scopeStylesToRoot";
import { ROOT_SELECTOR, scopeStylesToRoot } from "./scopeStylesToRoot";
const inRoot = `:where(${ROOT_SELECTOR}, ${ROOT_SELECTOR} *, ${PORTAL_SELECTOR}, ${PORTAL_SELECTOR} *)`;
const inRoot = `:where(${ROOT_SELECTOR}, ${ROOT_SELECTOR} *)`;
const isRoot = `:where(${ROOT_SELECTOR})`;
const isRootOrPortal = `:where(${ROOT_SELECTOR}, ${PORTAL_SELECTOR})`;
async function scope(css: string, file = "base.css"): Promise<string> {
const result = await postcss([scopeStylesToRoot()]).process(css, {
@@ -31,10 +26,7 @@ describe("scopeStylesToRoot", () => {
`${isRoot} { line-height: 1.15 }`,
);
expect(await scope("body { margin: 0 }")).toBe(`${isRoot} { margin: 0 }`);
// The custom properties are needed by what floats out of the root too
expect(await scope(":root { --a: 1 }")).toBe(
`${isRootOrPortal} { --a: 1 }`,
);
expect(await scope(":root { --a: 1 }")).toBe(`${isRoot} { --a: 1 }`);
expect(await scope("body.no-scroll-body { position: fixed }")).toBe(
`${isRoot}.no-scroll-body { position: fixed }`,
);
@@ -74,11 +66,9 @@ describe("scopeStylesToRoot", () => {
);
});
it("leaves alone what already names the root or the portal", async () => {
it("leaves alone what already names the root", async () => {
const css = `${ROOT_SELECTOR}[data-platform="ios"] { --a: 1 }`;
expect(await scope(css)).toBe(css);
const portal = `${PORTAL_SELECTOR}[data-platform="ios"] { --a: 1 }`;
expect(await scope(portal)).toBe(portal);
});
it("reaches into layers and media queries", async () => {
@@ -109,8 +99,8 @@ describe("scopeStylesToRoot", () => {
expect(await scope("pre { font-size: 1px }", file)).toBe(
`pre${inRoot} { font-size: 1px }`,
);
expect(await scope("[data-x] pre { font-size: 1px }", file)).toBe(
`[data-x] pre${inRoot} { font-size: 1px }`,
expect(await scope(".modal pre { font-size: 1px }", file)).toBe(
`.modal pre${inRoot} { font-size: 1px }`,
);
expect(await scope(".box_abc12 { border: 0 }", file)).toBe(
".box_abc12 { border: 0 }",
@@ -118,14 +108,6 @@ describe("scopeStylesToRoot", () => {
expect(await scope(".a .b_abc12:hover { border: 0 }", file)).toBe(
".a .b_abc12:hover { border: 0 }",
);
// Confined by the class on an ancestor: these must still match in a menu
// that Compound portals out of the root
expect(await scope(".preview_abc12>video { inset: 0 }", file)).toBe(
".preview_abc12>video { inset: 0 }",
);
expect(
await scope(".menu_abc12 [role^=menuitem]:focus { outline: 0 }", file),
).toBe(".menu_abc12 [role^=menuitem]:focus { outline: 0 }");
});
it("leaves an excluded stylesheet as it is", async () => {
+14 -37
View File
@@ -24,27 +24,16 @@ import selectorParser, {
*/
export const ROOT_SELECTOR = "[data-element-call-root]";
/**
* How the stylesheets find the container that Element Call's menus and
* tooltips float into, outside the root. `CallPortalRoot` creates it in the
* host's document; it counts as Element Call's own, the way the root does.
*/
export const PORTAL_SELECTOR = "[data-element-call-portal]";
// Both are `:where()`, which has no specificity of its own, so the rules keep
// exactly the weight they had before being scoped and nothing in Element Call's
// cascade changes — only where it applies.
//
// The root or the portal container, or anything inside either. Appended to the
// element a rule is about, rather than prepended to the whole selector, so that
// a rule about the root itself (its theme class, say) still matches.
const IN_ROOT = `:where(${ROOT_SELECTOR}, ${ROOT_SELECTOR} *, ${PORTAL_SELECTOR}, ${PORTAL_SELECTOR} *)`;
// The root itself, standing in for the document's `html` and `body`. The page's
// own furniture (its height, margin and background) is not the portal's.
// The root, or anything inside it. Appended to the element a rule is about,
// rather than prepended to the whole selector, so that a rule about the root
// itself (its theme class, say) still matches.
const IN_ROOT = `:where(${ROOT_SELECTOR}, ${ROOT_SELECTOR} *)`;
// The root itself, standing in for the document.
const IS_ROOT = `:where(${ROOT_SELECTOR})`;
// The root and the portal container, standing in for `:root`: the custom
// properties declared there are needed by whatever floats out of the root too.
const IS_ROOT_OR_PORTAL = `:where(${ROOT_SELECTOR}, ${PORTAL_SELECTOR})`;
/**
* Confines a stylesheet to Element Call's root element, for the build of
@@ -56,22 +45,15 @@ const IS_ROOT_OR_PORTAL = `:where(${ROOT_SELECTOR}, ${PORTAL_SELECTOR})`;
* the host's document too. This rewrites every selector so that it matches only
* the root or its descendants:
*
* - `html` and `body` become the root element, which is what stands in for the
* document inside a host. `:root` becomes the root and the portal container
* (see `PORTAL_SELECTOR`), so that its custom properties reach both.
* - `html`, `body` and `:root` become the root element, which is what stands in
* for the document inside a host.
* - Everything else keeps its selector and gains `:where([data-element-call-root],
* [data-element-call-root] *, [data-element-call-portal],
* [data-element-call-portal] *)` on the element it styles, so that it applies
* to the menus and tooltips Compound floats out of the root as well.
* - Selectors that already name the root or the portal container are left
* alone, as are keyframe selectors and rules nested inside another rule,
* which are relative to it.
* [data-element-call-root] *)` on the element it styles.
* - Selectors that already name the root are left alone, as are keyframe
* selectors and rules nested inside another rule, which are relative to it.
*
* CSS modules are scoped by their class names already, so only their selectors
* without a class anywhere — `pre`, but neither `.pre` nor `.modal pre` — are
* touched. A module class on an ancestor confines a rule as well as one on the
* element it styles, and scoping such a rule would break it wherever Compound
* portals that part of Element Call out of the root, as it does menus.
* that would match by element alone — `pre` rather than `.pre` — are touched.
*
* The root's custom properties are still inherited by everything inside it,
* the way they were from `:root`. Compound's own stylesheet — the design
@@ -135,8 +117,7 @@ const scopeAll = processor(false);
const scopeBare = processor(true);
function scopeSelector(selector: Selector, isModule: boolean): void {
const text = String(selector);
if (text.includes(ROOT_SELECTOR) || text.includes(PORTAL_SELECTOR)) return;
if (String(selector).includes(ROOT_SELECTOR)) return;
const compounds = splitCompounds(selector);
if (compounds.length === 0) return;
@@ -144,16 +125,12 @@ function scopeSelector(selector: Selector, isModule: boolean): void {
// Something said of the document is said of the root instead
const document = compounds[0].find(isDocumentSelector);
if (document !== undefined) {
document.replaceWith(
pseudo(document.type === "pseudo" ? IS_ROOT_OR_PORTAL : IS_ROOT),
);
document.replaceWith(pseudo(IS_ROOT));
return;
}
if (isModule && compounds.some((c) => c.some((n) => n.type === "class")))
return;
const subject = compounds.at(-1)!;
if (isModule && subject.some((node) => node.type === "class")) return;
// Pseudo-elements have to come last in a compound selector
const pseudoElement = subject.find(isPseudoElement);
+2 -2
View File
@@ -19,10 +19,10 @@ services:
- ./backend/playwright_homeserver-othersite.yaml:/data/cfg/homeserver.yaml:Z
element-web:
# Pin to a SHA so that upstream cannot break our tests. Renovate handles regular updates.
image: ghcr.io/element-hq/element-web:develop@sha256:9ed1f2140ce855b8e599bf4b16f9be47c3295738989574efbb0b8f0e159c5de7
image: ghcr.io/element-hq/element-web:develop@sha256:01b0026b7f8760c511d15bea7199873d1dd33cbdb43ba4b2e39b74f508583ca4
element-web-1:
# Pin to a SHA so that upstream cannot break our tests. Renovate handles regular updates.
image: ghcr.io/element-hq/element-web:develop@sha256:9ed1f2140ce855b8e599bf4b16f9be47c3295738989574efbb0b8f0e159c5de7
image: ghcr.io/element-hq/element-web:develop@sha256:01b0026b7f8760c511d15bea7199873d1dd33cbdb43ba4b2e39b74f508583ca4
volumes:
# The other site opens the embedded package under test in place of the
# copy its image bundles (the first site opens the dev server's app.
+1
View File
@@ -55,6 +55,7 @@
"build-storybook": "storybook build"
},
"devDependencies": {
"@base-ui/react": "^1.9.0",
"@codecov/vite-plugin": "^2.0.0",
"@fontsource/inconsolata": "^5.1.0",
"@fontsource/inter": "^5.1.0",
+58
View File
@@ -24,6 +24,9 @@ importers:
.:
devDependencies:
'@base-ui/react':
specifier: ^1.9.0
version: 1.9.0(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
'@codecov/vite-plugin':
specifier: ^2.0.0
version: 2.0.1(vite@8.3.8(@types/node@26.6.11)(esbuild@0.28.2)(jiti@2.7.0)(sass@1.108.2)(terser@5.46.1)(yaml@2.9.1))
@@ -432,6 +435,33 @@ packages:
resolution: {integrity: sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==}
engines: {node: '>=6.9.0'}
'@base-ui/react@1.9.0':
resolution: {integrity: sha512-S8CSYosASBKtpL8SWUfS78rFElfLijiCgA7oHOK22jCJ95FULsYyKwBNFOgudt0RA+/7yNc7F81bOvQnRgbBiQ==}
engines: {node: '>=14.0.0'}
peerDependencies:
'@date-fns/tz': ^1.2.0
'@types/react': ^17 || ^18 || ^19
date-fns: ^4.0.0
react: ^17 || ^18 || ^19
react-dom: ^17 || ^18 || ^19
peerDependenciesMeta:
'@date-fns/tz':
optional: true
'@types/react':
optional: true
date-fns:
optional: true
'@base-ui/utils@0.5.0':
resolution: {integrity: sha512-dYGGcEttjkYiMoa5nHm8vLaJ2UcuTWxo3BFAwOYXeRg/q7UVVvA6cacEIXEs3FgBfK1CGtW1ptElqs7wsx+t9A==}
peerDependencies:
'@types/react': ^17 || ^18 || ^19
react: ^17 || ^18 || ^19
react-dom: ^17 || ^18 || ^19
peerDependenciesMeta:
'@types/react':
optional: true
'@bcoe/v8-coverage@1.0.2':
resolution: {integrity: sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==}
engines: {node: '>=18'}
@@ -5319,6 +5349,9 @@ packages:
require-main-filename@2.0.0:
resolution: {integrity: sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==}
reselect@5.3.0:
resolution: {integrity: sha512-XGoLeRAVzUTcJ1qkxPQhDJyIZ5d6zzZD9nT7AEZOaaU9UbWclhycElmhO+VD5bFeLuzhPBaOV2oXC8uG35ZSpg==}
resolve-from@4.0.0:
resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==}
engines: {node: '>=4'}
@@ -6293,6 +6326,29 @@ snapshots:
'@babel/helper-string-parser': 7.29.7
'@babel/helper-validator-identifier': 7.29.7
'@base-ui/react@1.9.0(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)':
dependencies:
'@babel/runtime': 8.0.8
'@base-ui/utils': 0.5.0(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
'@floating-ui/react-dom': 2.1.9(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
'@floating-ui/utils': 0.2.12
react: 19.3.1
react-dom: 19.3.1(react@19.3.1)
use-sync-external-store: 1.7.0(react@19.3.1)
optionalDependencies:
'@types/react': 19.3.0
'@base-ui/utils@0.5.0(@types/react@19.3.0)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)':
dependencies:
'@babel/runtime': 8.0.8
'@floating-ui/utils': 0.2.12
react: 19.3.1
react-dom: 19.3.1(react@19.3.1)
reselect: 5.3.0
use-sync-external-store: 1.7.0(react@19.3.1)
optionalDependencies:
'@types/react': 19.3.0
'@bcoe/v8-coverage@1.0.2': {}
'@blazediff/core@1.9.1': {}
@@ -10988,6 +11044,8 @@ snapshots:
require-main-filename@2.0.0: {}
reselect@5.3.0: {}
resolve-from@4.0.0: {}
resolve@1.22.13:
+68
View File
@@ -0,0 +1,68 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
.popover {
position: relative;
border-radius: var(--cpd-space-3x);
background: var(--cpd-color-bg-canvas-default);
box-shadow: var(--big-drop-shadow);
padding: var(--cpd-space-5x);
box-sizing: border-box;
inline-size: 310px;
max-inline-size: 90vw;
/* Draw an internal border */
&::after {
content: "";
position: absolute;
inset: 0;
border: var(--cpd-border-width-1) solid
var(--cpd-color-border-interactive-secondary);
border-radius: inherit;
pointer-events: none;
}
transition:
opacity 180ms,
transform 180ms;
&[data-starting-style] {
opacity: 0;
@media (prefers-reduced-motion: no-preference) {
transform: translate(0, var(--cpd-space-3x));
}
}
&[data-ending-style] {
transition-duration: 110ms;
opacity: 0;
@media (prefers-reduced-motion: no-preference) {
transform: translate(0, var(--cpd-space-2x));
}
}
p {
font: var(--cpd-font-body-sm-regular);
color: var(--cpd-color-text-secondary);
margin-block-end: var(--cpd-space-4x);
}
}
.title {
width: 100%;
display: flex;
> h3 {
margin-block-end: var(--cpd-space-2x);
flex-grow: 1;
}
> button {
margin-block-start: calc(-1 * var(--cpd-space-1x));
margin-inline-end: calc(-1 * var(--cpd-space-1x));
}
}
+41
View File
@@ -0,0 +1,41 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import type { Meta, StoryObj } from "@storybook/react-vite";
import { Popover } from "./Popover";
import { Button } from "@vector-im/compound-web";
import { VideoCallOffSolidIcon } from "@vector-im/compound-design-tokens/assets/web/icons";
import { useState } from "react";
const meta = {
component: Popover,
} satisfies Meta<typeof Popover>;
export default meta;
export const Default: StoryObj = {
render: () => {
const [open, setOpen] = useState(true);
return (
<Popover
title="Poor connection"
trigger={<Button>Open popover</Button>}
open={open}
onOpenChange={setOpen}
>
<p>Turn off all videos to improve call performance.</p>
<Button
size="md"
Icon={VideoCallOffSolidIcon}
style={{ width: "100%", marginBlockStart: 24 }}
>
Turn off all videos
</Button>
</Popover>
);
},
};
+30
View File
@@ -0,0 +1,30 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { expect, test } from "vitest";
import { axe } from "vitest-axe";
import { render, screen } from "@testing-library/react";
import { Popover } from "./Popover";
test("Popover renders", async () => {
render(
<Popover
title="Example"
trigger={<button>Open popover</button>}
open
onOpenChange={() => {}}
>
<p>This is an example of a popover.</p>
</Popover>,
);
const button = screen.getByRole("button", { name: "Open popover" });
const popover = screen.getByRole("dialog", { name: "Example" });
expect(button).toMatchSnapshot("button");
expect(popover).toMatchSnapshot("popover");
expect(await axe(document.body)).toHaveNoViolations();
});
+104
View File
@@ -0,0 +1,104 @@
/*
Copyright 2026 Element Creations Ltd.
SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { type FC, type ReactElement, type ReactNode } from "react";
import { Popover as BUIPopover } from "@base-ui/react/popover";
import styles from "./Popover.module.css";
import { Heading, IconButton } from "@vector-im/compound-web";
import { CloseIcon } from "@vector-im/compound-design-tokens/assets/web/icons";
import classNames from "classnames";
import { useRootElement } from "./RootElementContext";
import { useTranslation } from "react-i18next";
export interface PopoverProps {
/**
* The popover title.
*/
title: string;
/**
* The button that opens the popover. This must be a component that accepts a
* ref and spreads props.
*
* https://base-ui.com/react/handbook/composition
*/
trigger: ReactElement;
/**
* Whether the popover is open.
*/
open: boolean;
/**
* Event handler called when the user tries to open or close the popover.
*/
onOpenChange: (open: boolean) => void;
/**
* The popover contents.
*/
children: ReactNode;
className?: string;
/**
* The side of the trigger on which to place the popover. Note that the menu
* may still end up on a different side than the one you request if there
* isn't enough space.
* @default bottom
*/
side?: "top" | "bottom" | "left" | "right" | "inline-end" | "inline-start";
/**
* The edge along which the popover and trigger will be aligned.
* @default center
*/
align?: "start" | "center" | "end";
}
/**
* A popover opened by pressing a button.
*/
export const Popover: FC<PopoverProps> = ({
title,
trigger,
open,
onOpenChange,
children,
className,
side,
align,
}) => {
const { t } = useTranslation();
const rootElement = useRootElement();
return (
<BUIPopover.Root open={open} onOpenChange={onOpenChange}>
<BUIPopover.Trigger render={trigger} />
<BUIPopover.Portal container={rootElement}>
<BUIPopover.Positioner sideOffset={8} side={side} align={align}>
<BUIPopover.Popup className={classNames(styles.popover, className)}>
<div className={styles.title}>
<BUIPopover.Title
render={
<Heading as="h3" type="body" weight="semibold" size="lg">
{title}
</Heading>
}
/>
<BUIPopover.Close
render={
<IconButton
kind="secondary"
size="28px"
aria-label={t("action.close")}
>
<CloseIcon />
</IconButton>
}
/>
</div>
{children}
</BUIPopover.Popup>
</BUIPopover.Positioner>
</BUIPopover.Portal>
</BUIPopover.Root>
);
};
-16
View File
@@ -41,19 +41,3 @@ export const RootElementProvider = RootElementContext.Provider;
*/
export const useRootElement = (): HTMLElement =>
use(RootElementContext) ?? document.body;
const PortalElementContext = createContext<HTMLElement | null>(null);
/**
* Supplies the container that Compound floats Element Call's menus and tooltips
* into when that is outside the root: the component build's `CallPortalRoot`.
*/
export const PortalElementProvider = PortalElementContext.Provider;
/**
* The container that Element Call's menus and tooltips float into, if it is
* not the root's own document body. It gets the root's theme and platform, so
* that what floats out of the root looks as it would inside.
*/
export const usePortalElement = (): HTMLElement | null =>
use(PortalElementContext);
+71
View File
@@ -0,0 +1,71 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`Popover renders > button 1`] = `
<button
aria-controls="_r_0_"
aria-expanded="true"
aria-haspopup="dialog"
data-base-ui-click-trigger=""
data-popup-open=""
id="base-ui-_r_1_"
tabindex="0"
type="button"
>
Open popover
</button>
`;
exports[`Popover renders > popover 1`] = `
<div
aria-labelledby="base-ui-_r_4_"
class="_popover_8e8188"
data-align="center"
data-base-ui-focusable=""
data-open=""
data-side="bottom"
id="_r_0_"
role="dialog"
tabindex="-1"
>
<div
class="_title_8e8188"
>
<h3
class="_typography_6v6n8_153 _font-body-lg-semibold_6v6n8_74"
id="base-ui-_r_4_"
>
Example
</h3>
<button
aria-disabled="false"
aria-label="Close"
class="_icon-button_1215g_8"
data-kind="secondary"
role="button"
style="--cpd-icon-button-size: 28px;"
tabindex="0"
type="button"
>
<div
class="_indicator-icon_j097f_17"
style="--cpd-icon-button-size: 100%;"
>
<svg
fill="currentColor"
height="1em"
viewBox="0 0 24 24"
width="1em"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M6.293 6.293a1 1 0 0 1 1.414 0L12 10.586l4.293-4.293a1 1 0 1 1 1.414 1.414L13.414 12l4.293 4.293a1 1 0 0 1-1.414 1.414L12 13.414l-4.293 4.293a1 1 0 0 1-1.414-1.414L10.586 12 6.293 7.707a1 1 0 0 1 0-1.414"
/>
</svg>
</div>
</button>
</div>
<p>
This is an example of a popover.
</p>
</div>
`;
+3 -7
View File
@@ -123,16 +123,12 @@ before using one further down the tree. */
/* On Android and iOS, prefer native system fonts. The global.css file of
Compound Web is where these variables ultimately get consumed to set the page's
font-family. Also on the container that menus and tooltips float into, which
is outside the root in the component build. */
:is(
[data-element-call-root],
[data-element-call-portal]
)[data-platform="android"] {
font-family. */
[data-element-call-root][data-platform="android"] {
--cpd-font-family-sans: "Roboto", "Noto", "Inter", sans-serif;
}
:is([data-element-call-root], [data-element-call-portal])[data-platform="ios"] {
[data-element-call-root][data-platform="ios"] {
--cpd-font-family-sans:
-apple-system, BlinkMacSystemFont, "Inter", sans-serif;
}
-19
View File
@@ -19,7 +19,6 @@ import {
} from "vitest";
import { useTheme } from "./useTheme";
import { PortalElementProvider } from "./RootElementContext";
import { platform } from "./Platform";
import { useUrlParams } from "./UrlParams";
import {
@@ -104,24 +103,6 @@ describe("useTheme", () => {
expect(document.body.getAttribute("data-platform")).toBe(platform);
});
test("gives the portal container the theme and platform too", () => {
const portal = document.createElement("div");
const withPortal: FC<PropsWithChildren> = ({ children }) =>
createElement(
wrapper,
null,
createElement(PortalElementProvider, { value: portal }, children),
);
renderHook(() => useTheme(), { wrapper: withPortal });
expect(portal.classList.contains("cpd-theme-dark")).toBe(true);
expect(portal.getAttribute("data-platform")).toBe(platform);
act(() => themeChange$.next({ data: { name: "light" }, reply: vi.fn() }));
expect(portal.classList.contains("cpd-theme-dark")).toBe(false);
expect(portal.classList.contains("cpd-theme-light")).toBe(true);
});
test("theme changes in response to host requests", () => {
renderHook(() => useTheme(), { wrapper });
+8 -19
View File
@@ -8,13 +8,12 @@ Please see LICENSE in the repository root for full details.
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { useUrlParams } from "./UrlParams";
import { usePortalElement, useRootElement } from "./RootElementContext";
import { useRootElement } from "./RootElementContext";
import { platform } from "./Platform";
import { useHostBridge } from "./HostBridge";
export const useTheme = (): void => {
const rootElement = useRootElement();
const portalElement = usePortalElement();
const hostBridge = useHostBridge();
const { theme } = useUrlParams();
const [requestedTheme, setRequestedTheme] = useState(theme);
@@ -38,14 +37,13 @@ export const useTheme = (): void => {
rootElement.setAttribute("data-platform", platform);
}, [rootElement]);
// If no theme has been explicitly requested we default to dark
const lightness = requestedTheme?.includes("light") ? "light" : "dark";
const themeHighContrast = requestedTheme?.includes("high-contrast")
? "-hc"
: "";
const themeString = "cpd-theme-" + lightness + themeHighContrast;
useLayoutEffect(() => {
// If no theme has been explicitly requested we default to dark
const theme = requestedTheme?.includes("light") ? "light" : "dark";
const themeHighContrast = requestedTheme?.includes("high-contrast")
? "-hc"
: "";
const themeString = "cpd-theme-" + theme + themeHighContrast;
if (themeString !== previousTheme.current) {
rootElement.classList.remove(
"cpd-theme-light",
@@ -57,14 +55,5 @@ export const useTheme = (): void => {
previousTheme.current = themeString;
}
rootElement.classList.remove("no-theme");
}, [previousTheme, themeString, rootElement]);
// The menus and tooltips floating outside the root get its theme and
// platform too, so that they look as they would inside it.
useLayoutEffect(() => {
if (portalElement === null) return;
portalElement.setAttribute("data-platform", platform);
portalElement.classList.add(themeString);
return (): void => portalElement.classList.remove(themeString);
}, [portalElement, themeString]);
}, [previousTheme, requestedTheme, rootElement]);
};