npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

react-modal-navigation

v1.1.10

Published

React 19 modal navigation with automatic built-in CSS, Promise results and typed hooks

Readme

当前版本:1.1.9。单页面轻量模式、React.lazy、placement: "top" 和 top 偏移继续支持。顶部偏移现在会同时约束弹窗的可用高度,避免超出视口。

react-modal-navigation

React 19 多页面弹窗导航组件库。支持 Modal / Drawer / Sheet、页面堆栈、KeepAlive、Promise 返回结果、异步关闭守卫、Footer、Loading、暗黑主题与自动注入样式。

默认自动注入样式,无需手动导入 CSS 文件。

目录

  1. 安装和快速开始
  2. 对象形式打开弹窗
  3. 弹窗位置与尺寸
  4. 配置优先级与响应式
  5. 页面导航与传参
  6. Promise 结果与关闭守卫
  7. 异步提交与 Loading
  8. 主题与样式覆盖
  9. 事件、可访问性和注意事项
  10. TypeScript

安装和快速开始

npm install react-modal-navigation
import { ModalProvider, useModal } from 'react-modal-navigation';

function Home() {
  const { modal } = useModal();
  return <>
    <button onClick={() => modal.open('editUser')}>居中编辑</button>
    <button onClick={() => modal.open('deviceDrawer')}>右侧设备抽屉</button>
  </>;
}

function UserForm() {
  const { navigation } = useModal();
  return <button onClick={() => navigation.close({ id: 1, name: 'Ada' })}>完成</button>;
}

function DeviceHome() {
  const { navigation } = useModal();
  return <button onClick={() => navigation.navigate('DeviceDetail', { id: 123 })}>查看详情</button>;
}

function DeviceDetail() {
  const { navigation } = useModal();
  return <button onClick={() => navigation.goBack()}>返回</button>;
}

const registry = {
  editUser: {
    initialRoute: 'UserForm',
    modalOptions: { placement: 'center', width: 600, maxHeight: '85dvh' },
    screens: { UserForm: { title: '编辑用户', component: UserForm } },
  },
  deviceDrawer: {
    initialRoute: 'DeviceHome',
    modalOptions: { placement: 'right', width: 520 },
    screens: {
      DeviceHome: { title: '设备', component: DeviceHome },
      DeviceDetail: { title: '设备详情', component: DeviceDetail },
    },
  },
};

export default function App() {
  return <ModalProvider registry={registry}><Home /></ModalProvider>;
}

不需要 import 'react-modal-navigation/style.css',Provider 会自动注入组件样式;业务页面可以使用任意 CSS 方案。

推荐:对象形式打开弹窗

modal.open() 和 modal.openAsync() 现在都支持字符串位置参数及对象参数两种写法,原有代码不需要修改。推荐新项目采用对象形式,避免为了设置位置而传入无意义的 {}。

const { modal } = useModal();

// 推荐:只有名称和布局配置,不需要空的 params
await modal.open({
  name: 'editUser',
  options: { placement: 'bottom', width: '100%', height: '55dvh' },
});

// 带页面参数
await modal.open({
  name: 'editUser',
  params: { userId: 1001 },
  options: { placement: 'center', width: 640 },
});

// Promise 弹窗也支持同样的对象形式
const result = await modal.openAsync({
  name: 'editUser',
  params: { userId: 1001 },
  options: { placement: 'right', width: 520 },
});

// 旧 API 保持兼容
await modal.open('editUser');
await modal.open('editUser', { userId: 1001 });
await modal.open('editUser', {}, { placement: 'bottom', height: '55dvh' });

对象字段说明:

| 字段 | 类型 | 必填 | 说明 | | --- | --- | --- | --- | | name | string | 是 | registry 中注册的弹窗名称 | | params | unknown | 否 | 传给初始 Screen 的页面参数,默认 {} | | options | ModalOptions | 否 | 当前弹窗覆盖的布局、尺寸、主题和事件配置 |

兼容规则: 第一个参数是字符串时继续使用 open(name, params?, overrides?);第一个参数是对象时使用 open({ name, params?, options? })。对象形式不需要再传第二、第三个参数。配置优先级仍为 defaultOptions → modalOptions → options。openAsync 的结果结构不变。

