lakutata 3.1.4 → 3.1.6
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 +11 -11
- package/README.zh-CN.md +5 -5
- package/dist/cjs/exports/NwjsAdapter.d.ts +1 -0
- package/dist/cjs/exports/NwjsAdapter.js +20 -0
- package/dist/cjs/exports/ReactNativeAdapter.d.ts +1 -0
- package/dist/cjs/exports/ReactNativeAdapter.js +20 -0
- package/dist/esm/exports/NwjsAdapter.js +1 -0
- package/dist/esm/exports/ReactNativeAdapter.js +1 -0
- package/dist/types/exports/NwjsAdapter.d.ts +1 -0
- package/dist/types/exports/ReactNativeAdapter.d.ts +1 -0
- package/doc/en/Application.md +6 -1
- package/doc/en/Barcode.md +386 -0
- package/doc/en/Cache.md +2 -1
- package/doc/en/Command.md +20 -4
- package/doc/en/ContainerdIntegration.md +1 -1
- package/doc/en/Database.md +4 -0
- package/doc/en/DatabaseDrivers.md +75 -4
- package/doc/en/Entrypoint.md +4 -2
- package/doc/en/Exceptions.md +1 -1
- package/doc/en/FFI.md +1 -1
- package/doc/en/GRPC.md +1 -1
- package/doc/en/GettingStarted.md +16 -2
- package/doc/en/HTTP.md +1 -0
- package/doc/en/I18n.md +1 -1
- package/doc/en/Installers.md +34 -6
- package/doc/en/Math.md +1 -1
- package/doc/en/Migrations.md +2 -2
- package/doc/en/NativeAddons.md +12 -2
- package/doc/en/Overview.md +14 -11
- package/doc/en/Packaging.md +8 -1
- package/doc/en/ProjectStructure.md +18 -3
- package/doc/en/ServiceCalls.md +85 -5
- package/doc/en/UpgradingFrom1.md +2 -2
- package/doc/en/UpgradingFrom2.md +4 -4
- package/doc/en/WebRTC.md +4 -4
- package/doc/en/examples/MobileApp.md +730 -0
- package/doc/en/examples/README.md +2 -0
- package/doc/en/examples/TrayApp.md +1061 -0
- package/doc/zh/Application.md +3 -1
- package/doc/zh/Barcode.md +313 -0
- package/doc/zh/Cache.md +1 -1
- package/doc/zh/Command.md +12 -3
- package/doc/zh/ContainerdIntegration.md +1 -1
- package/doc/zh/Database.md +2 -0
- package/doc/zh/DatabaseDrivers.md +52 -2
- package/doc/zh/Entrypoint.md +3 -1
- package/doc/zh/Exceptions.md +1 -1
- package/doc/zh/FFI.md +1 -1
- package/doc/zh/GRPC.md +1 -1
- package/doc/zh/GettingStarted.md +12 -2
- package/doc/zh/HTTP.md +1 -0
- package/doc/zh/I18n.md +1 -1
- package/doc/zh/Installers.md +16 -5
- package/doc/zh/Math.md +1 -1
- package/doc/zh/Migrations.md +1 -1
- package/doc/zh/NativeAddons.md +4 -2
- package/doc/zh/Overview.md +5 -4
- package/doc/zh/Packaging.md +6 -1
- package/doc/zh/ProjectStructure.md +5 -2
- package/doc/zh/ServiceCalls.md +65 -2
- package/doc/zh/UpgradingFrom1.md +2 -2
- package/doc/zh/UpgradingFrom2.md +3 -3
- package/doc/zh/WebRTC.md +1 -1
- package/doc/zh/examples/MobileApp.md +671 -0
- package/doc/zh/examples/README.md +2 -0
- package/doc/zh/examples/TrayApp.md +980 -0
- package/package.json +36 -16
|
@@ -0,0 +1,980 @@
|
|
|
1
|
+
# 用 NW.js 开发托盘应用
|
|
2
|
+
|
|
3
|
+
这个示例构建一个常驻系统托盘的剪贴板历史:它记下在任何程序里复制的文本,应用窗口可以列出和搜索这些文本、把其中一条再次复制到剪贴板,还可以置顶要保留的条目。它从 `nwjs-react` 模板开始,展示用 lakutata 开发的 NW.js 应用由哪几部分组成:一是后台脚本,它是一个 lakutata 应用,只要应用在运行它就在运行,不管有没有窗口(这里它负责读取剪贴板,并维护托盘图标和托盘菜单);二是窗口,窗口中的 React 用户界面调用应用的动作,并接收应用推送的事件;三是应用的测试,测试不需要 NW.js 就能运行。
|
|
4
|
+
|
|
5
|
+
| 消息 | 作用 |
|
|
6
|
+
|---|---|
|
|
7
|
+
| `{cmd: 'clips.list'}` | 列出剪贴项,置顶的在前,然后是最新的 |
|
|
8
|
+
| `{cmd: 'clips.list', query: 'git'}` | 只列出文本包含 `git` 的剪贴项,不区分大小写 |
|
|
9
|
+
| `{cmd: 'clips.copy', id: '…'}` | 把一条剪贴项再次复制到剪贴板,它会移到最前 |
|
|
10
|
+
| `{cmd: 'clips.pin', id: '…', pinned: true}` | 置顶一条剪贴项:之后不管复制多少文本,它都会保留 |
|
|
11
|
+
| `{cmd: 'clips.delete', id: '…'}` | 删除一条剪贴项 |
|
|
12
|
+
| `{cmd: 'clips.clear'}` | 删除置顶以外的所有剪贴项 |
|
|
13
|
+
|
|
14
|
+
历史有变化时,应用会向窗口推送 `clips.changed` 事件。
|
|
15
|
+
|
|
16
|
+
## 1. 创建项目
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
npx @lakutata/cli create --name clips --template nwjs-react --yes
|
|
20
|
+
cd clips
|
|
21
|
+
rm packages/app/src/controllers/ExampleController.ts packages/app/src/dtos/GreetDTO.ts
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
项目是一个工作区(见 [ProjectStructure](../ProjectStructure.md)):`packages/app` 是 NW.js 的后台脚本,也是一个 lakutata 应用;`packages/ui` 是用户界面,即由 Vite 构建的 React 页面;`packages/resources` 存放图标。应用不需要安装其他包:剪贴板和托盘由 NW.js 提供,历史是用 `node:fs` 写入的 JSON 文件。这里删掉了模板中的示例控制器。
|
|
25
|
+
|
|
26
|
+
## 2. 输入
|
|
27
|
+
|
|
28
|
+
**`packages/app/src/dtos/ClipDTO.ts`**
|
|
29
|
+
|
|
30
|
+
```typescript
|
|
31
|
+
import {DTO} from 'lakutata'
|
|
32
|
+
import {Expect} from 'lakutata/decorator/dto'
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* 文本包含查询词的剪贴项,没有查询词时为全部
|
|
36
|
+
*/
|
|
37
|
+
export class SearchClipsDTO extends DTO {
|
|
38
|
+
@Expect(DTO.String().trim().max(200).optional())
|
|
39
|
+
public query?: string
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* 按 id 指定的一条历史剪贴项
|
|
44
|
+
*/
|
|
45
|
+
export class ClipIdDTO extends DTO {
|
|
46
|
+
@Expect(DTO.String().uuid().required())
|
|
47
|
+
public id: string
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* 要置顶或取消置顶的剪贴项
|
|
52
|
+
*/
|
|
53
|
+
export class PinClipDTO extends ClipIdDTO {
|
|
54
|
+
@Expect(DTO.Boolean().required())
|
|
55
|
+
public pinned: boolean
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
每个动作运行前都先用 DTO 校验输入(见 [DTOValidation](../DTOValidation.md))。剪贴项用 id 指定,id 是历史生成的 UUID:`.uuid()` 拒绝其他字符串,报错 `"id" must be a valid GUID`。消息是 JSON,值会保留原来的类型:`pinned` 必须是布尔值。
|
|
60
|
+
|
|
61
|
+
## 3. 异常
|
|
62
|
+
|
|
63
|
+
**`packages/app/src/exceptions/ClipExceptions.ts`**
|
|
64
|
+
|
|
65
|
+
```typescript
|
|
66
|
+
import {Exception} from 'lakutata'
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* 剪贴项不在历史中(或已不在)
|
|
70
|
+
*/
|
|
71
|
+
export class ClipNotFoundException extends Exception {
|
|
72
|
+
public errno: string = 'E_CLIP_NOT_FOUND'
|
|
73
|
+
}
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
异常带有 `errno`,用户界面根据这个代码判断错误(见 [Exceptions](../Exceptions.md))。窗口收到的错误和抛出时一样,带有全部属性(见 [ServiceCalls](../ServiceCalls.md) 第 3 节):`error.errno` 是 `'E_CLIP_NOT_FOUND'`。服务传输方式无论错误的状态码是什么,都用统一的响应结构返回,所以这个异常不需要 `statusCode`。
|
|
77
|
+
|
|
78
|
+
## 4. 历史
|
|
79
|
+
|
|
80
|
+
**`packages/app/src/components/History.ts`**
|
|
81
|
+
|
|
82
|
+
```typescript
|
|
83
|
+
import {Component, DTO} from 'lakutata'
|
|
84
|
+
import {type Entrypoint} from 'lakutata/com/entrypoint'
|
|
85
|
+
import {Configurable, Inject} from 'lakutata/decorator/di'
|
|
86
|
+
import {randomUUID} from 'node:crypto'
|
|
87
|
+
import {mkdir, readFile, rename, writeFile} from 'node:fs/promises'
|
|
88
|
+
import path from 'node:path'
|
|
89
|
+
import {ClipNotFoundException} from '../exceptions/ClipExceptions.js'
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* 复制到剪贴板的一段文本
|
|
93
|
+
*/
|
|
94
|
+
export type Clip = { id: string, text: string, copiedAt: string, pinned: boolean }
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* 读写剪贴板的文本:在应用中是 NW.js 的剪贴板,在测试中是一个替身
|
|
98
|
+
*/
|
|
99
|
+
export type ClipboardAccess = { read(): string, write(text: string): void }
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* 剪贴板历史:复制过的文本,最新的在前,保存在文件中。NW.js 不会通知剪贴板的变化,所以组件定时读取剪贴板。历史的变化会推送给
|
|
103
|
+
* 窗口(clips.changed),并通知其他组件(changed)
|
|
104
|
+
*/
|
|
105
|
+
export class History extends Component {
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* 向窗口推送事件
|
|
109
|
+
*/
|
|
110
|
+
@Inject('entrypoint')
|
|
111
|
+
protected readonly entrypoint: Entrypoint
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* 读写的剪贴板
|
|
115
|
+
*/
|
|
116
|
+
@Configurable(DTO.Object({read: DTO.Function().required(), write: DTO.Function().required()}).required())
|
|
117
|
+
protected readonly clipboard: ClipboardAccess
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* 历史文件
|
|
121
|
+
*/
|
|
122
|
+
@Configurable(DTO.String().required())
|
|
123
|
+
protected readonly file: string
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* 读取剪贴板的间隔,单位为毫秒
|
|
127
|
+
*/
|
|
128
|
+
@Configurable(DTO.Number().integer().min(10).optional().default(500))
|
|
129
|
+
protected readonly interval: number
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* 保留的剪贴项数量,不算置顶的
|
|
133
|
+
*/
|
|
134
|
+
@Configurable(DTO.Number().integer().min(1).optional().default(50))
|
|
135
|
+
protected readonly limit: number
|
|
136
|
+
|
|
137
|
+
#clips: Clip[] = []
|
|
138
|
+
|
|
139
|
+
//最后一次从剪贴板读到的文本:它发生变化就是一次复制
|
|
140
|
+
#last: string = ''
|
|
141
|
+
|
|
142
|
+
#timer: NodeJS.Timeout | undefined
|
|
143
|
+
|
|
144
|
+
//文件的写入,一个接一个进行
|
|
145
|
+
#saved: Promise<void> = Promise.resolve()
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* 从文件读取历史,然后定时读取剪贴板:应用启动时剪贴板里已有的内容不算复制
|
|
149
|
+
*/
|
|
150
|
+
protected async init(): Promise<void> {
|
|
151
|
+
this.#clips = await readFile(this.file, 'utf8').then((text: string): Clip[] => JSON.parse(text), (): Clip[] => [])
|
|
152
|
+
this.#last = this.clipboard.read()
|
|
153
|
+
this.#timer = setInterval((): void => this.read(), this.interval)
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
protected async destroy(): Promise<void> {
|
|
157
|
+
clearInterval(this.#timer)
|
|
158
|
+
await this.#saved
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* 读取剪贴板:与上次读到的不同的文本就是一次复制
|
|
163
|
+
*/
|
|
164
|
+
protected read(): void {
|
|
165
|
+
const text: string = this.clipboard.read()
|
|
166
|
+
if (!text.trim() || text === this.#last) return
|
|
167
|
+
this.#last = text
|
|
168
|
+
this.add(text)
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* 把文本放到历史的最前面:再次复制的文本会移到最前,超出上限的最旧的未置顶剪贴项会被丢弃
|
|
173
|
+
* @param text
|
|
174
|
+
*/
|
|
175
|
+
protected add(text: string): Clip {
|
|
176
|
+
const clip: Clip = this.#clips.find((item: Clip): boolean => item.text === text) ?? {id: randomUUID(), text: text, copiedAt: '', pinned: false}
|
|
177
|
+
clip.copiedAt = new Date().toISOString()
|
|
178
|
+
let kept: number = 0
|
|
179
|
+
this.#clips = [clip, ...this.#clips.filter((item: Clip): boolean => item !== clip)].filter((item: Clip): boolean => item.pinned || ++kept <= this.limit)
|
|
180
|
+
this.changed()
|
|
181
|
+
return clip
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* 保存历史并通知它已变化:先写到旁边的文件,再重命名过去,这样文件永远不会只写了一半
|
|
186
|
+
*/
|
|
187
|
+
protected changed(): void {
|
|
188
|
+
const json: string = JSON.stringify(this.#clips)
|
|
189
|
+
this.#saved = this.#saved.then(async (): Promise<void> => {
|
|
190
|
+
await mkdir(path.dirname(this.file), {recursive: true})
|
|
191
|
+
await writeFile(`${this.file}.tmp`, json)
|
|
192
|
+
await rename(`${this.file}.tmp`, this.file)
|
|
193
|
+
})
|
|
194
|
+
this.entrypoint.broadcast('clips.changed')
|
|
195
|
+
this.emit('changed')
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* 剪贴项:置顶的在前,然后是最新的;有查询词时只返回文本包含它的(不区分大小写)
|
|
200
|
+
* @param query
|
|
201
|
+
*/
|
|
202
|
+
public list(query?: string): Clip[] {
|
|
203
|
+
const lowered: string | undefined = query?.toLowerCase()
|
|
204
|
+
return this.#clips
|
|
205
|
+
.filter((clip: Clip): boolean => !lowered || clip.text.toLowerCase().includes(lowered))
|
|
206
|
+
.sort((a: Clip, b: Clip): number => Number(b.pinned) - Number(a.pinned) || b.copiedAt.localeCompare(a.copiedAt))
|
|
207
|
+
.map((clip: Clip): Clip => ({...clip}))
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* 历史中的一条剪贴项
|
|
212
|
+
* @param id
|
|
213
|
+
*/
|
|
214
|
+
protected find(id: string): Clip {
|
|
215
|
+
const clip: Clip | undefined = this.#clips.find((item: Clip): boolean => item.id === id)
|
|
216
|
+
if (!clip) throw new ClipNotFoundException('The clip {0} is not in the history', id)
|
|
217
|
+
return clip
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* 把剪贴项再次复制到剪贴板:它会移到最前
|
|
222
|
+
* @param id
|
|
223
|
+
*/
|
|
224
|
+
public copy(id: string): Clip {
|
|
225
|
+
const {text} = this.find(id)
|
|
226
|
+
this.#last = text
|
|
227
|
+
this.clipboard.write(text)
|
|
228
|
+
return {...this.add(text)}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* 置顶或取消置顶剪贴项:置顶的剪贴项会一直保留,不管之后复制了什么
|
|
233
|
+
* @param id
|
|
234
|
+
* @param pinned
|
|
235
|
+
*/
|
|
236
|
+
public pin(id: string, pinned: boolean): Clip {
|
|
237
|
+
const clip: Clip = this.find(id)
|
|
238
|
+
clip.pinned = pinned
|
|
239
|
+
this.changed()
|
|
240
|
+
return {...clip}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* 删除一条剪贴项
|
|
245
|
+
* @param id
|
|
246
|
+
*/
|
|
247
|
+
public remove(id: string): void {
|
|
248
|
+
const clip: Clip = this.find(id)
|
|
249
|
+
this.#clips = this.#clips.filter((item: Clip): boolean => item !== clip)
|
|
250
|
+
this.changed()
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* 删除置顶以外的所有剪贴项
|
|
255
|
+
*/
|
|
256
|
+
public clear(): void {
|
|
257
|
+
this.#clips = this.#clips.filter((clip: Clip): boolean => clip.pinned)
|
|
258
|
+
this.changed()
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
- 组件只创建一次,由整个应用共用(见 [Objects](../Objects.md)):剪贴项由它保存,因为剪贴项要跨越多次请求保留,而控制器只在一次请求中存在(见 [Controllers](../Controllers.md) 第 2 节)。
|
|
264
|
+
- 组件对 NW.js 一无所知,它用到的东西都由选项提供(见 [Injection](../Injection.md)):`clipboard` 是读写剪贴板文本的两个函数(在应用中是 NW.js 的剪贴板,见第 8 节;在测试中是一个变量,见第 11 节),`file` 是保存历史的文件。
|
|
265
|
+
- NW.js 不会通知剪贴板的变化,所以 `init()` 每隔 `interval` 毫秒读取一次剪贴板。与上次读到的不同的文本就是一次复制;应用启动时剪贴板里已有的文本不算,`copy()` 自己写入的文本也不算。
|
|
266
|
+
- 再次复制的文本会移到最前,而不是再加一条。超过 `limit` 条时,最旧的剪贴项会被丢弃,置顶的除外。
|
|
267
|
+
- 每次变化都会保存文件并发出通知:`this.entrypoint.broadcast()` 向窗口推送 `clips.changed`(见 [ServiceCalls](../ServiceCalls.md) 第 5 节),`this.emit('changed')` 通知其他组件,比如托盘(见第 6 节)。文件先写到旁边的临时文件(`history.json.tmp`),再重命名覆盖原文件,这样即使程序崩溃,文件也不会只写了一半;写入按顺序进行,应用停止时 `destroy()` 会等最后一次写入完成。
|
|
268
|
+
|
|
269
|
+
## 5. 控制器
|
|
270
|
+
|
|
271
|
+
**`packages/app/src/controllers/ClipController.ts`**
|
|
272
|
+
|
|
273
|
+
```typescript
|
|
274
|
+
import {Controller} from 'lakutata/com/entrypoint'
|
|
275
|
+
import {ServiceAction} from 'lakutata/decorator/ctrl'
|
|
276
|
+
import {Inject} from 'lakutata/decorator/di'
|
|
277
|
+
import {type Clip, History} from '../components/History.js'
|
|
278
|
+
import {ClipIdDTO, PinClipDTO, SearchClipsDTO} from '../dtos/ClipDTO.js'
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* 历史的动作,由窗口调用:window.ipc.invoke({cmd: 'clips.list'})
|
|
282
|
+
*/
|
|
283
|
+
export class ClipController extends Controller {
|
|
284
|
+
|
|
285
|
+
@Inject('history')
|
|
286
|
+
protected readonly history: History
|
|
287
|
+
|
|
288
|
+
@ServiceAction({cmd: 'clips.list'}, SearchClipsDTO)
|
|
289
|
+
public async list(input: SearchClipsDTO): Promise<Clip[]> {
|
|
290
|
+
return this.history.list(input.query)
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
@ServiceAction({cmd: 'clips.copy'}, ClipIdDTO)
|
|
294
|
+
public async copy(input: ClipIdDTO): Promise<Clip> {
|
|
295
|
+
return this.history.copy(input.id)
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
@ServiceAction({cmd: 'clips.pin'}, PinClipDTO)
|
|
299
|
+
public async pin(input: PinClipDTO): Promise<Clip> {
|
|
300
|
+
return this.history.pin(input.id, input.pinned)
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
@ServiceAction({cmd: 'clips.delete'}, ClipIdDTO)
|
|
304
|
+
public async remove(input: ClipIdDTO): Promise<void> {
|
|
305
|
+
this.history.remove(input.id)
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
@ServiceAction({cmd: 'clips.clear'})
|
|
309
|
+
public async clear(): Promise<void> {
|
|
310
|
+
this.history.clear()
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
每个 `@ServiceAction` 由一条消息调用:`{cmd: 'clips.pin', id: '…', pinned: true}` 会以 `{id: '…', pinned: true}` 调用 `pin()`,输入由 `PinClipDTO` 校验(见 [ServiceCalls](../ServiceCalls.md) 第 2 节)。动作都很短:实际工作由控制器注入的 `history` 组件完成。没有返回值的动作(比如 `remove()`)会返回 `{success: true, error: null}`。
|
|
316
|
+
|
|
317
|
+
## 6. 窗口和托盘
|
|
318
|
+
|
|
319
|
+
应用常驻托盘:关闭窗口只是把它隐藏,从托盘菜单可以重新显示窗口或退出应用。模板中有两个文件要修改:窗口组件和 NW.js API 的类型声明;托盘是一个新组件。
|
|
320
|
+
|
|
321
|
+
**`packages/app/src/components/MainWindow.ts`**
|
|
322
|
+
|
|
323
|
+
```typescript
|
|
324
|
+
import {Application, Component, DTO} from 'lakutata'
|
|
325
|
+
import {Configurable, Inject} from 'lakutata/decorator/di'
|
|
326
|
+
|
|
327
|
+
/**
|
|
328
|
+
* 应用的窗口:它的宿主页面(packages/app/host)把用户界面放在 webview 中,与 Node.js 和 NW.js 隔离(用户界面只能通过宿主页面
|
|
329
|
+
* 的消息调用应用的动作)。关闭窗口只是把它隐藏:应用在托盘中继续读取剪贴板
|
|
330
|
+
*/
|
|
331
|
+
export class MainWindow extends Component {
|
|
332
|
+
|
|
333
|
+
@Inject(Application)
|
|
334
|
+
protected readonly app: Application
|
|
335
|
+
|
|
336
|
+
@Configurable(DTO.Number().optional().default(420))
|
|
337
|
+
protected readonly width: number
|
|
338
|
+
|
|
339
|
+
@Configurable(DTO.Number().optional().default(640))
|
|
340
|
+
protected readonly height: number
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* 开发时用户界面的 URL,否则使用构建好的文件
|
|
344
|
+
*/
|
|
345
|
+
@Configurable(DTO.String().optional())
|
|
346
|
+
protected readonly ui?: string
|
|
347
|
+
|
|
348
|
+
#window: nw.Window | undefined
|
|
349
|
+
|
|
350
|
+
protected async init(): Promise<void> {
|
|
351
|
+
//页面是应用中的文件:应用的资源(lakutata.resources)在它的 resources 目录中,用户界面的路径相对于宿主页面
|
|
352
|
+
const query: URLSearchParams = new URLSearchParams({ui: this.ui ?? '../ui/index.html'})
|
|
353
|
+
//开发时打开用户界面的 DevTools(用户界面由 Vite 提供)
|
|
354
|
+
if (this.ui) query.set('devtools', 'true')
|
|
355
|
+
const window: nw.Window = await new Promise((resolve: (window: nw.Window) => void): void => nw.Window.open(`resources/host/index.html?${query}`, {
|
|
356
|
+
title: this.app.appName,
|
|
357
|
+
width: this.width,
|
|
358
|
+
height: this.height,
|
|
359
|
+
//窗口的图标(Windows、Linux;macOS 的窗口显示应用的图标)
|
|
360
|
+
icon: 'resources/logo.png'
|
|
361
|
+
}, resolve))
|
|
362
|
+
this.#window = window
|
|
363
|
+
//关闭窗口时把它隐藏:应用从托盘退出,或者在被要求退出时退出(macOS 上的 Cmd+Q)
|
|
364
|
+
window.on('close', (reason?: 'quit'): unknown => reason === 'quit' ? this.app.exit(0) : window.hide())
|
|
365
|
+
//再次启动应用时,把窗口重新显示出来
|
|
366
|
+
nw.App.on('open', (): void => this.show())
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* 重新显示窗口,放到其他窗口前面
|
|
371
|
+
*/
|
|
372
|
+
public show(): void {
|
|
373
|
+
this.#window?.show()
|
|
374
|
+
this.#window?.restore()
|
|
375
|
+
this.#window?.focus()
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
protected async destroy(): Promise<void> {
|
|
379
|
+
this.#window?.removeAllListeners('close').close(true)
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
```
|
|
383
|
+
|
|
384
|
+
- 窗口打开模板的宿主页面(`packages/app/host`),宿主页面把用户界面放在 webview 中。用户界面与 Node.js 和 NW.js 隔离运行:它只能通过宿主页面的消息访问应用,相当于 Electron 中预加载脚本的角色。
|
|
385
|
+
- NW.js 通过 `close` 事件要求窗口关闭;监听了这个事件后,窗口只有通过 `close(true)` 才会关闭。这里的监听器把窗口隐藏,除非应用正在退出(macOS 上的 Cmd+Q,这时监听器会收到 `'quit'`)。应用停止时,`destroy()` 移除监听器并关闭窗口。
|
|
386
|
+
- `show()` 把窗口重新显示出来,托盘菜单会调用它,再次启动应用时也会调用它(`nw.App.on('open')`:NW.js 只运行应用的一个实例)。
|
|
387
|
+
|
|
388
|
+
**`packages/app/src/components/Tray.ts`**
|
|
389
|
+
|
|
390
|
+
```typescript
|
|
391
|
+
import {Application, Component} from 'lakutata'
|
|
392
|
+
import {Inject} from 'lakutata/decorator/di'
|
|
393
|
+
import {type Clip, History} from './History.js'
|
|
394
|
+
import {MainWindow} from './MainWindow.js'
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* 托盘菜单中剪贴项标签的最大长度
|
|
398
|
+
*/
|
|
399
|
+
const LABEL: number = 40
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* 应用在系统托盘中的图标(macOS 的菜单栏、Windows 的通知区域):它的菜单可以再次复制最近的剪贴项、显示窗口或退出应用
|
|
403
|
+
*/
|
|
404
|
+
export class Tray extends Component {
|
|
405
|
+
|
|
406
|
+
@Inject(Application)
|
|
407
|
+
protected readonly app: Application
|
|
408
|
+
|
|
409
|
+
@Inject('history')
|
|
410
|
+
protected readonly history: History
|
|
411
|
+
|
|
412
|
+
@Inject('window')
|
|
413
|
+
protected readonly window: MainWindow
|
|
414
|
+
|
|
415
|
+
#tray: nw.Tray | undefined
|
|
416
|
+
|
|
417
|
+
protected async init(): Promise<void> {
|
|
418
|
+
//macOS 的菜单栏按图标的原始尺寸显示,不会缩小:所以这里显示应用的名称来代替图标(22 像素、只有黑色和透明的模板图片可以放得下)
|
|
419
|
+
this.#tray = new nw.Tray(process.platform === 'darwin' ? {title: this.app.appName} : {icon: 'resources/logo.png', tooltip: this.app.appName})
|
|
420
|
+
this.update()
|
|
421
|
+
this.history.on('changed', (): void => this.update())
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* 用最近的剪贴项重新生成菜单
|
|
426
|
+
*/
|
|
427
|
+
protected update(): void {
|
|
428
|
+
const menu: nw.Menu = new nw.Menu()
|
|
429
|
+
for (const clip of this.history.list().slice(0, 5)) {
|
|
430
|
+
menu.append(new nw.MenuItem({label: this.label(clip), click: (): unknown => this.history.copy(clip.id)}))
|
|
431
|
+
}
|
|
432
|
+
menu.append(new nw.MenuItem({type: 'separator'}))
|
|
433
|
+
menu.append(new nw.MenuItem({label: 'Show the history', click: (): void => this.window.show()}))
|
|
434
|
+
menu.append(new nw.MenuItem({label: 'Quit', click: (): unknown => this.app.exit(0)}))
|
|
435
|
+
this.#tray!.menu = menu
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/**
|
|
439
|
+
* 剪贴项的标签:它的第一行,过长时截短
|
|
440
|
+
* @param clip
|
|
441
|
+
*/
|
|
442
|
+
protected label(clip: Clip): string {
|
|
443
|
+
const line: string = clip.text.trim().split('\n')[0]
|
|
444
|
+
return `${clip.pinned ? '★ ' : ''}${line.length > LABEL ? `${line.slice(0, LABEL - 1)}…` : line}`
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
protected async destroy(): Promise<void> {
|
|
448
|
+
this.#tray?.remove()
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
```
|
|
452
|
+
|
|
453
|
+
- 托盘菜单列出最近的五条剪贴项,选中一条就把它再次复制到剪贴板。每当历史发出 `changed`,组件就重新生成菜单。
|
|
454
|
+
- **Quit** 调用 `this.app.exit(0)`:应用正常停止,组件依次销毁(见 [Application](../Application.md) 第 3 节),托盘图标被移除,窗口被关闭。
|
|
455
|
+
- 在 Windows 上,通知区域会把应用的图标缩小显示。macOS 的菜单栏按图标的原始尺寸显示(`logo.png` 有 512 像素),所以那里显示应用的名称来代替图标。NW.js 建议在后台脚本中创建托盘,因为后台脚本和应用存在得一样久:页面中创建的托盘在页面跳转后就不再工作。
|
|
456
|
+
|
|
457
|
+
模板的类型声明描述了它用到的 NW.js API。这里加上了窗口的 `close` 事件和 `hide()`、`nw.App.dataPath`、剪贴板、托盘及其菜单:
|
|
458
|
+
|
|
459
|
+
**`packages/app/src/nw.d.ts`**
|
|
460
|
+
|
|
461
|
+
```typescript
|
|
462
|
+
/**
|
|
463
|
+
* 应用用到的 NW.js API(后台脚本中的全局对象 nw):https://docs.nwjs.io
|
|
464
|
+
*/
|
|
465
|
+
declare namespace nw {
|
|
466
|
+
|
|
467
|
+
/**
|
|
468
|
+
* NW.js 的窗口
|
|
469
|
+
*/
|
|
470
|
+
interface Window {
|
|
471
|
+
on(event: 'closed' | 'loaded' | 'focus' | 'blur' | 'minimize' | 'restore', listener: () => void): this
|
|
472
|
+
/**
|
|
473
|
+
* 窗口被要求关闭:由用户关闭,或在应用退出时(macOS 上的 Cmd+Q)带着 quit 参数。监听了这个事件后,窗口只有通过
|
|
474
|
+
* close(true) 才会关闭
|
|
475
|
+
* @param event
|
|
476
|
+
* @param listener
|
|
477
|
+
*/
|
|
478
|
+
on(event: 'close', listener: (reason?: 'quit') => void): this
|
|
479
|
+
removeAllListeners(event?: string): this
|
|
480
|
+
show(): void
|
|
481
|
+
hide(): void
|
|
482
|
+
focus(): void
|
|
483
|
+
restore(): void
|
|
484
|
+
/**
|
|
485
|
+
* 关闭窗口:传 true 时不触发 close 事件
|
|
486
|
+
* @param force
|
|
487
|
+
*/
|
|
488
|
+
close(force?: boolean): void
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
/**
|
|
492
|
+
* 窗口的选项:https://docs.nwjs.io/References/Manifest%20Format/#window-subfields
|
|
493
|
+
*/
|
|
494
|
+
interface WindowOptions {
|
|
495
|
+
title?: string
|
|
496
|
+
width?: number
|
|
497
|
+
height?: number
|
|
498
|
+
icon?: string
|
|
499
|
+
show?: boolean
|
|
500
|
+
[option: string]: unknown
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/**
|
|
504
|
+
* 系统剪贴板:https://docs.nwjs.io/References/Clipboard/
|
|
505
|
+
*/
|
|
506
|
+
interface Clipboard {
|
|
507
|
+
get(type?: 'text' | 'html' | 'rtf' | 'png' | 'jpeg'): string
|
|
508
|
+
set(data: string, type?: 'text' | 'html' | 'rtf' | 'png' | 'jpeg'): void
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/**
|
|
512
|
+
* 菜单项:https://docs.nwjs.io/References/MenuItem/
|
|
513
|
+
*/
|
|
514
|
+
class MenuItem {
|
|
515
|
+
constructor(options: {label?: string, type?: 'normal' | 'separator', enabled?: boolean, click?: () => void})
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/**
|
|
519
|
+
* 菜单:https://docs.nwjs.io/References/Menu/
|
|
520
|
+
*/
|
|
521
|
+
class Menu {
|
|
522
|
+
append(item: MenuItem): void
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
/**
|
|
526
|
+
* 系统托盘中的图标(macOS 的菜单栏、Windows 的通知区域):https://docs.nwjs.io/References/Tray/
|
|
527
|
+
*/
|
|
528
|
+
class Tray {
|
|
529
|
+
constructor(options: {title?: string, tooltip?: string, icon?: string})
|
|
530
|
+
menu: Menu
|
|
531
|
+
remove(): void
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
const App: {
|
|
535
|
+
/**
|
|
536
|
+
* 应用的参数,位于应用目录之后
|
|
537
|
+
*/
|
|
538
|
+
readonly argv: string[]
|
|
539
|
+
/**
|
|
540
|
+
* 应用的数据目录,位于用户的数据目录中
|
|
541
|
+
*/
|
|
542
|
+
readonly dataPath: string
|
|
543
|
+
/**
|
|
544
|
+
* 退出应用
|
|
545
|
+
*/
|
|
546
|
+
quit(): void
|
|
547
|
+
/**
|
|
548
|
+
* 应用再次启动:它的命令行交给第一个实例
|
|
549
|
+
* @param event
|
|
550
|
+
* @param listener
|
|
551
|
+
*/
|
|
552
|
+
on(event: 'open', listener: (commandLine: string) => void): void
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
const Window: {
|
|
556
|
+
/**
|
|
557
|
+
* 打开窗口:URL 相对于应用的目录
|
|
558
|
+
* @param url
|
|
559
|
+
* @param options
|
|
560
|
+
* @param callback
|
|
561
|
+
*/
|
|
562
|
+
open(url: string, options: WindowOptions, callback: (window: nw.Window) => void): void
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
const Clipboard: {
|
|
566
|
+
/**
|
|
567
|
+
* 剪贴板
|
|
568
|
+
*/
|
|
569
|
+
get(): Clipboard
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
```
|
|
573
|
+
|
|
574
|
+
## 7. 应用的选项
|
|
575
|
+
|
|
576
|
+
**`packages/app/src/config/Config.ts`**
|
|
577
|
+
|
|
578
|
+
```typescript
|
|
579
|
+
import type {ApplicationOptions} from 'lakutata'
|
|
580
|
+
import {buildEntrypoints, httpServiceEntrypoint} from 'lakutata/com/entrypoint'
|
|
581
|
+
import {nwjsServiceEntrypoint} from 'lakutata/adapter/nwjs'
|
|
582
|
+
import path from 'node:path'
|
|
583
|
+
import {type ClipboardAccess, History} from '../components/History.js'
|
|
584
|
+
import {MainWindow} from '../components/MainWindow.js'
|
|
585
|
+
import {Tray} from '../components/Tray.js'
|
|
586
|
+
import {ClipController} from '../controllers/ClipController.js'
|
|
587
|
+
|
|
588
|
+
export type ConfigOptions = {
|
|
589
|
+
/**
|
|
590
|
+
* 读写的剪贴板,在应用中是 NW.js 的剪贴板(测试传入自己的)
|
|
591
|
+
*/
|
|
592
|
+
clipboard: ClipboardAccess
|
|
593
|
+
/**
|
|
594
|
+
* 应用的数据目录,历史保存在这里
|
|
595
|
+
*/
|
|
596
|
+
dataPath: string
|
|
597
|
+
/**
|
|
598
|
+
* 读取剪贴板的间隔,单位为毫秒(默认 500)
|
|
599
|
+
*/
|
|
600
|
+
interval?: number
|
|
601
|
+
/**
|
|
602
|
+
* 保留的剪贴项数量,不算置顶的(默认 50)
|
|
603
|
+
*/
|
|
604
|
+
limit?: number
|
|
605
|
+
/**
|
|
606
|
+
* 开发时用户界面的 URL(Vite 的开发服务器),否则使用构建好的文件
|
|
607
|
+
*/
|
|
608
|
+
ui?: string
|
|
609
|
+
mode?: 'development' | 'production'
|
|
610
|
+
/**
|
|
611
|
+
* 是否打开窗口和托盘图标,默认为 true(测试在没有它们的情况下提供动作)
|
|
612
|
+
*/
|
|
613
|
+
window?: boolean
|
|
614
|
+
/**
|
|
615
|
+
* 放置动作桥接对象的全局对象,默认是 NW.js 的(测试传入自己的)
|
|
616
|
+
*/
|
|
617
|
+
global?: object
|
|
618
|
+
/**
|
|
619
|
+
* 开发用的 HTTP 入口的端口,默认没有。工具(Postman、curl)用 POST / 和消息(模式和输入)调用动作,用 GET /events
|
|
620
|
+
* 接收推送给它们的事件(Server-Sent Events),并在 id 请求头(或 id 查询参数)中给出客户端 id
|
|
621
|
+
*/
|
|
622
|
+
devPort?: number
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
/**
|
|
626
|
+
* 应用的选项
|
|
627
|
+
* @param options
|
|
628
|
+
*/
|
|
629
|
+
export function config(options: ConfigOptions): ApplicationOptions {
|
|
630
|
+
return {
|
|
631
|
+
id: 'clips',
|
|
632
|
+
name: 'Clips',
|
|
633
|
+
mode: options.mode ?? 'development',
|
|
634
|
+
components: {
|
|
635
|
+
entrypoint: buildEntrypoints({
|
|
636
|
+
controllers: [ClipController],
|
|
637
|
+
//用户界面通过窗口的宿主页面调用动作:window.ipc.invoke({cmd: 'clips.list'})
|
|
638
|
+
service: [
|
|
639
|
+
nwjsServiceEntrypoint({global: options.global}),
|
|
640
|
+
...options.devPort === undefined ? [] : [httpServiceEntrypoint({port: options.devPort})]
|
|
641
|
+
]
|
|
642
|
+
}),
|
|
643
|
+
history: {
|
|
644
|
+
class: History,
|
|
645
|
+
clipboard: options.clipboard,
|
|
646
|
+
file: path.join(options.dataPath, 'history.json'),
|
|
647
|
+
interval: options.interval,
|
|
648
|
+
limit: options.limit
|
|
649
|
+
},
|
|
650
|
+
...(options.window === false ? {} : {
|
|
651
|
+
window: {
|
|
652
|
+
class: MainWindow,
|
|
653
|
+
ui: options.ui
|
|
654
|
+
},
|
|
655
|
+
tray: {
|
|
656
|
+
class: Tray
|
|
657
|
+
}
|
|
658
|
+
})
|
|
659
|
+
},
|
|
660
|
+
//先提供动作,窗口再加载用户界面;历史从一开始就读取剪贴板,窗口隐藏时也一样
|
|
661
|
+
bootstrap: options.window === false ? ['entrypoint', 'history'] : ['entrypoint', 'history', 'window', 'tray']
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
```
|
|
665
|
+
|
|
666
|
+
`history` 的选项就是组件的选项:剪贴板、文件(数据目录中的 `history.json`),以及间隔和上限,这两项为 `undefined` 时使用默认值。没有窗口时(`window: false`,即测试中),也没有托盘:需要 NW.js 的组件都不创建,动作通过测试传入的全局对象提供。
|
|
667
|
+
|
|
668
|
+
## 8. 后台脚本
|
|
669
|
+
|
|
670
|
+
**`packages/app/src/App.ts`**
|
|
671
|
+
|
|
672
|
+
```typescript
|
|
673
|
+
import {Application, type ILogger} from 'lakutata'
|
|
674
|
+
import {config} from './config/Config.js'
|
|
675
|
+
|
|
676
|
+
/**
|
|
677
|
+
* 开发时用户界面的 URL(--ui=<url>,Vite 的开发服务器),由 lakutata nwjs run 传入
|
|
678
|
+
*/
|
|
679
|
+
const ui: string | undefined = nw.App.argv.find((argument: string): boolean => argument.startsWith('--ui='))?.slice('--ui='.length)
|
|
680
|
+
|
|
681
|
+
/**
|
|
682
|
+
* 开发时应用运行在开发用的 NW.js 中(lakutata nwjs run:sdk 版本,带 DevTools),安装后运行在普通版本中
|
|
683
|
+
*/
|
|
684
|
+
const development: boolean = process.versions['nw-flavor'] === 'sdk'
|
|
685
|
+
|
|
686
|
+
/**
|
|
687
|
+
* 通过 NW.js 访问的系统剪贴板
|
|
688
|
+
*/
|
|
689
|
+
const clipboard: nw.Clipboard = nw.Clipboard.get()
|
|
690
|
+
|
|
691
|
+
//NW.js 只运行应用的一个实例:再次启动的实例会退出,第一个实例把窗口放到最前面
|
|
692
|
+
Application
|
|
693
|
+
.run(config({
|
|
694
|
+
clipboard: {read: (): string => clipboard.get('text'), write: (text: string): void => clipboard.set(text, 'text')},
|
|
695
|
+
//NW.js 为应用提供的数据目录,位于用户的数据目录中
|
|
696
|
+
dataPath: nw.App.dataPath,
|
|
697
|
+
ui: ui,
|
|
698
|
+
mode: development ? 'development' : 'production',
|
|
699
|
+
//开发时把动作提供给工具(Postman、curl),安装后的应用不提供
|
|
700
|
+
devPort: development ? Number(process.env.DEV_PORT ?? 9000) : undefined
|
|
701
|
+
}))
|
|
702
|
+
.onLaunched((app: Application, log: ILogger): void => log.info('%s started in %s mode', app.appName, app.mode()))
|
|
703
|
+
.onFatalException((error: Error, log: ILogger): void => {
|
|
704
|
+
log.error('The application cannot start: %s', error.message)
|
|
705
|
+
process.exit(1)
|
|
706
|
+
})
|
|
707
|
+
```
|
|
708
|
+
|
|
709
|
+
模板的 `App.ts` 中加了两个选项:`clipboard` 是按文本读写的 NW.js 剪贴板(`nw.Clipboard.get()`),`dataPath` 是 NW.js 给应用的数据目录(`nw.App.dataPath`)。这个目录以 `packages/app/package.json` 中 `lakutata.installer` 的 `appId`(`clips`)命名,开发时和安装后都一样:macOS 上是 `~/Library/Application Support/clips/Default`,Windows 上是 `%LOCALAPPDATA%\clips`,Linux 上是 `~/.config/clips`。
|
|
710
|
+
|
|
711
|
+
模板的宿主页面和桥接代码(`packages/app/host`、`packages/ui/src/ipc.ts`)保持不变:它们给用户界面提供应用的动作和事件,不提供 NW.js 或 Node.js 的其他任何东西。
|
|
712
|
+
|
|
713
|
+
## 9. 用户界面
|
|
714
|
+
|
|
715
|
+
**`packages/ui/src/App.tsx`**
|
|
716
|
+
|
|
717
|
+
```tsx
|
|
718
|
+
import {useCallback, useEffect, useState} from 'react'
|
|
719
|
+
|
|
720
|
+
/**
|
|
721
|
+
* 历史中的一条剪贴项,即动作返回的格式
|
|
722
|
+
*/
|
|
723
|
+
type Clip = { id: string, text: string, copiedAt: string, pinned: boolean }
|
|
724
|
+
|
|
725
|
+
export function App() {
|
|
726
|
+
const [query, setQuery] = useState<string>('')
|
|
727
|
+
const [clips, setClips] = useState<Clip[]>([])
|
|
728
|
+
const [failure, setFailure] = useState<string>('')
|
|
729
|
+
|
|
730
|
+
const load = useCallback((): void => {
|
|
731
|
+
window.ipc.invoke<Clip[]>({cmd: 'clips.list', query: query || undefined})
|
|
732
|
+
.then((loaded: Clip[]): void => setClips(loaded))
|
|
733
|
+
.catch((error: Error): void => setFailure(error.message))
|
|
734
|
+
}, [query])
|
|
735
|
+
|
|
736
|
+
useEffect((): () => void => {
|
|
737
|
+
load()
|
|
738
|
+
//历史变化了:在这里或从托盘复制了内容
|
|
739
|
+
window.ipc.on('clips.changed', load)
|
|
740
|
+
return (): void => {
|
|
741
|
+
window.ipc.off('clips.changed', load)
|
|
742
|
+
}
|
|
743
|
+
}, [load])
|
|
744
|
+
|
|
745
|
+
/**
|
|
746
|
+
* 调用历史的动作,历史会推送它的变化
|
|
747
|
+
* @param data
|
|
748
|
+
*/
|
|
749
|
+
const act = (data: Record<string, unknown>): void => {
|
|
750
|
+
window.ipc.invoke(data).catch((error: Error): void => setFailure(error.message))
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
return (
|
|
754
|
+
<main>
|
|
755
|
+
<input type="search" placeholder="Search the history" value={query} onChange={(event): void => setQuery(event.target.value)}/>
|
|
756
|
+
<button onClick={(): void => act({cmd: 'clips.clear'})}>Clear</button>
|
|
757
|
+
{failure && <p role="alert">{failure}</p>}
|
|
758
|
+
<ul>
|
|
759
|
+
{clips.map((clip: Clip) => (
|
|
760
|
+
<li key={clip.id}>
|
|
761
|
+
<pre title={new Date(clip.copiedAt).toLocaleString()}>{clip.text}</pre>
|
|
762
|
+
<button onClick={(): void => act({cmd: 'clips.copy', id: clip.id})}>Copy</button>
|
|
763
|
+
<button onClick={(): void => act({cmd: 'clips.pin', id: clip.id, pinned: !clip.pinned})}>{clip.pinned ? 'Unpin' : 'Pin'}</button>
|
|
764
|
+
<button onClick={(): void => act({cmd: 'clips.delete', id: clip.id})}>Delete</button>
|
|
765
|
+
</li>
|
|
766
|
+
))}
|
|
767
|
+
</ul>
|
|
768
|
+
</main>
|
|
769
|
+
)
|
|
770
|
+
}
|
|
771
|
+
```
|
|
772
|
+
|
|
773
|
+
- `window.ipc` 是模板的桥接对象(`packages/ui/src/ipc.ts`):`invoke()` 调用动作,返回它的 `payload` 或抛出它的错误;`on()` 和 `off()` 监听应用推送的事件。
|
|
774
|
+
- 每次收到 `clips.changed` 都重新加载列表,不管变化来自哪里:在其他程序中复制、窗口中的操作,还是在托盘菜单中选了一条剪贴项。
|
|
775
|
+
- 按钮不直接修改列表:历史推送它的变化,列表随之更新。
|
|
776
|
+
|
|
777
|
+
## 10. 运行
|
|
778
|
+
|
|
779
|
+
```bash
|
|
780
|
+
npm run dev
|
|
781
|
+
```
|
|
782
|
+
|
|
783
|
+
这个命令启动 Vite 的开发服务器和 NW.js:开发服务器提供用户界面,`packages/ui` 有变化时会重新加载它;NW.js 的窗口加载用户界面并打开它的 DevTools。应用会输出日志 `Clips started in development mode`。在任何程序中复制几段文本:它们会出现在窗口的最上面,也会出现在托盘菜单中(macOS 菜单栏上显示名称 `Clips`)。
|
|
784
|
+
|
|
785
|
+
开发时,动作也通过 HTTP 在 9000 端口(`DEV_PORT`)提供,可以用 curl 或 Postman 试用:`POST /` 发送消息,`GET /events` 以 Server-Sent Events 的形式接收某个客户端的事件(见 [ServiceCalls](../ServiceCalls.md) 第 4 节)。先复制 `git log --oneline -5`,再复制 `https://docs.nwjs.io/References/Tray/`,然后在另一个终端中运行:
|
|
786
|
+
|
|
787
|
+
```bash
|
|
788
|
+
curl -N 'localhost:9000/events?id=me' &
|
|
789
|
+
# event: client
|
|
790
|
+
# data: ["me"]
|
|
791
|
+
|
|
792
|
+
curl -X POST localhost:9000/ -H 'Content-Type: application/json' -d '{"cmd": "clips.list"}'
|
|
793
|
+
# {"success":true,"error":null,"payload":[{"id":"89994a65-872a-44f1-bdf2-d44d2ead2748","text":"https://docs.nwjs.io/References/Tray/","copiedAt":"2026-11-03T15:29:26.787Z","pinned":false},{"id":"7de7167d-cfaa-4861-807c-f65ea10b97fc","text":"git log --oneline -5","copiedAt":"2026-11-03T15:29:25.786Z","pinned":false}]}
|
|
794
|
+
|
|
795
|
+
curl -X POST localhost:9000/ -H 'Content-Type: application/json' -d '{"cmd": "clips.pin", "id": "7de7167d-cfaa-4861-807c-f65ea10b97fc", "pinned": true}'
|
|
796
|
+
# {"success":true,"error":null,"payload":{"id":"7de7167d-cfaa-4861-807c-f65ea10b97fc","text":"git log --oneline -5","copiedAt":"2026-11-03T15:29:25.786Z","pinned":true}}
|
|
797
|
+
# event: clips.changed
|
|
798
|
+
# data: []
|
|
799
|
+
|
|
800
|
+
curl -X POST localhost:9000/ -H 'Content-Type: application/json' -d '{"cmd": "clips.list", "query": "TRAY"}'
|
|
801
|
+
# {"success":true,"error":null,"payload":[{"id":"89994a65-872a-44f1-bdf2-d44d2ead2748","text":"https://docs.nwjs.io/References/Tray/","copiedAt":"2026-11-03T15:29:26.787Z","pinned":false}]}
|
|
802
|
+
|
|
803
|
+
curl -X POST localhost:9000/ -H 'Content-Type: application/json' -d '{"cmd": "clips.copy", "id": "00000000-0000-4000-8000-000000000000"}'
|
|
804
|
+
# {"success":false,"error":{…,"message":"The clip 00000000-0000-4000-8000-000000000000 is not in the history","errMsg":"The clip 00000000-0000-4000-8000-000000000000 is not in the history","err":"ClipNotFoundException","errno":"E_CLIP_NOT_FOUND"},"payload":null}
|
|
805
|
+
```
|
|
806
|
+
|
|
807
|
+
窗口立即显示了置顶,因为事件也推送到了窗口。错误带有异常的全部属性,包括调用栈(这里省略了)。
|
|
808
|
+
|
|
809
|
+
## 11. 测试
|
|
810
|
+
|
|
811
|
+
**`packages/app/src/tests/App.spec.ts`**
|
|
812
|
+
|
|
813
|
+
```typescript
|
|
814
|
+
import {after, before, describe, it} from 'node:test'
|
|
815
|
+
import assert from 'node:assert'
|
|
816
|
+
import {mkdtempSync, readFileSync, rmSync} from 'node:fs'
|
|
817
|
+
import os from 'node:os'
|
|
818
|
+
import path from 'node:path'
|
|
819
|
+
import {Application} from 'lakutata'
|
|
820
|
+
import {NWJS_SERVICE_BRIDGE, type NwjsServiceBridge} from 'lakutata/adapter/nwjs'
|
|
821
|
+
import type {Clip} from '../components/History.js'
|
|
822
|
+
import {config} from '../config/Config.js'
|
|
823
|
+
|
|
824
|
+
/**
|
|
825
|
+
* 测试用的剪贴板文本,应用在没有 NW.js 的情况下读写它
|
|
826
|
+
*/
|
|
827
|
+
let copied: string = ''
|
|
828
|
+
|
|
829
|
+
/**
|
|
830
|
+
* 测试的全局对象:通过放在它上面的桥接对象调用动作,与窗口的宿主页面调用方式相同
|
|
831
|
+
*/
|
|
832
|
+
const shared: Record<symbol, unknown> = {}
|
|
833
|
+
|
|
834
|
+
/**
|
|
835
|
+
* 像用户界面那样调用动作(window.ipc.invoke)
|
|
836
|
+
* @param data
|
|
837
|
+
*/
|
|
838
|
+
function invoke(data: Record<string, unknown>): Promise<any> {
|
|
839
|
+
return (shared[Symbol.for(NWJS_SERVICE_BRIDGE)] as NwjsServiceBridge).invoke(data, 'page')
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
/**
|
|
843
|
+
* 历史中的文本,按历史的顺序
|
|
844
|
+
*/
|
|
845
|
+
async function texts(): Promise<string[]> {
|
|
846
|
+
return (await invoke({cmd: 'clips.list'})).payload.map((clip: Clip): string => clip.text)
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
/**
|
|
850
|
+
* 像其他程序那样把文本复制到剪贴板,并等历史读到它:即最新的未置顶剪贴项
|
|
851
|
+
* @param text
|
|
852
|
+
*/
|
|
853
|
+
async function copy(text: string): Promise<void> {
|
|
854
|
+
copied = text
|
|
855
|
+
const latest = async (): Promise<string | undefined> => (await invoke({cmd: 'clips.list'})).payload.find((clip: Clip): boolean => !clip.pinned)?.text
|
|
856
|
+
for (let attempt: number = 0; await latest() !== text; attempt++) {
|
|
857
|
+
if (attempt === 100) throw new Error(`${text} was not read from the clipboard`)
|
|
858
|
+
await new Promise((resolve): unknown => setTimeout(resolve, 10))
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
describe('Clips', (): void => {
|
|
863
|
+
|
|
864
|
+
let app: Application
|
|
865
|
+
let data: string
|
|
866
|
+
const pushed: string[] = []
|
|
867
|
+
|
|
868
|
+
before(async (): Promise<void> => {
|
|
869
|
+
data = mkdtempSync(path.join(os.tmpdir(), 'clips-'))
|
|
870
|
+
copied = 'On the clipboard before the application starts'
|
|
871
|
+
app = await new Promise<Application>((resolve: (app: Application) => void): void => {
|
|
872
|
+
Application.run(config({
|
|
873
|
+
clipboard: {read: (): string => copied, write: (text: string): void => void (copied = text)},
|
|
874
|
+
dataPath: data,
|
|
875
|
+
interval: 10,
|
|
876
|
+
limit: 3,
|
|
877
|
+
window: false,
|
|
878
|
+
global: shared
|
|
879
|
+
})).onLaunched((launched: Application): void => resolve(launched))
|
|
880
|
+
})
|
|
881
|
+
//页面订阅应用的事件
|
|
882
|
+
const bridge: NwjsServiceBridge = shared[Symbol.for(NWJS_SERVICE_BRIDGE)] as NwjsServiceBridge
|
|
883
|
+
bridge.subscribe('page', (event: string): unknown => pushed.push(event))
|
|
884
|
+
})
|
|
885
|
+
|
|
886
|
+
after(async (): Promise<void> => {
|
|
887
|
+
await app?.dispose()
|
|
888
|
+
rmSync(data, {recursive: true, force: true})
|
|
889
|
+
})
|
|
890
|
+
|
|
891
|
+
it('keeps the texts copied, the latest first, but not what the clipboard held at the start', async (): Promise<void> => {
|
|
892
|
+
await copy('git status')
|
|
893
|
+
await copy('npm test')
|
|
894
|
+
assert.deepStrictEqual(await texts(), ['npm test', 'git status'])
|
|
895
|
+
//窗口收到了通知
|
|
896
|
+
assert.ok(pushed.includes('clips.changed'))
|
|
897
|
+
})
|
|
898
|
+
|
|
899
|
+
it('moves a text copied again to the top, and drops the oldest clips beyond the limit', async (): Promise<void> => {
|
|
900
|
+
await copy('git status')
|
|
901
|
+
await copy('ls -la')
|
|
902
|
+
await copy('pwd')
|
|
903
|
+
assert.deepStrictEqual(await texts(), ['pwd', 'ls -la', 'git status'])
|
|
904
|
+
})
|
|
905
|
+
|
|
906
|
+
it('keeps the pinned clips first, beyond the limit', async (): Promise<void> => {
|
|
907
|
+
const [, , oldest] = (await invoke({cmd: 'clips.list'})).payload
|
|
908
|
+
assert.strictEqual((await invoke({cmd: 'clips.pin', id: oldest.id, pinned: true})).payload.pinned, true)
|
|
909
|
+
await copy('make')
|
|
910
|
+
await copy('make install')
|
|
911
|
+
await copy('make clean')
|
|
912
|
+
assert.deepStrictEqual(await texts(), ['git status', 'make clean', 'make install', 'make'])
|
|
913
|
+
})
|
|
914
|
+
|
|
915
|
+
it('copies a clip to the clipboard again', async (): Promise<void> => {
|
|
916
|
+
const clips: Clip[] = (await invoke({cmd: 'clips.list', query: 'INSTALL'})).payload
|
|
917
|
+
assert.deepStrictEqual(clips.map((clip: Clip): string => clip.text), ['make install'])
|
|
918
|
+
await invoke({cmd: 'clips.copy', id: clips[0].id})
|
|
919
|
+
assert.strictEqual(copied, 'make install')
|
|
920
|
+
assert.deepStrictEqual(await texts(), ['git status', 'make install', 'make clean', 'make'])
|
|
921
|
+
})
|
|
922
|
+
|
|
923
|
+
it('removes a clip, then all of them but the pinned ones', async (): Promise<void> => {
|
|
924
|
+
const [, second] = (await invoke({cmd: 'clips.list'})).payload
|
|
925
|
+
assert.strictEqual((await invoke({cmd: 'clips.delete', id: second.id})).success, true)
|
|
926
|
+
assert.deepStrictEqual(await texts(), ['git status', 'make clean', 'make'])
|
|
927
|
+
await invoke({cmd: 'clips.clear'})
|
|
928
|
+
assert.deepStrictEqual(await texts(), ['git status'])
|
|
929
|
+
})
|
|
930
|
+
|
|
931
|
+
it('keeps the history in its file', async (): Promise<void> => {
|
|
932
|
+
await new Promise((resolve): unknown => setTimeout(resolve, 50))
|
|
933
|
+
const saved: Clip[] = JSON.parse(readFileSync(path.join(data, 'history.json'), 'utf8'))
|
|
934
|
+
assert.deepStrictEqual(saved.map((clip: Clip): string => clip.text), ['git status'])
|
|
935
|
+
})
|
|
936
|
+
|
|
937
|
+
it('refuses a clip that is not in the history, and an invalid input', async (): Promise<void> => {
|
|
938
|
+
const missing = await invoke({cmd: 'clips.copy', id: '00000000-0000-4000-8000-000000000000'})
|
|
939
|
+
assert.strictEqual(missing.success, false)
|
|
940
|
+
assert.strictEqual(missing.error.errno, 'E_CLIP_NOT_FOUND')
|
|
941
|
+
const invalid = await invoke({cmd: 'clips.pin', id: 'first'})
|
|
942
|
+
assert.strictEqual(invalid.success, false)
|
|
943
|
+
assert.match(invalid.error.message, /id/)
|
|
944
|
+
})
|
|
945
|
+
})
|
|
946
|
+
```
|
|
947
|
+
|
|
948
|
+
测试用 Node.js 运行应用,不需要 NW.js:`window: false` 不创建窗口和托盘,剪贴板是一个变量,数据目录是一个临时目录。`nwjsServiceEntrypoint` 把它的桥接对象放在传入的全局对象上(`global: shared`),在 NW.js 中窗口的宿主页面就是在那里找到它的;测试和窗口一样通过它调用动作,并订阅某个客户端的事件。10 毫秒的间隔和 3 条的上限让测试运行得更快。
|
|
949
|
+
|
|
950
|
+
```bash
|
|
951
|
+
npm test
|
|
952
|
+
```
|
|
953
|
+
|
|
954
|
+
```
|
|
955
|
+
app │ ✔ keeps the texts copied, the latest first, but not what the clipboard held at the start
|
|
956
|
+
app │ ✔ moves a text copied again to the top, and drops the oldest clips beyond the limit
|
|
957
|
+
app │ ✔ keeps the pinned clips first, beyond the limit
|
|
958
|
+
app │ ✔ copies a clip to the clipboard again
|
|
959
|
+
app │ ✔ removes a clip, then all of them but the pinned ones
|
|
960
|
+
app │ ✔ keeps the history in its file
|
|
961
|
+
app │ ✔ refuses a clip that is not in the history, and an invalid input
|
|
962
|
+
app │ ℹ pass 7
|
|
963
|
+
✔ test ran in app
|
|
964
|
+
```
|
|
965
|
+
|
|
966
|
+
`npm test` 先构建各个包(包括用户界面),再运行测试。需要 NW.js 的部分,即系统剪贴板、托盘和窗口,用 `npm run dev` 实际试用。
|
|
967
|
+
|
|
968
|
+
## 12. 打包
|
|
969
|
+
|
|
970
|
+
- `npm run package:host` 构建各个包,然后在 `dist/installer` 中生成当前平台的安装包:macOS 上是 `dmg`,Linux 上是 `deb`,Windows 上是 `nsis` 安装程序和 `zip`。`npm run package:linux` 在 Docker 中生成 Linux 的安装包,在任何平台上都可以运行。安装包由 `lakutata package installer` 根据 `packages/app/package.json` 中的 `lakutata.installer` 生成(见 [Installers](../Installers.md))。
|
|
971
|
+
- 安装后的应用运行在普通版本的 NW.js 中,没有 DevTools:它的模式是 `production`,也没有 HTTP 入口(只有在 `lakutata nwjs run` 的 sdk 版本中才会传入 `devPort`)。
|
|
972
|
+
- 应用运行在 `packages/app/package.json` 中 `lakutata.nwjs` 指定的 NW.js 版本中;`npm run nwjs:use -- <version>` 可以换成其他版本,比如 `win7`,即 NW.js 0.72,能在 Windows 7、8 和 8.1 上运行的最后一个版本(见 [ProjectStructure](../ProjectStructure.md))。
|
|
973
|
+
|
|
974
|
+
<!--
|
|
975
|
+
check:
|
|
976
|
+
create: clips nwjs-react
|
|
977
|
+
remove: packages/app/src/controllers/ExampleController.ts packages/app/src/dtos/GreetDTO.ts
|
|
978
|
+
run: npm test
|
|
979
|
+
run: npm run typecheck -w ui
|
|
980
|
+
-->
|