Compare commits

...
Author SHA1 Message Date
Timo K. 1a9ce198ed Make tooltips and modals also use a the scoped styles
Otherwise we would end up using EW's root styles (f.ex. `h3`) in EC's
modals. (EC's tooltips would look different in SPA vs Emebedded)
2026-11-30 18:49:28 +01:00
Timo K. 0a37f63736 Fix the script that scopes the Element Call prefixes styles. 2026-11-30 18:47:47 +01:00
8 changed files with 195 additions and 46 deletions
+36 -6
View File
@@ -22,13 +22,24 @@ 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(screen.getByRole("button", { name: "Microphone" })).toBeTruthy();
expect(portalOf(labelParent())?.parentElement).toBe(document.body);
});
test("floats into the root it is given", () => {
@@ -39,14 +50,33 @@ test("floats into the root it is given", () => {
<LabelledButton />
</CallPortalRoot>,
);
const button = screen.getByRole("button", { name: "Microphone" });
const label = document.getElementById(
button.getAttribute("aria-labelledby")!,
);
expect(root.contains(label)).toBe(true);
// Into a container of Element Call's own, for its stylesheets to find
expect(portalOf(labelParent())?.parentElement).toBe(root);
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}>
+37 -9
View File
@@ -5,22 +5,50 @@ 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 } from "react";
import { type FC, type ReactNode, useLayoutEffect, useState } 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. 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.
* 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.
*/
export const CallPortalRoot: FC<Props> = ({ root, children }): ReactNode =>
root === undefined ? (
children
) : (
<PortalRoot root={root}>{children}</PortalRoot>
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>
);
};
+24 -6
View File
@@ -8,10 +8,15 @@ Please see LICENSE in the repository root for full details.
import { describe, expect, it } from "vitest";
import postcss from "postcss";
import { ROOT_SELECTOR, scopeStylesToRoot } from "./scopeStylesToRoot";
import {
PORTAL_SELECTOR,
ROOT_SELECTOR,
scopeStylesToRoot,
} from "./scopeStylesToRoot";
const inRoot = `:where(${ROOT_SELECTOR}, ${ROOT_SELECTOR} *)`;
const inRoot = `:where(${ROOT_SELECTOR}, ${ROOT_SELECTOR} *, ${PORTAL_SELECTOR}, ${PORTAL_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, {
@@ -26,7 +31,10 @@ describe("scopeStylesToRoot", () => {
`${isRoot} { line-height: 1.15 }`,
);
expect(await scope("body { margin: 0 }")).toBe(`${isRoot} { margin: 0 }`);
expect(await scope(":root { --a: 1 }")).toBe(`${isRoot} { --a: 1 }`);
// 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("body.no-scroll-body { position: fixed }")).toBe(
`${isRoot}.no-scroll-body { position: fixed }`,
);
@@ -66,9 +74,11 @@ describe("scopeStylesToRoot", () => {
);
});
it("leaves alone what already names the root", async () => {
it("leaves alone what already names the root or the portal", 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 () => {
@@ -99,8 +109,8 @@ describe("scopeStylesToRoot", () => {
expect(await scope("pre { font-size: 1px }", file)).toBe(
`pre${inRoot} { font-size: 1px }`,
);
expect(await scope(".modal pre { font-size: 1px }", file)).toBe(
`.modal 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(".box_abc12 { border: 0 }", file)).toBe(
".box_abc12 { border: 0 }",
@@ -108,6 +118,14 @@ 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 () => {
+37 -14
View File
@@ -24,16 +24,27 @@ 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 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.
// 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.
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
@@ -45,15 +56,22 @@ const IS_ROOT = `:where(${ROOT_SELECTOR})`;
* the host's document too. This rewrites every selector so that it matches only
* the root or its descendants:
*
* - `html`, `body` and `:root` become the root element, which is what stands in
* for the document inside a host.
* - `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.
* - Everything else keeps its selector and gains `:where([data-element-call-root],
* [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.
* [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.
*
* CSS modules are scoped by their class names already, so only their selectors
* that would match by element alone — `pre` rather than `.pre` — are touched.
* 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.
*
* The root's custom properties are still inherited by everything inside it,
* the way they were from `:root`. Compound's own stylesheet — the design
@@ -117,7 +135,8 @@ const scopeAll = processor(false);
const scopeBare = processor(true);
function scopeSelector(selector: Selector, isModule: boolean): void {
if (String(selector).includes(ROOT_SELECTOR)) return;
const text = String(selector);
if (text.includes(ROOT_SELECTOR) || text.includes(PORTAL_SELECTOR)) return;
const compounds = splitCompounds(selector);
if (compounds.length === 0) return;
@@ -125,12 +144,16 @@ 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(IS_ROOT));
document.replaceWith(
pseudo(document.type === "pseudo" ? IS_ROOT_OR_PORTAL : 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);
+16
View File
@@ -41,3 +41,19 @@ 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);
+7 -3
View File
@@ -123,12 +123,16 @@ 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. */
[data-element-call-root][data-platform="android"] {
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"] {
--cpd-font-family-sans: "Roboto", "Noto", "Inter", sans-serif;
}
[data-element-call-root][data-platform="ios"] {
:is([data-element-call-root], [data-element-call-portal])[data-platform="ios"] {
--cpd-font-family-sans:
-apple-system, BlinkMacSystemFont, "Inter", sans-serif;
}
+19
View File
@@ -19,6 +19,7 @@ import {
} from "vitest";
import { useTheme } from "./useTheme";
import { PortalElementProvider } from "./RootElementContext";
import { platform } from "./Platform";
import { useUrlParams } from "./UrlParams";
import {
@@ -103,6 +104,24 @@ 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 });
+19 -8
View File
@@ -8,12 +8,13 @@ Please see LICENSE in the repository root for full details.
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { useUrlParams } from "./UrlParams";
import { useRootElement } from "./RootElementContext";
import { usePortalElement, 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);
@@ -37,13 +38,14 @@ 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",
@@ -55,5 +57,14 @@ export const useTheme = (): void => {
previousTheme.current = themeString;
}
rootElement.classList.remove("no-theme");
}, [previousTheme, requestedTheme, rootElement]);
}, [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]);
};