弹窗位置与尺寸

placement 可选值

| placement | 说明 | 默认高度 | 推荐场景 | | --- | --- | --- | --- | | center | 居中弹窗 | 内容高度,受 maxHeight 限制 | 表单、确认框、详情 | | left | 左侧抽屉 | 视口高度减去上下缝隙 | 导航、筛选 | | right | 右侧抽屉(默认) | 视口高度减去上下缝隙 | 设备设置、编辑页 | | top | 顶部弹出层 | 内容高度 | 顶部操作面板 | | bottom | 底部弹出层 | 内容高度 | 移动端操作、筛选 |

右侧抽屉:上下左右与视口保持 5px

modal.open('deviceDrawer', { deviceId: 123 }, {
  placement: 'right',
  width: 520,
  viewportGap: 5,
});

左右抽屉的高度固定为 calc(100dvh - 10px)(viewportGap: 5 时),即距视口顶部、底部各 5px;同时距左右视口边缘至少 5px。无需传 height: '100dvh',即使传入 height,左右抽屉仍遵循视口高度规则。

// 左侧抽屉
modal.open('deviceDrawer', {}, { placement: 'left', width: '35vw' });

// 居中弹窗
modal.open('editUser', {}, {
  placement: 'center', width: 680, height: '70dvh', maxHeight: '85dvh',
});

// 底部 Sheet
modal.open('editUser', {}, {
  placement: 'bottom', width: '100%', height: '55dvh',
});

// 顶部 Sheet
modal.open('editUser', {}, {
  placement: 'top', width: 800, height: 320,
});

尺寸预设

size 仅控制宽度,可选 sm(400px)、md(560px)、lg(720px)、xl(960px)、full(100%)。显式 width 优先于 size。不传时默认宽度 460px。

modal.open('editUser', {}, { placement: 'center', size: 'lg' });
modal.open('editUser', {}, { placement: 'center', size: 'lg', width: 640 }); // width 优先

| 属性 | 类型 | 默认 | 作用 | | --- | --- | --- | --- | | placement | center \| left \| right \| top \| bottom | right | 弹窗位置 | | size | sm \| md \| lg \| xl \| full | 未设置 | 预设宽度 | | width | number \| string | 460 | 弹窗宽度,数字单位 px | | height | number \| string | 自动 | 居中/顶部/底部高度;左右抽屉强制视口高度 | | maxWidth | number \| string | 同 width | 最大宽度 | | maxHeight | number \| string | 视口减去缝隙 | 最大高度;左右抽屉强制视口高度 | | viewportGap | number | 5 | 视口四周留白,单位 px | | borderRadius | number \| string | 12 | 圆角 | | mobileFullscreen | boolean | false | 宽度 ≤640px 时铺满屏幕,覆盖缝隙规则 |

视口边界使用 100dvh(动态视口高度),适应移动端浏览器地址栏;内容区域单独滚动,Header / Footer 不跟随内容滚动。viewportGap 应使用有限的非负数字。

配置优先级与响应式

从低到高:ModalProvider.defaultOptions → registry[name].modalOptions → modal.open(name, params, overrides)。

<ModalProvider registry={registry} defaultOptions={{ placement: 'center', size: 'md', viewportGap: 5 }}>
  <App />
</ModalProvider>
const registry = {
  users: {
    initialRoute: 'List',
    modalOptions: { placement: 'right', width: 520 },
    screens: { List: { title: '用户列表', component: UserList } },
  },
};

modal.open('users'); // 默认右侧 520px
modal.open('users', {}, { placement: 'center', width: 700 }); // 本次临时居中
modal.open('users', {}, { mobileFullscreen: true }); // 手机端全屏

注意:mobileFullscreen: true 在宽度 ≤640px 时会覆盖 placement 与 viewportGap,故不再保留 5px 缝隙;需要缝隙时不要启用此项。

页面导航与传参

function UserList() {
  const { navigation } = useModal();
  return <button onClick={() => navigation.navigate('UserDetail', { id: 8 })}>详情</button>;
}

