设计插件 API
构建 Napacitor 插件的第一步——也可以说是最重要的一步——就是设计 API。API 是我们在编写各平台具体实现时要遵循的契约。
我们可以用 TypeScript 定义插件 API;它将成为实现时的契约,并带来 TypeScript 的好处,例如代码补全与类型检查。
等等,这真的需要一个插件吗?
信不信由你,现代浏览器已经能做许多我们认为是「原生功能」的事情,例如查询电池状态、语音识别,还有——没错——屏幕方向。在构建 Web Native 应用时,曾经需要插件才能访问的功能现在以 Web API 形式提供,这种情况并不罕见。
在为某个特性构建插件之前,我们建议先到 What Web Can Do Today 这类站点看看你所需的功能是否已作为 Web API 提供。
如果屏幕方向已经有 Web API,为什么还要费劲 自己写一个?看看 Screen Orientation Web API 就会发现 iOS 并未实现该 API(截至本文撰写时),这意味着我们需要自己提供实现。况且,当应用运行在 MAUI 宿主内时,方向来自原生平台,而非浏览器。
定义 ScreenOrientation API
我们或许无法直接使用 Screen Orientation Web API,但可以参照它来设计插件 API:
| 方法名 | 输入参数 | 返回值 |
|---|---|---|
| orientation | Promise<ScreenOrientationResult> | |
| addListener | (eventName, listenerFunc) | Promise<PluginListenerHandle> |
| removeAllListeners | Promise<void> |
注意这里没有 lock() 或 unlock():.NET MAUI 没有跨平台的方向锁定 API,因此我们让插件只承诺原生层在所有平台上都能交付的能力。
我们来创建一个目录存放插件 API。新建子文件夹 src/plugins/screen-orientation,并在其中添加以下文件:
definitions.tsindex.ts
在 definitions.ts 中填入以下代码:
import type { PluginListenerHandle } from '@napacitor/core';
export type OrientationType = 'portrait' | 'landscape';
export interface ScreenOrientationResult {
type: OrientationType;
}
export interface ScreenOrientationPlugin {
/**
* Returns the screen's current orientation.
*/
orientation(): Promise<ScreenOrientationResult>;
/**
* Listens for screen orientation changes.
*/
addListener(
eventName: 'screenOrientationChange',
listenerFunc: (orientation: ScreenOrientationResult) => void,
): Promise<PluginListenerHandle>;
/**
* Removes all listeners
*/
removeAllListeners(): Promise<void>;
}
注册 ScreenOrientation 插件
要在 Napacitor 应用中使用该插件,我们需要通过 @napacitor/core 导出的 registerPlugin() 模块来注册它。
在 index.ts 中填入以下代码:
import { registerPlugin } from '@napacitor/core';
import type { ScreenOrientationPlugin } from './definitions';
const ScreenOrientation = registerPlugin<ScreenOrientationPlugin>(
'ScreenOrientation',
);
export * from './definitions';
export { ScreenOrientation };
上面的代码创建了一个关联到插件实现代码的对象。字符串 'ScreenOrientation' 是插件名——用 [NapacitorPlugin] 注册的 C# 类必须暴露完全相同的名称(不区分大小写)。
API 设计完成;接下来我们构建一个会调用它的用户界面。这样做能让我们在实现各平台集成时更容易测试。下一步:使用插件 API。