-
Notifications
You must be signed in to change notification settings - Fork 70
/
window.js
491 lines (438 loc) · 13.9 KB
/
window.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
// @ts-check
/**
* @module Window
*
* Provides ApplicationWindow class and methods
*
* Don't use this module directly, get instances of ApplicationWindow with
* `socket:application` methods like `getCurrentWindow`, `createWindow`,
* `getWindow`, and `getWindows`.
*/
import { isValidPercentageValue } from './util.js'
import * as statuses from './window/constants.js'
import location from './location.js'
import { URL } from './url.js'
import hotkey from './window/hotkey.js'
import menu from './application/menu.js'
import ipc from './ipc.js'
/**
* @param {string} url
* @return {string}
* @ignore
*/
export function formatURL (url) {
const href = location?.href ?? 'socket:///'
return String(new URL(url, href))
}
/**
* @class ApplicationWindow
* Represents a window in the application
*/
export class ApplicationWindow {
#index
#options
#senderWindowIndex = globalThis.__args.index
#listeners = {}
// TODO(@chicoxyzzy): add parent and children? (needs native process support)
static constants = statuses
static hotkey = hotkey
constructor ({ index, ...options }) {
this.#index = index
this.#options = options
}
#updateOptions (response) {
const { data, err } = response
if (err) {
throw new Error(err)
}
const { index, ...options } = data
this.#options = options
return data
}
/**
* Get the index of the window
* @return {number} - the index of the window
*/
get index () {
return this.#index
}
/**
* @type {import('./window/hotkey.js').default}
*/
get hotkey () {
return hotkey
}
/**
* Get the size of the window
* @return {{ width: number, height: number }} - the size of the window
*/
getSize () {
return {
width: this.#options.width,
height: this.#options.height
}
}
/**
* Get the title of the window
* @return {string} - the title of the window
*/
getTitle () {
return this.#options.title
}
/**
* Get the status of the window
* @return {string} - the status of the window
*/
getStatus () {
return this.#options.status
}
/**
* Close the window
* @return {Promise<object>} - the options of the window
*/
async close () {
const { data, err } = await ipc.send('window.close', {
index: this.#senderWindowIndex,
targetWindowIndex: this.#index
})
if (err) {
throw err
}
return data
}
/**
* Shows the window
* @return {Promise<ipc.Result>}
*/
async show () {
const response = await ipc.send('window.show', { index: this.#senderWindowIndex, targetWindowIndex: this.#index })
return this.#updateOptions(response)
}
/**
* Hides the window
* @return {Promise<ipc.Result>}
*/
async hide () {
const response = await ipc.send('window.hide', { index: this.#senderWindowIndex, targetWindowIndex: this.#index })
return this.#updateOptions(response)
}
/**
* Maximize the window
* @return {Promise<ipc.Result>}
*/
async maximize () {
const response = await ipc.send('window.maximize', { index: this.#senderWindowIndex, targetWindowIndex: this.#index })
return this.#updateOptions(response)
}
/**
* Minimize the window
* @return {Promise<ipc.Result>}
*/
async minimize () {
const response = await ipc.send('window.minimize', { index: this.#senderWindowIndex, targetWindowIndex: this.#index })
return this.#updateOptions(response)
}
/**
* Restore the window
* @return {Promise<ipc.Result>}
*/
async restore () {
const response = await ipc.send('window.restore', { index: this.#senderWindowIndex, targetWindowIndex: this.#index })
return this.#updateOptions(response)
}
/**
* Sets the title of the window
* @param {string} title - the title of the window
* @return {Promise<ipc.Result>}
*/
async setTitle (title) {
const response = await ipc.send('window.setTitle', { index: this.#senderWindowIndex, targetWindowIndex: this.#index, value: title })
return this.#updateOptions(response)
}
/**
* Sets the size of the window
* @param {object} opts - an options object
* @param {(number|string)=} opts.width - the width of the window
* @param {(number|string)=} opts.height - the height of the window
* @return {Promise<ipc.Result>}
* @throws {Error} - if the width or height is invalid
*/
async setSize (opts) {
// default values
const options = {
targetWindowIndex: this.#index,
index: this.#senderWindowIndex
}
if ((opts.width != null && typeof opts.width !== 'number' && typeof opts.width !== 'string') ||
(typeof opts.width === 'string' && !isValidPercentageValue(opts.width)) ||
(typeof opts.width === 'number' && !(Number.isInteger(opts.width) && opts.width > 0))) {
throw new Error(`Window width must be an integer number or a string with a valid percentage value from 0 to 100 ending with %. Got ${opts.width} instead.`)
}
if (typeof opts.width === 'string' && isValidPercentageValue(opts.width)) {
options.width = opts.width
}
if (typeof opts.width === 'number') {
options.width = opts.width.toString()
}
if ((opts.height != null && typeof opts.height !== 'number' && typeof opts.height !== 'string') ||
(typeof opts.height === 'string' && !isValidPercentageValue(opts.height)) ||
(typeof opts.height === 'number' && !(Number.isInteger(opts.height) && opts.height > 0))) {
throw new Error(`Window height must be an integer number or a string with a valid percentage value from 0 to 100 ending with %. Got ${opts.height} instead.`)
}
if (typeof opts.height === 'string' && isValidPercentageValue(opts.height)) {
options.height = opts.height
}
if (typeof opts.height === 'number') {
options.height = opts.height.toString()
}
const response = await ipc.send('window.setSize', options)
return this.#updateOptions(response)
}
/**
* Navigate the window to a given path
* @param {object} path - file path
* @return {Promise<ipc.Result>}
*/
async navigate (path) {
const response = await ipc.send('window.navigate', { index: this.#senderWindowIndex, targetWindowIndex: this.#index, url: formatURL(path) })
return this.#updateOptions(response)
}
/**
* Opens the Web Inspector for the window
* @return {Promise<object>}
*/
async showInspector () {
const { data, err } = await ipc.send('window.showInspector', { index: this.#senderWindowIndex, targetWindowIndex: this.#index })
if (err) {
throw err
}
return data
}
/**
* Sets the background color of the window
* @param {object} opts - an options object
* @param {number} opts.red - the red value
* @param {number} opts.green - the green value
* @param {number} opts.blue - the blue value
* @param {number} opts.alpha - the alpha value
* @return {Promise<object>}
*/
async setBackgroundColor (opts) {
const response = await ipc.send('window.setBackgroundColor', { index: this.#senderWindowIndex, targetWindowIndex: this.#index, ...opts })
return this.#updateOptions(response)
}
/**
* Opens a native context menu.
* @param {object} options - an options object
* @return {Promise<object>}
*/
async setContextMenu (options) {
return await menu.context.set(options)
}
/**
* Shows a native open file dialog.
* @param {object} options - an options object
* @return {Promise<string[]>} - an array of file paths
*/
async showOpenFilePicker (options) {
const result = await ipc.request('window.showFileSystemPicker', {
type: 'open',
...options
})
if (result.err) {
throw result.err
}
return result.data.paths
}
/**
* Shows a native save file dialog.
* @param {object} options - an options object
* @return {Promise<string[]>} - an array of file paths
*/
async showSaveFilePicker (options) {
const result = await ipc.request('window.showFileSystemPicker', {
type: 'save',
...options
})
if (result.err) {
throw result.err
}
return result.data.paths[0] ?? null
}
/**
* Shows a native directory dialog.
* @param {object} options - an options object
* @return {Promise<string[]>} - an array of file paths
*/
async showDirectoryFilePicker (options) {
const result = await ipc.request('window.showFileSystemPicker', {
type: 'open',
allowDirs: true,
...options
})
if (result.err) {
throw result.err
}
return result.data.paths
}
/**
* This is a high-level API that you should use instead of `ipc.send` when
* you want to send a message to another window or to the backend.
*
* @param {object} options - an options object
* @param {number=} options.window - the window to send the message to
* @param {boolean=} [options.backend = false] - whether to send the message to the backend
* @param {string} options.event - the event to send
* @param {(string|object)=} options.value - the value to send
* @returns
*/
async send (options) {
if (this.#index !== this.#senderWindowIndex) {
throw new Error('window.send can only be used from the current window')
}
if (!Number.isInteger(options.window) && options.backend !== true) {
throw new Error('window should be an integer')
}
if (options.backend === true && options.window != null) {
throw new Error('backend option cannot be used together with window option')
}
if (typeof options.event !== 'string' || options.event.length === 0) {
throw new Error('event should be a non-empty string')
}
const value = typeof options.value !== 'string' ? JSON.stringify(options.value) : options.value
if (options.backend === true) {
return await ipc.send('process.write', {
index: this.#senderWindowIndex,
event: options.event,
value: value !== undefined ? JSON.stringify(value) : null
})
}
return await ipc.send('window.send', {
index: this.#senderWindowIndex,
targetWindowIndex: options.window,
event: options.event,
value: encodeURIComponent(value)
})
}
/**
* Post a message to a window
* TODO(@jwerle): research using `BroadcastChannel` instead
* @param {object} message
* @return {Promise}
*/
async postMessage (message) {
if (this.#index === this.#senderWindowIndex) {
globalThis.dispatchEvent(new MessageEvent('message', message))
} else {
return await ipc.send('window.send', {
index: this.#senderWindowIndex,
targetWindowIndex: this.#index,
event: 'message',
value: encodeURIComponent(message.data)
})
}
}
/**
* Opens an URL in the default browser.
* @param {object} options
* @returns {Promise<ipc.Result>}
*/
async openExternal (options) {
return await ipc.send('platform.openExternal', options)
}
// public EventEmitter methods
/**
* Adds a listener to the window.
* @param {string} event - the event to listen to
* @param {function(*): void} cb - the callback to call
* @returns {void}
*/
addListener (event, cb) {
if (this.#index !== this.#senderWindowIndex) {
throw new Error('window.addListener can only be used from the current window')
}
if (!(event in this.#listeners)) {
this.#listeners[event] = []
}
this.#listeners[event].push(cb)
globalThis.addEventListener(event, cb)
}
/**
* Adds a listener to the window. An alias for `addListener`.
* @param {string} event - the event to listen to
* @param {function(*): void} cb - the callback to call
* @returns {void}
* @see addListener
*/
on (event, cb) {
if (this.#index !== this.#senderWindowIndex) {
throw new Error('window.on can only be used from the current window')
}
if (!(event in this.#listeners)) {
this.#listeners[event] = []
}
this.#listeners[event].push(cb)
globalThis.addEventListener(event, cb)
}
/**
* Adds a listener to the window. The listener is removed after the first call.
* @param {string} event - the event to listen to
* @param {function(*): void} cb - the callback to call
* @returns {void}
*/
once (event, cb) {
if (this.#index !== this.#senderWindowIndex) {
throw new Error('window.once can only be used from the current window')
}
if (!(event in this.#listeners)) {
this.#listeners[event] = []
}
globalThis.addEventListener(event, cb, { once: true })
}
/**
* Removes a listener from the window.
* @param {string} event - the event to remove the listener from
* @param {function(*): void} cb - the callback to remove
* @returns {void}
*/
removeListener (event, cb) {
if (this.#index !== this.#senderWindowIndex) {
throw new Error('window.removeListener can only be used from the current window')
}
this.#listeners[event] = this.#listeners[event].filter(listener => listener !== cb)
globalThis.removeEventListener(event, cb)
}
/**
* Removes all listeners from the window.
* @param {string} event - the event to remove the listeners from
* @returns {void}
*/
removeAllListeners (event) {
if (this.#index !== this.#senderWindowIndex) {
throw new Error('window.removeAllListeners can only be used from the current window')
}
for (const cb of this.#listeners[event]) {
globalThis.removeEventListener(event, cb)
}
}
/**
* Removes a listener from the window. An alias for `removeListener`.
* @param {string} event - the event to remove the listener from
* @param {function(*): void} cb - the callback to remove
* @returns {void}
* @see removeListener
*/
off (event, cb) {
if (this.#index !== this.#senderWindowIndex) {
throw new Error('window.off can only be used from the current window')
}
this.#listeners[event] = this.#listeners[event].filter(listener => listener !== cb)
globalThis.removeEventListener(event, cb)
}
}
export { hotkey }
export default ApplicationWindow
/**
* @ignore
*/
export const constants = statuses