Files
element-call-Github/src/useRootSize.ts
T
Timo K.andClaude Fable 5.1 779ee7a008 Finish measuring the root rather than the viewport
The move from media queries to `@container element-call` queries left a
few places still asking the viewport: the room header's compact size
and the lobby's footer placement went through `useMediaQuery`, the
lobby's video preview was `50vh` tall, the reaction picker was capped at
`100vw`, and the content insets and the gradient background were sized
from `100vw`/`100vh`. Embedded in a corner of a host's page, each of
those answered for the page rather than the corner.

`useRootSizeMatches` is `useMediaQuery` for the root element, built on
the same `observeElementSize$` the layout uses; the lengths become
container units. Container units resolve against the nearest query
container, and there are others in the tree (the spotlight layouts, the
media tiles), so base.css says when they may be used.

jsdom gives the body no size at all, which would have every such query
read as a tiny window; the test setup now gives it a desktop's, matching
what the media query mock already answered.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-08 15:38:59 +02:00

51 lines
1.6 KiB
TypeScript

/*
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 { useEffect, useState } from "react";
import { distinctUntilChanged, map } from "rxjs";
import { useRootElement } from "./RootElementContext";
import { useLatest } from "./useLatest";
import { type ElementSize, observeElementSize$ } from "./utils/elementSize";
/**
* Whether the space Element Call is drawn in satisfies a condition on its
* size: the counterpart of {@link useMediaQuery} for the container rather than
* the viewport, and of the `@container element-call` queries in the
* stylesheets. The two are the same thing standalone, where the root is the
* page; for a component in a corner of a host's page they are not, and it is
* the corner that matters.
*
* Re-renders only when the answer changes, not on every pixel of resize.
*/
export function useRootSizeMatches(
matches: (size: ElementSize) => boolean,
): boolean {
const rootElement = useRootElement();
// The latest predicate, so that an inline arrow does not resubscribe on
// every render
const latestMatches = useLatest(matches);
const [result, setResult] = useState(() =>
matches({
width: rootElement.clientWidth,
height: rootElement.clientHeight,
}),
);
useEffect(() => {
const subscription = observeElementSize$(rootElement)
.pipe(
map((size) => latestMatches.current(size)),
distinctUntilChanged(),
)
.subscribe(setResult);
return (): void => subscription.unsubscribe();
}, [rootElement, latestMatches]);
return result;
}