alert.md 4.1 KB

全局提示与输入调用规范(window.fmode.alert / window.fmode.input)

本文定义统一的 UI 提示与输入接口,避免在各页面中分散使用浏览器 alert() 或事件派发。通过在 app.ts 中挂载的 window.fmode,可直接以函数方式调用。

总览

  • window.fmode.alert(detail):信息提示或确认弹窗
  • window.fmode.input(detail):输入弹窗(含 inputs
    • 简化输入用法(与 prompt() 等价):await window.fmode.input(message: string, defaultValue?: string) 返回输入的字符串或 null

二者均返回一个结果对象(等同于 Ionic AlertController.onDidDismiss() 的结果),可被 await。如果在 detail 中提供了 callback(result),系统会优先回调并同时派发 globalAlert:result 事件,含 detail.requestId(可选)。

参数 detail 结构

通用字段(两者均支持):

  • header?: string 标题,默认:提示 / 请输入
  • subHeader?: string 副标题
  • message?: string 消息正文(支持换行)
  • buttons?: Array<{ text: string; role?: 'cancel'|'confirm'|string }> 按钮定义,默认:
    • alert:[{ text: '确定', role: 'confirm' }]
    • input:[{ text: '取消', role: 'cancel' }, { text: '确定', role: 'confirm' }]
  • callback?: (result: any) => void 结果回调函数(优先级高于结果事件派发)
  • requestId?: string 请求 ID(用于在结果事件中关联)

window.fmode.input 支持:

  • inputs?: Array<{ name: string; type?: string; placeholder?: string; value?: any }> 输入项,默认:[{ name: 'value', type: 'text', placeholder: '请输入内容' }]

返回结果

  • Promise 解析为 result 对象,包含:
    • role: 按钮角色,如 'confirm' | 'cancel' | string
    • 可能包含输入值(参考 Ionic Alert 返回的 data 格式)
  • 若定义了 detail.callback,会被调用:detail.callback(result)
  • 同时派发:window.dispatchEvent(new CustomEvent('globalAlert:result', { detail: { requestId, result } }))

使用示例

信息提示(alert)

await window.fmode.alert({
  header: '报表导出',
  message: '✅ 报表导出成功!',
  buttons: [{ text: '确定', role: 'confirm' }]
});

确认交互(await 结果)

const result = await window.fmode.alert({
  header: '删除确认',
  message: '确定要删除该记录吗?',
  buttons: [
    { text: '取消', role: 'cancel' },
    { text: '确定', role: 'confirm' }
  ]
});
if (result?.role === 'confirm') {
  // 执行删除
}

输入弹窗

const result = await window.fmode.input({
  header: '请输入标签',
  inputs: [
    { name: 'tag', type: 'text', placeholder: '标签名称' }
  ],
  buttons: [
    { text: '取消', role: 'cancel' },
    { text: '确定', role: 'confirm' }
  ]
});
if (result?.role === 'confirm') {
  const value = result?.data?.values?.tag;
  // 使用输入值
}

简化输入用法(prompt 等价)

// 直接传入描述与默认值,返回字符串或 null
const name = await window.fmode.input('请输入项目名称', '默认项目');
if (name !== null) {
  // 用户点击了“确定”,拿到输入字符串
  console.log('新项目名称:', name);
} else {
  // 用户取消
}

迁移规则

  • 禁止使用浏览器 alert(),统一改为 window.fmode.alert()
  • 禁止派发 globalAlert/globalPrompt 事件,统一改为直接函数调用
  • 若需要跨组件监听结果,使用 requestId + globalAlert:result 事件进行关联

实现位置

  • src/app/app.ts:挂载 window.fmode.alert / window.fmode.input,并通过 Ionic AlertController 实现 UI 弹窗与结果返回
    • 字符串简化用法由 presentPromptSimple(message, defaultValue?) 提供,直接返回字符串或 null
  • src/fmode-ng-augmentation.d.ts:为 window.fmode 添加 TypeScript 类型声明

注意事项

  • 保持按钮的 role 与业务语义一致,用于结果分支判断
  • 输入项的 name 建议使用业务含义清晰的键名,避免与其它输入重复
  • 在需要异步结果通知的场景下,务必传入 requestId 以便事件监听端进行匹配