跳到正文
开发版

页面导航与物理动效 ​

跟随控件几何边界 (FollowBounds) ​

将 FollowBounds 挂载到任意控件上,即可让它自动环绕定位到另一个目标控件周围。它直接读取布局阶段准备好的 LayoutGeometry 输出(包含滚动偏移与几何变换),并将目标矩形映射到跟随者父容器的局部坐标系中。跟随者自身不占用 Flex 布局空间,而其内部子节点依然遵循常规的布局与内边距规则。

FollowBounds
780#[model]
781#[derive(Default)]
782pub struct SpringTabs {
783 #[observe]
784 pub active: u8,
785}
786
787#[event]
788fn pick_tab(
789 index: u8,
790 tabs: model!(SpringTabs),
791 target: entity!(),
792 followers: query!(mut FollowBounds),
793) {
794 tabs.set_active(index);
795 for follower in followers {
796 follower.target = target;
797 }
798}
799
800#[model]
801impl SpringTabs {
802 pub fn set_active(&mut self, index: u8) {
803 self.active = index;
804 }
805}
806
807#[compose]
808fn spring_scene(tabs: model!(SpringTabs), reduced: bool) {
809 ui! {
810 Column (
811 grow: 1.0,
812 padding: Padding::all(20),
813 justify: JustifyContent::SpaceBetween,
814 text_color: ColorToken::OnSurface
815 ) {
816 Text (
817 "Tap any pill — FollowBounds retargets mid-flight",
818 height: 22,
819 font_size: 13,
820 text_color: ColorToken::OnSurfaceVariant,
821 paragraph: ParagraphStyle::label().with_align(TextAlign::Start)
822 )
823 Row (
824 height: 52,
825 padding: Padding::all(5),
826 column_gap: 6,
827 align: AlignItems::Center,
828 bg_color: ColorToken::SurfaceVariant,
829 border_radius: 12
830 ) {
831 Button (
832 "MCU",
833 id: "spring_first",
834 grow: 1.0,
835 height: 38,
836 border_radius: 8,
837 normal_color: ColorToken::Surface,
838 pressed_color: ColorToken::SurfaceVariant,
839 text_color: ColorToken::OnSurface
840 ) on Tap(pick_tab::callback(0, tabs))
841 Button (
842 "Desktop",
843 grow: 1.4,
844 height: 38,
845 border_radius: 8,
846 normal_color: ColorToken::Surface,
847 pressed_color: ColorToken::SurfaceVariant,
848 text_color: ColorToken::OnSurface
849 ) on Tap(pick_tab::callback(1, tabs))
850 Button (
851 "Web",
852 grow: 1.0,
853 height: 38,
854 border_radius: 8,
855 normal_color: ColorToken::Surface,
856 pressed_color: ColorToken::SurfaceVariant,
857 text_color: ColorToken::OnSurface
858 ) on Tap(pick_tab::callback(2, tabs))
859 View (
860 id: "spring_ring",
861 border_width: 2,
862 border_color: ColorToken::Primary,
863 border_radius: 9
864 ) [
865 FollowBounds::new(id("spring_first"))
866 .with_transition(indicator_transition(reduced)),
867 ]
868 }
869 Text (
870 text: ${
871 match tabs.active() {
872 0 => "Target 01 · SPI framebuffer with dirty-rect clips",
873 1 => "Target 02 · Batched GPU draws with retained textures",
874 _ => "Target 03 · Browser canvas driven by requestAnimationFrame",
875 }
876 },
877 height: 20,
878 font_size: 12,
879 text_color: ColorToken::OnSurfaceVariant,
880 paragraph: ParagraphStyle::label().with_align(TextAlign::Start)
881 )
882 }
883 };
884}
正在加载预览…

在 MCU、Desktop 与 Web 三个不同宽度的按钮间快速连点,观察 FollowBounds 如何在半途带着当前速度平滑折返并自适应目标宽度。

rust
use mirui::prelude::*;
use mirui::ui::widgets::FollowBounds;

