@loidolt/theme-tauri 0.0.0-stage → 0.12.1

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,100 @@
1
+ import { onDestroy } from 'svelte';
2
+ import { isTauri } from './platform.js';
3
+ /** The Web Notifications API, when this page has it. */
4
+ function webNotification() {
5
+ if (typeof window === 'undefined')
6
+ return null;
7
+ const api = window.Notification;
8
+ return typeof api === 'function' ? api : null;
9
+ }
10
+ const asState = (value) => value === 'granted' || value === 'denied' ? value : 'default';
11
+ /**
12
+ * OS notifications with the permission flow handled. Inside a Tauri window with
13
+ * `@tauri-apps/plugin-notification` they come from Rust; in a browser, or a window without the
14
+ * plugin, from the Web Notifications API; with neither, `notify()` resolves `false` (or shows a
15
+ * toast, given a `toaster`). A denied permission never throws.
16
+ *
17
+ * ```ts
18
+ * const notifications = createNotifications({ plugin: notification, toaster });
19
+ * // on a button: await notifications.requestPermission();
20
+ * // later, from anywhere:
21
+ * notifications.notify({ title: 'Export finished', body: 'The file is in Downloads.' });
22
+ * ```
23
+ */
24
+ export function createNotifications(options = {}) {
25
+ const { plugin, toaster } = options;
26
+ const web = webNotification();
27
+ const backend = plugin && isTauri() ? 'tauri' : web ? 'web' : 'none';
28
+ let permission = $state(backend === 'none' ? 'unsupported' : asState(web?.permission));
29
+ let destroyed = false;
30
+ const settle = (next) => {
31
+ if (!destroyed)
32
+ permission = next;
33
+ return next;
34
+ };
35
+ let ready = Promise.resolve();
36
+ if (backend === 'tauri') {
37
+ ready = plugin.isPermissionGranted().then((granted) => {
38
+ // `false` means denied or not asked; the web view's own state tells them apart.
39
+ settle(granted ? 'granted' : asState(web?.permission));
40
+ }, () => {
41
+ /* the plugin is installed in JS but not registered in Rust */
42
+ });
43
+ }
44
+ async function requestPermission() {
45
+ if (backend === 'none')
46
+ return permission;
47
+ await ready;
48
+ if (permission !== 'default')
49
+ return permission;
50
+ try {
51
+ const answer = backend === 'tauri' ? plugin.requestPermission() : web.requestPermission();
52
+ return settle(asState(await answer));
53
+ }
54
+ catch {
55
+ return permission;
56
+ }
57
+ }
58
+ function show({ title, body, icon, silent }) {
59
+ try {
60
+ if (backend === 'tauri')
61
+ plugin.sendNotification({ title, body, icon, silent });
62
+ else if (backend === 'web')
63
+ new web(title, { body, icon, silent });
64
+ else
65
+ return false;
66
+ return true;
67
+ }
68
+ catch {
69
+ // Android Chrome, for one, only notifies through a service worker.
70
+ return false;
71
+ }
72
+ }
73
+ async function notify(notification) {
74
+ await ready;
75
+ const shown = !destroyed && permission === 'granted' && show(notification);
76
+ if (!shown && !destroyed && toaster) {
77
+ toaster.info(notification.title, { description: notification.body });
78
+ }
79
+ return shown;
80
+ }
81
+ const destroy = () => {
82
+ destroyed = true;
83
+ };
84
+ try {
85
+ onDestroy(destroy);
86
+ }
87
+ catch {
88
+ /* module scope: the caller owns `destroy()` */
89
+ }
90
+ return {
91
+ backend,
92
+ get permission() {
93
+ return permission;
94
+ },
95
+ ready,
96
+ requestPermission,
97
+ notify,
98
+ destroy,
99
+ };
100
+ }
@@ -0,0 +1,37 @@
1
+ import type { OsPlugin, Teardown, UnlistenFn } from './types.js';
2
+ /** The operating system around a Tauri window. */
3
+ export type TauriPlatform = 'macos' | 'windows' | 'linux' | 'ios' | 'android';
4
+ export declare const noop: Teardown;
5
+ /**
6
+ * Whether the page runs inside a Tauri 2 window: `false` in a browser and on the server. Every
7
+ * adapter checks this first, so the same app code ships to the web untouched.
8
+ *
9
+ * It reads the same `isTauri` global as `isTauri()` from `@tauri-apps/api/core`, and also
10
+ * `__TAURI_INTERNALS__` (the IPC bridge itself), without importing the Tauri runtime.
11
+ */
12
+ export declare function isTauri(): boolean;
13
+ /**
14
+ * The OS around the Tauri window, or `null` in a browser and on the server. Pass
15
+ * `@tauri-apps/plugin-os` for the answer from Rust; without it the web view's user agent decides,
16
+ * which tells macOS, Windows and Linux apart reliably enough for styling.
17
+ */
18
+ export declare function tauriPlatform(os?: OsPlugin): TauriPlatform | null;
19
+ /**
20
+ * Writes `data-tauri-platform="macos"` (or `"windows"`, `"linux"`, …) on `<html>`, which
21
+ * `styles.css` keys its desktop manners to and which your own CSS can use for a platform-specific
22
+ * tweak. Returns the teardown. A no-op in a browser.
23
+ */
24
+ export declare function markTauriPlatform(element?: HTMLElement, os?: OsPlugin): Teardown;
25
+ /**
26
+ * Most calls here are cosmetic — a window tint, a menu label. A rejection (a plugin missing from
27
+ * the Rust side, a permission the capability file does not grant) must never surface as an
28
+ * unhandled error.
29
+ */
30
+ export declare function quietly(result: unknown): void;
31
+ /**
32
+ * Turns Tauri's promised unlisten function into a synchronous teardown. A teardown that runs
33
+ * before the function arrives still unlistens once it does.
34
+ */
35
+ export declare function listen(pending: Promise<UnlistenFn> | UnlistenFn): Teardown;
36
+ /** One teardown for several. */
37
+ export declare function combine(...teardowns: Array<Teardown | undefined>): Teardown;
@@ -0,0 +1,102 @@
1
+ export const noop = () => { };
2
+ /**
3
+ * Whether the page runs inside a Tauri 2 window: `false` in a browser and on the server. Every
4
+ * adapter checks this first, so the same app code ships to the web untouched.
5
+ *
6
+ * It reads the same `isTauri` global as `isTauri()` from `@tauri-apps/api/core`, and also
7
+ * `__TAURI_INTERNALS__` (the IPC bridge itself), without importing the Tauri runtime.
8
+ */
9
+ export function isTauri() {
10
+ if (typeof window === 'undefined' || typeof document === 'undefined')
11
+ return false;
12
+ const scope = globalThis;
13
+ return Boolean(scope.isTauri) || (scope.__TAURI_INTERNALS__ ?? null) !== null;
14
+ }
15
+ /** The OS as the web view's user agent reports it. */
16
+ function platformFromUserAgent() {
17
+ const agent = navigator.userAgent;
18
+ if (/iPhone|iPad|iPod/.test(agent))
19
+ return 'ios';
20
+ if (/Android/.test(agent))
21
+ return 'android';
22
+ if (/Windows/.test(agent))
23
+ return 'windows';
24
+ // iPadOS reports a desktop Mac; only it has a touch screen.
25
+ if (/Macintosh|Mac OS X/.test(agent))
26
+ return (navigator.maxTouchPoints ?? 0) > 1 ? 'ios' : 'macos';
27
+ return 'linux';
28
+ }
29
+ /**
30
+ * The OS around the Tauri window, or `null` in a browser and on the server. Pass
31
+ * `@tauri-apps/plugin-os` for the answer from Rust; without it the web view's user agent decides,
32
+ * which tells macOS, Windows and Linux apart reliably enough for styling.
33
+ */
34
+ export function tauriPlatform(os) {
35
+ if (!isTauri())
36
+ return null;
37
+ if (os) {
38
+ try {
39
+ return os.type();
40
+ }
41
+ catch {
42
+ /* the plugin is installed in JS but not registered in Rust */
43
+ }
44
+ }
45
+ return platformFromUserAgent();
46
+ }
47
+ /**
48
+ * Writes `data-tauri-platform="macos"` (or `"windows"`, `"linux"`, …) on `<html>`, which
49
+ * `styles.css` keys its desktop manners to and which your own CSS can use for a platform-specific
50
+ * tweak. Returns the teardown. A no-op in a browser.
51
+ */
52
+ export function markTauriPlatform(element, os) {
53
+ const platform = tauriPlatform(os);
54
+ const root = element ?? (typeof document === 'undefined' ? null : document.documentElement);
55
+ if (!platform || !root)
56
+ return noop;
57
+ root.dataset.tauriPlatform = platform;
58
+ return () => {
59
+ delete root.dataset.tauriPlatform;
60
+ };
61
+ }
62
+ /**
63
+ * Most calls here are cosmetic — a window tint, a menu label. A rejection (a plugin missing from
64
+ * the Rust side, a permission the capability file does not grant) must never surface as an
65
+ * unhandled error.
66
+ */
67
+ export function quietly(result) {
68
+ if (result && typeof result.catch === 'function') {
69
+ result.catch(() => { });
70
+ }
71
+ }
72
+ /**
73
+ * Turns Tauri's promised unlisten function into a synchronous teardown. A teardown that runs
74
+ * before the function arrives still unlistens once it does.
75
+ */
76
+ export function listen(pending) {
77
+ let removed = false;
78
+ let unlisten;
79
+ Promise.resolve(pending).then((resolved) => {
80
+ if (removed)
81
+ resolved();
82
+ else
83
+ unlisten = resolved;
84
+ }, () => { });
85
+ return () => {
86
+ if (removed)
87
+ return;
88
+ removed = true;
89
+ unlisten?.();
90
+ };
91
+ }
92
+ /** One teardown for several. */
93
+ export function combine(...teardowns) {
94
+ let done = false;
95
+ return () => {
96
+ if (done)
97
+ return;
98
+ done = true;
99
+ for (const teardown of teardowns)
100
+ teardown?.();
101
+ };
102
+ }
@@ -0,0 +1,135 @@
1
+ import type { Theme } from '@loidolt/theme-svelte';
2
+ import { type DeepLinkOptions } from './deep-links.js';
3
+ import { type FileDrop, type FileDropOptions } from './file-drop.svelte.js';
4
+ import { type DesktopFiles } from './files.js';
5
+ import { type Notifications, type NotificationsOptions } from './notifications.svelte.js';
6
+ import { type TauriPlatform } from './platform.js';
7
+ import { type MenuBar, type MenuBarOptions } from './menu-bar.svelte.js';
8
+ import { type SingleInstanceOptions } from './single-instance.js';
9
+ import { type Tray, type TrayOptions } from './tray.js';
10
+ import type { DeepLinkPlugin, DialogPlugin, FsPlugin, WebviewPlugin, EventModule, MenuModule, NotificationPlugin, OsPlugin, TrayModule, WindowPlugin } from './types.js';
11
+ import { type ShowWindowOptions, type WindowAppearanceOptions, type WindowChromeOptions } from './window.svelte.js';
12
+ /**
13
+ * The Tauri modules you installed, passed as namespaces (`import * as os from
14
+ * '@tauri-apps/plugin-os'`). Each one present turns on the adapters that use it.
15
+ */
16
+ export interface TauriPlugins {
17
+ /** `@tauri-apps/plugin-os`: the platform from Rust instead of the user agent. */
18
+ os?: OsPlugin;
19
+ /**
20
+ * The window: `getCurrentWindow` from `@tauri-apps/api/window`, or the window it returns. Pass
21
+ * the function itself to keep the layout browser-safe: it reads the Tauri runtime, so calling
22
+ * it in a browser throws, and `setupTauri` only calls it inside a window. Turns on the window
23
+ * background and appearance, the overlay title bar insets, and showing a window that starts
24
+ * hidden.
25
+ */
26
+ window?: WindowPlugin | (() => WindowPlugin);
27
+ /** `@tauri-apps/plugin-notification`: OS notifications from Rust. */
28
+ notification?: NotificationPlugin;
29
+ /** `@tauri-apps/api/event`: second launches, with `singleInstance`. */
30
+ event?: EventModule;
31
+ /** `@tauri-apps/plugin-deep-link`: URLs that open the app, with `deepLinks`. */
32
+ deepLink?: DeepLinkPlugin;
33
+ /** `@tauri-apps/api/tray` and `@tauri-apps/api/menu`: a tray icon, with `tray`. */
34
+ tray?: TrayModule;
35
+ /** `@tauri-apps/api/menu`: the tray's menu, with `tray`, and the menu bar, with `menuBar`. */
36
+ menu?: MenuModule;
37
+ /** `@tauri-apps/plugin-dialog`: native open and save dialogs, in `desktop.files`. */
38
+ dialog?: DialogPlugin;
39
+ /** `@tauri-apps/plugin-fs`: reading picked and dropped files, writing saved ones. */
40
+ fs?: FsPlugin;
41
+ /**
42
+ * The web view: `getCurrentWebview` from `@tauri-apps/api/webview`, uncalled like `window`, or
43
+ * the web view it returns. Files dropped on the window, with `fileDrop`.
44
+ */
45
+ webview?: WebviewPlugin | (() => WebviewPlugin);
46
+ }
47
+ /** `false` turns one adapter off even though its module is present. */
48
+ type Toggle<T> = T | false;
49
+ export interface SetupTauriOptions {
50
+ plugins?: TauriPlugins;
51
+ /** `data-tauri-platform` on `<html>`. On by default; `false` leaves the root alone. */
52
+ markPlatform?: boolean;
53
+ /**
54
+ * The app's `createTheme` store: the window's native light or dark appearance follows it, and
55
+ * `system` hands the appearance back to the OS. Needs `window`.
56
+ */
57
+ theme?: Theme;
58
+ /** The window background (and, with `theme`, appearance) following the page. Needs `window`. */
59
+ appearance?: Toggle<Omit<WindowAppearanceOptions, 'window' | 'theme'>>;
60
+ /**
61
+ * The title bar `tauri.conf.json` sets up. `{ titleBar: 'overlay' }` insets the page to clear
62
+ * the macOS window buttons. Needs `window`.
63
+ */
64
+ chrome?: Toggle<Omit<WindowChromeOptions, 'window'>>;
65
+ /**
66
+ * Shows the window once the theme has reached it and the fonts are in — pair it with
67
+ * `"visible": false` in `tauri.conf.json` for a launch with no flash. On by default; needs
68
+ * `window`.
69
+ */
70
+ show?: Toggle<Omit<ShowWindowOptions, 'window' | 'until'>>;
71
+ /**
72
+ * `desktop.notifications`: through `notification` in a window, the Web Notifications API in a
73
+ * browser. `false` leaves it out.
74
+ */
75
+ notifications?: Omit<NotificationsOptions, 'plugin'> | false;
76
+ /** Second launches of the app, forwarded by `tauri-plugin-single-instance`. Needs `event`. */
77
+ singleInstance?: Omit<SingleInstanceOptions, 'event'>;
78
+ /** Links that open the app, routed with `navigate` or `onUrl`. Needs `deepLink`. */
79
+ deepLinks?: Omit<DeepLinkOptions, 'deepLink'>;
80
+ /** A tray icon with a menu, as `desktop.tray`. Needs `tray` and `menu`. */
81
+ tray?: Omit<TrayOptions, 'tray' | 'menu'>;
82
+ /**
83
+ * `desktop.files`: native open and save dialogs through `dialog` and `fs` in a window, a file
84
+ * input and a download in a browser. `false` leaves it out.
85
+ */
86
+ files?: false;
87
+ /** Files dropped on the window, as `desktop.fileDrop`. Needs `webview`, and `fs` to read them. */
88
+ fileDrop?: Omit<FileDropOptions, 'webview' | 'fs'>;
89
+ /** The native menu bar, built from a command registry, as `desktop.menuBar`. Needs `menu`. */
90
+ menuBar?: Omit<MenuBarOptions, 'menu'>;
91
+ }
92
+ export interface TauriSetup {
93
+ /** The OS around the window, or `null` in a browser and on the server. */
94
+ readonly platform: TauriPlatform | null;
95
+ /**
96
+ * Settles once every adapter that needs a round trip to Rust has applied — with `window`, once
97
+ * the window has its background and appearance and has been shown. Never rejects.
98
+ */
99
+ readonly ready: Promise<void>;
100
+ /** OS notifications with their permission; absent with `notifications: false`. */
101
+ readonly notifications: Notifications | undefined;
102
+ /** Present when `tray` options and the `tray` and `menu` modules were given. */
103
+ readonly tray: Tray | undefined;
104
+ /** `pick()`, `pickPaths()` and `save()`; absent with `files: false`. */
105
+ readonly files: DesktopFiles | undefined;
106
+ /** Present when `fileDrop` options and the `webview` module were given; reactive `dragging`. */
107
+ readonly fileDrop: FileDrop | undefined;
108
+ /** Present when `menuBar` options and the `menu` module were given. */
109
+ readonly menuBar: MenuBar | undefined;
110
+ /** Removes everything. Automatic when called during component initialisation. */
111
+ destroy(): void;
112
+ }
113
+ /**
114
+ * Every adapter in one call, each turned on by the module it needs. Call it once, in the root
115
+ * layout, with what the app installed:
116
+ *
117
+ * ```svelte
118
+ * <script lang="ts">
119
+ * import { getCurrentWindow } from '@tauri-apps/api/window';
120
+ * import * as os from '@tauri-apps/plugin-os';
121
+ * import { setupTauri } from '@loidolt/theme-tauri';
122
+ * import { theme } from './theme';
123
+ *
124
+ * const desktop = setupTauri({
125
+ * plugins: { os, window: getCurrentWindow },
126
+ * theme,
127
+ * chrome: { titleBar: 'overlay' },
128
+ * });
129
+ * </script>
130
+ * ```
131
+ *
132
+ * In a browser (or on the server) every adapter is a no-op, so the same layout ships to the web.
133
+ */
134
+ export declare function setupTauri(options?: SetupTauriOptions): TauriSetup;
135
+ export {};
package/dist/setup.js ADDED
@@ -0,0 +1,91 @@
1
+ import { onDestroy } from 'svelte';
2
+ import { handleDeepLinks } from './deep-links.js';
3
+ import { createFileDrop } from './file-drop.svelte.js';
4
+ import { createDesktopFiles } from './files.js';
5
+ import { createNotifications, } from './notifications.svelte.js';
6
+ import { combine, isTauri, markTauriPlatform, tauriPlatform, } from './platform.js';
7
+ import { createMenuBar, isMenuBarModule, } from './menu-bar.svelte.js';
8
+ import { handleSecondInstance } from './single-instance.js';
9
+ import { createTray } from './tray.js';
10
+ import { insetWindowChrome, showWindow, syncWindowAppearance, } from './window.svelte.js';
11
+ const on = (value) => value === false ? null : (value ?? {});
12
+ /**
13
+ * Every adapter in one call, each turned on by the module it needs. Call it once, in the root
14
+ * layout, with what the app installed:
15
+ *
16
+ * ```svelte
17
+ * <script lang="ts">
18
+ * import { getCurrentWindow } from '@tauri-apps/api/window';
19
+ * import * as os from '@tauri-apps/plugin-os';
20
+ * import { setupTauri } from '@loidolt/theme-tauri';
21
+ * import { theme } from './theme';
22
+ *
23
+ * const desktop = setupTauri({
24
+ * plugins: { os, window: getCurrentWindow },
25
+ * theme,
26
+ * chrome: { titleBar: 'overlay' },
27
+ * });
28
+ * </script>
29
+ * ```
30
+ *
31
+ * In a browser (or on the server) every adapter is a no-op, so the same layout ships to the web.
32
+ */
33
+ export function setupTauri(options = {}) {
34
+ const { os, window: windowOption, notification, event, deepLink, tray: trayModule, menu, dialog, fs, webview, } = options.plugins ?? {};
35
+ const platform = tauriPlatform(os);
36
+ const win = typeof windowOption === 'function' ? (isTauri() ? windowOption() : undefined) : windowOption;
37
+ const teardowns = [];
38
+ if (options.markPlatform !== false)
39
+ teardowns.push(markTauriPlatform(undefined, os));
40
+ let notifications;
41
+ if (options.notifications !== false) {
42
+ notifications = createNotifications({ ...options.notifications, plugin: notification });
43
+ teardowns.push(notifications.destroy);
44
+ }
45
+ if (event && options.singleInstance) {
46
+ teardowns.push(handleSecondInstance({ ...options.singleInstance, event }));
47
+ }
48
+ if (deepLink && options.deepLinks) {
49
+ teardowns.push(handleDeepLinks({ ...options.deepLinks, deepLink }));
50
+ }
51
+ let tray;
52
+ if (trayModule && menu && options.tray) {
53
+ tray = createTray({ ...options.tray, tray: trayModule, menu });
54
+ teardowns.push(tray.destroy);
55
+ }
56
+ const files = options.files === false ? undefined : createDesktopFiles({ dialog, fs });
57
+ let fileDrop;
58
+ if (webview && options.fileDrop) {
59
+ fileDrop = createFileDrop({ ...options.fileDrop, webview, fs });
60
+ teardowns.push(fileDrop.destroy);
61
+ }
62
+ let menuBar;
63
+ if (menu && options.menuBar && isMenuBarModule(menu)) {
64
+ menuBar = createMenuBar({ ...options.menuBar, menu }, os);
65
+ teardowns.push(menuBar.destroy);
66
+ }
67
+ let windowReady = Promise.resolve();
68
+ if (win) {
69
+ const appearanceOptions = on(options.appearance);
70
+ const appearance = appearanceOptions
71
+ ? syncWindowAppearance({ ...appearanceOptions, window: win, theme: options.theme }, os)
72
+ : undefined;
73
+ if (appearance)
74
+ teardowns.push(appearance.destroy);
75
+ const chrome = on(options.chrome);
76
+ if (chrome)
77
+ teardowns.push(insetWindowChrome({ ...chrome, window: win }, os));
78
+ const applied = appearance?.ready ?? Promise.resolve();
79
+ const show = on(options.show);
80
+ windowReady = show ? showWindow({ ...show, window: win, until: applied }, os) : applied;
81
+ }
82
+ const ready = Promise.all([windowReady, notifications?.ready, tray?.ready, menuBar?.ready]).then(() => { });
83
+ const destroy = combine(...teardowns);
84
+ try {
85
+ onDestroy(destroy);
86
+ }
87
+ catch {
88
+ /* module scope: the caller owns `destroy()` */
89
+ }
90
+ return { platform, ready, notifications, tray, menuBar, files, fileDrop, destroy };
91
+ }
@@ -0,0 +1,34 @@
1
+ import type { EventModule, Teardown } from './types.js';
2
+ /** A second launch of the app, forwarded to the running one. */
3
+ export interface SecondInstance {
4
+ /** The second process's command line, starting with the executable. */
5
+ args: string[];
6
+ /** Its working directory, against which relative paths in `args` resolve. */
7
+ cwd: string;
8
+ /**
9
+ * The files it was asked to open: sent by Rust when it knows them (files opened from the macOS
10
+ * Finder), otherwise read from `args` with {@link filesFromArgs}.
11
+ */
12
+ files: string[];
13
+ }
14
+ export interface SingleInstanceOptions {
15
+ /** `@tauri-apps/api/event`. */
16
+ event: EventModule;
17
+ /** Called for each second launch, after Rust has focused the existing window. */
18
+ onSecondInstance: (launch: SecondInstance) => void;
19
+ /** The event Rust emits. Defaults to `'single-instance'`. */
20
+ eventName?: string;
21
+ }
22
+ /**
23
+ * The file paths in a command line: everything after the executable that is not a flag
24
+ * (`-x`, `--flag`) or a URL, with relative paths resolved against `cwd`. `file://` URLs become
25
+ * paths. Everything after a lone `--` counts as a path, flags included.
26
+ */
27
+ export declare function filesFromArgs(args: readonly string[], cwd?: string): string[];
28
+ /**
29
+ * Hands each second launch of the app to `onSecondInstance` with its arguments and files.
30
+ * `tauri-plugin-single-instance` is Rust-only: register it first in `src-tauri/src/lib.rs` with a
31
+ * callback that focuses the main window and emits the launch as an event (see the README); this
32
+ * listens for that event. A no-op outside a Tauri window.
33
+ */
34
+ export declare function handleSecondInstance(options: SingleInstanceOptions): Teardown;
@@ -0,0 +1,69 @@
1
+ import { isTauri, listen, noop } from './platform.js';
2
+ const windowsPath = /^[A-Za-z]:[\\/]|^\\\\/;
3
+ const scheme = /^[A-Za-z][A-Za-z0-9+.-]+:/;
4
+ /**
5
+ * The file paths in a command line: everything after the executable that is not a flag
6
+ * (`-x`, `--flag`) or a URL, with relative paths resolved against `cwd`. `file://` URLs become
7
+ * paths. Everything after a lone `--` counts as a path, flags included.
8
+ */
9
+ export function filesFromArgs(args, cwd = '') {
10
+ const files = [];
11
+ let literal = false;
12
+ for (const arg of args.slice(1)) {
13
+ if (!literal && arg === '--') {
14
+ literal = true;
15
+ continue;
16
+ }
17
+ if (!arg || (!literal && arg.startsWith('-')))
18
+ continue;
19
+ if (arg.startsWith('file://')) {
20
+ const path = fileUrlPath(arg);
21
+ if (path)
22
+ files.push(path);
23
+ continue;
24
+ }
25
+ if (!windowsPath.test(arg) && scheme.test(arg))
26
+ continue;
27
+ files.push(resolve(arg, cwd));
28
+ }
29
+ return files;
30
+ }
31
+ function fileUrlPath(url) {
32
+ try {
33
+ const path = decodeURIComponent(new URL(url).pathname);
34
+ // file:///C:/Users/… → C:/Users/…
35
+ return /^\/[A-Za-z]:\//.test(path) ? path.slice(1) : path;
36
+ }
37
+ catch {
38
+ return null;
39
+ }
40
+ }
41
+ function resolve(path, cwd) {
42
+ if (path.startsWith('/') || windowsPath.test(path) || !cwd)
43
+ return path;
44
+ const separator = cwd.includes('\\') && !cwd.includes('/') ? '\\' : '/';
45
+ const relative = path.replace(/^\.[\\/]/, '');
46
+ return cwd.endsWith(separator) ? cwd + relative : cwd + separator + relative;
47
+ }
48
+ /**
49
+ * Hands each second launch of the app to `onSecondInstance` with its arguments and files.
50
+ * `tauri-plugin-single-instance` is Rust-only: register it first in `src-tauri/src/lib.rs` with a
51
+ * callback that focuses the main window and emits the launch as an event (see the README); this
52
+ * listens for that event. A no-op outside a Tauri window.
53
+ */
54
+ export function handleSecondInstance(options) {
55
+ if (!isTauri())
56
+ return noop;
57
+ const { event, onSecondInstance, eventName = 'single-instance' } = options;
58
+ try {
59
+ return listen(event.listen(eventName, ({ payload }) => {
60
+ const args = Array.isArray(payload?.args) ? payload.args : [];
61
+ const cwd = typeof payload?.cwd === 'string' ? payload.cwd : '';
62
+ const files = Array.isArray(payload?.files) ? payload.files : filesFromArgs(args, cwd);
63
+ onSecondInstance({ args, cwd, files });
64
+ }));
65
+ }
66
+ catch {
67
+ return noop;
68
+ }
69
+ }
@@ -0,0 +1,35 @@
1
+ /*
2
+ * @loidolt/theme-tauri — the stylesheet half of the desktop adapters. Import it after the theme.
3
+ * Every rule is zero-specificity (`:where`), so the app's own CSS always wins, and every rule is
4
+ * inert in a browser: it keys to `data-tauri-platform`, which only `markTauriPlatform` (or
5
+ * `setupTauri`) writes, and only inside a Tauri window.
6
+ */
7
+
8
+ /*
9
+ * Desktop manners: clicking or dragging across the app's chrome does not select its labels, as
10
+ * in a native window. Content stays selectable.
11
+ */
12
+ :where([data-tauri-platform])
13
+ :where(
14
+ .ldt-button,
15
+ .ldt-icon-button,
16
+ .ldt-switch,
17
+ .ldt-tabs__trigger,
18
+ .ldt-toggle-group,
19
+ .ldt-segmented-nav,
20
+ .ldt-nav-menu,
21
+ .ldt-tab-bar,
22
+ .ldt-topbar
23
+ ) {
24
+ -webkit-user-select: none;
25
+ user-select: none;
26
+ }
27
+
28
+ /*
29
+ * An overlay title bar with the macOS window buttons in the topbar's own row (`insetWindowChrome`
30
+ * with `trafficLights: 'beside'`): the bar alone is inset from the left to clear them. The
31
+ * attribute is gone in full screen, where the buttons hide.
32
+ */
33
+ :where([data-tauri-platform][data-tauri-traffic-lights='beside']) :where(.ldt-topbar) {
34
+ --ldt-safe-left: var(--ldt-tauri-traffic-lights, 78px);
35
+ }
package/dist/tray.d.ts ADDED
@@ -0,0 +1,68 @@
1
+ import type { MenuModule, TrayImage, TrayModule } from './types.js';
2
+ /**
3
+ * One line of the tray menu; `'separator'` for a rule between groups, `'quit'` for the platform's
4
+ * own Quit item (macOS and Windows).
5
+ */
6
+ export type TrayMenuItem = {
7
+ id: string;
8
+ label: string;
9
+ /** Greyed out when `false`. Defaults to `true`. */
10
+ enabled?: boolean;
11
+ /** Runs when the item is chosen. */
12
+ action?: () => void;
13
+ } | 'separator' | 'quit';
14
+ export interface TrayContent {
15
+ /**
16
+ * A path, PNG or ICO bytes, or an `Image`, or a promise of one — pass `defaultWindowIcon()`
17
+ * from `@tauri-apps/api/app` for the app's own icon. Without one, macOS shows only `title`.
18
+ */
19
+ icon?: TrayImage | Promise<TrayImage | null> | null;
20
+ /** The hover text. Not shown on Linux. */
21
+ tooltip?: string;
22
+ /** Text beside the icon in the macOS menu bar. */
23
+ title?: string;
24
+ /** The menu, top to bottom. Empty or absent: no menu. */
25
+ items?: TrayMenuItem[];
26
+ }
27
+ export interface TrayOptions extends TrayContent {
28
+ /** `@tauri-apps/api/tray`. */
29
+ tray: TrayModule;
30
+ /** `@tauri-apps/api/menu`. */
31
+ menu: MenuModule;
32
+ /** A stable id, for finding the icon from Rust. */
33
+ id?: string;
34
+ /** macOS: draw the icon as a template image, tinted to match the menu bar. */
35
+ iconAsTemplate?: boolean;
36
+ /**
37
+ * A left click on the icon — showing the main window, say. With it, the menu opens on a right
38
+ * click only (macOS, Windows).
39
+ */
40
+ onClick?: () => void;
41
+ }
42
+ export interface Tray {
43
+ /** Settles once the icon is in the tray (or failed to get there). */
44
+ readonly ready: Promise<void>;
45
+ /** Changes what is given and leaves the rest. A no-op once destroyed. */
46
+ update(changes: TrayContent): Promise<void>;
47
+ /** Removes the icon and frees its menu. Safe to call twice, even before {@link ready}. */
48
+ destroy(): void;
49
+ }
50
+ /**
51
+ * An icon in the menu bar (macOS) or system tray (Windows, Linux) with a simple menu, for an app
52
+ * that keeps working with its window closed. A no-op outside a Tauri window.
53
+ *
54
+ * ```ts
55
+ * const tray = createTray({
56
+ * tray, menu, // import * as tray from '@tauri-apps/api/tray', and menu likewise
57
+ * icon: defaultWindowIcon(),
58
+ * tooltip: 'Watching for new files',
59
+ * items: [
60
+ * { id: 'show', label: 'Show window', action: show },
61
+ * 'separator',
62
+ * { id: 'quit', label: 'Quit', action: quit },
63
+ * ],
64
+ * });
65
+ * tray.update({ tooltip: '2 jobs running' });
66
+ * ```
67
+ */
68
+ export declare function createTray(options: TrayOptions): Tray;