@trimjs/web-app 0.2.10 → 0.3.1

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
@@ -1,1042 +1,447 @@
1
1
  # @trimjs/web-app
2
2
 
3
- 一个用于应用与基座平台通讯的 SDK。
3
+ SDK for building apps that run inside the Trim host environment.
4
4
 
5
- ## 简介
5
+ `@trimjs/web-app` provides a single JavaScript API for common host capabilities, including page title updates, file operations, file authorization, app settings, and App Auth route flows. It works in supported web iframe hosts and mobile WebView hosts.
6
6
 
7
- `@trimjs/web-app` 是一个跨平台通讯 SDK,让你的应用能够轻松调用基座平台的能力。
8
-
9
- **核心特性:**
10
-
11
- - 🌐 **跨平台支持** - 同时支持在 Web iframe 和 App WebView 中运行
12
- - 🎯 **统一 API** - 提供统一的接口调用基座平台能力(如设置标题、打开文件等)
13
- - 🔧 **自动兼容** - 开发者无需关心底层平台差异,SDK 自动处理兼容性
14
- - 📦 **开箱即用** - 简单初始化即可使用,无需复杂配置
15
-
16
- ## 安装
17
-
18
- 使用 npm、yarn 或 pnpm 安装:
7
+ ## Installation
19
8
 
20
9
  ```bash
21
- # npm
22
10
  npm install @trimjs/web-app
11
+ ```
23
12
 
24
- # yarn
13
+ ```bash
25
14
  yarn add @trimjs/web-app
15
+ ```
26
16
 
27
- # pnpm
17
+ ```bash
28
18
  pnpm add @trimjs/web-app
29
19
  ```
30
20
 
31
- ## 快速开始
32
-
33
- ### 基础使用
21
+ ## Quick Start
34
22
 
35
- ```typescript
23
+ ```ts
36
24
  import { TrimApp } from '@trimjs/web-app';
37
25
 
38
- // 创建实例
39
26
  const app = new TrimApp();
40
27
 
41
- // 调用方法
42
- await app.setTitle('我的应用');
28
+ await app.setTitle('My App');
29
+
30
+ const config = await app.getPlatformConfig();
31
+ console.log(config.theme, config.language);
43
32
  ```
44
33
 
45
- ### 完整示例
34
+ All host APIs wait for SDK initialization internally. You usually do not need to call `ready()` before using them.
46
35
 
47
- ```typescript
36
+ ## Basic Usage
37
+
38
+ ```ts
48
39
  import { TrimApp } from '@trimjs/web-app';
49
40
 
50
- // 创建实例
51
- const app = new TrimApp({
52
- debug: true, // 开启调试模式,会输出日志
53
- });
41
+ const app = new TrimApp({ debug: true });
54
42
 
55
- // 设置应用标题
56
- await app.setTitle('我的应用');
43
+ await app.setTitle('Document Viewer');
57
44
 
58
- // 打开文件
59
- await app.openFile('/path/to/file.pdf');
45
+ await app.openFile('/vol1/1000/demo.pdf');
60
46
 
61
- // 打开文件管理器
62
- await app.openFileManager('/path/to/folder');
47
+ await app.openFileManager('/vol1/1000');
63
48
 
64
- // 设置退出页面提示
65
49
  await app.setExitPageTips({
66
- title: '确认退出?',
67
- content: '你有未保存的更改',
50
+ title: 'Leave this page?',
51
+ content: 'Unsaved changes may be lost.',
68
52
  });
69
53
 
70
- // 获取平台配置
71
- const config = await app.getPlatformConfig();
72
- console.log('主题:', config.theme);
73
- console.log('语言:', config.language);
74
- console.log('日期格式:', config.format.date);
75
- console.log('时间格式:', config.format.time);
76
-
77
- // 请求接口(仅 Web 平台)
78
- if (app.isWeb) {
79
- const response = await app.query({
80
- api: 'xxx.FileStation.List',
81
- method: 'list',
82
- version: 2,
83
- params: { folder_path: '/home' },
84
- });
85
- console.log('文件列表:', response);
86
- }
87
-
88
- // 选择文件
89
- const selectedFiles = await app.pickFile({
54
+ const files = await app.pickFile({
90
55
  multiple: true,
91
56
  accept: ['.pdf', '.doc', '.docx'],
92
- title: '选择文档文件',
57
+ title: 'Select files',
93
58
  });
94
- console.log('选中的文件:', selectedFiles);
95
- ```
96
-
97
- > **注意**:所有方法都会自动等待 SDK 初始化完成,你可以直接调用,无需手动等待。
98
-
99
- ### 浏览器插件宿主
100
-
101
- 在 Web 环境下,SDK 现在会优先探测浏览器插件宿主;如果当前页面存在扩展桥接链路,就会优先走 extension transport,否则再回退到原有的 iframe / postmate 宿主模式。
102
59
 
103
- 这意味着本地开发时,应用代码仍然可以保持:
104
-
105
- ```typescript
106
- const app = new TrimApp();
60
+ const userFileAuth = await app.authorizeUserFile('/vol1/1000/photos');
61
+ console.log(userFileAuth?.data);
107
62
  ```
108
63
 
109
- 无需显式切换宿主类型。
110
-
111
- ## API 文档
112
-
113
- ### TrimApp
64
+ ## Public APIs
114
65
 
115
- #### 构造函数
66
+ ### Constructor
116
67
 
117
- ```typescript
68
+ ```ts
118
69
  new TrimApp(options?: TrimAppOptions)