function UserDetail() {
  const { navigation } = useModal();
  const id = navigation.currentRoute?.params?.id;
  return <>
    <p>用户 ID:{id}</p>
    <button onClick={() => navigation.setParams({ tab: 'settings' })}>切换标签</button>
    <button onClick={() => navigation.goBack({ updated: true })}>返回</button>
  </>;
}

navigate 进入路由,goBack(result?) 返回上一页,replace 替换当前页,reset 重置栈,setParams 合并当前页参数。隐藏页面 KeepAlive 保留状态;建议用 useFocusEffect 管理轮询和订阅。

页面跳转方法速查

| 方法 | 使用示例 | 行为 | |---|---|---| | navigate | navigation.navigate('UserDetail', { userId: 1 }) | 跳转;已有同名页面则复用并截断后续页面 | | goBack | navigation.goBack({ saved: true }) | 返回上一页并传回结果;根页面返回 false | | replace | navigation.replace('Success', { id: 1 }) | 替换当前页面 | | reset | navigation.reset('UserList') | 重置为新的根页面 | | setParams | navigation.setParams({ tab: 'info' }) | 浅合并当前页面参数 | | close | await navigation.close({ id: 1 }) | 关闭整个弹窗,不是返回上一页 |

navigation.canGoBack 判断能否返回;navigation.currentRoute 获取当前页面 { key, name, params };navigation.stack 获取完整导航栈。上一页使用 useNavigationResult(callback) 接收 goBack(result) 的结果,KeepAlive 页面使用 useIsFocused() / useFocusEffect() 管理焦点副作用。

完整的逐项说明、栈变化示例、返回值和注意事项请阅读 API 参考手册 · 第 5 章:页面导航。

Promise 结果与关闭守卫

const { modal } = useModal();
const result = await modal.openAsync('editUser');
if (result.status === 'confirmed') console.log(result.value);
else console.log(result.status, result.reason);

弹窗内部:await navigation.close({ id: 1 }) 返回确认结果。modal.open() 返回 Promise<number | null>(弹窗实例 ID 或阻止打开时 null),不是 openAsync 的业务结果。

modalOptions: {
  onBeforeClose: async ({ reason }) => {
    if (hasUnsavedChanges()) return window.confirm('未保存,确定关闭吗?');
    return true;
  },
  onOpen: ctx => console.log('opened', ctx),
  onClose: ctx => console.log('closed', ctx.reason),
  onNavigate: ctx => console.log('navigated', ctx),
  onFocus: ctx => console.log('focused', ctx),
  onBlur: ctx => console.log('blurred', ctx),
}

关闭被拒绝时弹窗继续存在。替换、取消和 Provider 卸载等情况,openAsync() 返回不同状态与 reason。不要将 onClose 当作弹窗仍处于活动状态的回调。

异步提交与 Loading

import { useModal, useModalTask, useModalLoading } from 'react-modal-navigation';

function SaveScreen() {
  const { navigation } = useModal();
  const { run, pending, error } = useModalTask();
  const save = async () => {
    const result = await run(() => Promise.resolve({ id: 10 }), { loadingText: '保存中...' });
    if (result.status === 'success') await navigation.close(result.value);
  };
  return <>
    {error && <p role="alert">保存失败,请重试</p>}
    <button disabled={pending} onClick={save}>保存</button>
  </>;
}

useModalLoading().showLoading() 返回任务 token,使用 hideLoading(token) 结束对应任务;多个任务并发不会相互误关。useModalTask 阻止同一 Hook 的重复提交,但不会自动取消网络请求。

主题与样式覆盖

<ModalProvider registry={registry} theme="auto"
  backgroundColor={{ light: '#fff', dark: '#334155' }}>
  <App />
</ModalProvider>

不需要导入库的 CSS。已有 className、bodyClassName、headerClassName、footerClassName 可供业务样式覆盖;也可在业务项目中覆盖 --pmn-surface、--pmn-text、--pmn-border 等 CSS 变量。自动注入 CSS 时请注意 CSS 优先级。若站点 CSP 禁止内联样式,可改用 react-modal-navigation/style.css 静态导入,并按需配置 CSP。

