@trimjs/web-app 0.1.4 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -288,26 +288,16 @@ const dateFormatter = new Intl.DateTimeFormat(config.language, {
288
288
  async close(): Promise<void>
289
289
  ```
290
290
 
291
- 关闭应用(仅支持 Web 平台)。
291
+ 关闭应用。
292
292
 
293
293
  **返回值:**
294
294
 
295
295
  - `Promise<void>`
296
296
 
297
- **注意:**
298
-
299
- - 此方法仅在 Web 平台(iframe)中可用
300
- - 在移动端调用会抛出错误
301
-
302
297
  **示例:**
303
298
 
304
299
  ```typescript
305
- // 检查是否为 Web 平台
306
- if (app.isWeb) {
307
- await app.query();
308
- } else {
309
- console.log("query 方法仅在 Web 平台可用");
310
- }
300
+ app.close();
311
301
  ```
312
302
 
313
303
  ---
package/package.json CHANGED
@@ -1,11 +1,10 @@
1
1
  {
2
2
  "name": "@trimjs/web-app",
3
- "version": "0.1.4",
3
+ "version": "0.1.5",
4
4
  "description": "web app sdk for nas",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
7
7
  "module": "dist/index.js",
8
- "types": "dist/index.d.ts",
9
8
  "scripts": {
10
9
  "dev": "vite",
11
10
  "build": "tsc -b && vite build",
@@ -13,7 +12,6 @@
13
12
  "typecheck": "tsc --noEmit"
14
13
  },
15
14
  "files": [
16
- "src",
17
15
  "dist"
18
16
  ],
19
17
  "devDependencies": {
package/src/index.ts DELETED
@@ -1,257 +0,0 @@
1
- import { logger } from "./logger";
2
- import type { PlatformConfig, TrimAppOptions } from "./types";
3
- import type { FlutterInAppWebView } from "./mobile/index";
4
- import { isFnApp } from "./utils/platform";
5
- import { callHandler, initMobile } from "./mobile/index";
6
- import { initWeb, OSConnection } from "./web/index";
7
- import { AppMessage } from "./mobile/types";
8
- import { type ResponseData } from "@fn/micro-app-postmate/src/child/os-type";
9
- import {
10
- type FilePickerParams,
11
- type QueryConfig,
12
- } from "@fn/micro-app-postmate/src/child/type";
13
-
14
- /**
15
- * @trim/app - NAS 应用 SDK
16
- * @description nas 应用 SDK
17
- */
18
-
19
- // 导出类型
20
- export type { TrimAppOptions } from "./types";
21
-
22
- /**
23
- * Trim App 实例类
24
- */
25
- export class TrimApp {
26
- private options: TrimAppOptions;
27
-
28
- private flutterInAppWebView: FlutterInAppWebView | null = null;
29
- private osConnector: OSConnection | null = null;
30
- private initPromise: Promise<void>;
31
-
32
- public isWeb: boolean = true;
33
-
34
- constructor(options: TrimAppOptions = {}) {
35
- this.options = options;
36
-
37
- // 设置 debug 模式
38
- if (options.debug) {
39
- logger.setDebug(true);
40
- logger.log("Trim App initialized with debug mode");
41
- }
42
-
43
- logger.log("Options:", options);
44
-
45
- // 保存初始化 Promise
46
- this.initPromise = this.init();
47
- }
48
-
49
- private async init(): Promise<void> {
50
- logger.log("Starting initialization...");
51
-
52
- return new Promise((resolve) => {
53
- if (isFnApp()) {
54
- this.isWeb = false;
55
- logger.log("Initializing mobile platform...");
56
- initMobile().then((flutterInAppWebView) => {
57
- this.flutterInAppWebView = flutterInAppWebView;
58
- logger.log("Mobile platform initialized");
59
- resolve();
60
- });
61
- } else {
62
- this.isWeb = true;
63
- logger.log("Initializing web platform...");
64
- initWeb().then((osConnector) => {
65
- this.osConnector = osConnector as OSConnection;
66
- logger.log("Web platform initialized");
67
- resolve();
68
- });
69
- }
70
- });
71
- }
72
-
73
- public async callAppMethod<T>(
74
- fn: string,
75
- params?: string
76
- ): Promise<T | null> {
77
- if (!this.flutterInAppWebView) {
78
- return null;
79
- }
80
- return callHandler<T>(this.flutterInAppWebView, fn, params);
81
- }
82
-
83
- /**
84
- * 等待初始化完成
85
- * @returns Promise
86
- */
87
- async ready(): Promise<void> {
88
- return this.initPromise;
89
- }
90
-
91
- /**
92
- * 获取配置
93
- */
94
- getOptions(): TrimAppOptions {
95
- return this.options;
96
- }
97
-
98
- /**
99
- * 更新配置
100
- */
101
- setOptions(options: Partial<TrimAppOptions>) {
102
- this.options = { ...this.options, ...options };
103
-
104
- // 更新 debug 模式
105
- if (options.debug !== undefined) {
106
- logger.setDebug(options.debug);
107
- }
108
-
109
- logger.log("Options updated:", this.options);
110
- }
111
-
112
- // 调用 app 的方法
113
-
114
- /**
115
- * 获取平台配置
116
- */
117
- async getPlatformConfig(): Promise<PlatformConfig> {
118
- // 等待初始化完成
119
- await this.initPromise;
120
-
121
- if (this.isWeb) {
122
- const config = await this.osConnector?.methods.getPlatformConfig();
123
- if (!config) {
124
- throw new Error("Failed to get platform config");
125
- }
126
- return config;
127
- } else {
128
- const config = await this.callAppMethod<AppMessage>("getAppMessage");
129
- if (!config) {
130
- throw new Error("Failed to get platform config");
131
- }
132
- return {
133
- theme: config.nightMode as "dark" | "light",
134
- language: config.language,
135
- appVersion: config.appVersion,
136
- systemVersion: config.systemVersion,
137
- format: {
138
- date: config.dateFormat,
139
- time: config.timeFormat,
140
- },
141
- };
142
- }
143
- }
144
-
145
- /**
146
- * setTitle - 设置标题
147
- * @param title 标题文本
148
- */
149
- async setTitle(title: string) {
150
- // 等待初始化完成
151
- await this.initPromise;
152
-
153
- logger.log("Setting title:", title);
154
-
155
- if (this.isWeb) {
156
- return this.osConnector?.methods.setTitle(title);
157
- } else {
158
- return this.callAppMethod("updateTitle", title);
159
- }
160
- }
161
-
162
- /**
163
- * setExitPageTips - 设置退出页面提示
164
- * @param params 提示参数
165
- */
166
- async setExitPageTips(params?: { title?: string; content?: string }) {
167
- // 等待初始化完成
168
- await this.initPromise;
169
-
170
- if (this.isWeb) {
171
- return this.osConnector?.methods.setExitPageTips(params);
172
- } else {
173
- return this.callAppMethod(
174
- "setExitPageTips",
175
- params ? JSON.stringify(params) : ""
176
- );
177
- }
178
- }
179
-
180
- /**
181
- * 通过应用打开某个文件
182
- */
183
- async openFile(path: string) {
184
- // 等待初始化完成
185
- await this.initPromise;
186
-
187
- logger.log("Opening file:", path);
188
-
189
- if (this.isWeb) {
190
- return this.osConnector?.methods.openFile(path);
191
- } else {
192
- return this.callAppMethod("openFile", path);
193
- }
194
- }
195
-
196
- /**
197
- * 打开文件管理器
198
- */
199
- async openFileManager(path: string) {
200
- // 等待初始化完成
201
- await this.initPromise;
202
-
203
- logger.log("Opening file manager:", path);
204
-
205
- if (this.isWeb) {
206
- return this.osConnector?.methods.openFileManagerApp(path);
207
- } else {
208
- return this.callAppMethod("openFileManager", path);
209
- }
210
- }
211
-
212
- /**
213
- * 关闭应用
214
- */
215
- async close() {
216
- // 等待初始化完成
217
- await this.initPromise;
218
- if (this.isWeb) {
219
- return this.osConnector?.methods.close();
220
- } else {
221
- return this.callAppMethod("exitPage");
222
- }
223
- }
224
-
225
- /**
226
- * 请求接口
227
- */
228
- async query<T>(params: any, config?: QueryConfig): Promise<ResponseData<T>> {
229
- // 等待初始化完成
230
- await this.initPromise;
231
- if (this.isWeb) {
232
- const result = await this.osConnector?.methods.query<T>(params, config);
233
- if (!result) {
234
- throw new Error("Failed to query");
235
- }
236
- return result;
237
- } else {
238
- throw new Error("query is not supported on mobile platform");
239
- }
240
- }
241
-
242
- /**
243
- * 选择文件
244
- */
245
- async pickFile(params: FilePickerParams) {
246
- // 等待初始化完成
247
- await this.initPromise;
248
- if (this.isWeb) {
249
- return this.osConnector?.methods.pickFile(params);
250
- } else {
251
- return this.callAppMethod("openFolder", JSON.stringify(params));
252
- }
253
- }
254
- }
255
-
256
- // 默认导出
257
- export default TrimApp;
package/src/logger.ts DELETED
@@ -1,65 +0,0 @@
1
- /**
2
- * Logger 工具类
3
- * 只有在 debug 模式下才会输出日志
4
- */
5
- class Logger {
6
- private debug: boolean = false;
7
-
8
- /**
9
- * 设置 debug 模式
10
- * @param enabled 是否启用 debug
11
- */
12
- setDebug(enabled: boolean) {
13
- this.debug = enabled;
14
- }
15
-
16
- /**
17
- * 获取当前 debug 状态
18
- */
19
- isDebug(): boolean {
20
- return this.debug;
21
- }
22
-
23
- /**
24
- * 输出日志(只在 debug 模式下)
25
- * @param args 日志参数
26
- */
27
- log(...args: any[]) {
28
- if (this.debug) {
29
- console.log('[Trim App]', ...args);
30
- }
31
- }
32
-
33
- /**
34
- * 输出警告日志(只在 debug 模式下)
35
- * @param args 日志参数
36
- */
37
- warn(...args: any[]) {
38
- if (this.debug) {
39
- console.warn('[Trim App]', ...args);
40
- }
41
- }
42
-
43
- /**
44
- * 输出错误日志(只在 debug 模式下)
45
- * @param args 日志参数
46
- */
47
- error(...args: any[]) {
48
- if (this.debug) {
49
- console.error('[Trim App]', ...args);
50
- }
51
- }
52
-
53
- /**
54
- * 输出信息日志(只在 debug 模式下)
55
- * @param args 日志参数
56
- */
57
- info(...args: any[]) {
58
- if (this.debug) {
59
- console.info('[Trim App]', ...args);
60
- }
61
- }
62
- }
63
-
64
- // 导出单例
65
- export const logger = new Logger();
@@ -1,112 +0,0 @@
1
- import { logger } from "../logger";
2
- import { isFnApp } from "../utils/platform";
3
-
4
- export interface FlutterInAppWebView {
5
- callHandler: (fn: string, params?: string) => Promise<string>;
6
- _platformReady?: boolean;
7
- }
8
-
9
- declare global {
10
- interface Window {
11
- flutter_inappwebview: FlutterInAppWebView;
12
- fnAppMessage?: (message: string) => void;
13
- onAppHeaderGoBack?: () => boolean | number | string; // 随意返回
14
- }
15
- }
16
-
17
- let isReady = false;
18
- window.addEventListener("flutterInAppWebViewPlatformReady", () => {
19
- isReady = true;
20
- });
21
-
22
- export const initMobile = () => {
23
- /**
24
- * 处理app有回掉的方法消息
25
- */
26
- return new Promise<FlutterInAppWebView>((res) => {
27
- if (isReady || window.flutter_inappwebview?._platformReady) {
28
- logger.log("flutter_inappwebview is ready");
29
- res(window.flutter_inappwebview);
30
- } else {
31
- window.addEventListener("flutterInAppWebViewPlatformReady", () => {
32
- logger.log("flutter_inappwebview is ready");
33
- res(window.flutter_inappwebview);
34
- });
35
- }
36
- });
37
- };
38
-
39
- export interface FnAppMessage<T> {
40
- reqId: string;
41
- method: string;
42
- result: T;
43
- }
44
-
45
- export const callHandler = async <T>(
46
- flutterInAppWebView: FlutterInAppWebView,
47
- fn: string,
48
- params?: string
49
- ): Promise<T | null> => {
50
- logger.log(`callHandler: ${fn}, params: ${params}`);
51
- const res = await flutterInAppWebView.callHandler(fn, params);
52
- if (res) {
53
- try {
54
- const messageData: FnAppMessage<string> = JSON.parse(res);
55
- logger.log(`messageData: ${JSON.stringify(messageData)}`);
56
- const appMessage: T = JSON.parse(messageData.result);
57
- logger.log(`appMessage: ${JSON.stringify(appMessage)}`);
58
- return appMessage;
59
- } catch (error) {
60
- logger.error(`error: ${error}`);
61
- return null;
62
- }
63
- }
64
- return null;
65
- };
66
-
67
- // 存储app消息的回调
68
- const fnAppMessageHandleMap = new Map<
69
- string,
70
- (Response: FnAppMessage<any>) => void
71
- >();
72
-
73
- function initAppMessageEvent() {
74
- window.fnAppMessage = (message: string) => {
75
- logger.log("app-message", message);
76
- const data: FnAppMessage<any> = JSON.parse(message);
77
-
78
- const handle = fnAppMessageHandleMap.get(data.reqId);
79
- if (handle) {
80
- handle(data);
81
- fnAppMessageHandleMap.delete(data.reqId);
82
- }
83
- };
84
- }
85
-
86
- if (isFnApp()) {
87
- initAppMessageEvent();
88
- }
89
-
90
- export async function pickFilePromise(
91
- flutterInAppWebView: FlutterInAppWebView,
92
- params: {
93
- title: string;
94
- multiple: boolean;
95
- directory: boolean;
96
- }
97
- ): Promise<string[] | undefined> {
98
- return new Promise((resolve, reject) => {
99
- flutterInAppWebView
100
- ?.callHandler("openFolder", JSON.stringify(params))
101
- .then((reqId) => {
102
- if (reqId) {
103
- function handle(data: FnAppMessage<string[]>) {
104
- resolve(data.result);
105
- }
106
- fnAppMessageHandleMap.set(reqId, handle);
107
- } else {
108
- reject(new Error("openFolder failed"));
109
- }
110
- });
111
- });
112
- }
@@ -1,9 +0,0 @@
1
- export interface AppMessage {
2
- nightMode: string; // dark | light
3
- language: string;
4
- platform: string;
5
- appVersion?: string;
6
- systemVersion: string;
7
- dateFormat: string; // yyyy-MM-dd
8
- timeFormat: string; // 12h | 24h
9
- }
package/src/types.ts DELETED
@@ -1,18 +0,0 @@
1
- /**
2
- * SDK 配置选项
3
- */
4
- export interface TrimAppOptions {
5
- /** 是否开启 debug 模式,开启后会输出日志 */
6
- debug?: boolean;
7
- }
8
-
9
- export interface PlatformConfig {
10
- theme: "dark" | "light";
11
- language: string; // "zh-CN" | "en-US" ....
12
- appVersion?: string;
13
- systemVersion: string;
14
- format: {
15
- date?: string; // "YYYY-MM-DD" | "MM-DD-YYYY" | "DD-MM-YYYY" | "YYYY/MM/DD" | "MM/DD/YYYY" | "DD/MM/YYYY"
16
- time?: string; // "12h" | "24h"
17
- };
18
- }
@@ -1,17 +0,0 @@
1
- export function fnAppUAMatch(ua: string) {
2
- const regex = /FNOS\/([\d.]+)|FNAppType\/(\w+)|FNAppVer\/([\d.]+)/g;
3
-
4
- const matches: any = {};
5
- let match;
6
- while ((match = regex.exec(ua)) !== null) {
7
- if (match[1]) matches.fnOSVersion = match[1];
8
- if (match[2]) matches.fnAppType = match[2];
9
- if (match[3]) matches.fnAppVersion = match[3];
10
- }
11
-
12
- return matches;
13
- }
14
-
15
- export const isFnApp = () => {
16
- return fnAppUAMatch(navigator.userAgent).fnAppVersion;
17
- };
package/src/web/index.ts DELETED
@@ -1,27 +0,0 @@
1
- import { connectToOS } from "@fn/micro-app-postmate";
2
- import { type OSConfig } from "@fn/micro-app-postmate/src/parent/type";
3
- import {
4
- type OSMethods,
5
- type ConnectionResult,
6
- type AsyncMethodReturns,
7
- } from "@fn/micro-app-postmate/src/types";
8
- import type { PlatformConfig, TrimAppOptions } from "../types";
9
-
10
- export type OSConnection = AsyncMethodReturns<
11
- ConnectionResult<
12
- OSMethods & {
13
- setExitPageTips: (params?: { title?: string; content?: string }) => void;
14
- openFileManagerApp: (path: string) => void;
15
- openFile: (path: string) => void;
16
- getPlatformConfig: () => Promise<PlatformConfig>;
17
- close: () => void;
18
- },
19
- OSConfig
20
- >
21
- >;
22
-
23
- export const initWeb = (options?: TrimAppOptions) => {
24
- return connectToOS({
25
- debug: options?.debug,
26
- }).promise;
27
- };