119
70
  ```
120
71
 
121
- 创建 TrimApp 实例。
72
+ Creates a Trim app SDK instance.
122
73
 
123
- **参数:**
124
-
125
- - `options` (可选) - 配置选项
126
- - `debug?: boolean` - 是否开启调试模式,默认 `false`
127
-
128
- **示例:**
129
-
130
- ```typescript
131
- // 不带配置
132
- const app = new TrimApp();
133
-
134
- // 开启调试模式
74
+ ```ts
135
75
  const app = new TrimApp({ debug: true });
136
76
  ```
137
77
 
138
- ---
139
-
140
- #### setTitle
141
-
142
- ```typescript
143
- async setTitle(title: string): Promise<void | null>
144
- ```
145
-
146
- 设置应用标题。
147
-
148
- **参数:**
149
-
150
- - `title: string` - 标题文本
151
-
152
- **返回值:**
153
-
154
- - 成功时返回 `Promise<void>`
155
- - 失败时返回 `Promise<null>`
156
-
157
- **示例:**
158
-
159
- ```typescript
160
- await app.setTitle('我的应用');
161
- ```
162
-
163
- ---
164
-
165
- #### openFile
166
-
167
- ```typescript
168
- async openFile(path: string): Promise<void | null>
169
- ```
170
-
171
- 通过应用打开指定文件。
172
-
173
- **参数:**
174
-
175
- - `path: string` - 文件路径
176
-
177
- **返回值:**
178
-
179
- - 成功时返回 `Promise<void>`
180
- - 失败时返回 `Promise<null>`
181
-
182
- **示例:**
183
-
184
- ```typescript
185
- await app.openFile('/path/to/document.pdf');
186
- ```
187
-
188
- ---
189
-
190
- #### openFileManager
78
+ ### ready
191
79
 
192
- ```typescript
193
- async openFileManager(path: string): Promise<void | null>
80
+ ```ts
81
+ ready(): Promise<void>
194
82
  ```
195
83
 
196
- 打开文件管理器并定位到指定路径。
197
-
198
- **参数:**
199
-
200
- - `path: string` - 文件夹路径
201
-
202
- **返回值:**
203
-
204
- - 成功时返回 `Promise<void>`
205
- - 失败时返回 `Promise<null>`
84
+ Waits until the SDK initialization is complete. Most apps do not need to call this explicitly because SDK methods wait for initialization automatically.
206
85
 
207
- **示例:**
86
+ ### setTitle
208
87
 
209
- ```typescript
210
- await app.openFileManager('/path/to/folder');
88
+ ```ts
89
+ setTitle(title: string): Promise<void | null>
211
90
  ```
212
91
 
213
- ---
214
-
215
- #### openApp
216
-
217
- ```typescript
218
- async openApp(anchor: string): Promise<void | null>
219
- ```
220
-
221
- 通过应用锚点打开指定应用(仅支持 Web 平台)。
222
-
223
- **参数:**
224
-
225
- - `anchor: string` - 应用锚点(唯一标识)
226
-
227
- **返回值:**
228
-
229
- - 成功时返回 `Promise<void>`
230
- - 失败时返回 `Promise<null>`
92
+ Sets the current app page title in the host.
231
93
 
232
- **注意:**
233
-
234
- - 此方法仅在 Web 平台(iframe)中可用
235
- - 在移动端调用会抛出错误:`openApp is not supported on mobile platform`
236
-
237
- **示例:**
238
-
239
- ```typescript
240
- await app.openApp('trim.notes');
94
+ ```ts
95
+ await app.setTitle('My App');
241
96
  ```
242
97
 
243
- ---
98
+ ### setExitPageTips
244
99
 
245
- #### setExitPageTips
246
-
247
- ```typescript
248
- async setExitPageTips(params?: { title?: string; content?: string }): Promise<void | null>
100
+ ```ts
101
+ setExitPageTips(params?: { title?: string; content?: string }): Promise<void | null>
249
102
  ```
250
103
 
251
- 设置退出页面时的提示信息。
252
-
253
- **参数:**
254
-
255
- - `params` (可选) - 提示参数
256
- - `title?: string` - 提示标题
257
- - `content?: string` - 提示内容
258
-
259
- **返回值:**
260
-
261
- - 成功时返回 `Promise<void>`
262
- - 失败时返回 `Promise<null>`
263
-
264
- **示例:**
104
+ Sets or clears the confirmation message shown when the user leaves the app page.
265
105
 
266
- ```typescript
267
- // 设置提示
106
+ ```ts
268
107
  await app.setExitPageTips({
269
- title: '确认退出?',
270
- content: '你有未保存的更改',
108
+ title: 'Leave this page?',
109
+ content: 'Unsaved changes may be lost.',
271
110
  });
272
111
 
273
- // 清除提示
274
112
  await app.setExitPageTips();
275
113
  ```
276
114
 
277
- ---
115
+ ### getPlatformConfig
278
116
 
279
- #### getPlatformConfig
280
-
281
- ```typescript
282
- async getPlatformConfig(): Promise<PlatformConfig>
283
- ```
284
-
285
- 获取平台配置信息,包括主题、语言、日期时间格式等。
286
-
287
- **返回值:**
288
-
289
- - `Promise<PlatformConfig>` - 平台配置对象
290
-
291
- **PlatformConfig 结构:**
292
-
293
- ```typescript
294
- interface PlatformConfig {
295
- theme: 'dark' | 'light'; // 主题模式
296
- language: string; // 语言代码,如 "zh-CN"、"en-US"
297
- appVersion?: string; // 应用版本号
298
- systemVersion: string; // 系统版本号
299
- format: {
300
- date?: string; // 日期格式,如 "YYYY-MM-DD"、"MM-DD-YYYY"
301
- time?: string; // 时间格式,"12h" 或 "24h"
302
- };
303
- }
117
+ ```ts
118
+ getPlatformConfig(): Promise<PlatformConfig>
304
119
  ```
