@octanejs/tauri 0.0.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 +129 -0
- package/package.json +51 -0
- package/src/index.ts +13 -0
- package/src/internal.ts +94 -0
- package/src/useInvoke.ts +54 -0
- package/src/useInvokeState.ts +113 -0
- package/src/useTauriEvent.ts +110 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Dominic Gannaway
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
# @octanejs/tauri
|
|
2
|
+
|
|
3
|
+
Octane hooks for [Tauri](https://tauri.app) v2 desktop apps.
|
|
4
|
+
|
|
5
|
+
Octane already runs inside a Tauri webview with no adapter: a zero-config Vite
|
|
6
|
+
project builds to static assets that `frontendDist` serves. What that leaves
|
|
7
|
+
open is the lifecycle glue between Tauri's promise/callback IPC and Octane's
|
|
8
|
+
render model, which is all this package is.
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
pnpm add @octanejs/tauri @tauri-apps/api
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## `useInvoke(cmd, args?, options?)`
|
|
15
|
+
|
|
16
|
+
Runs a command and suspends until it resolves. Renders through `@try` /
|
|
17
|
+
`@pending` / `@catch` like any other suspending read.
|
|
18
|
+
|
|
19
|
+
```tsx
|
|
20
|
+
function Projects() @{
|
|
21
|
+
const projects = useInvoke<Project[]>('list_projects', { archived: false });
|
|
22
|
+
<ul>
|
|
23
|
+
@for (const project of projects; key project.id) {
|
|
24
|
+
<li>{project.name as string}</li>
|
|
25
|
+
}
|
|
26
|
+
</ul>
|
|
27
|
+
}
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
The promise is memoized on the call-site slot, so a replay never re-runs the
|
|
31
|
+
command. The default refetch key is the command name plus the *values* of a
|
|
32
|
+
record argument, so the `{ archived: false }` literal above does not refetch on
|
|
33
|
+
every render. That serialization costs one pass over the record per render,
|
|
34
|
+
which is nothing for the small argument objects commands take; array and binary
|
|
35
|
+
payloads are compared by identity instead.
|
|
36
|
+
|
|
37
|
+
`options.headers` is keyed the same way, so rotating an `Authorization` value
|
|
38
|
+
issues a new command instead of serving the one the previous token fetched.
|
|
39
|
+
|
|
40
|
+
`options.deps` replaces the argument half of that key, not the command name or
|
|
41
|
+
the headers: both are always part of it, so a changed command or credential can
|
|
42
|
+
never keep serving the previous one's result.
|
|
43
|
+
|
|
44
|
+
Writing `use(invoke('cmd', args))` directly in a `.tsrx` file also works and
|
|
45
|
+
gets the compiler's parallel-`use()` treatment. Reach for `useInvoke` when you
|
|
46
|
+
want explicit `deps`, or when the call lives in a plain `.ts` custom hook where
|
|
47
|
+
no template transform applies.
|
|
48
|
+
|
|
49
|
+
## `useInvokeState(cmd, args?, options?)`
|
|
50
|
+
|
|
51
|
+
The non-suspending form, for a button that reports its own progress.
|
|
52
|
+
|
|
53
|
+
```tsx
|
|
54
|
+
const { status, data, error, refetch } = useInvokeState<string>('sync_now');
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
`refetch()` returns the state to `pending` and clears `data`. There is no
|
|
58
|
+
stale-while-revalidate here on purpose: caching, retries, and background
|
|
59
|
+
refetching are a query library's job, and `@octanejs/tanstack-query` already
|
|
60
|
+
does that over any promise, including `invoke`.
|
|
61
|
+
|
|
62
|
+
## `useTauriEvent(event, handler, options?)`
|
|
63
|
+
|
|
64
|
+
Subscribes for the lifetime of the call site.
|
|
65
|
+
|
|
66
|
+
```tsx
|
|
67
|
+
useTauriEvent<Progress>('sync:progress', (received) => setProgress(received.payload));
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
`listen()` resolves its unlisten function *asynchronously*. A component that
|
|
71
|
+
unmounts before that lands leaks the listener, which is the single most common
|
|
72
|
+
Tauri lifecycle bug in a hand-written `useEffect`; this hook detaches either
|
|
73
|
+
way. `handler` is read through a ref, so an inline closure does not resubscribe:
|
|
74
|
+
only `event`, `options.target`, and `options.enabled` do.
|
|
75
|
+
|
|
76
|
+
A failed subscription is thrown by default, so a missing `core:event` permission
|
|
77
|
+
in the capability file is loud rather than a silently dead feature. That costs
|
|
78
|
+
the subtree: a component that throws never commits, so it cannot retry on its
|
|
79
|
+
own and only the boundary's `reset()` brings it back.
|
|
80
|
+
|
|
81
|
+
For a supplementary subscription whose loss should not take the subtree down,
|
|
82
|
+
pass `onError` instead. The component stays mounted, so changing `event` or
|
|
83
|
+
flipping `enabled` retries the subscription:
|
|
84
|
+
|
|
85
|
+
```tsx
|
|
86
|
+
useTauriEvent<Progress>('sync:progress', onProgress, {
|
|
87
|
+
enabled: watching,
|
|
88
|
+
onError: (error) => setBanner(describe(error)),
|
|
89
|
+
});
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Off-host behavior
|
|
93
|
+
|
|
94
|
+
Everything is guarded on `window.__TAURI_INTERNALS__`, so a plain browser tab or
|
|
95
|
+
an SSR pass never faults on a missing bridge:
|
|
96
|
+
|
|
97
|
+
| | no Tauri host |
|
|
98
|
+
| --- | --- |
|
|
99
|
+
| `useInvoke` | rejects with `TauriUnavailableError` (reaches `@catch`) |
|
|
100
|
+
| `useInvokeState` | `status: 'error'` with `TauriUnavailableError` |
|
|
101
|
+
| `useTauriEvent` | throws `TauriUnavailableError` from the boundary |
|
|
102
|
+
|
|
103
|
+
Server rendering performs no IPC at all: `useInvokeState` renders `pending` and
|
|
104
|
+
issues the command on the client after hydration.
|
|
105
|
+
|
|
106
|
+
To preview or test the app in an ordinary browser, install Tauri's own mock
|
|
107
|
+
bridge and the hooks behave normally:
|
|
108
|
+
|
|
109
|
+
```ts
|
|
110
|
+
import { mockIPC } from '@tauri-apps/api/mocks';
|
|
111
|
+
|
|
112
|
+
mockIPC((cmd, args) => {
|
|
113
|
+
if (cmd === 'list_projects') return fixtureProjects;
|
|
114
|
+
return null;
|
|
115
|
+
}, { shouldMockEvents: true });
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
`examples/workbench` does exactly that, which is how its browser journeys run
|
|
119
|
+
without a Rust toolchain.
|
|
120
|
+
|
|
121
|
+
## Not covered
|
|
122
|
+
|
|
123
|
+
The rest of `@tauri-apps/api` (window, webview, menu, tray, path, dpi, image)
|
|
124
|
+
and the `@tauri-apps/plugin-*` packages are already framework-neutral. Import
|
|
125
|
+
them directly; wrapping them here would only add a version-coupled second copy
|
|
126
|
+
of an API that does not need render integration.
|
|
127
|
+
|
|
128
|
+
`Channel<T>` streaming has no hook yet. Construct it in a `useMemo` so its
|
|
129
|
+
identity is stable across renders, and keep the handler in a ref.
|
package/package.json
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@octanejs/tauri",
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"engines": {
|
|
7
|
+
"node": ">=22"
|
|
8
|
+
},
|
|
9
|
+
"octane": {
|
|
10
|
+
"hookSlots": {
|
|
11
|
+
"manual": [
|
|
12
|
+
"src"
|
|
13
|
+
]
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"description": "Tauri bindings for the octane renderer — Octane hooks over the framework-neutral @tauri-apps/api command and event surface.",
|
|
17
|
+
"author": {
|
|
18
|
+
"name": "Dominic Gannaway",
|
|
19
|
+
"email": "dg@domgan.com"
|
|
20
|
+
},
|
|
21
|
+
"publishConfig": {
|
|
22
|
+
"access": "public"
|
|
23
|
+
},
|
|
24
|
+
"repository": {
|
|
25
|
+
"type": "git",
|
|
26
|
+
"url": "git+https://github.com/octanejs/octane.git",
|
|
27
|
+
"directory": "packages/tauri"
|
|
28
|
+
},
|
|
29
|
+
"main": "src/index.ts",
|
|
30
|
+
"module": "src/index.ts",
|
|
31
|
+
"types": "src/index.ts",
|
|
32
|
+
"files": [
|
|
33
|
+
"src",
|
|
34
|
+
"README.md"
|
|
35
|
+
],
|
|
36
|
+
"exports": {
|
|
37
|
+
".": "./src/index.ts"
|
|
38
|
+
},
|
|
39
|
+
"peerDependencies": {
|
|
40
|
+
"@tauri-apps/api": ">=2.0.0",
|
|
41
|
+
"octane": "0.1.17"
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"@tauri-apps/api": "2.11.1",
|
|
45
|
+
"vitest": "^4.1.10",
|
|
46
|
+
"octane": "0.1.17"
|
|
47
|
+
},
|
|
48
|
+
"scripts": {
|
|
49
|
+
"test": "vitest run"
|
|
50
|
+
}
|
|
51
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export { TauriUnavailableError } from './internal';
|
|
2
|
+
export * from './useInvoke';
|
|
3
|
+
export * from './useInvokeState';
|
|
4
|
+
export * from './useTauriEvent';
|
|
5
|
+
|
|
6
|
+
export type { InvokeArgs } from '@tauri-apps/api/core';
|
|
7
|
+
export type {
|
|
8
|
+
Event,
|
|
9
|
+
EventCallback,
|
|
10
|
+
EventName,
|
|
11
|
+
EventTarget,
|
|
12
|
+
UnlistenFn,
|
|
13
|
+
} from '@tauri-apps/api/event';
|
package/src/internal.ts
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import type { InvokeArgs } from '@tauri-apps/api/core';
|
|
2
|
+
|
|
3
|
+
const subSlotCache = new Map<symbol, Map<string, symbol>>();
|
|
4
|
+
const bareTagCache = new Map<string, symbol>();
|
|
5
|
+
|
|
6
|
+
export function subSlot(slot: symbol | undefined, tag: string): symbol {
|
|
7
|
+
if (slot === undefined) {
|
|
8
|
+
let bare = bareTagCache.get(tag);
|
|
9
|
+
if (bare === undefined) bareTagCache.set(tag, (bare = Symbol.for(':' + tag)));
|
|
10
|
+
return bare;
|
|
11
|
+
}
|
|
12
|
+
let byTag = subSlotCache.get(slot);
|
|
13
|
+
if (byTag === undefined) subSlotCache.set(slot, (byTag = new Map()));
|
|
14
|
+
let derived = byTag.get(tag);
|
|
15
|
+
if (derived === undefined) {
|
|
16
|
+
byTag.set(tag, (derived = Symbol.for((slot.description ?? '') + ':' + tag)));
|
|
17
|
+
}
|
|
18
|
+
return derived;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function splitSlot(args: any[]): [any[], symbol | undefined] {
|
|
22
|
+
const tail = args[args.length - 1];
|
|
23
|
+
const slot = typeof tail === 'symbol' ? tail : undefined;
|
|
24
|
+
return [slot === undefined ? args : args.slice(0, -1), slot];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Raised where `@tauri-apps/api` would fault on a missing IPC bridge: during
|
|
29
|
+
* SSR, in a plain browser tab, and in a test that forgot `mockIPC`. The bare
|
|
30
|
+
* `window.__TAURI_INTERNALS__` TypeError names nothing the caller can act on.
|
|
31
|
+
*/
|
|
32
|
+
export class TauriUnavailableError extends Error {
|
|
33
|
+
constructor(what: string) {
|
|
34
|
+
super(
|
|
35
|
+
`${what} requires a Tauri host: window.__TAURI_INTERNALS__ is not present. ` +
|
|
36
|
+
'Run the app through Tauri, or install @tauri-apps/api/mocks in tests and browser previews.',
|
|
37
|
+
);
|
|
38
|
+
this.name = 'TauriUnavailableError';
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function hasTauriHost(): boolean {
|
|
43
|
+
return typeof window !== 'undefined' && (window as any).__TAURI_INTERNALS__ != null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function isPlainRecord(args: InvokeArgs): args is Record<string, unknown> {
|
|
47
|
+
return (
|
|
48
|
+
typeof args === 'object' &&
|
|
49
|
+
!Array.isArray(args) &&
|
|
50
|
+
!ArrayBuffer.isView(args) &&
|
|
51
|
+
!(args instanceof ArrayBuffer)
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function stableStringify(value: unknown): string {
|
|
56
|
+
return JSON.stringify(value, (_key, raw) => {
|
|
57
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return raw;
|
|
58
|
+
const sorted: Record<string, unknown> = {};
|
|
59
|
+
for (const key of Object.keys(raw as Record<string, unknown>).sort()) {
|
|
60
|
+
sorted[key] = (raw as Record<string, unknown>)[key];
|
|
61
|
+
}
|
|
62
|
+
return sorted;
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Default refetch key for a command's arguments. A record is serialized so the
|
|
68
|
+
* ubiquitous `invoke('cmd', { id })` object literal does not refetch on every
|
|
69
|
+
* render, which costs one pass over the record per render: fine for the small
|
|
70
|
+
* argument objects commands take, and `options.deps` opts out when it is not.
|
|
71
|
+
* Array and binary payloads are identity-compared instead, because serializing
|
|
72
|
+
* a buffer per render is never the cheaper trade.
|
|
73
|
+
*/
|
|
74
|
+
export function argsKey(args: InvokeArgs | undefined): unknown {
|
|
75
|
+
if (args === undefined) return undefined;
|
|
76
|
+
return isPlainRecord(args) ? stableStringify(args) : args;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Refetch key for `InvokeOptions.headers`. Headers reach the host on every
|
|
81
|
+
* request, so a rotated `Authorization` value has to refetch exactly like a
|
|
82
|
+
* changed argument would. Compared by value for the same reason `argsKey`
|
|
83
|
+
* compares a record by value: the inline `{ Authorization: token }` literal is
|
|
84
|
+
* the common case, and identity would refetch on every render.
|
|
85
|
+
*/
|
|
86
|
+
export function headersKey(headers: HeadersInit | undefined): unknown {
|
|
87
|
+
if (headers === undefined) return undefined;
|
|
88
|
+
// Header iteration is spec-ordered (lowercased, sorted), so it is canonical
|
|
89
|
+
// already; the other two forms go through the same key sort as arguments.
|
|
90
|
+
if (typeof Headers !== 'undefined' && headers instanceof Headers) {
|
|
91
|
+
return stableStringify([...headers]);
|
|
92
|
+
}
|
|
93
|
+
return stableStringify(headers);
|
|
94
|
+
}
|
package/src/useInvoke.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { invoke } from '@tauri-apps/api/core';
|
|
2
|
+
import type { InvokeArgs } from '@tauri-apps/api/core';
|
|
3
|
+
import { use, useMemo } from 'octane';
|
|
4
|
+
import {
|
|
5
|
+
TauriUnavailableError,
|
|
6
|
+
argsKey,
|
|
7
|
+
hasTauriHost,
|
|
8
|
+
headersKey,
|
|
9
|
+
splitSlot,
|
|
10
|
+
subSlot,
|
|
11
|
+
} from './internal';
|
|
12
|
+
|
|
13
|
+
export interface UseInvokeOptions {
|
|
14
|
+
/**
|
|
15
|
+
* Extra refetch key, appended to the command name and headers rather than
|
|
16
|
+
* replacing them, so a changed `cmd` or `headers` always refetches. Defaults
|
|
17
|
+
* to the argument values.
|
|
18
|
+
*/
|
|
19
|
+
deps?: readonly unknown[];
|
|
20
|
+
/** Request headers, forwarded to `invoke`'s `InvokeOptions`. */
|
|
21
|
+
headers?: HeadersInit;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function useInvoke<T>(cmd: string, args?: InvokeArgs, options?: UseInvokeOptions): T;
|
|
25
|
+
export function useInvoke<T>(
|
|
26
|
+
cmd: string,
|
|
27
|
+
args: InvokeArgs | undefined,
|
|
28
|
+
options: UseInvokeOptions | undefined,
|
|
29
|
+
slot: symbol | undefined,
|
|
30
|
+
): T;
|
|
31
|
+
export function useInvoke<T>(cmd: string, ...rest: [InvokeArgs?, UseInvokeOptions?, symbol?]): T {
|
|
32
|
+
const [args, slot] = splitSlot(rest);
|
|
33
|
+
const invokeArgs = args[0] as InvokeArgs | undefined;
|
|
34
|
+
const options = args[1] as UseInvokeOptions | undefined;
|
|
35
|
+
const headers = options?.headers;
|
|
36
|
+
const deps = [cmd, headersKey(headers), ...(options?.deps ?? [argsKey(invokeArgs)])];
|
|
37
|
+
|
|
38
|
+
const request = useMemo(
|
|
39
|
+
() => {
|
|
40
|
+
// Suspending on an absent bridge would hang the boundary until the SSR
|
|
41
|
+
// timeout with nothing to report; a rejection reaches @catch instead.
|
|
42
|
+
const pending = hasTauriHost()
|
|
43
|
+
? invoke<T>(cmd, invokeArgs, headers === undefined ? undefined : { headers })
|
|
44
|
+
: Promise.reject<T>(new TauriUnavailableError(`useInvoke('${cmd}')`));
|
|
45
|
+
// A deps change abandons this promise before use() ever observes it.
|
|
46
|
+
pending.catch(() => {});
|
|
47
|
+
return pending;
|
|
48
|
+
},
|
|
49
|
+
deps,
|
|
50
|
+
subSlot(slot, 'invoke:request'),
|
|
51
|
+
);
|
|
52
|
+
|
|
53
|
+
return use(request) as T;
|
|
54
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { invoke } from '@tauri-apps/api/core';
|
|
2
|
+
import type { InvokeArgs } from '@tauri-apps/api/core';
|
|
3
|
+
import { useCallback, useEffect, useMemo, useReducer, useState } from 'octane';
|
|
4
|
+
import {
|
|
5
|
+
TauriUnavailableError,
|
|
6
|
+
argsKey,
|
|
7
|
+
hasTauriHost,
|
|
8
|
+
headersKey,
|
|
9
|
+
splitSlot,
|
|
10
|
+
subSlot,
|
|
11
|
+
} from './internal';
|
|
12
|
+
import type { UseInvokeOptions } from './useInvoke';
|
|
13
|
+
|
|
14
|
+
export interface InvokeState<T> {
|
|
15
|
+
status: 'pending' | 'success' | 'error';
|
|
16
|
+
data: T | undefined;
|
|
17
|
+
error: unknown;
|
|
18
|
+
/** Re-run the command. Returns the state to `pending` and clears `data`. */
|
|
19
|
+
refetch: () => void;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
type Settled<T> = Pick<InvokeState<T>, 'status' | 'data' | 'error'>;
|
|
23
|
+
/** A settled result stamped with the request key that produced it. */
|
|
24
|
+
type Snapshot<T> = Settled<T> & { key: readonly unknown[] };
|
|
25
|
+
|
|
26
|
+
const PENDING: Settled<never> = { status: 'pending', data: undefined, error: undefined };
|
|
27
|
+
|
|
28
|
+
/** Elementwise `Object.is`, matching how the effect below compares the same key. */
|
|
29
|
+
function sameRequest(a: readonly unknown[], b: readonly unknown[]): boolean {
|
|
30
|
+
if (a.length !== b.length) return false;
|
|
31
|
+
for (let i = 0; i < a.length; i++) {
|
|
32
|
+
if (!Object.is(a[i], b[i])) return false;
|
|
33
|
+
}
|
|
34
|
+
return true;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function useInvokeState<T>(
|
|
38
|
+
cmd: string,
|
|
39
|
+
args?: InvokeArgs,
|
|
40
|
+
options?: UseInvokeOptions,
|
|
41
|
+
): InvokeState<T>;
|
|
42
|
+
export function useInvokeState<T>(
|
|
43
|
+
cmd: string,
|
|
44
|
+
args: InvokeArgs | undefined,
|
|
45
|
+
options: UseInvokeOptions | undefined,
|
|
46
|
+
slot: symbol | undefined,
|
|
47
|
+
): InvokeState<T>;
|
|
48
|
+
export function useInvokeState<T>(
|
|
49
|
+
cmd: string,
|
|
50
|
+
...rest: [InvokeArgs?, UseInvokeOptions?, symbol?]
|
|
51
|
+
): InvokeState<T> {
|
|
52
|
+
const [args, slot] = splitSlot(rest);
|
|
53
|
+
const invokeArgs = args[0] as InvokeArgs | undefined;
|
|
54
|
+
const options = args[1] as UseInvokeOptions | undefined;
|
|
55
|
+
const headers = options?.headers;
|
|
56
|
+
const deps = [cmd, headersKey(headers), ...(options?.deps ?? [argsKey(invokeArgs)])];
|
|
57
|
+
|
|
58
|
+
const [snapshot, setSnapshot] = useState<Snapshot<T> | null>(
|
|
59
|
+
null,
|
|
60
|
+
subSlot(slot, 'invokeState:settled'),
|
|
61
|
+
);
|
|
62
|
+
const [attempt, retry] = useReducer(
|
|
63
|
+
(count: number) => count + 1,
|
|
64
|
+
0,
|
|
65
|
+
subSlot(slot, 'invokeState:attempt'),
|
|
66
|
+
);
|
|
67
|
+
const request = [...deps, attempt];
|
|
68
|
+
|
|
69
|
+
// Deriving the reset rather than deferring it to the effect is what upholds
|
|
70
|
+
// the no-stale-while-revalidate contract: the very render that first observes
|
|
71
|
+
// a new command, args, or attempt reports `pending` instead of handing back
|
|
72
|
+
// the previous request's payload for a frame.
|
|
73
|
+
const settled: Settled<T> =
|
|
74
|
+
snapshot !== null && sameRequest(snapshot.key, request) ? snapshot : (PENDING as Settled<T>);
|
|
75
|
+
|
|
76
|
+
useEffect(
|
|
77
|
+
() => {
|
|
78
|
+
if (!hasTauriHost()) {
|
|
79
|
+
setSnapshot({
|
|
80
|
+
status: 'error',
|
|
81
|
+
data: undefined,
|
|
82
|
+
error: new TauriUnavailableError(`useInvokeState('${cmd}')`),
|
|
83
|
+
key: request,
|
|
84
|
+
});
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
let disposed = false;
|
|
88
|
+
invoke<T>(cmd, invokeArgs, headers === undefined ? undefined : { headers }).then(
|
|
89
|
+
(data) => {
|
|
90
|
+
// The cleanup below runs before a deps-change or refetch re-entry, so
|
|
91
|
+
// an in-flight command can never overwrite the request that replaced it.
|
|
92
|
+
if (!disposed) setSnapshot({ status: 'success', data, error: undefined, key: request });
|
|
93
|
+
},
|
|
94
|
+
(error) => {
|
|
95
|
+
if (!disposed) setSnapshot({ status: 'error', data: undefined, error, key: request });
|
|
96
|
+
},
|
|
97
|
+
);
|
|
98
|
+
return () => {
|
|
99
|
+
disposed = true;
|
|
100
|
+
};
|
|
101
|
+
},
|
|
102
|
+
request,
|
|
103
|
+
subSlot(slot, 'invokeState:effect'),
|
|
104
|
+
);
|
|
105
|
+
|
|
106
|
+
const refetch = useCallback(() => retry(0), [], subSlot(slot, 'invokeState:refetch'));
|
|
107
|
+
|
|
108
|
+
return useMemo(
|
|
109
|
+
() => ({ status: settled.status, data: settled.data, error: settled.error, refetch }),
|
|
110
|
+
[settled, refetch],
|
|
111
|
+
subSlot(slot, 'invokeState:result'),
|
|
112
|
+
);
|
|
113
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { listen } from '@tauri-apps/api/event';
|
|
2
|
+
import type {
|
|
3
|
+
EventCallback,
|
|
4
|
+
EventName,
|
|
5
|
+
EventTarget as TauriEventTarget,
|
|
6
|
+
UnlistenFn,
|
|
7
|
+
} from '@tauri-apps/api/event';
|
|
8
|
+
import { useEffect, useReducer, useRef } from 'octane';
|
|
9
|
+
import { TauriUnavailableError, hasTauriHost, splitSlot, subSlot } from './internal';
|
|
10
|
+
|
|
11
|
+
export interface UseTauriEventOptions {
|
|
12
|
+
/** Event target to listen to. Defaults to `{ kind: 'Any' }`. */
|
|
13
|
+
target?: string | TauriEventTarget;
|
|
14
|
+
/** Subscribe only while true. Defaults to true. */
|
|
15
|
+
enabled?: boolean;
|
|
16
|
+
/**
|
|
17
|
+
* Receive a failed subscription instead of having it thrown to the enclosing
|
|
18
|
+
* boundary. Supply this for a supplementary subscription whose loss should
|
|
19
|
+
* not take the subtree down; leave it off so a missing capability is loud.
|
|
20
|
+
*/
|
|
21
|
+
onError?: (error: unknown) => void;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function targetKey(target: string | TauriEventTarget | undefined): string | undefined {
|
|
25
|
+
if (target === undefined || typeof target === 'string') return target;
|
|
26
|
+
return 'label' in target ? `${target.kind}:${target.label}` : target.kind;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Subscribe to a Tauri event for the lifetime of the call site.
|
|
31
|
+
*
|
|
32
|
+
* `handler` and `onError` are read through refs, so an inline closure does not
|
|
33
|
+
* resubscribe: only `event`, `target`, and `enabled` do.
|
|
34
|
+
*/
|
|
35
|
+
export function useTauriEvent<T>(
|
|
36
|
+
event: EventName,
|
|
37
|
+
handler: EventCallback<T>,
|
|
38
|
+
options?: UseTauriEventOptions,
|
|
39
|
+
): void;
|
|
40
|
+
export function useTauriEvent<T>(
|
|
41
|
+
event: EventName,
|
|
42
|
+
handler: EventCallback<T>,
|
|
43
|
+
options: UseTauriEventOptions | undefined,
|
|
44
|
+
slot: symbol | undefined,
|
|
45
|
+
): void;
|
|
46
|
+
export function useTauriEvent<T>(
|
|
47
|
+
event: EventName,
|
|
48
|
+
handler: EventCallback<T>,
|
|
49
|
+
...rest: [UseTauriEventOptions?, symbol?]
|
|
50
|
+
): void {
|
|
51
|
+
const [args, slot] = splitSlot(rest);
|
|
52
|
+
const options = args[0] as UseTauriEventOptions | undefined;
|
|
53
|
+
const enabled = options?.enabled ?? true;
|
|
54
|
+
const target = options?.target;
|
|
55
|
+
|
|
56
|
+
const latest = useRef(handler, subSlot(slot, 'event:handler'));
|
|
57
|
+
latest.current = handler;
|
|
58
|
+
const latestOnError = useRef(options?.onError, subSlot(slot, 'event:onError'));
|
|
59
|
+
latestOnError.current = options?.onError;
|
|
60
|
+
const failure = useRef<unknown>(undefined, subSlot(slot, 'event:failure'));
|
|
61
|
+
const [, rerender] = useReducer((count: number) => count + 1, 0, subSlot(slot, 'event:update'));
|
|
62
|
+
|
|
63
|
+
useEffect(
|
|
64
|
+
() => {
|
|
65
|
+
if (!enabled) return;
|
|
66
|
+
// Reporting through onError keeps the component committed, so flipping
|
|
67
|
+
// `enabled` or changing the event retries. A thrown failure destroys the
|
|
68
|
+
// component instead, and only the boundary's reset() brings it back.
|
|
69
|
+
const report = (error: unknown) => {
|
|
70
|
+
const onError = latestOnError.current;
|
|
71
|
+
if (onError !== undefined) onError(error);
|
|
72
|
+
else {
|
|
73
|
+
failure.current = error;
|
|
74
|
+
rerender(0);
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
if (!hasTauriHost()) {
|
|
79
|
+
report(new TauriUnavailableError(`useTauriEvent('${event}')`));
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
// listen() resolves its unlisten function asynchronously. Unmounting
|
|
83
|
+
// before that lands must still detach, or the listener outlives the
|
|
84
|
+
// component and its handler ref forever.
|
|
85
|
+
let disposed = false;
|
|
86
|
+
let unlisten: UnlistenFn | undefined;
|
|
87
|
+
listen<T>(
|
|
88
|
+
event,
|
|
89
|
+
(payload) => latest.current(payload),
|
|
90
|
+
target === undefined ? undefined : { target },
|
|
91
|
+
).then(
|
|
92
|
+
(stop) => {
|
|
93
|
+
if (disposed) stop();
|
|
94
|
+
else unlisten = stop;
|
|
95
|
+
},
|
|
96
|
+
(error) => {
|
|
97
|
+
if (!disposed) report(error);
|
|
98
|
+
},
|
|
99
|
+
);
|
|
100
|
+
return () => {
|
|
101
|
+
disposed = true;
|
|
102
|
+
unlisten?.();
|
|
103
|
+
};
|
|
104
|
+
},
|
|
105
|
+
[event, enabled, targetKey(target)],
|
|
106
|
+
subSlot(slot, 'event:effect'),
|
|
107
|
+
);
|
|
108
|
+
|
|
109
|
+
if (failure.current !== undefined) throw failure.current;
|
|
110
|
+
}
|