Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 61 additions & 8 deletions jest/mocks/toast.tsx
Original file line number Diff line number Diff line change
@@ -1,30 +1,83 @@
import { useEffect, useEffectEvent } from 'react';
import { useEffect, useEffectEvent, useRef } from 'react';
import { View, type ViewProps } from 'react-native';
import type { TabBarFrame } from 'modules/toast';

// How long the HUD takes to animate away, as the native view does.
const hideDuration = 200;

// The toast's UIKit views: plain views. The HUD reports it has gone a moment
// after it is hidden. They are findable as `toast-hud` and `icon-<name>`.
// No tab bar showing, unless a test gives one.
let tabBar: TabBarFrame | null = null;
// Whether the HUD says where the tab bar is as it mounts, as the native view
// does once it is in a window.
let answersOnMount = true;
const followers = new Set<(frame: TabBarFrame | null) => void>();

/**
* Where the tab bar is: sent to the HUDs showing now, as the native view sends
* it when the tab bar moves, appears or goes, and to those that mount later.
*/
export const setTabBarFrame = (frame: TabBarFrame | null) => {
tabBar = frame;
answersOnMount = true;
followers.forEach(follow => follow(frame));
};

/** Holds back the next HUD's first answer until `setTabBarFrame`. */
export const holdTabBarFrame = () => {
answersOnMount = false;
};

/** No tab bar, answered on mount: for a test's `afterEach`. */
export const resetTabBarFrame = () => {
tabBar = null;
answersOnMount = true;
};

// The toast's UIKit views: plain views. The HUD says where the tab bar is, and
// reports it has gone a moment after it is hidden, once it has shown. They
// are findable as `toast-hud` and `icon-<name>`.
export const ToastHUD = ({
visible,
onHidden,
onTabBarFrame,
...props
}: ViewProps & { visible: boolean; onHidden: () => void }) => {
}: ViewProps & {
visible: boolean;
onHidden: () => void;
onTabBarFrame: (event: { nativeEvent: { frame?: TabBarFrame } }) => void;
}) => {
const hidden = useEffectEvent(onHidden);
const shown = useRef(false);
useEffect(() => {
if (visible) {
shown.current = true;
return;
}
if (!shown.current) {
return;
}
const timer = setTimeout(hidden, hideDuration);
return () => clearTimeout(timer);
}, [visible]);
return <View testID="toast-hud" {...props} />;

const send = useEffectEvent((frame: TabBarFrame | null) =>
onTabBarFrame({ nativeEvent: frame ? { frame } : {} }),
);
useEffect(() => {
const follow = (frame: TabBarFrame | null) => send(frame);
if (answersOnMount) {
follow(tabBar);
}
followers.add(follow);
return () => {
followers.delete(follow);
};
}, []);

// `visible` stays on the view, for tests to read.
return <View testID="toast-hud" {...props} {...{ visible }} />;
};

export const ToastSymbol = ({ name }: { name: string }) => (
<View testID={`icon-${name}`} />
);

// No tab bar showing, unless a test gives one.
export const tabBarFrame = jest.fn(() => Promise.resolve(null));
45 changes: 20 additions & 25 deletions modules/toast/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
import { requireNativeModule, requireNativeView } from 'expo';
import type { ColorValue, ViewProps } from 'react-native';
import { requireNativeView } from 'expo';
import type { ColorValue, NativeSyntheticEvent, ViewProps } from 'react-native';

/** A tab bar's frame in its window, in points, with the window's size. */
export interface TabBarFrame {
x: number;
y: number;
width: number;
height: number;
windowWidth: number;
windowHeight: number;
}

