diff --git a/jest/mocks/toast.tsx b/jest/mocks/toast.tsx index f1e48f270..fcb1bb7c7 100644 --- a/jest/mocks/toast.tsx +++ b/jest/mocks/toast.tsx @@ -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-`. +// 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-`. 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 ; + + 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 ; }; export const ToastSymbol = ({ name }: { name: string }) => ( ); - -// No tab bar showing, unless a test gives one. -export const tabBarFrame = jest.fn(() => Promise.resolve(null)); diff --git a/modules/toast/index.ts b/modules/toast/index.ts index 9f29c1ad8..617fb9f5e 100644 --- a/modules/toast/index.ts +++ b/modules/toast/index.ts @@ -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; @@ -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 { @@ -36,26 +54,3 @@ export const ToastSymbol = requireNativeView( '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; -}>('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); diff --git a/modules/toast/ios/Tests/TabBarLocatorTests.swift b/modules/toast/ios/Tests/TabBarLocatorTests.swift index 20e65f935..9662e90f0 100644 --- a/modules/toast/ios/Tests/TabBarLocatorTests.swift +++ b/modules/toast/ios/Tests/TabBarLocatorTests.swift @@ -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) } } diff --git a/modules/toast/ios/ToastModule.swift b/modules/toast/ios/ToastModule.swift index f8cc9399e..50a379927 100644 --- a/modules/toast/ios/ToastModule.swift +++ b/modules/toast/ios/ToastModule.swift @@ -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 @@ -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() @@ -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) } @@ -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. diff --git a/ota-fingerprint.json b/ota-fingerprint.json index 713665905..49e7aa102 100644 --- a/ota-fingerprint.json +++ b/ota-fingerprint.json @@ -1,6 +1,6 @@ { "runtimeVersion": "19.2.0", - "ios": "33092ecc4833f7d42c75041268ad403021c22519", + "ios": "6a7a277d7b4ab1d32e131b078390e6ed7014d59d", "android": "26ad9b5116e48c2984715157cadfb3ab4cacb761", "sources": { "ios": { @@ -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", diff --git a/src/components/Toast.tsx b/src/components/Toast.tsx index 760483320..a2ef09b95 100644 --- a/src/components/Toast.tsx +++ b/src/components/Toast.tsx @@ -9,6 +9,7 @@ import { View, } from 'react-native'; import Animated, { + LinearTransition, useAnimatedStyle, useSharedValue, withSpring, @@ -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'; @@ -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(); - 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(() => @@ -283,7 +254,20 @@ const ToastView: React.FC> = ({ 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(); + // 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); @@ -320,11 +304,6 @@ const ToastView: React.FC> = ({ 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 ( > = ({ 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 @@ -359,8 +339,11 @@ const ToastView: React.FC> = ({ > remove(id)} + onTabBarFrame={({ nativeEvent }) => + setTabBar(nativeEvent.frame ?? null) + } style={hud.toast} > {symbol ? ( diff --git a/src/components/__tests__/Toast.test.tsx b/src/components/__tests__/Toast.test.tsx index 857a5b69b..36f28524f 100644 --- a/src/components/__tests__/Toast.test.tsx +++ b/src/components/__tests__/Toast.test.tsx @@ -10,7 +10,11 @@ import DeviceInfo from 'constants/DeviceInfo'; import { textStyles } from 'components/Text'; import { Toast, toast } from 'components/Toast'; import { toast as androidToast } from 'components/Toast.android'; -import { tabBarFrame } from 'modules/toast'; +import { + holdTabBarFrame, + resetTabBarFrame, + setTabBarFrame, +} from 'test-utils/mocks/toast'; import { WindowProvider } from 'hooks/useWindow'; import { registerWindow } from 'services/windows'; import { Windows } from 'test-utils/mocks/windows'; @@ -24,6 +28,7 @@ beforeEach(() => { afterEach(async () => { await act(() => toast('', 'none')); + resetTabBarFrame(); }); describe('Toast (iOS)', () => { @@ -82,7 +87,6 @@ describe('Toast (iOS)', () => { Windows.targetWindowId.mockReturnValue('a'); await act(() => toast('Here', 'success')); expect(screen.getByText('Here')).toBeTruthy(); - expect(tabBarFrame).toHaveBeenLastCalledWith('a'); Windows.targetWindowId.mockReturnValue(null); unregister(); }); @@ -167,12 +171,6 @@ describe('Toast (iOS)', () => { }); describe('placement', () => { - afterEach(() => { - (tabBarFrame as jest.Mock).mockImplementation(() => - Promise.resolve(null), - ); - }); - const window = { windowWidth: 402, windowHeight: 874 }; const margins = () => { const style = StyleSheet.flatten( @@ -191,10 +189,7 @@ describe('Toast (iOS)', () => { }; const frame = ( bar: { x: number; y: number; width: number; height: number } | null, - ) => - (tabBarFrame as jest.Mock).mockResolvedValue( - bar && { ...bar, ...window }, - ); + ) => setTabBarFrame(bar && { ...bar, ...window }); it('sits a gap above a tab bar along the bottom', async () => { await show({ x: 0, y: 791, width: 402, height: 83 }); @@ -225,32 +220,38 @@ describe('Toast (iOS)', () => { expect(margins()).toEqual({ bottom: 21, left: 21, right: 21 }); }); - it('waits for the tab bar before it shows, and takes none if asking fails', async () => { - let fail: (error: Error) => void = () => {}; - (tabBarFrame as jest.Mock).mockReturnValue( - new Promise((_, reject) => { - fail = reject; - }), - ); + it('waits for the HUD to say where the tab bar is before it shows', async () => { + holdTabBarFrame(); await render(); await act(() => toast('Saved', 'success')); - expect(screen.queryByText('Saved')).toBeNull(); - await act(() => fail(new Error('No window'))); + expect(screen.getByTestId('toast-hud').props.visible).toBe(false); + + await act(() => frame({ x: 0, y: 791, width: 402, height: 83 })); + expect(screen.getByTestId('toast-hud').props.visible).toBe(true); + expect(margins().bottom).toBe(83 + 16); + }); + + it('follows the tab bar as it comes and goes while it shows', async () => { + // At launch the logging-in toast shows before the tabs can be found. + await show(null); + expect(margins().bottom).toBe(16); + + await act(() => frame({ x: 0, y: 791, width: 402, height: 83 })); + expect(margins().bottom).toBe(83 + 16); + + // A sheet over the tabs. + await act(() => frame(null)); expect(margins().bottom).toBe(16); }); - it('ignores an answer that comes after the toast is gone', async () => { - let answer: (value: null) => void = () => {}; - (tabBarFrame as jest.Mock).mockReturnValue( - new Promise(resolve => { - answer = resolve; - }), - ); + it('glides to a new place only once it has been placed', async () => { + holdTabBarFrame(); await render(); await act(() => toast('Saved', 'success')); - await act(() => toast('', 'none')); - await act(() => answer(null)); - expect(screen.queryByText('Saved')).toBeNull(); + const layout = () => screen.getByRole('alert').props.layout; + expect(layout()).toBeUndefined(); + await act(() => frame(null)); + expect(layout()).toBeDefined(); }); });