事件可访问性和注意事项

  • closeOnOverlay 默认 false;closeOnEsc 默认 true。
  • 对话框有 role="dialog"、aria-modal、Tab 焦点约束、关闭后焦点恢复。
  • 背景滚动被锁定,并补偿滚动条宽度。
  • KeepAlive 页面隐藏时保持组件挂载,轮询/订阅请自行按焦点停止。
  • 若多次调用 open() 或存在异步关闭守卫,建议 await 以避免竞态。
  • 样式注入依赖浏览器 DOM;SSR 时不会直接访问 document。严格 CSP 环境可能需要改为静态 CSS。

TypeScript

公开类型位于 types/index.d.ts,包括 ModalOptions、ModalRegistry、ModalNavigation、ModalResult 等。

import type { ModalRegistry } from 'react-modal-navigation';
const registry: ModalRegistry = {
  demo: { initialRoute: 'Main', modalOptions: { placement: 'right', size: 'lg' }, screens: { Main: { component: Main } } },
};

支持 modal.open({ name, params, options }) 和 modal.openAsync({ name, params, options }),字符串形式继续兼容。

简洁的对象调用

对象调用现在还支持将布局配置直接放在顶层,options 不再是必需的:

const { modal } = useModal();

modal.open({ name: 'editUser', placement: 'bottom', width: '100%', height: '55dvh' });
modal.open({ name: 'editUser', params: { userId: 1001 }, placement: 'right', width: 520 });

// 原有嵌套 options 形式仍然可用
modal.open({ name: 'editUser', options: { placement: 'center', width: 640 } });

两种对象写法都适用于 modal.openAsync()。若同时提供顶层布局参数和 options,options 中的同名配置优先。字符串形式 modal.open('editUser', params, options) 保持兼容。

明确区分确认和取消

新增 modal.confirm(value) 和 modal.dismiss(reason),使 Promise 结果语义更加清晰,尤其是确认时没有返回值的场景。

function EditUser() {
  const { modal } = useModal();
  return <>
    <button onClick={() => modal.confirm({ saved: true })}>保存并关闭</button>
    <button onClick={() => modal.confirm()}>仅确认,不返回数据</button>
    <button onClick={() => modal.dismiss('cancel')}>取消</button>
  </>;
}

const result = await modal.openAsync({ name: 'editUser', placement: 'right', width: 520 });
if (result.status === 'confirmed') {
  // result.value 允许为 undefined,仍属于 confirmed
} else if (result.status === 'dismissed') {
  // result.reason 可能是 cancel、api、escape 等
}

confirm 和 dismiss 均遵守 onBeforeClose 异步关闭守卫;返回 Promise<boolean>,表示是否实际关闭。原有 modal.close(result) 保持不变:传入值视为确认,不传值视为取消。

建议的业务实践

  • 编辑表单:用 modal.openAsync() 等待提交结果,用 onBeforeClose 检查未保存数据。
  • 抽屉式详情:用 placement: 'right',高度自动适配视口,四周保留默认 5px 间距。
  • 移动端筛选:用 placement: 'bottom' 和 height: '55dvh'。
  • 防止重复提交:在弹窗页面中使用 useModalTask(),并在成功后 modal.confirm(result)。
  • 导航返回值:多页面流程中用 navigation.goBack(result),最外层完成时用 modal.confirm(result)。

表单未保存保护

在任意弹窗页面调用 useModalUnsavedChanges(isDirty)。关闭、取消、ESC、遮罩关闭和替换弹窗时都会检查;用户拒绝放弃修改则保留当前弹窗。KeepAlive 页面即使暂时隐藏,保护仍然生效。

import { useState } from 'react';
import { useModal, useModalUnsavedChanges } from 'react-modal-navigation';

function EditUser() {
  const { modal } = useModal();
  const [name, setName] = useState('');
  const [savedName, setSavedName] = useState('');
  useModalUnsavedChanges(name !== savedName, { message: '修改尚未保存,确定退出?' });
  async function save() {
    await saveUser({ name });
    setSavedName(name);
    // 保存成功后 dirty 变为 false,再关闭;异步状态提交可能需要等待一次渲染
  }
  return <><input value={name} onChange={e => setName(e.target.value)} /><button onClick={save}>保存</button><button onClick={() => modal.dismiss('cancel')}>取消</button></>;
}

全局自定义确认对话框(支持异步):