#[compose]
fn selection() {
    ui! {
        View (width: 240, height: 120) {
            View (id: "selected", width: 80, height: 40, bg_color: Color::rgb(30, 70, 120))
            View (border_width: 2, border_color: Color::rgb(80, 160, 240)) [
                FollowBounds::new(id("selected")).with_outset(3),
            ]
        }
    };
}

let mut app = App::headless(240, 120);
app.with_default_widgets();
let root = app.spawn_root().id();
app.compose(root, selection());
app.render().unwrap();
  • with_content(true):跟随目标扣除内边距(padding)后的内容框;
  • with_outset(value):向外扩张映射后的矩形(传入负数则向内收缩);
  • with_offset(x, y):在跟随者父容器的逻辑坐标系中附加平移偏移。若目标存在旋转,会映射为其轴对齐外接矩形(AABB)。

跟随者同时遵循自身祖先与目标祖先的裁剪区域。当目标处于隐藏、已删除、未挂载、循环引用(如指向自身或自身子树内部)或无法映射的状态时,跟随者会自动暂停绘制、输入与输出读取,直到目标关系重新合法;移除 FollowBounds 组件则会恢复控件原本书写的 Style。

默认情况下边界立即跳变。加上 .with_transition(mirui::anim::SNAPPY) 或传入 TweenConfig 即可为位置与尺寸变化开启平滑动画。首次挂载定位与从不可用状态恢复时总是立即到位;在运动途中切换目标(retargeting)会保留各轴当前的显示位置,弹簧过渡还会保留当前运动速度。只有启用了过渡动画的跟随者才会分配运动组件存储,并在后续推进与重定向时原地复用。

在测试中模拟近场联机 ​

Gallery 的 Nearby(nearby_demo)在一个本地掌机游戏启动器中综合展示了 FollowBounds、方向性 PageView 卡组滑动与保留式模态浮层,并配套提供了确定性的近场/联机状态模拟检查器(按 F2 或点击 Web 画布上方的 Simulate 展开):

模拟控制 / 联机流程快捷键 / 触发入口行为与状态契约
展开/收起模拟检查器F2 / Web Simulate在 640×480 启动器左侧展开 300 px 宽的可滚动检查器面板,不改变应用业务状态
联机流程与 9 组预设用例按 J 或长按 X / 检查器覆盖创建/加入房间、本地匹配、局域网与直连等 9 组预设(成功、连接/恢复失败、有/无房间、重连中、远端关闭、无匹配、不支持)
单步推进与本地确认Deliver reply / Local A / Local BDeliver reply 附带预期结果提示推进单步远端响应;Local A / Local B 驱动房主审批与开始确认
状态门控故障注入故障按钮 / Repeat case / Stop case按当前阶段注入失败、超时、房主拒绝、远端离开、断线或恢复结果;Repeat case 重跑当前用例,Stop case 恢复原启动器位置
目录与卡组导航快捷键Tab / K / Y / XTab 切换收藏夹与分类目录;K 打开设置与搜索软键盘;Y 排序/搜索/切换主题;X 短按启动、长按进入联机

交互式演示 (page_studio 与 nearby) ​

Gallery 的 Showcase 展区提供了两个完整的导航与动效示例:

  1. Page Studio (page_studio):通过收藏夹、地点详情与笔记编辑器演示保留状态的栈式导航(NavigationStack),通过场景面板演示受状态驱动的单页切换(PageView),并在工具栏中提供 None / Slide / Fade 视觉效果与 Tween / Spring(Smooth、Snappy、Bouncy、Interactive)运动算法的实时正交组合对比:
sh
cargo run -p gallery --example page_studio_demo
cargo run -p gallery --example page_studio_demo --no-default-features --features wgpu
  1. Nearby (nearby_demo):本地掌机游戏启动器,包含收藏夹、平台与游戏目录浏览、搜索键盘、多层模态弹窗、十种内置音效以及联机房间发现流程(按 F2 或点击 Web 画布上方的 Simulate 可展开左侧 300 逻辑像素宽的联机状态机注入检查器):