305
120
 
306
- **示例:**
121
+ Returns host platform settings such as theme, language, app version, system version, date format, and time format.
307
122
 
308
- ```typescript
123
+ ```ts
309
124
  const config = await app.getPlatformConfig();
310
125
 
311
- // 根据主题调整 UI
312
126
  if (config.theme === 'dark') {
313
- document.body.classList.add('dark-mode');
127
+ document.documentElement.classList.add('dark');
314
128
  }
315
-
316
- // 根据语言设置国际化
317
- i18n.setLocale(config.language);
318
-
319
- // 根据日期格式格式化日期
320
- const dateFormatter = new Intl.DateTimeFormat(config.language, {
321
- dateStyle: 'short',
322
- });
323
129
  ```
324
130
 
325
- ---
326
-
327
- #### close
131
+ ### openFile
328
132
 
329
- ```typescript
330
- async close(): Promise<void>
133
+ ```ts
134
+ openFile(path: string): Promise<void | null>
331
135
  ```
332
136
 
333
- 关闭应用。
334
-
335
- **返回值:**
336
-
337
- - `Promise<void>`
137
+ Opens a file with the host system.
338
138
 
339
- **示例:**
340
-
341
- ```typescript
342
- app.close();
139
+ ```ts
140
+ await app.openFile('/vol1/1000/demo.pdf');
343
141
  ```
344
142
 
345
- ---
346
-
347
- #### ready
143
+ ### openFileManager
348
144
 
349
- ```typescript
350
- async ready(): Promise<void>
145
+ ```ts
146
+ openFileManager(path: string): Promise<void | null>
351
147
  ```
352
148
 
353
- 等待 SDK 初始化完成。虽然所有方法都会自动等待初始化,但在某些场景下你可能需要显式等待。
354
-
355
- **返回值:**
356
-
357
- - `Promise<void>` - 初始化完成时 resolve
358
-
359
- **示例:**
360
-
361
- ```typescript
362
- const app = new TrimApp();
363
-
364
- // 显式等待初始化完成
365
- await app.ready();
149
+ Opens the host file manager and navigates to the given path.
366
150
 
367
- // 现在可以安全地访问属性
368
- console.log('当前平台:', app.isWeb ? 'Web' : 'Mobile');
151
+ ```ts
152
+ await app.openFileManager('/vol1/1000');
369
153
  ```
370
154
 
371
- ---
155
+ ### openAppSetting
372
156
 
373
- #### getOptions
374
-
375
- ```typescript
376
- getOptions(): TrimAppOptions
157
+ ```ts
158
+ openAppSetting(): Promise<void | null>
377
159
  ```
378
160
 
379
- 获取当前配置选项。
380
-
381
- **返回值:**
382
-
383
- - `TrimAppOptions` - 当前配置对象
161
+ Opens the current app settings page in the host system.
384
162
 
385
- **示例:**
386
-
387
- ```typescript
388
- const options = app.getOptions();
389
- console.log('调试模式:', options.debug);
163
+ ```ts
164
+ await app.openAppSetting();
390
165
  ```
391
166
 
392
- ---
393
-
394
- #### setOptions
167
+ ### openURL
395
168
 
396
- ```typescript
397
- setOptions(options: Partial<TrimAppOptions>): void
169
+ ```ts
170
+ openURL(url: string, target?: string, features?: string): Promise<void | null>
398
171
  ```
399
172
 
400
- 更新配置选项。
401
-
402
- **参数:**
403
-
404
- - `options: Partial<TrimAppOptions>` - 要更新的配置项
405
-
406
- **示例:**
407
-
408
- ```typescript
409
- // 开启调试模式
410
- app.setOptions({ debug: true });
173
+ Opens a URL using the host-supported behavior. In a web host, this follows browser `window.open` behavior. In a mobile WebView host, it opens the URL in the system browser.
411
174
 
412
- // 关闭调试模式
413
- app.setOptions({ debug: false });
175
+ ```ts
176
+ await app.openURL('https://example.com', '_blank');
414
177
  ```
415
178
 
416
- ---
179
+ ### close
417
180
 
418
- #### query
419
-
420
- ```typescript
421
- async query<T>(params: any, config?: QueryConfig): Promise<ResponseData<T>>
181
+ ```ts
182
+ close(): Promise<void | null>
422
183
  ```
423
184
 
424
- 请求接口(仅支持 Web 平台)。用于调用 NAS 系统的 API。
425
-
426
- **参数:**
185
+ Closes the current app page.
427
186
 
428
- - `params: any` - 请求参数,通常包含 API 名称、方法、版本等信息
429
- - `config?: QueryConfig` - 可选配置
430
- - `timer?: boolean` - 是否是定时器请求
431
- - `observable?: boolean` - 是否返回 Observable
432
- - `skipPreflight?: boolean` - 是否跳过预检请求
433
- - `autoFailTips?: boolean` - 是否自动显示失败提示
187
+ ```ts
188
+ await app.close();
189
+ ```
434
190
 
435
- **返回值:**
191
+ ### showFileDetails
436
192
 
437
- - `Promise<ResponseData<T>>` - 响应数据
193
+ ```ts
194
+ showFileDetails(paths: string[], options?: FileDetailsOptions): Promise<void | null>
195
+ ```
438
196
 
439
- **ResponseData 结构:**
197
+ Shows the host file details panel for one or more paths.
440
198
 