<ModalProvider registry={registry} confirmDiscard={async ({ name, reason }) => {
  return window.confirm(`弹窗 ${name} 有未保存的内容,确定放弃?`);
}}>
  <App />
</ModalProvider>

也可以单页面传入 onBeforeDiscard,优先级高于全局 confirmDiscard。默认调用 window.confirm;SSR/非浏览器环境默认拒绝丢弃。请注意:本功能阻止关闭和弹窗替换,但不阻止弹窗内部 navigation.navigate/goBack/reset,也不自动保护浏览器刷新。

动画(新增)

默认 220ms,随 placement 自动切换:居中缩放淡入淡出、左右抽屉横向滑动、上下 Sheet 纵向滑动;遮罩渐变。

modal.open({ name: 'editUser', placement: 'right', width: 520, animation: true, animationDuration: 260 });
modal.open({ name: 'quickInfo', placement: 'center', animation: false });

animationDuration 单位毫秒;系统启用 prefers-reduced-motion: reduce 时自动关闭动画。退出动画结束后才触发 onClose 和队列中的下一个弹窗。

打开时指定初始页面

在同一个弹窗中注册多个页面,默认使用 initialRoute。通过 screen 可以在打开时覆盖初始页面,不需要先打开列表再导航。

const registry = {
  userModal: {
    initialRoute: 'UserList',
    screens: {
      UserList: { component: UserList, title: '用户列表' },
      UserDetail: { component: UserDetail, title: '用户详情' },
      UserEdit: { component: UserEdit, title: '编辑用户' },
    },
  },
};

modal.open({ name: 'userModal' }); // 打开 UserList
modal.open({
  name: 'userModal',
  screen: 'UserDetail',
  params: { userId: 1001 },
  placement: 'right',
  width: 600,
});

// Promise 和队列 API 也支持 screen
const result = await modal.openAsync({
  name: 'userModal',
  screen: 'UserEdit',
  params: { userId: 1001 },
});
  • screen 必须是 registry[name].screens 中注册的页面名称。
  • 省略 screen 时使用 initialRoute;params 始终传给选中的初始页面。
  • 未注册的页面会抛出错误,不会静默回退。
  • 传统字符串调用 modal.open('userModal', params, options) 保持不变。
  • screen 只在打开时生效,打开后切换页面请使用 navigation.navigate()。

动态页面标题与路由参数

每个弹窗页面均可通过 useModal() 取得 navigation.currentRoute,或者直接读取页面组件的 route 属性。params 是打开或跳转页面时传入的参数。

import { useEffect } from 'react';
import { useModal } from 'react-modal-navigation';

function UserDetail({ route }) {
  const { navigation } = useModal();
  const userId = route.params?.userId;

  useEffect(() => {
    navigation.setOptions({ title: `用户详情 #${userId}` });
  }, [navigation.setOptions, userId]);

  return <div>用户 ID:{userId}</div>;
}

// 打开时指定页面和参数
modal.open({ name: 'userModal', screen: 'UserDetail', params: { userId: 1001 } });

// 弹窗内导航时传参
navigation.navigate('UserDetail', { userId: 1002 });

navigation.setOptions(options) 更新当前路由实例的页面配置(例如 title、renderHeaderRight、showBackButton),不会修改 Registry,也不会重置页面栈。navigation.setParams({ userId: 1003 }) 则合并当前页面参数。详情见 API 文档。

Footer 异步操作的整窗 Loading

点击默认 Footer 的 Done/Cancel 按钮后,组件会在异步操作期间自动显示覆盖整个弹窗的 Loading 蒙层,完成或失败后自动移除。无需手动管理加载状态。loadingText 优先于 translate('modal.processing'),可按业务分别设置。

function EditUser() {
  const { t } = useTranslation();
  useModalFooter({
    doneText: t('common.save'),
    loadingText: t('common.saving'),
    done: async () => { await saveUser(); },
  });
  return <UserForm />;
}

如果需要手动控制整个弹窗的加载,可继续使用 useModalLoading() 的 setLoading(true, t('...')) / setLoading(false),或者 modal.setLoading(...)。

整窗 Loading 蒙层