sh
cargo run -p gallery --example nearby_demo
cargo run -p gallery --example nearby_demo --no-default-features --features sdl-gpu
cargo run -p gallery --example nearby_demo --no-default-features --features wgpu

NavigationPath<R> 是一个存放已压入路由目标(pushed destinations)的可观察模型。根页面本身不包含在路径栈内。可通过 App::add_model 独立注册,或作为 model!(owned NavigationPath<R>) 嵌入父模型:

rust
use mirui::app::App;
use mirui::ui::widgets::navigation::NavigationPath;

#[derive(Clone)]
enum Route {
    Devices,
    Device(u32),
}

let mut app = App::headless(320, 240);
let path = app
    .add_model(NavigationPath::<Route>::with_capacity(8))
    .finish();

path.push(Route::Devices).unwrap();
path.push(Route::Device(7)).unwrap();
assert_eq!(path.len(), 2);
path.pop().unwrap();
assert_eq!(path.len(), 1);
path.clear().unwrap();
assert!(path.is_empty());

len()、is_empty() 与 revision() 均可被响应式观察。with_capacity(n) 预先准备最多容纳 n 层路由的存储槽位:push 直接将路由值移入预备槽位(不扩容、不克隆);pop 与 clear 保留已分配容量;对空栈调用 pop 不会发布多余的变更通知。

保留状态的导航栈 (NavigationStack) ​

NavigationStack 将 NavigationPath<R> 绑定到页面生成回调 on CreatePage。它的直接子节点就是根页面(Root Page),而每当路径压入新路由时則调用 CreatePage 构造子页面。每种路由枚举类型 R 只需调用一次 app.with_widget(navigation::view::<Route>()) 注册视图:

NavigationStack
1840#[derive(Clone, Copy)]
1841enum StackRoute {
1842 Devices,
1843 Detail(u32),
1844}
1845
1846#[compose]
1847fn stack_devices_page(path: model!(NavigationPath<StackRoute>)) -> Entity {
1848 ui! {
1849 Column (
1850 grow: 1.0,
1851 padding: Padding::all(14),
1852 row_gap: 8,
1853 bg_color: ColorToken::SurfaceVariant,
1854 border_radius: 10
1855 ) {
1856 Text ("Pushed · Devices", height: 22, font_size: 15, text_color: ColorToken::Primary)
1857 Row (height: 34, column_gap: 8) {
1858 Button (
1859 "Inspect #7 →",
1860 grow: 1.0,
1861 height: 32,
1862 font_size: 12,
1863 border_radius: 7,
1864 normal_color: ColorToken::Primary,
1865 pressed_color: ColorToken::Secondary,
1866 text_color: ColorToken::OnPrimary
1867 ) on Tap { let _ = path.push(StackRoute::Detail(7)); }
1868 Button (
1869 "← Back",
1870 width: 76,
1871 height: 32,
1872 font_size: 12,
1873 border_radius: 7,
1874 normal_color: ColorToken::Surface,
1875 pressed_color: ColorToken::Outline,
1876 text_color: ColorToken::OnSurface
1877 ) on Tap { let _ = path.pop(); }
1878 }
1879 }
1880 }
1881}
1882
1883#[compose]
1884fn stack_detail_page(path: model!(NavigationPath<StackRoute>), id: u32) -> Entity {
1885 ui! {
1886 Column (
1887 grow: 1.0,
1888 padding: Padding::all(14),
1889 row_gap: 8,
1890 bg_color: ColorToken::Secondary,
1891 border_radius: 10
1892 ) {
1893 Text (
1894 text: ${ format_args!("Device #{id} · ESP32-C3") },
1895 capacity: 28,
1896 height: 22,
1897 font_size: 15,
1898 text_color: ColorToken::OnSecondary
1899 )
1900 Row (height: 34, column_gap: 8) {
1901 Button (
1902 "← Pop one",
1903 grow: 1.0,
1904 height: 32,
1905 font_size: 12,
1906 border_radius: 7,
1907 normal_color: ColorToken::Surface,
1908 pressed_color: ColorToken::Outline,
1909 text_color: ColorToken::OnSurface
1910 ) on Tap { let _ = path.pop(); }
1911 Button (
1912 "Clear root",
1913 width: 88,
1914 height: 32,
1915 font_size: 12,
1916 border_radius: 7,
1917 normal_color: ColorToken::Primary,
1918 pressed_color: ColorToken::Outline,
1919 text_color: ColorToken::OnPrimary
1920 ) on Tap { let _ = path.clear(); }
1921 }
1922 }
1923 }
1924}
1925
1926#[event]
1927fn build_stack_page(
1928 event: event!(StackCreatePage<StackRoute>),
1929 path: model!(NavigationPath<StackRoute>),
1930) -> Entity {
1931 match *event.route() {
1932 StackRoute::Devices => ui! { stack_devices_page(path) },
1933 StackRoute::Detail(id) => ui! { stack_detail_page(path, id) },
1934 }
1935}
1936
1937#[compose]
1938fn nav_stack_scene(path: model!(NavigationPath<StackRoute>), reduced: bool) {
1939 ui! {
1940 Column (
1941 grow: 1.0,
1942 padding: Padding::all(18),
1943 row_gap: 10,
1944 text_color: ColorToken::OnSurface
1945 ) {
1946 Text (
1947 text: ${ format_args!("Stack depth: {}", path.len()) },
1948 capacity: 24,
1949 height: 20,
1950 font_size: 12,
1951 text_color: ColorToken::OnSurfaceVariant,
1952 paragraph: ParagraphStyle::label().with_align(TextAlign::Start)
1953 )
1954 NavigationStack (
1955 path: path.clone(),
1956 grow: 1.0,
1957 transition: if reduced {
1958 PageTransition::None
1959 } else {
1960 PageTransition::slide(mirui::anim::SMOOTH)
1961 }
1962 ) {
1963 Column (
1964 grow: 1.0,
1965 padding: Padding::all(14),
1966 justify: JustifyContent::SpaceBetween,
1967 bg_color: ColorToken::SurfaceVariant,
1968 border_radius: 10
1969 ) {
1970 Text ("Root · Home page", height: 22, font_size: 15)
1971 Button (
1972 "Push Devices →",
1973 width: Dimension::percent(100),
1974 height: 34,
1975 font_size: 13,
1976 border_radius: 8,
1977 normal_color: ColorToken::Primary,
1978 pressed_color: ColorToken::Secondary,
1979 text_color: ColorToken::OnPrimary
1980 ) on Tap { let _ = path.push(StackRoute::Devices); }
1981 }
1982 } on CreatePage(build_stack_page::callback(path))
1983 }
1984 };
1985}
正在加载预览…

点击 Push Devices → 与 Inspect #7 → 连续压入两层路由,再点 ← Pop one 或 Clear root 滑回上一层。

rust
use mirui::prelude::*;
use mirui::ui::widgets::{Button, Text};
use mirui::ui::widgets::navigation::{self, CreatePage, NavigationPath, NavigationStack, PageTransition};
use mirui::anim::SMOOTH;

#[derive(Clone, Copy)]
enum Route { Devices, Device(u32), Settings }

#[compose]
fn shell(path: model!(NavigationPath<Route>)) -> Entity {
    ui! {
        NavigationStack(path: path.clone(), grow: 1.0,
            transition: PageTransition::slide(SMOOTH)) {
            Column(grow: 1.0) {
                Text("Home")
                Button(height: 40) [Text::label("Devices")]
                on Tap { path.push(Route::Devices).unwrap(); }
                Button(height: 40) [Text::label("Settings")]
                on Tap { path.push(Route::Settings).unwrap(); }
            }
        } on CreatePage(create_page::callback(path))
    }
}

