@x-tech-laboratories/x-app 0.103.0 → 0.105.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/README.md CHANGED
@@ -12,8 +12,9 @@ an app moves over by changing the package name in its imports and its `x-libs-*`
12
12
  | `app/define` | The base app: `define_app` puts an X-app's name, ports, files, its own settings and its `define_feature` features (tables, migrations, calls, `api_spec`, settings, histories) together into one store every device keeps (`open_store` calling each feature's `on_open`, `needs_upgrade`, `bind_methods(database, on_change, caller)` running each call as its `caller`, calling each feature's `after_write`, recording versions and announcing writes, `is_read_only`), `page_only` (the specs' `page_only` calls and the writes of `user_only` settings, refused with `page_only_refusal`), its sync engine, its backups' names and schedule, and its bridges named after the app; `AppMethodsOf<typeof app>` types the app's calls. |
13
13
  | `app/server`, `app/daemon` | `run_server(app, { web_folder })`: the web server from `<PREFIX>_CONFIG` with accounts in `accounts.db` (moved there once from the data's own file, tokens starting with the app's `token_prefix`), the calls, OpenAPI, MCP, the server's backups and its sync peer, a token or MCP client refused the app's `page_only` calls and the `user_only_backup_calls` (restore, remove, schedule) and its calls run as the `program` caller; `run_daemon(app)`: the desktop daemon from `<PREFIX>_DB` with sync, letting devices connect, backups, certificates and the desktop settings; Both take the app's `services` (see `app/services`), `run_daemon(app, env, { services })`. `build_server`, `start_daemon`, `open_app_database` (with `on_restore` hooks) and `register_app_calls` for tests and apps that add their own. |
14
14
  | `app/services` | An app's own work beside its calls, run by both hosts: `StartServices` gets a `HostContext` (`kind`, `database()`, `profile`, `device_name`, the server's raw `config`, `plugins_folder`, `declared_file` from `<PREFIX>_DECLARED_FILE` or `/etc/<id>/declared.json`, `announce`, `emit(event, data)` for the page's `on_event`, `side_database(name)` for a never-backed-up file such as `<base>-index.db`, `back_up`) and returns `HostServices` (`before_restore`, `after_restore`, `stop`), stopped before sync and the database. |