441
- ```typescript
442
- interface ResponseData<T> {
443
- reqid: string; // 请求 ID
444
- result: ResponseStatus; // 响应状态:'succ' | 'fail' | 'cancel' | 'doing'
445
- taskId?: string; // 任务 ID(如果适用)
446
- type?: string; // 类型
447
- errmsg?: string; // 错误消息
448
- errno?: number; // 错误码
449
- extra?: string; // 额外信息
450
- // ... 其他 T 类型的字段
451
- }
199
+ ```ts
200
+ await app.showFileDetails(['/vol1/1000/photos'], { admin: true });
452
201
  ```
453
202
 
454
- **注意:**
203
+ ### authorizeUserFile
455
204
 
456
- - 此方法仅在 Web 平台(iframe)中可用
457
- - 在移动端调用会抛出错误
205
+ ```ts
206
+ authorizeUserFile(path: string): Promise<AppBridgeResponse<boolean> | undefined>
207
+ ```
458
208
 
459
- **示例:**
209
+ Requests authorization for a user file or folder path.
460
210
 
461
- ```typescript
462
- // 调用文件列表 API
463
- const response = await app.query({
464
- api: "x'x'x.FileStation.List",
465
- method: 'list',
466
- version: 2,
467
- params: {
468
- folder_path: '/home',
469
- additional: ['size', 'time', 'perm', 'type'],
470
- },
471
- });
211
+ ```ts
212
+ const result = await app.authorizeUserFile('/vol1/1000/photos');
472
213
 
473
- if (response.result === 'succ') {
474
- console.log('文件列表:', response);
475
- } else {
476
- console.error('请求失败:', response.errmsg);
214
+ if (result?.data) {
215
+ console.log('Authorized');
477
216
  }
478
-
479
- // 使用配置选项
480
- const response2 = await app.query(
481
- { api: 'xxxx', method: 'query', version: 1 },
482
- {
483
- timer: false,
484
- autoFailTips: true,
485
- },
486
- );
487
217
  ```
488
218
 
489
- ---
219
+ ### authorizeSharedFile
490
220
 
491
- #### pickFile
492
-
493
- ```typescript
494
- async pickFile(params: FilePickerParams): Promise<string[]>
221
+ ```ts
222
+ authorizeSharedFile(path: string): Promise<AppBridgeResponse<boolean> | undefined>
495
223
  ```
496
224
 
497
- 打开文件选择器,让用户选择文件或文件夹。
498
-
499
- **参数:**
500
-
501
- - `params: FilePickerParams` - 文件选择器参数
502
- - `multiple?: boolean` - 是否多选,默认 `false`
503
- - `directory?: boolean` - 是否选择文件夹,默认 `false`
504
- - `accept?: string[]` - 接受的文件类型,如 `['.pdf', '.doc', '.docx']`
505
- - `sidebarGroup?: string[]` - 侧边栏分组,可选值:`'myFiles'`、`'otherShare'`、`'external'`、`'remote'`、`'favorites'`、`'storage'`、`'torrent'`、`'team'`,默认 `['myFiles']`
506
- - `disabledPaths?: string[]` - 不可选的路径列表
507
- - `selectablePatterns?: [string, string][]` - 可选择的正则表达式(预留)
508
- - `expandFiles?: Array<{ title: string; extension: string }>` - 扩充搜索的文件类型
509
- - `creatable?: boolean` - 是否允许创建文件夹,默认 `true`
510
- - `title?: string` - 对话框标题,默认 `'选择文件'` 或 `'选择文件夹'`
511
- - `okText?: string` - 确认按钮文本,默认 `'确定'`
512
-
513
- **返回值:**
514
-
515
- - `Promise<string[]>` - 选中的文件路径数组
225
+ Requests authorization for a shared file or folder path.
516
226
 
517
- **示例:**
227
+ ```ts
228
+ const result = await app.authorizeSharedFile('/share/demo');
229
+ ```
518
230
 
519
- ```typescript
520
- // 选择单个文件
521
- const files = await app.pickFile({
522
- multiple: false,
523
- accept: ['.pdf', '.doc', '.docx'],
524
- title: '选择文档文件',
525
- });
526
- console.log('选中的文件:', files[0]);
231
+ ### pickFile
527
232
 
528
- // 选择多个文件
529
- const multipleFiles = await app.pickFile({
530
- multiple: true,
531
- accept: ['.jpg', '.png', '.gif'],
532
- title: '选择图片文件',
533
- });
534
- console.log('选中的文件:', multipleFiles);
233
+ ```ts
234
+ pickFile(params: FilePickerParams): Promise<string[] | undefined>
235
+ ```
535
236
 
536
- // 选择文件夹
537
- const folders = await app.pickFile({
538
- directory: true,
539
- title: '选择文件夹',
540
- });
541
- console.log('选中的文件夹:', folders[0]);
237
+ Opens the host file picker.
542
238
 
543
- // 限制侧边栏范围
239
+ ```ts
544
240
  const files = await app.pickFile({
545
241
  multiple: true,
546
- sidebarGroup: ['myFiles', 'favorites'],
547
- accept: ['.txt', '.md'],
548
- });
549
-
550
- // 禁用某些路径
551
- const files = await app.pickFile({
552
- disabledPaths: ['/vol1/1000/private', '/vol2/1000/temp'],
553
- accept: ['.pdf'],
242
+ accept: ['.pdf', 'image/*'],
243
+ title: 'Select files',
554
244
  });
555
245
  ```
556
246
 
557
- ---
247
+ Common `FilePickerParams` fields:
558
248
 