useModalLoading() / modal.setLoading() 触发的 Loading 覆盖整个弹窗(Header、页面内容和 Footer),居中展示无卡片、无阴影的旋转圆圈及可国际化文案。背景使用半透明蒙层,弹窗内的操作在加载期间被遮挡。

modal.setLoading(true, { text: t("common.loading") });
// 请求结束后
modal.setLoading(false);

弹窗内部 Toast 消息提醒

useToast() 只在当前弹窗的范围内显示消息,不会向全局 document.body 添加通知。支持成功、错误、警告、信息四种状态,最多同时显示 5 条;默认 3000ms 后自动消失。

import { useToast } from 'react-modal-navigation';
import { useTranslation } from 'react-i18next';

function EditDevice() {
  const toast = useToast();
  const { t } = useTranslation();
  const save = async () => {
    try {
      await saveDevice();
      toast.success(t('device.saveSuccess'));
    } catch (error) {
      toast.error(t('device.saveFailed'), { duration: 5000 });
    }
  };
  return <button onClick={save}>{t('common.save')}</button>;
}
const toast = useToast();
toast('操作提示');                  // 默认 info
toast.info('请先填写名称');
toast.success('保存成功');
toast.warning('设备暂时离线');
toast.error('保存失败', { duration: 5000 });
const id = toast('持续提醒', { duration: 0 }); // 不自动关闭
toast.dismiss(id);                 // 关闭指定消息
toast.clear();                    // 清空当前弹窗消息

duration 单位毫秒;设为 0 则不自动消失。dismissible: false 隐藏关闭按钮。消息区域始终限制在弹窗内,弹窗关闭时通知自动销毁。国际化文案由业务侧调用 t() 后传入。

导航保护与页面缓存

使用 useModalUnsavedChanges(dirty, { message, onBeforeDiscard }) 注册当前页面的未保存数据保护。现在内部 navigate、goBack、replace、reset 以及弹窗关闭/替换都检查将被移除的脏页面。navigate 进入新页面不会丢弃当前 KeepAlive 页面,因此不触发丢弃确认;返回或重置时会检查。异步确认期间拒绝重复导航。

导航方法 navigate、goBack、replace、reset 现在返回 Promise<boolean>,可通过 await 判断是否被拦截:

const { navigation } = useModal();
const moved = await navigation.goBack({ saved: true });
if (!moved) console.log('用户取消了离开操作');

缓存可按页面与弹窗共同控制:

const registry = {
  userModal: {
    initialRoute: 'List',
    modalOptions: { maxCachedScreens: 2 },
    screens: {
      List: { component: List, keepAlive: true },
      Edit: { component: Edit, keepAlive: false },
      Detail: { component: Detail, keepAlive: true },
    },
  },
};

keepAlive 默认 true,maxCachedScreens 默认无限制;设置为 0 仅挂载当前页面。未缓存页面重新进入时会重新挂载、重新初始化局部状态;导航栈和路由参数仍然保留。缓存限制按当前导航栈中靠近栈顶的页面计算,并非 LRU。

并发安全与状态隔离

导航操作 navigate、goBack、replace、reset 返回 Promise<boolean>,应使用 await 获取实际结果。组件在异步离开确认期间拒绝重复导航,并在确认返回后检查页面身份;关闭或卸载的实例不会继续提交导航。Loading 的命令引用保持稳定,文案更新不会重新创建命令对象。

const { navigation } = useModal();
const handleBack = async () => {
  const didNavigate = await navigation.goBack({ updated: true });
  if (!didNavigate) return;
};

导航、Toast 和 Loading 均由弹窗实例管理,弹窗关闭时清理未完成的通知定时器和任务。

Context 订阅拆分(性能)

需要导航操作但不读取当前路由的页面,优先使用 useModalNavigationCommands();该 Hook 不订阅导航栈变化。

import { useModalNavigationCommands, useModalNavigationState } from 'react-modal-navigation';

function NextButton() {
  const { navigate } = useModalNavigationCommands();
  return <button onClick={() => navigate('UserDetail', { id: 1 })}>详情</button>;
}

function Breadcrumb() {
  const { currentRoute, canGoBack, stack } = useModalNavigationState();
  return <span>{currentRoute?.name} · {stack.length} · {canGoBack ? '可返回' : '首页'}</span>;
}