15
- | `app/desktop`, `app/preload` | `run_desktop(app, electron, { main_dir })`: Electron's main process as a portal onto this computer's daemon or a server, with the window, the login entry, a second launch and `--daemon`; `run_preload(app, electron)` puts every bridge on the page. Electron is handed in, so neither imports it. |
16
- | `app/web/app_page`, `app/web/page` | `render_app({ app, pages, general_settings })`: the page on the web, the desktop or Android in the `Shell`, with sign-in in a browser, Your account, Settings (the app's general sections, each page's own, Connections, Desktop app, Sync and Backups) and `SyncButton`; `page_hooks<Methods>()` gives the app's typed `calls`, `use_data` and `use_settings`. The phone's host (`app/web/android`) loads only on Android. The page API's `on_event(name, listener)` hears the named events the app's services `emit`, on the web and the desktop. |
15
+ | `app/links` | `app_link(scheme, route)` and `route_of_link(scheme, link)`: an app's links such as `x-notes://note/<id>` and the page route they open. |
16
+ | `app/desktop`, `app/preload` | `run_desktop(app, electron, { main_dir })`: Electron's main process as a portal onto this computer's daemon or a server, with the window (`default_size` fixed or from the screen's free area, the daemon told while one is in front for its services' `window_in_front`), the tray (`show_tray_icon`, the app's own `tray` rows above Show, Quit and Quit completely, closing the last window leaving the app in it, `--hidden` starting there), the app's `link_scheme` links opening the window on their page (`route_of_link` to map them its own way; the page follows the `open` event), the login entry, a second launch and `--daemon`; the app's own `desktop_settings` switches sit in Settings → Desktop app beside the base's; `run_preload(app, electron)` puts every bridge on the page. Electron is handed in, so neither imports it. |
17
+ | `app/web/app_page`, `app/web/page` | `render_app({ app, pages, general_settings })`: the page on the web, the desktop or Android in the `Shell`, with sign-in in a browser, Your account, Settings (the app's general sections, each page's own, Connections, Desktop app, Sync and Backups) and `SyncButton`; `page_hooks<Methods>()` gives the app's typed `calls`, `use_data` and `use_settings`. The phone's host (`app/web/android`) loads only on Android. The page API's `on_event(name, listener)` hears the named events the app's services `emit`, on the web and the desktop. A page may have an `icon` (the sidebar then shows icon rows), a `use_badge` hook ("Inbox · 3"), `in_sidebar: false` with `active_as` for a page reached only by its route; `default_page` names the page an empty route opens, and the `use_chrome(parts)` hook gives the `sidebar` content under the rows, header `tools` and a `side_pane`. |
17
18
  | `config/vite`, `config/electron_vite`, `config/vitest`, `config/tsconfig/*.json` | An X-app's configs as presets: `web_vite_config({ port })` and `android_vite_config()` for the page, `desktop_vite_config()` for electron-vite's window, daemon, preload and page, `vitest_config()` for tests in `tests/` in UTC with coverage of `src/` to the terminal, merged with the app's own floor so `autoUpdate` still raises it, and `base`, `node`, `web` and `tests` tsconfigs to extend. |
18
19
  | `app_new` | The `x-app-new <X-Name>` command: a new X-app's files written once, laid out as the Application Standard asks, on the base app, the presets, X-App's Nix lib and its CI actions, with an example notes feature; `--port`, `--folder`, `--no-desktop` and `--no-android`. |
19
20
  | `durations` | `parse_duration` for settings such as `"2h30m"`, `format_duration` in months down to seconds and "less than a second" below one, `format_age`, and `format_clock` for a playing time such as `"3:07"`, with `{ hours: "always" }` writing `"0:03:07"` so a column of times lines up and `empty` for no time. |
@@ -9,6 +9,7 @@ export interface DaemonOptions {
9
9
  default_peer_port?: number;
10
10
  services?: StartServices;
11
11
  declared_file?: string;
12
+ icon_path?: string | null;
12
13
  }
13
14
  export interface Daemon {
14
15
  shut_down: () => Promise<void>;
@@ -46,13 +46,16 @@ export async function start_daemon(app, options) {
46
46
  // ── Desktop settings ───────────────────────────────────────────────
47
47
  const desktop_file = join(profile, "desktop.json");
48
48
  function read_desktop() {
49
- return read_desktop_settings(existsSync(desktop_file) ? JSON.parse(readFileSync(desktop_file, "utf8")) : null);
49
+ return read_desktop_settings(existsSync(desktop_file) ? JSON.parse(readFileSync(desktop_file, "utf8")) : null, app.desktop_settings);
50
50
  }
51
+ // Told by the window as it comes and goes.
52
+ let window_in_front = false;
51
53
  const daemon_methods = {
52
54
  get_desktop_settings: read_desktop,
53
- set_desktop_setting: (key, value) => writeFileSync(desktop_file, JSON.stringify(read_desktop_settings({ ...read_desktop(), [key]: value }), null, 2)),
55
+ set_desktop_setting: (key, value) => writeFileSync(desktop_file, JSON.stringify(read_desktop_settings({ ...read_desktop(), [key]: value }, app.desktop_settings), null, 2)),
54
56
  // Stops once the answer has gone back.
55
57
  stop_daemon: () => void setTimeout(() => void shut_down(), 0),
58
+ set_window_in_front: (in_front) => void (window_in_front = in_front === true),
56
59
  };
57
60
  // ── Calls ──────────────────────────────────────────────────────────
58
61
  const daemon = fastify({ bodyLimit: call_body_limit, forceCloseConnections: true });
@@ -114,6 +117,8 @@ export async function start_daemon(app, options) {
114
117
  emit: (event, data) => changes.send(JSON.stringify(data), { event }),
115
118
  side_database: sides.open,
116
119
  back_up: opened.back_up,
120
+ window_in_front: () => window_in_front,
121
+ icon_path: options.icon_path ?? null,
117
122
  });
118
123
  opened.on_restore({ before: () => services.before_restore?.(), after: () => services.after_restore?.() });
119
124
  }
@@ -139,7 +144,7 @@ export async function run_daemon(app, env = process.env, extra = {}) {
139
144
  // A run on another database has a socket of its own.
140
145
  const socket_path = env[`${app.env_prefix}_SOCKET`] || daemon_socket_path({ app: app.id, data_file: database_path });
141
146
  try {
142
- const daemon = await start_daemon(app, { database_path, socket_path, on_stopped: () => process.exit(0), declared_file: declared_file_of(app, env), ...extra });
147
+ const daemon = await start_daemon(app, { database_path, socket_path, on_stopped: () => process.exit(0), declared_file: declared_file_of(app, env), icon_path: env[`${app.env_prefix}_ICON`] ?? null, ...extra });
143
148
  // Another daemon on this database got there first, which is all that was asked for.
144
149
  if (!daemon)
145
150
  process.exit(0);
@@ -11,7 +11,7 @@ import { type SettingSpec, type SettingsMethods, type SettingsStore, type Settin
11
11
  import { type MigrationStep, type SqlDatabase } from "../sql.ts";
12
12
  import { type SyncedTable } from "../sync_engine.ts";
13
13
  import { type PeerListeningMethods, type SyncDeviceMethods, type SyncStatus } from "../sync_protocol.ts";
14
- import { type DesktopMethods } from "./protocol.ts";
14
+ import { type DesktopMethods, type DesktopSettingSpec } from "./protocol.ts";
15
15
  export type StoreMethod = (database: SqlDatabase, ...args: never[]) => unknown;
16
16
  export type KeptHistory = Pick<History<unknown>, "synced_table" | "install" | "forget_touched" | "record" | "prune">;
17
17
  export interface Feature<Methods extends Record<string, StoreMethod> = Record<string, StoreMethod>> {
@@ -54,6 +54,8 @@ export interface AppOptions<Features extends readonly Feature[]> {
54
54
  setting_key_example?: string;
55
55
  page_only_refusal?: string;
56
56
  token_prefix?: string;
57
+ desktop_settings?: Readonly<Record<string, DesktopSettingSpec>>;
58
+ link_scheme?: string;
57
59
  }
58
60
  export declare const base_setting_defaults: {
59
61
  history_days: number;
@@ -101,6 +103,8 @@ export declare function define_app<const Features extends readonly Feature[]>(op
101
103
  setting_key_example?: string;
102
104
  page_only_refusal?: string;
103
105
  token_prefix?: string;
106
+ desktop_settings?: Readonly<Record<string, DesktopSettingSpec>>;
107
+ link_scheme?: string;
104
108
  features: readonly Feature<Record<string, StoreMethod>>[];
105
109
  settings_store: SettingsStore;
106
110
  setting_defaults: Readonly<import("../settings.ts").Settings>;
@@ -2,13 +2,17 @@ import { type AutostartOptions } from "../autostart.ts";
2
2
  import { type AppLike, type FocusableWindowLike } from "../electron/app.ts";
3
3
  import type { IpcMainLike } from "../electron/bridge.ts";
4
4
  import type { WindowLike } from "../electron/events.ts";
5
+ import { type TrayElectronLike, type TrayRow } from "../electron/tray.ts";
5
6
  import { type BrowserWindowLike, type BrowserWindowOptionsLike, type NativeThemeLike, type ScreenLike, type ShellLike } from "../electron/window.ts";
6
7
  import { call_daemon, start_daemon } from "../local_daemon.ts";
7
8
  import type { App } from "./define.ts";
8
9
  type DesktopWindow = BrowserWindowLike & FocusableWindowLike & WindowLike & {
9
10
  webContents: {
10
11
  reload(): void;
12
+ once(event: "did-finish-load", listener: () => void): unknown;
11
13
  };
14
+ isFocused(): boolean;
15
+ isVisible(): boolean;
12
16
  };
13
17
  export interface ElectronLike {
14
18
  app: AppLike & {
@@ -28,15 +32,39 @@ export interface ElectronLike {
28
32
  };
29
33
  ipcMain: IpcMainLike;
30
34
  nativeTheme: NativeThemeLike;
31
- screen: ScreenLike;
35
+ screen: ScreenLike & {
36
+ getPrimaryDisplay(): {
37
+ workAreaSize: {
38
+ width: number;
39
+ height: number;
40
+ };
41
+ };
42
+ };
32
43
  shell: ShellLike;
44
+ Tray?: TrayElectronLike<unknown>["Tray"];
45
+ Menu?: TrayElectronLike<unknown>["Menu"];
46
+ nativeImage?: TrayElectronLike<unknown>["nativeImage"];
47
+ }
48
+ export interface TrayTools {
49
+ call: (method: string, args?: unknown[]) => Promise<unknown>;
50
+ open: (route: string) => void;
33
51
  }
52
+ export type AppTrayRows = (tools: TrayTools) => Promise<{
53
+ tooltip?: string;
54
+ rows: TrayRow[];
55
+ }>;
34
56
  export interface DesktopOptions {
35
57
  main_dir: string;
36
58
  default_size?: {
37
59
  width: number;
38
60
  height: number;
39
- };
61
+ } | ((work_area: {
62
+ width: number;
63
+ height: number;
64
+ }) => {
65
+ width: number;
66
+ height: number;
67
+ });
40
68
  min_size?: {
41
69
  width: number;
42
70
  height: number;
@@ -47,6 +75,8 @@ export interface DesktopOptions {
47
75
  start_daemon?: typeof start_daemon;
48
76
  call_daemon?: typeof call_daemon;
49
77
  set_autostart?: (options: AutostartOptions, on: boolean) => void;
78
+ tray?: AppTrayRows;
79
+ route_of_link?: (link: string) => string | null;
50
80
  }
51
81
  export declare function run_desktop(app: App, electron: ElectronLike, options: DesktopOptions): void;
52
82
  export {};
@@ -13,10 +13,12 @@ import { connection_file_storage } from "../connection_file_storage.js";
13
13
  import { create_connections } from "../connections.js";
14
14
  import { create_daemon_link } from "../daemon_link.js";
15
15
  import { create_daemon_router, default_local_tables } from "../daemon_router.js";
16
- import { bring_to_front, hold_single_instance } from "../electron/app.js";
16
+ import { bring_to_front, first_argument, hold_single_instance } from "../electron/app.js";
17
+ import { app_rows, create_app_tray, tray_groups } from "../electron/tray.js";
17
18
  import { create_window, is_app_page } from "../electron/window.js";
18
19
  import { call_daemon, daemon_log_path, daemon_socket_path, start_daemon } from "../local_daemon.js";
19
20
  import { peer_listening_method_names, sync_device_method_names } from "../sync_protocol.js";
21
+ import { route_of_link } from "./links.js";
20
22
  // ── Desktop ──────────────────────────────────────────────────────────────────
21
23
  export function run_desktop(app, electron, options) {
22
24
  const { BrowserWindow, dialog, ipcMain } = electron;
@@ -41,7 +43,9 @@ export function run_desktop(app, electron, options) {
41
43
  // The command that starts this app again, which the login entry runs.
42
44
  const own_command = (args) => launch_command({ launcher: env[`${prefix}_LAUNCHER`] ?? null, is_packaged: electron.app.isPackaged, app_path: electron.app.getAppPath(), args });
43
45
  function ensure_daemon() {
44
- return start({ socket_path, script: join(options.main_dir, "daemon.js"), env: { [`${prefix}_DB`]: database_path, [`${prefix}_SOCKET`]: socket_path }, log_file });
46
+ // Only the user's own daemon reads what this computer's configuration declares, unless a run names a file itself.
47
+ const declared = is_own_profile ? {} : { [`${prefix}_DECLARED_FILE`]: env[`${prefix}_DECLARED_FILE`] ?? "" };
48
+ return start({ socket_path, script: join(options.main_dir, "daemon.js"), env: { [`${prefix}_DB`]: database_path, [`${prefix}_SOCKET`]: socket_path, [`${prefix}_ICON`]: icon_path, ...declared }, log_file });
45
49
  }
46
50
  // ── Connections ──────────────────────────────────────────────────────
47
51
  // Certificates the user trusted, read again whenever the daemon saves the list, so calls to a server honour them.
@@ -64,6 +68,7 @@ export function run_desktop(app, electron, options) {
64
68
  on_change: () => {
65
69
  app.bridges.events.emit(windows(), "changed", null);
66
70
  void apply_window_settings().catch(() => undefined);
71
+ void tray?.refresh();
67
72
  },
68
73
  on_sync_status: (status) => app.bridges.events.emit(windows(), "sync_status", status),
69
74
  // The app's own events, such as a reply as it is written, go to every window by name.
@@ -78,11 +83,12 @@ export function run_desktop(app, electron, options) {
78
83
  function get_desktop_settings() {
79
84
  return call("daemon/get_desktop_settings");
80
85
  }
81
- // Only the user's own profile starts at login; a dev run never writes the login entry.
86
+ // The tray as its setting says, and, for the user's own profile only, the login entry; a dev run never writes it.
82
87
  async function apply_window_settings() {
88
+ const settings = await get_desktop_settings();
89
+ tray?.set_shown(settings.show_tray_icon);
83
90
  if (!is_own_profile)
84
91
  return;
85
- const settings = await get_desktop_settings();
86
92
  write_autostart({ id: `${app.id}-daemon`, name: `${app.name} in the background`, comment: `Sync and backups for ${app.name}`, icon: icon_path, command: own_command(["--daemon"]) }, settings.start_at_login && settings.keep_running_in_background);
87
93
  }
88
94
  // ── Window ───────────────────────────────────────────────────────────
@@ -90,30 +96,71 @@ export function run_desktop(app, electron, options) {
90
96
  dev_url: electron.app.isPackaged ? undefined : env.ELECTRON_RENDERER_URL,
91
97
  file: join(options.main_dir, "../renderer/index.html"),
92
98
  };
99
+ // The daemon's services keep quiet, such as about notifications, while a window is in front.
100
+ function tell_in_front() {
101
+ const in_front = windows().some((each) => each.isFocused() && each.isVisible());
102
+ void call("daemon/set_window_in_front", [in_front]).catch(() => undefined);
103
+ }
93
104
  function open_window() {
94
- return create_window(BrowserWindow, {
105
+ const size = options.default_size ?? { width: 1100, height: 760 };
106
+ const window = create_window(BrowserWindow, {
95
107
  ...page,
96
108
  title: app.name,
97
109
  icon: icon_path,
98
110
  // electron-vite emits an ESM preload as .mjs; loading .js here silently yields no bridge.
99
111
  preload: join(options.main_dir, "../preload/index.mjs"),
100
- default_size: options.default_size ?? { width: 1100, height: 760 },
112
+ default_size: typeof size === "function" ? size(electron.screen.getPrimaryDisplay().workAreaSize) : size,
101
113
  min_size: options.min_size ?? { width: 360, height: 480 },
102
114
  native_theme: electron.nativeTheme,
103
115
  shell: electron.shell,
104
116
  screen: electron.screen,
105
117
  state_file: join(profile, "window.json"),
106
118
  });
119
+ for (const event of ["focus", "blur", "show", "hide", "closed"])
120
+ window.on(event, tell_in_front);
121
+ return window;
107
122
  }
108
- function show_window() {
109
- bring_to_front(windows()[0] ?? open_window());
123
+ // Brings the window forward, making one if it was closed, and hands it the route once its page listens.
124
+ function show_window(route) {
125
+ const existing = windows()[0];
126
+ const window = existing ?? open_window();
127
+ bring_to_front(window);
128
+ if (!route)
129
+ return;
130
+ const open = () => app.bridges.events.emit([window], "app_event", { event: "open", data: route });
131
+ if (existing)
132
+ open();
133
+ else
134
+ window.webContents.once("did-finish-load", open);
110
135
  }
136
+ // The page an argument such as x-notes://note/<id> opens, if the app has links.
137
+ const link_route = options.route_of_link ?? (app.link_scheme ? (link) => route_of_link(app.link_scheme, link) : () => null);
138
+ const route_in = (args) => first_argument(args, link_route);
111
139
  // Stops the daemon as well, so nothing runs until the app is opened again.
112
140
  async function quit_completely() {
113
141
  router.quitting();
114
142
  await call("daemon/stop_daemon").catch(() => undefined);
115
143
  electron.app.quit();
116
144
  }
145
+ // ── Tray ───────────────────────────────────────────────────────────
146
+ // The app's rows above Show, Quit and Quit completely; its calls go to the daemon the window works on.
147
+ const { Tray, Menu, nativeImage } = electron;
148
+ const tray = Tray && Menu && nativeImage
149
+ ? create_app_tray({
150
+ electron: { Tray, Menu, nativeImage },
151
+ icon_path,
152
+ on_click: () => show_window(),
153
+ on_error: (error) => console.error(error),
154
+ read: async () => {
155
+ const own = options.tray ? await options.tray({ call: (method, args = []) => call(`call/${method}`, args), open: (route) => show_window(route) }) : { rows: [] };
156
+ const quit = () => {
157
+ router.quitting();
158
+ electron.app.quit();
159
+ };
160
+ return { tooltip: own.tooltip ?? app.name, rows: tray_groups(own.rows, app_rows({ app_name: app.name, show: () => show_window(), quit, quit_completely: () => void quit_completely() })) };
161
+ },
162
+ })
163
+ : null;
117
164
  // ── Bridges ──────────────────────────────────────────────────────────
118
165
  // Only the app's own page may call in, never a site a link led to.
119
166
  function trusted(event) {
@@ -123,7 +170,17 @@ export function run_desktop(app, electron, options) {
123
170
  function register_bridges() {
124
171
  const handle_options = { trusted, envelopes: true };
125
172
  const { bridges } = app;
126
- bridges.calls.handle(ipcMain, forwarded(app.method_names, "call"), handle_options);
173
+ // A write the page makes shows in the tray at once, as the daemon tells this window of no change it made itself.
174
+ const calls = Object.fromEntries(Object.entries(forwarded(app.method_names, "call")).map(([name, forward]) => [
175
+ name,
176
+ async (...args) => {
177
+ const result = await forward(...args);
178
+ if (!app.is_read_only(name))
179
+ void tray?.refresh();
180
+ return result;
181
+ },
182
+ ]));
183
+ bridges.calls.handle(ipcMain, calls, handle_options);
127
184
  bridges.backups.handle(ipcMain, forwarded(backup_method_names, "backups"), handle_options);
128
185
  bridges.device.handle(ipcMain, forwarded(sync_device_method_names, "device"), handle_options);
129
186
  bridges.peer_listening.handle(ipcMain, forwarded(peer_listening_method_names, "peer_listening"), handle_options);
@@ -153,14 +210,20 @@ export function run_desktop(app, electron, options) {
153
210
  register_bridges();
154
211
  router.start();
155
212
  await apply_window_settings().catch(() => undefined);
156
- show_window();
213
+ // `--hidden`, as a login entry may pass it, starts in the tray, unless there is no tray to open the window from.
214
+ if (!(argv.includes("--hidden") && tray?.is_shown()))
215
+ show_window(route_in(argv));
157
216
  });
158
217
  electron.app.on("will-quit", () => {
159
218
  router.stop();
219
+ tray?.stop();
160
220
  unwatchFile(certificates_file, trust_certificates);
161
221
  });
162
- // Closing the window ends only the window; the daemon runs on.
163
- electron.app.on("window-all-closed", () => electron.app.quit());
222
+ // Closing the window ends only the window, or leaves the app in the tray; the daemon runs on either way.
223
+ electron.app.on("window-all-closed", () => {
224
+ if (!tray?.is_shown())
225
+ electron.app.quit();
226
+ });
164
227
  }
165
228
  // `<app>-desktop --daemon`, as the login entry runs it, starts only the daemon.
166
229
  async function start_daemon_alone() {
@@ -173,10 +236,11 @@ export function run_desktop(app, electron, options) {
173
236
  electron.app.exit(1);
174
237
  }
175
238
  }
176
- // A second launch brings the window forward, but one that only starts the daemon leaves the window be.
239
+ // A second launch brings the window forward on the page its link names, but one that only starts the daemon or
240
+ // starts hidden leaves the window be.
177
241
  function open_from_second_launch(second_argv) {
178
- if (!second_argv.includes("--daemon"))
179
- show_window();
242
+ if (!second_argv.includes("--daemon") && !second_argv.includes("--hidden"))
243
+ show_window(route_in(second_argv));
180
244
  }
181
245
  if (argv.includes("--daemon"))
182
246
  void start_daemon_alone();
@@ -0,0 +1,2 @@
1
+ export declare function app_link(scheme: string, route: string): string;
2
+ export declare function route_of_link(scheme: string, text: string): string | null;
@@ -0,0 +1,15 @@
1
+ // Links such as x-notes://note/<id>, which open the desktop app on that page from a notification or any other program,
2
+ // in the scheme the app names.
3
+ // ── Links ────────────────────────────────────────────────────────────────────
4
+ // The link to a page, given its route such as "#/note/<id>".
5
+ export function app_link(scheme, route) {
6
+ return `${scheme}://${route.replace(/^#?\/?/, "")}`;
7
+ }
8
+ // The page's route a link names, such as "#/note/<id>", or null when the text is not one of the app's links.
9
+ export function route_of_link(scheme, text) {
10
+ const prefix = `${scheme.toLowerCase()}://`;
11
+ if (!text.toLowerCase().startsWith(prefix))
12
+ return null;
13
+ const path = text.slice(prefix.length).replace(/\/+$/, "");
14
+ return /^[a-z0-9/_-]*$/i.test(path) ? `#/${path}` : null;
15
+ }
@@ -4,11 +4,18 @@ import type { ConnectionClient } from "../connection_protocol.ts";
4
4
  import type { Client } from "../electron/bridge.ts";
5
5
  import type { PeerListeningClient, SyncDeviceClient } from "../sync_protocol.ts";
6
6
  export interface DesktopSettings {
7
+ show_tray_icon: boolean;
7
8
  keep_running_in_background: boolean;
8
9
  start_at_login: boolean;
10
+ [key: string]: boolean;
9
11
  }
10
12
  export declare const desktop_setting_defaults: DesktopSettings;
11
- export declare function read_desktop_settings(saved: unknown): DesktopSettings;
13
+ export interface DesktopSettingSpec {
14
+ default: boolean;
15
+ label: string;
16
+ hint?: string;
17
+ }
18
+ export declare function read_desktop_settings(saved: unknown, specs?: Readonly<Record<string, DesktopSettingSpec>>): DesktopSettings;
12
19
  export interface DesktopMethods {
13
20
  get_desktop_settings: () => DesktopSettings;
14
21
  set_desktop_setting: <Key extends keyof DesktopSettings>(key: Key, value: DesktopSettings[Key]) => void;
@@ -19,6 +26,7 @@ export interface DaemonMethods {
19
26
  get_desktop_settings: () => DesktopSettings;
20
27
  set_desktop_setting: (key: keyof DesktopSettings, value: boolean) => void;
21
28
  stop_daemon: () => void;
29
+ set_window_in_front: (in_front: boolean) => void;
22
30
  }
23
31
  export type Host = "web" | "desktop" | "android";
24
32
  export interface BackupFolder {
@@ -1,13 +1,14 @@
1
1
  // What the base app's hosts and processes say to each other: the page's api on every host, and the desktop app's own
2
2
  // settings, which its daemon keeps beside the database rather than syncing, since they belong to the computer.
3
3
  export const desktop_setting_defaults = {
4
+ show_tray_icon: true,
4
5
  keep_running_in_background: true,
5
6
  start_at_login: true,
6
7
  };
7
- // Settings saved on the device, each default where it is missing or damaged.
8
- export function read_desktop_settings(saved) {
8
+ // Settings saved on the device, the base's and the app's own, each default where it is missing or damaged.
9
+ export function read_desktop_settings(saved, specs = {}) {
9
10
  const settings = (saved ?? {});
10
- const flag = (key) => (typeof settings[key] === "boolean" ? settings[key] : desktop_setting_defaults[key]);
11
- return { keep_running_in_background: flag("keep_running_in_background"), start_at_login: flag("start_at_login") };
11
+ const defaults = { ...desktop_setting_defaults, ...Object.fromEntries(Object.entries(specs).map(([key, spec]) => [key, spec.default])) };
12
+ return Object.fromEntries(Object.entries(defaults).map(([key, fallback]) => [key, typeof settings[key] === "boolean" ? settings[key] : fallback]));
12
13
  }
13
14
  export const desktop_method_names = ["get_desktop_settings", "set_desktop_setting", "quit_completely"];
@@ -224,6 +224,8 @@ export async function run_server(app, options) {
224
224
  emit: (event, data) => changes.send(JSON.stringify(data), { event }),
225
225
  side_database: sides.open,
226
226
  back_up: opened.back_up,
227
+ window_in_front: () => false,
228
+ icon_path: null,
227
229
  })
228
230
  : no_services;
229
231
  opened.on_restore({ before: () => services.before_restore?.(), after: () => services.after_restore?.() });
@@ -12,6 +12,8 @@ export interface HostContext {
12
12
  emit: (event: string, data: unknown) => void;
13
13
  side_database: (name: string) => DatabaseSync;
14
14
  back_up: () => Promise<void>;
15
+ window_in_front: () => boolean;
16
+ icon_path: string | null;
15
17
  }
16
18
  export interface HostServices {
17
19
  before_restore?: () => void;
@@ -35,17 +35,24 @@ function SidebarFoot() {
35
35
  function Pages({ pages, account }) {
36
36
  const { app } = pages;
37
37
  const route = use_route();
38
- const [section = pages.pages[0]?.id ?? "settings", ...rest] = route.parts;
38
+ const [section = pages.default_page ?? pages.pages[0]?.id ?? "settings", ...rest] = route.parts;
39
39
  const shown = pages.pages.find((candidate) => candidate.id === section);
40
40
  const is_account = account !== null && section === "account";
41
41
  const label = shown?.label ?? (is_account ? "Your account" : "Settings");
42
42
  const view_key = route.parts.join("/");
43
+ const chrome = pages.use_chrome?.(route.parts) ?? {};
43
44
  useEffect(() => {
44
45
  document.title = `${label} · ${app.name}`;
45
46
  }, [label, app.name]);
46
- const sections = pages.pages.map((each) => ({ id: each.id, label: each.label, href: `#/${each.id}` }));
47
+ // Each listed page's badge, such as how many things wait, from its hook, called in the same order every time.
48
+ const listed = pages.pages.filter((each) => each.in_sidebar !== false);
49
+ const badges = listed.map((each) => each.use_badge?.() ?? null);
50
+ const row_label = (index) => (badges[index] ? `${listed[index].label} · ${badges[index]}` : listed[index].label);
51
+ const with_icons = listed.some((each) => each.icon);
52
+ const sections = listed.map((each, index) => ({ id: each.id, label: row_label(index), href: `#/${each.id}` }));
53
+ const views = listed.map((each, index) => ({ id: each.id, label: row_label(index), href: `#/${each.id}`, ...(each.icon ? { icon: each.icon } : {}) }));
47
54
  const view = shown ? shown.view(rest) : is_account ? _jsx(AccountPage, { account: account }) : _jsx(SettingsView, { pages: pages, is_admin: account === null || is_admin(account.me) });
48
- return (_jsx(Shell, { brand: app.name, brand_icon: pages.brand_icon ?? "icon.svg", sections: sections, active: section, theme: theme_choice(`${app.id}-theme`), view_key: view_key, user: account ? account.me.name : undefined, user_href: account ? "#/account" : undefined, on_logout: account ? () => void account.sign_out() : undefined, sidebar_foot: _jsx(SidebarFoot, {}), settings: { href: "#/settings" }, children: _jsx(Fragment, { children: view }, view_key) }));
55
+ return (_jsx(Shell, { brand: app.name, brand_icon: pages.brand_icon ?? "icon.svg", ...(with_icons ? { views } : { sections }), active: shown?.active_as ?? section, ...(chrome.sidebar ? { sidebar: chrome.sidebar } : {}), ...(chrome.tools ? { tools: chrome.tools } : {}), ...(chrome.side_pane ? { side_pane: chrome.side_pane } : {}), theme: theme_choice(`${app.id}-theme`), view_key: view_key, user: account ? account.me.name : undefined, user_href: account ? "#/account" : undefined, on_logout: account ? () => void account.sign_out() : undefined, sidebar_foot: _jsx(SidebarFoot, {}), settings: { href: "#/settings" }, children: _jsx(Fragment, { children: view }, view_key) }));
49
56
  }
50
57
  // ── App ──────────────────────────────────────────────────────────────────────
51
58
  // A browser reaches the server's data, so it signs in; the desktop and phone apps keep their own and sign in only to sync.
@@ -76,6 +83,12 @@ async function host_api(app) {
76
83
  }
77
84
  // Starts the page on whichever host it runs: the desktop app, the phone app or a browser.
78
85
  export async function render_app(pages, root = document.getElementById("app")) {
79
- set_page_api(await host_api(pages.app));
86
+ const api = await host_api(pages.app);
87
+ set_page_api(api);
88
+ // A link the desktop app was opened with, or a tray row, opens its page.
89
+ api.on_event?.("open", (route) => {
90
+ if (typeof route === "string" && route.startsWith("#/"))
91
+ location.hash = route;
92
+ });
80
93
  createRoot(root).render(_jsx(AppView, { pages: pages }));
81
94
  }
@@ -1,4 +1,6 @@
1
+ import type { IconGlyph } from "../../web/react/icons.tsx";
1
2
  import { type SettingsSection } from "../../web/react/layout.tsx";
3
+ import type { ShellSidePane } from "../../web/react/shell.tsx";
2
4
  import type { App } from "../define.ts";
3
5
  export interface PageSettingsProps {
4
6
  settings: Record<string, unknown>;
@@ -9,12 +11,23 @@ export interface AppPage {
9
11
  label: string;
10
12
  view: (parts: string[]) => React.ReactNode;
11
13
  settings?: (props: PageSettingsProps) => SettingsSection[];
14
+ icon?: IconGlyph;
15
+ use_badge?: () => number | string | null;
16
+ in_sidebar?: boolean;
17
+ active_as?: string;
18
+ }
19
+ export interface AppChrome {
20
+ sidebar?: React.ReactNode;
21
+ tools?: React.ReactNode;
22
+ side_pane?: ShellSidePane;
12
23
  }
13
24
  export interface AppPages {
14
- app: Pick<App, "id" | "name" | "data_name" | "server_example" | "bridges">;
25
+ app: Pick<App, "id" | "name" | "data_name" | "server_example" | "bridges"> & Partial<Pick<App, "desktop_settings">>;
15
26
  pages: readonly AppPage[];
16
27
  general_settings?: (props: PageSettingsProps) => SettingsSection[];
17
28
  brand_icon?: string;
29
+ default_page?: string;
30
+ use_chrome?: (parts: readonly string[]) => AppChrome;
18
31
  }
19
32
  export declare function SettingsView({ pages, is_admin }: {
20
33
  pages: AppPages;
@@ -22,7 +22,7 @@ function FolderBackups({ backups, folder, data_name }) {
22
22
  return _jsx(BackupSettings, { device: backups, data_name: data_name, on_restored: () => location.reload(), folder_row: folder_row, can_back_up: Boolean(name) }, name ?? "");
23
23
  }
24
24
  // The desktop app's own settings, which belong to this computer and do not sync.
25
- function Desktop({ app_name }) {
25
+ function Desktop({ app_name, own }) {
26
26
  const { desktop } = page();
27
27
  const [settings, set_settings] = useState(null);
28
28
  useEffect(() => void desktop?.get_desktop_settings().then(set_settings, () => undefined), [desktop]);
@@ -32,7 +32,7 @@ function Desktop({ app_name }) {
32
32
  set_settings({ ...settings, [key]: on });
33
33
  attempt(desktop.set_desktop_setting(key, on));
34
34
  };
35
- return (_jsxs(_Fragment, { children: [_jsx(SettingRow, { label: "Keep running in the background", hint: "Sync and backups carry on with the window closed. Turned off, they stop shortly after the last window closes.", as_label: true, children: _jsx(Switch, { label: "Keep running in the background", checked: settings.keep_running_in_background, on_change: (on) => change("keep_running_in_background", on) }) }), _jsx(SettingRow, { label: "Start at login", hint: `Starts ${app_name} in the background when you log in, without opening its window.`, as_label: true, children: _jsx(Switch, { label: "Start at login", checked: settings.start_at_login, disabled: !settings.keep_running_in_background, on_change: (on) => change("start_at_login", on) }) }), _jsx(SettingRow, { label: "Quit completely", hint: `Closes the window and stops ${app_name} in the background too, until you open it again.`, children: _jsx("button", { type: "button", onClick: () => attempt(desktop.quit_completely()), children: "Quit completely" }) })] }));
35
+ return (_jsxs(_Fragment, { children: [_jsx(SettingRow, { label: "Show the tray icon", hint: `Keeps ${app_name} in the tray, where closing the window leaves it.`, as_label: true, children: _jsx(Switch, { label: "Show the tray icon", checked: settings.show_tray_icon, on_change: (on) => change("show_tray_icon", on) }) }), _jsx(SettingRow, { label: "Keep running in the background", hint: "Sync and backups carry on with the window closed. Turned off, they stop shortly after the last window closes.", as_label: true, children: _jsx(Switch, { label: "Keep running in the background", checked: settings.keep_running_in_background, on_change: (on) => change("keep_running_in_background", on) }) }), _jsx(SettingRow, { label: "Start at login", hint: `Starts ${app_name} in the background when you log in, without opening its window.`, as_label: true, children: _jsx(Switch, { label: "Start at login", checked: settings.start_at_login, disabled: !settings.keep_running_in_background, on_change: (on) => change("start_at_login", on) }) }), Object.entries(own).map(([key, spec]) => (_jsx(SettingRow, { label: spec.label, ...(spec.hint ? { hint: spec.hint } : {}), as_label: true, children: _jsx(Switch, { label: spec.label, checked: settings[key] ?? spec.default, on_change: (on) => change(key, on) }) }, key))), _jsx(SettingRow, { label: "Quit completely", hint: `Closes the window and stops ${app_name} in the background too, until you open it again.`, children: _jsx("button", { type: "button", onClick: () => attempt(desktop.quit_completely()), children: "Quit completely" }) })] }));
36
36
  }
37
37
  // A desktop window on a server's daemon works on the server's data, as a browser does.
38
38
  function storage_category(app, is_admin) {
@@ -44,7 +44,7 @@ function storage_category(app, is_admin) {
44
44
  sections.push({ id: "connections", heading: "Connections", hint: `The ${data_name} this window works on: This computer's own, or an ${name} server's.`, content: _jsxs(_Fragment, { children: [_jsx(ConnectionSettings, { client: connections, certificates: certificates, placeholder: app.server_example }), !device && certificates && _jsx(TrustedCertificates, { certificates: certificates })] }) });
45
45
  }
46
46
  if (desktop)
47
- sections.push({ id: "desktop", heading: "Desktop app", content: _jsx(Desktop, { app_name: name }) });
47
+ sections.push({ id: "desktop", heading: "Desktop app", content: _jsx(Desktop, { app_name: name, own: app.desktop_settings ?? {} }) });
48
48
  if (device && (!on_server || is_admin)) {
49
49
  const hint = on_server ? `Keep the server's ${data_name} alike with the devices paired with it.` : `Keep this device's ${data_name} alike with your other devices and your ${name} server.`;
50
50
  sections.push({ id: "sync", heading: "Sync", hint, content: _jsx(SyncSettings, { device: device, subscribe: (listener) => data_watch.subscribe(listener), data_name: data_name, extra: peer_listening && _jsx(PeerListeningSettings, { listening: peer_listening }) }) });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@x-tech-laboratories/x-app",
3
- "version": "0.103.0",
3
+ "version": "0.105.0",
4
4
  "description": "Code the X-apps share: agents and their long runs, passwords and sign-in, the Fastify server pieces, durations, and the web page's helpers and widgets",
5
5
  "license": "GPL-3.0-or-later",
6
6
  "repository": {