#[event]
fn create_page(event: event!(CreatePage<Route>), path: model!(NavigationPath<Route>)) -> Entity {
    match *event.route() {
        Route::Devices => ui! { devices(path) },
        Route::Device(id) => ui! { detail(path, id) },
        Route::Settings => ui! { settings(path) },
    }
}

当从栈顶弹出返回到此前访问过的页面时,原有的控件树、输入框状态与滚动位置均原样恢复。处于栈底隐藏状态的页面不接收输入,并在重新显示时自动恢复响应式更新;而被弹出栈外的条目则会释放其页面子树。一个 NavigationPath 实例同一时刻只能驱动一个活动的 NavigationStack。

受应用状态直接驱动的单页视图 (PageView) ​

如果不需要维护前进/后退历史栈,而是希望直接根据某个模型字段切换当前展示的页面,请使用 PageView:

PageView
1987#[derive(Clone, Copy, PartialEq, Eq, Default)]
1988pub enum ViewPage {
1989 #[default]
1990 Overview,
1991 Metrics,
1992 Logs,
1993}
1994
1995#[model]
1996#[derive(Default)]
1997pub struct ViewSession {
1998 #[observe]
1999 pub page: ViewPage,
2000}
2001
2002#[model]
2003impl ViewSession {
2004 pub fn select(&mut self, page: ViewPage) {
2005 self.page = page;
2006 }
2007}
2008
2009#[event]
2010fn create_view_page(event: event!(ViewCreatePage<ViewPage>)) -> Entity {
2011 match event.route() {
2012 ViewPage::Overview => ui! {
2013 Column (
2014 grow: 1.0,
2015 padding: Padding::all(16),
2016 justify: JustifyContent::Center,
2017 bg_color: ColorToken::SurfaceVariant,
2018 border_radius: 10
2019 ) {
2020 Text ("Overview · 160 MHz RISC-V", height: 24, font_size: 15, text_color: ColorToken::Primary)
2021 }
2022 },
2023 ViewPage::Metrics => ui! {
2024 Column (
2025 grow: 1.0,
2026 padding: Padding::all(16),
2027 justify: JustifyContent::Center,
2028 bg_color: ColorToken::Secondary,
2029 border_radius: 10
2030 ) {
2031 Text ("Metrics · Dirty flush 0.4 ms", height: 24, font_size: 15, text_color: ColorToken::OnSecondary)
2032 }
2033 },
2034 ViewPage::Logs => ui! {
2035 Column (
2036 grow: 1.0,
2037 padding: Padding::all(16),
2038 justify: JustifyContent::Center,
2039 bg_color: ColorToken::SurfaceVariant,
2040 border_radius: 10
2041 ) {
2042 Text ("Logs · 0 allocations in frame", height: 24, font_size: 15, text_color: ColorToken::OnSurface)
2043 }
2044 },
2045 }
2046}
2047
2048#[compose]
2049fn nav_pageview_scene(session: model!(ViewSession), reduced: bool) {
2050 ui! {
2051 Column (
2052 grow: 1.0,
2053 padding: Padding::all(18),
2054 row_gap: 10,
2055 text_color: ColorToken::OnSurface
2056 ) {
2057 Row (height: 32, column_gap: 6) {
2058 Button (
2059 "Overview",
2060 grow: 1.0,
2061 height: 30,
2062 font_size: 12,
2063 border_radius: 7,
2064 normal_color: ColorToken::SurfaceVariant,
2065 pressed_color: ColorToken::Outline,
2066 text_color: ColorToken::OnSurface
2067 ) on Tap { session.select(ViewPage::Overview); }
2068 Button (
2069 "Metrics",
2070 grow: 1.0,
2071 height: 30,
2072 font_size: 12,
2073 border_radius: 7,
2074 normal_color: ColorToken::SurfaceVariant,
2075 pressed_color: ColorToken::Outline,
2076 text_color: ColorToken::OnSurface
2077 ) on Tap { session.select(ViewPage::Metrics); }
2078 Button (
2079 "Logs",
2080 grow: 1.0,
2081 height: 30,
2082 font_size: 12,
2083 border_radius: 7,
2084 normal_color: ColorToken::Primary,
2085 pressed_color: ColorToken::Secondary,
2086 text_color: ColorToken::OnPrimary
2087 ) on Tap { session.select(ViewPage::Logs); }
2088 }
2089 PageView (
2090 page: ${ session.page() },
2091 grow: 1.0,
2092 transition: if reduced {
2093 PageTransition::None
2094 } else {
2095 PageTransition::slide(mirui::anim::SNAPPY)
2096 }
2097 ) on CreatePage(create_view_page::callback())
2098 }
2099 };
2100}
正在加载预览…

