@ng-desktop/platform 0.0.0-stage → 0.4.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.
@@ -0,0 +1,421 @@
1
+ import { computeFuzzyFilterFallback, computeHashFallback, InMemoryFsStore, resolveDefaultAppId, } from './bridge-fs-compute.js';
2
+ import { InMemorySqliteStore, resolveNativeImageAsset } from './bridge-sqlite.js';
3
+ /**
4
+ * Ensures `globalThis.__NG_NATIVE__` is initialized.
5
+ * In the Rust native runtime (`JscEngine` / `QuickJsEngine`), the host injects this at startup;
6
+ * in Node/Vitest unit tests, this provides an identical in-memory command queue.
7
+ */
8
+ export function ensureNgNativeBridge() {
9
+ if (globalThis.__NG_NATIVE__) {
10
+ return globalThis.__NG_NATIVE__;
11
+ }
12
+ if (typeof __NG_DESKTOP_PROD_BUNDLE__ === 'undefined' || !__NG_DESKTOP_PROD_BUNDLE__) {
13
+ let queue = [];
14
+ let batchDepth = 0;
15
+ const batchBuffer = [];
16
+ const emit = (cmd) => {
17
+ if (batchDepth > 0) {
18
+ batchBuffer.push(cmd);
19
+ }
20
+ else {
21
+ queue.push(cmd);
22
+ }
23
+ };
24
+ let systemTheme = 'dark';
25
+ let clipboardText = '';
26
+ const sqliteStore = new InMemorySqliteStore();
27
+ const fsStore = new InMemoryFsStore();
28
+ let windowGeometry = {
29
+ width: 1020,
30
+ height: 720,
31
+ x: null,
32
+ y: null,
33
+ maximized: false,
34
+ };
35
+ let appMenuItems = [];
36
+ let trayState = {
37
+ visible: false,
38
+ icon: '',
39
+ tooltip: '',
40
+ menuItems: [],
41
+ };
42
+ let shortcuts = [];
43
+ let nextConfirmResponse = null;
44
+ let networkStatus = {
45
+ online: true,
46
+ metered: false,
47
+ connectivity: 'full',
48
+ };
49
+ const systemLocale = (typeof Intl !== 'undefined' ? Intl.DateTimeFormat().resolvedOptions().locale : '') ||
50
+ 'en-US';
51
+ const systemTimezone = (typeof Intl !== 'undefined' ? Intl.DateTimeFormat().resolvedOptions().timeZone : '') ||
52
+ 'UTC';
53
+ const systemErrors = [];
54
+ const httpEndpoints = new Map();
55
+ let httpConfig = {
56
+ platform: 'js-fallback',
57
+ useFetchTransport: true,
58
+ interceptorsEnabled: true,
59
+ xsrfEnabled: true,
60
+ xsrfCookieName: 'XSRF-TOKEN',
61
+ xsrfHeaderName: 'X-XSRF-TOKEN',
62
+ xsrfTokenValue: '',
63
+ jsonpEnabled: false,
64
+ requestsViaParent: false,
65
+ maxParallelConnections: 24,
66
+ cacheEnabled: true,
67
+ timeoutMs: 15_000,
68
+ };
69
+ const listenersByNode = new Map();
70
+ let nextListenerId = 1;
71
+ const escapeNewlines = (value) => value.replace(/\r?\n/g, '\u001e');
72
+ const fallbackBridge = {
73
+ registerStyle(cls, bg = 'none', fg = 'none', pad = 0, space = 0, extras = '') {
74
+ const extraTrimmed = extras.trim();
75
+ emit(extraTrimmed
76
+ ? `style ${cls} ${bg} ${fg} ${pad} ${space} ${extraTrimmed}`
77
+ : `style ${cls} ${bg} ${fg} ${pad} ${space}`);
78
+ },
79
+ declareSignal(name, initial = 0) {
80
+ emit(`signal ${name} ${initial}`);
81
+ },
82
+ createElement(id, tag) {
83
+ emit(`create ${id} ${tag}`);
84
+ return id;
85
+ },
86
+ createComment(id, text = 'anchor') {
87
+ emit(`comment ${id} ${text}`);
88
+ return id;
89
+ },
90
+ setText(id, text) {
91
+ emit(`text ${id} ${escapeNewlines(text)}`);
92
+ },
93
+ setAttribute(id, key, value) {
94
+ emit(`attr ${id} ${key} ${escapeNewlines(value)}`);
95
+ },
96
+ setWindowIcon(id, appId, icoPath) {
97
+ emit(`icon ${id} ${appId} ${icoPath}`);
98
+ },
99
+ appendChild(parent, child) {
100
+ emit(`append ${parent} ${child}`);
101
+ },
102
+ insertBefore(parent, child, refChild) {
103
+ if (refChild) {
104
+ emit(`insert_before ${parent} ${child} ${refChild}`);
105
+ }
106
+ else {
107
+ emit(`insert_before ${parent} ${child}`);
108
+ }
109
+ },
110
+ removeChild(parent, child) {
111
+ emit(`remove_child ${parent} ${child}`);
112
+ },
113
+ addClass(id, className) {
114
+ emit(`add_class ${id} ${className}`);
115
+ },
116
+ removeClass(id, className) {
117
+ emit(`remove_class ${id} ${className}`);
118
+ },
119
+ bindText(id, signalName, template) {
120
+ emit(`bind_text ${id} ${signalName} ${template}`);
121
+ },
122
+ bindAttr(id, attrKey, signalName, template = '{}') {
123
+ emit(`bind_attr ${id} ${attrKey} ${signalName} ${template}`);
124
+ },
125
+ bindVisible(id, signalName, op = '!=', rhs = 0) {
126
+ emit(`bind_visible ${id} ${signalName} ${op} ${rhs}`);
127
+ },
128
+ onAdd(id, eventName, signalName, delta = 1) {
129
+ emit(`on_add ${id} ${eventName} ${signalName} ${delta}`);
130
+ },
131
+ onSet(id, eventName, signalName, value = 0) {
132
+ emit(`on_set ${id} ${eventName} ${signalName} ${value}`);
133
+ },
134
+ listen(id, eventName, callback) {
135
+ const lid = nextListenerId++;
136
+ let byEvent = listenersByNode.get(id);
137
+ if (!byEvent) {
138
+ byEvent = new Map();
139
+ listenersByNode.set(id, byEvent);
140
+ }
141
+ let callbacks = byEvent.get(eventName);
142
+ if (!callbacks) {
143
+ callbacks = new Map();
144
+ byEvent.set(eventName, callbacks);
145
+ }
146
+ callbacks.set(lid, callback);
147
+ return () => {
148
+ callbacks.delete(lid);
149
+ if (callbacks.size === 0) {
150
+ byEvent.delete(eventName);
151
+ if (byEvent.size === 0) {
152
+ listenersByNode.delete(id);
153
+ }
154
+ }
155
+ };
156
+ },
157
+ destroyNode(id) {
158
+ listenersByNode.delete(id);
159
+ emit(`destroy ${id}`);
160
+ },
161
+ getSystemTheme() {
162
+ return systemTheme;
163
+ },
164
+ setSystemTheme(theme) {
165
+ systemTheme = theme === 'light' ? 'light' : 'dark';
166
+ },
167
+ getClipboard() {
168
+ return clipboardText;
169
+ },
170
+ setClipboard(text) {
171
+ clipboardText = text;
172
+ },
173
+ sendNotification(title, body, icon = resolveDefaultAppId()) {
174
+ emit(`comment notify_${nextListenerId++} [${icon}] ${title}: ${body}`);
175
+ },
176
+ openFileDialog(_title = 'Open File', defaultPath = '/home/user/document.txt') {
177
+ return defaultPath;
178
+ },
179
+ saveFileDialog(_title = 'Save File', suggestedName = '/home/user/untitled.txt') {
180
+ return suggestedName;
181
+ },
182
+ confirmDialog(options = {}) {
183
+ if (nextConfirmResponse !== null) {
184
+ const next = nextConfirmResponse;
185
+ nextConfirmResponse = null;
186
+ return next;
187
+ }
188
+ return options.defaultConfirmed !== false;
189
+ },
190
+ setNextConfirmDialogResponse(confirmed) {
191
+ nextConfirmResponse = Boolean(confirmed);
192
+ },
193
+ configureHttp(config) {
194
+ httpConfig = { ...httpConfig, ...config };
195
+ return { ...httpConfig };
196
+ },
197
+ getHttpConfig() {
198
+ return { ...httpConfig };
199
+ },
200
+ registerHttpEndpoint(method, url, status, body) {
201
+ const key = `${method.trim().toUpperCase()} ${url.trim()}`;
202
+ httpEndpoints.set(key, {
203
+ status,
204
+ statusText: status < 400 ? 'OK' : 'Error',
205
+ body,
206
+ headers: {},
207
+ transport: 'mock-route',
208
+ callKind: 'json',
209
+ cached: false,
210
+ });
211
+ },
212
+ httpRequest(method, url, _body, options) {
213
+ const key = `${method.trim().toUpperCase()} ${url.trim()}`;
214
+ return (httpEndpoints.get(key) ?? {
215
+ status: 404,
216
+ statusText: 'Not Found',
217
+ body: '{"error":"Endpoint not registered"}',
218
+ headers: {},
219
+ transport: 'js-fallback',
220
+ callKind: options?.callKind ?? 'json',
221
+ cached: false,
222
+ });
223
+ },
224
+ httpBatchRequest(requests) {
225
+ return requests.map((req) => fallbackBridge.httpRequest(req.method, req.url, req.body, req.options));
226
+ },
227
+ httpRequestAsync(method, url, body, options) {
228
+ return Promise.resolve(fallbackBridge.httpRequest(method, url, body, options));
229
+ },
230
+ httpBatchRequestAsync(requests) {
231
+ return Promise.resolve(fallbackBridge.httpBatchRequest(requests));
232
+ },
233
+ downloadImageAsync(url, width) {
234
+ return Promise.resolve({
235
+ ok: true,
236
+ cached: false,
237
+ path: fallbackBridge.resolveImageAsset(url, width),
238
+ });
239
+ },
240
+ sqliteExecute(sql) {
241
+ return sqliteStore.execute(sql);
242
+ },
243
+ sqliteQuery(sql) {
244
+ return sqliteStore.query(sql);
245
+ },
246
+ getNetworkStatus() {
247
+ return { ...networkStatus };
248
+ },
249
+ setNetworkStatus(online, metered = false) {
250
+ networkStatus = {
251
+ online,
252
+ metered,
253
+ connectivity: !online ? 'offline' : metered ? 'limited' : 'full',
254
+ };
255
+ },
256
+ getSystemLocale() {
257
+ return systemLocale;
258
+ },
259
+ getSystemTimezone() {
260
+ return systemTimezone;
261
+ },
262
+ resolveImageAsset(src, width) {
263
+ return resolveNativeImageAsset(src, width);
264
+ },
265
+ logSystemError(message) {
266
+ systemErrors.push(String(message));
267
+ },
268
+ getSystemErrors() {
269
+ return [...systemErrors];
270
+ },
271
+ computeFuzzyFilter(items, query, limit = 50) {
272
+ return computeFuzzyFilterFallback(items, query, limit);
273
+ },
274
+ computeHash(input) {
275
+ return computeHashFallback(input);
276
+ },
277
+ fsResolvePath(kind, relPath) {
278
+ return fsStore.resolvePath(kind, relPath);
279
+ },
280
+ fsReadText(path) {
281
+ return fsStore.readText(path);
282
+ },
283
+ fsWriteText(path, content) {
284
+ return fsStore.writeText(path, content);
285
+ },
286
+ fsWatchFile(path) {
287
+ return fsStore.watchFile(path);
288
+ },
289
+ fsPollChangedFiles() {
290
+ return fsStore.pollChangedFiles();
291
+ },
292
+ getWindowGeometry() {
293
+ return { ...windowGeometry };
294
+ },
295
+ setWindowGeometry(geom) {
296
+ windowGeometry = {
297
+ width: typeof geom.width === 'number' && geom.width >= 160
298
+ ? Math.trunc(geom.width)
299
+ : windowGeometry.width,
300
+ height: typeof geom.height === 'number' && geom.height >= 120
301
+ ? Math.trunc(geom.height)
302
+ : windowGeometry.height,
303
+ x: typeof geom.x === 'number'
304
+ ? Math.trunc(geom.x)
305
+ : geom.x === null
306
+ ? null
307
+ : (windowGeometry.x ?? null),
308
+ y: typeof geom.y === 'number'
309
+ ? Math.trunc(geom.y)
310
+ : geom.y === null
311
+ ? null
312
+ : (windowGeometry.y ?? null),
313
+ maximized: typeof geom.maximized === 'boolean' ? geom.maximized : windowGeometry.maximized,
314
+ };
315
+ return { ...windowGeometry };
316
+ },
317
+ getAppMenu() {
318
+ return appMenuItems.map((item) => ({ ...item }));
319
+ },
320
+ setAppMenu(items) {
321
+ appMenuItems = items.map((item) => ({
322
+ id: String(item.id),
323
+ label: String(item.label || item.id),
324
+ accelerator: item.accelerator ?? null,
325
+ enabled: item.enabled !== false,
326
+ }));
327
+ return appMenuItems.map((item) => ({ ...item }));
328
+ },
329
+ getTrayState() {
330
+ return { ...trayState, menuItems: [...(trayState.menuItems ?? [])] };
331
+ },
332
+ setTrayState(state) {
333
+ trayState = {
334
+ visible: typeof state.visible === 'boolean' ? state.visible : trayState.visible,
335
+ icon: typeof state.icon === 'string' ? state.icon : trayState.icon,
336
+ tooltip: typeof state.tooltip === 'string' ? state.tooltip : trayState.tooltip,
337
+ menuItems: state.menuItems ? [...state.menuItems] : [...(trayState.menuItems ?? [])],
338
+ };
339
+ return { ...trayState, menuItems: [...(trayState.menuItems ?? [])] };
340
+ },
341
+ registerShortcut(accelerator, actionId) {
342
+ const cleanAcc = accelerator.trim();
343
+ const cleanAction = actionId.trim();
344
+ if (!cleanAcc || !cleanAction) {
345
+ return shortcuts.map((s) => ({ ...s }));
346
+ }
347
+ const existing = shortcuts.find((s) => s.accelerator === cleanAcc);
348
+ if (existing) {
349
+ existing.actionId = cleanAction;
350
+ }
351
+ else {
352
+ shortcuts.push({ accelerator: cleanAcc, actionId: cleanAction });
353
+ }
354
+ return shortcuts.map((s) => ({ ...s }));
355
+ },
356
+ unregisterShortcut(accelerator) {
357
+ const cleanAcc = accelerator.trim();
358
+ shortcuts = shortcuts.filter((s) => s.accelerator !== cleanAcc);
359
+ return shortcuts.map((s) => ({ ...s }));
360
+ },
361
+ getRegisteredShortcuts() {
362
+ return shortcuts.map((s) => ({ ...s }));
363
+ },
364
+ __dispatchEvent(id, eventName, eventPayload = {}) {
365
+ const callbacks = listenersByNode.get(id)?.get(eventName);
366
+ if (!callbacks || callbacks.size === 0) {
367
+ return;
368
+ }
369
+ for (const callback of Array.from(callbacks.values())) {
370
+ callback(eventPayload);
371
+ }
372
+ },
373
+ __dispatchAndDrain(id, eventName, eventPayload = {}) {
374
+ fallbackBridge.__dispatchEvent(id, eventName, eventPayload);
375
+ fallbackBridge.__flushTimers();
376
+ return fallbackBridge.__drainQueue();
377
+ },
378
+ __flushTimers() {
379
+ // No-op in synchronous fallback
380
+ },
381
+ __tickTimers() {
382
+ // No-op in synchronous fallback
383
+ },
384
+ __tickAndDrain(nowMs, completions = []) {
385
+ if (Array.isArray(completions)) {
386
+ for (const [cbId, payload] of completions) {
387
+ fallbackBridge.__resolveHostCallback?.(cbId, payload);
388
+ }
389
+ }
390
+ fallbackBridge.__tickTimers?.(nowMs);
391
+ return fallbackBridge.__drainQueue();
392
+ },
393
+ __resolveHostCallback() {
394
+ // No-op in synchronous fallback
395
+ },
396
+ beginBatch() {
397
+ batchDepth += 1;
398
+ },
399
+ endBatch() {
400
+ if (batchDepth > 0) {
401
+ batchDepth -= 1;
402
+ }
403
+ if (batchDepth === 0 && batchBuffer.length > 0) {
404
+ queue.push(...batchBuffer);
405
+ batchBuffer.length = 0;
406
+ }
407
+ },
408
+ __drainQueue() {
409
+ if (queue.length === 0) {
410
+ return '';
411
+ }
412
+ const out = queue.join('\n');
413
+ queue = [];
414
+ return out;
415
+ },
416
+ };
417
+ globalThis.__NG_NATIVE__ = fallbackBridge;
418
+ return fallbackBridge;
419
+ }
420
+ throw new Error('Native __NG_NATIVE__ bridge is required in production bundles.');
421
+ }
@@ -0,0 +1,33 @@
1
+ import { NgNativeBridge } from './bridge';
2
+ export interface ParsedStyleRule {
3
+ className: string;
4
+ background: string;
5
+ color: string;
6
+ padding: number;
7
+ spacing: number;
8
+ borderRadius: number | null;
9
+ fontSize: number | null;
10
+ fontWeight: number | null;
11
+ minWidth: number | null;
12
+ minHeight: number | null;
13
+ orientation: 'horizontal' | 'vertical' | null;
14
+ hexpand: boolean | null;
15
+ vexpand: boolean | null;
16
+ halign: string | null;
17
+ valign: string | null;
18
+ minChildren: number | null;
19
+ maxChildren: number | null;
20
+ homogeneous: boolean | null;
21
+ }
22
+ export declare function parsePixelInt(raw: string): number | null;
23
+ export declare function mapAlignKeyword(raw: string): string | null;
24
+ /**
25
+ * Parses component CSS rules at runtime into `ParsedStyleRule` descriptors compatible with
26
+ * the Rust engine's CSS Flexbox/Grid and typography/radius extension syntax.
27
+ */
28
+ export declare function parseRuntimeStyles(cssSource: string): ParsedStyleRule[];
29
+ /**
30
+ * Formats optional `ParsedStyleRule` layout/typography fields as space-separated `key=value` tokens.
31
+ */
32
+ export declare function formatParsedStyleExtensions(rule: ParsedStyleRule): string;
33
+ export declare function registerParsedStyles(bridge: NgNativeBridge, styles: readonly string[]): void;