mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-14 12:25:05 +00:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f5499fd336 | ||
|
|
a9bc26bed2 | ||
|
|
3503edc65b | ||
|
|
9dedc14bbb |
+22
-6
@@ -7,12 +7,12 @@ canonical files and are trying to add or change one.
|
||||
|
||||
## Canonical files
|
||||
|
||||
| File | Use case |
|
||||
| ---------------------------------------- | ----------------------------------------------------------------- |
|
||||
| `components/ui/combobox.tsx` | Anchored picker with search; mobile falls back to bottom sheet |
|
||||
| `components/ui/tooltip.tsx` | Non-interactive hover/long-press tooltip |
|
||||
| `components/ui/hover-card.tsx` | Desktop-web hover card the pointer can move onto; Portal |
|
||||
| `components/ui/autocomplete-popover.tsx` | Slash-command autocomplete anchored to the focused composer input |
|
||||
| File | Use case |
|
||||
| ------------------------------------- | ----------------------------------------------------------------- |
|
||||
| `components/ui/combobox.tsx` | Anchored picker with search; mobile falls back to bottom sheet |
|
||||
| `components/ui/tooltip.tsx` | Non-interactive hover/long-press tooltip |
|
||||
| `components/ui/hover-card.tsx` | Desktop-web hover card the pointer can move onto; Portal |
|
||||
| `components/ui/autocomplete-popover/` | Slash-command autocomplete anchored to the focused composer input |
|
||||
|
||||
Each handles a different mix of concerns: combobox owns input focus, tooltip is
|
||||
non-interactive, hover-card is web-only desktop, autocomplete keeps the composer
|
||||
@@ -280,6 +280,22 @@ popover or leaves it behind the keyboard. `measureAtRest` measures through
|
||||
Fabric's transform-free `measureLayout` instead. Re-measure when `isMoving`
|
||||
settles; the composer's resting position changes as the draft grows.
|
||||
|
||||
A measured rect is an asynchronous copy, so it lands after the anchor's new
|
||||
layout has painted. The composer resizes while the autocomplete is open: a
|
||||
wrapped line, cleared text, a window resize. On web a `ResizeObserver` reads
|
||||
the anchor's rect against the layer and commits the placement with `flushSync`,
|
||||
which runs after layout and before paint. On native a Reanimated frame callback
|
||||
reads only the anchor's height on the UI thread and holds its bottom edge at
|
||||
the rest measurement. A height carries no transform. On iOS the absolute
|
||||
position does not reliably include one: the keyboard lift runs on the native
|
||||
driver and reaches the shadow tree only when the view re-renders. The
|
||||
fixed-bottom model is wrong for the centered New workspace composer on tablets,
|
||||
which grows around its middle, and for width or x changes. The popover is off
|
||||
there by half the growth, or by the old width, until the next rest measurement.
|
||||
Keep the portal's `KeyboardTranslateView` host-sized with
|
||||
`pointerEvents="box-none"` and position the popover inside it, so the popover
|
||||
moves without leaving its parent's bounds (Gotcha 1).
|
||||
|
||||
The provider also reconciles iOS from the controller's native `onEnd` event.
|
||||
The controller's stock iOS shared values update at move start and during an
|
||||
interactive move, but not at the terminal event, so JS contention can otherwise
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import React, { act, type ReactNode } from "react";
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { PortalProvider } from "@gorhom/portal";
|
||||
import { View } from "react-native";
|
||||
import { KeyboardProvider } from "react-native-keyboard-controller";
|
||||
import { SafeAreaProvider } from "react-native-safe-area-context";
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import { RetainedPanel } from "@/components/retained-panel";
|
||||
import { KeyboardShiftProvider } from "@/keyboard/shift";
|
||||
import type { AutocompleteOption } from "./autocomplete";
|
||||
import { AutocompletePopover } from "./autocomplete-popover";
|
||||
@@ -14,19 +16,20 @@ import { FloatingPanelPortalHost } from "./floating-panel-portal";
|
||||
beforeEach(() => vi.stubGlobal("React", React));
|
||||
|
||||
/**
|
||||
* The popover's height bound is a Reanimated style. Reanimated computes a style's first value
|
||||
* when its hook first runs and sends later values from an effect, after the commit that mounts
|
||||
* the view. Native paints that commit: a bound computed while the popover was closed painted the
|
||||
* popover at its minimum height, hanging down over the composer, for a frame on every open.
|
||||
* Web runs the effect before paint, so the wrong value only shows as the first style the DOM
|
||||
* receives.
|
||||
* The popover must paint its first frame at its place. On native, Reanimated computes a style's
|
||||
* first value when its hook first runs and sends later values after the mounting commit, which
|
||||
* native paints: a bound computed while the popover was closed hung the popover over the composer
|
||||
* for a frame on every open. The frame now mounts only with a measured anchor. This suite runs the
|
||||
* web frame; the native frame was checked frame by frame on Android.
|
||||
*/
|
||||
|
||||
const SAFE_AREA = {
|
||||
frame: { x: 0, y: 0, width: 390, height: 844 },
|
||||
insets: { top: 0, left: 0, right: 0, bottom: 0 },
|
||||
};
|
||||
const COMPOSER_TOP = 600;
|
||||
// The composer rests on the dock's bottom edge and grows upward, as in the app.
|
||||
const COMPOSER_BOTTOM = 124;
|
||||
const OFFSET_FROM_ANCHOR = 12;
|
||||
const OPTIONS: AutocompleteOption[] = ["help", "hello", "history"].map((name) => ({
|
||||
id: name,
|
||||
label: `/${name}`,
|
||||
@@ -44,8 +47,25 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
const SCREEN_STYLE = { width: 390, height: 844 };
|
||||
const COMPOSER_STYLE = { position: "absolute" as const, top: COMPOSER_TOP, left: 16, width: 358 };
|
||||
const INPUT_STYLE = { height: 120 };
|
||||
const styleCache = new Map<string, object>();
|
||||
function cachedStyle<T extends object>(key: string, create: () => T): T {
|
||||
const cached = styleCache.get(key);
|
||||
if (cached) return cached as T;
|
||||
const style = create();
|
||||
styleCache.set(key, style);
|
||||
return style;
|
||||
}
|
||||
function composerStyle(width: number): object {
|
||||
return cachedStyle(`composer:${width}`, () => ({
|
||||
position: "absolute" as const,
|
||||
bottom: COMPOSER_BOTTOM,
|
||||
left: 16,
|
||||
width,
|
||||
}));
|
||||
}
|
||||
function inputStyle(height: number): object {
|
||||
return cachedStyle(`input:${height}`, () => ({ height }));
|
||||
}
|
||||
function ignoreSelection(): void {}
|
||||
|
||||
function Providers({ children }: { children: ReactNode }): ReactNode {
|
||||
@@ -60,22 +80,36 @@ function Providers({ children }: { children: ReactNode }): ReactNode {
|
||||
);
|
||||
}
|
||||
|
||||
function Screen({ visible }: { visible: boolean }): ReactNode {
|
||||
interface ScreenProps {
|
||||
visible: boolean;
|
||||
panelActive?: boolean;
|
||||
inputHeight?: number;
|
||||
composerWidth?: number;
|
||||
}
|
||||
|
||||
function Screen({
|
||||
visible,
|
||||
panelActive = true,
|
||||
inputHeight = 120,
|
||||
composerWidth = 358,
|
||||
}: ScreenProps): ReactNode {
|
||||
return (
|
||||
<Providers>
|
||||
<View style={SCREEN_STYLE}>
|
||||
<View style={COMPOSER_STYLE}>
|
||||
<AutocompletePopover
|
||||
visible={visible}
|
||||
options={OPTIONS}
|
||||
selectedIndex={OPTIONS.length - 1}
|
||||
onSelect={ignoreSelection}
|
||||
>
|
||||
<View style={INPUT_STYLE} />
|
||||
</AutocompletePopover>
|
||||
<RetainedPanel active={panelActive}>
|
||||
<View style={SCREEN_STYLE}>
|
||||
<View style={composerStyle(composerWidth)}>
|
||||
<AutocompletePopover
|
||||
visible={visible}
|
||||
options={OPTIONS}
|
||||
selectedIndex={OPTIONS.length - 1}
|
||||
onSelect={ignoreSelection}
|
||||
>
|
||||
<View testID="composer-input" style={inputStyle(inputHeight)} />
|
||||
</AutocompletePopover>
|
||||
</View>
|
||||
<FloatingPanelPortalHost />
|
||||
</View>
|
||||
<FloatingPanelPortalHost />
|
||||
</View>
|
||||
</RetainedPanel>
|
||||
</Providers>
|
||||
);
|
||||
}
|
||||
@@ -89,6 +123,43 @@ function render(node: ReactNode): void {
|
||||
act(() => root?.render(node));
|
||||
}
|
||||
|
||||
/** Commits a change to the screen synchronously and lets the browser paint it. */
|
||||
async function changeAndPaint(node: ReactNode): Promise<void> {
|
||||
flushSync(() => root?.render(node));
|
||||
await new Promise<void>((resolve) => {
|
||||
requestAnimationFrame(() => {
|
||||
const channel = new MessageChannel();
|
||||
channel.port1.addEventListener("message", () => resolve(), { once: true });
|
||||
channel.port1.start();
|
||||
channel.port2.postMessage(null);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function rectOf(testID: string): DOMRect | null {
|
||||
return document.querySelector(`[data-testid="${testID}"]`)?.getBoundingClientRect() ?? null;
|
||||
}
|
||||
|
||||
/** Where the popover sits against the composer, or null when it is not painted. */
|
||||
function placementAgainstComposer(): { gap: number; x: number; width: number } | null {
|
||||
const popover = rectOf("composer-autocomplete-popover");
|
||||
const composer = rectOf("composer-input");
|
||||
if (!popover || !composer) return null;
|
||||
return {
|
||||
gap: Math.round(composer.top - popover.bottom),
|
||||
x: Math.round(popover.x - composer.x),
|
||||
width: Math.round(popover.width - composer.width),
|
||||
};
|
||||
}
|
||||
|
||||
async function openSettled(props: Omit<ScreenProps, "visible"> = {}): Promise<void> {
|
||||
render(<Screen visible={false} {...props} />);
|
||||
render(<Screen visible {...props} />);
|
||||
await waitForPopover();
|
||||
await new Promise((resolve) => setTimeout(resolve, 200));
|
||||
expect(placementAgainstComposer()).toEqual({ gap: OFFSET_FROM_ANCHOR, x: 0, width: 0 });
|
||||
}
|
||||
|
||||
/** Every max-height the popover's frame has held, starting with the one it mounted with. */
|
||||
function recordPopoverMaxHeights(): { values: string[]; stop: () => void } {
|
||||
const values: string[] = [];
|
||||
@@ -150,3 +221,42 @@ it("opens with its height bound instead of the bound it had while closed", async
|
||||
expect(Number.parseFloat(settled)).toBeGreaterThan(0);
|
||||
expect(recording.values[0]).toBe(settled);
|
||||
});
|
||||
|
||||
/**
|
||||
* The popover lives in a portal and copies the composer's rect. A copy taken after the composer's
|
||||
* layout paints the composer at its new size against the popover's old place: the popover overlapped
|
||||
* a composer that grew a line, floated above one that shrank, and kept the old width after a resize.
|
||||
*/
|
||||
it("moves with the composer in the frame the composer grows", async () => {
|
||||
await openSettled();
|
||||
await changeAndPaint(<Screen visible inputHeight={160} />);
|
||||
expect(placementAgainstComposer()).toEqual({ gap: OFFSET_FROM_ANCHOR, x: 0, width: 0 });
|
||||
});
|
||||
|
||||
it("follows the composer down when its text clears before the popover closes", async () => {
|
||||
// The input relayouts on the cleared text before the autocomplete hides the popover.
|
||||
await openSettled({ inputHeight: 160 });
|
||||
await changeAndPaint(<Screen visible inputHeight={120} />);
|
||||
expect(placementAgainstComposer()).toEqual({ gap: OFFSET_FROM_ANCHOR, x: 0, width: 0 });
|
||||
});
|
||||
|
||||
it("matches the composer's width in the frame the composer resizes", async () => {
|
||||
await openSettled();
|
||||
await changeAndPaint(<Screen visible composerWidth={240} />);
|
||||
expect(placementAgainstComposer()).toEqual({ gap: OFFSET_FROM_ANCHOR, x: 0, width: 0 });
|
||||
});
|
||||
|
||||
/**
|
||||
* A retained workspace stays mounted while another route shows. A popover left open there tracked a
|
||||
* composer it could not measure, and on native stopped following the composer after the user came
|
||||
* back.
|
||||
*/
|
||||
it("closes while its retained panel is hidden and reopens in place when it shows again", async () => {
|
||||
await openSettled();
|
||||
render(<Screen visible panelActive={false} />);
|
||||
expect(rectOf("composer-autocomplete-popover")).toBeNull();
|
||||
render(<Screen visible />);
|
||||
await waitForPopover();
|
||||
await new Promise((resolve) => setTimeout(resolve, 200));
|
||||
expect(placementAgainstComposer()).toEqual({ gap: OFFSET_FROM_ANCHOR, x: 0, width: 0 });
|
||||
});
|
||||
|
||||
+39
-81
@@ -1,19 +1,13 @@
|
||||
import { useCallback, useEffect, useRef, useState, type ReactElement, type ReactNode } from "react";
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactElement,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { View, useWindowDimensions, type StyleProp, type ViewStyle } from "react-native";
|
||||
StyleSheet,
|
||||
View,
|
||||
useWindowDimensions,
|
||||
type StyleProp,
|
||||
type ViewStyle,
|
||||
} from "react-native";
|
||||
import { Portal } from "@gorhom/portal";
|
||||
import Animated, {
|
||||
useAnimatedReaction,
|
||||
useAnimatedStyle,
|
||||
type DerivedValue,
|
||||
} from "react-native-reanimated";
|
||||
import { useAnimatedReaction, useAnimatedRef } from "react-native-reanimated";
|
||||
import { scheduleOnRN } from "react-native-worklets";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import {
|
||||
@@ -25,18 +19,10 @@ import {
|
||||
measureFloatingPanelPortalHost,
|
||||
useFloatingPanelPortalHostName,
|
||||
} from "@/components/ui/floating-panel-portal";
|
||||
import { useRetainedPanelActive } from "@/components/retained-panel";
|
||||
import { KeyboardTranslateView, useKeyboardAnchor, useKeyboardShift } from "@/keyboard/shift";
|
||||
import { SPACING } from "@/styles/theme";
|
||||
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
|
||||
|
||||
const OFFSET_FROM_ANCHOR = SPACING[3];
|
||||
|
||||
interface RelativeAnchorRect {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
hostHeight: number;
|
||||
}
|
||||
import { PopoverFrame } from "./internal/frame";
|
||||
import type { AnchorAtRest } from "./internal/placement";
|
||||
|
||||
interface AutocompletePopoverProps {
|
||||
visible: boolean;
|
||||
@@ -59,8 +45,16 @@ export function AutocompletePopover({
|
||||
}: AutocompletePopoverProps): ReactElement | null {
|
||||
"use no memo";
|
||||
// React Compiler memoizes effect captures by reading SharedValue.value during render.
|
||||
const anchorRef = useRef<View>(null);
|
||||
const [relativeAnchorRect, setRelativeAnchorRect] = useState<RelativeAnchorRect | null>(null);
|
||||
const anchorRef = useAnimatedRef<View>();
|
||||
// The animated ref returns its native handle, which React 19 would call as a ref cleanup.
|
||||
// The anchor stays a plain View: its style is the caller's Unistyles style.
|
||||
const setAnchorElement = useCallback(
|
||||
(element: View | null) => {
|
||||
anchorRef(element);
|
||||
},
|
||||
[anchorRef],
|
||||
);
|
||||
const [anchorAtRest, setAnchorAtRest] = useState<AnchorAtRest | null>(null);
|
||||
const windowDimensions = useWindowDimensions();
|
||||
const safeAreaInsets = useSafeAreaInsets();
|
||||
const portalHostName = useFloatingPanelPortalHostName();
|
||||
@@ -68,7 +62,9 @@ export function AutocompletePopover({
|
||||
const anchor = useKeyboardAnchor();
|
||||
const { measureAtRest } = anchor;
|
||||
const measurementGeneration = useRef(0);
|
||||
const canMeasure = visible && (options.length === 0 || selectedIndex >= 0);
|
||||
// A retained panel stays mounted while hidden; its anchor cannot be measured until it shows.
|
||||
const isPanelActive = useRetainedPanelActive();
|
||||
const canMeasure = isPanelActive && visible && (options.length === 0 || selectedIndex >= 0);
|
||||
|
||||
const remeasure = useCallback(() => {
|
||||
if (!canMeasure) return;
|
||||
@@ -82,10 +78,11 @@ export function AutocompletePopover({
|
||||
if (generation !== measurementGeneration.current || !anchorRect || !hostRect) {
|
||||
return undefined;
|
||||
}
|
||||
setRelativeAnchorRect({
|
||||
setAnchorAtRest({
|
||||
x: anchorRect.x - hostRect.x,
|
||||
y: anchorRect.y - hostRect.y,
|
||||
width: anchorRect.width,
|
||||
height: anchorRect.height,
|
||||
hostHeight: hostRect.height,
|
||||
});
|
||||
return undefined;
|
||||
@@ -95,7 +92,7 @@ export function AutocompletePopover({
|
||||
useEffect(() => {
|
||||
measurementGeneration.current += 1;
|
||||
if (!canMeasure) {
|
||||
setRelativeAnchorRect(null);
|
||||
setAnchorAtRest(null);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -118,27 +115,22 @@ export function AutocompletePopover({
|
||||
[isMoving, remeasure],
|
||||
);
|
||||
|
||||
// Lay out at the anchor's resting position; the KeyboardTranslateView below lifts
|
||||
// it with the anchor. Height changes only at keyboard boundaries.
|
||||
const baseStyle = useMemo(() => {
|
||||
if (!relativeAnchorRect) return null;
|
||||
return inlineUnistylesStyle({
|
||||
position: "absolute" as const,
|
||||
left: relativeAnchorRect.x,
|
||||
width: relativeAnchorRect.width,
|
||||
bottom: relativeAnchorRect.hostHeight - relativeAnchorRect.y + OFFSET_FROM_ANCHOR,
|
||||
});
|
||||
}, [relativeAnchorRect]);
|
||||
|
||||
// The translate view is the popover's own frame, so it lifts only the popover.
|
||||
// The layer covers the host and rides the anchor's keyboard translation; the frame inside it
|
||||
// places the popover. A layer that spans the host keeps the popover inside its parent's bounds,
|
||||
// which Android hit-testing requires.
|
||||
return (
|
||||
<View ref={anchorRef} onLayout={remeasure} style={anchorStyle} collapsable={false}>
|
||||
<View ref={setAnchorElement} onLayout={remeasure} style={anchorStyle} collapsable={false}>
|
||||
{children}
|
||||
{canMeasure && relativeAnchorRect && baseStyle ? (
|
||||
{canMeasure && anchorAtRest ? (
|
||||
<Portal hostName={portalHostName}>
|
||||
<KeyboardTranslateView {...anchor.translation} style={baseStyle}>
|
||||
<KeyboardTranslateView
|
||||
{...anchor.translation}
|
||||
style={StyleSheet.absoluteFill}
|
||||
pointerEvents="box-none"
|
||||
>
|
||||
<PopoverFrame
|
||||
anchorY={relativeAnchorRect.y}
|
||||
anchorRef={anchorRef}
|
||||
anchorAtRest={anchorAtRest}
|
||||
reservedLift={anchor.reservedLift}
|
||||
topInset={safeAreaInsets.top}
|
||||
>
|
||||
@@ -155,37 +147,3 @@ export function AutocompletePopover({
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
interface PopoverFrameProps {
|
||||
anchorY: number;
|
||||
reservedLift: DerivedValue<number>;
|
||||
topInset: number;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bounds the popover's height to the space above the anchor. It mounts only with a measured
|
||||
* anchor: Reanimated computes the first style when the hook first runs and sends later values
|
||||
* after the mounting commit, which native paints. A bound computed before the measurement painted
|
||||
* the popover at its minimum height, hanging over the composer, for a frame on every open.
|
||||
*/
|
||||
function PopoverFrame({
|
||||
anchorY,
|
||||
reservedLift,
|
||||
topInset,
|
||||
children,
|
||||
}: PopoverFrameProps): ReactElement {
|
||||
"use no memo";
|
||||
// React Compiler memoizes effect captures by reading SharedValue.value during render.
|
||||
const heightStyle = useAnimatedStyle(
|
||||
() => ({
|
||||
maxHeight: Math.max(0, anchorY - reservedLift.value - topInset - OFFSET_FROM_ANCHOR * 2),
|
||||
}),
|
||||
[anchorY, reservedLift, topInset],
|
||||
);
|
||||
return (
|
||||
<Animated.View testID="composer-autocomplete-popover" style={heightStyle}>
|
||||
{children}
|
||||
</Animated.View>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { useCallback, type ReactElement } from "react";
|
||||
import Animated, {
|
||||
measure,
|
||||
useAnimatedStyle,
|
||||
useFrameCallback,
|
||||
useSharedValue,
|
||||
} from "react-native-reanimated";
|
||||
import { placeAboveAnchor, type PopoverFrameProps } from "./placement";
|
||||
|
||||
/**
|
||||
* The composer grows upward from a fixed bottom edge as its text wraps. Its height is read on the
|
||||
* UI thread every frame, so the popover moves in the frame the composer's new layout mounts; an
|
||||
* asynchronous measurement through JS painted the composer over or away from the popover first.
|
||||
*
|
||||
* The frame mounts only with a measured anchor. Reanimated computes the first style when the hook
|
||||
* first runs and sends later values after the mounting commit, which native paints: a placement
|
||||
* computed before the measurement painted the popover over the composer for a frame on every open.
|
||||
*/
|
||||
export function PopoverFrame({
|
||||
anchorRef,
|
||||
anchorAtRest,
|
||||
reservedLift,
|
||||
topInset,
|
||||
children,
|
||||
}: PopoverFrameProps): ReactElement {
|
||||
"use no memo";
|
||||
// React Compiler memoizes effect captures by reading SharedValue.value during render.
|
||||
const anchorHeight = useSharedValue(anchorAtRest.height);
|
||||
const anchorLost = useSharedValue(false);
|
||||
const readAnchorHeight = useCallback(() => {
|
||||
"worklet";
|
||||
if (anchorLost.value) return;
|
||||
const measured = measure(anchorRef);
|
||||
if (!measured) {
|
||||
// The anchor left the shadow tree, usually as the composer unmounts; the portal removes the
|
||||
// frame a commit later. Each failed measure() logs a warning, and a busy JS thread holds
|
||||
// that commit for many frames, so stop measuring and follow the rest measurement.
|
||||
anchorLost.value = true;
|
||||
return;
|
||||
}
|
||||
if (measured.height !== anchorHeight.value) {
|
||||
anchorHeight.value = measured.height;
|
||||
}
|
||||
}, [anchorHeight, anchorLost, anchorRef]);
|
||||
useFrameCallback(readAnchorHeight);
|
||||
|
||||
const style = useAnimatedStyle(() => {
|
||||
const anchorBottom = anchorAtRest.y + anchorAtRest.height;
|
||||
const liveHeight = anchorLost.value ? anchorAtRest.height : anchorHeight.value;
|
||||
return {
|
||||
position: "absolute",
|
||||
left: anchorAtRest.x,
|
||||
width: anchorAtRest.width,
|
||||
...placeAboveAnchor({
|
||||
anchorTop: anchorBottom - liveHeight,
|
||||
hostHeight: anchorAtRest.hostHeight,
|
||||
reservedLift: reservedLift.value,
|
||||
topInset,
|
||||
}),
|
||||
};
|
||||
}, [anchorAtRest, anchorHeight, anchorLost, reservedLift, topInset]);
|
||||
|
||||
return (
|
||||
<Animated.View testID="composer-autocomplete-popover" style={style}>
|
||||
{children}
|
||||
</Animated.View>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { useLayoutEffect, useRef, useState, type ReactElement } from "react";
|
||||
import { flushSync } from "react-dom";
|
||||
import { View } from "react-native";
|
||||
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
|
||||
import { placeAboveAnchor, type AnchorAtRest, type PopoverFrameProps } from "./placement";
|
||||
|
||||
type AnchorRect = Omit<AnchorAtRest, "height">;
|
||||
|
||||
function rectWithin(anchor: HTMLElement, host: HTMLElement): AnchorRect {
|
||||
const anchorRect = anchor.getBoundingClientRect();
|
||||
const hostRect = host.getBoundingClientRect();
|
||||
return {
|
||||
x: anchorRect.x - hostRect.x,
|
||||
y: anchorRect.y - hostRect.y,
|
||||
width: anchorRect.width,
|
||||
hostHeight: hostRect.height,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The composer resizes as its text wraps and as the window resizes. ResizeObserver callbacks run
|
||||
* after layout and before paint, so committing the new placement synchronously there paints the
|
||||
* popover against the composer's new rect in the same frame.
|
||||
*/
|
||||
export function PopoverFrame({
|
||||
anchorRef,
|
||||
anchorAtRest,
|
||||
reservedLift,
|
||||
topInset,
|
||||
children,
|
||||
}: PopoverFrameProps): ReactElement {
|
||||
"use no memo";
|
||||
// React Compiler memoizes effect captures by reading SharedValue.value during render.
|
||||
const frameRef = useRef<View>(null);
|
||||
const [anchor, setAnchor] = useState<AnchorRect>(anchorAtRest);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const anchorElement = anchorRef.current as unknown as HTMLElement | null;
|
||||
// The frame's parent is the portal layer, which covers the host.
|
||||
const host = (frameRef.current as unknown as HTMLElement | null)?.parentElement;
|
||||
if (!anchorElement || !host) return undefined;
|
||||
setAnchor(rectWithin(anchorElement, host));
|
||||
const observer = new ResizeObserver(() => {
|
||||
flushSync(() => setAnchor(rectWithin(anchorElement, host)));
|
||||
});
|
||||
observer.observe(anchorElement);
|
||||
observer.observe(host);
|
||||
return () => observer.disconnect();
|
||||
}, [anchorAtRest, anchorRef]);
|
||||
|
||||
const style = inlineUnistylesStyle({
|
||||
position: "absolute" as const,
|
||||
left: anchor.x,
|
||||
width: anchor.width,
|
||||
...placeAboveAnchor({
|
||||
anchorTop: anchor.y,
|
||||
hostHeight: anchor.hostHeight,
|
||||
reservedLift: reservedLift.value,
|
||||
topInset,
|
||||
}),
|
||||
});
|
||||
|
||||
return (
|
||||
<View ref={frameRef} testID="composer-autocomplete-popover" style={style}>
|
||||
{children}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import type { ReactNode } from "react";
|
||||
import type { View } from "react-native";
|
||||
import type { AnimatedRef, DerivedValue } from "react-native-reanimated";
|
||||
import { SPACING } from "@/styles/theme";
|
||||
|
||||
const OFFSET_FROM_ANCHOR = SPACING[3];
|
||||
|
||||
/** The anchor's resting rect, relative to the portal host the popover renders in. */
|
||||
export interface AnchorAtRest {
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
hostHeight: number;
|
||||
}
|
||||
|
||||
export interface PopoverFrameProps {
|
||||
anchorRef: AnimatedRef<View>;
|
||||
/** Taken asynchronously; the frame follows the anchor's live size between measurements. */
|
||||
anchorAtRest: AnchorAtRest;
|
||||
reservedLift: DerivedValue<number>;
|
||||
topInset: number;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
/** Places the popover above an anchor whose top edge is `anchorTop` within the host. */
|
||||
export function placeAboveAnchor(input: {
|
||||
anchorTop: number;
|
||||
hostHeight: number;
|
||||
reservedLift: number;
|
||||
topInset: number;
|
||||
}): { bottom: number; maxHeight: number } {
|
||||
"worklet";
|
||||
return {
|
||||
bottom: input.hostHeight - input.anchorTop + OFFSET_FROM_ANCHOR,
|
||||
maxHeight: Math.max(
|
||||
0,
|
||||
input.anchorTop - input.reservedLift - input.topInset - OFFSET_FROM_ANCHOR * 2,
|
||||
),
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user