useModal() 和 useModalNavigation() 保持兼容,会订阅导航状态;仅需要操作方法时推荐使用拆分后的 Hook。弹窗级 Toast/Loading 仍有独立的状态更新路径,后续可通过 React Profiler 继续验证渲染次数。

独立状态订阅(性能优化)

Loading、Footer 和 Toast 分别使用独立的 external store(useSyncExternalStore)。 通知 Toast 不会更新 Footer/Loading 的状态订阅;更新 Footer 配置不会通知 Toast/Loading;Loading 文案变化只通知 Loading 订阅者。 useToast() 返回稳定的命令接口;useModalFooter() 注册页面配置;useModalLoading() 仍兼容原 API,并订阅 isLoading。 导航命令与导航状态继续通过 useModalNavigationCommands()、useModalNavigationState() 分离。

tests/react-profiler.test.mjs 提供 React Profiler 的更新次数回归测试;需在测试环境额外安装与 React 19 匹配的 react-test-renderer,否则测试明确标记为跳过。此测试验证独立 store 的消费者隔离,不等同于完整浏览器页面性能基准。

1.1.6 性能与稳定性优化

  • 修复 ModalNavigator 缺少 useState 导入导致的运行时异常。
  • 稳定页面级导航保护 Context 值,减少缓存页面无关重渲染。
  • 缓存当前页面的合并配置,减少 Header / Footer 不必要的属性引用变化。
  • Toast 超过 5 条时主动清理被淘汰消息的计时器,避免多余回调。
  • Footer 使用同步锁阻止连续点击触发并行提交。
  • 保留原有 API;建议在实际业务中使用 React Profiler 验证缓存页面的提交次数。

React 19 实际组件渲染性能回归测试

本项目提供 tests/react-profiler.integration.test.jsx,测试会挂载真实的 ModalProvider、ModalNavigator、KeepAlive 页面及 Toast/Loading Hook,并用 React Profiler 统计提交次数,而不是只测试模拟 Store。

npm install
npm run test:react

测试覆盖 Toast 更新时当前页面的提交次数、缓存页面在 Toast 与 Loading 更新时的提交次数。此测试需要完整安装 React 19、Vitest、jsdom 等依赖。 如果依赖安装失败或测试没有执行,不能据此宣称通过,也不能将“0 次重渲染”视为已验证结论。运行结果应作为是否进一步拆分 Context 的依据。

1.1.6 使用体验扩展

import { useModal, useModalRoute, useModalParams, useModalFooter, useToast } from 'react-modal-navigation';

function EditDevice() {
  const { navigation } = useModal();
  const { name, key } = useModalRoute();
  const { deviceId } = useModalParams();
  const toast = useToast();
  useModalFooter({
    actions: [
      { key: 'cancel', label: '取消', variant: 'secondary', onClick: () => navigation.goBack() },
      { key: 'save', label: '保存', variant: 'primary', loadingText: '保存中...',
        onClick: () => toast.promise(() => saveDevice(deviceId), { loading: '正在保存', success: '保存成功', error: '保存失败' }) },
    ],
  });
  const pickDevice = async () => {
    const result = await navigation.navigateAsync('DevicePicker');
    if (result.status === 'returned') console.log(result.value);
  };
  return <button onClick={pickDevice}>选择设备</button>;
}
// DevicePicker: navigation.goBack(selectedDevice)

navigateAsync() 返回 {status:'returned',value}、{status:'removed'}、{status:'cancelled'} 或 {status:'dismissed'},不会因页面被替换或弹窗关闭而无限等待。toast.promise() 保留原始 Promise 的返回值和异常。actions 与旧版 done/cancel 二选一;各按钮有独立 pending 状态。

v1.1.6 架构与性能优化

Loading 与 Toast 控制逻辑已从 ModalNavigator 提取为独立控制器,原有 useModalLoading()、useToast()、Footer 与导航 API 保持不变。

只需控制 Loading、无需读取状态时,建议使用:

import { useModalLoadingCommands, useModalLoadingState } from 'react-modal-navigation';