559
- #### $on
249
+ | Field | Type | Description |
250
+ | --------------- | ---------- | --------------------------------------------------- |
251
+ | `multiple` | `boolean` | Allows selecting multiple files. |
252
+ | `directory` | `boolean` | Allows selecting folders instead of files. |
253
+ | `accept` | `string[]` | Accepted file extensions or MIME types. |
254
+ | `title` | `string` | Picker title. |
255
+ | `okText` | `string` | Confirm button text. |
256
+ | `creatable` | `boolean` | Allows creating folders when supported by the host. |
257
+ | `disabledPaths` | `string[]` | Paths that cannot be selected. |
560
258
 
561
- ```typescript
562
- async $on(event: string, cb: (...args: any[]) => void): Promise<void>
563
- ```
564
-
565
- 监听系统事件(仅 Web 平台)。
566
-
567
- **参数:**
259
+ ### pickSharedFile
568
260
 
569
- - `event: string` - 事件名称
570
- - `cb: (...args: any[]) => void` - 回调函数
261
+ ```ts
262
+ pickSharedFile(
263
+ params?: Omit<FilePickerParams, 'directory'>,
264
+ ): Promise<AppBridgeResponse<string[]> | undefined>
265
+ ```
571
266
 
572
- **示例:**
267
+ Opens the shared file picker and authorizes the selected shared paths for the current app. The host controls the `directory` behavior, so callers should not pass it.
573
268
 
574
- ```typescript
575
- // 监听主题变更
576
- app.$on('os/theme', (theme) => {
577
- console.log('主题变更:', theme);
269
+ ```ts
270
+ const result = await app.pickSharedFile({
271
+ title: 'Select shared folder',
578
272
  });
579
273
 
580
- // 监听语言变更
581
- app.$on('os/language', (language) => {
582
- console.log('语言变更:', language);
583
- });
274
+ console.log(result?.data);
584
275
  ```
585
276
 
586
- ---
277
+ ## Host Events
587
278
 
588
- #### $off
279
+ ### $on
589
280
 
590
- ```typescript
591
- async $off(event: string, cb: (...args: any[]) => void): Promise<void>
281
+ ```ts
282
+ $on(event: string, callback: (...args: unknown[]) => void): Promise<void>
592
283
  ```
593
284
 
594
- 取消监听系统事件(仅 Web 平台)。
285
+ Subscribes to host events when the current runtime provides an event bus. The most common use cases are reacting to theme and language changes.
595
286
 
596
- **参数:**
597
-
598
- - `event: string` - 事件名称
599
- - `cb: (...args: any[]) => void` - 之前注册的回调函数引用
600
-
601
- **示例:**
602
-
603
- ```typescript
604
- const onThemeChange = (theme) => {
605
- console.log('主题变更:', theme);
606
- };
607
-
608
- app.$on('os/theme', onThemeChange);
287
+ ```ts
288
+ await app.$on('os/theme', (theme) => {
289
+ console.log('Theme changed:', theme);
290
+ });
609
291
 