export interface ToastHUDProps extends ViewProps {
cornerRadius: number;
Expand All @@ -11,6 +21,14 @@ export interface ToastHUDProps extends ViewProps {
visible: boolean;
/** Called once it has animated away after `visible` turned false. */
onHidden: () => void;
/**
* Where the tab bar the person sees is, wherever UIKit put it: called as
* soon as the HUD is in a window, then whenever the tab bar moves, appears
* or goes. `frame` is missing when none shows: on the login, under a sheet,
* at the top on iPad (where it floats and the bar itself is hidden) and on
* the Mac.
*/
onTabBarFrame: (event: NativeSyntheticEvent<{ frame?: TabBarFrame }>) => void;
}

export interface ToastSymbolProps extends ViewProps {
Expand All @@ -36,26 +54,3 @@ export const ToastSymbol = requireNativeView<ToastSymbolProps>(
'LearnXToast',
'ToastSymbolView',
);

/** A tab bar's frame in its window, in points, with the window's size. */
export interface TabBarFrame {
x: number;
y: number;
width: number;
height: number;
windowWidth: number;
windowHeight: number;
}

const ToastModule = requireNativeModule<{
tabBarFrame: (windowId?: string) => Promise<TabBarFrame | null>;
}>('LearnXToast');

/**
* Where the tab bar the person sees is, wherever UIKit put it, or null when
* none shows: on the login, under a sheet, at the top on iPad (where it
* floats and the bar itself is hidden) and on the Mac. In the window
* `windowId` (`services/windows`), or with none, in any. iOS only.
*/
export const tabBarFrame = (windowId?: string) =>
ToastModule.tabBarFrame(windowId);
19 changes: 17 additions & 2 deletions modules/toast/ios/Tests/TabBarLocatorTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,22 @@ import UIKit
#expect(TabBarLocator.frame(in: window) == nil)
}

@Test func looksOnlyInTheWindowAsked() {
#expect(TabBarLocator.frame(windowId: "no-such-window") == nil)
@Test func toastFollowsTheTabBarWhileInAWindow() throws {
let tabs = tabs()
let window = window(tabs)
let toast = ToastView(appContext: nil)
#expect(toast.sentTabBarFrame == nil)

window.addSubview(toast)
let shown = try #require(toast.sentTabBarFrame)
#expect(shown == TabBarLocator.frame(in: window))
#expect(shown != nil)

tabs.tabBar.isHidden = true
toast.followTabBar()
#expect(toast.sentTabBarFrame == .some(nil))

toast.removeFromSuperview()
#expect(toast.sentTabBarFrame == nil)
}
}
59 changes: 35 additions & 24 deletions modules/toast/ios/ToastModule.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,8 @@ public final class ToastModule: Module {
public func definition() -> ModuleDefinition {
Name("LearnXToast")

// Where the tab bar is, so the toast keeps clear of it wherever UIKit put it.
// In the toast's own window when there are several (iPad, Mac).
AsyncFunction("tabBarFrame") { (windowId: String?) -> [String: Double]? in
MainActor.assumeIsolated {
TabBarLocator.frame(windowId: windowId)
}
}.runOnQueue(.main)

View(ToastView.self) {
Events("onHidden")
Events("onHidden", "onTabBarFrame")

Prop("cornerRadius") { (view: ToastView, radius: Double) in
view.cornerRadius = radius
Expand All @@ -42,11 +34,21 @@ public final class ToastModule: Module {

/// The toast HUD: its backdrop (Liquid Glass on iOS 26 and later, the thick blur material system HUDs used before
/// that) with the React children on top. It animates itself in and out, the backdrop, the content and the motion
/// in one animation, so they arrive and leave together. A glass effect view under an ancestor with alpha below 1
/// in one animation, so they arrive and leave together. While in a window it follows where the tab bar is, so the
/// toast can keep clear of it. A glass effect view under an ancestor with alpha below 1
/// never renders, so the backdrop fades by animating its effect, and JS must not fade this view or its ancestors.
final class ToastView: ExpoView {
/// Sent once the toast has animated away.
let onHidden = EventDispatcher()
/// Sent as soon as the view is in a window, then whenever the tab bar moves, appears or goes: `frame` is
/// `TabBarLocator`'s answer, missing when no tab bar shows.
let onTabBarFrame = EventDispatcher()

/// Checks the tab bar every frame while the view is in a window. The tab bar can come or go under a toast that is
/// already up (the tabs appear at launch, a sheet over them closes), and UIKit posts nothing for either.
private var tabBarLink: CADisplayLink?
/// The last frame sent, or nil before the first.
private(set) var sentTabBarFrame: [String: Double]??

/// Moves with the animation; holds the backdrop and the content.
private let hud = UIView()
Expand Down Expand Up @@ -138,6 +140,28 @@ final class ToastView: ExpoView {
}
}

override func didMoveToWindow() {
super.didMoveToWindow()
tabBarLink?.invalidate()
tabBarLink = nil
sentTabBarFrame = nil
guard window != nil else { return }
// Before the first layout, so the toast is placed before it animates in.
followTabBar()
// The link holds its target strongly; invalidating it on leaving the window breaks the cycle.
let link = CADisplayLink(target: self, selector: #selector(followTabBar))
link.add(to: .main, forMode: .common)
tabBarLink = link
}

@objc func followTabBar() {
guard let window else { return }
let frame = TabBarLocator.frame(in: window)
guard sentTabBarFrame != .some(frame) else { return }
sentTabBarFrame = .some(frame)
onTabBarFrame(frame.map { ["frame": $0] } ?? [:])
}

override func mountChildComponentView(_ childComponentView: UIView, index: Int) {
contentView.insertSubview(childComponentView, at: index)
}
Expand Down Expand Up @@ -190,20 +214,7 @@ final class ToastSymbolView: ExpoView {
/// small display, at the top on iPad, where it floats and the bar itself is hidden), and nothing shows it on the
/// login, under a sheet or on the Mac.
enum TabBarLocator {
/// The visible tab bar's frame in its window, with the window's size, or nil when none shows. Only in the scene
/// whose session has the id `windowId`, when given.
@MainActor static func frame(windowId: String? = nil) -> [String: Double]? {
let scenes = UIApplication.shared.connectedScenes
.compactMap { $0 as? UIWindowScene }
.filter { windowId == nil || $0.session.persistentIdentifier == windowId }
for window in scenes.flatMap(\.windows) {
if let frame = frame(in: window) {
return frame
}
}
return nil
}

/// The visible tab bar's frame in `window`, with the window's size, or nil when none shows.
@MainActor static func frame(in window: UIWindow) -> [String: Double]? {
guard let root = window.rootViewController,
// A sheet or a full screen modal covers the tab bar.
Expand Down
4 changes: 2 additions & 2 deletions ota-fingerprint.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"runtimeVersion": "19.2.0",
"ios": "33092ecc4833f7d42c75041268ad403021c22519",
"ios": "6a7a277d7b4ab1d32e131b078390e6ed7014d59d",
"android": "26ad9b5116e48c2984715157cadfb3ab4cacb761",
"sources": {
"ios": {
Expand All @@ -16,7 +16,7 @@
"dir modules/shortcuts/ios": "77f8113c1737ea6fef56118e978807bcf4eac572",
"dir modules/sidebar/ios": "da0e6916e77e28500abfff4bb8e7620f0030fcdc",
"dir modules/spotlight/ios": "0c556f33bb595592925a631602f7e4289090cff0",
"dir modules/toast/ios": "aa4d01b8183803ed5c95a7a366b90a82fedabb94",
"dir modules/toast/ios": "e415f55d67909e102c5cb165d0235afaa61b1e21",
"dir modules/windows/ios": "c308265226d7823bc1f418f935212e856e3322a7",
"dir patches": "4b704c3173cb5c4cf55cd2d08d13d4c25144a392",
"contents expoAutolinkingConfig:ios": "05caaf7be38c362b6267259a7bde61f171c52acf",
Expand Down
59 changes: 21 additions & 38 deletions src/components/Toast.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
View,
} from 'react-native';
import Animated, {
LinearTransition,
useAnimatedStyle,
useSharedValue,
withSpring,
Expand All @@ -22,12 +23,7 @@ import { create } from 'zustand';
import DeviceInfo from 'constants/DeviceInfo';
import Spacing from 'constants/Spacing';
import { Text, type TextVariant } from 'components/Text';
import {
tabBarFrame,
ToastHUD,
ToastSymbol,
type TabBarFrame,
} from 'modules/toast';
import { ToastHUD, ToastSymbol, type TabBarFrame } from 'modules/toast';

import { playHaptic } from 'services/haptics';
import { targetWindow } from 'services/windows';
Expand Down Expand Up @@ -231,31 +227,6 @@ const toastInsets = (insets: Margins, bar: TabBarFrame | null): Margins => {
return { bottom: edge('bottom'), left: edge('left'), right: edge('right') };
};

/**
* Where the tab bar is while the toast shows, asked again when the window
* changes size. Undefined until UIKit answers, a moment after the toast mounts.
*/
const useTabBarFrame = () => {
// This window's size: React Native's window dimensions are the key
// window's.
const { width, height } = useSafeAreaFrame();
const { windowId } = useWindow();
const [frame, setFrame] = useState<TabBarFrame | null>();
useEffect(() => {
let current = true;
const answer = (value: TabBarFrame | null) => {
if (current) {
setFrame(value);
}
};
tabBarFrame(windowId).then(answer, () => answer(null));
return () => {
current = false;
};
}, [width, height, windowId]);
return frame;
};

/** The height of the keyboard while it is up, so the toast can sit above it. */
const useKeyboardHeight = () => {
const [height, setHeight] = useState(() =>
Expand Down Expand Up @@ -283,7 +254,20 @@ const ToastView: React.FC<Omit<ToastState, 'duration'>> = ({
const insets = useSafeAreaInsets();
const { width: windowWidth } = useSafeAreaFrame();
const keyboardHeight = useKeyboardHeight();
const tabBar = useTabBarFrame();
// Where the tab bar is, as the HUD follows it. Undefined until the HUD is in
// a window, and the toast waits for it before it animates in, so it doesn't
// jump. Later moves, as when the tabs appear under the logging-in toast at
// launch or a sheet over them closes, glide.
const [tabBar, setTabBar] = useState<TabBarFrame | null>();
// The layout transition goes on in a commit after the first answer's, so
// that the toast takes its first place without gliding there.
const [placed, setPlaced] = useState(false);
useEffect(() => {
if (tabBar !== undefined) {
// oxlint-disable-next-line react/set-state-in-effect -- a commit after the first answer's, see above
setPlaced(true);
}
}, [tabBar]);
const margins = toastInsets(insets, tabBar ?? null);
const drag = useSharedValue(0);

Expand Down Expand Up @@ -320,11 +304,6 @@ const ToastView: React.FC<Omit<ToastState, 'duration'>> = ({
const metrics = mac ? macMetrics : iosMetrics;
const hud = mac ? macStyles : iosStyles;

// Placed once UIKit says where the tab bar is, so it doesn't jump.
if (tabBar === undefined) {
return null;
}

return (
<View
pointerEvents="box-none"
Expand All @@ -344,6 +323,7 @@ const ToastView: React.FC<Omit<ToastState, 'duration'>> = ({
accessibilityRole="alert"
accessibilityLabel={text}
accessibilityHint=""
layout={placed ? LinearTransition : undefined}
style={[
// The overlay's window doesn't hold its content to the screen's
// width, so the wrapper's side padding alone lets a long toast run
Expand All @@ -359,8 +339,11 @@ const ToastView: React.FC<Omit<ToastState, 'duration'>> = ({
>
<ToastHUD
cornerRadius={metrics.cornerRadius}
visible={visible}
visible={visible && tabBar !== undefined}
onHidden={() => remove(id)}
onTabBarFrame={({ nativeEvent }) =>
setTabBar(nativeEvent.frame ?? null)
}
style={hud.toast}
>
{symbol ? (
Expand Down
Loading