tauri-plugin-live-activity 0.3.0 → 0.5.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.ko.md +26 -8
- package/README.md +26 -9
- package/cli/ios.mjs +65 -46
- package/cli/migration.mjs +55 -0
- package/cli/report.mjs +2 -2
- package/cli/setup.mjs +18 -7
- package/cli/steps.mjs +1 -1
- package/cli/templates/LiveActivityCustomViews.swift +25 -0
- package/cli/xcodegen.mjs +28 -20
- package/dist-js/index.d.ts +9 -5
- package/dist-js/index.js +7 -3
- package/dist-js/jsx/index.d.ts +59 -0
- package/dist-js/jsx/index.js +101 -0
- package/dist-js/jsx/jsx-dev-runtime.d.ts +4 -0
- package/dist-js/jsx/jsx-dev-runtime.js +6 -0
- package/dist-js/jsx/jsx-runtime.d.ts +16 -0
- package/dist-js/jsx/jsx-runtime.js +9 -0
- package/dist-js/react/index.d.ts +12 -0
- package/dist-js/react/index.js +42 -0
- package/dist-js/react/session.d.ts +68 -0
- package/dist-js/react/session.js +138 -0
- package/dist-js/types.d.ts +16 -3
- package/package.json +17 -4
package/README.ko.md
CHANGED
|
@@ -23,8 +23,12 @@ Tauri 2 앱이 하고 있는 일을 iPhone 잠금 화면과 Dynamic Island에, A
|
|
|
23
23
|
</table>
|
|
24
24
|
|
|
25
25
|
네 장 모두 고양이 Mochi를 따라가는 [데모 앱](https://github.com/1eedaegon/tauri-plugin-live-activity/tree/main/examples/demo)에서
|
|
26
|
-
캡처했습니다. 플러그인은 iOS 16.
|
|
27
|
-
`UNSUPPORTED_PLATFORM`을 돌려줍니다.
|
|
26
|
+
캡처했습니다. 플러그인은 iOS 16.2 이상과 Android 8 이상에서 동작하고, 데스크톱에서는 활동 명령이
|
|
27
|
+
`UNSUPPORTED_PLATFORM`을 돌려줍니다. iOS에서는 [activitykit](https://github.com/1eedaegon/activitykit-rs) 크레이트
|
|
28
|
+
위에서 동작하므로 플러그인 자체의 Swift 코드가 없습니다. Android에서는 진행률과 타이머 템플릿의 수명 주기를
|
|
29
|
+
[liveupdate](https://github.com/1eedaegon/liveupdate-rs) 크레이트로 Rust에서 처리합니다. 레이아웃도 이 크레이트가
|
|
30
|
+
안드로이드 알림 스타일로 그리고, 플러그인의 Kotlin은 권한 명령만 맡습니다. 1.0 전까지는 마이너 버전이 바뀔 때 API도 바뀔 수
|
|
31
|
+
있습니다.
|
|
28
32
|
|
|
29
33
|
## 설치
|
|
30
34
|
|
|
@@ -43,8 +47,9 @@ npx tauri-plugin-live-activity setup
|
|
|
43
47
|
```
|
|
44
48
|
|
|
45
49
|
`setup`은 플러그인 권한을 허용하고, Android 최소 버전을 API 26으로 올리고, Mac에서는 활동을 그리는
|
|
46
|
-
위젯 확장을 Xcode 프로젝트에 추가합니다. `tauri ios init` 뒤에 실행하고, 나중에
|
|
47
|
-
처음부터 다시 만들었다면 한 번 더 실행하세요.
|
|
50
|
+
위젯 확장을 activitykit의 Swift 패키지로 Xcode 프로젝트에 추가합니다. `tauri ios init` 뒤에 실행하고, 나중에
|
|
51
|
+
`src-tauri/gen/apple`을 처음부터 다시 만들었다면 한 번 더 실행하세요. 0.3으로 설정한 앱이라면 다시 한 번
|
|
52
|
+
실행하면 위젯과 직접 만든 뷰를 activitykit으로 옮겨 줍니다. 무엇이 바뀔지는 `--dry-run`으로 먼저 볼 수 있습니다.
|
|
48
53
|
|
|
49
54
|
## 사용법
|
|
50
55
|
|
|
@@ -83,7 +88,7 @@ await updateLayout({ id, snapshot: { revision: 2, values: { ...values, tone: 're
|
|
|
83
88
|
let status = Style { color: Some(Bound::key("tone").into()), ..Style::default() };
|
|
84
89
|
// 나중에: 값을 모두 다시 보내면서 색만 바꿉니다.
|
|
85
90
|
values.insert("tone".into(), Value::Text("red".into()));
|
|
86
|
-
app.live_activity().update_layout(LayoutUpdateInput { id, snapshot: LayoutSnapshot { revision: 2, values, stale_at: None } })?;
|
|
91
|
+
app.live_activity().update_layout(LayoutUpdateInput { id, snapshot: LayoutSnapshot { revision: 2, values, stale_at: None, timestamp: None } })?;
|
|
87
92
|
```
|
|
88
93
|
|
|
89
94
|
값을 가리킬 수 있는 것은 `color`, `background`, `tint`, `opacity`, `size`, `weight`, `cornerRadius`와
|
|
@@ -98,6 +103,8 @@ app.live_activity().update_layout(LayoutUpdateInput { id, snapshot: LayoutSnapsh
|
|
|
98
103
|
레이아웃은 `text`/`bound`, `path`(SVG path 데이터), `vstack`·`hstack`·`zstack`·`spacer`·`divider`와
|
|
99
104
|
아래 여섯 가지로 만듭니다. 그림은 모두 iOS 잠금화면입니다. 예시의 빌더는 `layout`에서 꺼내 씁니다
|
|
100
105
|
(`const { vstack, hstack, text, bound, symbol, image, gauge, progress, timerText, button } = layout;`).
|
|
106
|
+
같은 레이아웃을 TSX로 쓸 수 있고, React 훅으로 컴포넌트와 액티비티를 함께 움직일 수도 있습니다
|
|
107
|
+
([TSX and React](https://github.com/1eedaegon/tauri-plugin-live-activity/blob/main/docs/usage.md#tsx-and-react)).
|
|
101
108
|
|
|
102
109
|
### 심볼
|
|
103
110
|
|
|
@@ -227,12 +234,12 @@ custom('ring', { props: { level: bind('done'), width: 4 } }),
|
|
|
227
234
|
```
|
|
228
235
|
|
|
229
236
|
```swift
|
|
230
|
-
"ring":
|
|
237
|
+
"ring": ActivityKitCustomView { props in Ring(level: props.number("level") ?? 0) },
|
|
231
238
|
```
|
|
232
239
|
|
|
233
240
|
뷰가 없는 이름은 아무것도 그리지 않고 `degradedFeatures`에 `layout.custom.ring`으로 남습니다. 마지막 수단은
|
|
234
|
-
복사된 `LiveActivityWidget.swift
|
|
235
|
-
바뀐 부분은 직접 합쳐야 합니다.
|
|
241
|
+
복사된 `LiveActivityWidget.swift`(activitykit의 위젯 템플릿)를 직접 고치는 것입니다. 그러면 `setup`은 그 파일을
|
|
242
|
+
그대로 두고, 템플릿이 바뀐 부분은 직접 합쳐야 합니다.
|
|
236
243
|
|
|
237
244
|
제한: Live Activity는 네트워크를 쓸 수 없고 메모리도 적습니다. 그린 PNG는 1 MiB, 1224 × 480 픽셀까지이고,
|
|
238
245
|
이는 Apple의 가장 큰 잠금화면 크기를 @3x로 잰 값입니다. 글꼴은 확장 안에 있어야 합니다. 기기에서는 App
|
|
@@ -241,6 +248,17 @@ Group을 Apple 계정에 한 번 등록해야 하는데, 자동 서명이 대신
|
|
|
241
248
|
아이콘이 됩니다. 레이아웃, 스타일, 값은 여전히 3584를 나눠 씁니다.
|
|
242
249
|
[자세히](https://github.com/1eedaegon/tauri-plugin-live-activity/blob/main/docs/usage.md#beyond-the-built-in-parts)
|
|
243
250
|
|
|
251
|
+
## 제약
|
|
252
|
+
|
|
253
|
+
- iOS: iOS 16.2 이상의 iPhone 또는 iPadOS 17 이상의 iPad가 필요하고, 버튼은 iOS 17부터 동작합니다. 활동은 앱이
|
|
254
|
+
포그라운드에 있을 때만 시작되고(아니면 `NOT_FOREGROUND`), 시스템이 8시간 뒤에 끝냅니다.
|
|
255
|
+
- iOS는 활동마다 마지막 값을 앱의 Application Support에 평문으로 남깁니다. 플러그인 설정에
|
|
256
|
+
`"receipts": "redacted"`를 주면 값 대신 다이제스트만 남깁니다.
|
|
257
|
+
- 버튼을 누르면 Rust의 `on_action` 핸들러가 끝날 때까지 최대 4초 기다립니다. JavaScript 리스너는 기다리지 않습니다.
|
|
258
|
+
- `app.live_activity()`의 Rust 메서드는 응답이 올 때까지 스레드를 멈추므로 메인 스레드가 아닌 곳에서 호출하세요. iOS에서
|
|
259
|
+
메인 스레드에서 호출하면 바로 `NATIVE_ERROR`를 돌려줍니다. JavaScript의 명령은 멈추지 않습니다.
|
|
260
|
+
- 푸시 갱신은 없습니다. Android는 진행 중 알림으로 보여 주고, 시스템이 허용하면 Live Update로 올립니다.
|
|
261
|
+
|
|
244
262
|
## Samsung Now Bar
|
|
245
263
|
|
|
246
264
|
`tauri.conf.json`에 `"plugins": { "live-activity": { "android": { "samsungNowBar": true } } }`를 넣으면
|
package/README.md
CHANGED
|
@@ -23,8 +23,11 @@ an ongoing notification on Android. You describe the layout in TypeScript; the p
|
|
|
23
23
|
</table>
|
|
24
24
|
|
|
25
25
|
All four come from the [demo app](https://github.com/1eedaegon/tauri-plugin-live-activity/tree/main/examples/demo),
|
|
26
|
-
which follows a cat named Mochi. The plugin runs on iOS 16.
|
|
27
|
-
activity commands return `UNSUPPORTED_PLATFORM`.
|
|
26
|
+
which follows a cat named Mochi. The plugin runs on iOS 16.2+ and Android 8+; on desktop, its
|
|
27
|
+
activity commands return `UNSUPPORTED_PLATFORM`. On iOS it is built on the
|
|
28
|
+
[activitykit](https://github.com/1eedaegon/activitykit-rs) crate and has no Swift of its own. On Android every activity runs
|
|
29
|
+
its lifecycle in Rust, on the [liveupdate](https://github.com/1eedaegon/liveupdate-rs) crate, which draws templates
|
|
30
|
+
and layouts as Android's notification styles; the plugin's Kotlin only answers the permission commands. Before 1.0, a minor version may change the API.
|
|
28
31
|
|
|
29
32
|
## Install
|
|
30
33
|
|
|
@@ -43,9 +46,10 @@ Then add one line to the builder in `src-tauri/src/lib.rs`:
|
|
|
43
46
|
```
|
|
44
47
|
|
|
45
48
|
`setup` grants the plugin's permissions, raises the Android minimum to API 26 and, on a Mac,
|
|
46
|
-
adds the widget extension that draws the activity to the Xcode project
|
|
47
|
-
`tauri ios init`, and again if `src-tauri/gen/apple` is ever made from
|
|
48
|
-
|
|
49
|
+
adds the widget extension that draws the activity to the Xcode project, on activitykit's Swift
|
|
50
|
+
package. Run it after `tauri ios init`, and again if `src-tauri/gen/apple` is ever made from
|
|
51
|
+
scratch. On an app that 0.3 set up, run it again: it moves the widget and your custom views to
|
|
52
|
+
activitykit. `--dry-run` shows what it would change.
|
|
49
53
|
|
|
50
54
|
## Use
|
|
51
55
|
|
|
@@ -83,7 +87,7 @@ await updateLayout({ id, snapshot: { revision: 2, values: { ...values, tone: 're
|
|
|
83
87
|
let status = Style { color: Some(Bound::key("tone").into()), ..Style::default() };
|
|
84
88
|
// Later: every value again, with the new color.
|
|
85
89
|
values.insert("tone".into(), Value::Text("red".into()));
|
|
86
|
-
app.live_activity().update_layout(LayoutUpdateInput { id, snapshot: LayoutSnapshot { revision: 2, values, stale_at: None } })?;
|
|
90
|
+
app.live_activity().update_layout(LayoutUpdateInput { id, snapshot: LayoutSnapshot { revision: 2, values, stale_at: None, timestamp: None } })?;
|
|
87
91
|
```
|
|
88
92
|
|
|
89
93
|
Only `color`, `background`, `tint`, `opacity`, `size`, `weight`, `cornerRadius` and the layout's
|
|
@@ -98,6 +102,8 @@ the same minor version. [More](https://github.com/1eedaegon/tauri-plugin-live-ac
|
|
|
98
102
|
Layouts are built from `text`/`bound`, `path` (SVG path data) and `vstack`, `hstack`, `zstack`,
|
|
99
103
|
`spacer`, `divider`, plus the six below. Each picture is the iOS Lock Screen. The snippets take
|
|
100
104
|
the builders from `layout` (`const { vstack, hstack, text, bound, symbol, image, gauge, progress, timerText, button } = layout;`).
|
|
105
|
+
The same layouts can be written in TSX, and a React hook keeps an activity in step with a component
|
|
106
|
+
([TSX and React](https://github.com/1eedaegon/tauri-plugin-live-activity/blob/main/docs/usage.md#tsx-and-react)).
|
|
101
107
|
|
|
102
108
|
### Symbols
|
|
103
109
|
|
|
@@ -227,12 +233,12 @@ custom('ring', { props: { level: bind('done'), width: 4 } }),
|
|
|
227
233
|
```
|
|
228
234
|
|
|
229
235
|
```swift
|
|
230
|
-
"ring":
|
|
236
|
+
"ring": ActivityKitCustomView { props in Ring(level: props.number("level") ?? 0) },
|
|
231
237
|
```
|
|
232
238
|
|
|
233
239
|
A name without a view draws nothing and is reported in `degradedFeatures` as `layout.custom.ring`. The last
|
|
234
|
-
resort is to edit the copied `LiveActivityWidget.swift
|
|
235
|
-
yours to merge.
|
|
240
|
+
resort is to edit the copied `LiveActivityWidget.swift`, activitykit's widget template; `setup` then keeps your copy,
|
|
241
|
+
and template updates are yours to merge.
|
|
236
242
|
|
|
237
243
|
Limits: a Live Activity has no network and little memory. A drawn PNG is at most 1 MiB and 1224 × 480 pixels,
|
|
238
244
|
Apple's largest Lock Screen presentation at @3x. Fonts must be in the extension. On a device the App Group is
|
|
@@ -241,6 +247,17 @@ and props, not the view. Android draws none of these, except that the first draw
|
|
|
241
247
|
notification's large icon. Layout, styles and values still share 3584.
|
|
242
248
|
[More](https://github.com/1eedaegon/tauri-plugin-live-activity/blob/main/docs/usage.md#beyond-the-built-in-parts)
|
|
243
249
|
|
|
250
|
+
## Limits
|
|
251
|
+
|
|
252
|
+
- iOS: an iPhone with iOS 16.2 or an iPad with iPadOS 17; buttons need iOS 17. An activity starts only while the
|
|
253
|
+
app is in the foreground (`NOT_FOREGROUND` otherwise), and the system ends it after 8 hours.
|
|
254
|
+
- iOS keeps each activity's last values in plain text in the app's Application Support, unless the plugin
|
|
255
|
+
configuration sets `"receipts": "redacted"`.
|
|
256
|
+
- A button's tap waits for your Rust `on_action` handlers, at most 4 seconds; JavaScript listeners are not awaited.
|
|
257
|
+
- The Rust methods of `app.live_activity()` block until the answer: call them off the main thread. On iOS a call on
|
|
258
|
+
the main thread answers `NATIVE_ERROR` at once. The commands from JavaScript never block.
|
|
259
|
+
- No push updates. Android shows an ongoing notification, promoted to a Live Update where the system allows it.
|
|
260
|
+
|
|
244
261
|
## Samsung Now Bar
|
|
245
262
|
|
|
246
263
|
Set `"plugins": { "live-activity": { "android": { "samsungNowBar": true } } }` in
|
package/cli/ios.mjs
CHANGED
|
@@ -1,21 +1,23 @@
|
|
|
1
|
-
// The iOS part of setup: Info.ios.plist, the widget files in gen/apple with the fonts and images it
|
|
2
|
-
//
|
|
3
|
-
//
|
|
1
|
+
// The iOS part of setup: Info.ios.plist, the widget files in gen/apple with the fonts and images it bundles, the
|
|
2
|
+
// XcodeGen spec that adds the widget extension on activitykit's Swift package, the App Group, and the regenerated
|
|
3
|
+
// Xcode project. An app that 0.2 or 0.3 set up loses the plugin's old Swift files on the way (migration.mjs).
|
|
4
4
|
import { spawnSync } from 'node:child_process';
|
|
5
|
-
import {
|
|
6
|
-
import { join,
|
|
5
|
+
import { readdirSync, rmSync } from 'node:fs';
|
|
6
|
+
import { join, resolve } from 'node:path';
|
|
7
|
+
import { OLD_MODULES, RETIRED, released, renameCustomViews } from './migration.mjs';
|
|
7
8
|
import { newPlist, setTrueKey } from './plist.mjs';
|
|
8
9
|
import { SetupError, parseJson, readText, step, tail, which, writeFile } from './steps.mjs';
|
|
9
10
|
import { assetSteps, bundledFonts, fontSteps } from './widget-files.mjs';
|
|
10
11
|
import { SPEC_FILE, WIDGET, addInclude, appGroupOf, readProject, widgetSpec, writtenBySetup } from './xcodegen.mjs';
|
|
11
12
|
|
|
12
|
-
|
|
13
|
-
|
|
13
|
+
/** The widget bundle: activitykit's template, under the name 0.2 and 0.3 gave the plugin's. */
|
|
14
|
+
const WIDGET_FILE = 'LiveActivityWidget.swift';
|
|
15
|
+
const WIDGET_TEMPLATE = join('templates', 'ios', 'Widget.swift');
|
|
16
|
+
/** The app's own file: created once from the template and never written again, but for the names of activitykit. */
|
|
14
17
|
const CUSTOM_VIEWS = 'LiveActivityCustomViews.swift';
|
|
18
|
+
const CUSTOM_VIEWS_TEMPLATE = new URL('./templates/LiveActivityCustomViews.swift', import.meta.url);
|
|
15
19
|
const GROUP = /^group\.[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*$/;
|
|
16
20
|
const PLIST_KEY = 'NSSupportsLiveActivities';
|
|
17
|
-
// Left out of the copy of Tauri's Swift API, as the plugin's build script does.
|
|
18
|
-
const NOT_COPIED = ['.build', 'Package.resolved', 'Tests'];
|
|
19
21
|
|
|
20
22
|
export function iosSteps(context) {
|
|
21
23
|
const { srcTauri, platform, show } = context;
|
|
@@ -42,12 +44,13 @@ export function iosSteps(context) {
|
|
|
42
44
|
const widget = join(apple, WIDGET);
|
|
43
45
|
const appGroup = appGroupFor(context, apple, project);
|
|
44
46
|
const include = includeStep(context, specPath, yaml);
|
|
45
|
-
// XcodeGen lists the files of a folder when it generates, so a new widget file also needs a run.
|
|
47
|
+
// XcodeGen lists the files of a folder when it generates, so a new or removed widget file also needs a run.
|
|
46
48
|
const projectSteps = [
|
|
47
|
-
|
|
49
|
+
widgetStep(context, widget), ...retiredSteps(context, widget, readText(join(apple, SPEC_FILE))), customViewsStep(context, widget),
|
|
50
|
+
...fontSteps(context, widget), ...assetSteps(context, widget),
|
|
48
51
|
specStep(context, apple, project, { fonts: bundledFonts(context, widget), appGroup }), include,
|
|
49
52
|
];
|
|
50
|
-
return [plist, ...projectSteps,
|
|
53
|
+
return [plist, ...projectSteps, xcodegenStep(context, apple, specPath, projectSteps, include)];
|
|
51
54
|
}
|
|
52
55
|
|
|
53
56
|
/**
|
|
@@ -63,12 +66,19 @@ function appGroupFor({ appGroup, config }, apple, project) {
|
|
|
63
66
|
return group;
|
|
64
67
|
}
|
|
65
68
|
|
|
66
|
-
/**
|
|
67
|
-
|
|
69
|
+
/**
|
|
70
|
+
* LiveActivityCustomViews.swift belongs to the app: created once, then never written again, except that a file of 0.3
|
|
71
|
+
* takes activitykit's names, its views kept.
|
|
72
|
+
*/
|
|
73
|
+
function customViewsStep({ show }, widget) {
|
|
68
74
|
const path = join(widget, CUSTOM_VIEWS);
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
75
|
+
const current = readText(path);
|
|
76
|
+
if (current !== undefined) {
|
|
77
|
+
const renamed = renameCustomViews(current);
|
|
78
|
+
if (renamed === undefined) return step('unchanged', show(path));
|
|
79
|
+
return step('updated', show(path), "activitykit's names for the registry and its types; your views are kept", writeFile(path, renamed));
|
|
80
|
+
}
|
|
81
|
+
const stub = readText(CUSTOM_VIEWS_TEMPLATE);
|
|
72
82
|
return step('created', show(path), 'yours, for custom views; setup never changes it again', writeFile(path, stub));
|
|
73
83
|
}
|
|
74
84
|
|
|
@@ -86,20 +96,44 @@ function infoPlistStep({ srcTauri, show }) {
|
|
|
86
96
|
return step('kept', show(path), `it sets ${PLIST_KEY} to something other than true; Live Activities need true`);
|
|
87
97
|
}
|
|
88
98
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
99
|
+
/** The widget bundle from activitykit's template; one that 0.2 or 0.3 wrote is replaced, one of the app's kept. */
|
|
100
|
+
function widgetStep({ activitykit, show }, widget) {
|
|
101
|
+
const wanted = readText(join(activitykit.dir, WIDGET_TEMPLATE));
|
|
102
|
+
if (wanted === undefined) throw new SetupError(`The activitykit crate at ${activitykit.dir} has no ${WIDGET_TEMPLATE}.`);
|
|
103
|
+
const path = join(widget, WIDGET_FILE);
|
|
104
|
+
const current = readText(path);
|
|
105
|
+
if (current === undefined) return step('created', show(path), '', writeFile(path, wanted));
|
|
106
|
+
if (current === wanted) return step('unchanged', show(path));
|
|
107
|
+
if (released(WIDGET_FILE, current)) {
|
|
108
|
+
return step('updated', show(path), "activitykit's widget, in place of the one tauri-plugin-live-activity 0.3 wrote", writeFile(path, wanted));
|
|
109
|
+
}
|
|
110
|
+
if (OLD_MODULES.test(current)) {
|
|
111
|
+
return step('todo', show(path), "imports the Swift modules of tauri-plugin-live-activity 0.3, which 0.4 no longer has: draw with ActivityKitWidget's ActivityKitLayoutWidget(), or delete the file and run setup again");
|
|
112
|
+
}
|
|
113
|
+
return step('kept', show(path), "differs from activitykit's template; to take the template, delete it and run setup again");
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* The button intent and the custom views registry of 0.2 and 0.3, which activitykit's products replace. A spec changed
|
|
118
|
+
* by hand, which setup keeps, may still name one: XcodeGen would fail without it, so it stays as a step to do.
|
|
119
|
+
*/
|
|
120
|
+
function retiredSteps({ show }, widget, spec) {
|
|
121
|
+
const kept = spec !== undefined && !writtenBySetup(spec);
|
|
122
|
+
return RETIRED.flatMap(name => {
|
|
123
|
+
const path = join(widget, name);
|
|
94
124
|
const current = readText(path);
|
|
95
|
-
if (current === undefined) return
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
125
|
+
if (current === undefined) return [];
|
|
126
|
+
if (kept && spec.includes(name)) {
|
|
127
|
+
return [step('todo', show(path), `${SPEC_FILE}, which you changed, still names it: take it out of the spec, then delete it; activitykit's Swift package replaces it`)];
|
|
128
|
+
}
|
|
129
|
+
if (released(name, current)) {
|
|
130
|
+
return [step('removed', show(path), "activitykit's Swift package replaces it", () => rmSync(path))];
|
|
131
|
+
}
|
|
132
|
+
return [step('todo', show(path), "changed by hand; activitykit's Swift package replaces it, so move your changes and delete it")];
|
|
99
133
|
});
|
|
100
134
|
}
|
|
101
135
|
|
|
102
|
-
function specStep({ plugin, config, srcTauri, show }, apple, project, { fonts, appGroup }) {
|
|
136
|
+
function specStep({ plugin, activitykit, config, srcTauri, show }, apple, project, { fonts, appGroup }) {
|
|
103
137
|
const path = join(apple, SPEC_FILE);
|
|
104
138
|
const wanted = widgetSpec({
|
|
105
139
|
fonts,
|
|
@@ -107,7 +141,7 @@ function specStep({ plugin, config, srcTauri, show }, apple, project, { fonts, a
|
|
|
107
141
|
// XcodeGen writes the entitlements file from the spec, so the App Group goes into the spec, at the app's path.
|
|
108
142
|
appEntitlements: project.entitlements ?? `${project.appTarget}/${project.appTarget}.entitlements`,
|
|
109
143
|
pluginVersion: plugin.version,
|
|
110
|
-
packagePath: join(
|
|
144
|
+
packagePath: join(activitykit.dir, 'swift'),
|
|
111
145
|
appTarget: project.appTarget,
|
|
112
146
|
bundleId: `${project.bundleId ?? config.identifier}.widget`,
|
|
113
147
|
...appVersions(config, srcTauri),
|
|
@@ -115,13 +149,13 @@ function specStep({ plugin, config, srcTauri, show }, apple, project, { fonts, a
|
|
|
115
149
|
});
|
|
116
150
|
const current = readText(path);
|
|
117
151
|
if (current === undefined) {
|
|
118
|
-
return step('created', show(path),
|
|
152
|
+
return step('created', show(path), "the widget extension on activitykit's Swift package, and the button intent and custom views in the app", writeFile(path, wanted));
|
|
119
153
|
}
|
|
120
154
|
if (current === wanted) return step('unchanged', show(path));
|
|
121
155
|
if (!writtenBySetup(current)) {
|
|
122
156
|
return step('kept', show(path), 'it was changed by hand; delete it and run setup again to have it written anew');
|
|
123
157
|
}
|
|
124
|
-
return step('updated', show(path), 'for the current plugin and app version', writeFile(path, wanted));
|
|
158
|
+
return step('updated', show(path), 'for the current plugin, activitykit and app version', writeFile(path, wanted));
|
|
125
159
|
}
|
|
126
160
|
|
|
127
161
|
/** The `version` of Cargo.toml's [package] section. */
|
|
@@ -150,21 +184,6 @@ function includeStep({ show }, specPath, yaml) {
|
|
|
150
184
|
return step('todo', show(specPath), `add ${SPEC_FILE} to its include list`);
|
|
151
185
|
}
|
|
152
186
|
|
|
153
|
-
/** The plugin's Swift package refers to Tauri's at ../.tauri/tauri-api, which the plugin's iOS build copies there. */
|
|
154
|
-
function swiftPackageStep({ plugin, show }) {
|
|
155
|
-
const target = join(plugin.dir, '.tauri', 'tauri-api');
|
|
156
|
-
if (existsSync(join(target, 'Package.swift'))) return step('unchanged', show(target));
|
|
157
|
-
const source = plugin.tauriDir && join(plugin.tauriDir, 'mobile', 'ios-api');
|
|
158
|
-
if (!source || !existsSync(join(source, 'Package.swift'))) {
|
|
159
|
-
const detail = "the plugin's Swift package needs Tauri's Swift API here. Build the Rust code for iOS once to make it: "
|
|
160
|
-
+ 'cargo build --target aarch64-apple-ios-sim (x86_64-apple-ios on an Intel Mac) in src-tauri';
|
|
161
|
-
return step('todo', show(target), detail);
|
|
162
|
-
}
|
|
163
|
-
const copied = path => !NOT_COPIED.some(name => relative(source, path) === name || relative(source, path).startsWith(name + sep));
|
|
164
|
-
const detail = "Tauri's Swift API for the plugin's Swift package, as the plugin's iOS build copies it";
|
|
165
|
-
return step('created', show(target), detail, () => cpSync(source, target, { recursive: true, filter: copied }));
|
|
166
|
-
}
|
|
167
|
-
|
|
168
187
|
function generatedWithWidget(apple) {
|
|
169
188
|
return readdirSync(apple).filter(name => name.endsWith('.xcodeproj'))
|
|
170
189
|
.some(name => readText(join(apple, name, 'project.pbxproj'))?.includes(WIDGET));
|
|
@@ -173,7 +192,7 @@ function generatedWithWidget(apple) {
|
|
|
173
192
|
function xcodegenStep({ env, show }, apple, specPath, projectSteps, include) {
|
|
174
193
|
const command = `xcodegen generate --spec ${show(specPath)}`;
|
|
175
194
|
if (include.status === 'todo') return step('skipped', 'Xcode project', 'waits for the include in project.yml');
|
|
176
|
-
const changed = projectSteps.some(item =>
|
|
195
|
+
const changed = projectSteps.some(item => ['created', 'updated', 'removed'].includes(item.status));
|
|
177
196
|
if (!changed && generatedWithWidget(apple)) return step('unchanged', 'Xcode project');
|
|
178
197
|
const xcodegen = which('xcodegen', env);
|
|
179
198
|
if (!xcodegen) return step('todo', 'Xcode project', `XcodeGen is not on PATH. Install it (brew install xcodegen), then run: ${command}`);
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// What setup changes in an app that tauri-plugin-live-activity 0.2 or 0.3 set up, whose widget extension and app
|
|
2
|
+
// target compiled the plugin's own Swift: 0.4 takes the widget, the button intent and the custom views registry from
|
|
3
|
+
// activitykit's Swift package.
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
5
|
+
|
|
6
|
+
/** The SHA-256 of each template as a release of the plugin wrote it into the widget folder. */
|
|
7
|
+
export const RELEASED = {
|
|
8
|
+
// 0.2.0, 0.2.1 and 0.3.0: the button intent, which activitykit's ActivityKitIntent product replaces.
|
|
9
|
+
'LiveActivityActionIntent.swift': ['cd96e40c42aae84b2e76db2f264f8ead892bf77c282e51f7443dc8624bc3ead5'],
|
|
10
|
+
// 0.3.0: the base of the custom views, which activitykit's ActivityKitViews product replaces.
|
|
11
|
+
'LiveActivityCustomRegistry.swift': ['75c2275fe63da34234fca039ed459151edb851c1acf1faf0e6a400791345983f'],
|
|
12
|
+
// 0.2.x and 0.3.0: the widget bundle on the plugin's own Swift modules.
|
|
13
|
+
'LiveActivityWidget.swift': [
|
|
14
|
+
'2a76d033acbbd208c7050e10394c31c120ad96d0ff55189daed11ad5255cbd2c',
|
|
15
|
+
'a8abe58a70300204b1406e5dbcc0d53f6265b525785903d5b2e6e1d2b317476d',
|
|
16
|
+
],
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/** Files that only the plugin's own Swift needed. */
|
|
20
|
+
export const RETIRED = ['LiveActivityActionIntent.swift', 'LiveActivityCustomRegistry.swift'];
|
|
21
|
+
|
|
22
|
+
/** The Swift modules of the plugin before 0.4; a widget file that imports one no longer builds. */
|
|
23
|
+
export const OLD_MODULES = /\bimport\s+(LiveActivityShared|LiveActivityUI|LiveActivityCore)\b/;
|
|
24
|
+
|
|
25
|
+
const sha256 = text => createHash('sha256').update(text).digest('hex');
|
|
26
|
+
|
|
27
|
+
/** True when `text` is the file `name` exactly as a release wrote it. */
|
|
28
|
+
export function released(name, text) {
|
|
29
|
+
return RELEASED[name]?.includes(sha256(text)) ?? false;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// The names of 0.3's custom views file and activitykit's, longest first: `LiveActivityCustomView` is a prefix of the
|
|
33
|
+
// other two, and the class `LiveActivityCustomViews` keeps its Swift name.
|
|
34
|
+
const RENAMES = [
|
|
35
|
+
['TauriLiveActivityCustomViews', 'ActivityKitCustomViews'],
|
|
36
|
+
['LiveActivityCustomViewRegistry', 'ActivityKitCustomViewRegistry'],
|
|
37
|
+
['LiveActivityCustomProps', 'ActivityKitCustomProps'],
|
|
38
|
+
['LiveActivityCustomView', 'ActivityKitCustomView'],
|
|
39
|
+
];
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* The app's custom views file with activitykit's names: the Objective-C name, the registry, the view and props types,
|
|
43
|
+
* and `import ActivityKitViews`. The app's views stay as they are. Undefined when the file has none of 0.3's names.
|
|
44
|
+
*/
|
|
45
|
+
export function renameCustomViews(text) {
|
|
46
|
+
if (!RENAMES.some(([old]) => new RegExp(`\\b${old}\\b`).test(text))) return undefined;
|
|
47
|
+
let next = RENAMES.reduce((current, [old, name]) => current.replace(new RegExp(`\\b${old}\\b`, 'g'), name), text);
|
|
48
|
+
if (!/^\s*import\s+ActivityKitViews\b/m.test(next)) {
|
|
49
|
+
const swiftUI = /^import SwiftUI[ \t]*$/m.exec(next);
|
|
50
|
+
next = swiftUI
|
|
51
|
+
? `${next.slice(0, swiftUI.index)}import ActivityKitViews\n${next.slice(swiftUI.index)}`
|
|
52
|
+
: `import ActivityKitViews\n${next}`;
|
|
53
|
+
}
|
|
54
|
+
return next;
|
|
55
|
+
}
|
package/cli/report.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// The summary that setup prints.
|
|
2
2
|
|
|
3
|
-
const DONE = { created: 'created', updated: 'updated', ran: 'ran', kept: 'kept', skipped: 'skipped' };
|
|
4
|
-
const WOULD = { created: 'would create', updated: 'would update', ran: 'would run', kept: 'would keep', skipped: 'would skip' };
|
|
3
|
+
const DONE = { created: 'created', updated: 'updated', removed: 'removed', ran: 'ran', kept: 'kept', skipped: 'skipped' };
|
|
4
|
+
const WOULD = { created: 'would create', updated: 'would update', removed: 'would remove', ran: 'would run', kept: 'would keep', skipped: 'would skip' };
|
|
5
5
|
|
|
6
6
|
function line(item, dryRun) {
|
|
7
7
|
const label = (dryRun ? WOULD : DONE)[item.status];
|
package/cli/setup.mjs
CHANGED
|
@@ -10,6 +10,8 @@ import { widgetFiles } from './widget-files.mjs';
|
|
|
10
10
|
export { SetupError } from './steps.mjs';
|
|
11
11
|
|
|
12
12
|
export const CRATE = 'tauri-plugin-live-activity';
|
|
13
|
+
/** The crate whose Swift package the widget extension and the app target link. */
|
|
14
|
+
export const ACTIVITYKIT = 'activitykit';
|
|
13
15
|
/** `default` reads; the others allow the commands that change activities. */
|
|
14
16
|
export const PERMISSIONS = [
|
|
15
17
|
'live-activity:default',
|
|
@@ -31,8 +33,8 @@ export function setup({
|
|
|
31
33
|
} = {}) {
|
|
32
34
|
const files = widgetFiles(cwd, { fonts, assets });
|
|
33
35
|
const app = findApp(cwd);
|
|
34
|
-
const plugin =
|
|
35
|
-
const context = { ...app, plugin, env, platform, files, appGroup, show: path => display(cwd, path) };
|
|
36
|
+
const { plugin, activitykit } = findCrates(app, env);
|
|
37
|
+
const context = { ...app, plugin, activitykit, env, platform, files, appGroup, show: path => display(cwd, path) };
|
|
36
38
|
const planned = [...(iosOnly ? [] : [capabilitiesStep(context), ...androidSteps(context)]), ...iosSteps(context)];
|
|
37
39
|
const steps = dryRun ? planned : planned.map(apply);
|
|
38
40
|
return { dryRun, version: plugin.version, steps: steps.map(({ effect, ...rest }) => rest), notes: notes(context) };
|
|
@@ -63,8 +65,11 @@ function findApp(cwd) {
|
|
|
63
65
|
return { srcTauri, configPath, configText, config };
|
|
64
66
|
}
|
|
65
67
|
|
|
66
|
-
/**
|
|
67
|
-
|
|
68
|
+
/**
|
|
69
|
+
* The plugin crate's version and the folder of the activitykit crate it depends on, from `cargo metadata`: the widget
|
|
70
|
+
* extension and the app target link activitykit's Swift package, which lies in that folder.
|
|
71
|
+
*/
|
|
72
|
+
export function findCrates({ srcTauri }, env) {
|
|
68
73
|
const args = ['metadata', '--format-version', '1', '--manifest-path', join(srcTauri, 'Cargo.toml')];
|
|
69
74
|
const result = spawnSync(env.CARGO || 'cargo', args, { env, encoding: 'utf8', maxBuffer: 1024 ** 3 });
|
|
70
75
|
if (result.error?.code === 'ENOENT') throw new SetupError('cargo was not found. Install Rust from https://rustup.rs, then run this again.');
|
|
@@ -76,9 +81,15 @@ function findPlugin({ srcTauri }, env) {
|
|
|
76
81
|
if (!crate) {
|
|
77
82
|
throw new SetupError(`${CRATE} is not a dependency of src-tauri/Cargo.toml yet. Add it first:\n cargo add ${CRATE} --manifest-path src-tauri/Cargo.toml`);
|
|
78
83
|
}
|
|
79
|
-
const
|
|
80
|
-
const
|
|
81
|
-
|
|
84
|
+
const kitId = metadata.resolve?.nodes?.find(node => node.id === crate.id)?.deps?.find(dep => dep.name === ACTIVITYKIT)?.pkg;
|
|
85
|
+
const kit = metadata.packages.find(item => (kitId ? item.id === kitId : item.name === ACTIVITYKIT));
|
|
86
|
+
if (!kit) {
|
|
87
|
+
throw new SetupError(`${CRATE} ${crate.version} does not depend on ${ACTIVITYKIT}, whose Swift package the widget extension links: use the crate of the npm package's version, ${NPM_VERSION}.`);
|
|
88
|
+
}
|
|
89
|
+
return {
|
|
90
|
+
plugin: { version: crate.version, dir: dirname(crate.manifest_path) },
|
|
91
|
+
activitykit: { version: kit.version, dir: dirname(kit.manifest_path) },
|
|
92
|
+
};
|
|
82
93
|
}
|
|
83
94
|
|
|
84
95
|
/** Adds the plugin's permissions to the app's capability: default.json, or the only capability file. */
|
package/cli/steps.mjs
CHANGED
|
@@ -9,7 +9,7 @@ export class SetupError extends Error {
|
|
|
9
9
|
name = 'SetupError';
|
|
10
10
|
}
|
|
11
11
|
|
|
12
|
-
/** Status: created, updated, ran, kept, skipped, todo or unchanged. */
|
|
12
|
+
/** Status: created, updated, removed, ran, kept, skipped, todo or unchanged. */
|
|
13
13
|
export function step(status, path, detail = '', effect = undefined) {
|
|
14
14
|
return effect ? { status, path, detail, effect } : { status, path, detail };
|
|
15
15
|
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import ActivityKitViews
|
|
2
|
+
import SwiftUI
|
|
3
|
+
|
|
4
|
+
// Your SwiftUI views for `custom` layout nodes. `npx tauri-plugin-live-activity setup` created this file once and never
|
|
5
|
+
// changes it. It is compiled into the widget extension, which draws the views, and into the app, so that activitykit can
|
|
6
|
+
// report a node whose name has no view here (`degradedFeatures`: `layout.custom.<name>`). Both targets link activitykit's
|
|
7
|
+
// `ActivityKitViews` product. Keep the Objective-C name: activitykit finds the views by it.
|
|
8
|
+
//
|
|
9
|
+
// A view gets the node's props: `props.number("level")`, `props.string("label")`, `props.bool("full")`. A prop bound to a
|
|
10
|
+
// value, `props: { level: bind('bowl') }`, has the value of the latest update. The node's style sets the frame, padding,
|
|
11
|
+
// colors and font around the view. A Live Activity has no network and little memory: draw with shapes, text and images
|
|
12
|
+
// of the extension; no timers, no animations of your own.
|
|
13
|
+
|
|
14
|
+
@available(iOS 16.1, *)
|
|
15
|
+
@objc(ActivityKitCustomViews)
|
|
16
|
+
final class LiveActivityCustomViews: ActivityKitCustomViewRegistry {
|
|
17
|
+
override class var views: [String: ActivityKitCustomView] {
|
|
18
|
+
[
|
|
19
|
+
// The layout node `custom('ring', { props: { level: bind('bowl') } })` draws this ring:
|
|
20
|
+
// "ring": ActivityKitCustomView { props in
|
|
21
|
+
// Circle().trim(from: 0, to: props.number("level") ?? 0).stroke(lineWidth: 4).rotationEffect(.degrees(-90))
|
|
22
|
+
// },
|
|
23
|
+
]
|
|
24
|
+
}
|
|
25
|
+
}
|
package/cli/xcodegen.mjs
CHANGED
|
@@ -6,10 +6,15 @@ export const SPEC_FILE = 'live-activity.yml';
|
|
|
6
6
|
export const WIDGET = 'LiveActivityWidget';
|
|
7
7
|
/** The extension's entitlements, next to its folder so that XcodeGen does not take them for a source. */
|
|
8
8
|
export const WIDGET_ENTITLEMENTS = `${WIDGET}.entitlements`;
|
|
9
|
-
/** The Info.plist key of the extension that names the App Group, for
|
|
10
|
-
export const APP_GROUP_KEY = '
|
|
11
|
-
/** The
|
|
12
|
-
|
|
9
|
+
/** The Info.plist key of the extension that names the App Group, for activitykit and the widget. */
|
|
10
|
+
export const APP_GROUP_KEY = 'ActivityKitAppGroup';
|
|
11
|
+
/** The key of 0.2 and 0.3, which a spec they wrote may hold. */
|
|
12
|
+
const OLD_APP_GROUP_KEY = 'TauriLiveActivityAppGroup';
|
|
13
|
+
/**
|
|
14
|
+
* The files of the widget folder that the app target compiles too. The custom views file is Swift, so the app target
|
|
15
|
+
* compiles Swift, which Xcode needs to take the App Intents metadata of the linked ActivityKitIntent product.
|
|
16
|
+
*/
|
|
17
|
+
export const APP_SOURCES = ['LiveActivityCustomViews.swift'];
|
|
13
18
|
|
|
14
19
|
const DIGEST_LINE = /^# setup-digest: ([0-9a-f]{16})\n/m;
|
|
15
20
|
|
|
@@ -76,9 +81,9 @@ export function readProject(text) {
|
|
|
76
81
|
};
|
|
77
82
|
}
|
|
78
83
|
|
|
79
|
-
/** The App Group of a spec that setup wrote, so that a later run keeps it. */
|
|
84
|
+
/** The App Group of a spec that setup wrote, this version or 0.2 and 0.3, so that a later run keeps it. */
|
|
80
85
|
export function appGroupOf(spec = '') {
|
|
81
|
-
const value = new RegExp(`^\\s
|
|
86
|
+
const value = new RegExp(`^\\s+(?:${APP_GROUP_KEY}|${OLD_APP_GROUP_KEY}): ("[^"\\n]*")$`, 'm').exec(spec)?.[1];
|
|
82
87
|
return value && JSON.parse(value);
|
|
83
88
|
}
|
|
84
89
|
|
|
@@ -114,10 +119,10 @@ export function writtenBySetup(text) {
|
|
|
114
119
|
const quoted = value => JSON.stringify(String(value));
|
|
115
120
|
|
|
116
121
|
/**
|
|
117
|
-
* The included spec: the widget extension target, and
|
|
118
|
-
*
|
|
119
|
-
* targets, the app's at `appEntitlements`, and to the extension's Info.plist, where
|
|
120
|
-
* read it. XcodeGen merges the app target's part into the target of project.yml.
|
|
122
|
+
* The included spec: activitykit's Swift package, the widget extension target, and in the app target the extension,
|
|
123
|
+
* the button intent and the custom views. `fonts` go to the extension's UIAppFonts. An `appGroup` goes to the
|
|
124
|
+
* entitlements of both targets, the app's at `appEntitlements`, and to the extension's Info.plist, where activitykit
|
|
125
|
+
* and the widget read it. XcodeGen merges the app target's part into the target of project.yml.
|
|
121
126
|
*/
|
|
122
127
|
export function widgetSpec({
|
|
123
128
|
pluginVersion, packagePath, appTarget, bundleId, appVersion, buildVersion, teamGroup, fonts = [], appGroup, appEntitlements,
|
|
@@ -134,14 +139,19 @@ export function widgetSpec({
|
|
|
134
139
|
' properties:',
|
|
135
140
|
` com.apple.security.application-groups: [${quoted(appGroup)}]`,
|
|
136
141
|
]);
|
|
142
|
+
const product = name => [' - package: ActivityKit', ` product: ${name}`];
|
|
137
143
|
const body = [
|
|
138
144
|
'packages:',
|
|
139
|
-
'
|
|
145
|
+
' ActivityKit:',
|
|
140
146
|
` path: ${quoted(packagePath)}`,
|
|
141
147
|
'targets:',
|
|
142
148
|
` ${quoted(appTarget)}:`,
|
|
143
149
|
` sources: [${APP_SOURCES.map(file => `${WIDGET}/${file}`).join(', ')}]`,
|
|
144
|
-
|
|
150
|
+
' dependencies:',
|
|
151
|
+
` - target: ${WIDGET}`,
|
|
152
|
+
// The system runs a button's intent in the app. The bridge itself is in the Rust library already.
|
|
153
|
+
...product('ActivityKitIntent'),
|
|
154
|
+
...product('ActivityKitViews'),
|
|
145
155
|
...entitlements(quoted(appEntitlements)),
|
|
146
156
|
' settings:',
|
|
147
157
|
' base:',
|
|
@@ -149,21 +159,19 @@ export function widgetSpec({
|
|
|
149
159
|
` ${WIDGET}:`,
|
|
150
160
|
' type: app-extension',
|
|
151
161
|
' platform: iOS',
|
|
152
|
-
' deploymentTarget: "16.
|
|
162
|
+
' deploymentTarget: "16.2"',
|
|
153
163
|
` sources: [${WIDGET}]`,
|
|
154
164
|
' dependencies:',
|
|
155
|
-
'
|
|
156
|
-
|
|
157
|
-
' - package: LiveActivity',
|
|
158
|
-
' product: LiveActivityUI',
|
|
165
|
+
...product('ActivityKitWidget'),
|
|
166
|
+
...product('ActivityKitViews'),
|
|
159
167
|
' info:',
|
|
160
168
|
` path: ${WIDGET}/Info.plist`,
|
|
161
169
|
' properties:',
|
|
162
170
|
...versions,
|
|
163
171
|
' NSExtension:',
|
|
164
172
|
' NSExtensionPointIdentifier: com.apple.widgetkit-extension',
|
|
165
|
-
' #
|
|
166
|
-
'
|
|
173
|
+
' # A start answers CONFIGURATION_REQUIRED without an extension that declares this.',
|
|
174
|
+
' ActivityKitLayout: 2',
|
|
167
175
|
...fontList,
|
|
168
176
|
...group,
|
|
169
177
|
...entitlements(WIDGET_ENTITLEMENTS),
|
|
@@ -179,7 +187,7 @@ export function widgetSpec({
|
|
|
179
187
|
].join('\n');
|
|
180
188
|
return [
|
|
181
189
|
`# Written by \`npx tauri-plugin-live-activity setup\` for tauri-plugin-live-activity ${pluginVersion}.`,
|
|
182
|
-
'# project.yml includes it. Setup writes it again for a new plugin version or app version, unless',
|
|
190
|
+
'# project.yml includes it. Setup writes it again for a new plugin or activitykit version or app version, unless',
|
|
183
191
|
'# the lines below were changed by hand.',
|
|
184
192
|
`# setup-digest: ${digest(body)}`,
|
|
185
193
|
body,
|
package/dist-js/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type UnlistenFn } from '@tauri-apps/api/event';
|
|
2
|
-
import type { ActionEvent, ActivityRecord, Capabilities, EndInput, LayoutActivityRecord, LayoutStartInput, LayoutUpdateInput, PermissionKind, Permissions, StartInput, UpdateInput } from './types.js';
|
|
2
|
+
import type { ActionEvent, ActivityRecord, Capabilities, EndInput, LayoutActivityRecord, LayoutEndInput, LayoutStartInput, LayoutUpdateInput, PermissionKind, Permissions, StartInput, UpdateInput } from './types.js';
|
|
3
3
|
export type * from './types.js';
|
|
4
4
|
/** Builders for the nodes of a layout tree. */
|
|
5
5
|
export * as layout from './layout.js';
|
|
@@ -21,20 +21,24 @@ export declare function list(): Promise<readonly ActivityRecord[]>;
|
|
|
21
21
|
export declare function startLayout(input: LayoutStartInput): Promise<LayoutActivityRecord>;
|
|
22
22
|
/** Replace every value with a newer revision; the layout stays as started. */
|
|
23
23
|
export declare function updateLayout(input: LayoutUpdateInput): Promise<LayoutActivityRecord>;
|
|
24
|
-
/** End this layout generation. A late update cannot revive it. */
|
|
25
|
-
export declare function endLayout(input:
|
|
24
|
+
/** End this layout generation, with final content when `snapshot` is given. A late update cannot revive it. */
|
|
25
|
+
export declare function endLayout(input: LayoutEndInput): Promise<LayoutActivityRecord>;
|
|
26
26
|
/** Reconcile plugin-owned layout records with the OS; `list` reports contract v1 activities. */
|
|
27
27
|
export declare function listLayout(): Promise<readonly LayoutActivityRecord[]>;
|
|
28
28
|
/**
|
|
29
29
|
* Write a PNG that `image` nodes with the source `{ file: name }` show, replacing one of that name. The widget
|
|
30
30
|
* reads it each time it draws the activity, on start and on every update, so write the picture first and then
|
|
31
31
|
* update. At most 1 MiB and 1224 x 480 pixels (`PAYLOAD_TOO_LARGE` beyond). On iOS it needs the App Group
|
|
32
|
-
* that `setup --app-group` configures (`CONFIGURATION_REQUIRED` without one)
|
|
32
|
+
* that `setup --app-group` configures (`CONFIGURATION_REQUIRED` without one), where activitykit writes it to
|
|
33
|
+
* `activitykit/images`; on Android the first such image
|
|
33
34
|
* becomes the notification's large icon.
|
|
34
35
|
*/
|
|
35
36
|
export declare function writeImage(name: string, png: Uint8Array | ArrayBuffer): Promise<void>;
|
|
36
37
|
/**
|
|
37
38
|
* Receive button taps while this webview is alive; resolves to the function that stops listening.
|
|
38
|
-
* Listening uses Tauri's event permissions (`core:event:default`).
|
|
39
|
+
* Listening uses Tauri's event permissions (`core:event:default`). The tap reaches the page after the Rust
|
|
40
|
+
* `on_action` handlers have run; the tap's intent does not wait for this handler, which runs in the webview whenever it
|
|
41
|
+
* gets the event, and not at all while the webview is suspended or was never created. Act on taps in Rust when they
|
|
42
|
+
* must not be lost.
|
|
39
43
|
*/
|
|
40
44
|
export declare function onAction(handler: (event: ActionEvent) => void): Promise<UnlistenFn>;
|
package/dist-js/index.js
CHANGED
|
@@ -38,7 +38,7 @@ export function startLayout(input) {
|
|
|
38
38
|
export function updateLayout(input) {
|
|
39
39
|
return invoke('plugin:live-activity|update_layout', { input });
|
|
40
40
|
}
|
|
41
|
-
/** End this layout generation. A late update cannot revive it. */
|
|
41
|
+
/** End this layout generation, with final content when `snapshot` is given. A late update cannot revive it. */
|
|
42
42
|
export function endLayout(input) {
|
|
43
43
|
return invoke('plugin:live-activity|end_layout', { input });
|
|
44
44
|
}
|
|
@@ -50,7 +50,8 @@ export function listLayout() {
|
|
|
50
50
|
* Write a PNG that `image` nodes with the source `{ file: name }` show, replacing one of that name. The widget
|
|
51
51
|
* reads it each time it draws the activity, on start and on every update, so write the picture first and then
|
|
52
52
|
* update. At most 1 MiB and 1224 x 480 pixels (`PAYLOAD_TOO_LARGE` beyond). On iOS it needs the App Group
|
|
53
|
-
* that `setup --app-group` configures (`CONFIGURATION_REQUIRED` without one)
|
|
53
|
+
* that `setup --app-group` configures (`CONFIGURATION_REQUIRED` without one), where activitykit writes it to
|
|
54
|
+
* `activitykit/images`; on Android the first such image
|
|
54
55
|
* becomes the notification's large icon.
|
|
55
56
|
*/
|
|
56
57
|
export function writeImage(name, png) {
|
|
@@ -59,7 +60,10 @@ export function writeImage(name, png) {
|
|
|
59
60
|
}
|
|
60
61
|
/**
|
|
61
62
|
* Receive button taps while this webview is alive; resolves to the function that stops listening.
|
|
62
|
-
* Listening uses Tauri's event permissions (`core:event:default`).
|
|
63
|
+
* Listening uses Tauri's event permissions (`core:event:default`). The tap reaches the page after the Rust
|
|
64
|
+
* `on_action` handlers have run; the tap's intent does not wait for this handler, which runs in the webview whenever it
|
|
65
|
+
* gets the event, and not at all while the webview is suspended or was never created. Act on taps in Rust when they
|
|
66
|
+
* must not be lost.
|
|
63
67
|
*/
|
|
64
68
|
export function onAction(handler) {
|
|
65
69
|
return listen('live-activity://action', event => handler(event.payload));
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { LayoutButtonNode, LayoutCustomNode, LayoutDividerNode, LayoutGaugeNode, LayoutHStackNode, LayoutImageNode, LayoutNode, LayoutPathNode, LayoutProgressNode, LayoutSpacerNode, LayoutSymbolNode, LayoutTextNode, LayoutTimerTextNode, LayoutVStackNode, LayoutZStackNode } from '../types.js';
|
|
2
|
+
export { bind } from '../layout.js';
|
|
3
|
+
/** What a stack takes as children: nodes, arrays of them, and booleans, `null` or `undefined`, which are left out. */
|
|
4
|
+
export type LayoutChild = LayoutNode | readonly LayoutChild[] | boolean | null | undefined;
|
|
5
|
+
/** What `Text` takes as children: strings and numbers, joined, and booleans, `null` or `undefined`, left out. */
|
|
6
|
+
export type TextChild = string | number | readonly TextChild[] | boolean | null | undefined;
|
|
7
|
+
/** The members of node `N` but its type and the members `Taken` that a component takes another way. */
|
|
8
|
+
type Props<N extends LayoutNode, Taken extends PropertyKey = never> = N extends unknown ? Omit<N, 'type' | Taken> : never;
|
|
9
|
+
type StackProps<N extends LayoutNode> = Props<N, 'children'> & {
|
|
10
|
+
readonly children: LayoutChild;
|
|
11
|
+
};
|
|
12
|
+
export type VStackProps = StackProps<LayoutVStackNode>;
|
|
13
|
+
export type HStackProps = StackProps<LayoutHStackNode>;
|
|
14
|
+
export type ZStackProps = StackProps<LayoutZStackNode>;
|
|
15
|
+
export type TextProps = Props<LayoutDividerNode> & ({
|
|
16
|
+
readonly children: TextChild;
|
|
17
|
+
readonly bind?: never;
|
|
18
|
+
} | {
|
|
19
|
+
readonly bind: string;
|
|
20
|
+
readonly children?: never;
|
|
21
|
+
});
|
|
22
|
+
export type ImageProps = Props<LayoutImageNode, 'source'> & ({
|
|
23
|
+
readonly asset: string;
|
|
24
|
+
readonly file?: never;
|
|
25
|
+
} | {
|
|
26
|
+
readonly file: string;
|
|
27
|
+
readonly asset?: never;
|
|
28
|
+
});
|
|
29
|
+
export type ButtonProps = Props<LayoutButtonNode, 'child'> & {
|
|
30
|
+
readonly children: LayoutNode;
|
|
31
|
+
};
|
|
32
|
+
/** Children from top to bottom. */
|
|
33
|
+
export declare function VStack({ children, ...options }: VStackProps): LayoutVStackNode;
|
|
34
|
+
/** Children side by side. */
|
|
35
|
+
export declare function HStack({ children, ...options }: HStackProps): LayoutHStackNode;
|
|
36
|
+
/** Children on top of each other, the first at the back. */
|
|
37
|
+
export declare function ZStack({ children, ...options }: ZStackProps): LayoutZStackNode;
|
|
38
|
+
/** Flexible space inside a stack. */
|
|
39
|
+
export declare function Spacer(props: Props<LayoutSpacerNode>): LayoutSpacerNode;
|
|
40
|
+
/** A separator line. */
|
|
41
|
+
export declare function Divider(props: Props<LayoutDividerNode>): LayoutDividerNode;
|
|
42
|
+
/** Literal text from its children, or with `bind` the value of that key. */
|
|
43
|
+
export declare function Text({ children, bind, ...options }: TextProps): LayoutTextNode;
|
|
44
|
+
/** An SF Symbol. */
|
|
45
|
+
export declare function SFSymbol({ name, ...options }: Props<LayoutSymbolNode>): LayoutSymbolNode;
|
|
46
|
+
/** An image of the widget extension's asset catalog (`asset`), or a PNG that the app wrote with `writeImage` (`file`). */
|
|
47
|
+
export declare function Image({ asset, file, ...options }: ImageProps): LayoutImageNode;
|
|
48
|
+
/** A shape from SVG path data `d`, drawn in a `box` of `[width, height]`. */
|
|
49
|
+
export declare function Path({ d, box, ...options }: Props<LayoutPathNode>): LayoutPathNode;
|
|
50
|
+
/** A progress bar or ring for the number value of `bind`. */
|
|
51
|
+
export declare function Progress({ bind, ...options }: Props<LayoutProgressNode>): LayoutProgressNode;
|
|
52
|
+
/** A gauge for the number value of `bind`. */
|
|
53
|
+
export declare function Gauge({ bind, ...options }: Props<LayoutGaugeNode>): LayoutGaugeNode;
|
|
54
|
+
/** A timer the system draws between the epoch-millisecond values of the `start` and `end` keys. */
|
|
55
|
+
export declare function TimerText({ start, end, ...options }: Props<LayoutTimerTextNode>): LayoutTimerTextNode;
|
|
56
|
+
/** A button around its one child; a tap reports `actionId` to `onAction`. */
|
|
57
|
+
export declare function Button({ actionId, children, ...options }: ButtonProps): LayoutButtonNode;
|
|
58
|
+
/** A SwiftUI view that the app registers under `name`; `props` are its inputs. */
|
|
59
|
+
export declare function Custom({ name, ...options }: Props<LayoutCustomNode>): LayoutCustomNode;
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// Layout components for TSX. Each returns the plain node object of its `layout` builder; nothing here
|
|
2
|
+
// imports Tauri or React, so a server can build the same layout.
|
|
3
|
+
import { bound, button, custom, divider, gauge, hstack, image, path, progress, spacer, symbol, text, timerText, vstack, zstack, } from '../layout.js';
|
|
4
|
+
export { bind } from '../layout.js';
|
|
5
|
+
/** Children from top to bottom. */
|
|
6
|
+
export function VStack({ children, ...options }) {
|
|
7
|
+
return vstack(nodes('VStack', children), options);
|
|
8
|
+
}
|
|
9
|
+
/** Children side by side. */
|
|
10
|
+
export function HStack({ children, ...options }) {
|
|
11
|
+
return hstack(nodes('HStack', children), options);
|
|
12
|
+
}
|
|
13
|
+
/** Children on top of each other, the first at the back. */
|
|
14
|
+
export function ZStack({ children, ...options }) {
|
|
15
|
+
return zstack(nodes('ZStack', children), options);
|
|
16
|
+
}
|
|
17
|
+
/** Flexible space inside a stack. */
|
|
18
|
+
export function Spacer(props) {
|
|
19
|
+
return spacer(props);
|
|
20
|
+
}
|
|
21
|
+
/** A separator line. */
|
|
22
|
+
export function Divider(props) {
|
|
23
|
+
return divider(props);
|
|
24
|
+
}
|
|
25
|
+
/** Literal text from its children, or with `bind` the value of that key. */
|
|
26
|
+
export function Text({ children, bind, ...options }) {
|
|
27
|
+
if (bind !== undefined) {
|
|
28
|
+
if (children !== undefined)
|
|
29
|
+
throw new TypeError('Text: takes children or bind, not both');
|
|
30
|
+
return bound(bind, options);
|
|
31
|
+
}
|
|
32
|
+
if (children === undefined)
|
|
33
|
+
throw new TypeError('Text: needs children or bind');
|
|
34
|
+
return text(words(children), options);
|
|
35
|
+
}
|
|
36
|
+
/** An SF Symbol. */
|
|
37
|
+
export function SFSymbol({ name, ...options }) {
|
|
38
|
+
return symbol(name, options);
|
|
39
|
+
}
|
|
40
|
+
/** An image of the widget extension's asset catalog (`asset`), or a PNG that the app wrote with `writeImage` (`file`). */
|
|
41
|
+
export function Image({ asset, file, ...options }) {
|
|
42
|
+
if ((asset === undefined) === (file === undefined))
|
|
43
|
+
throw new TypeError('Image: takes either asset or file');
|
|
44
|
+
return image(asset ?? { file: file }, options);
|
|
45
|
+
}
|
|
46
|
+
/** A shape from SVG path data `d`, drawn in a `box` of `[width, height]`. */
|
|
47
|
+
export function Path({ d, box, ...options }) {
|
|
48
|
+
return path(d, box, options);
|
|
49
|
+
}
|
|
50
|
+
/** A progress bar or ring for the number value of `bind`. */
|
|
51
|
+
export function Progress({ bind, ...options }) {
|
|
52
|
+
return progress(bind, options);
|
|
53
|
+
}
|
|
54
|
+
/** A gauge for the number value of `bind`. */
|
|
55
|
+
export function Gauge({ bind, ...options }) {
|
|
56
|
+
return gauge(bind, options);
|
|
57
|
+
}
|
|
58
|
+
/** A timer the system draws between the epoch-millisecond values of the `start` and `end` keys. */
|
|
59
|
+
export function TimerText({ start, end, ...options }) {
|
|
60
|
+
return timerText(start, end, options);
|
|
61
|
+
}
|
|
62
|
+
/** A button around its one child; a tap reports `actionId` to `onAction`. */
|
|
63
|
+
export function Button({ actionId, children, ...options }) {
|
|
64
|
+
const child = Array.isArray(children) && children.length === 1 ? children[0] : children;
|
|
65
|
+
if (!isNode(child))
|
|
66
|
+
throw new TypeError('Button: needs exactly one node as its child');
|
|
67
|
+
return button(actionId, child, options);
|
|
68
|
+
}
|
|
69
|
+
/** A SwiftUI view that the app registers under `name`; `props` are its inputs. */
|
|
70
|
+
export function Custom({ name, ...options }) {
|
|
71
|
+
return custom(name, options);
|
|
72
|
+
}
|
|
73
|
+
function isNode(value) {
|
|
74
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
75
|
+
&& typeof value.type === 'string';
|
|
76
|
+
}
|
|
77
|
+
function nodes(component, children) {
|
|
78
|
+
const found = [];
|
|
79
|
+
const visit = (child) => {
|
|
80
|
+
if (typeof child === 'boolean' || child === null || child === undefined)
|
|
81
|
+
return;
|
|
82
|
+
if (Array.isArray(child))
|
|
83
|
+
return child.forEach(visit);
|
|
84
|
+
if (!isNode(child))
|
|
85
|
+
throw new TypeError(`${component}: a child must be a layout node; put text in <Text>`);
|
|
86
|
+
found.push(child);
|
|
87
|
+
};
|
|
88
|
+
visit(children);
|
|
89
|
+
if (found.length === 0)
|
|
90
|
+
throw new TypeError(`${component}: needs at least one child`);
|
|
91
|
+
return found;
|
|
92
|
+
}
|
|
93
|
+
function words(children) {
|
|
94
|
+
if (typeof children === 'boolean' || children === null || children === undefined)
|
|
95
|
+
return '';
|
|
96
|
+
if (Array.isArray(children))
|
|
97
|
+
return children.map(words).join('');
|
|
98
|
+
if (typeof children === 'string' || typeof children === 'number')
|
|
99
|
+
return String(children);
|
|
100
|
+
throw new TypeError('Text: a child must be a string or a number');
|
|
101
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { LayoutNode } from '../types.js';
|
|
2
|
+
export type { JSX } from './jsx-runtime.js';
|
|
3
|
+
/** Calls the component with its props; the key and the source location are dropped. */
|
|
4
|
+
export declare function jsxDEV(type: unknown, props: unknown, _key?: unknown, _isStatic?: boolean, _source?: unknown, _self?: unknown): LayoutNode;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// The development JSX runtime (`"jsx": "react-jsxdev"`): the same elements as the production runtime.
|
|
2
|
+
import { jsx } from './jsx-runtime.js';
|
|
3
|
+
/** Calls the component with its props; the key and the source location are dropped. */
|
|
4
|
+
export function jsxDEV(type, props, _key, _isStatic, _source, _self) {
|
|
5
|
+
return jsx(type, props);
|
|
6
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { LayoutNode } from '../types.js';
|
|
2
|
+
type Component = (props: never) => LayoutNode;
|
|
3
|
+
export declare namespace JSX {
|
|
4
|
+
type Element = LayoutNode;
|
|
5
|
+
type ElementType = Component;
|
|
6
|
+
interface IntrinsicElements {
|
|
7
|
+
}
|
|
8
|
+
interface ElementChildrenAttribute {
|
|
9
|
+
children: unknown;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
/** Calls the component with its props. The key has no place in a layout node. */
|
|
13
|
+
export declare function jsx(type: unknown, props: unknown, _key?: unknown): LayoutNode;
|
|
14
|
+
/** The same for an element with several static children. */
|
|
15
|
+
export declare const jsxs: typeof jsx;
|
|
16
|
+
export {};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Calls the component with its props. The key has no place in a layout node. */
|
|
2
|
+
export function jsx(type, props, _key) {
|
|
3
|
+
if (typeof type !== 'function') {
|
|
4
|
+
throw new TypeError(`a layout has no element <${String(type)}>: use the components of tauri-plugin-live-activity/jsx`);
|
|
5
|
+
}
|
|
6
|
+
return type(props);
|
|
7
|
+
}
|
|
8
|
+
/** The same for an element with several static children. */
|
|
9
|
+
export const jsxs = jsx;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { ActionEvent } from '../types.js';
|
|
2
|
+
import { type LiveActivityState, type SessionOptions } from './session.js';
|
|
3
|
+
export type { LiveActivityState, LiveActivityStatus } from './session.js';
|
|
4
|
+
export interface UseLiveActivityOptions extends SessionOptions {
|
|
5
|
+
/** Taps on the buttons of this activity; taps of other activities are not passed on. */
|
|
6
|
+
readonly onAction?: (event: ActionEvent) => void;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Starts a layout activity on mount, sends `values` as an update whenever they change, and ends the activity on
|
|
10
|
+
* unmount or when `enabled` turns false.
|
|
11
|
+
*/
|
|
12
|
+
export declare function useLiveActivity(options: UseLiveActivityOptions): LiveActivityState;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// `useLiveActivity`: one layout activity kept in step with a React component. Only this entry imports React.
|
|
2
|
+
import { useEffect, useRef, useState } from 'react';
|
|
3
|
+
import { endLayout, onAction, startLayout, updateLayout } from '../index.js';
|
|
4
|
+
import { IDLE, Session } from './session.js';
|
|
5
|
+
const commands = { startLayout, updateLayout, endLayout };
|
|
6
|
+
/**
|
|
7
|
+
* Starts a layout activity on mount, sends `values` as an update whenever they change, and ends the activity on
|
|
8
|
+
* unmount or when `enabled` turns false.
|
|
9
|
+
*/
|
|
10
|
+
export function useLiveActivity(options) {
|
|
11
|
+
const [state, setState] = useState(IDLE);
|
|
12
|
+
const session = useRef(null);
|
|
13
|
+
if (session.current === null)
|
|
14
|
+
session.current = new Session(commands, setState);
|
|
15
|
+
const handler = useRef(options.onAction);
|
|
16
|
+
handler.current = options.onAction;
|
|
17
|
+
const listening = options.onAction !== undefined;
|
|
18
|
+
useEffect(() => {
|
|
19
|
+
session.current?.sync(options);
|
|
20
|
+
});
|
|
21
|
+
useEffect(() => {
|
|
22
|
+
const current = session.current;
|
|
23
|
+
// Strict Mode unmounts and mounts again at once: the end waits for a microtask, which the mount cancels.
|
|
24
|
+
current?.keep();
|
|
25
|
+
return () => current?.release();
|
|
26
|
+
}, []);
|
|
27
|
+
useEffect(() => {
|
|
28
|
+
if (!listening)
|
|
29
|
+
return undefined;
|
|
30
|
+
let open = true;
|
|
31
|
+
const stop = onAction((event) => {
|
|
32
|
+
const running = session.current?.activityId;
|
|
33
|
+
if (open && running !== undefined && event.activityId === running)
|
|
34
|
+
handler.current?.(event);
|
|
35
|
+
});
|
|
36
|
+
return () => {
|
|
37
|
+
open = false;
|
|
38
|
+
stop.then((unlisten) => unlisten(), () => { });
|
|
39
|
+
};
|
|
40
|
+
}, [listening]);
|
|
41
|
+
return state;
|
|
42
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import type { EndPolicy, Fallback, Layout, LayoutActivityRecord, LayoutAndroidOptions, LayoutEndInput, LayoutStartInput, LayoutStyle, LayoutUpdateInput, LayoutValues, LiveActivityError } from '../types.js';
|
|
2
|
+
export interface SessionOptions {
|
|
3
|
+
/** The app's key of the activity; another key ends the running activity and starts one for it. */
|
|
4
|
+
readonly activityKey: string;
|
|
5
|
+
/** Read at start: a change while the activity runs is not sent, since the layout is fixed for a generation. */
|
|
6
|
+
readonly layout: Layout;
|
|
7
|
+
/** The values to show; a render with other values sends them as an update. */
|
|
8
|
+
readonly values: LayoutValues;
|
|
9
|
+
/** Read at start. */
|
|
10
|
+
readonly styles?: {
|
|
11
|
+
readonly [token: string]: LayoutStyle;
|
|
12
|
+
};
|
|
13
|
+
/** Read at start. Defaults to `notification`. */
|
|
14
|
+
readonly fallback?: Fallback;
|
|
15
|
+
/** Read at start. */
|
|
16
|
+
readonly android?: LayoutAndroidOptions;
|
|
17
|
+
/** False ends the activity, and true starts it again. Defaults to true. */
|
|
18
|
+
readonly enabled?: boolean;
|
|
19
|
+
/** How the activity ends on unmount or when `enabled` turns false. Defaults to `{ kind: 'immediate' }`. */
|
|
20
|
+
readonly endPolicy?: EndPolicy;
|
|
21
|
+
}
|
|
22
|
+
export type LiveActivityStatus = 'idle' | 'starting' | 'active' | 'ending' | 'ended' | 'failed';
|
|
23
|
+
export interface LiveActivityState {
|
|
24
|
+
readonly status: LiveActivityStatus;
|
|
25
|
+
/** The plugin's newest record of the activity. */
|
|
26
|
+
readonly record: LayoutActivityRecord | undefined;
|
|
27
|
+
/** The last refusal; an accepted request clears it. */
|
|
28
|
+
readonly error: LiveActivityError | undefined;
|
|
29
|
+
}
|
|
30
|
+
/** The commands the session sends. */
|
|
31
|
+
export interface SessionCommands {
|
|
32
|
+
readonly startLayout: (input: LayoutStartInput) => Promise<LayoutActivityRecord>;
|
|
33
|
+
readonly updateLayout: (input: LayoutUpdateInput) => Promise<LayoutActivityRecord>;
|
|
34
|
+
readonly endLayout: (input: LayoutEndInput) => Promise<LayoutActivityRecord>;
|
|
35
|
+
}
|
|
36
|
+
export declare const IDLE: LiveActivityState;
|
|
37
|
+
export declare class Session {
|
|
38
|
+
private readonly commands;
|
|
39
|
+
private readonly changed;
|
|
40
|
+
private state;
|
|
41
|
+
private wanted;
|
|
42
|
+
private endPolicy;
|
|
43
|
+
/** The running activity of this generation, and the values and revision it last took. */
|
|
44
|
+
private running;
|
|
45
|
+
/** Values that an update was refused with: not sent again until they change. */
|
|
46
|
+
private refused;
|
|
47
|
+
/** The key whose start was refused: not started again until `enabled` turns off or the key changes. */
|
|
48
|
+
private failedKey;
|
|
49
|
+
private busy;
|
|
50
|
+
private mounts;
|
|
51
|
+
constructor(commands: SessionCommands, changed: (state: LiveActivityState) => void);
|
|
52
|
+
/** The id of the running activity. */
|
|
53
|
+
get activityId(): string | undefined;
|
|
54
|
+
/** The options of a render. */
|
|
55
|
+
sync(options: SessionOptions): void;
|
|
56
|
+
/** The component is gone: the activity ends, now or once the request in flight has answered. */
|
|
57
|
+
dispose(): void;
|
|
58
|
+
/** The component mounted, also again in Strict Mode. */
|
|
59
|
+
keep(): void;
|
|
60
|
+
/** The component unmounted: it is disposed after a microtask, unless it mounts again before (Strict Mode). */
|
|
61
|
+
release(): void;
|
|
62
|
+
private pump;
|
|
63
|
+
private start;
|
|
64
|
+
private update;
|
|
65
|
+
private end;
|
|
66
|
+
private send;
|
|
67
|
+
private set;
|
|
68
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
export const IDLE = Object.freeze({ status: 'idle', record: undefined, error: undefined });
|
|
2
|
+
const IMMEDIATE = Object.freeze({ kind: 'immediate' });
|
|
3
|
+
export class Session {
|
|
4
|
+
constructor(commands, changed) {
|
|
5
|
+
this.commands = commands;
|
|
6
|
+
this.changed = changed;
|
|
7
|
+
this.state = IDLE;
|
|
8
|
+
this.endPolicy = IMMEDIATE;
|
|
9
|
+
this.busy = false;
|
|
10
|
+
this.mounts = 0;
|
|
11
|
+
}
|
|
12
|
+
/** The id of the running activity. */
|
|
13
|
+
get activityId() {
|
|
14
|
+
return this.running?.record.id;
|
|
15
|
+
}
|
|
16
|
+
/** The options of a render. */
|
|
17
|
+
sync(options) {
|
|
18
|
+
this.endPolicy = options.endPolicy ?? IMMEDIATE;
|
|
19
|
+
if (options.enabled === false) {
|
|
20
|
+
this.wanted = undefined;
|
|
21
|
+
this.failedKey = undefined;
|
|
22
|
+
}
|
|
23
|
+
else {
|
|
24
|
+
this.wanted = options;
|
|
25
|
+
}
|
|
26
|
+
this.pump();
|
|
27
|
+
}
|
|
28
|
+
/** The component is gone: the activity ends, now or once the request in flight has answered. */
|
|
29
|
+
dispose() {
|
|
30
|
+
this.wanted = undefined;
|
|
31
|
+
this.pump();
|
|
32
|
+
}
|
|
33
|
+
/** The component mounted, also again in Strict Mode. */
|
|
34
|
+
keep() {
|
|
35
|
+
this.mounts += 1;
|
|
36
|
+
}
|
|
37
|
+
/** The component unmounted: it is disposed after a microtask, unless it mounts again before (Strict Mode). */
|
|
38
|
+
release() {
|
|
39
|
+
const mount = this.mounts;
|
|
40
|
+
queueMicrotask(() => {
|
|
41
|
+
if (this.mounts === mount)
|
|
42
|
+
this.dispose();
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
pump() {
|
|
46
|
+
if (this.busy)
|
|
47
|
+
return;
|
|
48
|
+
const wanted = this.wanted;
|
|
49
|
+
const running = this.running;
|
|
50
|
+
if (running && wanted?.activityKey !== running.record.activityKey)
|
|
51
|
+
return this.end(running.record);
|
|
52
|
+
if (!wanted)
|
|
53
|
+
return;
|
|
54
|
+
if (!running) {
|
|
55
|
+
if (wanted.activityKey !== this.failedKey)
|
|
56
|
+
this.start(wanted);
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
if (!sameValues(wanted.values, running.values) && !sameValues(wanted.values, this.refused)) {
|
|
60
|
+
this.update(running, { ...wanted.values });
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
start(options) {
|
|
64
|
+
// A copy: values that the caller changes in place are compared with what was sent, not with themselves.
|
|
65
|
+
const values = { ...options.values };
|
|
66
|
+
const input = {
|
|
67
|
+
activityKey: options.activityKey,
|
|
68
|
+
schemaVersion: 2,
|
|
69
|
+
fallback: options.fallback ?? 'notification',
|
|
70
|
+
layout: options.layout,
|
|
71
|
+
snapshot: { revision: 0, values },
|
|
72
|
+
...(options.styles === undefined ? {} : { styles: options.styles }),
|
|
73
|
+
...(options.android === undefined ? {} : { android: options.android }),
|
|
74
|
+
};
|
|
75
|
+
this.failedKey = undefined;
|
|
76
|
+
this.refused = undefined;
|
|
77
|
+
this.set({ status: 'starting', record: undefined, error: undefined });
|
|
78
|
+
this.send(this.commands.startLayout(input), (record) => {
|
|
79
|
+
this.running = { record, values, revision: 0 };
|
|
80
|
+
this.set({ status: 'active', record, error: undefined });
|
|
81
|
+
}, (error) => {
|
|
82
|
+
// Blocks only the key still wanted: `enabled` off meanwhile, or another key, starts again.
|
|
83
|
+
if (this.wanted?.activityKey === options.activityKey)
|
|
84
|
+
this.failedKey = options.activityKey;
|
|
85
|
+
this.set({ status: 'failed', record: undefined, error });
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
update(running, values) {
|
|
89
|
+
// Every attempt takes the next revision, so a refused one is never reused.
|
|
90
|
+
const revision = running.revision + 1;
|
|
91
|
+
this.running = { ...running, revision };
|
|
92
|
+
this.send(this.commands.updateLayout({ id: running.record.id, snapshot: { revision, values } }), (record) => {
|
|
93
|
+
this.refused = undefined;
|
|
94
|
+
this.running = { record, values, revision };
|
|
95
|
+
this.set({ status: 'active', record, error: undefined });
|
|
96
|
+
}, (error) => {
|
|
97
|
+
this.refused = values;
|
|
98
|
+
this.set({ ...this.state, error });
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
end(record) {
|
|
102
|
+
this.set({ status: 'ending', record, error: this.state.error });
|
|
103
|
+
this.send(this.commands.endLayout({ id: record.id, policy: this.endPolicy }), (ended) => {
|
|
104
|
+
this.running = undefined;
|
|
105
|
+
this.set({ status: 'ended', record: ended, error: undefined });
|
|
106
|
+
}, (error) => {
|
|
107
|
+
// Not tried again: the activity is left to the system.
|
|
108
|
+
this.running = undefined;
|
|
109
|
+
this.set({ status: 'failed', record, error });
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
send(request, accepted, refused) {
|
|
113
|
+
this.busy = true;
|
|
114
|
+
request.then(accepted, (error) => refused(asError(error))).finally(() => {
|
|
115
|
+
this.busy = false;
|
|
116
|
+
this.pump();
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
set(state) {
|
|
120
|
+
this.state = state;
|
|
121
|
+
this.changed(state);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
function sameValues(a, b) {
|
|
125
|
+
if (b === undefined)
|
|
126
|
+
return false;
|
|
127
|
+
const keys = Object.keys(a);
|
|
128
|
+
return keys.length === Object.keys(b).length && keys.every((key) => Object.is(a[key], b[key]));
|
|
129
|
+
}
|
|
130
|
+
/** The plugin rejects with `{ code, message }`; anything else reads as a `NATIVE_ERROR`. */
|
|
131
|
+
function asError(error) {
|
|
132
|
+
if (typeof error === 'object' && error !== null) {
|
|
133
|
+
const { code, message } = error;
|
|
134
|
+
if (typeof code === 'string' && typeof message === 'string')
|
|
135
|
+
return { code: code, message };
|
|
136
|
+
}
|
|
137
|
+
return { code: 'NATIVE_ERROR', message: error instanceof Error ? error.message : String(error) };
|
|
138
|
+
}
|
package/dist-js/types.d.ts
CHANGED
|
@@ -81,7 +81,8 @@ export interface EndInput {
|
|
|
81
81
|
/** Unsupported policies fail explicitly instead of being silently ignored. */
|
|
82
82
|
readonly policy: EndPolicy;
|
|
83
83
|
}
|
|
84
|
-
|
|
84
|
+
/** `pending`: scheduled and not started yet (iOS 26). */
|
|
85
|
+
export type ActivityState = 'pending' | 'active' | 'stale' | 'ended' | 'dismissed' | 'unknown';
|
|
85
86
|
export type PromotionState = 'promoted' | 'notPromoted' | 'unknown' | 'notApplicable';
|
|
86
87
|
export interface ActivityRecord {
|
|
87
88
|
/** Opaque handle for this generation; a later start receives a new handle. */
|
|
@@ -99,7 +100,7 @@ export interface ActivityRecord {
|
|
|
99
100
|
readonly promotionRequested: boolean;
|
|
100
101
|
readonly promotionState: PromotionState;
|
|
101
102
|
}
|
|
102
|
-
export type ErrorCode = 'UNSUPPORTED_PLATFORM' | 'UNSUPPORTED_FEATURE' | 'PERMISSION_DENIED' | 'CONFIGURATION_REQUIRED' | 'INVALID_INPUT' | 'PAYLOAD_TOO_LARGE' | 'NOT_FOUND' | 'STALE_REVISION' | 'CONFLICT' | 'SYSTEM_LIMIT' | 'NATIVE_ERROR';
|
|
103
|
+
export type ErrorCode = 'UNSUPPORTED_PLATFORM' | 'UNSUPPORTED_FEATURE' | 'PERMISSION_DENIED' | 'NOT_FOREGROUND' | 'CONFIGURATION_REQUIRED' | 'INVALID_INPUT' | 'PAYLOAD_TOO_LARGE' | 'NOT_FOUND' | 'STALE_REVISION' | 'CONFLICT' | 'SYSTEM_LIMIT' | 'NATIVE_ERROR';
|
|
103
104
|
/** Native plugin rejections are structured objects, not JavaScript Error instances. */
|
|
104
105
|
export interface LiveActivityError {
|
|
105
106
|
readonly code: ErrorCode;
|
|
@@ -112,12 +113,17 @@ export interface LayoutValues {
|
|
|
112
113
|
readonly [key: string]: LayoutValue;
|
|
113
114
|
}
|
|
114
115
|
export interface LayoutSnapshot {
|
|
115
|
-
/** Nonnegative JavaScript safe integer; strictly increases when the values change. */
|
|
116
|
+
/** Nonnegative JavaScript safe integer; strictly increases when the values change. Sent as given. */
|
|
116
117
|
readonly revision: number;
|
|
117
118
|
/** The complete map. An update keeps the keys and the value types accepted at start. */
|
|
118
119
|
readonly values: LayoutValues;
|
|
119
120
|
/** UTC Unix epoch milliseconds. */
|
|
120
121
|
readonly staleAt?: number;
|
|
122
|
+
/**
|
|
123
|
+
* When the content was made, UTC Unix epoch milliseconds. ActivityKit (iOS 17.2) drops content older than what it
|
|
124
|
+
* shows; without it iOS takes the time the content is sent. Android keeps it in the record.
|
|
125
|
+
*/
|
|
126
|
+
readonly timestamp?: number;
|
|
121
127
|
}
|
|
122
128
|
type ColorName = 'primary' | 'secondary' | 'accent' | 'red' | 'orange' | 'yellow' | 'green' | 'mint' | 'teal' | 'cyan' | 'blue' | 'indigo' | 'purple' | 'pink' | 'brown' | 'white' | 'black' | 'gray' | 'clear';
|
|
123
129
|
/** `#RRGGBB` or `#RRGGBBAA`. */
|
|
@@ -383,6 +389,13 @@ export interface LayoutUpdateInput {
|
|
|
383
389
|
/** Complete replacement snapshot, not a partial update. */
|
|
384
390
|
readonly snapshot: LayoutSnapshot;
|
|
385
391
|
}
|
|
392
|
+
/**
|
|
393
|
+
* The end of a layout activity. With `snapshot` it ends with that final content, checked as an update; without one it
|
|
394
|
+
* ends with the last accepted values.
|
|
395
|
+
*/
|
|
396
|
+
export interface LayoutEndInput extends EndInput {
|
|
397
|
+
readonly snapshot?: LayoutSnapshot;
|
|
398
|
+
}
|
|
386
399
|
/** The record does not repeat the layout. */
|
|
387
400
|
export interface LayoutActivityRecord {
|
|
388
401
|
/** Opaque handle for this generation; contract v1 commands do not see it. */
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tauri-plugin-live-activity",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Tauri 2 plugin for iOS Live Activities (ActivityKit and Dynamic Island) and Android Live Updates with ongoing notification fallback",
|
|
5
5
|
"author": "1eedaegon",
|
|
6
6
|
"type": "module",
|
|
@@ -17,6 +17,10 @@
|
|
|
17
17
|
"main": "./dist-js/index.js",
|
|
18
18
|
"exports": {
|
|
19
19
|
".": { "types": "./dist-js/index.d.ts", "import": "./dist-js/index.js" },
|
|
20
|
+
"./jsx": { "types": "./dist-js/jsx/index.d.ts", "import": "./dist-js/jsx/index.js" },
|
|
21
|
+
"./jsx/jsx-runtime": { "types": "./dist-js/jsx/jsx-runtime.d.ts", "import": "./dist-js/jsx/jsx-runtime.js" },
|
|
22
|
+
"./jsx/jsx-dev-runtime": { "types": "./dist-js/jsx/jsx-dev-runtime.d.ts", "import": "./dist-js/jsx/jsx-dev-runtime.js" },
|
|
23
|
+
"./react": { "types": "./dist-js/react/index.d.ts", "import": "./dist-js/react/index.js" },
|
|
20
24
|
"./package.json": "./package.json"
|
|
21
25
|
},
|
|
22
26
|
"bin": { "tauri-plugin-live-activity": "cli/bin.mjs" },
|
|
@@ -28,9 +32,11 @@
|
|
|
28
32
|
"scripts": {
|
|
29
33
|
"build": "tsc -p tsconfig.json",
|
|
30
34
|
"typecheck": "tsc -p tsconfig.json --noEmit && tsc -p examples/demo/tsconfig.json",
|
|
31
|
-
"test": "npm run build && npm run test:contracts && npm run test:api && npm run test:demo && npm run test:setup",
|
|
32
|
-
"test:contracts": "node --test --experimental-test-coverage \"--test-coverage-include=tools/validate-request.mjs\" --test-coverage-lines=80 --test-coverage-branches=80 --test-coverage-functions=80 tests/requests.test.mjs tests/layout-requests.test.mjs",
|
|
35
|
+
"test": "npm run build && npm run test:contracts && npm run test:api && npm run test:jsx && npm run test:react && npm run test:demo && npm run test:setup",
|
|
36
|
+
"test:contracts": "node --test --experimental-test-coverage \"--test-coverage-include=tools/validate-request.mjs\" --test-coverage-lines=80 --test-coverage-branches=80 --test-coverage-functions=80 tests/requests.test.mjs tests/layout-requests.test.mjs tests/contract-sync.test.mjs tests/android-liveupdate.test.mjs tests/ci.test.mjs tests/ci-cache.test.mjs tests/spec-coverage.test.mjs",
|
|
33
37
|
"test:api": "node --test --experimental-test-coverage \"--test-coverage-include=dist-js/*.js\" --test-coverage-lines=80 --test-coverage-branches=80 --test-coverage-functions=80 tests/api.test.mjs",
|
|
38
|
+
"test:jsx": "node --experimental-strip-types --test --experimental-test-coverage \"--test-coverage-include=dist-js/jsx/*.js\" --test-coverage-lines=80 --test-coverage-branches=80 --test-coverage-functions=80 tests/jsx.test.mjs",
|
|
39
|
+
"test:react": "node --test --experimental-test-coverage \"--test-coverage-include=dist-js/react/*.js\" --test-coverage-lines=80 --test-coverage-branches=80 --test-coverage-functions=80 tests/react.test.mjs",
|
|
34
40
|
"test:demo": "node --experimental-strip-types --test --experimental-test-coverage \"--test-coverage-include=examples/demo/src/*.ts\" \"--test-coverage-exclude=examples/demo/tests/**\" --test-coverage-lines=80 --test-coverage-branches=80 --test-coverage-functions=80 examples/demo/tests/self-test.test.mjs examples/demo/tests/ui-state.test.mjs examples/demo/tests/layouts.test.mjs examples/demo/tests/setup.test.mjs",
|
|
35
41
|
"test:setup": "node --test --experimental-test-coverage \"--test-coverage-include=cli/*.mjs\" --test-coverage-lines=80 --test-coverage-branches=80 --test-coverage-functions=80 tests/setup.test.mjs",
|
|
36
42
|
"build:demo": "npm run build && node examples/demo/build.mjs",
|
|
@@ -38,13 +44,20 @@
|
|
|
38
44
|
"pack:check": "npm pack --dry-run"
|
|
39
45
|
},
|
|
40
46
|
"peerDependencies": {
|
|
41
|
-
"@tauri-apps/api": "^2.12.4"
|
|
47
|
+
"@tauri-apps/api": "^2.12.4",
|
|
48
|
+
"react": ">=18"
|
|
49
|
+
},
|
|
50
|
+
"peerDependenciesMeta": {
|
|
51
|
+
"react": { "optional": true }
|
|
42
52
|
},
|
|
43
53
|
"devDependencies": {
|
|
44
54
|
"@tauri-apps/cli": "2.12.4",
|
|
45
55
|
"@tauri-apps/api": "2.12.4",
|
|
56
|
+
"@types/react": "19.3.0",
|
|
46
57
|
"ajv": "8.20.0",
|
|
47
58
|
"esbuild": "0.28.2",
|
|
59
|
+
"react": "19.3.1",
|
|
60
|
+
"react-test-renderer": "19.3.1",
|
|
48
61
|
"typescript": "7.0.2"
|
|
49
62
|
}
|
|
50
63
|
}
|