610
- // 取消监听
611
- app.$off('os/theme', onThemeChange);
292
+ await app.$on('os/language', (language) => {
293
+ console.log('Language changed:', language);
294
+ });
612
295
  ```
613
296
 
614
- ---
615
-
616
- #### $once
297
+ ## App Auth Route Flow
617
298
 
618
- ```typescript
619
- async $once(event: string, cb: (...args: any[]) => void): Promise<void>
620
- ```
621
-
622
- 监听一次系统事件,触发后自动取消(仅 Web 平台)。
299
+ App Auth routes are useful when an app needs to start a file authorization or file picker flow through a route-based page and receive the result through a callback URL.
623
300
 
624
- **参数:**
301
+ ### openAppAuth
625
302
 
626
- - `event: string` - 事件名称
627
- - `cb: (...args: any[]) => void` - 回调函数
303
+ ```ts
304
+ openAppAuth(
305
+ request: AppAuthRequest,
306
+ options?: { target?: string; features?: string },
307
+ ): Promise<string>
308
+ ```
628
309
 
629
- **示例:**
310
+ Starts an App Auth route flow. The returned string is the URL that was opened.
630
311
 
631
- ```typescript
632
- // 只监听一次激活事件
633
- app.$once('os/app.activated', () => {
634
- console.log('应用被激活');
312
+ ```ts
313
+ await app.openAppAuth({
314
+ routeMethod: 'pick-file',
315
+ method: 'pickFile',
316
+ appName: 'trim.demo',
317
+ directory: true,
318
+ redirectUri: '/callback',
319
+ state: 'pick-file-demo',
635
320
  });
636
321
  ```
637
322
 
638
- ---
323
+ Supported `routeMethod` values:
639
324
 
640
- #### 系统事件列表
325
+ | routeMethod | method |
326
+ | ----------------------- | --------------------- |
327
+ | `pick-file` | `pickFile` |
328
+ | `pick-shared-file` | `pickSharedFile` |
329
+ | `authorize-user-file` | `authorizeUserFile` |
330
+ | `authorize-shared-file` | `authorizeSharedFile` |
641
331
 
642
- 以下是基座平台提供的系统事件:
332
+ ### parseAppAuthCallback
643
333
 
644
- | 事件名 | 说明 |
645
- | ------------------------- | -------------------------- |
646
- | `os/theme` | 主题色变更(dark / light) |
647
- | `os/language` | 系统语言变更 |
648
- | `os/format.date` | 日期格式变更 |
649
- | `os/app.appMeta` | 应用元数据变更 |
650
- | `os/app.visibilitychange` | 应用最小化状态变更 |
651
- | `os/app.activated` | 应用激活态变更 |
652
- | `os/net.set` | 网络设置变更 |
653
- | `os/net.ovs` | 网络 OVS 开关变更 |
654
- | `os/storage.change` | 存储变更 |
334
+ ```ts
335
+ parseAppAuthCallback(input?: string | URL | URLSearchParams): AppAuthResult
336
+ ```
655
337
 
656
- ---
338
+ Parses the callback query parameters returned by an App Auth route flow.
657
339
 
658
- #### callAppMethod
340
+ ```ts
341
+ const result = app.parseAppAuthCallback();
659
342
 
660
- ```typescript
661
- async callAppMethod<T>(fn: string, params?: string): Promise<T | null>
343
+ console.log(result.status);
344
+ console.log(result.method);
345
+ console.log(result.state);
662
346
  ```
663
347
 
664
- 调用移动端 App 的方法(仅移动端可用)。
665
-
666
- **参数:**
667
-
668
- - `fn: string` - 要调用的方法名
669
- - `params?: string` - 方法参数(JSON 字符串)
348
+ ### buildAppAuthUrl
670
349
 
671
- **返回值:**
350
+ ```ts
351
+ buildAppAuthUrl(request: AppAuthRequest): Promise<string>
352
+ ```
672
353
 
673
- - `Promise<T | null>` - 方法返回结果,失败时返回 `null`
354
+ Builds an App Auth route URL without opening it. Most apps should use `openAppAuth()` directly. Use this helper only when you need to control navigation yourself.
674
355
 
675
- **注意:**
356
+ ```ts
357
+ const url = await app.buildAppAuthUrl({
358
+ routeMethod: 'authorize-user-file',
359
+ method: 'authorizeUserFile',
360
+ appName: 'trim.demo',
361
+ path: '/vol1/1000/photos',
362
+ redirectUri: '/callback',
363
+ });
364
+ ```
676
365
 
677
- - 此方法仅在移动端(WebView)中可用
678
- - 在 Web 平台调用会返回 `null`
679
- - 建议使用 SDK 提供的标准方法(如 `setTitle`、`openFile` 等),而不是直接调用此方法
366
+ ## Instance Properties
680
367
 
681
- **示例:**
368
+ ### isWeb
682
369
 
683
- ```typescript
684
- // 调用自定义方法
685
- const result = await app.callAppMethod<{ success: boolean }>(
686
- 'customMethod',
687
- JSON.stringify({ key: 'value' }),
688
- );
370
+ ```ts
371
+ isWeb: boolean;
689
372
  ```
690
373
 
691
- ---
692
-
693
- ### 实例属性
374
+ Indicates whether the current runtime is a web host.
694
375
 
695
- #### isWeb
376
+ ### isStandaloneWeb
696
377
 
697
- ```typescript
698
- readonly isWeb: boolean
378
+ ```ts
379
+ isStandaloneWeb: boolean;
699
380
  ```
700
381
 
701
- 判断当前运行环境是否为 Web 平台。
382
+ Indicates whether the current runtime is a standalone browser page without an iframe host.
702
383
 
703
- - `true` - 运行在 Web iframe 中
704
- - `false` - 运行在移动端 WebView 中
384
+ ## Types
705
385
 
706
- **示例:**
707
-
708
- ```typescript
709
- const app = new TrimApp();
710
- await app.ready();
711
-
712
- if (app.isWeb) {
713
- console.log('运行在 Web 平台');
714
- // Web 平台特有逻辑
715
- } else {
716
- console.log('运行在移动端');
717
- // 移动端特有逻辑
718
- }
386
+ ```ts
387
+ import type {
388
+ AppAuthAuthorizeRequest,
389
+ AppAuthBaseRequest,
390
+ AppAuthCallbackError,
391
+ AppAuthCallbackStatus,
392
+ AppAuthMethod,
393
+ AppAuthPickRequest,
394
+ AppAuthRequest,
395
+ AppAuthResult,
396
+ AppAuthRouteMethod,
397
+ AppBridgeResponse,
398
+ AuthorizeFileResult,
399
+ FileDetailsOptions,
400
+ FilePickerParams,
401
+ PlatformConfig,
402
+ TrimAppOptions,
403
+ } from '@trimjs/web-app';
719
404
  ```
720
405
 
721
- ## 配置选项
722
-
723
406
  ### TrimAppOptions
724
407
 
725
- ```typescript
408
+ ```ts
726
409
  interface TrimAppOptions {
727
- /** 是否开启调试模式,开启后会输出日志 */
728
410
  debug?: boolean;
729
411
  }
730
412
  ```
731
413
 
732
- **选项说明:**
733
-
734
- - `debug` (可选) - 是否开启调试模式
735
- - 类型:`boolean`
736
- - 默认值:`false`
737
- - 说明:开启后会在控制台输出 SDK 运行日志,方便调试
738
-
739
- **示例:**
740
-
741
- ```typescript
742
- // 开启调试模式
743
- const app = new TrimApp({ debug: true });
744
-
745
- // 运行时切换调试模式
746
- app.setOptions({ debug: false });
747
- ```
748
-
749
- ---
750
-
751
414
  ### PlatformConfig
752
415
 
753
- ```typescript
416
+ ```ts
754
417
  interface PlatformConfig {
755
- theme: 'dark' | 'light'; // 主题模式
756
- language: string; // 语言代码,如 "zh-CN"、"en-US"
757
- appVersion?: string; // 应用版本号
758
- systemVersion: string; // 系统版本号
418
+ theme: 'dark' | 'light';
419
+ language: string;
420
+ appVersion?: string;
421
+ systemVersion: string;
759
422
  format: {
760
- date?: string; // 日期格式,如 "YYYY-MM-DD"、"MM-DD-YYYY"、"DD-MM-YYYY"、"YYYY/MM/DD"、"MM/DD/YYYY"、"DD/MM/YYYY"
761
- time?: string; // 时间格式,"12h" 或 "24h"
423
+ date?: string;
424
+ time?: string;
762
425
  };
763
426
  }
764
427
  ```
765
428
 
766
- **字段说明:**
767
-
768
- - `theme` - 当前主题模式
769
- - `"dark"` - 深色模式
770
- - `"light"` - 浅色模式
771
- - `language` - 语言代码,遵循 BCP 47 标准
772
- - 常见值:`"zh-CN"`(简体中文)、`"en-US"`(美式英语)等
773
- - `appVersion` (可选) - 应用版本号
774
- - `systemVersion` - 系统版本号
775
- - `format.date` (可选) - 日期格式
776
- - 支持格式:`"YYYY-MM-DD"`、`"MM-DD-YYYY"`、`"DD-MM-YYYY"`、`"YYYY/MM/DD"`、`"MM/DD/YYYY"`、`"DD/MM/YYYY"`
777
- - `format.time` (可选) - 时间格式
778
- - `"12h"` - 12 小时制
779
- - `"24h"` - 24 小时制
780
-
781
- ## 平台差异
782
-
783
- ### Web 平台(iframe)
784
-
785
- 在 Web 平台中,SDK 通过 `postmate` 与父窗口(OS)进行通信。
786
-
787
- **支持的方法:**
788
-
789
- - ✅ `setTitle` - 设置标题
790
- - ✅ `setExitPageTips` - 设置退出提示
791
- - ✅ `openFile` - 打开文件
792
- - ✅ `openFileManager` - 打开文件管理器
793
- - ✅ `getPlatformConfig` - 获取平台配置
794
- - ✅ `close` - 关闭应用
795
- - ✅ `query` - 请求接口
796
- - ✅ `pickFile` - 选择文件
797
-
798
- ### 移动端平台(WebView)
799
-
800
- 在移动端平台中,SDK 通过 `flutter_inappwebview` 与原生 App 进行通信。
801
-
802
- **支持的方法:**
803
-
804
- - ✅ `setTitle` - 设置标题
805
- - ✅ `setExitPageTips` - 设置退出提示
806
- - ✅ `openFile` - 打开文件
807
- - ✅ `openFileManager` - 打开文件管理器
808
- - ✅ `getPlatformConfig` - 获取平台配置
809
- - ✅ `close` - 关闭页面
810
- - ❌ `query` - 不支持(会抛出错误)
811
- - ✅ `pickFile` - 选择文件
812
- - ✅ `callAppMethod` - 调用自定义 App 方法
813
-
814
- ## 类型导出
815
-
816
- SDK 导出了以下类型,方便你在 TypeScript 项目中使用:
817
-
818
- ```typescript
819
- import type { TrimAppOptions, PlatformConfig } from '@trimjs/web-app';
820
- ```
821
-
822
- 如果需要使用其他类型(如 `FilePickerParams`、`QueryConfig`、`ResponseData`),可以从 `@fn/micro-app-postmate` 导入:
823
-
824
- ```typescript
825
- import type {
826
- FilePickerParams,
827
- QueryConfig,
828
- ResponseData,
829
- } from '@fn/micro-app-postmate/src/child/type';
830
- import type { ResponseData as ResponseDataType } from '@fn/micro-app-postmate/src/child/os-type';
831
- ```
832
-
833
- ## 使用场景
834
-
835
- ### 场景 1:根据平台配置调整 UI
836
-
837
- ```typescript
838
- const app = new TrimApp({ debug: true });
839
- const config = await app.getPlatformConfig();
840
-
841
- // 根据主题切换 UI
842
- if (config.theme === 'dark') {
843
- document.body.classList.add('dark-mode');
844
- }
845
-
846
- // 根据语言设置国际化
847
- i18n.setLocale(config.language);
848
-
849
- // 根据日期格式显示日期
850
- const dateFormat = config.format.date || 'YYYY-MM-DD';
851
- const formattedDate = dayjs().format(dateFormat);
852
- ```
429
+ ### AppBridgeResponse
853
430
 
854
- ### 场景 2:文件上传功能
855
-
856
- ```typescript
857
- // 让用户选择文件
858
- const selectedFiles = await app.pickFile({
859
- multiple: true,
860
- accept: ['.jpg', '.png', '.pdf'],
861
- title: '选择要上传的文件',
862
- });
863
-
864
- if (selectedFiles && selectedFiles.length > 0) {
865
- // 处理选中的文件
866
- for (const filePath of selectedFiles) {
867
- console.log('上传文件:', filePath);
868
- // 执行上传逻辑...
869
- }
870
- }
871
- ```
872
-
873
- ### 场景 3:调用 NAS API
874
-
875
- ```typescript
876
- // 仅在 Web 平台调用 API
877
- if (app.isWeb) {
878
- try {
879
- const response = await app.query({
880
- api: 'xxx.FileStation.List',
881
- method: 'list',
882
- version: 2,
883
- params: {
884
- folder_path: '/home',
885
- additional: ['size', 'time', 'perm'],
886
- },
887
- });
888
-
889
- if (response.result === 'succ') {
890
- console.log('文件列表获取成功');
891
- }
892
- } catch (error) {
893
- console.error('API 调用失败:', error);
894
- }
895
- }
896
- ```
897
-
898
- ### 场景 4:页面退出确认
899
-
900
- ```typescript
901
- // 在用户有未保存数据时设置退出提示
902
- app.setExitPageTips({
903
- title: '确认离开?',
904
- content: '您有未保存的更改,确定要离开吗?',
905
- });
906
-
907
- // 保存数据后清除提示
908
- async function saveData() {
909
- // 保存逻辑...
910
- await app.setExitPageTips(); // 清除提示
911
- }
912
- ```
913
-
914
- ## 注意事项
915
-
916
- 1. **初始化时机**:SDK 会在创建实例时自动初始化,所有方法都会自动等待初始化完成,无需手动调用 `ready()`。
917
-
918
- 2. **平台检测**:SDK 会自动检测运行环境(Web 或移动端),通过 `isWeb` 属性可以判断当前平台。
919
-
920
- 3. **错误处理**:某些方法在特定平台可能不可用(如 `query` 在移动端),调用前建议检查 `isWeb` 属性。
921
-
922
- 4. **调试模式**:开启 `debug` 选项后,SDK 会在控制台输出详细的运行日志,方便开发和调试。
923
-
924
- 5. **异步方法**:所有与平台交互的方法都是异步的,记得使用 `await` 或 `.then()` 处理。
925
-
926
- 6. **文件选择器**:`pickFile` 方法会打开系统文件选择器,用户可能取消选择,返回的数组可能为空,记得处理这种情况。
927
-
928
- 7. **API 请求**:`query` 方法返回的 `ResponseData` 包含 `result` 字段,需要检查状态是否为 `'succ'` 来判断请求是否成功。
929
-
930
- ## 常见问题
931
-
932
- ### Q: 如何判断当前运行在哪个平台?
933
-
934
- A: 使用 `isWeb` 属性:
935
-
936
- ```typescript
937
- const app = new TrimApp();
938
- await app.ready();
939
-
940
- if (app.isWeb) {
941
- console.log('运行在 Web 平台');
942
- } else {
943
- console.log('运行在移动端');
944
- }
945
- ```
946
-
947
- ### Q: 为什么调用某些方法会报错?
948
-
949
- A: 某些方法只在特定平台可用:
950
-
951
- - `query()` 仅在 Web 平台可用
952
- - 在移动端调用这些方法会抛出错误
953
-
954
- 建议在调用前检查平台:
955
-
956
- ```typescript
957
- if (app.isWeb) {
958
- await app.query();
959
- } else {
960
- console.log('当前平台不支持 query 方法');
961
- }
962
- ```
963
-
964
- ### Q: 如何等待 SDK 初始化完成?
965
-
966
- A: 虽然所有方法都会自动等待初始化,但如果你需要显式等待:
967
-
968
- ```typescript
969
- const app = new TrimApp();
970
- await app.ready();
971
- // 现在可以安全地使用所有功能
972
- ```
973
-
974
- ### Q: `pickFile` 返回空数组是什么意思?
975
-
976
- A: 如果用户取消了文件选择,`pickFile` 会返回空数组。记得处理这种情况:
977
-
978
- ```typescript
979
- const files = await app.pickFile({ multiple: true });
980
- if (files.length === 0) {
981
- console.log('用户取消了选择');
982
- return;
983
- }
984
- // 处理选中的文件...
985
- ```
986
-
987
- ### Q: 如何调试 SDK 的问题?
988
-
989
- A: 开启 `debug` 模式,SDK 会在控制台输出详细日志:
990
-
991
- ```typescript
992
- const app = new TrimApp({ debug: true });
993
- // 现在所有操作都会输出日志
994
- ```
995
-
996
- ### Q: `query` 方法返回的 `result` 字段有哪些值?
997
-
998
- A: `result` 字段可能的值:
999
-
1000
- - `'succ'` - 成功
1001
- - `'fail'` - 失败
1002
- - `'cancel'` - 用户取消
1003
- - `'doing'` - 任务进行中
1004
-
1005
- ```typescript
1006
- const response = await app.query({
1007
- /* ... */
1008
- });
1009
- if (response.result === 'succ') {
1010
- // 处理成功情况
1011
- } else if (response.result === 'fail') {
1012
- // 处理失败情况
1013
- console.error('错误:', response.errmsg);
1014
- }
431
+ ```ts
432
+ type AppBridgeResponse<T> = {
433
+ code: number;
434
+ msg: string;
435
+ data: T;
436
+ };
1015
437
  ```
1016
438
 
1017
- ### Q: 可以在移动端使用 `query` 方法吗?
1018
-
1019
- A: 不可以。`query` 方法仅在 Web 平台可用。在移动端调用会抛出错误。如果需要调用 API,建议在 Web 平台使用,或者通过 `callAppMethod` 调用移动端原生方法。
1020
-
1021
- ## 开发
1022
-
1023
- ```bash
1024
- # 安装依赖
1025
- pnpm install
1026
-
1027
- # 开发模式
1028
- pnpm dev
439
+ ## Platform Notes
1029
440
 
1030
- # 构建
1031
- pnpm build
441
+ The SDK normalizes supported host APIs across web iframe hosts and mobile WebView hosts. Some APIs may require a recent host version. When an API is unavailable, the SDK throws an error or returns `undefined` depending on the method behavior.
1032
442
 
1033
- # 类型检查
1034
- pnpm typecheck
1035
-
1036
- # 代码检查
1037
- pnpm lint
1038
- ```
443
+ For route-based App Auth flows, use `openAppAuth()` to start the flow and `parseAppAuthCallback()` on the callback page to read the result.
1039
444
 
1040
- ## 许可证
445
+ ## License
1041
446
 
1042
447
  MIT