点击 Overview、Metrics 或 Logs 修改 session.page(),驱动 PageView 切换当前子页面。

rust
use mirui::prelude::*;
use mirui::ui::widgets::Text;
use mirui::ui::widgets::page_view::{self, CreatePage, PageView};

#[derive(Clone, Copy, PartialEq, Eq)]
enum Page { Home, Settings }

#[model]
struct Session {
    #[observe]
    page: Page,
}

#[model]
impl Session {
    fn show_settings(&mut self) { self.page = Page::Settings; }
}

#[event]
fn create_page(event: event!(CreatePage<Page>)) -> Entity {
    match event.route() {
        Page::Home => ui! { Text("Home", grow: 1.0) },
        Page::Settings => ui! { Text("Settings", grow: 1.0) },
    }
}

#[compose]
fn panel(session: model!(Session)) -> Entity {
    ui! {
        PageView(page: ${ session.page() }, grow: 1.0)
        on CreatePage(create_page::callback())
    }
}

路由值只需实现 Clone + PartialEq。当绑定值未发生变化时不会克隆路由或重建子树;当值改变时,会先构造新页面子树,再退役旧页面子树。

页面转场动画 (PageTransition) ​

rust
use mirui::anim::{BOUNCY, Easing, Transition, TweenConfig, ease};
use mirui::types::Fixed;
use mirui::ui::widgets::navigation::{PageDirection, PageTransition};

const MOVE: TweenConfig = TweenConfig::new(300, &ease::OUT_CUBIC);
let slide = PageTransition::slide(MOVE);
let returning = PageTransition::slide(MOVE).with_direction(PageDirection::Backward);
let fade = PageTransition::fade(BOUNCY);

fn custom_progress(t: Fixed) -> Fixed { t * t }
static CUSTOM: Easing = Easing::new(custom_progress);
let config: Transition = TweenConfig::new(240, &CUSTOM).into();
let mut motion = config.motion(Fixed::ZERO, Fixed::ONE);
motion.tick(16);
config.retarget(&mut motion, Fixed::from_int(2));

NavigationStack 与 PageView 均支持 transition: PageTransition::slide(config)(水平推拉)或 PageTransition::fade(config)(交叉淡入淡出),并可传入任意 TweenConfig 或弹簧预设(SMOOTH、SNAPPY、BOUNCY、INTERACTIVE)。NavigationStack 在压栈(push)时自动向前滑入、弹栈(pop)时自动反向滑出;PageView 默认向前滑动,也可通过 .with_direction(PageDirection::Backward) 显式指定反向滑入。

  • 中途折返(Reversal):在两个页面正在转场途中立即切回上一页时,不会销毁重建任一页面,而是直接将正在进行的运动平滑反向(弹簧保留当前速度);转场进行期间新旧两个页面均暂停接收指针输入,待转场落定后立即恢复。
  • 离屏缓冲开销:slide 推拉转场无需额外像素缓冲;fade 淡入淡出则复用 app.with_offscreen_pool_budget(bytes) 配置的离屏缓冲池合成两棵子树(1 倍缩放下两张 W × H RGBA 缓冲占用 8 × W × H 字节;若预算不足则记录警告并直接完成无动画切换,绝不隐式超额分配)。