@bun-native/core 0.0.0-bootstrap.0 → 0.33.0
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/LICENSE +21 -0
- package/README.md +5 -0
- package/bun-native-source.json +107 -0
- package/package.json +32 -1
- package/src/app-menu.ts +271 -0
- package/src/application.ts +2168 -0
- package/src/commit-plan.ts +233 -0
- package/src/context-menus.ts +76 -0
- package/src/dialogs.ts +153 -0
- package/src/display.ts +25 -0
- package/src/drops.ts +95 -0
- package/src/events.ts +331 -0
- package/src/files.ts +253 -0
- package/src/index.ts +88 -0
- package/src/message-dialogs.ts +487 -0
- package/src/notifications.ts +141 -0
- package/src/overlays.ts +55 -0
- package/src/processes.ts +218 -0
- package/src/services.ts +428 -0
- package/src/shortcuts.ts +129 -0
- package/src/splits.ts +34 -0
- package/src/theme.ts +96 -0
- package/src/tree.ts +672 -0
- package/src/types.ts +375 -0
|
@@ -0,0 +1,487 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
KeyModifiers,
|
|
3
|
+
MessageDialogOptions as WireMessageDialogOptions,
|
|
4
|
+
} from '@bun-native/protocol'
|
|
5
|
+
import { NativeServiceError } from './services.ts'
|
|
6
|
+
import { defaultTheme } from './theme.ts'
|
|
7
|
+
import { NativeStateError, type NativeBatch, type NativeNode, type NativeWindow } from './types.ts'
|
|
8
|
+
|
|
9
|
+
/** Buttons in one message dialog. */
|
|
10
|
+
const MAX_MESSAGE_DIALOG_BUTTONS = 4
|
|
11
|
+
/** Dialogs one window holds at a time: the shown one plus those queued behind it. */
|
|
12
|
+
const MAX_MESSAGE_DIALOGS_PER_WINDOW = 8
|
|
13
|
+
const MAX_TITLE_BYTES = 256
|
|
14
|
+
const MAX_MESSAGE_BYTES = 2_048
|
|
15
|
+
const MAX_DETAIL_BYTES = 4_096
|
|
16
|
+
const MAX_LABEL_BYTES = 64
|
|
17
|
+
const MAX_ID_BYTES = 64
|
|
18
|
+
|
|
19
|
+
export interface MessageDialogButton {
|
|
20
|
+
/** Returned in the result. 1-64 UTF-8 bytes without control characters, unique per dialog. */
|
|
21
|
+
readonly id: string
|
|
22
|
+
/** One nonblank line of at most 64 UTF-8 bytes. */
|
|
23
|
+
readonly label: string
|
|
24
|
+
/** Visual emphasis only; `normal` when absent. */
|
|
25
|
+
readonly kind?: 'normal' | 'primary' | 'destructive'
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface MessageDialogOptions {
|
|
29
|
+
/** One nonblank line of at most 256 UTF-8 bytes. */
|
|
30
|
+
readonly title: string
|
|
31
|
+
/** Nonblank, at most 2,048 UTF-8 bytes; line feeds allowed, other control characters not. */
|
|
32
|
+
readonly message: string
|
|
33
|
+
/** Secondary text, at most 4,096 UTF-8 bytes; line feeds allowed. */
|
|
34
|
+
readonly detail?: string
|
|
35
|
+
/** 1-4 buttons, shown left to right in this order. */
|
|
36
|
+
readonly buttons: readonly MessageDialogButton[]
|
|
37
|
+
/** The button focused when the dialog opens; the first button when absent. */
|
|
38
|
+
readonly defaultButton?: string
|
|
39
|
+
/** The button Escape activates. Without one, Escape only dismisses a `dismissible` dialog. */
|
|
40
|
+
readonly cancelButton?: string
|
|
41
|
+
/** Escape (without a cancel button) and a backdrop press resolve `{ kind: 'dismissed' }`. */
|
|
42
|
+
readonly dismissible?: boolean
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export type MessageDialogResult =
|
|
46
|
+
| Readonly<{ kind: 'button'; id: string }>
|
|
47
|
+
| Readonly<{ kind: 'dismissed' }>
|
|
48
|
+
|
|
49
|
+
export interface ConfirmDialogOptions {
|
|
50
|
+
readonly title: string
|
|
51
|
+
readonly message: string
|
|
52
|
+
readonly detail?: string
|
|
53
|
+
/** `OK` when absent. */
|
|
54
|
+
readonly confirmLabel?: string
|
|
55
|
+
/** `Cancel` when absent. */
|
|
56
|
+
readonly cancelLabel?: string
|
|
57
|
+
/** Draws the confirm button as destructive and focuses Cancel by default. */
|
|
58
|
+
readonly destructive?: boolean
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** A validated, immutable copy of the caller's options. */
|
|
62
|
+
export interface MessageDialogSpec {
|
|
63
|
+
readonly title: string
|
|
64
|
+
readonly message: string
|
|
65
|
+
readonly detail: string | undefined
|
|
66
|
+
readonly buttons: readonly Readonly<Required<MessageDialogButton>>[]
|
|
67
|
+
readonly defaultButton: string
|
|
68
|
+
readonly cancelButton: string | undefined
|
|
69
|
+
readonly dismissible: boolean
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const MESSAGE_KEYS = [
|
|
73
|
+
'title',
|
|
74
|
+
'message',
|
|
75
|
+
'detail',
|
|
76
|
+
'buttons',
|
|
77
|
+
'defaultButton',
|
|
78
|
+
'cancelButton',
|
|
79
|
+
'dismissible',
|
|
80
|
+
]
|
|
81
|
+
const CONFIRM_KEYS = ['title', 'message', 'detail', 'confirmLabel', 'cancelLabel', 'destructive']
|
|
82
|
+
const BUTTON_KEYS = ['id', 'label', 'kind']
|
|
83
|
+
const encoder = new TextEncoder()
|
|
84
|
+
|
|
85
|
+
function record(value: unknown, what: string): Record<string, unknown> {
|
|
86
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
87
|
+
throw new TypeError(what + ' must be an object')
|
|
88
|
+
return value as Record<string, unknown>
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function onlyKeys(data: Record<string, unknown>, allowed: readonly string[], what: string) {
|
|
92
|
+
for (const key of Object.keys(data))
|
|
93
|
+
if (!allowed.includes(key)) throw new TypeError('Unknown ' + what + ' option: ' + key)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function text(value: unknown, field: string, limit: number, lines: boolean): string {
|
|
97
|
+
if (typeof value !== 'string' || !value.trim())
|
|
98
|
+
throw new TypeError('Message dialog ' + field + ' must be a nonblank string')
|
|
99
|
+
if (value.length > limit || encoder.encode(value).byteLength > limit)
|
|
100
|
+
throw new TypeError('Message dialog ' + field + ' exceeds ' + limit + ' UTF-8 bytes')
|
|
101
|
+
if (!value.isWellFormed())
|
|
102
|
+
throw new TypeError('Message dialog ' + field + ' contains an unpaired surrogate')
|
|
103
|
+
if ((lines ? /[^\P{Cc}\n]/u : /\p{Cc}/u).test(value))
|
|
104
|
+
throw new TypeError('Message dialog ' + field + ' contains a control character')
|
|
105
|
+
return value
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function optional<T>(data: Record<string, unknown>, key: string, parse: (value: unknown) => T) {
|
|
109
|
+
return data[key] === undefined ? undefined : parse(data[key])
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function button(value: unknown): Readonly<Required<MessageDialogButton>> {
|
|
113
|
+
const data = record(value, 'A message dialog button')
|
|
114
|
+
onlyKeys(data, BUTTON_KEYS, 'message dialog button')
|
|
115
|
+
const kind = data['kind'] ?? 'normal'
|
|
116
|
+
if (kind !== 'normal' && kind !== 'primary' && kind !== 'destructive')
|
|
117
|
+
throw new TypeError('Message dialog button kind must be normal, primary or destructive')
|
|
118
|
+
return Object.freeze({
|
|
119
|
+
// An id is opaque, so surrounding whitespace is kept but blank ids are not.
|
|
120
|
+
id: text(data['id'], 'button id', MAX_ID_BYTES, false),
|
|
121
|
+
label: text(data['label'], 'button label', MAX_LABEL_BYTES, false),
|
|
122
|
+
kind,
|
|
123
|
+
})
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Validate and copy public options; nothing is staged on failure. */
|
|
127
|
+
export function messageDialogSpec(options: MessageDialogOptions): MessageDialogSpec {
|
|
128
|
+
const data = record(options, 'Message dialog options')
|
|
129
|
+
onlyKeys(data, MESSAGE_KEYS, 'message dialog')
|
|
130
|
+
const list = data['buttons']
|
|
131
|
+
if (!Array.isArray(list) || list.length < 1 || list.length > MAX_MESSAGE_DIALOG_BUTTONS)
|
|
132
|
+
throw new TypeError(
|
|
133
|
+
'A message dialog needs between 1 and ' + MAX_MESSAGE_DIALOG_BUTTONS + ' buttons'
|
|
134
|
+
)
|
|
135
|
+
const buttons = Object.freeze(list.map(button))
|
|
136
|
+
const ids = new Set(buttons.map((entry) => entry.id))
|
|
137
|
+
if (ids.size !== buttons.length) throw new TypeError('Message dialog button ids must be unique')
|
|
138
|
+
const reference = (field: string) => (value: unknown) => {
|
|
139
|
+
if (typeof value !== 'string' || !ids.has(value))
|
|
140
|
+
throw new TypeError('Message dialog ' + field + ' must name one of its buttons')
|
|
141
|
+
return value
|
|
142
|
+
}
|
|
143
|
+
const dismissible = data['dismissible'] ?? false
|
|
144
|
+
if (typeof dismissible !== 'boolean')
|
|
145
|
+
throw new TypeError('Message dialog dismissible must be a boolean')
|
|
146
|
+
return Object.freeze({
|
|
147
|
+
title: text(data['title'], 'title', MAX_TITLE_BYTES, false),
|
|
148
|
+
message: text(data['message'], 'message', MAX_MESSAGE_BYTES, true),
|
|
149
|
+
detail: optional(data, 'detail', (value) => text(value, 'detail', MAX_DETAIL_BYTES, true)),
|
|
150
|
+
buttons,
|
|
151
|
+
defaultButton: optional(data, 'defaultButton', reference('defaultButton')) ?? buttons[0]!.id,
|
|
152
|
+
cancelButton: optional(data, 'cancelButton', reference('cancelButton')),
|
|
153
|
+
dismissible,
|
|
154
|
+
})
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Cancel then confirm, Escape cancels; a destructive confirmation focuses Cancel. */
|
|
158
|
+
export function confirmDialogSpec(options: ConfirmDialogOptions): MessageDialogSpec {
|
|
159
|
+
const data = record(options, 'Confirm dialog options')
|
|
160
|
+
onlyKeys(data, CONFIRM_KEYS, 'confirm dialog')
|
|
161
|
+
const destructive = data['destructive'] ?? false
|
|
162
|
+
if (typeof destructive !== 'boolean')
|
|
163
|
+
throw new TypeError('Confirm dialog destructive must be a boolean')
|
|
164
|
+
return messageDialogSpec({
|
|
165
|
+
title: data['title'] as string,
|
|
166
|
+
message: data['message'] as string,
|
|
167
|
+
...(data['detail'] === undefined ? {} : { detail: data['detail'] as string }),
|
|
168
|
+
buttons: [
|
|
169
|
+
{ id: 'cancel', label: (data['cancelLabel'] ?? 'Cancel') as string },
|
|
170
|
+
{
|
|
171
|
+
id: 'confirm',
|
|
172
|
+
label: (data['confirmLabel'] ?? 'OK') as string,
|
|
173
|
+
kind: destructive ? 'destructive' : 'primary',
|
|
174
|
+
},
|
|
175
|
+
],
|
|
176
|
+
defaultButton: destructive ? 'cancel' : 'confirm',
|
|
177
|
+
cancelButton: 'cancel',
|
|
178
|
+
})
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const { colors, space, fontSizes } = defaultTheme.tokens
|
|
182
|
+
/** Not a host default: the one color the default theme has no token for. */
|
|
183
|
+
const DESTRUCTIVE = 0xb42318
|
|
184
|
+
const BUTTON_COLORS = {
|
|
185
|
+
normal: { background: colors['divider']!, color: colors['text']! },
|
|
186
|
+
primary: { background: colors['accent']!, color: colors['on_accent']! },
|
|
187
|
+
destructive: { background: DESTRUCTIVE, color: colors['on_accent']! },
|
|
188
|
+
} as const
|
|
189
|
+
|
|
190
|
+
type Outcome = { result: MessageDialogResult } | { error: Error }
|
|
191
|
+
|
|
192
|
+
/** The OS backend (Windows task dialogs, macOS alert sheets): the window supplies the host calls. */
|
|
193
|
+
export interface NativeMessageDialogBackend {
|
|
194
|
+
allocate(): number
|
|
195
|
+
show(id: number, options: WireMessageDialogOptions): Promise<void>
|
|
196
|
+
/** Resolves once the host no longer owns the dialog (it may already be gone). */
|
|
197
|
+
close(id: number): Promise<void>
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** The wire form of a validated spec; button `kind` has no OS equivalent. */
|
|
201
|
+
function wireOptions(spec: MessageDialogSpec): WireMessageDialogOptions {
|
|
202
|
+
return {
|
|
203
|
+
title: spec.title,
|
|
204
|
+
message: spec.message,
|
|
205
|
+
...(spec.detail === undefined ? {} : { detail: spec.detail }),
|
|
206
|
+
buttons: spec.buttons.map(({ id, label }) => ({ id, label })),
|
|
207
|
+
default_button: spec.defaultButton,
|
|
208
|
+
...(spec.cancelButton === undefined ? {} : { cancel_button: spec.cancelButton }),
|
|
209
|
+
...(spec.dismissible ? { dismissible: true as const } : {}),
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
class Dialog {
|
|
214
|
+
state: 'queued' | 'opening' | 'open' | 'closing' | 'settled' = 'queued'
|
|
215
|
+
layer: NativeNode<'overlay'> | undefined
|
|
216
|
+
/** The host's identity for an OS dialog the host still owns. */
|
|
217
|
+
nativeId: number | undefined
|
|
218
|
+
readonly buttons = new Map<NativeNode, string>()
|
|
219
|
+
outcome: Outcome | undefined
|
|
220
|
+
detach: () => void = () => {}
|
|
221
|
+
readonly result: Promise<MessageDialogResult>
|
|
222
|
+
resolve!: (result: MessageDialogResult) => void
|
|
223
|
+
reject!: (error: Error) => void
|
|
224
|
+
|
|
225
|
+
constructor(readonly spec: MessageDialogSpec) {
|
|
226
|
+
this.result = new Promise((resolve, reject) => {
|
|
227
|
+
this.resolve = resolve
|
|
228
|
+
this.reject = reject
|
|
229
|
+
})
|
|
230
|
+
// The caller may not await before revocation rejects it.
|
|
231
|
+
void this.result.catch(() => {})
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** The routed native event fields a dialog acts on. */
|
|
236
|
+
export type DialogInput =
|
|
237
|
+
| { type: 'click' }
|
|
238
|
+
| { type: 'key_down'; key: string; modifiers: KeyModifiers }
|
|
239
|
+
| { type: string }
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* One window's message dialogs. They are shown one at a time in call order:
|
|
243
|
+
* a later call waits, unseen, until every earlier dialog has settled and its
|
|
244
|
+
* layer has been removed. Input routed through a dialog's layer is handled
|
|
245
|
+
* here during ingestion, never through the callback queue, so a listener may
|
|
246
|
+
* await a dialog without blocking that dialog's own buttons.
|
|
247
|
+
*/
|
|
248
|
+
export class MessageDialogs {
|
|
249
|
+
private readonly dialogs: Dialog[] = []
|
|
250
|
+
private readonly native = new Map<number, Dialog>()
|
|
251
|
+
|
|
252
|
+
/** `backend` is read when a dialog opens: it is the OS backend or the overlay. */
|
|
253
|
+
constructor(
|
|
254
|
+
private readonly window: NativeWindow,
|
|
255
|
+
private readonly backend: () => NativeMessageDialogBackend | undefined = () => undefined
|
|
256
|
+
) {}
|
|
257
|
+
|
|
258
|
+
/** The host finished a dialog it owned. A result for a closed one is dropped. */
|
|
259
|
+
completeNative(
|
|
260
|
+
id: number,
|
|
261
|
+
result: { kind: 'button'; id: string } | { kind: 'dismissed' } | { kind: 'failed' }
|
|
262
|
+
): void {
|
|
263
|
+
const dialog = this.native.get(id)
|
|
264
|
+
if (!dialog) return
|
|
265
|
+
this.native.delete(id)
|
|
266
|
+
dialog.nativeId = undefined
|
|
267
|
+
if (dialog.state === 'closing' || dialog.state === 'settled') return
|
|
268
|
+
const outcome: Outcome =
|
|
269
|
+
result.kind === 'failed'
|
|
270
|
+
? {
|
|
271
|
+
error: new NativeServiceError(
|
|
272
|
+
'message_dialogs',
|
|
273
|
+
'native_failure',
|
|
274
|
+
'The native message dialog failed'
|
|
275
|
+
),
|
|
276
|
+
}
|
|
277
|
+
: { result }
|
|
278
|
+
if (dialog.state === 'opening') {
|
|
279
|
+
// The open call finishes it when the host's reply arrives.
|
|
280
|
+
dialog.outcome = outcome
|
|
281
|
+
dialog.state = 'closing'
|
|
282
|
+
} else this.finish(dialog, outcome)
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
show(spec: MessageDialogSpec, signal: AbortSignal | undefined): Promise<MessageDialogResult> {
|
|
286
|
+
if (signal?.aborted)
|
|
287
|
+
return Promise.reject(
|
|
288
|
+
new NativeServiceError('message_dialogs', 'cancelled', 'The message dialog was cancelled')
|
|
289
|
+
)
|
|
290
|
+
if (this.dialogs.length >= MAX_MESSAGE_DIALOGS_PER_WINDOW)
|
|
291
|
+
return Promise.reject(
|
|
292
|
+
new NativeServiceError(
|
|
293
|
+
'message_dialogs',
|
|
294
|
+
'limit_exceeded',
|
|
295
|
+
'This window already holds ' + MAX_MESSAGE_DIALOGS_PER_WINDOW + ' message dialogs'
|
|
296
|
+
)
|
|
297
|
+
)
|
|
298
|
+
const dialog = new Dialog(spec)
|
|
299
|
+
if (signal) {
|
|
300
|
+
const abort = () =>
|
|
301
|
+
this.decide(dialog, {
|
|
302
|
+
error: new NativeServiceError(
|
|
303
|
+
'message_dialogs',
|
|
304
|
+
'cancelled',
|
|
305
|
+
'The message dialog was cancelled'
|
|
306
|
+
),
|
|
307
|
+
})
|
|
308
|
+
signal.addEventListener('abort', abort, { once: true })
|
|
309
|
+
dialog.detach = () => signal.removeEventListener('abort', abort)
|
|
310
|
+
}
|
|
311
|
+
this.dialogs.push(dialog)
|
|
312
|
+
if (this.dialogs.length === 1) void this.open(dialog)
|
|
313
|
+
return dialog.result
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* Handle a routed event whose committed path is `path`. Returns true when
|
|
318
|
+
* the event belongs to a dialog layer: it is then not delivered to
|
|
319
|
+
* application listeners.
|
|
320
|
+
*/
|
|
321
|
+
receive(event: DialogInput, path: readonly NativeNode[], target: NativeNode): boolean {
|
|
322
|
+
const dialog = this.dialogs[0]
|
|
323
|
+
if (!dialog?.layer || !path.includes(dialog.layer)) return false
|
|
324
|
+
const { spec } = dialog
|
|
325
|
+
if (event.type === 'click') {
|
|
326
|
+
const id = dialog.buttons.get(target)
|
|
327
|
+
if (id !== undefined) this.decide(dialog, { result: { kind: 'button', id } })
|
|
328
|
+
} else if (event.type === 'key_down' && 'key' in event && event.key === 'escape') {
|
|
329
|
+
const { control, alt, shift, platform, function: fn } = event.modifiers
|
|
330
|
+
if (control || alt || shift || platform || fn) return true
|
|
331
|
+
if (spec.cancelButton !== undefined)
|
|
332
|
+
this.decide(dialog, { result: { kind: 'button', id: spec.cancelButton } })
|
|
333
|
+
else if (spec.dismissible) this.decide(dialog, { result: { kind: 'dismissed' } })
|
|
334
|
+
} else if (event.type === 'pointer_down' && target === dialog.layer && spec.dismissible)
|
|
335
|
+
this.decide(dialog, { result: { kind: 'dismissed' } })
|
|
336
|
+
return true
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** Owner close and shutdown: every dialog rejects at once; nothing is sent. */
|
|
340
|
+
revoke(): void {
|
|
341
|
+
const error = new NativeStateError('invalid_handle', 'Message dialog owner window was closed')
|
|
342
|
+
// The host closes its own dialogs with the owner window or at shutdown.
|
|
343
|
+
this.native.clear()
|
|
344
|
+
for (const dialog of this.dialogs.splice(0)) this.settle(dialog, { error })
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
private async openNative(dialog: Dialog, backend: NativeMessageDialogBackend): Promise<void> {
|
|
348
|
+
dialog.state = 'opening'
|
|
349
|
+
let id: number
|
|
350
|
+
try {
|
|
351
|
+
id = backend.allocate()
|
|
352
|
+
dialog.nativeId = id
|
|
353
|
+
this.native.set(id, dialog)
|
|
354
|
+
await backend.show(id, wireOptions(dialog.spec))
|
|
355
|
+
} catch (error) {
|
|
356
|
+
if (dialog.nativeId !== undefined) this.native.delete(dialog.nativeId)
|
|
357
|
+
dialog.nativeId = undefined
|
|
358
|
+
this.finish(dialog, { error: error instanceof Error ? error : new Error(String(error)) })
|
|
359
|
+
return
|
|
360
|
+
}
|
|
361
|
+
if (dialog.state === 'opening') dialog.state = 'open'
|
|
362
|
+
else if (dialog.state === 'closing') {
|
|
363
|
+
// Aborted while the host was showing it, or finished before this reply.
|
|
364
|
+
if (dialog.nativeId !== undefined) await this.close(dialog)
|
|
365
|
+
else if (dialog.outcome) this.finish(dialog, dialog.outcome)
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
private async open(dialog: Dialog): Promise<void> {
|
|
370
|
+
const backend = this.backend()
|
|
371
|
+
if (backend) return this.openNative(dialog, backend)
|
|
372
|
+
dialog.state = 'opening'
|
|
373
|
+
try {
|
|
374
|
+
await this.window.batch((batch) => build(batch, this.window.root, dialog))
|
|
375
|
+
} catch (error) {
|
|
376
|
+
dialog.layer = undefined
|
|
377
|
+
dialog.buttons.clear()
|
|
378
|
+
this.finish(dialog, { error: error instanceof Error ? error : new Error(String(error)) })
|
|
379
|
+
return
|
|
380
|
+
}
|
|
381
|
+
if (dialog.state === 'opening') dialog.state = 'open'
|
|
382
|
+
else if (dialog.state === 'closing') await this.close(dialog)
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/** The first decision wins; the result is delivered after the layer is removed. */
|
|
386
|
+
private decide(dialog: Dialog, outcome: Outcome): void {
|
|
387
|
+
if (dialog.state === 'closing' || dialog.state === 'settled') return
|
|
388
|
+
if (dialog.state === 'queued') {
|
|
389
|
+
this.finish(dialog, outcome)
|
|
390
|
+
return
|
|
391
|
+
}
|
|
392
|
+
dialog.outcome = outcome
|
|
393
|
+
const opened = dialog.state === 'open'
|
|
394
|
+
dialog.state = 'closing'
|
|
395
|
+
if (opened) void this.close(dialog)
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
private async close(dialog: Dialog): Promise<void> {
|
|
399
|
+
const id = dialog.nativeId
|
|
400
|
+
if (id !== undefined) {
|
|
401
|
+
// Delivery stops first; a result already queued for it is then dropped.
|
|
402
|
+
this.native.delete(id)
|
|
403
|
+
dialog.nativeId = undefined
|
|
404
|
+
try {
|
|
405
|
+
await this.backend()!.close(id)
|
|
406
|
+
} catch (error) {
|
|
407
|
+
this.finish(dialog, { error: error instanceof Error ? error : new Error(String(error)) })
|
|
408
|
+
return
|
|
409
|
+
}
|
|
410
|
+
this.finish(dialog, dialog.outcome!)
|
|
411
|
+
return
|
|
412
|
+
}
|
|
413
|
+
const layer = dialog.layer!
|
|
414
|
+
try {
|
|
415
|
+
await this.window.batch((batch) => batch.remove(layer))
|
|
416
|
+
} catch (error) {
|
|
417
|
+
// A closed owner has already settled it; any other failure is reported.
|
|
418
|
+
this.finish(dialog, { error: error instanceof Error ? error : new Error(String(error)) })
|
|
419
|
+
return
|
|
420
|
+
}
|
|
421
|
+
this.finish(dialog, dialog.outcome!)
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
private finish(dialog: Dialog, outcome: Outcome): void {
|
|
425
|
+
if (dialog.state === 'settled') return
|
|
426
|
+
const head = this.dialogs[0] === dialog
|
|
427
|
+
this.dialogs.splice(this.dialogs.indexOf(dialog), 1)
|
|
428
|
+
this.settle(dialog, outcome)
|
|
429
|
+
const next = this.dialogs[0]
|
|
430
|
+
if (head && next) void this.open(next)
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
private settle(dialog: Dialog, outcome: Outcome): void {
|
|
434
|
+
dialog.state = 'settled'
|
|
435
|
+
dialog.detach()
|
|
436
|
+
if ('error' in outcome) dialog.reject(outcome.error)
|
|
437
|
+
else dialog.resolve(Object.freeze(outcome.result))
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/** One window-anchored modal layer with a fixed, theme-default layout. */
|
|
442
|
+
function build(batch: NativeBatch, root: NativeNode<'box'>, dialog: Dialog): void {
|
|
443
|
+
const { spec } = dialog
|
|
444
|
+
const layer = batch.create({
|
|
445
|
+
kind: 'overlay',
|
|
446
|
+
modal: true,
|
|
447
|
+
style: { align_items: 'center', justify_content: 'center', padding: space['lg']! },
|
|
448
|
+
})
|
|
449
|
+
// A one-pixel divider frame without the optional decoration capability.
|
|
450
|
+
const frame = batch.create({
|
|
451
|
+
kind: 'box',
|
|
452
|
+
style: { width: 'fill', max_width: 420, padding: 1, background: colors['divider']! },
|
|
453
|
+
})
|
|
454
|
+
const panel = batch.create({
|
|
455
|
+
kind: 'box',
|
|
456
|
+
style: { gap: space['md']!, padding: space['lg']!, background: colors['surface']! },
|
|
457
|
+
})
|
|
458
|
+
batch.append(root, layer)
|
|
459
|
+
batch.append(layer, frame)
|
|
460
|
+
batch.append(frame, panel)
|
|
461
|
+
const line = (value: string, font: number, color: number) =>
|
|
462
|
+
batch.append(
|
|
463
|
+
panel,
|
|
464
|
+
batch.create({ kind: 'text', text: value, style: { font_size: font, color } })
|
|
465
|
+
)
|
|
466
|
+
line(spec.title, fontSizes['body']!, colors['text']!)
|
|
467
|
+
line(spec.message, fontSizes['sm']!, colors['text']!)
|
|
468
|
+
if (spec.detail !== undefined) line(spec.detail, fontSizes['sm']!, colors['disabled']!)
|
|
469
|
+
const row = batch.create({
|
|
470
|
+
kind: 'box',
|
|
471
|
+
style: { direction: 'row', gap: space['sm']!, justify_content: 'end' },
|
|
472
|
+
})
|
|
473
|
+
batch.append(panel, row)
|
|
474
|
+
let focused: NativeNode<'button'> | undefined
|
|
475
|
+
for (const entry of spec.buttons) {
|
|
476
|
+
const node = batch.create({
|
|
477
|
+
kind: 'button',
|
|
478
|
+
text: entry.label,
|
|
479
|
+
style: { padding: space['sm']!, ...BUTTON_COLORS[entry.kind] },
|
|
480
|
+
})
|
|
481
|
+
batch.append(row, node)
|
|
482
|
+
dialog.buttons.set(node, entry.id)
|
|
483
|
+
if (entry.id === spec.defaultButton) focused = node
|
|
484
|
+
}
|
|
485
|
+
batch.focus(focused!)
|
|
486
|
+
dialog.layer = layer
|
|
487
|
+
}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import {
|
|
2
|
+
MAX_NOTIFICATION_BODY_BYTES,
|
|
3
|
+
MAX_NOTIFICATION_TITLE_BYTES,
|
|
4
|
+
type NotificationDismissal,
|
|
5
|
+
} from '@bun-native/protocol'
|
|
6
|
+
import type { Listener } from './types.ts'
|
|
7
|
+
|
|
8
|
+
export interface NotificationOptions {
|
|
9
|
+
/** One nonempty line of plain text, at most 256 UTF-8 bytes. */
|
|
10
|
+
readonly title: string
|
|
11
|
+
/** Plain text, at most 2048 UTF-8 bytes; line feeds are the only control characters. */
|
|
12
|
+
readonly body?: string
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export type NotificationEvent =
|
|
16
|
+
| Readonly<{
|
|
17
|
+
type: 'notification_activated'
|
|
18
|
+
sequence: number
|
|
19
|
+
notification: NativeNotification
|
|
20
|
+
/** Aborted when the notification is withdrawn, dismissed, its window closes or the app stops. */
|
|
21
|
+
signal: AbortSignal
|
|
22
|
+
}>
|
|
23
|
+
| Readonly<{
|
|
24
|
+
type: 'notification_dismissed'
|
|
25
|
+
sequence: number
|
|
26
|
+
notification: NativeNotification
|
|
27
|
+
/** `expired` by timeout, `dismissed` by the user, `closed` by the server otherwise. */
|
|
28
|
+
reason: NotificationDismissal
|
|
29
|
+
signal: AbortSignal
|
|
30
|
+
}>
|
|
31
|
+
|
|
32
|
+
export interface NativeNotification {
|
|
33
|
+
readonly title: string
|
|
34
|
+
readonly body: string
|
|
35
|
+
/** False when the notification server offers no actions: no activation can arrive. */
|
|
36
|
+
readonly activatable: boolean
|
|
37
|
+
/** False once withdrawn, dismissed or revoked; no later activation is delivered. */
|
|
38
|
+
readonly active: boolean
|
|
39
|
+
/** Idempotent. Delivery stops immediately; resolves after the server closes it. */
|
|
40
|
+
withdraw(): Promise<void>
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const OPTION_KEYS = ['title', 'body']
|
|
44
|
+
const encoder = new TextEncoder()
|
|
45
|
+
|
|
46
|
+
export function notificationRequest(options: NotificationOptions): { title: string; body: string } {
|
|
47
|
+
if (!options || typeof options !== 'object' || Array.isArray(options))
|
|
48
|
+
throw new TypeError('Notification options must be an object')
|
|
49
|
+
if (Object.keys(options).some((key) => !OPTION_KEYS.includes(key)))
|
|
50
|
+
throw new TypeError('Unknown notification option')
|
|
51
|
+
const { title } = options
|
|
52
|
+
const body = Object.hasOwn(options, 'body') ? options.body : ''
|
|
53
|
+
if (
|
|
54
|
+
typeof title !== 'string' ||
|
|
55
|
+
!title ||
|
|
56
|
+
!title.isWellFormed() ||
|
|
57
|
+
encoder.encode(title).byteLength > MAX_NOTIFICATION_TITLE_BYTES ||
|
|
58
|
+
/\p{Cc}/u.test(title)
|
|
59
|
+
)
|
|
60
|
+
throw new TypeError(
|
|
61
|
+
'Notification title must be one nonempty line of at most 256 UTF-8 bytes without control characters'
|
|
62
|
+
)
|
|
63
|
+
if (
|
|
64
|
+
typeof body !== 'string' ||
|
|
65
|
+
!body.isWellFormed() ||
|
|
66
|
+
encoder.encode(body).byteLength > MAX_NOTIFICATION_BODY_BYTES ||
|
|
67
|
+
/[^\P{Cc}\n]/u.test(body)
|
|
68
|
+
)
|
|
69
|
+
throw new TypeError(
|
|
70
|
+
'Notification body must be at most 2048 UTF-8 bytes with no control characters other than line feeds'
|
|
71
|
+
)
|
|
72
|
+
return { title, body }
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Internal registry entry. Consumers only receive its frozen handle. */
|
|
76
|
+
export class NotificationRegistration {
|
|
77
|
+
readonly handle: NativeNotification
|
|
78
|
+
readonly controller = new AbortController()
|
|
79
|
+
listener: Listener<NotificationEvent> | undefined
|
|
80
|
+
activatable = false
|
|
81
|
+
private ended = false
|
|
82
|
+
private withdrawing: Promise<void> | undefined
|
|
83
|
+
|
|
84
|
+
constructor(
|
|
85
|
+
readonly id: number,
|
|
86
|
+
readonly windowId: number,
|
|
87
|
+
title: string,
|
|
88
|
+
body: string,
|
|
89
|
+
listener: Listener<NotificationEvent>,
|
|
90
|
+
withdraw: (registration: NotificationRegistration) => Promise<void>
|
|
91
|
+
) {
|
|
92
|
+
this.listener = listener
|
|
93
|
+
this.handle = publicHandle(this, title, body, withdraw)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
withdraw(withdraw: (registration: NotificationRegistration) => Promise<void>): Promise<void> {
|
|
97
|
+
this.withdrawing ??= this.ended ? Promise.resolve() : withdraw(this)
|
|
98
|
+
return this.withdrawing
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Accepts activations. */
|
|
102
|
+
get live(): boolean {
|
|
103
|
+
return !this.ended
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** A queued callback, including the final dismissal, may still run. */
|
|
107
|
+
get deliverable(): boolean {
|
|
108
|
+
return this.listener !== undefined
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The server removed it: no activation follows, but the dismissal is delivered. */
|
|
112
|
+
end(): void {
|
|
113
|
+
this.ended = true
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Synchronous local revocation; the server notification is closed separately. */
|
|
117
|
+
revoke(): void {
|
|
118
|
+
this.ended = true
|
|
119
|
+
this.listener = undefined
|
|
120
|
+
this.controller.abort()
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function publicHandle(
|
|
125
|
+
registration: NotificationRegistration,
|
|
126
|
+
title: string,
|
|
127
|
+
body: string,
|
|
128
|
+
withdraw: (registration: NotificationRegistration) => Promise<void>
|
|
129
|
+
): NativeNotification {
|
|
130
|
+
return Object.freeze({
|
|
131
|
+
title,
|
|
132
|
+
body,
|
|
133
|
+
get activatable() {
|
|
134
|
+
return registration.activatable
|
|
135
|
+
},
|
|
136
|
+
get active() {
|
|
137
|
+
return registration.live
|
|
138
|
+
},
|
|
139
|
+
withdraw: () => registration.withdraw(withdraw),
|
|
140
|
+
})
|
|
141
|
+
}
|
package/src/overlays.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
DismissRequestEvent,
|
|
3
|
+
KeyEvent,
|
|
4
|
+
NativeNode,
|
|
5
|
+
NativeWindow,
|
|
6
|
+
PointerEvent,
|
|
7
|
+
} from './types.ts'
|
|
8
|
+
|
|
9
|
+
export type DismissEvent =
|
|
10
|
+
| { readonly reason: 'escape'; readonly event: KeyEvent<'key_down'> }
|
|
11
|
+
| { readonly reason: 'backdrop'; readonly event: PointerEvent<'pointer_down'> }
|
|
12
|
+
| { readonly reason: 'blur'; readonly event: DismissRequestEvent }
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Observe an overlay's dismissal requests: an unmodified Escape whose native
|
|
16
|
+
* focus route passes through the overlay, or a press on a window overlay's own
|
|
17
|
+
* backdrop (not on any descendant). The innermost overlay handles Escape first
|
|
18
|
+
* and stops it, so one press closes one layer. Removing the overlay, closing
|
|
19
|
+
* the window or calling the returned function revokes every registration.
|
|
20
|
+
*
|
|
21
|
+
* A popup window overlay (`surface: 'window'`) also reports `blur` when its
|
|
22
|
+
* parent window stops being active. While a popup is open the parent window's
|
|
23
|
+
* key events target it, so Escape reaches it without moving focus.
|
|
24
|
+
*
|
|
25
|
+
* This occupies the overlay's bubbling `key_down`, `pointer_down` and
|
|
26
|
+
* `dismiss` registrations; capture-phase listeners stay available. Nothing is removed
|
|
27
|
+
* natively until the listener commits a batch.
|
|
28
|
+
*/
|
|
29
|
+
export function onDismiss(
|
|
30
|
+
window: NativeWindow,
|
|
31
|
+
overlay: NativeNode<'overlay'>,
|
|
32
|
+
listener: (event: DismissEvent) => void | Promise<void>
|
|
33
|
+
): () => void {
|
|
34
|
+
const keys = window.on(overlay, 'key_down', (event) => {
|
|
35
|
+
const { control, alt, shift, platform, function: fn } = event.modifiers
|
|
36
|
+
if (event.key !== 'escape' || control || alt || shift || platform || fn) return
|
|
37
|
+
event.stopPropagation()
|
|
38
|
+
return listener({ reason: 'escape', event })
|
|
39
|
+
})
|
|
40
|
+
const presses = window.on(overlay, 'pointer_down', (event) => {
|
|
41
|
+
if (event.node !== overlay) return
|
|
42
|
+
event.stopPropagation()
|
|
43
|
+
return listener({ reason: 'backdrop', event })
|
|
44
|
+
})
|
|
45
|
+
const requests = window.on(overlay, 'dismiss', (event) => {
|
|
46
|
+
if (event.node !== overlay) return
|
|
47
|
+
event.stopPropagation()
|
|
48
|
+
return listener({ reason: 'blur', event })
|
|
49
|
+
})
|
|
50
|
+
return () => {
|
|
51
|
+
keys()
|
|
52
|
+
presses()
|
|
53
|
+
requests()
|
|
54
|
+
}
|
|
55
|
+
}
|