function SaveButton() {
  const { showLoading, hideLoading } = useModalLoadingCommands();
  const save = async () => {
    const token = showLoading('保存中...');
    try { await saveData(); } finally { hideLoading(token); }
  };
  return <button onClick={save}>保存</button>;
}

function LoadingIndicator() {
  const { visible } = useModalLoadingState();
  return visible ? <span>正在处理</span> : null;
}

声明式 Footer 的按钮配置现在使用逐属性比较,避免 JSON 序列化丢失函数属性或遗漏新增配置字段。异步操作仍需要在业务层使用 try/finally 管理自身资源。

类型增强:可通过 TypedModalNavigation<Routes> 为项目提供路由名及参数的静态检查。

返回按钮显示规则(1.1.6 修复)

默认 Header 在导航栈超过一页时自动显示返回按钮。使用 navigation.navigate('Detail') 推入页面;replace / reset 不增加可返回的历史。可通过 showBackButton: false 隐藏,页面 setOptions({ showBackButton: true }) 可覆盖默认设置。如果使用 renderHeader 自定义整个 Header,需要自行渲染返回按钮。

页面跳转动画

navigation.navigate() 进入新页面时默认从右侧轻滑入,navigation.goBack() 返回时从左侧轻滑入,动画时长默认为 240ms。仅页面路由发生变化时触发,修改参数、Toast 或 Footer 不会重复触发。系统启用减少动态效果时会自动关闭动画。

const registry = {
  device: {
    initialRoute: 'List',
    modalOptions: { pageAnimation: true, pageAnimationDuration: 260 },
    screens: { List: { component: List }, Detail: { component: Detail } },
  },
};

// 页面内
navigation.navigate('Detail', { id: 1 });
navigation.goBack();

不需要动画时传入 pageAnimation: false。animation: false 同时禁用弹窗和页面动画。

更明显的页面滑动效果

默认页面滑动距离由 22px 提高到 96px,动画时长由 240ms 提高到 360ms,并增加淡入和轻微缩放。可通过以下选项调整:

modalOptions: {
  pageAnimation: true,
  pageAnimationDuration: 420,
  pageAnimationDistance: 140,
}

pageAnimationDistance 范围为 0–300px;pageAnimationDuration 范围为 0–1000ms。系统启用减少动态效果时仍尊重该设置。

Full-width page transitions

navigation.navigate() and navigation.goBack() now slide both incoming and outgoing content pages in opposite directions across the full content width. Header and Footer stay fixed. Configure pageAnimationDuration (default 360ms) and disable via pageAnimation: false. Motion is suppressed when the user prefers reduced motion.

单页面弹窗(自动轻量模式)

注册单个页面时,无需定义路由栈;继续使用同一个 ModalProvider、modal.open()、modal.openAsync()、Footer、Toast、Loading、关闭守卫和弹窗样式。

import { lazy } from 'react';
const AddDevice = lazy(() => import('./AddDevice'));

export const registry = {
  addDevice: {
    component: AddDevice,
    title: '添加设备',
    modalOptions: { placement: 'center', width: 480 },
  },
};

// 与多页面弹窗完全一致
const result = await modal.openAsync('addDevice');
if (result.status === 'confirmed') await refreshDevices();

旧版 screens: { AddDevice: { component: AddDevice } } 只有一个页面时也自动进入轻量模式。两个及以上页面继续使用完整路由导航。单页面模式不会创建导航 reducer、页面缓存或页面切换动画;navigation.navigate()、goBack() 等路由操作返回 false,navigateAsync() 返回 {status:'cancelled'}。仍可调用 navigation.setParams()、navigation.setOptions()、navigation.close()。

单页表单建议使用 modal.confirm({success:true}) 结束 openAsync;取消则使用 modal.dismiss()。

Tailwind background colors (v1.1.10)

export default {
  component: Settings,
  modalOptions: {
    placement: 'right',
    backgroundColor: { light: 'bg-gray-100', dark: 'bg-slate-700' },
  },
};

backgroundColor also accepts CSS colors ('#f5f5f5', 'oklch(...)'). The modal's theme selects light or dark; it does not require the host's dark: selector. For Tailwind v4, ensure registry source files are scanned by Tailwind. Dynamically generated class names must be safelisted using @source inline(...) or equivalent. The package does not bundle Tailwind.